mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-12-05 12:35:42 +00:00
Compare commits
79
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
42fdbfe899 | ||
|
|
e40cd36151 | ||
|
|
ab54536886 | ||
|
|
72196c3447 | ||
|
|
48d2d52d28 | ||
|
|
6199a93f52 | ||
|
|
8397965df2 | ||
|
|
6c8a086190 | ||
|
|
3ef49faa26 | ||
|
|
55b30fbf1d | ||
|
|
7464bd7697 | ||
|
|
22694a380d | ||
|
|
6c7242aa64 | ||
|
|
92e4eecb58 | ||
|
|
24dfa920b5 | ||
|
|
c32852e311 | ||
|
|
1c758abd04 | ||
|
|
9796345987 | ||
|
|
c359eac6df | ||
|
|
d16ca4d8a8 | ||
|
|
0e44b3a032 | ||
|
|
dae92488ce | ||
|
|
4d0a65722a | ||
|
|
8e643b4747 | ||
|
|
a9622c9c29 | ||
|
|
0136fb6196 | ||
|
|
13e712c849 | ||
|
|
5cd0aaa99a | ||
|
|
e1b5309593 | ||
|
|
f12ae2f60d | ||
|
|
e37f20625b | ||
|
|
e5bea33cdc | ||
|
|
506cd5876e | ||
|
|
7c508e8940 | ||
|
|
7e6bac5d01 | ||
|
|
1fbe162b49 | ||
|
|
efd93dd9b4 | ||
|
|
20185ab7e9 | ||
|
|
3dc58e58cb | ||
|
|
b50d333f6c | ||
|
|
d0f0aa4502 | ||
|
|
ee0fb08268 | ||
|
|
cf06f89c11 | ||
|
|
e9f8f9d717 | ||
|
|
42146570fb | ||
|
|
feff080d5b | ||
|
|
7ef64474e3 | ||
|
|
db034d6598 | ||
|
|
44866db692 | ||
|
|
0fd3a1a2b8 | ||
|
|
8d9b7084f8 | ||
|
|
1c8f78a082 | ||
|
|
cd24e503ba | ||
|
|
259fa57d5c | ||
|
|
88dfddd18a | ||
|
|
2204da404a | ||
|
|
f08eedb3f6 | ||
|
|
d0f7264ea8 | ||
|
|
06d728b218 | ||
|
|
194a6a58c2 | ||
|
|
36f65bed5a | ||
|
|
4209654d0a | ||
|
|
e67177a15b | ||
|
|
049ce1d6b0 | ||
|
|
5ce46e0a5d | ||
|
|
bf033f2f11 | ||
|
|
3c3639100f | ||
|
|
ee1d861955 | ||
|
|
0c9b059edc | ||
|
|
efa03d62ac | ||
|
|
d238a94018 | ||
|
|
f9be8f0c44 | ||
|
|
8cf0373b5e | ||
|
|
844a1a2473 | ||
|
|
fda618618c | ||
|
|
23a964f8a7 | ||
|
|
9ffad375ae | ||
|
|
9e6fe314ae | ||
|
|
68dc1c4549 |
No files matched your search
@@ -0,0 +1,31 @@
|
||||
name: Build Venus (Mali)
|
||||
# The Mali (Venus) route's binaries from tools/venus (David Cimo's recipes): Mesa's Venus ICD and the
|
||||
# Mali compatibility layer (glibc, for the session) and virglrenderer's vtest server (bionic, run by
|
||||
# the app over the phone's own Vulkan driver), packed as venus.tzst rooted at app/src/main. The apk
|
||||
# build fetches it by tools/venus/release.env (tag + sha256); nothing compiled is kept in this repo.
|
||||
on:
|
||||
workflow_dispatch:
|
||||
push:
|
||||
branches: [test/non-adreno-all]
|
||||
paths: ['tools/venus/**', '.github/workflows/build-venus.yml']
|
||||
permissions:
|
||||
contents: read
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 120
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Tools
|
||||
run: |
|
||||
sudo apt-get update -qq
|
||||
sudo apt-get install -y -qq ninja-build pkg-config zstd python3-pip
|
||||
pip3 install --break-system-packages 'meson>=1.5'
|
||||
- name: Build
|
||||
run: ANDROID_NDK_HOME="$ANDROID_NDK_LATEST_HOME" WORK=$PWD/venus-work tools/venus/ci-build.sh
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: venus
|
||||
path: |
|
||||
venus-work/venus.tzst
|
||||
venus-work/venus.tzst.sha256
|
||||
@@ -186,7 +186,7 @@ jobs:
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: app/src/main/assets/linuxfs
|
||||
key: preloads-${{ env.PRELOAD_CACHE_VERSION }}-${{ hashFiles('app/src/main/cpp/fakeinput_steam.cpp', 'app/src/main/cpp/adrenotools/src/hook/kgsl.h', 'tools/quest/*', 'tools/linuxfs/preload/*.c', 'tools/linuxfs/build-x86-preloads.sh', 'tools/linuxfs/fex/*', 'tools/linuxfs/clipboard/*.c', 'tools/linuxfs/ssbs/*.c', 'tools/proot/fastpath/*.c', 'tools/linuxfs/overlay/usr/local/bin/*', 'tools/linuxfs/overlay/usr/bin/**', 'tools/linuxfs/desktop/*', 'tools/gamescope/release.env', 'tools/wlroots/release.env', 'tools/linuxfs/uruntime.env', 'tools/linuxfs/licenses/*', 'tools/mangoapp/*', 'tools/msitools/**', 'tools/comet/**', 'tools/linuxfs/debian-image.env') }}
|
||||
key: preloads-${{ env.PRELOAD_CACHE_VERSION }}-${{ hashFiles('app/src/main/cpp/fakeinput_steam.cpp', 'app/src/main/cpp/adrenotools/src/hook/kgsl.h', 'tools/quest/*', 'tools/linuxfs/preload/*.c', 'tools/linuxfs/build-x86-preloads.sh', 'tools/linuxfs/fex/*', 'tools/linuxfs/clipboard/*.c', 'tools/linuxfs/ssbs/*.c', 'tools/linuxfs/xclipse-layer/*', 'tools/proot/fastpath/*.c', 'tools/linuxfs/overlay/usr/local/bin/*', 'tools/linuxfs/overlay/usr/bin/**', 'tools/linuxfs/desktop/*', 'tools/gamescope/release.env', 'tools/wlroots/release.env', 'tools/linuxfs/uruntime.env', 'tools/linuxfs/licenses/*', 'tools/mangoapp/*', 'tools/msitools/**', 'tools/comet/**', 'tools/vkbridge/client/**', 'tools/vkbridge/common/**', 'tools/vkbridge/tests/**', 'tools/vkbridge/build-client-linux.sh', 'tools/linuxfs/debian-image.env') }}
|
||||
|
||||
- name: Build libfakeinput.so and libblsession.so (glibc aarch64)
|
||||
if: steps.preloads.outputs.cache-hit != 'true'
|
||||
@@ -195,7 +195,7 @@ jobs:
|
||||
run: |
|
||||
set -euo pipefail
|
||||
sudo apt-get update -qq
|
||||
sudo apt-get install -y -qq gcc-aarch64-linux-gnu g++-aarch64-linux-gnu >/dev/null
|
||||
sudo apt-get install -y -qq gcc-aarch64-linux-gnu g++-aarch64-linux-gnu libvulkan-dev >/dev/null
|
||||
D=app/src/main/assets/linuxfs
|
||||
mkdir -p "$D"
|
||||
aarch64-linux-gnu-g++ -shared -fPIC -O2 -Wall -Wno-attributes -Wno-nonnull-compare \
|
||||
@@ -215,7 +215,15 @@ jobs:
|
||||
aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -pthread \
|
||||
-o "$D/libssbs.so" tools/linuxfs/ssbs/ssbs_adapter.c -ldl
|
||||
aarch64-linux-gnu-strip --strip-unneeded "$D/libssbs.so"
|
||||
# Samsung Xclipse driver workarounds, a Vulkan layer the system-driver path enables there.
|
||||
mkdir -p "$D/usr/local/lib/droiddeck-xclipse"
|
||||
aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -Wextra -Wno-unused-parameter -fvisibility=hidden -pthread \
|
||||
-o "$D/usr/local/lib/droiddeck-xclipse/libVkLayer_droiddeck_xclipse.so" tools/linuxfs/xclipse-layer/xclipse_layer.c -ldl
|
||||
aarch64-linux-gnu-strip --strip-unneeded "$D/usr/local/lib/droiddeck-xclipse/libVkLayer_droiddeck_xclipse.so"
|
||||
install -m644 tools/linuxfs/xclipse-layer/VkLayer_droiddeck_xclipse.json "$D/usr/local/lib/droiddeck-xclipse/"
|
||||
mkdir -p "$D/usr/local/bin"
|
||||
# The Mali bridge's Linux side: ICD, manifest and self-test (tools/vkbridge).
|
||||
tools/vkbridge/build-client-linux.sh "$D" aarch64-linux-gnu-gcc
|
||||
aarch64-linux-gnu-gcc -O2 -Wall -Wextra -o "$D/usr/local/bin/droiddeck-clipboard" tools/linuxfs/clipboard/clipboard.c -ldl
|
||||
aarch64-linux-gnu-strip --strip-unneeded "$D/usr/local/bin/droiddeck-clipboard"
|
||||
for script in tools/linuxfs/overlay/usr/local/bin/droiddeck-* tools/linuxfs/overlay/usr/local/bin/steam-compatibility; do
|
||||
@@ -406,6 +414,30 @@ jobs:
|
||||
run: |
|
||||
set -euo pipefail
|
||||
bash tools/linuxfs/check-preloads.sh app/src/main/assets/linuxfs
|
||||
D=app/src/main/assets/linuxfs
|
||||
syms() { readelf -Ws "$1" | awk '$4 == "FUNC" && $5 == "GLOBAL" {sub(/@.*/, "", $8); print $8}'; }
|
||||
# The bridge ICD: libc only, and nothing exported but the loader's three entry points.
|
||||
VKB="$D/usr/local/lib/vkbridge/libvulkan_droidbridge.so"
|
||||
test -f "$VKB" && test -f "$D/usr/local/share/vkbridge/droidbridge_icd.json" && test -f "$D/usr/local/bin/droiddeck-vkbridge-smoke"
|
||||
VKB_NEED=$(readelf -d "$VKB" | sed -n 's/.*NEEDED.*\[\(.*\)\]/\1/p' | grep -vx 'libc.so.6' | grep -vx 'ld-linux-aarch64.so.1' || true)
|
||||
[ -z "$VKB_NEED" ] || { echo "::error::the bridge ICD needs $VKB_NEED"; exit 1; }
|
||||
[ "$(syms "$VKB" | grep -c '^vk_icd')" = 3 ] || { echo "::error::the bridge ICD does not export the loader interface"; exit 1; }
|
||||
|
||||
# Mali (Venus), David Cimo's route: the vtest server (jniLibs), the Venus ICD (assets/venus)
|
||||
# and the Mali compatibility layer (assets/linuxfs), built by build-venus.yml and fetched by
|
||||
# tag + sha256 like gamescope. The app uses it only on a GPU that is not an Adreno.
|
||||
- name: Fetch the Mali (Venus) component (tools/venus/release.env)
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
. tools/venus/release.env
|
||||
gh release download "${VENUS_TAG}" -R "${VENUS_REPO}" -p venus.tzst -O venus.tzst
|
||||
echo "${VENUS_SHA256} venus.tzst" | sha256sum -c -
|
||||
tar --use-compress-program=unzstd -xf venus.tzst -C app/src/main
|
||||
test -f app/src/main/jniLibs/arm64-v8a/libvirgl_test_server.so
|
||||
test -f app/src/main/assets/venus/libvulkan_virtio.so
|
||||
rm venus.tzst
|
||||
|
||||
# The store download engines (app/src/main/rust/stores) are Rust, built by Gradle's
|
||||
# buildRustStores task through cargo-ndk. rustup and cargo are on the runner image; the Android
|
||||
@@ -465,6 +497,7 @@ jobs:
|
||||
run: |
|
||||
set -o pipefail
|
||||
python3 tools/quest/build-driver.py "$ANDROID_HOME/ndk/$NDK_VERSION"
|
||||
python3 tools/powervr/fetch.py
|
||||
python3 tools/release/runtime_inputs.py record
|
||||
./gradlew assembleRelease --console=plain -PndkVersion="$NDK_VERSION" 2>&1 | tee /tmp/build.log
|
||||
python3 tools/release/check_session_assets.py app/build/outputs/apk/release/app-release.apk
|
||||
@@ -504,7 +537,10 @@ jobs:
|
||||
if-no-files-found: ignore
|
||||
|
||||
- name: Steam import and game environment tests
|
||||
run: python3 -m unittest discover -s tools/tests -p 'test_*.py'
|
||||
run: |
|
||||
# The Xclipse layer regression test compiles the layer against the distribution's headers.
|
||||
sudo apt-get update -qq && sudo apt-get install -y -qq libvulkan-dev >/dev/null
|
||||
python3 -m unittest discover -s tools/tests -p 'test_*.py'
|
||||
|
||||
- name: Unit tests
|
||||
run: ./gradlew testReleaseUnitTest --console=plain -PndkVersion="$NDK_VERSION"
|
||||
|
||||
@@ -40,3 +40,4 @@ __pycache__/
|
||||
# Local signing with the release key (tools/build_local.sh); holds a password.
|
||||
.signing.env
|
||||
app/src/main/assets/directaudio/
|
||||
app/src/main/assets/hybris/
|
||||
@@ -5,7 +5,7 @@
|
||||
</picture>
|
||||
</p>
|
||||
|
||||
DroidDeck brings the SteamOS experience to Android: Valve's Steam client in Big Picture on your Adreno handheld, with Windows games through Valve's ARM64 Proton.
|
||||
DroidDeck brings the SteamOS experience to Android: Valve's Steam client in Big Picture on your Android handheld, with Windows games through Valve's ARM64 Proton.
|
||||
|
||||
<p align="center"><a href="https://discord.gg/JRGAvawjsm"><img src="https://img.shields.io/badge/Discord-Join%20the%20community-5865F2?logo=discord&logoColor=white" alt="Join the DroidDeck Discord"></a></p>
|
||||
|
||||
@@ -15,7 +15,7 @@ DroidDeck brings the SteamOS experience to Android: Valve's Steam client in Big
|
||||
|
||||
## Requirements and install
|
||||
|
||||
Use Android 9 or newer on a supported Adreno device (730 or newer, or 8xx). Adreno 6xx is experimental: DirectX 11 uses DXVK 2 and may run, and DirectX 12 games can still crash. Mali, Xclipse, PowerVR, and Adreno 710 are unsupported. No root is required. Allow about 3 GB for the runtime and 1.1 GB more for the desktop and emulators. Install the APK from [Releases](https://github.com/Droid-Deck/DroidDeck/releases), install the Linux runtime, then press **Play** and sign in. Steam downloads on first launch. Install **Desktop & apps** to use the desktop and emulators. The **Store** installs Linux apps and games from Flathub (ARM64 builds) with Flatpak; with additional options to install Appimages and set up scripts. **Stores** (Setup › Stores › "Show Stores in the rail") signs in to GOG, Epic Games and Amazon Games, browses their catalogs and libraries, downloads games into the Games storage and adds each one to the Steam client as a non-Steam game, so it launches through Proton like everything else; the cog on its chip row sets which tab a store opens on and the download speed tier.
|
||||
Use Android 9 or newer. Supported Adreno devices include 730 or newer, or 8xx. Adreno 6xx is experimental: DirectX 11 uses DXVK 2 and may run, and DirectX 12 games can still crash. PowerVR support is experimental: where the system Vulkan backend is available, the app selects it automatically. Mali, Xclipse, and Adreno 710 are unsupported. No root is required. Allow about 3 GB for the runtime and 1.1 GB more for the desktop and emulators. Install the APK from [Releases](https://github.com/Droid-Deck/DroidDeck/releases), install the Linux runtime, then press **Play** and sign in. Steam downloads on first launch. Install **Desktop & apps** to use the desktop and emulators. The **Store** installs Linux apps and games from Flathub (ARM64 builds) with Flatpak; with additional options to install Appimages and set up scripts. **Stores** (Setup › Stores › "Show Stores in the rail") signs in to GOG, Epic Games and Amazon Games, browses their catalogs and libraries, downloads games into the Games storage and adds each one to the Steam client as a non-Steam game, so it launches through Proton like everything else; the cog on its chip row sets which tab a store opens on and the download speed tier.
|
||||
|
||||
Before Steam launches, you must turn off **Restrict child processes** in Developer options. If this option is not available in developer settings (Android 12 and 13 devices), first launch of Steam will present a "Fix it for me" button, which will help automate the setup process.
|
||||
|
||||
|
||||
@@ -149,6 +149,9 @@ android {
|
||||
release {
|
||||
minifyEnabled false
|
||||
signingConfig signingConfigs.testkey
|
||||
// Mali bridge development fork: debuggable so `adb shell run-as` reaches the session
|
||||
// logs and VkBridgeNative's development override (-Pdroiddeck.notDebuggable to drop).
|
||||
debuggable !project.hasProperty('droiddeck.notDebuggable')
|
||||
}
|
||||
}
|
||||
|
||||
@@ -276,6 +279,24 @@ def buildRustStores = tasks.register('buildRustStores', Exec) {
|
||||
if (!skipRust) android.sourceSets.main.jniLibs.srcDir(rustJniLibsDir)
|
||||
tasks.named('preBuild').configure { dependsOn(buildRustStores) }
|
||||
|
||||
// The Mali bridge's server (tools/vkbridge, app/src/main/cpp/vkbridge) is a program, not a library:
|
||||
// it runs beside the session as the app's child, so a driver crash ends that process and not the
|
||||
// app. AGP's CMake integration packages only shared libraries, so the NDK's clang builds it here
|
||||
// into one more jniLibs source, named libvkbridge_server.so so Android extracts it (the native
|
||||
// library directory is the one place the app may exec from).
|
||||
def vkbridgeJniLibsDir = layout.buildDirectory.dir('vkbridgeJniLibs')
|
||||
def buildVkBridgeServer = tasks.register('buildVkBridgeServer', Exec) {
|
||||
description = 'Builds the Vulkan bridge server (libvkbridge_server.so) with the NDK.'
|
||||
inputs.dir(rootProject.file('tools/vkbridge/common'))
|
||||
inputs.dir(layout.projectDirectory.dir('src/main/cpp/vkbridge'))
|
||||
inputs.file(rootProject.file('tools/vkbridge/build-server-android.sh'))
|
||||
outputs.dir(vkbridgeJniLibsDir)
|
||||
commandLine 'bash', rootProject.file('tools/vkbridge/build-server-android.sh').absolutePath,
|
||||
android.ndkDirectory.absolutePath, vkbridgeJniLibsDir.get().asFile.absolutePath
|
||||
}
|
||||
android.sourceSets.main.jniLibs.srcDir(vkbridgeJniLibsDir)
|
||||
tasks.named('preBuild').configure { dependsOn(buildVkBridgeServer) }
|
||||
|
||||
dependencies {
|
||||
// The runtime tarball is a zstd-compressed tar.
|
||||
implementation 'com.github.luben:zstd-jni:1.5.2-3@aar'
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,194 @@
|
||||
/* SPDX-License-Identifier: GPL-3.0-or-later
|
||||
*
|
||||
* The command buffers each device has handed out, so that a handle the driver never gave (or has
|
||||
* since freed, with its pool) is refused here instead of reaching the driver. Handles arrive from
|
||||
* clients as plain numbers; one the driver did not know took the whole app down inside Mali's
|
||||
* vkBeginCommandBuffer (SIGSEGV at 0x10, Steam's Zink on an Edge 60 and a Tab S11). A refused
|
||||
* command buffer fails its call with VK_ERROR_DEVICE_LOST, which the client reports, and is logged
|
||||
* once per handle.
|
||||
*/
|
||||
#define _GNU_SOURCE
|
||||
#include "vkb_server.h"
|
||||
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#define CBT_BUCKETS 1024
|
||||
|
||||
typedef struct cbt_entry {
|
||||
VkCommandBuffer cb;
|
||||
VkCommandPool pool;
|
||||
struct cbt_entry *next;
|
||||
} cbt_entry;
|
||||
|
||||
typedef struct vkb_cbtrack {
|
||||
pthread_mutex_t lock;
|
||||
cbt_entry *b[CBT_BUCKETS];
|
||||
VkCommandBuffer last_refused;
|
||||
PFN_vkAllocateCommandBuffers alloc;
|
||||
PFN_vkFreeCommandBuffers free_cbs;
|
||||
PFN_vkDestroyCommandPool destroy_pool;
|
||||
PFN_vkBeginCommandBuffer begin;
|
||||
PFN_vkQueueSubmit submit;
|
||||
PFN_vkQueueSubmit2 submit2;
|
||||
} vkb_cbtrack;
|
||||
|
||||
static unsigned bucket(VkCommandBuffer cb)
|
||||
{
|
||||
uint64_t k = (uint64_t)(uintptr_t)cb;
|
||||
k ^= k >> 31;
|
||||
k *= 0x9e3779b97f4a7c15ull;
|
||||
return (unsigned)(k >> 54) & (CBT_BUCKETS - 1);
|
||||
}
|
||||
|
||||
static vkb_cbtrack *cur(void)
|
||||
{
|
||||
vkb_srv_table *t = vkb_srv_current_table();
|
||||
return t ? t->cbtrack : NULL;
|
||||
}
|
||||
|
||||
static int known_locked(vkb_cbtrack *k, VkCommandBuffer cb)
|
||||
{
|
||||
for (cbt_entry *e = k->b[bucket(cb)]; e; e = e->next)
|
||||
if (e->cb == cb) return 1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
int vkb_cbtrack_known(vkb_srv_table *t, VkCommandBuffer cb, const char *what)
|
||||
{
|
||||
vkb_cbtrack *k = t ? t->cbtrack : NULL;
|
||||
if (!k) return cb != VK_NULL_HANDLE;
|
||||
pthread_mutex_lock(&k->lock);
|
||||
int ok = cb && known_locked(k, cb);
|
||||
int first = !ok && k->last_refused != cb;
|
||||
if (!ok) k->last_refused = cb;
|
||||
pthread_mutex_unlock(&k->lock);
|
||||
if (first)
|
||||
VKB_ERR("device %u: %s on command buffer %p, which this device never allocated or has freed; refused (the client "
|
||||
"gets VK_ERROR_DEVICE_LOST)", t->id, what, (void *)cb);
|
||||
return ok;
|
||||
}
|
||||
|
||||
static VKAPI_ATTR VkResult VKAPI_CALL cbt_AllocateCommandBuffers(VkDevice device, const VkCommandBufferAllocateInfo *info,
|
||||
VkCommandBuffer *out)
|
||||
{
|
||||
vkb_cbtrack *k = cur();
|
||||
VkResult r = k->alloc(device, info, out);
|
||||
if (r != VK_SUCCESS || !info) return r;
|
||||
pthread_mutex_lock(&k->lock);
|
||||
for (uint32_t i = 0; i < info->commandBufferCount; i++) {
|
||||
if (!out[i] || known_locked(k, out[i])) continue;
|
||||
cbt_entry *e = malloc(sizeof(*e));
|
||||
if (!e) continue;
|
||||
e->cb = out[i];
|
||||
e->pool = info->commandPool;
|
||||
unsigned h = bucket(out[i]);
|
||||
e->next = k->b[h];
|
||||
k->b[h] = e;
|
||||
}
|
||||
pthread_mutex_unlock(&k->lock);
|
||||
return r;
|
||||
}
|
||||
|
||||
static void forget_locked(vkb_cbtrack *k, VkCommandBuffer cb, VkCommandPool pool)
|
||||
{
|
||||
for (unsigned h = cb ? bucket(cb) : 0; h < CBT_BUCKETS; h = cb ? CBT_BUCKETS : h + 1) {
|
||||
cbt_entry **pp = &k->b[h];
|
||||
while (*pp) {
|
||||
cbt_entry *e = *pp;
|
||||
if ((cb && e->cb == cb) || (!cb && e->pool == pool)) {
|
||||
*pp = e->next;
|
||||
free(e);
|
||||
} else {
|
||||
pp = &e->next;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static VKAPI_ATTR void VKAPI_CALL cbt_FreeCommandBuffers(VkDevice device, VkCommandPool pool, uint32_t n, const VkCommandBuffer *cbs)
|
||||
{
|
||||
vkb_cbtrack *k = cur();
|
||||
pthread_mutex_lock(&k->lock);
|
||||
for (uint32_t i = 0; i < n; i++)
|
||||
if (cbs[i]) forget_locked(k, cbs[i], pool);
|
||||
pthread_mutex_unlock(&k->lock);
|
||||
k->free_cbs(device, pool, n, cbs);
|
||||
}
|
||||
|
||||
static VKAPI_ATTR void VKAPI_CALL cbt_DestroyCommandPool(VkDevice device, VkCommandPool pool, const VkAllocationCallbacks *a)
|
||||
{
|
||||
vkb_cbtrack *k = cur();
|
||||
if (pool) {
|
||||
pthread_mutex_lock(&k->lock);
|
||||
forget_locked(k, VK_NULL_HANDLE, pool);
|
||||
pthread_mutex_unlock(&k->lock);
|
||||
}
|
||||
k->destroy_pool(device, pool, a);
|
||||
}
|
||||
|
||||
static VKAPI_ATTR VkResult VKAPI_CALL cbt_BeginCommandBuffer(VkCommandBuffer cb, const VkCommandBufferBeginInfo *info)
|
||||
{
|
||||
vkb_cbtrack *k = cur();
|
||||
if (!vkb_cbtrack_known(vkb_srv_current_table(), cb, "vkBeginCommandBuffer")) return VK_ERROR_DEVICE_LOST;
|
||||
return k->begin(cb, info);
|
||||
}
|
||||
|
||||
static VKAPI_ATTR VkResult VKAPI_CALL cbt_QueueSubmit(VkQueue queue, uint32_t n, const VkSubmitInfo *s, VkFence fence)
|
||||
{
|
||||
vkb_cbtrack *k = cur();
|
||||
vkb_srv_table *t = vkb_srv_current_table();
|
||||
for (uint32_t i = 0; i < n; i++)
|
||||
for (uint32_t j = 0; j < s[i].commandBufferCount; j++)
|
||||
if (!vkb_cbtrack_known(t, s[i].pCommandBuffers[j], "vkQueueSubmit")) return VK_ERROR_DEVICE_LOST;
|
||||
return k->submit(queue, n, s, fence);
|
||||
}
|
||||
|
||||
static VKAPI_ATTR VkResult VKAPI_CALL cbt_QueueSubmit2(VkQueue queue, uint32_t n, const VkSubmitInfo2 *s, VkFence fence)
|
||||
{
|
||||
vkb_cbtrack *k = cur();
|
||||
vkb_srv_table *t = vkb_srv_current_table();
|
||||
for (uint32_t i = 0; i < n; i++)
|
||||
for (uint32_t j = 0; j < s[i].commandBufferInfoCount; j++)
|
||||
if (!vkb_cbtrack_known(t, s[i].pCommandBufferInfos[j].commandBuffer, "vkQueueSubmit2")) return VK_ERROR_DEVICE_LOST;
|
||||
return k->submit2(queue, n, s, fence);
|
||||
}
|
||||
|
||||
void vkb_cbtrack_device_init(vkb_srv_table *t)
|
||||
{
|
||||
if (!t->dt.vkAllocateCommandBuffers || !t->dt.vkFreeCommandBuffers || !t->dt.vkDestroyCommandPool || !t->dt.vkBeginCommandBuffer ||
|
||||
!t->dt.vkQueueSubmit)
|
||||
return;
|
||||
vkb_cbtrack *k = calloc(1, sizeof(*k));
|
||||
if (!k) return;
|
||||
pthread_mutex_init(&k->lock, NULL);
|
||||
k->alloc = t->dt.vkAllocateCommandBuffers;
|
||||
k->free_cbs = t->dt.vkFreeCommandBuffers;
|
||||
k->destroy_pool = t->dt.vkDestroyCommandPool;
|
||||
k->begin = t->dt.vkBeginCommandBuffer;
|
||||
k->submit = t->dt.vkQueueSubmit;
|
||||
k->submit2 = t->dt.vkQueueSubmit2;
|
||||
t->cbtrack = k;
|
||||
t->dt.vkAllocateCommandBuffers = cbt_AllocateCommandBuffers;
|
||||
t->dt.vkFreeCommandBuffers = cbt_FreeCommandBuffers;
|
||||
t->dt.vkDestroyCommandPool = cbt_DestroyCommandPool;
|
||||
t->dt.vkBeginCommandBuffer = cbt_BeginCommandBuffer;
|
||||
t->dt.vkQueueSubmit = cbt_QueueSubmit;
|
||||
if (k->submit2) t->dt.vkQueueSubmit2 = cbt_QueueSubmit2;
|
||||
}
|
||||
|
||||
void vkb_cbtrack_device_destroy(vkb_srv_table *t)
|
||||
{
|
||||
vkb_cbtrack *k = t->cbtrack;
|
||||
if (!k) return;
|
||||
for (unsigned h = 0; h < CBT_BUCKETS; h++) {
|
||||
while (k->b[h]) {
|
||||
cbt_entry *e = k->b[h];
|
||||
k->b[h] = e->next;
|
||||
free(e);
|
||||
}
|
||||
}
|
||||
pthread_mutex_destroy(&k->lock);
|
||||
free(k);
|
||||
t->cbtrack = NULL;
|
||||
}
|
||||
@@ -0,0 +1,608 @@
|
||||
/* SPDX-License-Identifier: GPL-3.0-or-later
|
||||
*
|
||||
* Connections: one thread per client thread, requests executed in order, replies sent back.
|
||||
* A command buffer's recorded commands arrive in one message at vkEndCommandBuffer and are
|
||||
* replayed here.
|
||||
*/
|
||||
#define _GNU_SOURCE
|
||||
#include "vkb_server.h"
|
||||
|
||||
#include <errno.h>
|
||||
#include <setjmp.h>
|
||||
#include <signal.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/socket.h>
|
||||
#include <time.h>
|
||||
#include <unistd.h>
|
||||
|
||||
static pthread_mutex_t tables_lock = PTHREAD_MUTEX_INITIALIZER;
|
||||
static vkb_srv_table *tables[VKB_MAX_TABLES];
|
||||
static uint32_t next_table_id = 1;
|
||||
|
||||
static pthread_mutex_t procs_lock = PTHREAD_MUTEX_INITIALIZER;
|
||||
static vkb_srv_proc *procs;
|
||||
|
||||
static __thread vkb_srv_table *tls_table;
|
||||
__thread const char *vkb_srv_current_cmd;
|
||||
|
||||
vkb_srv_table *vkb_srv_current_table(void) { return tls_table; }
|
||||
void vkb_srv_set_current_table(vkb_srv_table *t) { tls_table = t; }
|
||||
|
||||
/* Server side of the generated encoders' helpers: handles are already the server's values. */
|
||||
uint64_t vkb_remote(const void *h) { return (uint64_t)(uintptr_t)h; }
|
||||
int vkb_cb_begin_is_secondary(const VkCommandBufferBeginInfo *s) { (void)s; return 1; }
|
||||
|
||||
uint32_t vkb_table_register(vkb_srv_table *t)
|
||||
{
|
||||
pthread_mutex_lock(&tables_lock);
|
||||
uint32_t id = 0;
|
||||
for (uint32_t tries = 0; tries < VKB_MAX_TABLES; tries++) {
|
||||
uint32_t cand = next_table_id++;
|
||||
if (next_table_id >= VKB_MAX_TABLES) next_table_id = 1;
|
||||
if (!tables[cand]) {
|
||||
id = cand;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (id) {
|
||||
t->id = id;
|
||||
tables[id] = t;
|
||||
}
|
||||
pthread_mutex_unlock(&tables_lock);
|
||||
return id;
|
||||
}
|
||||
|
||||
void vkb_table_unregister(vkb_srv_table *t)
|
||||
{
|
||||
pthread_mutex_lock(&tables_lock);
|
||||
if (t->id && t->id < VKB_MAX_TABLES && tables[t->id] == t) tables[t->id] = NULL;
|
||||
pthread_mutex_unlock(&tables_lock);
|
||||
}
|
||||
|
||||
vkb_srv_table *vkb_table_get(uint32_t id)
|
||||
{
|
||||
if (!id || id >= VKB_MAX_TABLES) return NULL;
|
||||
pthread_mutex_lock(&tables_lock);
|
||||
vkb_srv_table *t = tables[id];
|
||||
pthread_mutex_unlock(&tables_lock);
|
||||
return t;
|
||||
}
|
||||
|
||||
void vkb_srv_reply_status(vkb_srv_call *c, uint32_t status)
|
||||
{
|
||||
c->status = status;
|
||||
}
|
||||
|
||||
void vkb_srv_bad_message(vkb_srv_call *c)
|
||||
{
|
||||
VKB_ERR("malformed request");
|
||||
c->status = VKB_ST_BAD_MESSAGE;
|
||||
}
|
||||
|
||||
void vkb_srv_missing(vkb_srv_call *c, const char *name)
|
||||
{
|
||||
VKB_ERR("the driver has no %s", name);
|
||||
c->status = VKB_ST_MISSING;
|
||||
}
|
||||
|
||||
void vkb_srv_close_after_send(vkb_srv_call *c, int fd)
|
||||
{
|
||||
if (c->nclose < VKB_MAX_FDS) c->close_after[c->nclose++] = fd;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ process cleanup */
|
||||
|
||||
void vkb_proc_cleanup(vkb_srv_proc *p)
|
||||
{
|
||||
/* Devices first, then their instances. */
|
||||
for (int pass = 0; pass < 2; pass++) {
|
||||
for (uint32_t i = 1; i < VKB_MAX_TABLES; i++) {
|
||||
pthread_mutex_lock(&tables_lock);
|
||||
vkb_srv_table *t = tables[i];
|
||||
int mine = t && t->proc == p && t->is_device == (pass == 0);
|
||||
if (mine) tables[i] = NULL;
|
||||
pthread_mutex_unlock(&tables_lock);
|
||||
if (!mine) continue;
|
||||
if (p->driver_crashed) {
|
||||
/* The driver faulted for this process: calling into it for its objects again could
|
||||
* fault again, outside any guard. They are left to the driver. */
|
||||
VKB_WARN("process %d: %s %u left as it is (the driver crashed serving it)", p->pid, t->is_device ? "device" : "instance", t->id);
|
||||
if (t->is_device) vkb_cbtrack_device_destroy(t);
|
||||
} else if (t->is_device) {
|
||||
VKB_INFO("process %d exited without destroying device %u; cleaning up", p->pid, t->id);
|
||||
vkb_cbtrack_device_destroy(t);
|
||||
if (t->real.vkDeviceWaitIdle) t->real.vkDeviceWaitIdle(t->device);
|
||||
vkb_spvfix_device_destroy(t);
|
||||
vkb_dsmap_device_destroy(t);
|
||||
vkb_pcache_device_destroy(t);
|
||||
vkb_emu_device_destroy(t);
|
||||
vkb_mem_free_all(t);
|
||||
t->real.vkDestroyDevice(t->device, NULL);
|
||||
} else {
|
||||
VKB_INFO("process %d exited without destroying instance %u; cleaning up", p->pid, t->id);
|
||||
t->real.vkDestroyInstance(t->instance, NULL);
|
||||
}
|
||||
pthread_mutex_destroy(&t->lock);
|
||||
free(t);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static vkb_srv_proc *proc_join(uint64_t token, int pid)
|
||||
{
|
||||
pthread_mutex_lock(&procs_lock);
|
||||
vkb_srv_proc *p = procs;
|
||||
while (p && p->token != token) p = p->next;
|
||||
if (!p) {
|
||||
p = calloc(1, sizeof(*p));
|
||||
p->token = token;
|
||||
p->pid = pid;
|
||||
pthread_mutex_init(&p->olock, NULL);
|
||||
pthread_cond_init(&p->ocond, NULL);
|
||||
p->next = procs;
|
||||
procs = p;
|
||||
VKB_INFO("client process %d connected", pid);
|
||||
}
|
||||
p->conns++;
|
||||
pthread_mutex_unlock(&procs_lock);
|
||||
return p;
|
||||
}
|
||||
|
||||
static void proc_leave(vkb_srv_proc *p)
|
||||
{
|
||||
pthread_mutex_lock(&procs_lock);
|
||||
int last = --p->conns == 0;
|
||||
if (last) {
|
||||
vkb_srv_proc **pp = &procs;
|
||||
while (*pp && *pp != p) pp = &(*pp)->next;
|
||||
if (*pp) *pp = p->next;
|
||||
}
|
||||
pthread_mutex_unlock(&procs_lock);
|
||||
if (last) {
|
||||
vkb_proc_cleanup(p);
|
||||
VKB_INFO("client process %d gone", p->pid);
|
||||
pthread_mutex_destroy(&p->olock);
|
||||
pthread_cond_destroy(&p->ocond);
|
||||
free(p);
|
||||
} else {
|
||||
pthread_mutex_lock(&p->olock);
|
||||
p->conn_closed = 1;
|
||||
pthread_cond_broadcast(&p->ocond);
|
||||
pthread_mutex_unlock(&p->olock);
|
||||
}
|
||||
}
|
||||
|
||||
/* Waits until every async request of the process up to `barrier` has run. */
|
||||
static void order_wait(vkb_srv_proc *p, uint64_t barrier)
|
||||
{
|
||||
if (!p || !barrier) return;
|
||||
pthread_mutex_lock(&p->olock);
|
||||
int waited = 0;
|
||||
while (p->watermark < barrier) {
|
||||
struct timespec ts;
|
||||
clock_gettime(CLOCK_REALTIME, &ts);
|
||||
ts.tv_sec += 1;
|
||||
if (pthread_cond_timedwait(&p->ocond, &p->olock, &ts) != 0 && ++waited >= 3 && p->conn_closed) {
|
||||
/* A connection of this process is gone with requests it never sent: go on. */
|
||||
VKB_WARN("process %d: async request %llu never arrived; continuing", p->pid, (unsigned long long)(p->watermark + 1));
|
||||
p->watermark = barrier;
|
||||
memset(p->done, 0, sizeof(p->done));
|
||||
break;
|
||||
}
|
||||
}
|
||||
pthread_mutex_unlock(&p->olock);
|
||||
}
|
||||
|
||||
static void order_done(vkb_srv_proc *p, uint64_t seq)
|
||||
{
|
||||
if (!p || !seq) return;
|
||||
pthread_mutex_lock(&p->olock);
|
||||
if (seq > p->watermark) {
|
||||
p->done[seq % VKB_SEQ_RING] = 1;
|
||||
while (p->done[(p->watermark + 1) % VKB_SEQ_RING]) {
|
||||
p->done[(p->watermark + 1) % VKB_SEQ_RING] = 0;
|
||||
p->watermark++;
|
||||
}
|
||||
pthread_cond_broadcast(&p->ocond);
|
||||
}
|
||||
pthread_mutex_unlock(&p->olock);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ command buffer replay */
|
||||
|
||||
static int is_stream_cmd(uint32_t id)
|
||||
{
|
||||
const char *n = vkb_cmd_names[id];
|
||||
return !strncmp(n, "vkCmd", 5) || id == VKB_CMD_vkBeginCommandBuffer || id == VKB_CMD_vkbPushDescRaw;
|
||||
}
|
||||
|
||||
void vkb_sv_vkEndCommandBuffer(vkb_srv_call *c)
|
||||
{
|
||||
VkCommandBuffer cb = (VkCommandBuffer)(uintptr_t)vkb_dec_u64(&c->d);
|
||||
size_t len = 0;
|
||||
const uint8_t *s = vkb_dec_blob(&c->d, &len);
|
||||
if (c->d.err) {
|
||||
vkb_srv_bad_message(c);
|
||||
return;
|
||||
}
|
||||
/* A command buffer the device never handed out (or has freed) is not replayed: the driver would
|
||||
* be given a pointer it does not own (server_cbtrack.c). */
|
||||
if (!vkb_cbtrack_known(c->table, cb, "vkEndCommandBuffer")) {
|
||||
vkb_enc_u32(&c->r, (uint32_t)VK_ERROR_DEVICE_LOST);
|
||||
return;
|
||||
}
|
||||
VkResult begin_r = VK_SUCCESS;
|
||||
size_t pos = 0;
|
||||
vkb_enc scratch;
|
||||
vkb_enc_init(&scratch);
|
||||
uint32_t ncmds = 0;
|
||||
while (s && pos + 8 <= len) {
|
||||
uint32_t id, n;
|
||||
memcpy(&id, s + pos, 4);
|
||||
memcpy(&n, s + pos + 4, 4);
|
||||
pos += 8;
|
||||
if (id >= VKB_CMD_COUNT || !is_stream_cmd(id) || n > len - pos) {
|
||||
VKB_ERR("command stream: bad entry (id %u, %u bytes) after %u commands", id, n, ncmds);
|
||||
c->status = VKB_ST_BAD_MESSAGE;
|
||||
vkb_enc_free(&scratch);
|
||||
return;
|
||||
}
|
||||
vkb_srv_call sub;
|
||||
memset(&sub, 0, sizeof(sub));
|
||||
vkb_dec_init(&sub.d, s + pos, n, c->d.arena, NULL, 0);
|
||||
sub.r = scratch;
|
||||
vkb_enc_reset(&sub.r);
|
||||
sub.dt = c->dt;
|
||||
sub.table = c->table;
|
||||
sub.conn = c->conn;
|
||||
sub.in_stream = 1;
|
||||
vkb_srv_current_cmd = vkb_cmd_names[id];
|
||||
vkb_srv_handlers[id](&sub);
|
||||
vkb_srv_current_cmd = vkb_cmd_names[VKB_CMD_vkEndCommandBuffer];
|
||||
scratch = sub.r;
|
||||
if (sub.status != VKB_ST_OK) {
|
||||
VKB_ERR("command stream: %s failed (status %u)", vkb_cmd_names[id], sub.status);
|
||||
}
|
||||
if (id == VKB_CMD_vkBeginCommandBuffer && scratch.len >= 4) memcpy(&begin_r, scratch.buf, 4);
|
||||
pos += (n + 7) & ~(size_t)7;
|
||||
ncmds++;
|
||||
}
|
||||
vkb_enc_free(&scratch);
|
||||
VkResult r = c->dt->vkEndCommandBuffer(cb);
|
||||
if (begin_r != VK_SUCCESS) r = begin_r;
|
||||
if (vkb_verbose) VKB_DBG("command buffer %p: %u commands, %zu bytes -> %d", (void *)cb, ncmds, len, r);
|
||||
vkb_enc_u32(&c->r, (uint32_t)r);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ hello */
|
||||
|
||||
void vkb_sv_vkbHello(vkb_srv_call *c)
|
||||
{
|
||||
uint64_t hash = vkb_dec_u64(&c->d);
|
||||
uint64_t token = vkb_dec_u64(&c->d);
|
||||
uint32_t pid = vkb_dec_u32(&c->d);
|
||||
const char *comm = vkb_dec_str(&c->d);
|
||||
if (c->d.err) {
|
||||
vkb_srv_bad_message(c);
|
||||
return;
|
||||
}
|
||||
vkb_enc_u64(&c->r, VKB_PROTOCOL_HASH);
|
||||
if (hash != VKB_PROTOCOL_HASH) {
|
||||
VKB_ERR("client %d (%s) speaks protocol %016llx, this server %016llx: refusing", pid,
|
||||
comm ? comm : "?", (unsigned long long)hash, (unsigned long long)VKB_PROTOCOL_HASH);
|
||||
vkb_enc_u32(&c->r, 0);
|
||||
return;
|
||||
}
|
||||
if (!c->conn->proc) {
|
||||
c->conn->proc = proc_join(token, (int)pid);
|
||||
if (c->conn->proc->conns == 1) VKB_INFO("process %u is %s", pid, comm ? comm : "?");
|
||||
}
|
||||
vkb_enc_u32(&c->r, 1);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ statistics */
|
||||
|
||||
/* VKBRIDGE_STATS=<seconds> on the server: time spent per command, waiting for order, idle. */
|
||||
static uint64_t st_ns[VKB_CMD_COUNT], st_n[VKB_CMD_COUNT], st_wait_ns, st_last;
|
||||
static int st_period = -1;
|
||||
|
||||
static uint64_t mono_ns(void)
|
||||
{
|
||||
struct timespec ts;
|
||||
clock_gettime(CLOCK_MONOTONIC, &ts);
|
||||
return (uint64_t)ts.tv_sec * 1000000000ull + (uint64_t)ts.tv_nsec;
|
||||
}
|
||||
|
||||
static void stats_add(uint32_t cmd, uint64_t ns, uint64_t wait_ns)
|
||||
{
|
||||
if (st_period < 0) {
|
||||
const char *v = getenv("VKBRIDGE_STATS");
|
||||
st_period = v ? atoi(v) : 0;
|
||||
}
|
||||
if (!st_period) return;
|
||||
__atomic_add_fetch(&st_ns[cmd], ns, __ATOMIC_RELAXED);
|
||||
__atomic_add_fetch(&st_n[cmd], 1, __ATOMIC_RELAXED);
|
||||
__atomic_add_fetch(&st_wait_ns, wait_ns, __ATOMIC_RELAXED);
|
||||
uint64_t now = mono_ns(), last = __atomic_load_n(&st_last, __ATOMIC_RELAXED);
|
||||
if (!last) {
|
||||
__atomic_store_n(&st_last, now, __ATOMIC_RELAXED);
|
||||
return;
|
||||
}
|
||||
if (now - last < (uint64_t)st_period * 1000000000ull || !__atomic_compare_exchange_n(&st_last, &last, now, 0, __ATOMIC_RELAXED, __ATOMIC_RELAXED))
|
||||
return;
|
||||
uint64_t total = 0;
|
||||
for (uint32_t i = 0; i < VKB_CMD_COUNT; i++) total += st_ns[i];
|
||||
VKB_INFO("stats over %ds: %.1f ms in handlers, %.1f ms waiting for order", st_period, total / 1e6, st_wait_ns / 1e6);
|
||||
for (int k = 0; k < 8; k++) {
|
||||
uint64_t best = 0;
|
||||
uint32_t bi = 0;
|
||||
for (uint32_t i = 0; i < VKB_CMD_COUNT; i++)
|
||||
if (st_ns[i] > best) {
|
||||
best = st_ns[i];
|
||||
bi = i;
|
||||
}
|
||||
if (!best) break;
|
||||
VKB_INFO(" %-40s %8llu calls %9.2f ms (%.2f us each)", vkb_cmd_names[bi], (unsigned long long)st_n[bi], best / 1e6,
|
||||
best / 1e3 / (double)st_n[bi]);
|
||||
st_ns[bi] = 0;
|
||||
}
|
||||
memset(st_ns, 0, sizeof(st_ns));
|
||||
memset(st_n, 0, sizeof(st_n));
|
||||
st_wait_ns = 0;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ connection loop */
|
||||
|
||||
/* Reads the next request. Buffered: a burst of small asynchronous requests costs one recvmsg, not
|
||||
* two reads each. Descriptors arrive with the first bytes of their message, so they queue up in
|
||||
* order and each header takes its nfds from the front. The payload points into the buffer and
|
||||
* stays valid until the next call. */
|
||||
static int srv_recv(vkb_srv_conn *conn, vkb_msg_hdr *h, uint8_t **payload, int *fds, int *nfds)
|
||||
{
|
||||
*nfds = 0;
|
||||
if (conn->rpos == conn->rlen && conn->rcap > (16u << 20)) {
|
||||
free(conn->rb);
|
||||
conn->rb = NULL;
|
||||
conn->rcap = conn->rpos = conn->rlen = 0;
|
||||
}
|
||||
for (;;) {
|
||||
size_t avail = conn->rlen - conn->rpos;
|
||||
size_t need = sizeof(*h);
|
||||
if (avail >= sizeof(*h)) {
|
||||
memcpy(h, conn->rb + conn->rpos, sizeof(*h));
|
||||
if (h->magic != VKB_MAGIC) {
|
||||
VKB_ERR("transport: bad message magic 0x%08x", h->magic);
|
||||
return -1;
|
||||
}
|
||||
if (h->size > (1u << 30) || h->nfds > VKB_MAX_FDS) {
|
||||
VKB_ERR("transport: bad message (%u bytes, %u descriptors)", h->size, h->nfds);
|
||||
return -1;
|
||||
}
|
||||
need += h->size;
|
||||
if (avail >= need) {
|
||||
if ((int)h->nfds > conn->fdn) {
|
||||
VKB_ERR("transport: message arrived without its %u descriptors", h->nfds);
|
||||
return -1;
|
||||
}
|
||||
*nfds = (int)h->nfds;
|
||||
memcpy(fds, conn->fdq, sizeof(int) * h->nfds);
|
||||
conn->fdn -= (int)h->nfds;
|
||||
memmove(conn->fdq, conn->fdq + h->nfds, sizeof(int) * conn->fdn);
|
||||
*payload = conn->rb + conn->rpos + sizeof(*h);
|
||||
conn->rpos += need;
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
if (conn->rpos) {
|
||||
memmove(conn->rb, conn->rb + conn->rpos, avail);
|
||||
conn->rpos = 0;
|
||||
conn->rlen = avail;
|
||||
}
|
||||
if (need < (256u << 10)) need = 256u << 10;
|
||||
if (need > conn->rcap) {
|
||||
size_t nc = conn->rcap ? conn->rcap : (256u << 10);
|
||||
while (nc < need) nc *= 2;
|
||||
uint8_t *nb = realloc(conn->rb, nc);
|
||||
if (!nb) return -1;
|
||||
conn->rb = nb;
|
||||
conn->rcap = nc;
|
||||
}
|
||||
union {
|
||||
char buf[CMSG_SPACE(sizeof(int) * VKB_MAX_FDS)];
|
||||
struct cmsghdr align;
|
||||
} cm;
|
||||
struct iovec iov = {conn->rb + conn->rlen, conn->rcap - conn->rlen};
|
||||
struct msghdr msg;
|
||||
memset(&msg, 0, sizeof(msg));
|
||||
msg.msg_iov = &iov;
|
||||
msg.msg_iovlen = 1;
|
||||
msg.msg_control = cm.buf;
|
||||
msg.msg_controllen = sizeof(cm.buf);
|
||||
ssize_t r;
|
||||
do {
|
||||
r = recvmsg(conn->sock, &msg, MSG_CMSG_CLOEXEC);
|
||||
} while (r < 0 && errno == EINTR);
|
||||
if (r <= 0) return -1;
|
||||
for (struct cmsghdr *cmh = CMSG_FIRSTHDR(&msg); cmh; cmh = CMSG_NXTHDR(&msg, cmh)) {
|
||||
if (cmh->cmsg_level != SOL_SOCKET || cmh->cmsg_type != SCM_RIGHTS) continue;
|
||||
int n = (int)((cmh->cmsg_len - CMSG_LEN(0)) / sizeof(int));
|
||||
for (int i = 0; i < n; i++) {
|
||||
int fd;
|
||||
memcpy(&fd, CMSG_DATA(cmh) + i * sizeof(int), sizeof(int));
|
||||
if (conn->fdn < (int)(sizeof(conn->fdq) / sizeof(conn->fdq[0]))) conn->fdq[conn->fdn++] = fd;
|
||||
else close(fd);
|
||||
}
|
||||
}
|
||||
if (msg.msg_flags & MSG_CTRUNC) VKB_WARN("transport: descriptors truncated");
|
||||
conn->rlen += (size_t)r;
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ driver fault guard */
|
||||
|
||||
/*
|
||||
* A fault inside the GPU driver while serving one client used to take the whole app down (the
|
||||
* server runs in its process). Each request runs under a guard: SIGSEGV/SIGBUS on that thread
|
||||
* jumps back here, the client is cut off (it sees the bridge gone and fails or falls back), and
|
||||
* the app and the other clients go on. Any other fault goes to the handler that was there before.
|
||||
*/
|
||||
static __thread sigjmp_buf *t_guard;
|
||||
static __thread volatile sig_atomic_t t_fault;
|
||||
static struct sigaction prev_segv, prev_bus;
|
||||
static pthread_once_t guard_once = PTHREAD_ONCE_INIT;
|
||||
|
||||
static void guard_handler(int sig, siginfo_t *si, void *uc)
|
||||
{
|
||||
sigjmp_buf *g = t_guard;
|
||||
if (g) {
|
||||
t_guard = NULL;
|
||||
t_fault = sig;
|
||||
siglongjmp(*g, 1);
|
||||
}
|
||||
struct sigaction *p = sig == SIGBUS ? &prev_bus : &prev_segv;
|
||||
if ((p->sa_flags & SA_SIGINFO) && p->sa_sigaction) {
|
||||
p->sa_sigaction(sig, si, uc);
|
||||
return;
|
||||
}
|
||||
if (!(p->sa_flags & SA_SIGINFO) && p->sa_handler == SIG_IGN) return;
|
||||
if (!(p->sa_flags & SA_SIGINFO) && p->sa_handler && p->sa_handler != SIG_DFL) {
|
||||
p->sa_handler(sig);
|
||||
return;
|
||||
}
|
||||
signal(sig, SIG_DFL);
|
||||
raise(sig);
|
||||
}
|
||||
|
||||
static void guard_install(void)
|
||||
{
|
||||
struct sigaction sa;
|
||||
memset(&sa, 0, sizeof(sa));
|
||||
sa.sa_sigaction = guard_handler;
|
||||
sa.sa_flags = SA_SIGINFO | SA_ONSTACK;
|
||||
sigemptyset(&sa.sa_mask);
|
||||
sigaction(SIGSEGV, &sa, &prev_segv);
|
||||
sigaction(SIGBUS, &sa, &prev_bus);
|
||||
}
|
||||
|
||||
static void *conn_main(void *arg)
|
||||
{
|
||||
pthread_once(&guard_once, guard_install);
|
||||
vkb_srv_conn *conn = arg;
|
||||
vkb_srv_call c;
|
||||
vkb_enc_init(&c.r);
|
||||
int fds[VKB_MAX_FDS];
|
||||
for (;;) {
|
||||
vkb_msg_hdr h;
|
||||
int nfds = 0;
|
||||
uint8_t *payload;
|
||||
if (srv_recv(conn, &h, &payload, fds, &nfds) < 0) break;
|
||||
vkb_enc_reset(&c.r);
|
||||
vkb_dec_init(&c.d, payload, h.size, &conn->arena, fds, nfds);
|
||||
c.conn = conn;
|
||||
c.status = VKB_ST_OK;
|
||||
c.nclose = 0;
|
||||
c.in_stream = 0;
|
||||
c.table = NULL;
|
||||
c.dt = &vkb_global_dt;
|
||||
if (h.cmd >= VKB_CMD_COUNT) {
|
||||
VKB_ERR("unknown command id %u", h.cmd);
|
||||
c.status = VKB_ST_BAD_MESSAGE;
|
||||
} else if (!conn->proc && h.cmd != VKB_CMD_vkbHello) {
|
||||
VKB_ERR("%s before hello", vkb_cmd_names[h.cmd]);
|
||||
c.status = VKB_ST_BAD_MESSAGE;
|
||||
} else {
|
||||
if (h.table) {
|
||||
c.table = vkb_table_get(h.table);
|
||||
if (!c.table || c.table->proc != conn->proc) {
|
||||
VKB_ERR("%s: unknown dispatch table %u", vkb_cmd_names[h.cmd], h.table);
|
||||
c.status = VKB_ST_BAD_TABLE;
|
||||
} else {
|
||||
c.dt = &c.table->dt;
|
||||
}
|
||||
}
|
||||
if (c.status == VKB_ST_OK) {
|
||||
uint64_t t0 = st_period ? mono_ns() : 0;
|
||||
order_wait(conn->proc, h.barrier);
|
||||
uint64_t t1 = st_period ? mono_ns() : 0;
|
||||
vkb_srv_set_current_table(c.table);
|
||||
if (vkb_verbose) VKB_DBG("-> %s", vkb_cmd_names[h.cmd]);
|
||||
vkb_srv_current_cmd = vkb_cmd_names[h.cmd];
|
||||
sigjmp_buf jb;
|
||||
if (sigsetjmp(jb, 1)) {
|
||||
VKB_ERR("the GPU driver crashed (signal %d) in %s for process %d; that client is cut off, the app and "
|
||||
"the other clients carry on", (int)t_fault, vkb_cmd_names[h.cmd], conn->proc ? conn->proc->pid : -1);
|
||||
if (conn->proc) conn->proc->driver_crashed = 1;
|
||||
vkb_srv_current_cmd = NULL;
|
||||
vkb_srv_set_current_table(NULL);
|
||||
order_done(conn->proc, h.seq);
|
||||
break;
|
||||
}
|
||||
t_guard = &jb;
|
||||
vkb_srv_handlers[h.cmd](&c);
|
||||
t_guard = NULL;
|
||||
vkb_srv_current_cmd = NULL;
|
||||
vkb_srv_set_current_table(NULL);
|
||||
if (st_period) stats_add(h.cmd, mono_ns() - t1, t1 - t0);
|
||||
}
|
||||
}
|
||||
vkb_dec_close_untaken(&c.d);
|
||||
order_done(conn->proc, h.seq);
|
||||
if (!(h.flags & VKB_F_NOREPLY)) {
|
||||
vkb_msg_hdr rh = {VKB_MAGIC, c.status == VKB_ST_OK ? (uint32_t)c.r.len : 0, c.status, 0,
|
||||
c.status == VKB_ST_OK ? (uint32_t)c.r.nfds : 0, 0, 0, 0};
|
||||
if (c.r.oom) {
|
||||
rh.cmd = VKB_ST_BAD_MESSAGE;
|
||||
rh.size = 0;
|
||||
rh.nfds = 0;
|
||||
}
|
||||
if (vkb_send_msg(conn->sock, &rh, c.r.buf, c.r.fds, (int)rh.nfds) < 0) {
|
||||
for (int i = 0; i < c.nclose; i++) close(c.close_after[i]);
|
||||
break;
|
||||
}
|
||||
} else if (c.status != VKB_ST_OK) {
|
||||
VKB_ERR("asynchronous %s failed (status %u)", vkb_cmd_names[h.cmd], c.status);
|
||||
} else if (vkb_cmd_result[h.cmd] && c.r.len >= sizeof(int32_t)) {
|
||||
/* The client already told the app VK_SUCCESS; a failure can only be reported here. */
|
||||
int32_t vr;
|
||||
memcpy(&vr, c.r.buf, sizeof(vr));
|
||||
if (vr < 0) VKB_ERR("asynchronous %s returned %d", vkb_cmd_names[h.cmd], vr);
|
||||
}
|
||||
for (int i = 0; i < c.nclose; i++) close(c.close_after[i]);
|
||||
vkb_arena_reset(&conn->arena);
|
||||
}
|
||||
close(conn->sock);
|
||||
vkb_enc_free(&c.r);
|
||||
free(conn->rb);
|
||||
for (int i = 0; i < conn->fdn; i++) close(conn->fdq[i]);
|
||||
vkb_arena_free(&conn->arena);
|
||||
if (conn->proc) proc_leave(conn->proc);
|
||||
free(conn);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
void vkb_srv_serve(int lfd)
|
||||
{
|
||||
stats_add(0, 0, 0);
|
||||
for (;;) {
|
||||
int s = accept4(lfd, NULL, NULL, SOCK_CLOEXEC);
|
||||
if (s < 0) {
|
||||
if (errno == EINTR || errno == ECONNABORTED) continue;
|
||||
VKB_ERR("accept: %s", strerror(errno));
|
||||
continue;
|
||||
}
|
||||
vkb_srv_conn *conn = calloc(1, sizeof(*conn));
|
||||
conn->sock = s;
|
||||
pthread_attr_t attr;
|
||||
pthread_attr_init(&attr);
|
||||
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
|
||||
/* Driver calls (pipeline compiles) can use a lot of stack. */
|
||||
pthread_attr_setstacksize(&attr, 4u << 20);
|
||||
if (pthread_create(&conn->thread, &attr, conn_main, conn) != 0) {
|
||||
VKB_ERR("cannot start a connection thread");
|
||||
close(s);
|
||||
free(conn);
|
||||
}
|
||||
pthread_attr_destroy(&attr);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,337 @@
|
||||
/* SPDX-License-Identifier: GPL-3.0-or-later
|
||||
*
|
||||
* Descriptor sets named by the client. Where the client keeps a pool's books it knows an
|
||||
* allocation will succeed, so it names the sets itself (VKB_DS_TAG | n) and sends the allocation
|
||||
* without waiting (vkbAllocDescSets) - DXVK allocates a set or two per draw, and a round trip
|
||||
* each was most of the bridge's remaining cost per frame. Here those names map to the driver's
|
||||
* sets: wrappers in the device's dispatch table translate them wherever a set goes back to the
|
||||
* driver (updates, template updates, binds, frees), and a pool's reset or destruction forgets its
|
||||
* sets. Sets the server named itself (the synchronous path) pass through untouched.
|
||||
*/
|
||||
#define _GNU_SOURCE
|
||||
#include "vkb_server.h"
|
||||
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#define VKB_DS_TAG (1ull << 63)
|
||||
#define DS_BUCKETS 8192
|
||||
#define DS_LOCAL 64
|
||||
|
||||
typedef struct ds_ent {
|
||||
uint64_t id;
|
||||
VkDescriptorSet set;
|
||||
struct ds_ent *next; /* bucket chain */
|
||||
struct ds_ent *pool_next; /* the pool's sets */
|
||||
} ds_ent;
|
||||
|
||||
typedef struct ds_pool {
|
||||
VkDescriptorPool pool;
|
||||
ds_ent *sets;
|
||||
struct ds_pool *next;
|
||||
} ds_pool;
|
||||
|
||||
typedef struct vkb_dsmap {
|
||||
pthread_mutex_t lock;
|
||||
ds_ent *buckets[DS_BUCKETS];
|
||||
ds_pool *pools;
|
||||
int warned;
|
||||
PFN_vkAllocateDescriptorSets allocate;
|
||||
PFN_vkUpdateDescriptorSets update;
|
||||
PFN_vkUpdateDescriptorSetWithTemplate update_template;
|
||||
PFN_vkCmdBindDescriptorSets bind;
|
||||
PFN_vkCmdBindDescriptorSets2 bind2;
|
||||
PFN_vkFreeDescriptorSets free_sets;
|
||||
PFN_vkResetDescriptorPool reset_pool;
|
||||
PFN_vkDestroyDescriptorPool destroy_pool;
|
||||
} vkb_dsmap;
|
||||
|
||||
static unsigned bucket(uint64_t id)
|
||||
{
|
||||
id *= 0x9e3779b97f4a7c15ull;
|
||||
return (unsigned)(id >> 51) & (DS_BUCKETS - 1);
|
||||
}
|
||||
|
||||
static vkb_dsmap *cur(void)
|
||||
{
|
||||
vkb_srv_table *t = vkb_srv_current_table();
|
||||
return t ? t->dsmap : NULL;
|
||||
}
|
||||
|
||||
static int tagged(VkDescriptorSet s)
|
||||
{
|
||||
return ((uint64_t)s & VKB_DS_TAG) != 0;
|
||||
}
|
||||
|
||||
/* The driver's set for a client name; VK_NULL_HANDLE when its allocation failed. */
|
||||
static VkDescriptorSet lookup(vkb_dsmap *m, VkDescriptorSet s)
|
||||
{
|
||||
if (!tagged(s)) return s;
|
||||
uint64_t id = (uint64_t)s;
|
||||
pthread_mutex_lock(&m->lock);
|
||||
ds_ent *e = m->buckets[bucket(id)];
|
||||
while (e && e->id != id) e = e->next;
|
||||
VkDescriptorSet r = e ? e->set : VK_NULL_HANDLE;
|
||||
pthread_mutex_unlock(&m->lock);
|
||||
return r;
|
||||
}
|
||||
|
||||
static void missing(vkb_dsmap *m, const char *where)
|
||||
{
|
||||
if (__atomic_fetch_add(&m->warned, 1, __ATOMIC_RELAXED) < 20)
|
||||
VKB_ERR("%s: a descriptor set the client allocated ahead does not exist (its allocation failed); skipped", where);
|
||||
}
|
||||
|
||||
static ds_pool *pool_get(vkb_dsmap *m, VkDescriptorPool pool, int create)
|
||||
{
|
||||
for (ds_pool *p = m->pools; p; p = p->next)
|
||||
if (p->pool == pool) return p;
|
||||
if (!create) return NULL;
|
||||
ds_pool *p = calloc(1, sizeof(*p));
|
||||
if (!p) return NULL;
|
||||
p->pool = pool;
|
||||
p->next = m->pools;
|
||||
m->pools = p;
|
||||
return p;
|
||||
}
|
||||
|
||||
/* Forgets the pool's sets (a reset or destruction freed them); the record goes with destroy. */
|
||||
static void pool_forget(vkb_dsmap *m, VkDescriptorPool pool, int destroy)
|
||||
{
|
||||
pthread_mutex_lock(&m->lock);
|
||||
for (ds_pool **pp = &m->pools; *pp; pp = &(*pp)->next) {
|
||||
ds_pool *p = *pp;
|
||||
if (p->pool != pool) continue;
|
||||
while (p->sets) {
|
||||
ds_ent *e = p->sets;
|
||||
p->sets = e->pool_next;
|
||||
ds_ent **bp = &m->buckets[bucket(e->id)];
|
||||
while (*bp && *bp != e) bp = &(*bp)->next;
|
||||
if (*bp) *bp = e->next;
|
||||
free(e);
|
||||
}
|
||||
if (destroy) {
|
||||
*pp = p->next;
|
||||
free(p);
|
||||
}
|
||||
break;
|
||||
}
|
||||
pthread_mutex_unlock(&m->lock);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ the allocation request */
|
||||
|
||||
/* vkbAllocDescSets: device, pool, count, then per set its layout and the client's name. */
|
||||
void vkb_sv_vkbAllocDescSets(vkb_srv_call *c)
|
||||
{
|
||||
VkDevice dev = (VkDevice)(uintptr_t)vkb_dec_u64(&c->d);
|
||||
VkDescriptorPool pool;
|
||||
vkb_dec_bytes(&c->d, &pool, sizeof(pool));
|
||||
uint32_t n = vkb_dec_u32(&c->d);
|
||||
if (c->d.err || !c->table || !c->table->dsmap || n == 0 || n > 4096) {
|
||||
vkb_srv_bad_message(c);
|
||||
return;
|
||||
}
|
||||
vkb_dsmap *m = c->table->dsmap;
|
||||
VkDescriptorSetLayout layouts_local[DS_LOCAL], *layouts = n <= DS_LOCAL ? layouts_local : malloc(n * sizeof(*layouts));
|
||||
uint64_t ids_local[DS_LOCAL], *ids = n <= DS_LOCAL ? ids_local : malloc(n * sizeof(*ids));
|
||||
VkDescriptorSet sets_local[DS_LOCAL], *sets = n <= DS_LOCAL ? sets_local : malloc(n * sizeof(*sets));
|
||||
if (!layouts || !ids || !sets) goto out;
|
||||
for (uint32_t i = 0; i < n; i++) {
|
||||
vkb_dec_bytes(&c->d, &layouts[i], sizeof(layouts[i]));
|
||||
ids[i] = vkb_dec_u64(&c->d);
|
||||
}
|
||||
if (c->d.err) {
|
||||
vkb_srv_bad_message(c);
|
||||
goto out;
|
||||
}
|
||||
VkDescriptorSetAllocateInfo ai = {VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO, NULL, pool, n, layouts};
|
||||
VkResult r = m->allocate(dev, &ai, sets);
|
||||
if (r != VK_SUCCESS) {
|
||||
VKB_ERR("allocating %u descriptor sets the client named ahead failed: %d (the client's pool books disagree "
|
||||
"with the driver)", n, r);
|
||||
goto out;
|
||||
}
|
||||
pthread_mutex_lock(&m->lock);
|
||||
ds_pool *p = pool_get(m, pool, 1);
|
||||
for (uint32_t i = 0; i < n; i++) {
|
||||
ds_ent *e = malloc(sizeof(*e));
|
||||
if (!e || !p) {
|
||||
free(e);
|
||||
break;
|
||||
}
|
||||
e->id = ids[i];
|
||||
e->set = sets[i];
|
||||
unsigned b = bucket(e->id);
|
||||
e->next = m->buckets[b];
|
||||
m->buckets[b] = e;
|
||||
e->pool_next = p->sets;
|
||||
p->sets = e;
|
||||
}
|
||||
pthread_mutex_unlock(&m->lock);
|
||||
out:
|
||||
if (layouts != layouts_local) free(layouts);
|
||||
if (ids != ids_local) free(ids);
|
||||
if (sets != sets_local) free(sets);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ wrappers */
|
||||
|
||||
static void VKAPI_CALL ds_UpdateDescriptorSets(VkDevice device, uint32_t nw, const VkWriteDescriptorSet *w, uint32_t nc,
|
||||
const VkCopyDescriptorSet *cp)
|
||||
{
|
||||
vkb_dsmap *m = cur();
|
||||
int any = 0;
|
||||
for (uint32_t i = 0; i < nw && !any; i++) any = tagged(w[i].dstSet);
|
||||
for (uint32_t i = 0; i < nc && !any; i++) any = tagged(cp[i].srcSet) || tagged(cp[i].dstSet);
|
||||
if (!any) {
|
||||
m->update(device, nw, w, nc, cp);
|
||||
return;
|
||||
}
|
||||
VkWriteDescriptorSet w_local[DS_LOCAL], *w2 = nw <= DS_LOCAL ? w_local : malloc(nw * sizeof(*w2));
|
||||
VkCopyDescriptorSet c_local[DS_LOCAL], *c2 = nc <= DS_LOCAL ? c_local : malloc(nc * sizeof(*c2));
|
||||
if ((nw && !w2) || (nc && !c2)) goto out;
|
||||
uint32_t kw = 0, kc = 0;
|
||||
for (uint32_t i = 0; i < nw; i++) {
|
||||
w2[kw] = w[i];
|
||||
w2[kw].dstSet = lookup(m, w[i].dstSet);
|
||||
if (w2[kw].dstSet) kw++;
|
||||
else missing(m, "vkUpdateDescriptorSets");
|
||||
}
|
||||
for (uint32_t i = 0; i < nc; i++) {
|
||||
c2[kc] = cp[i];
|
||||
c2[kc].srcSet = lookup(m, cp[i].srcSet);
|
||||
c2[kc].dstSet = lookup(m, cp[i].dstSet);
|
||||
if (c2[kc].srcSet && c2[kc].dstSet) kc++;
|
||||
else missing(m, "vkUpdateDescriptorSets (copy)");
|
||||
}
|
||||
if (kw || kc) m->update(device, kw, w2, kc, c2);
|
||||
out:
|
||||
if (w2 != w_local) free(w2);
|
||||
if (c2 != c_local) free(c2);
|
||||
}
|
||||
|
||||
static void VKAPI_CALL ds_UpdateDescriptorSetWithTemplate(VkDevice device, VkDescriptorSet set, VkDescriptorUpdateTemplate tmpl,
|
||||
const void *data)
|
||||
{
|
||||
vkb_dsmap *m = cur();
|
||||
VkDescriptorSet s = lookup(m, set);
|
||||
if (!s) {
|
||||
missing(m, "vkUpdateDescriptorSetWithTemplate");
|
||||
return;
|
||||
}
|
||||
m->update_template(device, s, tmpl, data);
|
||||
}
|
||||
|
||||
/* Translates n sets into out; 0 when one of them does not exist. */
|
||||
static int translate(vkb_dsmap *m, uint32_t n, const VkDescriptorSet *in, VkDescriptorSet *out)
|
||||
{
|
||||
for (uint32_t i = 0; i < n; i++) {
|
||||
/* VK_NULL_HANDLE is allowed in binds (graphicsPipelineLibrary) and stays so. */
|
||||
out[i] = in[i] ? lookup(m, in[i]) : VK_NULL_HANDLE;
|
||||
if (in[i] && !out[i]) return 0;
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
static void VKAPI_CALL ds_CmdBindDescriptorSets(VkCommandBuffer cb, VkPipelineBindPoint bp, VkPipelineLayout layout, uint32_t first,
|
||||
uint32_t n, const VkDescriptorSet *sets, uint32_t ndyn, const uint32_t *dyn)
|
||||
{
|
||||
vkb_dsmap *m = cur();
|
||||
VkDescriptorSet local[DS_LOCAL], *s = n <= DS_LOCAL ? local : malloc(n * sizeof(*s));
|
||||
if (!s) return;
|
||||
if (translate(m, n, sets, s)) m->bind(cb, bp, layout, first, n, s, ndyn, dyn);
|
||||
else missing(m, "vkCmdBindDescriptorSets");
|
||||
if (s != local) free(s);
|
||||
}
|
||||
|
||||
static void VKAPI_CALL ds_CmdBindDescriptorSets2(VkCommandBuffer cb, const VkBindDescriptorSetsInfo *info)
|
||||
{
|
||||
vkb_dsmap *m = cur();
|
||||
uint32_t n = info->descriptorSetCount;
|
||||
VkDescriptorSet local[DS_LOCAL], *s = n <= DS_LOCAL ? local : malloc(n * sizeof(*s));
|
||||
if (!s) return;
|
||||
VkBindDescriptorSetsInfo i2 = *info;
|
||||
i2.pDescriptorSets = s;
|
||||
if (translate(m, n, info->pDescriptorSets, s)) m->bind2(cb, &i2);
|
||||
else missing(m, "vkCmdBindDescriptorSets2");
|
||||
if (s != local) free(s);
|
||||
}
|
||||
|
||||
static VkResult VKAPI_CALL ds_FreeDescriptorSets(VkDevice device, VkDescriptorPool pool, uint32_t n, const VkDescriptorSet *sets)
|
||||
{
|
||||
vkb_dsmap *m = cur();
|
||||
VkDescriptorSet local[DS_LOCAL], *s = n <= DS_LOCAL ? local : malloc(n * sizeof(*s));
|
||||
if (!s) return VK_ERROR_OUT_OF_HOST_MEMORY;
|
||||
/* Named sets come only from pools without FREE_DESCRIPTOR_SET (the client keeps no books on
|
||||
* those), so this is an app error at worst: what does not exist is left out. */
|
||||
uint32_t k = 0;
|
||||
for (uint32_t i = 0; i < n; i++) {
|
||||
VkDescriptorSet t = sets[i] ? lookup(m, sets[i]) : VK_NULL_HANDLE;
|
||||
if (t || !sets[i]) s[k++] = t;
|
||||
}
|
||||
VkResult r = k ? m->free_sets(device, pool, k, s) : VK_SUCCESS;
|
||||
if (s != local) free(s);
|
||||
return r;
|
||||
}
|
||||
|
||||
static VkResult VKAPI_CALL ds_ResetDescriptorPool(VkDevice device, VkDescriptorPool pool, VkDescriptorPoolResetFlags flags)
|
||||
{
|
||||
vkb_dsmap *m = cur();
|
||||
pool_forget(m, pool, 0);
|
||||
return m->reset_pool(device, pool, flags);
|
||||
}
|
||||
|
||||
static void VKAPI_CALL ds_DestroyDescriptorPool(VkDevice device, VkDescriptorPool pool, const VkAllocationCallbacks *a)
|
||||
{
|
||||
vkb_dsmap *m = cur();
|
||||
if (pool) pool_forget(m, pool, 1);
|
||||
m->destroy_pool(device, pool, a);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ device hooks */
|
||||
|
||||
void vkb_dsmap_device_init(vkb_srv_table *t)
|
||||
{
|
||||
vkb_dispatch *dt = &t->dt;
|
||||
if (!dt->vkAllocateDescriptorSets || !dt->vkUpdateDescriptorSets || !dt->vkCmdBindDescriptorSets ||
|
||||
!dt->vkResetDescriptorPool || !dt->vkDestroyDescriptorPool || !dt->vkFreeDescriptorSets)
|
||||
return;
|
||||
vkb_dsmap *m = calloc(1, sizeof(*m));
|
||||
if (!m) return;
|
||||
pthread_mutex_init(&m->lock, NULL);
|
||||
m->allocate = dt->vkAllocateDescriptorSets;
|
||||
m->update = dt->vkUpdateDescriptorSets;
|
||||
m->update_template = dt->vkUpdateDescriptorSetWithTemplate;
|
||||
m->bind = dt->vkCmdBindDescriptorSets;
|
||||
m->bind2 = dt->vkCmdBindDescriptorSets2;
|
||||
m->free_sets = dt->vkFreeDescriptorSets;
|
||||
m->reset_pool = dt->vkResetDescriptorPool;
|
||||
m->destroy_pool = dt->vkDestroyDescriptorPool;
|
||||
dt->vkUpdateDescriptorSets = ds_UpdateDescriptorSets;
|
||||
if (m->update_template) dt->vkUpdateDescriptorSetWithTemplate = ds_UpdateDescriptorSetWithTemplate;
|
||||
dt->vkCmdBindDescriptorSets = ds_CmdBindDescriptorSets;
|
||||
if (m->bind2) dt->vkCmdBindDescriptorSets2 = ds_CmdBindDescriptorSets2;
|
||||
dt->vkFreeDescriptorSets = ds_FreeDescriptorSets;
|
||||
dt->vkResetDescriptorPool = ds_ResetDescriptorPool;
|
||||
dt->vkDestroyDescriptorPool = ds_DestroyDescriptorPool;
|
||||
t->dsmap = m;
|
||||
}
|
||||
|
||||
void vkb_dsmap_device_destroy(vkb_srv_table *t)
|
||||
{
|
||||
vkb_dsmap *m = t->dsmap;
|
||||
if (!m) return;
|
||||
vkb_dispatch *dt = &t->dt;
|
||||
dt->vkUpdateDescriptorSets = m->update;
|
||||
if (m->update_template) dt->vkUpdateDescriptorSetWithTemplate = m->update_template;
|
||||
dt->vkCmdBindDescriptorSets = m->bind;
|
||||
if (m->bind2) dt->vkCmdBindDescriptorSets2 = m->bind2;
|
||||
dt->vkFreeDescriptorSets = m->free_sets;
|
||||
dt->vkResetDescriptorPool = m->reset_pool;
|
||||
dt->vkDestroyDescriptorPool = m->destroy_pool;
|
||||
while (m->pools) pool_forget(m, m->pools->pool, 1);
|
||||
pthread_mutex_destroy(&m->lock);
|
||||
free(m);
|
||||
t->dsmap = NULL;
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
/* SPDX-License-Identifier: GPL-3.0-or-later
|
||||
*
|
||||
* Feature emulation: entry point. What the GPU lacks and the bridge can make up for is decided
|
||||
* here per physical device; the client reports those features as present, the server strips
|
||||
* them from vkCreateDevice and installs wrappers in the device's dispatch table.
|
||||
*/
|
||||
#define _GNU_SOURCE
|
||||
#include "vkb_server.h"
|
||||
#include "server_emu.h"
|
||||
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
static int token(const char *list, const char *t)
|
||||
{
|
||||
size_t n = strlen(t);
|
||||
for (const char *p = list; p && (p = strstr(p, t)); p += n)
|
||||
if ((p == list || p[-1] == ',') && (p[n] == ',' || p[n] == 0)) return 1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int env_off(const char *name)
|
||||
{
|
||||
const char *v = getenv(name);
|
||||
return v && !strcmp(v, "0");
|
||||
}
|
||||
|
||||
uint32_t vkb_emu_detect(const vkb_dispatch *idt, VkPhysicalDevice pd, uint32_t *missing)
|
||||
{
|
||||
VkPhysicalDeviceFeatures f;
|
||||
idt->vkGetPhysicalDeviceFeatures(pd, &f);
|
||||
uint32_t n = 0;
|
||||
idt->vkEnumerateDeviceExtensionProperties(pd, NULL, &n, NULL);
|
||||
VkExtensionProperties *e = calloc(n ? n : 1, sizeof(*e));
|
||||
idt->vkEnumerateDeviceExtensionProperties(pd, NULL, &n, e);
|
||||
int divisor = 0, depth_clip = 0, maint5 = 0, robust2 = 0;
|
||||
for (uint32_t i = 0; i < n; i++) {
|
||||
if (!strcmp(e[i].extensionName, "VK_EXT_vertex_attribute_divisor") ||
|
||||
!strcmp(e[i].extensionName, "VK_KHR_vertex_attribute_divisor"))
|
||||
divisor = 1;
|
||||
if (!strcmp(e[i].extensionName, "VK_EXT_depth_clip_enable")) depth_clip = 1;
|
||||
if (!strcmp(e[i].extensionName, "VK_KHR_maintenance5")) maint5 = 1;
|
||||
if (!strcmp(e[i].extensionName, "VK_EXT_robustness2") || !strcmp(e[i].extensionName, "VK_KHR_robustness2")) robust2 = 1;
|
||||
}
|
||||
free(e);
|
||||
/* VKBRIDGE_FAKE_MISSING=bc,divisor,clip,cull,depthclip pretends the GPU lacks them (host tests). */
|
||||
const char *fake = getenv("VKBRIDGE_FAKE_MISSING");
|
||||
if (fake) {
|
||||
if (token(fake, "bc")) f.textureCompressionBC = VK_FALSE;
|
||||
if (token(fake, "divisor")) divisor = 0;
|
||||
if (token(fake, "clip")) f.shaderClipDistance = VK_FALSE;
|
||||
if (token(fake, "cull")) f.shaderCullDistance = VK_FALSE;
|
||||
if (token(fake, "depthclip")) depth_clip = 0;
|
||||
if (token(fake, "maint5")) maint5 = 0;
|
||||
if (token(fake, "robustness2")) robust2 = 0;
|
||||
}
|
||||
uint32_t emu = 0;
|
||||
VkPhysicalDeviceProperties props;
|
||||
idt->vkGetPhysicalDeviceProperties(pd, &props);
|
||||
/* Vulkan 1.4 has maintenance5 in core. */
|
||||
if (!maint5 && (props.apiVersion < VK_API_VERSION_1_4 || (fake && token(fake, "maint5"))) && !env_off("VKBRIDGE_EMU_MAINT5"))
|
||||
emu |= VKB_EMU_MAINT5;
|
||||
if (!f.textureCompressionBC && vkb_emu_bcn_supported(idt, pd) && !env_off("VKBRIDGE_EMU_BCN")) emu |= VKB_EMU_BCN;
|
||||
if (!divisor && !env_off("VKBRIDGE_EMU_DIVISOR")) emu |= VKB_EMU_DIVISOR;
|
||||
if (!f.shaderClipDistance && !env_off("VKBRIDGE_EMU_CLIP")) emu |= VKB_EMU_CLIP_DISTANCE;
|
||||
if (!f.shaderCullDistance && !env_off("VKBRIDGE_EMU_CULL")) emu |= VKB_EMU_CULL_DISTANCE;
|
||||
if (!depth_clip && f.depthClamp && !env_off("VKBRIDGE_EMU_DEPTHCLIP")) emu |= VKB_EMU_DEPTH_CLIP;
|
||||
/* DXVK will not start without robustness2. Mali r44 lacks it; GameNative's wrapper reports it
|
||||
* (robustBufferAccess2, robustImageAccess2, nullDescriptor) without enforcing it, and DXVK
|
||||
* games run - out-of-bounds reads and null descriptors are then up to the driver. */
|
||||
if (!robust2 && f.robustBufferAccess && !env_off("VKBRIDGE_EMU_ROBUSTNESS2")) emu |= VKB_EMU_ROBUSTNESS2;
|
||||
/* PointSize in geometry/tessellation stages: stripped when the feature is missing. */
|
||||
if (!f.shaderTessellationAndGeometryPointSize && (f.geometryShader || f.tessellationShader)) emu |= VKB_EMU_POINT_SIZE;
|
||||
uint32_t miss = 0;
|
||||
if (!f.textureCompressionBC) miss |= VKB_EMU_BCN;
|
||||
if (!divisor) miss |= VKB_EMU_DIVISOR;
|
||||
if (!f.shaderClipDistance) miss |= VKB_EMU_CLIP_DISTANCE;
|
||||
if (!f.shaderCullDistance) miss |= VKB_EMU_CULL_DISTANCE;
|
||||
if (!depth_clip) miss |= VKB_EMU_DEPTH_CLIP;
|
||||
if (emu & VKB_EMU_MAINT5) miss |= VKB_EMU_MAINT5;
|
||||
if (!robust2) miss |= VKB_EMU_ROBUSTNESS2;
|
||||
*missing = miss;
|
||||
return emu & VKB_EMU_IMPLEMENTED;
|
||||
}
|
||||
|
||||
/* Remove a structure from a pNext chain (the chain lives in the request's arena). */
|
||||
static void chain_remove(VkDeviceCreateInfo *ci, VkStructureType t)
|
||||
{
|
||||
VkBaseOutStructure *prev = (VkBaseOutStructure *)ci;
|
||||
while (prev->pNext) {
|
||||
if (prev->pNext->sType == t) prev->pNext = prev->pNext->pNext;
|
||||
else prev = prev->pNext;
|
||||
}
|
||||
}
|
||||
|
||||
static VkPhysicalDeviceFeatures *find_features(VkDeviceCreateInfo *ci)
|
||||
{
|
||||
if (ci->pEnabledFeatures) return (VkPhysicalDeviceFeatures *)ci->pEnabledFeatures;
|
||||
for (VkBaseOutStructure *b = (VkBaseOutStructure *)ci->pNext; b; b = b->pNext)
|
||||
if (b->sType == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2) return &((VkPhysicalDeviceFeatures2 *)b)->features;
|
||||
return NULL;
|
||||
}
|
||||
|
||||
void vkb_emu_device_create_info(vkb_srv_table *inst, VkPhysicalDevice pd, uint32_t emu, VkDeviceCreateInfo *ci, vkb_arena *a)
|
||||
{
|
||||
VkPhysicalDeviceFeatures real;
|
||||
inst->real.vkGetPhysicalDeviceFeatures(pd, &real);
|
||||
VkPhysicalDeviceFeatures *f = find_features(ci);
|
||||
if ((emu & (VKB_EMU_BCN | VKB_EMU_DEPTH_CLIP)) && !f) {
|
||||
/* The BC decoder writes R8/RG8 storage images: it needs this feature on, so the request
|
||||
* gets a features structure if it had none. */
|
||||
f = vkb_arena_alloc(a, sizeof(*f));
|
||||
ci->pEnabledFeatures = f;
|
||||
}
|
||||
if (f) {
|
||||
/* pEnabledFeatures came from the request: it is ours to change. Anything the client asked
|
||||
* for that the GPU does not have is either emulated or would fail the call. */
|
||||
VkBool32 *want = (VkBool32 *)f;
|
||||
const VkBool32 *have = (const VkBool32 *)ℜ
|
||||
for (size_t i = 0; i < sizeof(*f) / sizeof(VkBool32); i++) {
|
||||
if (want[i] && !have[i]) want[i] = VK_FALSE;
|
||||
}
|
||||
if (emu & VKB_EMU_BCN) f->shaderStorageImageExtendedFormats = VK_TRUE;
|
||||
if (emu & VKB_EMU_DEPTH_CLIP) f->depthClamp = VK_TRUE;
|
||||
}
|
||||
if (emu & VKB_EMU_DIVISOR) chain_remove(ci, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VERTEX_ATTRIBUTE_DIVISOR_FEATURES_EXT);
|
||||
if (emu & VKB_EMU_DEPTH_CLIP) chain_remove(ci, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DEPTH_CLIP_ENABLE_FEATURES_EXT);
|
||||
if (emu & VKB_EMU_MAINT5) chain_remove(ci, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_5_FEATURES);
|
||||
if (emu & VKB_EMU_ROBUSTNESS2) {
|
||||
chain_remove(ci, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ROBUSTNESS_2_FEATURES_EXT);
|
||||
/* What robustness the GPU has stays on; robustBufferAccess2 asks for at least that. */
|
||||
VkPhysicalDeviceFeatures *rf = find_features(ci);
|
||||
if (rf) rf->robustBufferAccess = VK_TRUE;
|
||||
}
|
||||
}
|
||||
|
||||
void vkb_emu_device_init(vkb_srv_table *dev, uint32_t emu)
|
||||
{
|
||||
if (!emu) return;
|
||||
vkb_emu_device *e = calloc(1, sizeof(*e));
|
||||
e->flags = emu;
|
||||
e->dev = dev;
|
||||
pthread_mutex_init(&e->lock, NULL);
|
||||
dev->emu = e;
|
||||
vkb_emu_install(dev);
|
||||
}
|
||||
|
||||
void vkb_emu_device_destroy(vkb_srv_table *dev)
|
||||
{
|
||||
if (!dev->emu) return;
|
||||
vkb_emu_uninstall(dev);
|
||||
pthread_mutex_destroy(&dev->emu->lock);
|
||||
free(dev->emu);
|
||||
dev->emu = NULL;
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
/* SPDX-License-Identifier: GPL-3.0-or-later */
|
||||
#ifndef VKB_SERVER_EMU_H
|
||||
#define VKB_SERVER_EMU_H
|
||||
|
||||
#include "vkb_server.h"
|
||||
|
||||
/* Emulations that are implemented (the rest are never offered to the client). */
|
||||
#define VKB_EMU_IMPLEMENTED (VKB_EMU_MAINT5 | VKB_EMU_CLIP_DISTANCE | VKB_EMU_CULL_DISTANCE | VKB_EMU_POINT_SIZE | VKB_EMU_BCN | \
|
||||
VKB_EMU_DIVISOR | VKB_EMU_DEPTH_CLIP | VKB_EMU_ROBUSTNESS2)
|
||||
|
||||
#define VKB_EMU_BUCKETS 1024
|
||||
|
||||
typedef struct vkb_emu_image {
|
||||
VkImage image;
|
||||
VkImageType type;
|
||||
VkFormat format; /* what the driver holds */
|
||||
VkFormat client_format; /* what the app asked for (differs for emulated formats) */
|
||||
VkExtent3D extent;
|
||||
uint32_t mips, layers;
|
||||
void *emu; /* per-emulation state (BCn: decode resources) */
|
||||
struct vkb_emu_image *next;
|
||||
} vkb_emu_image;
|
||||
|
||||
typedef struct vkb_emu_buffer {
|
||||
VkBuffer buffer;
|
||||
VkDeviceSize size;
|
||||
struct vkb_emu_buffer *next;
|
||||
} vkb_emu_buffer;
|
||||
|
||||
typedef struct vkb_emu_device {
|
||||
uint32_t flags;
|
||||
vkb_srv_table *dev;
|
||||
pthread_mutex_t lock;
|
||||
vkb_emu_image *images[VKB_EMU_BUCKETS];
|
||||
vkb_emu_buffer *buffers[VKB_EMU_BUCKETS];
|
||||
void *bcn; /* server_emu_bcn.c */
|
||||
void *cmdstate; /* server_emu_cmdstate.c */
|
||||
void *divisor; /* server_emu_divisor.c */
|
||||
void *shaders; /* server_emu_shader.c */
|
||||
} vkb_emu_device;
|
||||
|
||||
/* command buffer state (server_emu_cmdstate.c) */
|
||||
void vkb_emu_cmdstate_install(vkb_srv_table *dev);
|
||||
void vkb_emu_cmdstate_uninstall(vkb_srv_table *dev);
|
||||
void vkb_emu_restore_compute(vkb_emu_device *e, VkCommandBuffer cb);
|
||||
void *vkb_emu_cb_gfx(vkb_emu_device *e, VkCommandBuffer cb, size_t size);
|
||||
VkDescriptorSet vkb_emu_cb_scratch_set(vkb_emu_device *e, VkCommandBuffer cb, VkDescriptorSetLayout dsl);
|
||||
/* vertex attribute divisor (server_emu_divisor.c) */
|
||||
typedef struct div_info div_info;
|
||||
size_t vkb_emu_divisor_info_size(void);
|
||||
void vkb_emu_divisor_pipeline(vkb_emu_device *e, VkDevice device, VkGraphicsPipelineCreateInfo *ci, div_info *out);
|
||||
void vkb_emu_divisor_created(vkb_emu_device *e, VkDevice device, VkPipelineCache cache, const VkGraphicsPipelineCreateInfo *ci,
|
||||
VkPipeline p, div_info *info);
|
||||
void vkb_emu_divisor_install(vkb_srv_table *dev);
|
||||
void vkb_emu_divisor_uninstall(vkb_srv_table *dev);
|
||||
void vkb_emu_gfx_bind_pipeline(vkb_emu_device *e, VkCommandBuffer cb, VkPipeline p);
|
||||
void vkb_emu_gfx_reset(void *gfx);
|
||||
void vkb_emu_gfx_free(void *gfx);
|
||||
/* BCn (server_emu_bcn.c) */
|
||||
void vkb_emu_bcn_install(vkb_srv_table *dev);
|
||||
void vkb_emu_bcn_uninstall(vkb_srv_table *dev);
|
||||
VkFormat vkb_emu_bcn_view_format(vkb_emu_device *e, VkImage image, VkFormat requested);
|
||||
void vkb_emu_bcn_buffer_usage(vkb_emu_device *e, VkBufferCreateInfo *ci);
|
||||
int vkb_emu_bcn_blocks_readback(vkb_emu_device *e, VkImage img);
|
||||
|
||||
/* layer (server_emu_layer.c) */
|
||||
void vkb_emu_depth_clip_pipeline(vkb_emu_device *e, VkGraphicsPipelineCreateInfo *ci);
|
||||
void vkb_emu_depth_clip_install(vkb_srv_table *dev);
|
||||
vkb_emu_device *vkb_emu_cur(void);
|
||||
const vkb_dispatch *vkb_emu_real(void);
|
||||
void *vkb_emu_chain_take(const void *head, VkStructureType t);
|
||||
vkb_emu_image *vkb_emu_find_image(vkb_emu_device *e, VkImage img);
|
||||
void vkb_emu_track_image(vkb_emu_device *e, VkImage img, const VkImageCreateInfo *ci, VkFormat client_format);
|
||||
|
||||
/* feature hooks (server_emu_features.c and friends) */
|
||||
int vkb_emu_bcn_supported(const vkb_dispatch *idt, VkPhysicalDevice pd);
|
||||
void vkb_emu_install(vkb_srv_table *dev);
|
||||
void vkb_emu_uninstall(vkb_srv_table *dev);
|
||||
void vkb_emu_install_features(vkb_srv_table *dev);
|
||||
void vkb_emu_uninstall_features(vkb_srv_table *dev);
|
||||
void vkb_emu_image_create_info(vkb_emu_device *e, VkImageCreateInfo *ci);
|
||||
void vkb_emu_image_release(vkb_emu_device *e, vkb_emu_image *img);
|
||||
/* Rewrites a graphics pipeline's shaders; temporary modules are appended to mods. */
|
||||
void vkb_emu_shader_pipeline(vkb_emu_device *e, VkDevice device, VkGraphicsPipelineCreateInfo *ci, VkShaderModule *mods,
|
||||
uint32_t *nmods, uint32_t cap);
|
||||
void vkb_emu_shader_install(vkb_srv_table *dev);
|
||||
VkShaderModule vkb_emu_shader_zero_base_instance(vkb_emu_device *e, VkDevice device, const VkPipelineShaderStageCreateInfo *vs);
|
||||
void vkb_emu_shader_uninstall(vkb_srv_table *dev);
|
||||
/* 1 = handled (the emulation recorded its own commands instead). */
|
||||
int vkb_emu_copy_image(vkb_emu_device *e, VkCommandBuffer cb, VkImage src, VkImageLayout sl, VkImage dst, VkImageLayout dl,
|
||||
uint32_t n, const VkImageCopy *regions);
|
||||
int vkb_emu_copy_image2(vkb_emu_device *e, VkCommandBuffer cb, const VkCopyImageInfo2 *info);
|
||||
int vkb_emu_copy_buffer_to_image(vkb_emu_device *e, VkCommandBuffer cb, VkBuffer src, VkImage dst, VkImageLayout dl, uint32_t n,
|
||||
const VkBufferImageCopy *regions);
|
||||
int vkb_emu_copy_buffer_to_image2(vkb_emu_device *e, VkCommandBuffer cb, const VkCopyBufferToImageInfo2 *info);
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,432 @@
|
||||
/* SPDX-License-Identifier: GPL-3.0-or-later
|
||||
*
|
||||
* BC1-BC7 textures on a GPU without them (textureCompressionBC missing; DXVK and vkd3d-proton
|
||||
* refuse such a device). The image the app creates in a BC format is created decoded instead
|
||||
* (RGBA8 / R8 / RG8 / RGBA16F, see vkb_emu_formats.h), mutable so sRGB/SNORM views work, and
|
||||
* every upload - vkCmdCopyBufferToImage(2), how all BC data arrives - becomes a compute dispatch
|
||||
* that decodes the blocks from the source buffer straight into it (shaders/bc_decode.comp). The
|
||||
* app's compute bindings are restored afterwards (server_emu_cmdstate.c).
|
||||
*
|
||||
* Not emulated (logged once): reading a BC image back to a buffer, and copies between BC and
|
||||
* uncompressed images (they would need an encoder).
|
||||
*/
|
||||
#define _GNU_SOURCE
|
||||
#include "server_emu.h"
|
||||
#include "vkb_emu_formats.h"
|
||||
#include "bc_spv.h"
|
||||
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
enum { FAM_BC1, FAM_BC2, FAM_BC3, FAM_BC4, FAM_BC5, FAM_BC6H, FAM_BC7, FAM_COUNT };
|
||||
|
||||
typedef struct bcn_state {
|
||||
VkDescriptorSetLayout dsl;
|
||||
VkPipelineLayout layout;
|
||||
VkPipeline pipes[FAM_COUNT];
|
||||
VkDeviceSize ssbo_align;
|
||||
int push; /* VK_KHR_push_descriptor; else per-command-buffer sets */
|
||||
pthread_mutex_t lock;
|
||||
} bcn_state;
|
||||
|
||||
typedef struct bcn_image {
|
||||
VkImageView views[16]; /* per mip: 2D array storage view of every layer */
|
||||
} bcn_image;
|
||||
|
||||
typedef struct pc_t {
|
||||
uint32_t src_word, row_blocks, layer_blocks, flags;
|
||||
int32_t dst_off[2];
|
||||
uint32_t extent[2];
|
||||
} pc_t;
|
||||
|
||||
static int family(VkFormat f)
|
||||
{
|
||||
switch (f) {
|
||||
case VK_FORMAT_BC1_RGB_UNORM_BLOCK: case VK_FORMAT_BC1_RGB_SRGB_BLOCK:
|
||||
case VK_FORMAT_BC1_RGBA_UNORM_BLOCK: case VK_FORMAT_BC1_RGBA_SRGB_BLOCK: return FAM_BC1;
|
||||
case VK_FORMAT_BC2_UNORM_BLOCK: case VK_FORMAT_BC2_SRGB_BLOCK: return FAM_BC2;
|
||||
case VK_FORMAT_BC3_UNORM_BLOCK: case VK_FORMAT_BC3_SRGB_BLOCK: return FAM_BC3;
|
||||
case VK_FORMAT_BC4_UNORM_BLOCK: case VK_FORMAT_BC4_SNORM_BLOCK: return FAM_BC4;
|
||||
case VK_FORMAT_BC5_UNORM_BLOCK: case VK_FORMAT_BC5_SNORM_BLOCK: return FAM_BC5;
|
||||
case VK_FORMAT_BC6H_UFLOAT_BLOCK: case VK_FORMAT_BC6H_SFLOAT_BLOCK: return FAM_BC6H;
|
||||
default: return FAM_BC7;
|
||||
}
|
||||
}
|
||||
|
||||
static uint32_t family_flags(VkFormat f)
|
||||
{
|
||||
uint32_t fl = 0;
|
||||
if (f == VK_FORMAT_BC1_RGB_UNORM_BLOCK || f == VK_FORMAT_BC1_RGB_SRGB_BLOCK) fl |= 1;
|
||||
if (f == VK_FORMAT_BC4_SNORM_BLOCK || f == VK_FORMAT_BC5_SNORM_BLOCK || f == VK_FORMAT_BC6H_SFLOAT_BLOCK) fl |= 2;
|
||||
return fl;
|
||||
}
|
||||
|
||||
int vkb_emu_bcn_supported(const vkb_dispatch *idt, VkPhysicalDevice pd)
|
||||
{
|
||||
VkPhysicalDeviceFeatures f;
|
||||
idt->vkGetPhysicalDeviceFeatures(pd, &f);
|
||||
if (!f.shaderStorageImageExtendedFormats) {
|
||||
VKB_WARN("BC emulation: the GPU lacks shaderStorageImageExtendedFormats");
|
||||
return 0;
|
||||
}
|
||||
static const VkFormat need[] = {VK_FORMAT_R8G8B8A8_UNORM, VK_FORMAT_R8_UNORM, VK_FORMAT_R8G8_UNORM, VK_FORMAT_R16G16B16A16_SFLOAT};
|
||||
for (size_t i = 0; i < sizeof(need) / sizeof(need[0]); i++) {
|
||||
VkFormatProperties fp;
|
||||
idt->vkGetPhysicalDeviceFormatProperties(pd, need[i], &fp);
|
||||
if (!(fp.optimalTilingFeatures & VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT)) {
|
||||
VKB_WARN("BC emulation: format %d cannot be a storage image", need[i]);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
VkPhysicalDeviceProperties p;
|
||||
idt->vkGetPhysicalDeviceProperties(pd, &p);
|
||||
if (p.apiVersion >= VK_API_VERSION_1_4) return 1;
|
||||
uint32_t n = 0;
|
||||
idt->vkEnumerateDeviceExtensionProperties(pd, NULL, &n, NULL);
|
||||
VkExtensionProperties *e = calloc(n ? n : 1, sizeof(*e));
|
||||
idt->vkEnumerateDeviceExtensionProperties(pd, NULL, &n, e);
|
||||
free(e);
|
||||
/* Without VK_KHR_push_descriptor (Mali-G720 on driver 44.1) the decoder binds ordinary sets. */
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* Push descriptors for the decoder; without them, sets from the command buffer's scratch pools.
|
||||
* VKBRIDGE_FAKE_MISSING=...,push takes the second way on a GPU that has them (host tests). */
|
||||
static int has_push(vkb_srv_table *dev)
|
||||
{
|
||||
const char *fake = getenv("VKBRIDGE_FAKE_MISSING");
|
||||
if (fake && strstr(fake, "push")) return 0;
|
||||
VkPhysicalDeviceProperties p;
|
||||
dev->real.vkGetPhysicalDeviceProperties(dev->physical, &p);
|
||||
if (p.apiVersion >= VK_API_VERSION_1_4 && dev->api_version >= VK_API_VERSION_1_4) return dev->real.vkCmdPushDescriptorSet != NULL;
|
||||
uint32_t n = 0;
|
||||
dev->real.vkEnumerateDeviceExtensionProperties(dev->physical, NULL, &n, NULL);
|
||||
VkExtensionProperties *e = calloc(n ? n : 1, sizeof(*e));
|
||||
dev->real.vkEnumerateDeviceExtensionProperties(dev->physical, NULL, &n, e);
|
||||
int ok = 0;
|
||||
for (uint32_t i = 0; i < n; i++) ok |= !strcmp(e[i].extensionName, "VK_KHR_push_descriptor");
|
||||
free(e);
|
||||
return ok && dev->real.vkCmdPushDescriptorSet != NULL;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ images */
|
||||
|
||||
void vkb_emu_image_create_info(vkb_emu_device *e, VkImageCreateInfo *ci)
|
||||
{
|
||||
if (!(e->flags & VKB_EMU_BCN) || !vkb_is_bc(ci->format)) return;
|
||||
/* The image keeps the meaning of the app's format (sRGB, SNORM) so blits and copies convert as
|
||||
* they would; the decoder writes it through a view in the storage format (EXTENDED_USAGE lets
|
||||
* the image carry STORAGE although sRGB/SNORM formats cannot be stored to). */
|
||||
static __thread VkFormat list[2];
|
||||
VkFormat view = vkb_bc_view_format(ci->format), st = vkb_bc_storage_format(ci->format);
|
||||
list[0] = view;
|
||||
list[1] = st;
|
||||
ci->format = view;
|
||||
ci->flags &= ~(VkImageCreateFlags)VK_IMAGE_CREATE_BLOCK_TEXEL_VIEW_COMPATIBLE_BIT;
|
||||
ci->flags |= VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT | VK_IMAGE_CREATE_EXTENDED_USAGE_BIT;
|
||||
ci->usage |= VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT;
|
||||
for (VkBaseOutStructure *b = (VkBaseOutStructure *)ci->pNext; b; b = b->pNext) {
|
||||
if (b->sType == VK_STRUCTURE_TYPE_IMAGE_FORMAT_LIST_CREATE_INFO) {
|
||||
VkImageFormatListCreateInfo *fl = (VkImageFormatListCreateInfo *)b;
|
||||
fl->viewFormatCount = view == st ? 1 : 2;
|
||||
fl->pViewFormats = list;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void vkb_emu_image_release(vkb_emu_device *e, vkb_emu_image *img)
|
||||
{
|
||||
bcn_image *bi = img->emu;
|
||||
if (!bi) return;
|
||||
for (int i = 0; i < 16; i++)
|
||||
if (bi->views[i]) e->dev->real.vkDestroyImageView(e->dev->device, bi->views[i], NULL);
|
||||
free(bi);
|
||||
img->emu = NULL;
|
||||
}
|
||||
|
||||
VkFormat vkb_emu_bcn_view_format(vkb_emu_device *e, VkImage image, VkFormat requested)
|
||||
{
|
||||
if (!(e->flags & VKB_EMU_BCN)) return requested;
|
||||
if (vkb_is_bc(requested)) return vkb_bc_view_format(requested);
|
||||
vkb_emu_image *r = vkb_emu_find_image(e, image);
|
||||
if (r && vkb_is_bc(r->client_format)) {
|
||||
VKB_ONCE(VKB_LOG_WARN, "BC emulation: an uncompressed view (format %d) of a BC image shows decoded texels (logged once)", requested);
|
||||
return vkb_bc_view_format(r->client_format);
|
||||
}
|
||||
return requested;
|
||||
}
|
||||
|
||||
static VKAPI_ATTR VkResult VKAPI_CALL emu_CreateImageView(VkDevice device, const VkImageViewCreateInfo *ci,
|
||||
const VkAllocationCallbacks *pAllocator, VkImageView *pView)
|
||||
{
|
||||
VkImageViewCreateInfo *v = (VkImageViewCreateInfo *)ci;
|
||||
v->format = vkb_emu_bcn_view_format(vkb_emu_cur(), ci->image, ci->format);
|
||||
return vkb_emu_real()->vkCreateImageView(device, v, pAllocator, pView);
|
||||
}
|
||||
|
||||
void vkb_emu_bcn_buffer_usage(vkb_emu_device *e, VkBufferCreateInfo *ci)
|
||||
{
|
||||
/* The decoder reads uploads as a storage buffer. */
|
||||
if ((e->flags & VKB_EMU_BCN) && (ci->usage & VK_BUFFER_USAGE_TRANSFER_SRC_BIT)) ci->usage |= VK_BUFFER_USAGE_STORAGE_BUFFER_BIT;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ decoder */
|
||||
|
||||
static VkPipeline pipeline(vkb_emu_device *e, int fam)
|
||||
{
|
||||
bcn_state *s = e->bcn;
|
||||
if (s->pipes[fam]) return s->pipes[fam];
|
||||
pthread_mutex_lock(&s->lock);
|
||||
if (!s->pipes[fam]) {
|
||||
static const uint32_t *const code[FAM_COUNT] = {spv_bc1, spv_bc2, spv_bc3, spv_bc4, spv_bc5, spv_bc6h, spv_bc7};
|
||||
static const size_t size[FAM_COUNT] = {sizeof(spv_bc1), sizeof(spv_bc2), sizeof(spv_bc3), sizeof(spv_bc4),
|
||||
sizeof(spv_bc5), sizeof(spv_bc6h), sizeof(spv_bc7)};
|
||||
const vkb_dispatch *r = &e->dev->real;
|
||||
VkDevice d = e->dev->device;
|
||||
VkShaderModuleCreateInfo mci = {VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO, NULL, 0, size[fam], code[fam]};
|
||||
VkShaderModule m;
|
||||
if (r->vkCreateShaderModule(d, &mci, NULL, &m) == VK_SUCCESS) {
|
||||
VkComputePipelineCreateInfo pci = {VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO};
|
||||
pci.stage = (VkPipelineShaderStageCreateInfo){VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, NULL, 0,
|
||||
VK_SHADER_STAGE_COMPUTE_BIT, m, "main", NULL};
|
||||
pci.layout = s->layout;
|
||||
if (r->vkCreateComputePipelines(d, VK_NULL_HANDLE, 1, &pci, NULL, &s->pipes[fam]) != VK_SUCCESS) {
|
||||
VKB_ERR("BC emulation: decoder pipeline %d failed to build", fam);
|
||||
s->pipes[fam] = VK_NULL_HANDLE;
|
||||
}
|
||||
r->vkDestroyShaderModule(d, m, NULL);
|
||||
}
|
||||
}
|
||||
pthread_mutex_unlock(&s->lock);
|
||||
return s->pipes[fam];
|
||||
}
|
||||
|
||||
static VkImageView storage_view(vkb_emu_device *e, vkb_emu_image *img, uint32_t mip)
|
||||
{
|
||||
if (mip >= 16) return VK_NULL_HANDLE;
|
||||
pthread_mutex_lock(&e->lock);
|
||||
if (!img->emu) img->emu = calloc(1, sizeof(bcn_image));
|
||||
bcn_image *bi = img->emu;
|
||||
VkImageView v = bi->views[mip];
|
||||
pthread_mutex_unlock(&e->lock);
|
||||
if (v) return v;
|
||||
VkImageViewUsageCreateInfo usage = {VK_STRUCTURE_TYPE_IMAGE_VIEW_USAGE_CREATE_INFO, NULL, VK_IMAGE_USAGE_STORAGE_BIT};
|
||||
VkImageViewCreateInfo ci = {VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO, &usage, 0, img->image, VK_IMAGE_VIEW_TYPE_2D_ARRAY,
|
||||
vkb_bc_storage_format(img->client_format),
|
||||
{0}, {VK_IMAGE_ASPECT_COLOR_BIT, mip, 1, 0, img->layers}};
|
||||
if (e->dev->real.vkCreateImageView(e->dev->device, &ci, NULL, &v) != VK_SUCCESS) return VK_NULL_HANDLE;
|
||||
pthread_mutex_lock(&e->lock);
|
||||
if (bi->views[mip]) {
|
||||
e->dev->real.vkDestroyImageView(e->dev->device, v, NULL);
|
||||
v = bi->views[mip];
|
||||
} else {
|
||||
bi->views[mip] = v;
|
||||
}
|
||||
pthread_mutex_unlock(&e->lock);
|
||||
return v;
|
||||
}
|
||||
|
||||
typedef struct region {
|
||||
VkDeviceSize offset;
|
||||
uint32_t row_length, image_height;
|
||||
VkImageSubresourceLayers sub;
|
||||
VkOffset3D ioff;
|
||||
VkExtent3D iext;
|
||||
} region;
|
||||
|
||||
static void decode(vkb_emu_device *e, VkCommandBuffer cb, VkBuffer src, vkb_emu_image *img, VkImageLayout layout,
|
||||
uint32_t n, const region *regs)
|
||||
{
|
||||
bcn_state *s = e->bcn;
|
||||
const vkb_dispatch *r = &e->dev->real;
|
||||
if (img->type != VK_IMAGE_TYPE_2D) {
|
||||
VKB_ONCE(VKB_LOG_WARN, "BC emulation: uploads to 1D/3D BC images are not decoded (logged once)");
|
||||
return;
|
||||
}
|
||||
VkPipeline pipe = pipeline(e, family(img->client_format));
|
||||
if (!pipe) return;
|
||||
for (uint32_t i = 0; i < n; i++) {
|
||||
const region *g = ®s[i];
|
||||
VkImageView view = storage_view(e, img, g->sub.mipLevel);
|
||||
if (!view) continue;
|
||||
VkImageSubresourceRange range = {VK_IMAGE_ASPECT_COLOR_BIT, g->sub.mipLevel, 1, g->sub.baseArrayLayer, g->sub.layerCount};
|
||||
VkMemoryBarrier mb = {VK_STRUCTURE_TYPE_MEMORY_BARRIER, NULL, VK_ACCESS_MEMORY_WRITE_BIT,
|
||||
VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT};
|
||||
VkImageMemoryBarrier ib = {VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, NULL, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_SHADER_WRITE_BIT,
|
||||
layout, VK_IMAGE_LAYOUT_GENERAL, VK_QUEUE_FAMILY_IGNORED, VK_QUEUE_FAMILY_IGNORED, img->image, range};
|
||||
r->vkCmdPipelineBarrier(cb, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT | VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,
|
||||
0, 1, &mb, 0, NULL, 1, &ib);
|
||||
VkDeviceSize aligned = g->offset & ~(s->ssbo_align - 1);
|
||||
VkDescriptorBufferInfo bi = {src, aligned, VK_WHOLE_SIZE};
|
||||
VkDescriptorImageInfo ii = {VK_NULL_HANDLE, view, VK_IMAGE_LAYOUT_GENERAL};
|
||||
VkWriteDescriptorSet w[2] = {
|
||||
{VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, NULL, VK_NULL_HANDLE, 0, 0, 1, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, NULL, &bi, NULL},
|
||||
{VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, NULL, VK_NULL_HANDLE, 1, 0, 1, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, &ii, NULL, NULL}};
|
||||
r->vkCmdBindPipeline(cb, VK_PIPELINE_BIND_POINT_COMPUTE, pipe);
|
||||
if (s->push) {
|
||||
r->vkCmdPushDescriptorSet(cb, VK_PIPELINE_BIND_POINT_COMPUTE, s->layout, 0, 2, w);
|
||||
} else {
|
||||
VkDescriptorSet set = vkb_emu_cb_scratch_set(e, cb, s->dsl);
|
||||
if (!set) {
|
||||
VKB_ONCE(VKB_LOG_ERROR, "BC emulation: no descriptor set for the decoder (logged once)");
|
||||
continue;
|
||||
}
|
||||
w[0].dstSet = w[1].dstSet = set;
|
||||
r->vkUpdateDescriptorSets(e->dev->device, 2, w, 0, NULL);
|
||||
r->vkCmdBindDescriptorSets(cb, VK_PIPELINE_BIND_POINT_COMPUTE, s->layout, 0, 1, &set, 0, NULL);
|
||||
}
|
||||
uint32_t w_tex = g->row_length ? g->row_length : g->iext.width;
|
||||
uint32_t h_tex = g->image_height ? g->image_height : g->iext.height;
|
||||
pc_t pc;
|
||||
pc.src_word = (uint32_t)((g->offset - aligned) / 4);
|
||||
pc.row_blocks = (w_tex + 3) / 4;
|
||||
pc.layer_blocks = pc.row_blocks * ((h_tex + 3) / 4);
|
||||
pc.flags = family_flags(img->client_format) | (g->sub.baseArrayLayer << 8);
|
||||
pc.dst_off[0] = g->ioff.x;
|
||||
pc.dst_off[1] = g->ioff.y;
|
||||
pc.extent[0] = g->iext.width;
|
||||
pc.extent[1] = g->iext.height;
|
||||
r->vkCmdPushConstants(cb, s->layout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(pc), &pc);
|
||||
uint32_t bw = (g->iext.width + 3) / 4, bh = (g->iext.height + 3) / 4;
|
||||
r->vkCmdDispatch(cb, (bw + 7) / 8, (bh + 7) / 8, g->sub.layerCount);
|
||||
ib.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT;
|
||||
ib.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_TRANSFER_READ_BIT;
|
||||
ib.oldLayout = VK_IMAGE_LAYOUT_GENERAL;
|
||||
ib.newLayout = layout;
|
||||
r->vkCmdPipelineBarrier(cb, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, NULL, 0, NULL, 1, &ib);
|
||||
}
|
||||
vkb_emu_restore_compute(e, cb);
|
||||
}
|
||||
|
||||
static vkb_emu_image *bc_image(vkb_emu_device *e, VkImage img)
|
||||
{
|
||||
if (!(e->flags & VKB_EMU_BCN)) return NULL;
|
||||
vkb_emu_image *r = vkb_emu_find_image(e, img);
|
||||
return r && vkb_is_bc(r->client_format) ? r : NULL;
|
||||
}
|
||||
|
||||
int vkb_emu_copy_buffer_to_image(vkb_emu_device *e, VkCommandBuffer cb, VkBuffer src, VkImage dst, VkImageLayout dl, uint32_t n,
|
||||
const VkBufferImageCopy *regions)
|
||||
{
|
||||
vkb_emu_image *img = bc_image(e, dst);
|
||||
if (!img) return 0;
|
||||
region *g = malloc((n ? n : 1) * sizeof(*g));
|
||||
for (uint32_t i = 0; i < n; i++)
|
||||
g[i] = (region){regions[i].bufferOffset, regions[i].bufferRowLength, regions[i].bufferImageHeight, regions[i].imageSubresource,
|
||||
regions[i].imageOffset, regions[i].imageExtent};
|
||||
decode(e, cb, src, img, dl, n, g);
|
||||
free(g);
|
||||
return 1;
|
||||
}
|
||||
|
||||
int vkb_emu_copy_buffer_to_image2(vkb_emu_device *e, VkCommandBuffer cb, const VkCopyBufferToImageInfo2 *info)
|
||||
{
|
||||
vkb_emu_image *img = bc_image(e, info->dstImage);
|
||||
if (!img) return 0;
|
||||
region *g = malloc((info->regionCount ? info->regionCount : 1) * sizeof(*g));
|
||||
for (uint32_t i = 0; i < info->regionCount; i++) {
|
||||
const VkBufferImageCopy2 *r = &info->pRegions[i];
|
||||
g[i] = (region){r->bufferOffset, r->bufferRowLength, r->bufferImageHeight, r->imageSubresource, r->imageOffset, r->imageExtent};
|
||||
}
|
||||
decode(e, cb, info->srcBuffer, img, info->dstImageLayout, info->regionCount, g);
|
||||
free(g);
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* Copies between BC images copy decoded texels; a region may run past a small mip's edge (whole
|
||||
* blocks), which the decoded image does not have. */
|
||||
static void clamp_region(const vkb_emu_image *s, const vkb_emu_image *d, const VkImageSubresourceLayers *ss,
|
||||
const VkImageSubresourceLayers *ds, const VkOffset3D *so, const VkOffset3D *dof, VkExtent3D *ext)
|
||||
{
|
||||
uint32_t sw = s->extent.width >> ss->mipLevel, sh = s->extent.height >> ss->mipLevel;
|
||||
uint32_t dw = d->extent.width >> ds->mipLevel, dh = d->extent.height >> ds->mipLevel;
|
||||
if (!sw) sw = 1;
|
||||
if (!sh) sh = 1;
|
||||
if (!dw) dw = 1;
|
||||
if (!dh) dh = 1;
|
||||
if ((uint32_t)so->x + ext->width > sw) ext->width = sw > (uint32_t)so->x ? sw - (uint32_t)so->x : 0;
|
||||
if ((uint32_t)so->y + ext->height > sh) ext->height = sh > (uint32_t)so->y ? sh - (uint32_t)so->y : 0;
|
||||
if ((uint32_t)dof->x + ext->width > dw) ext->width = dw > (uint32_t)dof->x ? dw - (uint32_t)dof->x : 0;
|
||||
if ((uint32_t)dof->y + ext->height > dh) ext->height = dh > (uint32_t)dof->y ? dh - (uint32_t)dof->y : 0;
|
||||
}
|
||||
|
||||
int vkb_emu_copy_image(vkb_emu_device *e, VkCommandBuffer cb, VkImage src, VkImageLayout sl, VkImage dst, VkImageLayout dl, uint32_t n,
|
||||
const VkImageCopy *regions)
|
||||
{
|
||||
vkb_emu_image *s = bc_image(e, src), *d = bc_image(e, dst);
|
||||
if (!s && !d) return 0;
|
||||
if (!s || !d || vkb_bc_storage_format(s->client_format) != vkb_bc_storage_format(d->client_format)) {
|
||||
VKB_ONCE(VKB_LOG_WARN, "BC emulation: a copy between a BC image and another format is skipped (logged once)");
|
||||
return 1;
|
||||
}
|
||||
VkImageCopy *c = (VkImageCopy *)regions;
|
||||
for (uint32_t i = 0; i < n; i++)
|
||||
clamp_region(s, d, &c[i].srcSubresource, &c[i].dstSubresource, &c[i].srcOffset, &c[i].dstOffset, &c[i].extent);
|
||||
e->dev->real.vkCmdCopyImage(cb, src, sl, dst, dl, n, regions);
|
||||
return 1;
|
||||
}
|
||||
|
||||
int vkb_emu_copy_image2(vkb_emu_device *e, VkCommandBuffer cb, const VkCopyImageInfo2 *info)
|
||||
{
|
||||
vkb_emu_image *s = bc_image(e, info->srcImage), *d = bc_image(e, info->dstImage);
|
||||
if (!s && !d) return 0;
|
||||
if (!s || !d || vkb_bc_storage_format(s->client_format) != vkb_bc_storage_format(d->client_format)) {
|
||||
VKB_ONCE(VKB_LOG_WARN, "BC emulation: a copy between a BC image and another format is skipped (logged once)");
|
||||
return 1;
|
||||
}
|
||||
VkImageCopy2 *c = (VkImageCopy2 *)info->pRegions;
|
||||
for (uint32_t i = 0; i < info->regionCount; i++)
|
||||
clamp_region(s, d, &c[i].srcSubresource, &c[i].dstSubresource, &c[i].srcOffset, &c[i].dstOffset, &c[i].extent);
|
||||
e->dev->real.vkCmdCopyImage2(cb, info);
|
||||
return 1;
|
||||
}
|
||||
|
||||
int vkb_emu_bcn_blocks_readback(vkb_emu_device *e, VkImage img)
|
||||
{
|
||||
if (!bc_image(e, img)) return 0;
|
||||
VKB_ONCE(VKB_LOG_WARN, "BC emulation: reading a BC image back to a buffer is not supported (logged once)");
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ install */
|
||||
|
||||
void vkb_emu_bcn_install(vkb_srv_table *dev)
|
||||
{
|
||||
vkb_emu_device *e = dev->emu;
|
||||
if (!(e->flags & VKB_EMU_BCN)) return;
|
||||
bcn_state *s = calloc(1, sizeof(*s));
|
||||
pthread_mutex_init(&s->lock, NULL);
|
||||
VkPhysicalDeviceProperties p;
|
||||
dev->real.vkGetPhysicalDeviceProperties(dev->physical, &p);
|
||||
s->ssbo_align = p.limits.minStorageBufferOffsetAlignment ? p.limits.minStorageBufferOffsetAlignment : 4;
|
||||
VkDescriptorSetLayoutBinding b[2] = {{0, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1, VK_SHADER_STAGE_COMPUTE_BIT, NULL},
|
||||
{1, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1, VK_SHADER_STAGE_COMPUTE_BIT, NULL}};
|
||||
s->push = has_push(dev);
|
||||
VKB_INFO("BC emulation: decoder binds with %s", s->push ? "push descriptors" : "descriptor sets (no VK_KHR_push_descriptor)");
|
||||
VkDescriptorSetLayoutCreateInfo dci = {VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO, NULL,
|
||||
s->push ? VK_DESCRIPTOR_SET_LAYOUT_CREATE_PUSH_DESCRIPTOR_BIT : 0, 2, b};
|
||||
VkPushConstantRange pr = {VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(pc_t)};
|
||||
if (dev->real.vkCreateDescriptorSetLayout(dev->device, &dci, NULL, &s->dsl) != VK_SUCCESS) {
|
||||
VKB_ERR("BC emulation: cannot create the decoder's descriptor layout");
|
||||
free(s);
|
||||
e->flags &= ~VKB_EMU_BCN;
|
||||
return;
|
||||
}
|
||||
VkPipelineLayoutCreateInfo plci = {VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO, NULL, 0, 1, &s->dsl, 1, &pr};
|
||||
dev->real.vkCreatePipelineLayout(dev->device, &plci, NULL, &s->layout);
|
||||
e->bcn = s;
|
||||
dev->dt.vkCreateImageView = emu_CreateImageView;
|
||||
}
|
||||
|
||||
void vkb_emu_bcn_uninstall(vkb_srv_table *dev)
|
||||
{
|
||||
bcn_state *s = dev->emu->bcn;
|
||||
if (!s) return;
|
||||
for (int i = 0; i < FAM_COUNT; i++)
|
||||
if (s->pipes[i]) dev->real.vkDestroyPipeline(dev->device, s->pipes[i], NULL);
|
||||
dev->real.vkDestroyPipelineLayout(dev->device, s->layout, NULL);
|
||||
dev->real.vkDestroyDescriptorSetLayout(dev->device, s->dsl, NULL);
|
||||
pthread_mutex_destroy(&s->lock);
|
||||
free(s);
|
||||
dev->emu->bcn = NULL;
|
||||
}
|
||||
@@ -0,0 +1,290 @@
|
||||
/* SPDX-License-Identifier: GPL-3.0-or-later
|
||||
*
|
||||
* What an app has bound in a command buffer, for emulations that record commands of their own
|
||||
* into it (the BCn decoder's dispatches) and must leave the app's state as it was: the compute
|
||||
* pipeline, compute descriptor sets, push constants and push descriptors. Bind calls are kept as
|
||||
* they were made (a later call that covers an earlier one replaces it) and replayed in order.
|
||||
*/
|
||||
#define _GNU_SOURCE
|
||||
#include "server_emu.h"
|
||||
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
typedef struct bind_sets {
|
||||
VkPipelineLayout layout;
|
||||
uint32_t first, count, ndyn;
|
||||
VkDescriptorSet sets[32];
|
||||
uint32_t dyn[64];
|
||||
} bind_sets;
|
||||
|
||||
typedef struct push_consts {
|
||||
VkPipelineLayout layout;
|
||||
VkShaderStageFlags stages;
|
||||
uint32_t offset, size;
|
||||
uint8_t data[256];
|
||||
} push_consts;
|
||||
|
||||
typedef struct push_tmpl {
|
||||
VkDescriptorUpdateTemplate tmpl;
|
||||
VkPipelineLayout layout;
|
||||
uint32_t set;
|
||||
void *data;
|
||||
size_t size;
|
||||
} push_tmpl;
|
||||
|
||||
typedef struct cb_state {
|
||||
VkCommandBuffer cb;
|
||||
VkPipeline compute_pipeline;
|
||||
bind_sets *sets;
|
||||
uint32_t nsets, capsets;
|
||||
push_consts *pcs;
|
||||
uint32_t npcs, cappcs;
|
||||
push_tmpl *pts;
|
||||
uint32_t npts, cappts;
|
||||
void *gfx; /* graphics-side state (divisor emulation) */
|
||||
/* Descriptor sets emulations record with (no push descriptors), alive until the next begin. */
|
||||
VkDescriptorPool *scratch;
|
||||
uint32_t nscratch, cur_scratch, used_scratch;
|
||||
struct cb_state *next;
|
||||
} cb_state;
|
||||
|
||||
#define CB_BUCKETS 512
|
||||
#define SCRATCH_SETS 64
|
||||
typedef struct cmdstate {
|
||||
pthread_mutex_t lock;
|
||||
cb_state *b[CB_BUCKETS];
|
||||
} cmdstate;
|
||||
|
||||
/* Packed size of the template data being pushed (set by the raw push handler, server_misc.c). */
|
||||
__thread size_t vkb_emu_push_size;
|
||||
|
||||
static cmdstate *g_states_for(vkb_emu_device *e) { return (cmdstate *)e->cmdstate; }
|
||||
|
||||
static unsigned ch(VkCommandBuffer cb)
|
||||
{
|
||||
uint64_t k = (uint64_t)(uintptr_t)cb;
|
||||
k ^= k >> 30;
|
||||
k *= 0xbf58476d1ce4e5b9ull;
|
||||
return (unsigned)(k >> 55) & (CB_BUCKETS - 1);
|
||||
}
|
||||
|
||||
static cb_state *get(vkb_emu_device *e, VkCommandBuffer cb)
|
||||
{
|
||||
cmdstate *s = g_states_for(e);
|
||||
pthread_mutex_lock(&s->lock);
|
||||
cb_state *c = s->b[ch(cb)];
|
||||
while (c && c->cb != cb) c = c->next;
|
||||
if (!c) {
|
||||
c = calloc(1, sizeof(*c));
|
||||
c->cb = cb;
|
||||
c->next = s->b[ch(cb)];
|
||||
s->b[ch(cb)] = c;
|
||||
}
|
||||
pthread_mutex_unlock(&s->lock);
|
||||
return c;
|
||||
}
|
||||
|
||||
/* A descriptor set of layout `dsl` (storage buffers and images only) for a command the emulation
|
||||
* records into cb; it lives until cb is begun again, when the app has seen the work finish. */
|
||||
VkDescriptorSet vkb_emu_cb_scratch_set(vkb_emu_device *e, VkCommandBuffer cb, VkDescriptorSetLayout dsl)
|
||||
{
|
||||
cb_state *c = get(e, cb);
|
||||
const vkb_dispatch *r = &e->dev->real;
|
||||
for (;;) {
|
||||
if (c->cur_scratch >= c->nscratch) {
|
||||
VkDescriptorPoolSize sizes[2] = {{VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, SCRATCH_SETS * 2},
|
||||
{VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, SCRATCH_SETS * 2}};
|
||||
VkDescriptorPoolCreateInfo pci = {VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO, NULL, 0, SCRATCH_SETS, 2, sizes};
|
||||
VkDescriptorPool pool;
|
||||
VkDescriptorPool *np = realloc(c->scratch, (c->nscratch + 1) * sizeof(*np));
|
||||
if (!np) return VK_NULL_HANDLE;
|
||||
c->scratch = np;
|
||||
if (r->vkCreateDescriptorPool(e->dev->device, &pci, NULL, &pool) != VK_SUCCESS) return VK_NULL_HANDLE;
|
||||
c->scratch[c->nscratch++] = pool;
|
||||
}
|
||||
if (c->used_scratch < SCRATCH_SETS) {
|
||||
VkDescriptorSetAllocateInfo ai = {VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO, NULL, c->scratch[c->cur_scratch], 1, &dsl};
|
||||
VkDescriptorSet set;
|
||||
if (r->vkAllocateDescriptorSets(e->dev->device, &ai, &set) == VK_SUCCESS) {
|
||||
c->used_scratch++;
|
||||
return set;
|
||||
}
|
||||
}
|
||||
c->cur_scratch++;
|
||||
c->used_scratch = 0;
|
||||
}
|
||||
}
|
||||
|
||||
void *vkb_emu_cb_gfx(vkb_emu_device *e, VkCommandBuffer cb, size_t size)
|
||||
{
|
||||
cb_state *c = get(e, cb);
|
||||
if (!c->gfx) c->gfx = calloc(1, size);
|
||||
return c->gfx;
|
||||
}
|
||||
|
||||
static void reset(vkb_emu_device *e, cb_state *c)
|
||||
{
|
||||
for (uint32_t i = 0; i < c->nscratch && i <= c->cur_scratch; i++)
|
||||
e->dev->real.vkResetDescriptorPool(e->dev->device, c->scratch[i], 0);
|
||||
c->cur_scratch = 0;
|
||||
c->used_scratch = 0;
|
||||
c->compute_pipeline = VK_NULL_HANDLE;
|
||||
c->nsets = 0;
|
||||
c->npcs = 0;
|
||||
for (uint32_t i = 0; i < c->npts; i++) free(c->pts[i].data);
|
||||
c->npts = 0;
|
||||
vkb_emu_gfx_reset(c->gfx);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ wrappers */
|
||||
|
||||
static VKAPI_ATTR VkResult VKAPI_CALL emu_BeginCommandBuffer(VkCommandBuffer cb, const VkCommandBufferBeginInfo *info)
|
||||
{
|
||||
reset(vkb_emu_cur(), get(vkb_emu_cur(), cb));
|
||||
return vkb_emu_real()->vkBeginCommandBuffer(cb, info);
|
||||
}
|
||||
|
||||
static VKAPI_ATTR void VKAPI_CALL emu_CmdBindPipeline(VkCommandBuffer cb, VkPipelineBindPoint bp, VkPipeline p)
|
||||
{
|
||||
vkb_emu_device *e = vkb_emu_cur();
|
||||
if (bp == VK_PIPELINE_BIND_POINT_COMPUTE) get(e, cb)->compute_pipeline = p;
|
||||
if (bp == VK_PIPELINE_BIND_POINT_GRAPHICS) vkb_emu_gfx_bind_pipeline(e, cb, p);
|
||||
vkb_emu_real()->vkCmdBindPipeline(cb, bp, p);
|
||||
}
|
||||
|
||||
static VKAPI_ATTR void VKAPI_CALL emu_CmdBindDescriptorSets(VkCommandBuffer cb, VkPipelineBindPoint bp, VkPipelineLayout layout,
|
||||
uint32_t first, uint32_t count, const VkDescriptorSet *sets,
|
||||
uint32_t ndyn, const uint32_t *dyn)
|
||||
{
|
||||
if (bp == VK_PIPELINE_BIND_POINT_COMPUTE && count <= 32 && ndyn <= 64) {
|
||||
cb_state *c = get(vkb_emu_cur(), cb);
|
||||
/* Drop earlier calls this one covers completely. */
|
||||
uint32_t k = 0;
|
||||
for (uint32_t i = 0; i < c->nsets; i++) {
|
||||
bind_sets *b = &c->sets[i];
|
||||
if (b->first >= first && b->first + b->count <= first + count) continue;
|
||||
c->sets[k++] = *b;
|
||||
}
|
||||
c->nsets = k;
|
||||
if (c->nsets == c->capsets) {
|
||||
c->capsets = c->capsets ? c->capsets * 2 : 8;
|
||||
c->sets = realloc(c->sets, c->capsets * sizeof(*c->sets));
|
||||
}
|
||||
bind_sets *b = &c->sets[c->nsets++];
|
||||
b->layout = layout;
|
||||
b->first = first;
|
||||
b->count = count;
|
||||
b->ndyn = ndyn;
|
||||
memcpy(b->sets, sets, count * sizeof(*sets));
|
||||
if (ndyn) memcpy(b->dyn, dyn, ndyn * sizeof(*dyn));
|
||||
}
|
||||
vkb_emu_real()->vkCmdBindDescriptorSets(cb, bp, layout, first, count, sets, ndyn, dyn);
|
||||
}
|
||||
|
||||
static VKAPI_ATTR void VKAPI_CALL emu_CmdPushConstants(VkCommandBuffer cb, VkPipelineLayout layout, VkShaderStageFlags stages,
|
||||
uint32_t offset, uint32_t size, const void *data)
|
||||
{
|
||||
if ((stages & VK_SHADER_STAGE_COMPUTE_BIT) && offset + size <= 256) {
|
||||
cb_state *c = get(vkb_emu_cur(), cb);
|
||||
uint32_t k = 0;
|
||||
for (uint32_t i = 0; i < c->npcs; i++) {
|
||||
push_consts *p = &c->pcs[i];
|
||||
if (p->offset >= offset && p->offset + p->size <= offset + size && p->stages == stages) continue;
|
||||
c->pcs[k++] = *p;
|
||||
}
|
||||
c->npcs = k;
|
||||
if (c->npcs == c->cappcs) {
|
||||
c->cappcs = c->cappcs ? c->cappcs * 2 : 8;
|
||||
c->pcs = realloc(c->pcs, c->cappcs * sizeof(*c->pcs));
|
||||
}
|
||||
push_consts *p = &c->pcs[c->npcs++];
|
||||
p->layout = layout;
|
||||
p->stages = stages;
|
||||
p->offset = offset;
|
||||
p->size = size;
|
||||
memcpy(p->data + offset, data, size);
|
||||
}
|
||||
vkb_emu_real()->vkCmdPushConstants(cb, layout, stages, offset, size, data);
|
||||
}
|
||||
|
||||
static VKAPI_ATTR void VKAPI_CALL emu_CmdPushDescriptorSetWithTemplate(VkCommandBuffer cb, VkDescriptorUpdateTemplate tmpl,
|
||||
VkPipelineLayout layout, uint32_t set, const void *data)
|
||||
{
|
||||
/* Only the template's bind point decides; recording it for both costs nothing when replayed
|
||||
* into the same bind point it was made for. Sizes are unknown here: the bridge's raw template
|
||||
* path hands over the packed size (vkb_emu_push_size). */
|
||||
vkb_emu_device *e = vkb_emu_cur();
|
||||
cb_state *c = get(e, cb);
|
||||
size_t size = vkb_emu_push_size;
|
||||
if (size && size < (1u << 20)) {
|
||||
if (c->npts == c->cappts) {
|
||||
c->cappts = c->cappts ? c->cappts * 2 : 4;
|
||||
c->pts = realloc(c->pts, c->cappts * sizeof(*c->pts));
|
||||
}
|
||||
push_tmpl *p = &c->pts[c->npts++];
|
||||
p->tmpl = tmpl;
|
||||
p->layout = layout;
|
||||
p->set = set;
|
||||
p->size = size;
|
||||
p->data = malloc(size);
|
||||
memcpy(p->data, data, size);
|
||||
}
|
||||
vkb_emu_real()->vkCmdPushDescriptorSetWithTemplate(cb, tmpl, layout, set, data);
|
||||
}
|
||||
|
||||
/* Puts back what the app had bound for compute after an emulation recorded its own dispatch. */
|
||||
void vkb_emu_restore_compute(vkb_emu_device *e, VkCommandBuffer cb)
|
||||
{
|
||||
cb_state *c = get(e, cb);
|
||||
const vkb_dispatch *r = vkb_emu_real();
|
||||
if (c->compute_pipeline) r->vkCmdBindPipeline(cb, VK_PIPELINE_BIND_POINT_COMPUTE, c->compute_pipeline);
|
||||
for (uint32_t i = 0; i < c->nsets; i++) {
|
||||
bind_sets *b = &c->sets[i];
|
||||
r->vkCmdBindDescriptorSets(cb, VK_PIPELINE_BIND_POINT_COMPUTE, b->layout, b->first, b->count, b->sets, b->ndyn, b->dyn);
|
||||
}
|
||||
for (uint32_t i = 0; i < c->npts; i++) {
|
||||
push_tmpl *p = &c->pts[i];
|
||||
r->vkCmdPushDescriptorSetWithTemplate(cb, p->tmpl, p->layout, p->set, p->data);
|
||||
}
|
||||
for (uint32_t i = 0; i < c->npcs; i++) {
|
||||
push_consts *p = &c->pcs[i];
|
||||
r->vkCmdPushConstants(cb, p->layout, p->stages, p->offset, p->size, p->data + p->offset);
|
||||
}
|
||||
}
|
||||
|
||||
void vkb_emu_cmdstate_install(vkb_srv_table *dev)
|
||||
{
|
||||
vkb_emu_device *e = dev->emu;
|
||||
cmdstate *s = calloc(1, sizeof(*s));
|
||||
pthread_mutex_init(&s->lock, NULL);
|
||||
e->cmdstate = s;
|
||||
dev->dt.vkBeginCommandBuffer = emu_BeginCommandBuffer;
|
||||
dev->dt.vkCmdBindPipeline = emu_CmdBindPipeline;
|
||||
dev->dt.vkCmdBindDescriptorSets = emu_CmdBindDescriptorSets;
|
||||
dev->dt.vkCmdPushConstants = emu_CmdPushConstants;
|
||||
if (dev->real.vkCmdPushDescriptorSetWithTemplate) dev->dt.vkCmdPushDescriptorSetWithTemplate = emu_CmdPushDescriptorSetWithTemplate;
|
||||
}
|
||||
|
||||
void vkb_emu_cmdstate_uninstall(vkb_srv_table *dev)
|
||||
{
|
||||
cmdstate *s = dev->emu->cmdstate;
|
||||
if (!s) return;
|
||||
for (int i = 0; i < CB_BUCKETS; i++) {
|
||||
while (s->b[i]) {
|
||||
cb_state *c = s->b[i];
|
||||
s->b[i] = c->next;
|
||||
reset(dev->emu, c);
|
||||
for (uint32_t j = 0; j < c->nscratch; j++) dev->real.vkDestroyDescriptorPool(dev->device, c->scratch[j], NULL);
|
||||
free(c->scratch);
|
||||
free(c->sets);
|
||||
free(c->pcs);
|
||||
free(c->pts);
|
||||
vkb_emu_gfx_free(c->gfx);
|
||||
free(c);
|
||||
}
|
||||
}
|
||||
pthread_mutex_destroy(&s->lock);
|
||||
free(s);
|
||||
dev->emu->cmdstate = NULL;
|
||||
}
|
||||
@@ -0,0 +1,454 @@
|
||||
/* SPDX-License-Identifier: GPL-3.0-or-later
|
||||
*
|
||||
* Vertex attribute divisor (VK_EXT/KHR_vertex_attribute_divisor) on a GPU without it.
|
||||
*
|
||||
* A binding with divisor d != 1 fetches element firstInstance + i / d for instance i (d = 0: always
|
||||
* firstInstance). Emulated by giving such bindings a stride of 0 - every instance reads the same
|
||||
* element - and rebinding the buffer at that element before each draw. With d > 1 the draw is
|
||||
* split into runs of instances that share elements; each run keeps its own firstInstance, so
|
||||
* gl_InstanceIndex and every ordinary instance-rate attribute stay exactly as they were.
|
||||
* Indirect draws cannot be split on the CPU: divisor-0 bindings use element 0 there, d > 1 is
|
||||
* approximated the same way (logged once).
|
||||
*/
|
||||
#define _GNU_SOURCE
|
||||
#include "server_emu.h"
|
||||
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#define MAX_BIND 32
|
||||
|
||||
typedef struct div_info {
|
||||
uint32_t mask; /* bindings emulated */
|
||||
uint32_t divisor[MAX_BIND];
|
||||
uint32_t stride[MAX_BIND]; /* the app's stride (baked pipelines) */
|
||||
int dynamic_stride; /* the pipeline takes strides at bind time */
|
||||
int dynamic_input; /* the pipeline takes vertex input at record time */
|
||||
int split; /* some divisor > 1: draws are split */
|
||||
VkPipeline zero_base; /* variant whose vertex shader reads BaseInstance as 0 */
|
||||
VkShaderModule zero_vs; /* its vertex shader, between creation steps */
|
||||
uint32_t vs_stage;
|
||||
} div_info;
|
||||
|
||||
typedef struct pipe_rec {
|
||||
VkPipeline p;
|
||||
div_info info;
|
||||
struct pipe_rec *next;
|
||||
} pipe_rec;
|
||||
|
||||
typedef struct gfx_state {
|
||||
VkPipeline pipeline; /* bound graphics pipeline */
|
||||
div_info pipe; /* the bound pipeline's */
|
||||
div_info dyn; /* from vkCmdSetVertexInputEXT */
|
||||
int use_dyn;
|
||||
VkBuffer buf[MAX_BIND];
|
||||
VkDeviceSize off[MAX_BIND], size[MAX_BIND], stride[MAX_BIND];
|
||||
uint32_t bound; /* slots the app bound */
|
||||
uint32_t tampered; /* slots we rebound */
|
||||
} gfx_state;
|
||||
|
||||
typedef struct div_state {
|
||||
pthread_mutex_t lock;
|
||||
pipe_rec *b[256];
|
||||
} div_state;
|
||||
|
||||
static div_state *dstate(vkb_emu_device *e) { return e->divisor; }
|
||||
|
||||
static unsigned ph(VkPipeline p)
|
||||
{
|
||||
uint64_t k = (uint64_t)p;
|
||||
k ^= k >> 33;
|
||||
k *= 0xff51afd7ed558ccdull;
|
||||
return (unsigned)(k >> 56);
|
||||
}
|
||||
|
||||
static const div_info *find_pipe(vkb_emu_device *e, VkPipeline p)
|
||||
{
|
||||
div_state *s = dstate(e);
|
||||
pthread_mutex_lock(&s->lock);
|
||||
pipe_rec *r = s->b[ph(p)];
|
||||
while (r && r->p != p) r = r->next;
|
||||
pthread_mutex_unlock(&s->lock);
|
||||
return r ? &r->info : NULL;
|
||||
}
|
||||
|
||||
static void store_pipe(vkb_emu_device *e, VkPipeline p, const div_info *info)
|
||||
{
|
||||
div_state *s = dstate(e);
|
||||
pipe_rec *r = calloc(1, sizeof(*r));
|
||||
r->p = p;
|
||||
r->info = *info;
|
||||
pthread_mutex_lock(&s->lock);
|
||||
r->next = s->b[ph(p)];
|
||||
s->b[ph(p)] = r;
|
||||
pthread_mutex_unlock(&s->lock);
|
||||
}
|
||||
|
||||
static void drop_pipe(vkb_emu_device *e, VkPipeline p)
|
||||
{
|
||||
div_state *s = dstate(e);
|
||||
pthread_mutex_lock(&s->lock);
|
||||
pipe_rec **pp = &s->b[ph(p)];
|
||||
while (*pp && (*pp)->p != p) pp = &(*pp)->next;
|
||||
pipe_rec *r = *pp;
|
||||
if (r) *pp = r->next;
|
||||
pthread_mutex_unlock(&s->lock);
|
||||
if (r && r->info.zero_base) e->dev->real.vkDestroyPipeline(e->dev->device, r->info.zero_base, NULL);
|
||||
free(r);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ pipelines */
|
||||
|
||||
static int has_dynamic(const VkGraphicsPipelineCreateInfo *ci, VkDynamicState d)
|
||||
{
|
||||
if (!ci->pDynamicState) return 0;
|
||||
for (uint32_t i = 0; i < ci->pDynamicState->dynamicStateCount; i++)
|
||||
if (ci->pDynamicState->pDynamicStates[i] == d) return 1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* Strips the divisor state of one create info; returns what the pipeline needs at draw time. */
|
||||
void vkb_emu_divisor_pipeline(vkb_emu_device *e, VkDevice device, VkGraphicsPipelineCreateInfo *ci, div_info *out)
|
||||
{
|
||||
memset(out, 0, sizeof(*out));
|
||||
if (!(e->flags & VKB_EMU_DIVISOR)) return;
|
||||
out->dynamic_stride = has_dynamic(ci, VK_DYNAMIC_STATE_VERTEX_INPUT_BINDING_STRIDE);
|
||||
out->dynamic_input = has_dynamic(ci, VK_DYNAMIC_STATE_VERTEX_INPUT_EXT);
|
||||
/* Pieces linked from libraries bring their own records. */
|
||||
for (const VkBaseInStructure *b = ci->pNext; b; b = b->pNext) {
|
||||
if (b->sType != VK_STRUCTURE_TYPE_PIPELINE_LIBRARY_CREATE_INFO_KHR) continue;
|
||||
const VkPipelineLibraryCreateInfoKHR *l = (const void *)b;
|
||||
for (uint32_t i = 0; i < l->libraryCount; i++) {
|
||||
const div_info *li = find_pipe(e, l->pLibraries[i]);
|
||||
if (!li || !li->mask) continue;
|
||||
for (uint32_t k = 0; k < MAX_BIND; k++)
|
||||
if (li->mask & (1u << k)) {
|
||||
out->mask |= 1u << k;
|
||||
out->divisor[k] = li->divisor[k];
|
||||
out->stride[k] = li->stride[k];
|
||||
if (li->divisor[k] > 1) out->split = 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
VkPipelineVertexInputStateCreateInfo *vi = (VkPipelineVertexInputStateCreateInfo *)ci->pVertexInputState;
|
||||
if (!vi || out->dynamic_input) return;
|
||||
VkPipelineVertexInputDivisorStateCreateInfo *d =
|
||||
vkb_emu_chain_take(vi, VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_DIVISOR_STATE_CREATE_INFO);
|
||||
if (!d) return;
|
||||
VkVertexInputBindingDescription *bd = (VkVertexInputBindingDescription *)vi->pVertexBindingDescriptions;
|
||||
for (uint32_t i = 0; i < d->vertexBindingDivisorCount; i++) {
|
||||
uint32_t b = d->pVertexBindingDivisors[i].binding, div = d->pVertexBindingDivisors[i].divisor;
|
||||
if (div == 1 || b >= MAX_BIND) continue;
|
||||
for (uint32_t k = 0; k < vi->vertexBindingDescriptionCount; k++) {
|
||||
if (bd[k].binding != b) continue;
|
||||
out->mask |= 1u << b;
|
||||
out->divisor[b] = div;
|
||||
out->stride[b] = bd[k].stride;
|
||||
if (div > 1) out->split = 1;
|
||||
bd[k].stride = 0;
|
||||
}
|
||||
}
|
||||
/* The vertex shader's SPIR-V is still at hand here (it may be inline). */
|
||||
if (out->split && ci->pStages) {
|
||||
for (uint32_t st = 0; st < ci->stageCount; st++) {
|
||||
if (ci->pStages[st].stage != VK_SHADER_STAGE_VERTEX_BIT) continue;
|
||||
out->zero_vs = vkb_emu_shader_zero_base_instance(e, device, &ci->pStages[st]);
|
||||
out->vs_stage = st;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void vkb_emu_divisor_created(vkb_emu_device *e, VkDevice device, VkPipelineCache cache, const VkGraphicsPipelineCreateInfo *ci,
|
||||
VkPipeline p, div_info *info)
|
||||
{
|
||||
if (!(e->flags & VKB_EMU_DIVISOR)) return;
|
||||
if (!p) {
|
||||
if (info->zero_vs) vkb_emu_real()->vkDestroyShaderModule(device, info->zero_vs, NULL);
|
||||
return;
|
||||
}
|
||||
if (info->zero_vs) {
|
||||
/* Split draws move BaseInstance: a variant that reads it as 0 serves the usual
|
||||
* firstInstance = 0 draws exactly. */
|
||||
VkPipelineShaderStageCreateInfo *st = malloc(ci->stageCount * sizeof(*st));
|
||||
memcpy(st, ci->pStages, ci->stageCount * sizeof(*st));
|
||||
st[info->vs_stage].module = info->zero_vs;
|
||||
st[info->vs_stage].pNext = NULL;
|
||||
VkGraphicsPipelineCreateInfo v = *ci;
|
||||
v.pStages = st;
|
||||
if (vkb_emu_real()->vkCreateGraphicsPipelines(device, cache, 1, &v, NULL, &info->zero_base) != VK_SUCCESS)
|
||||
info->zero_base = VK_NULL_HANDLE;
|
||||
vkb_emu_real()->vkDestroyShaderModule(device, info->zero_vs, NULL);
|
||||
info->zero_vs = VK_NULL_HANDLE;
|
||||
free(st);
|
||||
}
|
||||
if (info->mask || info->dynamic_input || info->dynamic_stride) store_pipe(e, p, info);
|
||||
if (info->mask)
|
||||
VKB_DBG("divisor: pipeline %p emulates bindings 0x%x (dynamic stride %d, dynamic input %d, split %d, variant %p)", (void *)p,
|
||||
info->mask, info->dynamic_stride, info->dynamic_input, info->split, (void *)info->zero_base);
|
||||
}
|
||||
|
||||
size_t vkb_emu_divisor_info_size(void) { return sizeof(div_info); }
|
||||
|
||||
static VKAPI_ATTR void VKAPI_CALL emu_DestroyPipeline(VkDevice device, VkPipeline p, const VkAllocationCallbacks *pAllocator)
|
||||
{
|
||||
if (p) drop_pipe(vkb_emu_cur(), p);
|
||||
vkb_emu_real()->vkDestroyPipeline(device, p, pAllocator);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ command buffers */
|
||||
|
||||
static gfx_state *gfx(vkb_emu_device *e, VkCommandBuffer cb) { return vkb_emu_cb_gfx(e, cb, sizeof(gfx_state)); }
|
||||
|
||||
void vkb_emu_gfx_reset(void *g)
|
||||
{
|
||||
if (g) memset(g, 0, sizeof(gfx_state));
|
||||
}
|
||||
|
||||
void vkb_emu_gfx_free(void *g) { free(g); }
|
||||
|
||||
void vkb_emu_gfx_bind_pipeline(vkb_emu_device *e, VkCommandBuffer cb, VkPipeline p)
|
||||
{
|
||||
if (!(e->flags & VKB_EMU_DIVISOR)) return;
|
||||
gfx_state *g = gfx(e, cb);
|
||||
g->pipeline = p;
|
||||
const div_info *i = find_pipe(e, p);
|
||||
if (i) g->pipe = *i;
|
||||
else memset(&g->pipe, 0, sizeof(g->pipe));
|
||||
g->use_dyn = g->pipe.dynamic_input;
|
||||
}
|
||||
|
||||
static void record_bind(gfx_state *g, uint32_t first, uint32_t n, const VkBuffer *b, const VkDeviceSize *o, const VkDeviceSize *s,
|
||||
const VkDeviceSize *st)
|
||||
{
|
||||
for (uint32_t i = 0; i < n && first + i < MAX_BIND; i++) {
|
||||
uint32_t k = first + i;
|
||||
g->buf[k] = b[i];
|
||||
g->off[k] = o[i];
|
||||
g->size[k] = s ? s[i] : VK_WHOLE_SIZE;
|
||||
if (st) g->stride[k] = st[i];
|
||||
g->bound |= 1u << k;
|
||||
g->tampered &= ~(1u << k);
|
||||
}
|
||||
}
|
||||
|
||||
static VKAPI_ATTR void VKAPI_CALL emu_CmdBindVertexBuffers(VkCommandBuffer cb, uint32_t first, uint32_t n, const VkBuffer *b,
|
||||
const VkDeviceSize *o)
|
||||
{
|
||||
vkb_emu_device *e = vkb_emu_cur();
|
||||
record_bind(gfx(e, cb), first, n, b, o, NULL, NULL);
|
||||
vkb_emu_real()->vkCmdBindVertexBuffers(cb, first, n, b, o);
|
||||
}
|
||||
|
||||
static VKAPI_ATTR void VKAPI_CALL emu_CmdBindVertexBuffers2(VkCommandBuffer cb, uint32_t first, uint32_t n, const VkBuffer *b,
|
||||
const VkDeviceSize *o, const VkDeviceSize *s, const VkDeviceSize *st)
|
||||
{
|
||||
vkb_emu_device *e = vkb_emu_cur();
|
||||
record_bind(gfx(e, cb), first, n, b, o, s, st);
|
||||
vkb_emu_real()->vkCmdBindVertexBuffers2(cb, first, n, b, o, s, st);
|
||||
}
|
||||
|
||||
static VKAPI_ATTR void VKAPI_CALL emu_CmdSetVertexInputEXT(VkCommandBuffer cb, uint32_t nb, const VkVertexInputBindingDescription2EXT *bd,
|
||||
uint32_t na, const VkVertexInputAttributeDescription2EXT *ad)
|
||||
{
|
||||
vkb_emu_device *e = vkb_emu_cur();
|
||||
gfx_state *g = gfx(e, cb);
|
||||
memset(&g->dyn, 0, sizeof(g->dyn));
|
||||
g->dyn.dynamic_stride = 1;
|
||||
g->dyn.dynamic_input = 1;
|
||||
VkVertexInputBindingDescription2EXT *w = (VkVertexInputBindingDescription2EXT *)bd;
|
||||
for (uint32_t i = 0; i < nb; i++) {
|
||||
uint32_t b = w[i].binding;
|
||||
if (w[i].inputRate != VK_VERTEX_INPUT_RATE_INSTANCE || w[i].divisor == 1 || b >= MAX_BIND) continue;
|
||||
g->dyn.mask |= 1u << b;
|
||||
g->dyn.divisor[b] = w[i].divisor;
|
||||
g->dyn.stride[b] = w[i].stride;
|
||||
g->stride[b] = w[i].stride;
|
||||
w[i].stride = 0;
|
||||
w[i].divisor = 1;
|
||||
}
|
||||
vkb_emu_real()->vkCmdSetVertexInputEXT(cb, nb, bd, na, ad);
|
||||
}
|
||||
|
||||
/* Rebinds the emulated bindings for instances starting at `inst` (relative to the draw), and puts
|
||||
* back any slot we changed that the current pipeline does not emulate. */
|
||||
static void prepare(vkb_emu_device *e, VkCommandBuffer cb, gfx_state *g, const div_info *di, uint32_t first_instance, uint32_t inst)
|
||||
{
|
||||
const vkb_dispatch *r = vkb_emu_real();
|
||||
for (uint32_t k = 0; k < MAX_BIND; k++) {
|
||||
uint32_t bit = 1u << k;
|
||||
if (!(g->bound & bit)) continue;
|
||||
if (di->mask & bit) {
|
||||
uint32_t d = di->divisor[k];
|
||||
VkDeviceSize stride = di->dynamic_input ? g->dyn.stride[k] : (di->dynamic_stride ? g->stride[k] : di->stride[k]);
|
||||
VkDeviceSize elem = (VkDeviceSize)first_instance + (d ? inst / d : 0);
|
||||
VkDeviceSize off = g->off[k] + elem * stride;
|
||||
if (di->dynamic_stride || di->dynamic_input) {
|
||||
VkDeviceSize size = g->size[k] == VK_WHOLE_SIZE ? VK_WHOLE_SIZE : (g->size[k] > elem * stride ? g->size[k] - elem * stride : 0);
|
||||
VkDeviceSize zero = 0;
|
||||
r->vkCmdBindVertexBuffers2(cb, k, 1, &g->buf[k], &off, size == VK_WHOLE_SIZE ? NULL : &size, &zero);
|
||||
} else {
|
||||
r->vkCmdBindVertexBuffers(cb, k, 1, &g->buf[k], &off);
|
||||
}
|
||||
g->tampered |= bit;
|
||||
} else if (g->tampered & bit) {
|
||||
if (di->dynamic_stride) {
|
||||
VkDeviceSize size = g->size[k];
|
||||
r->vkCmdBindVertexBuffers2(cb, k, 1, &g->buf[k], &g->off[k], size == VK_WHOLE_SIZE ? NULL : &size, &g->stride[k]);
|
||||
} else {
|
||||
r->vkCmdBindVertexBuffers(cb, k, 1, &g->buf[k], &g->off[k]);
|
||||
}
|
||||
g->tampered &= ~bit;
|
||||
}
|
||||
}
|
||||
(void)e;
|
||||
}
|
||||
|
||||
static const div_info *active(gfx_state *g)
|
||||
{
|
||||
return g->use_dyn ? &g->dyn : &g->pipe;
|
||||
}
|
||||
|
||||
/* The next instance where some emulated binding moves to its next element. */
|
||||
static uint32_t next_boundary(const div_info *di, uint32_t i, uint32_t count)
|
||||
{
|
||||
uint32_t next = count;
|
||||
for (uint32_t k = 0; k < MAX_BIND; k++) {
|
||||
if (!(di->mask & (1u << k)) || di->divisor[k] <= 1) continue;
|
||||
uint32_t d = di->divisor[k], nb = (i / d + 1) * d;
|
||||
if (nb < next) next = nb;
|
||||
}
|
||||
return next;
|
||||
}
|
||||
|
||||
/* A split draw binds the BaseInstance-as-0 variant when that keeps it exact. */
|
||||
static int split_begin(vkb_emu_device *e, VkCommandBuffer cb, gfx_state *g, const div_info *di, uint32_t fi, uint32_t ic)
|
||||
{
|
||||
(void)e;
|
||||
if (!di->split || next_boundary(di, 0, ic) >= ic) return 0;
|
||||
if (fi == 0 && di->zero_base) {
|
||||
vkb_emu_real()->vkCmdBindPipeline(cb, VK_PIPELINE_BIND_POINT_GRAPHICS, di->zero_base);
|
||||
return 1;
|
||||
}
|
||||
if (fi != 0) VKB_ONCE(VKB_LOG_WARN, "divisor emulation: a split draw with firstInstance > 0 may see SV_InstanceID offset (logged once)");
|
||||
(void)g;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void split_end(VkCommandBuffer cb, gfx_state *g, int variant)
|
||||
{
|
||||
if (variant) vkb_emu_real()->vkCmdBindPipeline(cb, VK_PIPELINE_BIND_POINT_GRAPHICS, g->pipeline);
|
||||
}
|
||||
|
||||
static VKAPI_ATTR void VKAPI_CALL emu_CmdDraw(VkCommandBuffer cb, uint32_t vc, uint32_t ic, uint32_t fv, uint32_t fi)
|
||||
{
|
||||
vkb_emu_device *e = vkb_emu_cur();
|
||||
gfx_state *g = gfx(e, cb);
|
||||
const div_info *di = active(g);
|
||||
if (!di->mask && !g->tampered) {
|
||||
vkb_emu_real()->vkCmdDraw(cb, vc, ic, fv, fi);
|
||||
return;
|
||||
}
|
||||
VKB_DBG("divisor: draw %u instances from %u, bindings 0x%x (dyn %d), bound 0x%x", ic, fi, di->mask, g->use_dyn, g->bound);
|
||||
int variant = split_begin(e, cb, g, di, fi, ic);
|
||||
for (uint32_t i = 0; i < ic || (ic == 0 && i == 0);) {
|
||||
uint32_t end = next_boundary(di, i, ic);
|
||||
prepare(e, cb, g, di, fi, i);
|
||||
if (ic) vkb_emu_real()->vkCmdDraw(cb, vc, end - i, fv, fi + i);
|
||||
if (!ic) break;
|
||||
i = end;
|
||||
}
|
||||
split_end(cb, g, variant);
|
||||
}
|
||||
|
||||
static VKAPI_ATTR void VKAPI_CALL emu_CmdDrawIndexed(VkCommandBuffer cb, uint32_t xc, uint32_t ic, uint32_t fx, int32_t vo, uint32_t fi)
|
||||
{
|
||||
vkb_emu_device *e = vkb_emu_cur();
|
||||
gfx_state *g = gfx(e, cb);
|
||||
const div_info *di = active(g);
|
||||
if (!di->mask && !g->tampered) {
|
||||
vkb_emu_real()->vkCmdDrawIndexed(cb, xc, ic, fx, vo, fi);
|
||||
return;
|
||||
}
|
||||
int variant = split_begin(e, cb, g, di, fi, ic);
|
||||
for (uint32_t i = 0; i < ic || (ic == 0 && i == 0);) {
|
||||
uint32_t end = next_boundary(di, i, ic);
|
||||
prepare(e, cb, g, di, fi, i);
|
||||
if (ic) vkb_emu_real()->vkCmdDrawIndexed(cb, xc, end - i, fx, vo, fi + i);
|
||||
if (!ic) break;
|
||||
i = end;
|
||||
}
|
||||
split_end(cb, g, variant);
|
||||
}
|
||||
|
||||
static void indirect_prepare(vkb_emu_device *e, VkCommandBuffer cb)
|
||||
{
|
||||
gfx_state *g = gfx(e, cb);
|
||||
const div_info *di = active(g);
|
||||
if (!di->mask && !g->tampered) return;
|
||||
for (uint32_t k = 0; k < MAX_BIND; k++)
|
||||
if ((di->mask & (1u << k)) && di->divisor[k] > 1)
|
||||
VKB_ONCE(VKB_LOG_WARN, "divisor emulation: an indirect draw with an instance divisor > 1 is approximated (logged once)");
|
||||
prepare(e, cb, g, di, 0, 0);
|
||||
}
|
||||
|
||||
static VKAPI_ATTR void VKAPI_CALL emu_CmdDrawIndirect(VkCommandBuffer cb, VkBuffer b, VkDeviceSize o, uint32_t n, uint32_t s)
|
||||
{
|
||||
indirect_prepare(vkb_emu_cur(), cb);
|
||||
vkb_emu_real()->vkCmdDrawIndirect(cb, b, o, n, s);
|
||||
}
|
||||
|
||||
static VKAPI_ATTR void VKAPI_CALL emu_CmdDrawIndexedIndirect(VkCommandBuffer cb, VkBuffer b, VkDeviceSize o, uint32_t n, uint32_t s)
|
||||
{
|
||||
indirect_prepare(vkb_emu_cur(), cb);
|
||||
vkb_emu_real()->vkCmdDrawIndexedIndirect(cb, b, o, n, s);
|
||||
}
|
||||
|
||||
static VKAPI_ATTR void VKAPI_CALL emu_CmdDrawIndirectCount(VkCommandBuffer cb, VkBuffer b, VkDeviceSize o, VkBuffer cbuf, VkDeviceSize co,
|
||||
uint32_t max, uint32_t s)
|
||||
{
|
||||
indirect_prepare(vkb_emu_cur(), cb);
|
||||
vkb_emu_real()->vkCmdDrawIndirectCount(cb, b, o, cbuf, co, max, s);
|
||||
}
|
||||
|
||||
static VKAPI_ATTR void VKAPI_CALL emu_CmdDrawIndexedIndirectCount(VkCommandBuffer cb, VkBuffer b, VkDeviceSize o, VkBuffer cbuf,
|
||||
VkDeviceSize co, uint32_t max, uint32_t s)
|
||||
{
|
||||
indirect_prepare(vkb_emu_cur(), cb);
|
||||
vkb_emu_real()->vkCmdDrawIndexedIndirectCount(cb, b, o, cbuf, co, max, s);
|
||||
}
|
||||
|
||||
void vkb_emu_divisor_install(vkb_srv_table *dev)
|
||||
{
|
||||
vkb_emu_device *e = dev->emu;
|
||||
if (!(e->flags & VKB_EMU_DIVISOR)) return;
|
||||
div_state *s = calloc(1, sizeof(*s));
|
||||
pthread_mutex_init(&s->lock, NULL);
|
||||
e->divisor = s;
|
||||
vkb_dispatch *dt = &dev->dt;
|
||||
dt->vkDestroyPipeline = emu_DestroyPipeline;
|
||||
dt->vkCmdBindVertexBuffers = emu_CmdBindVertexBuffers;
|
||||
if (dev->real.vkCmdBindVertexBuffers2) dt->vkCmdBindVertexBuffers2 = emu_CmdBindVertexBuffers2;
|
||||
if (dev->real.vkCmdSetVertexInputEXT) dt->vkCmdSetVertexInputEXT = emu_CmdSetVertexInputEXT;
|
||||
dt->vkCmdDraw = emu_CmdDraw;
|
||||
dt->vkCmdDrawIndexed = emu_CmdDrawIndexed;
|
||||
dt->vkCmdDrawIndirect = emu_CmdDrawIndirect;
|
||||
dt->vkCmdDrawIndexedIndirect = emu_CmdDrawIndexedIndirect;
|
||||
if (dev->real.vkCmdDrawIndirectCount) dt->vkCmdDrawIndirectCount = emu_CmdDrawIndirectCount;
|
||||
if (dev->real.vkCmdDrawIndexedIndirectCount) dt->vkCmdDrawIndexedIndirectCount = emu_CmdDrawIndexedIndirectCount;
|
||||
}
|
||||
|
||||
void vkb_emu_divisor_uninstall(vkb_srv_table *dev)
|
||||
{
|
||||
div_state *s = dev->emu->divisor;
|
||||
if (!s) return;
|
||||
for (int i = 0; i < 256; i++) {
|
||||
while (s->b[i]) {
|
||||
pipe_rec *r = s->b[i];
|
||||
s->b[i] = r->next;
|
||||
free(r);
|
||||
}
|
||||
}
|
||||
pthread_mutex_destroy(&s->lock);
|
||||
free(s);
|
||||
dev->emu->divisor = NULL;
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
/* SPDX-License-Identifier: GPL-3.0-or-later
|
||||
*
|
||||
* Installs the feature emulations into a device.
|
||||
*/
|
||||
#define _GNU_SOURCE
|
||||
#include "server_emu.h"
|
||||
|
||||
void vkb_emu_install_features(vkb_srv_table *dev)
|
||||
{
|
||||
vkb_emu_cmdstate_install(dev);
|
||||
vkb_emu_shader_install(dev);
|
||||
vkb_emu_bcn_install(dev);
|
||||
vkb_emu_divisor_install(dev);
|
||||
}
|
||||
|
||||
void vkb_emu_uninstall_features(vkb_srv_table *dev)
|
||||
{
|
||||
vkb_emu_divisor_uninstall(dev);
|
||||
vkb_emu_bcn_uninstall(dev);
|
||||
vkb_emu_shader_uninstall(dev);
|
||||
vkb_emu_cmdstate_uninstall(dev);
|
||||
}
|
||||
@@ -0,0 +1,478 @@
|
||||
/* SPDX-License-Identifier: GPL-3.0-or-later
|
||||
*
|
||||
* Emulation wrappers installed into a device's dispatch table, like a Vulkan layer: the generated
|
||||
* handlers call c->dt, which for an emulating device points here first. The device is found
|
||||
* through the per-call table the connection loop sets (vkb_srv_current_table).
|
||||
*
|
||||
* VK_KHR_maintenance5 (Zink and DXVK 2.7 refuse a Vulkan 1.3 device without it):
|
||||
* - 64-bit flags structures (pipeline create flags 2, buffer usage 2) folded into the 32-bit
|
||||
* fields, which hold every bit a 1.3 driver knows;
|
||||
* - shader modules given inline (VkShaderModuleCreateInfo chained to a stage) created and
|
||||
* destroyed around the pipeline;
|
||||
* - vkCmdBindIndexBuffer2, vkGetRenderingAreaGranularity, vkGetImageSubresourceLayout2 and
|
||||
* vkGetDeviceImageSubresourceLayout on their 1.0 equivalents;
|
||||
* - VK_REMAINING_ARRAY_LAYERS in copy regions and VK_WHOLE_SIZE in vertex buffer sizes, resolved
|
||||
* from the image/buffer the server keeps a record of.
|
||||
*/
|
||||
#define _GNU_SOURCE
|
||||
#include "server_emu.h"
|
||||
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
/* ------------------------------------------------------------------ resource records */
|
||||
|
||||
static unsigned rh(uint64_t k)
|
||||
{
|
||||
k ^= k >> 29;
|
||||
k *= 0xbf58476d1ce4e5b9ull;
|
||||
return (unsigned)(k >> 52) & (VKB_EMU_BUCKETS - 1);
|
||||
}
|
||||
|
||||
void vkb_emu_track_image(vkb_emu_device *e, VkImage img, const VkImageCreateInfo *ci, VkFormat client_format)
|
||||
{
|
||||
vkb_emu_image *r = calloc(1, sizeof(*r));
|
||||
r->image = img;
|
||||
r->type = ci->imageType;
|
||||
r->format = ci->format;
|
||||
r->client_format = client_format;
|
||||
r->extent = ci->extent;
|
||||
r->mips = ci->mipLevels;
|
||||
r->layers = ci->arrayLayers;
|
||||
pthread_mutex_lock(&e->lock);
|
||||
unsigned h = rh((uint64_t)img);
|
||||
r->next = e->images[h];
|
||||
e->images[h] = r;
|
||||
pthread_mutex_unlock(&e->lock);
|
||||
}
|
||||
|
||||
vkb_emu_image *vkb_emu_find_image(vkb_emu_device *e, VkImage img)
|
||||
{
|
||||
pthread_mutex_lock(&e->lock);
|
||||
vkb_emu_image *r = e->images[rh((uint64_t)img)];
|
||||
while (r && r->image != img) r = r->next;
|
||||
pthread_mutex_unlock(&e->lock);
|
||||
return r;
|
||||
}
|
||||
|
||||
static void untrack_image(vkb_emu_device *e, VkImage img)
|
||||
{
|
||||
pthread_mutex_lock(&e->lock);
|
||||
vkb_emu_image **pp = &e->images[rh((uint64_t)img)];
|
||||
while (*pp && (*pp)->image != img) pp = &(*pp)->next;
|
||||
vkb_emu_image *r = *pp;
|
||||
if (r) *pp = r->next;
|
||||
pthread_mutex_unlock(&e->lock);
|
||||
if (r) {
|
||||
vkb_emu_image_release(e, r);
|
||||
free(r);
|
||||
}
|
||||
}
|
||||
|
||||
static void track_buffer(vkb_emu_device *e, VkBuffer b, VkDeviceSize size)
|
||||
{
|
||||
vkb_emu_buffer *r = calloc(1, sizeof(*r));
|
||||
r->buffer = b;
|
||||
r->size = size;
|
||||
pthread_mutex_lock(&e->lock);
|
||||
unsigned h = rh((uint64_t)b);
|
||||
r->next = e->buffers[h];
|
||||
e->buffers[h] = r;
|
||||
pthread_mutex_unlock(&e->lock);
|
||||
}
|
||||
|
||||
static VkDeviceSize buffer_size(vkb_emu_device *e, VkBuffer b)
|
||||
{
|
||||
pthread_mutex_lock(&e->lock);
|
||||
vkb_emu_buffer *r = e->buffers[rh((uint64_t)b)];
|
||||
while (r && r->buffer != b) r = r->next;
|
||||
VkDeviceSize s = r ? r->size : 0;
|
||||
pthread_mutex_unlock(&e->lock);
|
||||
return s;
|
||||
}
|
||||
|
||||
static void untrack_buffer(vkb_emu_device *e, VkBuffer b)
|
||||
{
|
||||
pthread_mutex_lock(&e->lock);
|
||||
vkb_emu_buffer **pp = &e->buffers[rh((uint64_t)b)];
|
||||
while (*pp && (*pp)->buffer != b) pp = &(*pp)->next;
|
||||
vkb_emu_buffer *r = *pp;
|
||||
if (r) *pp = r->next;
|
||||
pthread_mutex_unlock(&e->lock);
|
||||
free(r);
|
||||
}
|
||||
|
||||
vkb_emu_device *vkb_emu_cur(void)
|
||||
{
|
||||
vkb_srv_table *t = vkb_srv_current_table();
|
||||
return t ? t->emu : NULL;
|
||||
}
|
||||
|
||||
const vkb_dispatch *vkb_emu_real(void)
|
||||
{
|
||||
return &vkb_srv_current_table()->real;
|
||||
}
|
||||
|
||||
/* Removes the first structure of type t from a chain we own (decoded into the call's arena). */
|
||||
void *vkb_emu_chain_take(const void *head_const, VkStructureType t)
|
||||
{
|
||||
VkBaseOutStructure *prev = (VkBaseOutStructure *)head_const;
|
||||
while (prev->pNext) {
|
||||
if (prev->pNext->sType == t) {
|
||||
VkBaseOutStructure *found = prev->pNext;
|
||||
prev->pNext = found->pNext;
|
||||
return found;
|
||||
}
|
||||
prev = prev->pNext;
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ resources */
|
||||
|
||||
static VKAPI_ATTR VkResult VKAPI_CALL emu_CreateBuffer(VkDevice device, const VkBufferCreateInfo *pCreateInfo,
|
||||
const VkAllocationCallbacks *pAllocator, VkBuffer *pBuffer)
|
||||
{
|
||||
vkb_emu_device *e = vkb_emu_cur();
|
||||
VkBufferCreateInfo *ci = (VkBufferCreateInfo *)pCreateInfo;
|
||||
if (e->flags & VKB_EMU_MAINT5) {
|
||||
VkBufferUsageFlags2CreateInfo *u = vkb_emu_chain_take(ci, VK_STRUCTURE_TYPE_BUFFER_USAGE_FLAGS_2_CREATE_INFO);
|
||||
if (u) ci->usage = (VkBufferUsageFlags)u->usage;
|
||||
}
|
||||
vkb_emu_bcn_buffer_usage(e, ci);
|
||||
VkResult r = vkb_emu_real()->vkCreateBuffer(device, ci, pAllocator, pBuffer);
|
||||
if (r == VK_SUCCESS) track_buffer(e, *pBuffer, ci->size);
|
||||
return r;
|
||||
}
|
||||
|
||||
static VKAPI_ATTR void VKAPI_CALL emu_DestroyBuffer(VkDevice device, VkBuffer buffer, const VkAllocationCallbacks *pAllocator)
|
||||
{
|
||||
if (buffer) untrack_buffer(vkb_emu_cur(), buffer);
|
||||
vkb_emu_real()->vkDestroyBuffer(device, buffer, pAllocator);
|
||||
}
|
||||
|
||||
static VKAPI_ATTR VkResult VKAPI_CALL emu_CreateBufferView(VkDevice device, const VkBufferViewCreateInfo *pCreateInfo,
|
||||
const VkAllocationCallbacks *pAllocator, VkBufferView *pView)
|
||||
{
|
||||
if (vkb_emu_cur()->flags & VKB_EMU_MAINT5) vkb_emu_chain_take(pCreateInfo, VK_STRUCTURE_TYPE_BUFFER_USAGE_FLAGS_2_CREATE_INFO);
|
||||
return vkb_emu_real()->vkCreateBufferView(device, pCreateInfo, pAllocator, pView);
|
||||
}
|
||||
|
||||
static VKAPI_ATTR VkResult VKAPI_CALL emu_CreateImage(VkDevice device, const VkImageCreateInfo *pCreateInfo,
|
||||
const VkAllocationCallbacks *pAllocator, VkImage *pImage)
|
||||
{
|
||||
vkb_emu_device *e = vkb_emu_cur();
|
||||
VkImageCreateInfo *ci = (VkImageCreateInfo *)pCreateInfo;
|
||||
VkFormat client_format = ci->format;
|
||||
vkb_emu_image_create_info(e, ci);
|
||||
VkResult r = vkb_emu_real()->vkCreateImage(device, ci, pAllocator, pImage);
|
||||
if (r == VK_SUCCESS) vkb_emu_track_image(e, *pImage, ci, client_format);
|
||||
return r;
|
||||
}
|
||||
|
||||
static VKAPI_ATTR void VKAPI_CALL emu_DestroyImage(VkDevice device, VkImage image, const VkAllocationCallbacks *pAllocator)
|
||||
{
|
||||
if (image) untrack_image(vkb_emu_cur(), image);
|
||||
vkb_emu_real()->vkDestroyImage(device, image, pAllocator);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ pipelines */
|
||||
|
||||
/* Fold flags2 and create inline shader modules; temporaries are recorded in mods[]. */
|
||||
static void prep_stage(VkDevice device, VkPipelineShaderStageCreateInfo *st, VkShaderModule *mods, uint32_t *nmods, uint32_t cap)
|
||||
{
|
||||
if (st->module) return;
|
||||
VkShaderModuleCreateInfo *smci = vkb_emu_chain_take(st, VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO);
|
||||
if (!smci) return;
|
||||
VkShaderModule m = VK_NULL_HANDLE;
|
||||
smci->pNext = NULL;
|
||||
if (vkb_emu_real()->vkCreateShaderModule(device, smci, NULL, &m) == VK_SUCCESS) {
|
||||
st->module = m;
|
||||
if (*nmods < cap) mods[(*nmods)++] = m;
|
||||
}
|
||||
}
|
||||
|
||||
static VKAPI_ATTR VkResult VKAPI_CALL emu_CreateGraphicsPipelines(VkDevice device, VkPipelineCache cache, uint32_t n,
|
||||
const VkGraphicsPipelineCreateInfo *infos,
|
||||
const VkAllocationCallbacks *pAllocator, VkPipeline *pPipelines)
|
||||
{
|
||||
vkb_emu_device *e = vkb_emu_cur();
|
||||
VkShaderModule mods[64];
|
||||
uint32_t nmods = 0;
|
||||
size_t dsz = vkb_emu_divisor_info_size();
|
||||
uint8_t *divs = calloc(n ? n : 1, dsz);
|
||||
for (uint32_t i = 0; i < n; i++) {
|
||||
VkGraphicsPipelineCreateInfo *ci = (VkGraphicsPipelineCreateInfo *)&infos[i];
|
||||
vkb_emu_divisor_pipeline(e, device, ci, (div_info *)(divs + i * dsz));
|
||||
vkb_emu_depth_clip_pipeline(e, ci);
|
||||
/* Shader rewrites first: they read inline SPIR-V before it becomes a module. */
|
||||
vkb_emu_shader_pipeline(e, device, ci, mods, &nmods, 64);
|
||||
if (e->flags & VKB_EMU_MAINT5) {
|
||||
VkPipelineCreateFlags2CreateInfo *f2 = vkb_emu_chain_take(ci, VK_STRUCTURE_TYPE_PIPELINE_CREATE_FLAGS_2_CREATE_INFO);
|
||||
if (f2) ci->flags = (VkPipelineCreateFlags)f2->flags;
|
||||
for (uint32_t s = 0; s < ci->stageCount; s++)
|
||||
prep_stage(device, (VkPipelineShaderStageCreateInfo *)&ci->pStages[s], mods, &nmods, 64);
|
||||
}
|
||||
}
|
||||
VkResult r = vkb_emu_real()->vkCreateGraphicsPipelines(device, cache, n, infos, pAllocator, pPipelines);
|
||||
/* Before the temporary modules go: a divisor variant is built from the same stages. */
|
||||
for (uint32_t i = 0; i < n; i++)
|
||||
vkb_emu_divisor_created(e, device, cache, &infos[i], r >= 0 ? pPipelines[i] : VK_NULL_HANDLE, (div_info *)(divs + i * dsz));
|
||||
for (uint32_t i = 0; i < nmods; i++) vkb_emu_real()->vkDestroyShaderModule(device, mods[i], NULL);
|
||||
free(divs);
|
||||
return r;
|
||||
}
|
||||
|
||||
static VKAPI_ATTR VkResult VKAPI_CALL emu_CreateComputePipelines(VkDevice device, VkPipelineCache cache, uint32_t n,
|
||||
const VkComputePipelineCreateInfo *infos,
|
||||
const VkAllocationCallbacks *pAllocator, VkPipeline *pPipelines)
|
||||
{
|
||||
vkb_emu_device *e = vkb_emu_cur();
|
||||
VkShaderModule mods[64];
|
||||
uint32_t nmods = 0;
|
||||
for (uint32_t i = 0; i < n; i++) {
|
||||
VkComputePipelineCreateInfo *ci = (VkComputePipelineCreateInfo *)&infos[i];
|
||||
if (e->flags & VKB_EMU_MAINT5) {
|
||||
VkPipelineCreateFlags2CreateInfo *f2 = vkb_emu_chain_take(ci, VK_STRUCTURE_TYPE_PIPELINE_CREATE_FLAGS_2_CREATE_INFO);
|
||||
if (f2) ci->flags = (VkPipelineCreateFlags)f2->flags;
|
||||
prep_stage(device, &ci->stage, mods, &nmods, 64);
|
||||
}
|
||||
}
|
||||
VkResult r = vkb_emu_real()->vkCreateComputePipelines(device, cache, n, infos, pAllocator, pPipelines);
|
||||
for (uint32_t i = 0; i < nmods; i++) vkb_emu_real()->vkDestroyShaderModule(device, mods[i], NULL);
|
||||
return r;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ maintenance5 entry points */
|
||||
|
||||
static VKAPI_ATTR void VKAPI_CALL emu_CmdBindIndexBuffer2(VkCommandBuffer cb, VkBuffer buffer, VkDeviceSize offset, VkDeviceSize size,
|
||||
VkIndexType type)
|
||||
{
|
||||
(void)size;
|
||||
vkb_emu_real()->vkCmdBindIndexBuffer(cb, buffer, offset, type);
|
||||
}
|
||||
|
||||
static VKAPI_ATTR void VKAPI_CALL emu_GetRenderingAreaGranularity(VkDevice device, const VkRenderingAreaInfo *info, VkExtent2D *g)
|
||||
{
|
||||
(void)device;
|
||||
(void)info;
|
||||
g->width = 1;
|
||||
g->height = 1;
|
||||
}
|
||||
|
||||
static VKAPI_ATTR void VKAPI_CALL emu_GetImageSubresourceLayout2(VkDevice device, VkImage image, const VkImageSubresource2 *sub,
|
||||
VkSubresourceLayout2 *layout)
|
||||
{
|
||||
vkb_emu_real()->vkGetImageSubresourceLayout(device, image, &sub->imageSubresource, &layout->subresourceLayout);
|
||||
}
|
||||
|
||||
static VKAPI_ATTR void VKAPI_CALL emu_GetDeviceImageSubresourceLayout(VkDevice device, const VkDeviceImageSubresourceInfo *info,
|
||||
VkSubresourceLayout2 *layout)
|
||||
{
|
||||
VkImage img;
|
||||
memset(&layout->subresourceLayout, 0, sizeof(layout->subresourceLayout));
|
||||
if (vkb_emu_real()->vkCreateImage(device, info->pCreateInfo, NULL, &img) != VK_SUCCESS) return;
|
||||
vkb_emu_real()->vkGetImageSubresourceLayout(device, img, &info->pSubresource->imageSubresource, &layout->subresourceLayout);
|
||||
vkb_emu_real()->vkDestroyImage(device, img, NULL);
|
||||
}
|
||||
|
||||
/* VK_REMAINING_ARRAY_LAYERS in a copy region, resolved against the image. */
|
||||
static void fix_layers(vkb_emu_device *e, VkImage img, VkImageSubresourceLayers *l)
|
||||
{
|
||||
if (l->layerCount != VK_REMAINING_ARRAY_LAYERS) return;
|
||||
vkb_emu_image *r = vkb_emu_find_image(e, img);
|
||||
l->layerCount = r && r->layers > l->baseArrayLayer ? r->layers - l->baseArrayLayer : 1;
|
||||
}
|
||||
|
||||
static VKAPI_ATTR void VKAPI_CALL emu_CmdCopyImage(VkCommandBuffer cb, VkImage src, VkImageLayout sl, VkImage dst, VkImageLayout dl,
|
||||
uint32_t n, const VkImageCopy *regions)
|
||||
{
|
||||
vkb_emu_device *e = vkb_emu_cur();
|
||||
for (uint32_t i = 0; i < n; i++) {
|
||||
fix_layers(e, src, (VkImageSubresourceLayers *)®ions[i].srcSubresource);
|
||||
fix_layers(e, dst, (VkImageSubresourceLayers *)®ions[i].dstSubresource);
|
||||
}
|
||||
if (vkb_emu_copy_image(e, cb, src, sl, dst, dl, n, regions)) return;
|
||||
vkb_emu_real()->vkCmdCopyImage(cb, src, sl, dst, dl, n, regions);
|
||||
}
|
||||
|
||||
static VKAPI_ATTR void VKAPI_CALL emu_CmdCopyImage2(VkCommandBuffer cb, const VkCopyImageInfo2 *info)
|
||||
{
|
||||
vkb_emu_device *e = vkb_emu_cur();
|
||||
for (uint32_t i = 0; i < info->regionCount; i++) {
|
||||
fix_layers(e, info->srcImage, (VkImageSubresourceLayers *)&info->pRegions[i].srcSubresource);
|
||||
fix_layers(e, info->dstImage, (VkImageSubresourceLayers *)&info->pRegions[i].dstSubresource);
|
||||
}
|
||||
if (vkb_emu_copy_image2(e, cb, info)) return;
|
||||
vkb_emu_real()->vkCmdCopyImage2(cb, info);
|
||||
}
|
||||
|
||||
static VKAPI_ATTR void VKAPI_CALL emu_CmdBlitImage(VkCommandBuffer cb, VkImage src, VkImageLayout sl, VkImage dst, VkImageLayout dl,
|
||||
uint32_t n, const VkImageBlit *regions, VkFilter filter)
|
||||
{
|
||||
vkb_emu_device *e = vkb_emu_cur();
|
||||
for (uint32_t i = 0; i < n; i++) {
|
||||
fix_layers(e, src, (VkImageSubresourceLayers *)®ions[i].srcSubresource);
|
||||
fix_layers(e, dst, (VkImageSubresourceLayers *)®ions[i].dstSubresource);
|
||||
}
|
||||
vkb_emu_real()->vkCmdBlitImage(cb, src, sl, dst, dl, n, regions, filter);
|
||||
}
|
||||
|
||||
static VKAPI_ATTR void VKAPI_CALL emu_CmdBlitImage2(VkCommandBuffer cb, const VkBlitImageInfo2 *info)
|
||||
{
|
||||
vkb_emu_device *e = vkb_emu_cur();
|
||||
for (uint32_t i = 0; i < info->regionCount; i++) {
|
||||
fix_layers(e, info->srcImage, (VkImageSubresourceLayers *)&info->pRegions[i].srcSubresource);
|
||||
fix_layers(e, info->dstImage, (VkImageSubresourceLayers *)&info->pRegions[i].dstSubresource);
|
||||
}
|
||||
vkb_emu_real()->vkCmdBlitImage2(cb, info);
|
||||
}
|
||||
|
||||
static VKAPI_ATTR void VKAPI_CALL emu_CmdResolveImage(VkCommandBuffer cb, VkImage src, VkImageLayout sl, VkImage dst, VkImageLayout dl,
|
||||
uint32_t n, const VkImageResolve *regions)
|
||||
{
|
||||
vkb_emu_device *e = vkb_emu_cur();
|
||||
for (uint32_t i = 0; i < n; i++) {
|
||||
fix_layers(e, src, (VkImageSubresourceLayers *)®ions[i].srcSubresource);
|
||||
fix_layers(e, dst, (VkImageSubresourceLayers *)®ions[i].dstSubresource);
|
||||
}
|
||||
vkb_emu_real()->vkCmdResolveImage(cb, src, sl, dst, dl, n, regions);
|
||||
}
|
||||
|
||||
static VKAPI_ATTR void VKAPI_CALL emu_CmdResolveImage2(VkCommandBuffer cb, const VkResolveImageInfo2 *info)
|
||||
{
|
||||
vkb_emu_device *e = vkb_emu_cur();
|
||||
for (uint32_t i = 0; i < info->regionCount; i++) {
|
||||
fix_layers(e, info->srcImage, (VkImageSubresourceLayers *)&info->pRegions[i].srcSubresource);
|
||||
fix_layers(e, info->dstImage, (VkImageSubresourceLayers *)&info->pRegions[i].dstSubresource);
|
||||
}
|
||||
vkb_emu_real()->vkCmdResolveImage2(cb, info);
|
||||
}
|
||||
|
||||
static VKAPI_ATTR void VKAPI_CALL emu_CmdCopyBufferToImage(VkCommandBuffer cb, VkBuffer src, VkImage dst, VkImageLayout dl, uint32_t n,
|
||||
const VkBufferImageCopy *regions)
|
||||
{
|
||||
vkb_emu_device *e = vkb_emu_cur();
|
||||
for (uint32_t i = 0; i < n; i++) fix_layers(e, dst, (VkImageSubresourceLayers *)®ions[i].imageSubresource);
|
||||
if (vkb_emu_copy_buffer_to_image(e, cb, src, dst, dl, n, regions)) return;
|
||||
vkb_emu_real()->vkCmdCopyBufferToImage(cb, src, dst, dl, n, regions);
|
||||
}
|
||||
|
||||
static VKAPI_ATTR void VKAPI_CALL emu_CmdCopyBufferToImage2(VkCommandBuffer cb, const VkCopyBufferToImageInfo2 *info)
|
||||
{
|
||||
vkb_emu_device *e = vkb_emu_cur();
|
||||
for (uint32_t i = 0; i < info->regionCount; i++)
|
||||
fix_layers(e, info->dstImage, (VkImageSubresourceLayers *)&info->pRegions[i].imageSubresource);
|
||||
if (vkb_emu_copy_buffer_to_image2(e, cb, info)) return;
|
||||
vkb_emu_real()->vkCmdCopyBufferToImage2(cb, info);
|
||||
}
|
||||
|
||||
static VKAPI_ATTR void VKAPI_CALL emu_CmdCopyImageToBuffer(VkCommandBuffer cb, VkImage src, VkImageLayout sl, VkBuffer dst, uint32_t n,
|
||||
const VkBufferImageCopy *regions)
|
||||
{
|
||||
vkb_emu_device *e = vkb_emu_cur();
|
||||
for (uint32_t i = 0; i < n; i++) fix_layers(e, src, (VkImageSubresourceLayers *)®ions[i].imageSubresource);
|
||||
if (vkb_emu_bcn_blocks_readback(e, src)) return;
|
||||
vkb_emu_real()->vkCmdCopyImageToBuffer(cb, src, sl, dst, n, regions);
|
||||
}
|
||||
|
||||
static VKAPI_ATTR void VKAPI_CALL emu_CmdCopyImageToBuffer2(VkCommandBuffer cb, const VkCopyImageToBufferInfo2 *info)
|
||||
{
|
||||
vkb_emu_device *e = vkb_emu_cur();
|
||||
for (uint32_t i = 0; i < info->regionCount; i++)
|
||||
fix_layers(e, info->srcImage, (VkImageSubresourceLayers *)&info->pRegions[i].imageSubresource);
|
||||
if (vkb_emu_bcn_blocks_readback(e, info->srcImage)) return;
|
||||
vkb_emu_real()->vkCmdCopyImageToBuffer2(cb, info);
|
||||
}
|
||||
|
||||
static VKAPI_ATTR void VKAPI_CALL emu_CmdBindVertexBuffers2(VkCommandBuffer cb, uint32_t first, uint32_t n, const VkBuffer *buffers,
|
||||
const VkDeviceSize *offsets, const VkDeviceSize *sizes,
|
||||
const VkDeviceSize *strides)
|
||||
{
|
||||
vkb_emu_device *e = vkb_emu_cur();
|
||||
if (sizes) {
|
||||
VkDeviceSize *s = (VkDeviceSize *)sizes;
|
||||
for (uint32_t i = 0; i < n; i++) {
|
||||
if (s[i] != VK_WHOLE_SIZE || !buffers[i]) continue;
|
||||
VkDeviceSize total = buffer_size(e, buffers[i]);
|
||||
s[i] = total > offsets[i] ? total - offsets[i] : 0;
|
||||
}
|
||||
}
|
||||
vkb_emu_real()->vkCmdBindVertexBuffers2(cb, first, n, buffers, offsets, sizes, strides);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ install */
|
||||
|
||||
void vkb_emu_install(vkb_srv_table *dev)
|
||||
{
|
||||
vkb_emu_device *e = dev->emu;
|
||||
vkb_dispatch *dt = &dev->dt;
|
||||
/* Resource records are needed by every emulation. */
|
||||
dt->vkCreateBuffer = emu_CreateBuffer;
|
||||
dt->vkDestroyBuffer = emu_DestroyBuffer;
|
||||
dt->vkCreateImage = emu_CreateImage;
|
||||
dt->vkDestroyImage = emu_DestroyImage;
|
||||
dt->vkCreateGraphicsPipelines = emu_CreateGraphicsPipelines;
|
||||
dt->vkCreateComputePipelines = emu_CreateComputePipelines;
|
||||
dt->vkCmdCopyImage = emu_CmdCopyImage;
|
||||
dt->vkCmdCopyBufferToImage = emu_CmdCopyBufferToImage;
|
||||
if (dev->real.vkCmdCopyImage2) dt->vkCmdCopyImage2 = emu_CmdCopyImage2;
|
||||
if (dev->real.vkCmdCopyBufferToImage2) dt->vkCmdCopyBufferToImage2 = emu_CmdCopyBufferToImage2;
|
||||
dt->vkCmdCopyImageToBuffer = emu_CmdCopyImageToBuffer;
|
||||
if (dev->real.vkCmdCopyImageToBuffer2) dt->vkCmdCopyImageToBuffer2 = emu_CmdCopyImageToBuffer2;
|
||||
if (e->flags & VKB_EMU_MAINT5) {
|
||||
dt->vkCreateBufferView = emu_CreateBufferView;
|
||||
dt->vkCmdBindIndexBuffer2 = emu_CmdBindIndexBuffer2;
|
||||
dt->vkGetRenderingAreaGranularity = emu_GetRenderingAreaGranularity;
|
||||
dt->vkGetImageSubresourceLayout2 = emu_GetImageSubresourceLayout2;
|
||||
dt->vkGetDeviceImageSubresourceLayout = emu_GetDeviceImageSubresourceLayout;
|
||||
dt->vkCmdBlitImage = emu_CmdBlitImage;
|
||||
dt->vkCmdResolveImage = emu_CmdResolveImage;
|
||||
if (dev->real.vkCmdBlitImage2) dt->vkCmdBlitImage2 = emu_CmdBlitImage2;
|
||||
if (dev->real.vkCmdResolveImage2) dt->vkCmdResolveImage2 = emu_CmdResolveImage2;
|
||||
if (dev->real.vkCmdBindVertexBuffers2) dt->vkCmdBindVertexBuffers2 = emu_CmdBindVertexBuffers2;
|
||||
}
|
||||
vkb_emu_install_features(dev);
|
||||
vkb_emu_depth_clip_install(dev);
|
||||
VKB_INFO("device %u: emulation 0x%x installed", dev->id, e->flags);
|
||||
}
|
||||
|
||||
void vkb_emu_uninstall(vkb_srv_table *dev)
|
||||
{
|
||||
vkb_emu_device *e = dev->emu;
|
||||
vkb_emu_uninstall_features(dev);
|
||||
for (int i = 0; i < VKB_EMU_BUCKETS; i++) {
|
||||
while (e->images[i]) {
|
||||
vkb_emu_image *r = e->images[i];
|
||||
e->images[i] = r->next;
|
||||
vkb_emu_image_release(e, r);
|
||||
free(r);
|
||||
}
|
||||
while (e->buffers[i]) {
|
||||
vkb_emu_buffer *r = e->buffers[i];
|
||||
e->buffers[i] = r->next;
|
||||
free(r);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ depth clip enable */
|
||||
|
||||
/* VK_EXT_depth_clip_enable on a GPU without it. Without the extension Vulkan clips exactly when
|
||||
* depth clamp is off, so a pipeline's clamp becomes "not clip" (D3D's DepthClipEnable = FALSE is
|
||||
* clamping; clip + clamp only differs for fragments the clip removes anyway). The client hides
|
||||
* dynamic depth clip/clamp while this is emulated, so both are static pipeline state here. */
|
||||
void vkb_emu_depth_clip_pipeline(vkb_emu_device *e, VkGraphicsPipelineCreateInfo *ci)
|
||||
{
|
||||
if (!(e->flags & VKB_EMU_DEPTH_CLIP)) return;
|
||||
VkPipelineRasterizationStateCreateInfo *rs = (VkPipelineRasterizationStateCreateInfo *)ci->pRasterizationState;
|
||||
if (!rs) return;
|
||||
VkPipelineRasterizationDepthClipStateCreateInfoEXT *dc =
|
||||
vkb_emu_chain_take(rs, VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_DEPTH_CLIP_STATE_CREATE_INFO_EXT);
|
||||
if (dc) rs->depthClampEnable = dc->depthClipEnable ? VK_FALSE : VK_TRUE;
|
||||
}
|
||||
|
||||
void vkb_emu_depth_clip_install(vkb_srv_table *dev)
|
||||
{
|
||||
(void)dev;
|
||||
}
|
||||
@@ -0,0 +1,429 @@
|
||||
/* SPDX-License-Identifier: GPL-3.0-or-later
|
||||
*
|
||||
* Shader-side emulations, done when a graphics pipeline is created (both ends of the vertex ->
|
||||
* fragment interface are known then):
|
||||
*
|
||||
* clip distance (shaderClipDistance missing): the last pre-rasterization stage's ClipDistance
|
||||
* output becomes an ordinary varying at a free location; the fragment shader reads it and
|
||||
* discards the fragment when any distance is negative. For planar clip distances this is the
|
||||
* same set of pixels the hardware clipper would keep.
|
||||
* cull distance (shaderCullDistance missing): the output becomes an unread varying - nothing is
|
||||
* culled, which costs fragments but never drops geometry that should be visible.
|
||||
* point size in geometry/tessellation (shaderTessellationAndGeometryPointSize missing): same.
|
||||
*
|
||||
* Shader modules are kept as SPIR-V so a pipeline can build rewritten variants; the driver's own
|
||||
* module is created from a variant that needs none of the missing features.
|
||||
*/
|
||||
#define _GNU_SOURCE
|
||||
#include "server_emu.h"
|
||||
#include "spirv_edit.h"
|
||||
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <unistd.h>
|
||||
|
||||
typedef struct shader_rec {
|
||||
VkShaderModule module;
|
||||
uint32_t *code;
|
||||
size_t size;
|
||||
struct shader_rec *next;
|
||||
} shader_rec;
|
||||
|
||||
typedef struct shader_state {
|
||||
pthread_mutex_t lock;
|
||||
shader_rec *mods[1024];
|
||||
} shader_state;
|
||||
|
||||
#define SHADER_EMU (VKB_EMU_CLIP_DISTANCE | VKB_EMU_CULL_DISTANCE | VKB_EMU_POINT_SIZE)
|
||||
/* Emulations that need the shader modules' SPIR-V kept. */
|
||||
#define SHADER_STORE (SHADER_EMU | VKB_EMU_DIVISOR)
|
||||
|
||||
static unsigned mh(VkShaderModule m)
|
||||
{
|
||||
uint64_t k = (uint64_t)m;
|
||||
k ^= k >> 31;
|
||||
k *= 0x94d049bb133111ebull;
|
||||
return (unsigned)(k >> 54);
|
||||
}
|
||||
|
||||
static shader_state *state(vkb_emu_device *e) { return e->shaders; }
|
||||
|
||||
static const shader_rec *find_module(vkb_emu_device *e, VkShaderModule m)
|
||||
{
|
||||
shader_state *s = state(e);
|
||||
pthread_mutex_lock(&s->lock);
|
||||
shader_rec *r = s->mods[mh(m)];
|
||||
while (r && r->module != m) r = r->next;
|
||||
pthread_mutex_unlock(&s->lock);
|
||||
return r;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ rewrites */
|
||||
|
||||
/* Finds a standalone Output/Input variable decorated with a builtin; 0 if none. 2 = in a block. */
|
||||
static uint32_t builtin_var(const spv_mod *m, uint32_t builtin, uint32_t storage, int *in_block)
|
||||
{
|
||||
*in_block = 0;
|
||||
for (uint32_t i = 0; i < m->count; i++) {
|
||||
const spv_inst *in = &m->ins[i];
|
||||
if (in->op == SpvOpDecorate && in->w[1] == SpvDecorationBuiltIn && in->w[2] == builtin) {
|
||||
int d = spv_find_def(m, in->w[0]);
|
||||
if (d >= 0 && m->ins[d].op == SpvOpVariable && m->ins[d].w[2] == storage) return in->w[0];
|
||||
}
|
||||
if (in->op == SpvOpMemberDecorate && in->w[2] == SpvDecorationBuiltIn && in->w[3] == builtin) *in_block = 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
static uint32_t var_pointee(const spv_mod *m, uint32_t var)
|
||||
{
|
||||
int d = spv_find_def(m, var);
|
||||
if (d < 0) return 0;
|
||||
int p = spv_find_def(m, m->ins[d].w[0]);
|
||||
return p < 0 ? 0 : m->ins[p].w[2];
|
||||
}
|
||||
|
||||
static void add_decoration(spv_mod *m, uint32_t id, uint32_t dec, uint32_t value)
|
||||
{
|
||||
uint32_t ops[3] = {id, dec, value};
|
||||
spv_insert(m, spv_annotations_end(m), SpvOpDecorate, ops, 3);
|
||||
}
|
||||
|
||||
/* Builtin output -> plain varying at *loc (advanced). Returns the element count, 0 if absent. */
|
||||
static uint32_t demote_builtin(spv_mod *m, uint32_t builtin, uint32_t *loc, int *unsupported)
|
||||
{
|
||||
int in_block;
|
||||
uint32_t var = builtin_var(m, builtin, SpvStorageClassOutput, &in_block);
|
||||
if (!var) {
|
||||
if (in_block) *unsupported = 1;
|
||||
return 0;
|
||||
}
|
||||
uint32_t pointee = var_pointee(m, var);
|
||||
uint32_t n = spv_array_length(m, pointee);
|
||||
if (!n) n = 1;
|
||||
spv_remove_decoration(m, var, SpvDecorationBuiltIn);
|
||||
add_decoration(m, var, SpvDecorationLocation, *loc);
|
||||
*loc += n;
|
||||
return n;
|
||||
}
|
||||
|
||||
/* The pre-rasterization side. Returns the clip distance count (0: none), -1 if it cannot. */
|
||||
static int rewrite_pre_raster(spv_mod *m, uint32_t emu, uint32_t clip_loc, int last_stage)
|
||||
{
|
||||
int unsupported = 0;
|
||||
uint32_t loc = clip_loc;
|
||||
int clip = 0;
|
||||
if ((emu & VKB_EMU_CLIP_DISTANCE) && spv_has_capability(m, SpvCapabilityClipDistance)) {
|
||||
clip = (int)demote_builtin(m, SpvBuiltInClipDistance, &loc, &unsupported);
|
||||
spv_remove_capability(m, SpvCapabilityClipDistance);
|
||||
}
|
||||
if ((emu & VKB_EMU_CULL_DISTANCE) && spv_has_capability(m, SpvCapabilityCullDistance)) {
|
||||
demote_builtin(m, SpvBuiltInCullDistance, &loc, &unsupported);
|
||||
spv_remove_capability(m, SpvCapabilityCullDistance);
|
||||
}
|
||||
int model = spv_execution_model(m);
|
||||
if ((emu & VKB_EMU_POINT_SIZE) && (model == SpvExecutionModelGeometry || model == SpvExecutionModelTessellationEvaluation) &&
|
||||
(spv_has_capability(m, SpvCapabilityGeometryPointSize) || spv_has_capability(m, SpvCapabilityTessellationPointSize))) {
|
||||
demote_builtin(m, SpvBuiltInPointSize, &loc, &unsupported);
|
||||
spv_remove_capability(m, SpvCapabilityGeometryPointSize);
|
||||
spv_remove_capability(m, SpvCapabilityTessellationPointSize);
|
||||
}
|
||||
(void)last_stage;
|
||||
if (unsupported) VKB_ONCE(VKB_LOG_WARN, "emulation: clip/cull distance inside an output block is not handled (logged once)");
|
||||
return unsupported && !clip ? -1 : clip;
|
||||
}
|
||||
|
||||
/* The fragment side: read the distances at `loc` and discard when any is negative. */
|
||||
static int rewrite_fragment(spv_mod *m, uint32_t loc, uint32_t n)
|
||||
{
|
||||
uint32_t f32 = spv_type_float(m, 32);
|
||||
uint32_t len = spv_const_u32(m, n);
|
||||
uint32_t arr = spv_type_array(m, f32, len);
|
||||
uint32_t parr = spv_type_pointer(m, SpvStorageClassInput, arr);
|
||||
uint32_t pf = spv_type_pointer(m, SpvStorageClassInput, f32);
|
||||
uint32_t tbool = spv_type_bool(m);
|
||||
uint32_t zero = spv_const_f32(m, 0.0f);
|
||||
uint32_t idx[16];
|
||||
for (uint32_t i = 0; i < n && i < 16; i++) idx[i] = spv_const_u32(m, i);
|
||||
uint32_t var = spv_new_id(m);
|
||||
uint32_t vops[3] = {parr, var, SpvStorageClassInput};
|
||||
spv_insert(m, spv_types_end(m), SpvOpVariable, vops, 3);
|
||||
add_decoration(m, var, SpvDecorationLocation, loc);
|
||||
spv_add_interface(m, var);
|
||||
|
||||
int ep = spv_find_op(m, SpvOpEntryPoint, 0);
|
||||
if (ep < 0) return -1;
|
||||
uint32_t fn = m->ins[ep].w[1];
|
||||
int fi = -1;
|
||||
for (uint32_t i = 0; i < m->count; i++)
|
||||
if (m->ins[i].op == SpvOpFunction && m->ins[i].w[1] == fn) fi = (int)i;
|
||||
if (fi < 0) return -1;
|
||||
int li = spv_find_op(m, SpvOpLabel, (uint32_t)fi);
|
||||
if (li < 0) return -1;
|
||||
uint32_t first_label = m->ins[li].w[0];
|
||||
uint32_t at = (uint32_t)li + 1;
|
||||
while (at < m->count && (m->ins[at].op == SpvOpVariable || m->ins[at].op == SpvOpLine || m->ins[at].op == SpvOpNoLine)) at++;
|
||||
|
||||
uint32_t any = 0;
|
||||
for (uint32_t i = 0; i < n && i < 16; i++) {
|
||||
uint32_t p = spv_new_id(m), v = spv_new_id(m), lt = spv_new_id(m);
|
||||
uint32_t ac[4] = {pf, p, var, idx[i]};
|
||||
at = spv_insert(m, at, SpvOpAccessChain, ac, 4) + 1;
|
||||
uint32_t ld[3] = {f32, v, p};
|
||||
at = spv_insert(m, at, SpvOpLoad, ld, 3) + 1;
|
||||
uint32_t cmp[4] = {tbool, lt, v, zero};
|
||||
at = spv_insert(m, at, SpvOpFOrdLessThan, cmp, 4) + 1;
|
||||
if (any) {
|
||||
uint32_t o = spv_new_id(m), orr[4] = {tbool, o, any, lt};
|
||||
at = spv_insert(m, at, SpvOpLogicalOr, orr, 4) + 1;
|
||||
any = o;
|
||||
} else {
|
||||
any = lt;
|
||||
}
|
||||
}
|
||||
uint32_t kill = spv_new_id(m), merge = spv_new_id(m);
|
||||
uint32_t sm[2] = {merge, 0};
|
||||
at = spv_insert(m, at, SpvOpSelectionMerge, sm, 2) + 1;
|
||||
uint32_t bc[3] = {any, kill, merge};
|
||||
at = spv_insert(m, at, SpvOpBranchConditional, bc, 3) + 1;
|
||||
at = spv_insert(m, at, SpvOpLabel, &kill, 1) + 1;
|
||||
at = spv_insert(m, at, spv_version(m) >= 0x00010600 ? SpvOpTerminateInvocation : SpvOpKill, NULL, 0) + 1;
|
||||
at = spv_insert(m, at, SpvOpLabel, &merge, 1) + 1;
|
||||
/* Phis that named the old entry block as a predecessor now come from the merge block. */
|
||||
for (uint32_t i = at; i < m->count; i++) {
|
||||
spv_inst *in = &m->ins[i];
|
||||
if (in->op != 245 /* OpPhi */) continue;
|
||||
for (uint32_t k = 3; k < (uint32_t)in->n - 1; k += 2)
|
||||
if (in->w[k] == first_label) in->w[k] = merge;
|
||||
}
|
||||
return m->err ? -1 : 0;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ module store */
|
||||
|
||||
static VkResult make_module(VkDevice device, const spv_mod *m, VkShaderModule *out)
|
||||
{
|
||||
uint32_t *code;
|
||||
size_t size = spv_write(m, &code);
|
||||
if (!size) return VK_ERROR_OUT_OF_HOST_MEMORY;
|
||||
const char *dump = getenv("VKBRIDGE_DUMP_SPIRV");
|
||||
if (dump && *dump) {
|
||||
static int seq;
|
||||
char path[512];
|
||||
snprintf(path, sizeof(path), "%s/vkbridge-%d-%d.spv", dump, (int)getpid(), __atomic_fetch_add(&seq, 1, __ATOMIC_RELAXED));
|
||||
FILE *f = fopen(path, "wb");
|
||||
if (f) {
|
||||
fwrite(code, 1, size, f);
|
||||
fclose(f);
|
||||
}
|
||||
}
|
||||
VkShaderModuleCreateInfo ci = {VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO, NULL, 0, size, code};
|
||||
VkResult r = vkb_emu_real()->vkCreateShaderModule(device, &ci, NULL, out);
|
||||
free(code);
|
||||
return r;
|
||||
}
|
||||
|
||||
static VKAPI_ATTR VkResult VKAPI_CALL emu_CreateShaderModule(VkDevice device, const VkShaderModuleCreateInfo *ci,
|
||||
const VkAllocationCallbacks *pAllocator, VkShaderModule *pModule)
|
||||
{
|
||||
vkb_emu_device *e = vkb_emu_cur();
|
||||
spv_mod m;
|
||||
VkResult r;
|
||||
int needs = 0;
|
||||
if (spv_parse(&m, ci->pCode, ci->codeSize) == 0) {
|
||||
needs = spv_has_capability(&m, SpvCapabilityClipDistance) || spv_has_capability(&m, SpvCapabilityCullDistance) ||
|
||||
spv_has_capability(&m, SpvCapabilityGeometryPointSize) || spv_has_capability(&m, SpvCapabilityTessellationPointSize);
|
||||
}
|
||||
if (needs) {
|
||||
/* The driver's module must not ask for what it lacks; pipelines use rewritten variants. */
|
||||
int maxo = spv_max_location(&m, SpvStorageClassOutput);
|
||||
rewrite_pre_raster(&m, e->flags, (uint32_t)(maxo + 1), 1);
|
||||
r = make_module(device, &m, pModule);
|
||||
} else {
|
||||
r = vkb_emu_real()->vkCreateShaderModule(device, ci, pAllocator, pModule);
|
||||
}
|
||||
spv_free(&m);
|
||||
if (r != VK_SUCCESS) return r;
|
||||
shader_rec *rec = calloc(1, sizeof(*rec));
|
||||
rec->module = *pModule;
|
||||
rec->size = ci->codeSize;
|
||||
rec->code = malloc(ci->codeSize);
|
||||
memcpy(rec->code, ci->pCode, ci->codeSize);
|
||||
shader_state *s = state(e);
|
||||
pthread_mutex_lock(&s->lock);
|
||||
unsigned h = mh(*pModule);
|
||||
rec->next = s->mods[h];
|
||||
s->mods[h] = rec;
|
||||
pthread_mutex_unlock(&s->lock);
|
||||
return r;
|
||||
}
|
||||
|
||||
static VKAPI_ATTR void VKAPI_CALL emu_DestroyShaderModule(VkDevice device, VkShaderModule module, const VkAllocationCallbacks *pAllocator)
|
||||
{
|
||||
vkb_emu_device *e = vkb_emu_cur();
|
||||
if (module) {
|
||||
shader_state *s = state(e);
|
||||
pthread_mutex_lock(&s->lock);
|
||||
shader_rec **pp = &s->mods[mh(module)];
|
||||
while (*pp && (*pp)->module != module) pp = &(*pp)->next;
|
||||
shader_rec *r = *pp;
|
||||
if (r) *pp = r->next;
|
||||
pthread_mutex_unlock(&s->lock);
|
||||
if (r) {
|
||||
free(r->code);
|
||||
free(r);
|
||||
}
|
||||
}
|
||||
vkb_emu_real()->vkDestroyShaderModule(device, module, pAllocator);
|
||||
}
|
||||
|
||||
/* The SPIR-V of a stage: its module's (kept here) or the inline VkShaderModuleCreateInfo's. */
|
||||
static int stage_code(vkb_emu_device *e, const VkPipelineShaderStageCreateInfo *st, const uint32_t **code, size_t *size)
|
||||
{
|
||||
if (st->module) {
|
||||
const shader_rec *r = find_module(e, st->module);
|
||||
if (!r) return 0;
|
||||
*code = r->code;
|
||||
*size = r->size;
|
||||
return 1;
|
||||
}
|
||||
for (const VkBaseInStructure *b = st->pNext; b; b = b->pNext) {
|
||||
if (b->sType == VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO) {
|
||||
*code = ((const VkShaderModuleCreateInfo *)b)->pCode;
|
||||
*size = ((const VkShaderModuleCreateInfo *)b)->codeSize;
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* Replace a stage's shader by a rewritten module (recorded for destruction after the call). */
|
||||
static void set_stage_module(VkDevice device, VkPipelineShaderStageCreateInfo *st, const spv_mod *m, VkShaderModule *mods,
|
||||
uint32_t *nmods, uint32_t cap)
|
||||
{
|
||||
VkShaderModule mod;
|
||||
if (*nmods >= cap || make_module(device, m, &mod) != VK_SUCCESS) return;
|
||||
mods[(*nmods)++] = mod;
|
||||
st->module = mod;
|
||||
vkb_emu_chain_take(st, VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO);
|
||||
}
|
||||
|
||||
void vkb_emu_shader_pipeline(vkb_emu_device *e, VkDevice device, VkGraphicsPipelineCreateInfo *ci, VkShaderModule *mods,
|
||||
uint32_t *nmods, uint32_t cap)
|
||||
{
|
||||
if (!(e->flags & SHADER_EMU) || !ci->pStages) return;
|
||||
VkPipelineShaderStageCreateInfo *pre = NULL, *frag = NULL;
|
||||
int pre_rank = -1;
|
||||
for (uint32_t s = 0; s < ci->stageCount; s++) {
|
||||
VkPipelineShaderStageCreateInfo *st = (VkPipelineShaderStageCreateInfo *)&ci->pStages[s];
|
||||
int rank = st->stage == VK_SHADER_STAGE_VERTEX_BIT ? 0 : st->stage == VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT ? 1
|
||||
: st->stage == VK_SHADER_STAGE_GEOMETRY_BIT ? 2 : -1;
|
||||
if (rank > pre_rank) {
|
||||
pre_rank = rank;
|
||||
pre = st;
|
||||
}
|
||||
if (st->stage == VK_SHADER_STAGE_FRAGMENT_BIT) frag = st;
|
||||
}
|
||||
if (!pre) return;
|
||||
const uint32_t *code;
|
||||
size_t size;
|
||||
if (!stage_code(e, pre, &code, &size)) return;
|
||||
spv_mod pm;
|
||||
if (spv_parse(&pm, code, size) != 0) return;
|
||||
if (!spv_has_capability(&pm, SpvCapabilityClipDistance) && !spv_has_capability(&pm, SpvCapabilityCullDistance) &&
|
||||
!spv_has_capability(&pm, SpvCapabilityGeometryPointSize) && !spv_has_capability(&pm, SpvCapabilityTessellationPointSize)) {
|
||||
spv_free(&pm);
|
||||
return;
|
||||
}
|
||||
spv_mod fm;
|
||||
int have_frag = 0;
|
||||
const uint32_t *fcode;
|
||||
size_t fsize;
|
||||
if (frag && stage_code(e, frag, &fcode, &fsize) && spv_parse(&fm, fcode, fsize) == 0) have_frag = 1;
|
||||
int loc = spv_max_location(&pm, SpvStorageClassOutput);
|
||||
if (have_frag) {
|
||||
int fl = spv_max_location(&fm, SpvStorageClassInput);
|
||||
if (fl > loc) loc = fl;
|
||||
}
|
||||
int clip = rewrite_pre_raster(&pm, e->flags, (uint32_t)(loc + 1), 1);
|
||||
if (clip >= 0) set_stage_module(device, pre, &pm, mods, nmods, cap);
|
||||
if (clip > 0) {
|
||||
if (have_frag) {
|
||||
if (rewrite_fragment(&fm, (uint32_t)(loc + 1), (uint32_t)clip) == 0) set_stage_module(device, frag, &fm, mods, nmods, cap);
|
||||
} else {
|
||||
VKB_ONCE(VKB_LOG_WARN, "emulation: clip distances in a pipeline without a fragment shader are not applied (logged once)");
|
||||
}
|
||||
}
|
||||
VKB_DBG("emulation: pipeline with %d clip distance(s) rewritten at location %d", clip, loc + 1);
|
||||
spv_free(&pm);
|
||||
if (have_frag) spv_free(&fm);
|
||||
}
|
||||
|
||||
/* A vertex shader that reads BaseInstance as 0 (divisor emulation splits draws, which moves
|
||||
* BaseInstance; DXVK derives SV_InstanceID from it). VK_NULL_HANDLE when the shader never reads it. */
|
||||
VkShaderModule vkb_emu_shader_zero_base_instance(vkb_emu_device *e, VkDevice device, const VkPipelineShaderStageCreateInfo *vs)
|
||||
{
|
||||
const uint32_t *code;
|
||||
size_t size;
|
||||
if (!e->shaders || !stage_code(e, vs, &code, &size)) return VK_NULL_HANDLE;
|
||||
spv_mod m;
|
||||
if (spv_parse(&m, code, size) != 0) return VK_NULL_HANDLE;
|
||||
int in_block;
|
||||
uint32_t var = builtin_var(&m, SpvBuiltInBaseInstance, SpvStorageClassInput, &in_block);
|
||||
VkShaderModule out = VK_NULL_HANDLE;
|
||||
if (var) {
|
||||
int d = spv_find_def(&m, var);
|
||||
int p = d >= 0 ? spv_find_def(&m, m.ins[d].w[0]) : -1;
|
||||
uint32_t type = p >= 0 ? m.ins[p].w[2] : 0;
|
||||
int td = spv_find_def(&m, type);
|
||||
uint32_t zero = 0;
|
||||
if (td >= 0 && m.ins[td].op == SpvOpTypeInt) {
|
||||
zero = spv_new_id(&m);
|
||||
uint32_t ops[3] = {type, zero, 0};
|
||||
spv_insert(&m, spv_types_end(&m), SpvOpConstant, ops, 3);
|
||||
}
|
||||
int changed = 0;
|
||||
for (uint32_t i = 0; zero && i < m.count; i++) {
|
||||
spv_inst *in = &m.ins[i];
|
||||
if (in->op == SpvOpLoad && in->w[2] == var) {
|
||||
/* %r = OpLoad %int %BaseInstance -> %r = OpCopyObject %int %zero */
|
||||
in->op = 83; /* OpCopyObject */
|
||||
in->w[2] = zero;
|
||||
in->n = 4;
|
||||
changed = 1;
|
||||
}
|
||||
}
|
||||
if (changed) make_module(device, &m, &out);
|
||||
}
|
||||
spv_free(&m);
|
||||
return out;
|
||||
}
|
||||
|
||||
void vkb_emu_shader_install(vkb_srv_table *dev)
|
||||
{
|
||||
vkb_emu_device *e = dev->emu;
|
||||
if (!(e->flags & SHADER_STORE)) return;
|
||||
shader_state *s = calloc(1, sizeof(*s));
|
||||
pthread_mutex_init(&s->lock, NULL);
|
||||
e->shaders = s;
|
||||
dev->dt.vkCreateShaderModule = emu_CreateShaderModule;
|
||||
dev->dt.vkDestroyShaderModule = emu_DestroyShaderModule;
|
||||
}
|
||||
|
||||
void vkb_emu_shader_uninstall(vkb_srv_table *dev)
|
||||
{
|
||||
shader_state *s = dev->emu->shaders;
|
||||
if (!s) return;
|
||||
for (int i = 0; i < 1024; i++) {
|
||||
while (s->mods[i]) {
|
||||
shader_rec *r = s->mods[i];
|
||||
s->mods[i] = r->next;
|
||||
free(r->code);
|
||||
free(r);
|
||||
}
|
||||
}
|
||||
pthread_mutex_destroy(&s->lock);
|
||||
free(s);
|
||||
dev->emu->shaders = NULL;
|
||||
}
|
||||
@@ -0,0 +1,356 @@
|
||||
/* SPDX-License-Identifier: GPL-3.0-or-later
|
||||
*
|
||||
* Instances, devices and the startup self-test.
|
||||
*/
|
||||
#define _GNU_SOURCE
|
||||
#include "vkb_server.h"
|
||||
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
vkb_pd_knowledge vkb_pds[VKB_MAX_PDS];
|
||||
int vkb_npds;
|
||||
|
||||
static int has_ext(const VkExtensionProperties *e, uint32_t n, const char *name)
|
||||
{
|
||||
for (uint32_t i = 0; i < n; i++)
|
||||
if (!strcmp(e[i].extensionName, name)) return 1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
const vkb_pd_knowledge *vkb_pd_lookup(const vkb_dispatch *dt, VkPhysicalDevice pd)
|
||||
{
|
||||
VkPhysicalDeviceIDProperties id = {VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ID_PROPERTIES};
|
||||
VkPhysicalDeviceProperties2 p2 = {VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &id};
|
||||
if (!dt->vkGetPhysicalDeviceProperties2) return NULL;
|
||||
dt->vkGetPhysicalDeviceProperties2(pd, &p2);
|
||||
for (int i = 0; i < vkb_npds; i++)
|
||||
if (vkb_pds[i].valid && !memcmp(vkb_pds[i].uuid, id.deviceUUID, VK_UUID_SIZE)) return &vkb_pds[i];
|
||||
return NULL;
|
||||
}
|
||||
|
||||
/* What the self-test found, for a later session's log (the in-app server tests once). */
|
||||
void vkb_log_summary(void)
|
||||
{
|
||||
for (int i = 0; i < vkb_npds; i++) {
|
||||
const vkb_pd_knowledge *k = &vkb_pds[i];
|
||||
if (k->valid)
|
||||
VKB_INFO("%s: memory sharing = %s, missing 0x%x, emulating 0x%x (from the first session's self-test)", k->name,
|
||||
vkb_mem_strategy_name(k->info.strategy), k->info.missing, k->info.emu);
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ startup self-test */
|
||||
|
||||
static void log_device(const vkb_dispatch *dt, VkPhysicalDevice pd, const VkPhysicalDeviceProperties *p)
|
||||
{
|
||||
VKB_INFO("GPU: %s (vendor 0x%04x device 0x%04x, Vulkan %u.%u.%u, driver 0x%08x)", p->deviceName,
|
||||
p->vendorID, p->deviceID, VK_API_VERSION_MAJOR(p->apiVersion), VK_API_VERSION_MINOR(p->apiVersion),
|
||||
VK_API_VERSION_PATCH(p->apiVersion), p->driverVersion);
|
||||
VkPhysicalDeviceFeatures f;
|
||||
dt->vkGetPhysicalDeviceFeatures(pd, &f);
|
||||
#define F(x) #x, f.x
|
||||
VKB_INFO("features: %s=%u %s=%u %s=%u %s=%u %s=%u %s=%u %s=%u %s=%u", F(textureCompressionBC), F(shaderClipDistance),
|
||||
F(shaderCullDistance), F(geometryShader), F(tessellationShader), F(depthClamp), F(shaderFloat64), F(shaderInt64));
|
||||
VKB_INFO("features: %s=%u %s=%u %s=%u %s=%u %s=%u %s=%u %s=%u %s=%u", F(multiViewport), F(independentBlend), F(logicOp),
|
||||
F(fillModeNonSolid), F(dualSrcBlend), F(sampleRateShading), F(depthBiasClamp), F(wideLines));
|
||||
VKB_INFO("features: %s=%u %s=%u %s=%u %s=%u %s=%u %s=%u %s=%u %s=%u", F(drawIndirectFirstInstance), F(multiDrawIndirect),
|
||||
F(occlusionQueryPrecise), F(pipelineStatisticsQuery), F(vertexPipelineStoresAndAtomics),
|
||||
F(fragmentStoresAndAtomics), F(shaderStorageImageWriteWithoutFormat), F(imageCubeArray));
|
||||
VKB_INFO("features: %s=%u %s=%u %s=%u %s=%u %s=%u %s=%u", F(robustBufferAccess), F(fullDrawIndexUint32), F(samplerAnisotropy),
|
||||
F(depthBounds), F(largePoints), F(shaderStorageImageExtendedFormats));
|
||||
#undef F
|
||||
uint32_t n = 0;
|
||||
dt->vkEnumerateDeviceExtensionProperties(pd, NULL, &n, NULL);
|
||||
VkExtensionProperties *e = calloc(n ? n : 1, sizeof(*e));
|
||||
dt->vkEnumerateDeviceExtensionProperties(pd, NULL, &n, e);
|
||||
static const char *const watch[] = {
|
||||
"VK_EXT_depth_clip_enable", "VK_EXT_vertex_attribute_divisor", "VK_KHR_vertex_attribute_divisor",
|
||||
"VK_EXT_external_memory_dma_buf", "VK_EXT_image_drm_format_modifier", "VK_KHR_external_memory_fd",
|
||||
"VK_EXT_external_memory_host", "VK_ANDROID_external_memory_android_hardware_buffer",
|
||||
"VK_KHR_external_semaphore_fd", "VK_KHR_external_fence_fd", "VK_EXT_queue_family_foreign",
|
||||
"VK_EXT_robustness2", "VK_EXT_transform_feedback", "VK_EXT_custom_border_color",
|
||||
"VK_EXT_mutable_descriptor_type", "VK_VALVE_mutable_descriptor_type", "VK_EXT_extended_dynamic_state3",
|
||||
"VK_EXT_graphics_pipeline_library", "VK_EXT_physical_device_drm", "VK_KHR_push_descriptor",
|
||||
"VK_EXT_descriptor_indexing", "VK_KHR_timeline_semaphore", "VK_EXT_memory_budget",
|
||||
"VK_KHR_maintenance5", "VK_EXT_line_rasterization", "VK_EXT_provoking_vertex",
|
||||
};
|
||||
char line[1024];
|
||||
size_t len = 0;
|
||||
line[0] = 0;
|
||||
for (size_t i = 0; i < sizeof(watch) / sizeof(watch[0]); i++) {
|
||||
int ok = has_ext(e, n, watch[i]);
|
||||
len += (size_t)snprintf(line + len, sizeof(line) - len, "%s%s%s", len ? " " : "", ok ? "+" : "-", watch[i] + 3);
|
||||
if (len > 700 || i + 1 == sizeof(watch) / sizeof(watch[0])) {
|
||||
VKB_INFO("extensions: %s", line);
|
||||
len = 0;
|
||||
line[0] = 0;
|
||||
}
|
||||
}
|
||||
VKB_INFO("%u device extensions in total", n);
|
||||
/* All of them, until the device runs show which ones the server's process sees (it is not an
|
||||
* app process, and saw fewer than the capability viewer on the same tablet). */
|
||||
len = 0;
|
||||
line[0] = 0;
|
||||
for (uint32_t i = 0; i < n; i++) {
|
||||
len += (size_t)snprintf(line + len, sizeof(line) - len, "%s%s:%u", len ? " " : "", e[i].extensionName + 3, e[i].specVersion);
|
||||
if (len > 700 || i + 1 == n) {
|
||||
VKB_INFO(" all: %s", line);
|
||||
len = 0;
|
||||
line[0] = 0;
|
||||
}
|
||||
}
|
||||
free(e);
|
||||
VkPhysicalDeviceMemoryProperties mp;
|
||||
dt->vkGetPhysicalDeviceMemoryProperties(pd, &mp);
|
||||
for (uint32_t i = 0; i < mp.memoryHeapCount; i++)
|
||||
VKB_INFO("memory heap %u: %llu MB flags 0x%x", i, (unsigned long long)(mp.memoryHeaps[i].size >> 20), mp.memoryHeaps[i].flags);
|
||||
for (uint32_t i = 0; i < mp.memoryTypeCount; i++)
|
||||
VKB_INFO("memory type %u: heap %u flags 0x%x", i, mp.memoryTypes[i].heapIndex, mp.memoryTypes[i].propertyFlags);
|
||||
}
|
||||
|
||||
void vkb_selftest_all(void)
|
||||
{
|
||||
uint32_t api = VK_API_VERSION_1_0;
|
||||
if (vkb_global_dt.vkEnumerateInstanceVersion) vkb_global_dt.vkEnumerateInstanceVersion(&api);
|
||||
if (api > VK_API_VERSION_1_3) api = VK_API_VERSION_1_3;
|
||||
VkApplicationInfo app = {VK_STRUCTURE_TYPE_APPLICATION_INFO, NULL, "vkbridge-selftest", 1, "vkbridge", 1, api};
|
||||
VkInstanceCreateInfo ci = {VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO, NULL, 0, &app, 0, NULL, 0, NULL};
|
||||
VkInstance inst;
|
||||
VkResult r = vkb_global_dt.vkCreateInstance(&ci, NULL, &inst);
|
||||
if (r != VK_SUCCESS) {
|
||||
VKB_ERR("self-test: vkCreateInstance failed (%d); the driver is unusable", r);
|
||||
return;
|
||||
}
|
||||
vkb_dispatch dt;
|
||||
vkb_dispatch_load_instance(&dt, vkb_gipa, inst);
|
||||
uint32_t n = 0;
|
||||
dt.vkEnumeratePhysicalDevices(inst, &n, NULL);
|
||||
if (n > VKB_MAX_PDS) n = VKB_MAX_PDS;
|
||||
VkPhysicalDevice pds[VKB_MAX_PDS];
|
||||
dt.vkEnumeratePhysicalDevices(inst, &n, pds);
|
||||
VKB_INFO("self-test: loader Vulkan %u.%u, %u physical device(s)", VK_API_VERSION_MAJOR(api), VK_API_VERSION_MINOR(api), n);
|
||||
for (uint32_t i = 0; i < n; i++) {
|
||||
VkPhysicalDeviceIDProperties id = {VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ID_PROPERTIES};
|
||||
VkPhysicalDeviceProperties2 p2 = {VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &id};
|
||||
dt.vkGetPhysicalDeviceProperties2(pds[i], &p2);
|
||||
log_device(&dt, pds[i], &p2.properties);
|
||||
vkb_pd_knowledge *k = &vkb_pds[vkb_npds++];
|
||||
memcpy(k->uuid, id.deviceUUID, VK_UUID_SIZE);
|
||||
snprintf(k->name, sizeof(k->name), "%s", p2.properties.deviceName);
|
||||
k->info.real_api_version = p2.properties.apiVersion;
|
||||
vkb_mem_selftest(k, inst, &dt, pds[i]);
|
||||
k->info.emu_available = vkb_emu_detect(&dt, pds[i], &k->info.missing);
|
||||
k->info.emu = k->info.emu_available;
|
||||
const char *emu_env = getenv("VKBRIDGE_EMULATE");
|
||||
if (emu_env && !strcmp(emu_env, "0")) k->info.emu = 0;
|
||||
k->valid = 1;
|
||||
VKB_INFO("%s: memory sharing = %s, missing 0x%x, emulating 0x%x", k->name, vkb_mem_strategy_name(k->info.strategy),
|
||||
k->info.missing, k->info.emu);
|
||||
}
|
||||
dt.vkDestroyInstance(inst, NULL);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ instance */
|
||||
|
||||
void vkb_sv_vkCreateInstance(vkb_srv_call *c)
|
||||
{
|
||||
VkInstanceCreateInfo *ci = NULL;
|
||||
if (vkb_dec_u8(&c->d)) {
|
||||
ci = vkb_dec_alloc(&c->d, sizeof(*ci));
|
||||
if (ci) vkb_dec_VkInstanceCreateInfo(&c->d, ci);
|
||||
}
|
||||
uint8_t want_out = vkb_dec_u8(&c->d);
|
||||
if (c->d.err || !ci || !want_out) {
|
||||
vkb_srv_bad_message(c);
|
||||
return;
|
||||
}
|
||||
VkInstance inst = VK_NULL_HANDLE;
|
||||
VkResult r = vkb_global_dt.vkCreateInstance(ci, NULL, &inst);
|
||||
uint32_t id = 0;
|
||||
if (r == VK_SUCCESS) {
|
||||
vkb_srv_table *t = calloc(1, sizeof(*t));
|
||||
pthread_mutex_init(&t->lock, NULL);
|
||||
t->instance = inst;
|
||||
t->proc = c->conn->proc;
|
||||
t->api_version = ci->pApplicationInfo ? ci->pApplicationInfo->apiVersion : VK_API_VERSION_1_0;
|
||||
vkb_dispatch_load_instance(&t->real, vkb_gipa, inst);
|
||||
t->dt = t->real;
|
||||
id = vkb_table_register(t);
|
||||
if (!id) {
|
||||
t->real.vkDestroyInstance(inst, NULL);
|
||||
free(t);
|
||||
r = VK_ERROR_OUT_OF_HOST_MEMORY;
|
||||
inst = VK_NULL_HANDLE;
|
||||
} else {
|
||||
VKB_INFO("instance %u created (app \"%s\", engine \"%s\", Vulkan %u.%u)", id,
|
||||
ci->pApplicationInfo && ci->pApplicationInfo->pApplicationName ? ci->pApplicationInfo->pApplicationName : "",
|
||||
ci->pApplicationInfo && ci->pApplicationInfo->pEngineName ? ci->pApplicationInfo->pEngineName : "",
|
||||
VK_API_VERSION_MAJOR(t->api_version), VK_API_VERSION_MINOR(t->api_version));
|
||||
}
|
||||
} else {
|
||||
VKB_ERR("vkCreateInstance failed: %d", r);
|
||||
}
|
||||
vkb_enc_u32(&c->r, (uint32_t)r);
|
||||
vkb_enc_u64(&c->r, (uint64_t)(uintptr_t)inst);
|
||||
vkb_enc_u32(&c->r, id);
|
||||
}
|
||||
|
||||
void vkb_sv_vkDestroyInstance(vkb_srv_call *c)
|
||||
{
|
||||
VkInstance inst = (VkInstance)(uintptr_t)vkb_dec_u64(&c->d);
|
||||
vkb_srv_table *t = c->table;
|
||||
if (!t || t->is_device || t->instance != inst) {
|
||||
vkb_srv_bad_message(c);
|
||||
return;
|
||||
}
|
||||
vkb_table_unregister(t);
|
||||
t->real.vkDestroyInstance(inst, NULL);
|
||||
pthread_mutex_destroy(&t->lock);
|
||||
free(t);
|
||||
c->table = NULL;
|
||||
}
|
||||
|
||||
void vkb_sv_vkbQueryServer(vkb_srv_call *c)
|
||||
{
|
||||
VkPhysicalDevice pd = (VkPhysicalDevice)(uintptr_t)vkb_dec_u64(&c->d);
|
||||
if (c->d.err || !c->table) {
|
||||
vkb_srv_bad_message(c);
|
||||
return;
|
||||
}
|
||||
const vkb_pd_knowledge *k = vkb_pd_lookup(c->dt, pd);
|
||||
vkb_server_pd_info info;
|
||||
memset(&info, 0, sizeof(info));
|
||||
if (k) info = k->info;
|
||||
else VKB_WARN("query for a physical device the self-test did not see");
|
||||
vkb_enc_raw(&c->r, &info, sizeof(info));
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ device */
|
||||
|
||||
static int list_has(const char *const *l, uint32_t n, const char *s)
|
||||
{
|
||||
for (uint32_t i = 0; i < n; i++)
|
||||
if (l[i] && !strcmp(l[i], s)) return 1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
void vkb_sv_vkCreateDevice(vkb_srv_call *c)
|
||||
{
|
||||
VkPhysicalDevice pd = (VkPhysicalDevice)(uintptr_t)vkb_dec_u64(&c->d);
|
||||
VkDeviceCreateInfo *ci = NULL;
|
||||
if (vkb_dec_u8(&c->d)) {
|
||||
ci = vkb_dec_alloc(&c->d, sizeof(*ci));
|
||||
if (ci) vkb_dec_VkDeviceCreateInfo(&c->d, ci);
|
||||
}
|
||||
uint8_t want_out = vkb_dec_u8(&c->d);
|
||||
vkb_srv_table *inst = c->table;
|
||||
if (c->d.err || !ci || !want_out || !inst || inst->is_device) {
|
||||
vkb_srv_bad_message(c);
|
||||
return;
|
||||
}
|
||||
const vkb_pd_knowledge *k = vkb_pd_lookup(&inst->real, pd);
|
||||
uint32_t strategy = k ? k->info.strategy : VKB_MEM_NONE;
|
||||
uint32_t emu = k ? k->info.emu : 0;
|
||||
|
||||
/* Extensions the server itself needs (memory sharing), when the driver has them. */
|
||||
uint32_t avail_n = 0;
|
||||
inst->real.vkEnumerateDeviceExtensionProperties(pd, NULL, &avail_n, NULL);
|
||||
VkExtensionProperties *avail = vkb_dec_alloc(&c->d, (avail_n ? avail_n : 1) * sizeof(*avail));
|
||||
inst->real.vkEnumerateDeviceExtensionProperties(pd, NULL, &avail_n, avail);
|
||||
uint32_t extra_n = 0;
|
||||
const char *const *extra = vkb_mem_required_extensions(strategy, &extra_n);
|
||||
const char **exts = vkb_dec_alloc(&c->d, (ci->enabledExtensionCount + extra_n + 10) * sizeof(char *));
|
||||
uint32_t n = 0;
|
||||
for (uint32_t i = 0; i < ci->enabledExtensionCount; i++) {
|
||||
const char *e = ci->ppEnabledExtensionNames[i];
|
||||
if (!has_ext(avail, avail_n, e)) {
|
||||
VKB_DBG("device extension %s is emulated or client-side; not passed to the driver", e);
|
||||
continue;
|
||||
}
|
||||
exts[n++] = e;
|
||||
}
|
||||
for (uint32_t i = 0; i < extra_n; i++)
|
||||
if (has_ext(avail, avail_n, extra[i]) && !list_has(exts, n, extra[i])) exts[n++] = extra[i];
|
||||
/* What the client's presentation code uses on every device (dma-buf swapchains, sync fds). */
|
||||
static const char *const wsi_exts[] = {
|
||||
"VK_KHR_external_memory_fd", "VK_EXT_external_memory_dma_buf", "VK_KHR_image_format_list",
|
||||
"VK_EXT_image_drm_format_modifier", "VK_KHR_external_semaphore_fd", "VK_KHR_external_fence_fd",
|
||||
};
|
||||
for (size_t i = 0; i < sizeof(wsi_exts) / sizeof(wsi_exts[0]); i++)
|
||||
if (has_ext(avail, avail_n, wsi_exts[i]) && !list_has(exts, n, wsi_exts[i])) exts[n++] = wsi_exts[i];
|
||||
/* The BC decoder binds its buffer and image with push descriptors. */
|
||||
if ((emu & VKB_EMU_BCN) && has_ext(avail, avail_n, "VK_KHR_push_descriptor") && !list_has(exts, n, "VK_KHR_push_descriptor"))
|
||||
exts[n++] = "VK_KHR_push_descriptor";
|
||||
ci->enabledExtensionCount = n;
|
||||
ci->ppEnabledExtensionNames = exts;
|
||||
ci->enabledLayerCount = 0;
|
||||
ci->ppEnabledLayerNames = NULL;
|
||||
|
||||
vkb_emu_device_create_info(inst, pd, emu, ci, c->d.arena);
|
||||
|
||||
VkDevice dev = VK_NULL_HANDLE;
|
||||
VkResult r = inst->real.vkCreateDevice(pd, ci, NULL, &dev);
|
||||
uint32_t id = 0;
|
||||
if (r == VK_SUCCESS) {
|
||||
vkb_srv_table *t = calloc(1, sizeof(*t));
|
||||
pthread_mutex_init(&t->lock, NULL);
|
||||
t->is_device = 1;
|
||||
t->proc = c->conn->proc;
|
||||
t->instance = inst->instance;
|
||||
t->device = dev;
|
||||
t->physical = pd;
|
||||
t->parent = inst;
|
||||
t->pd = k;
|
||||
t->api_version = inst->api_version;
|
||||
t->real = inst->real;
|
||||
PFN_vkGetDeviceProcAddr gdpa = (PFN_vkGetDeviceProcAddr)vkb_gipa(inst->instance, "vkGetDeviceProcAddr");
|
||||
vkb_dispatch_load_device(&t->real, gdpa, dev);
|
||||
t->dt = t->real;
|
||||
id = vkb_table_register(t);
|
||||
if (!id) {
|
||||
t->real.vkDestroyDevice(dev, NULL);
|
||||
free(t);
|
||||
dev = VK_NULL_HANDLE;
|
||||
r = VK_ERROR_OUT_OF_HOST_MEMORY;
|
||||
} else {
|
||||
vkb_emu_device_init(t, emu);
|
||||
vkb_pcache_device_init(t);
|
||||
vkb_dsmap_device_init(t);
|
||||
vkb_spvfix_device_init(t);
|
||||
vkb_cbtrack_device_init(t); /* last: it wraps what the others installed */
|
||||
VKB_INFO("device %u created on %s (%u extensions, memory sharing %s)", id, k ? k->name : "?", n,
|
||||
vkb_mem_strategy_name(strategy));
|
||||
for (uint32_t i = 0; i < n; i++) VKB_DBG(" device extension %s", exts[i]);
|
||||
}
|
||||
} else {
|
||||
VKB_ERR("vkCreateDevice failed: %d (%u extensions)", r, n);
|
||||
for (uint32_t i = 0; i < n; i++) VKB_ERR(" requested %s", exts[i]);
|
||||
}
|
||||
vkb_enc_u32(&c->r, (uint32_t)r);
|
||||
vkb_enc_u64(&c->r, (uint64_t)(uintptr_t)dev);
|
||||
vkb_enc_u32(&c->r, id);
|
||||
}
|
||||
|
||||
void vkb_sv_vkDestroyDevice(vkb_srv_call *c)
|
||||
{
|
||||
VkDevice dev = (VkDevice)(uintptr_t)vkb_dec_u64(&c->d);
|
||||
vkb_srv_table *t = c->table;
|
||||
if (!t || !t->is_device || t->device != dev) {
|
||||
vkb_srv_bad_message(c);
|
||||
return;
|
||||
}
|
||||
vkb_table_unregister(t);
|
||||
vkb_cbtrack_device_destroy(t);
|
||||
vkb_spvfix_device_destroy(t);
|
||||
vkb_dsmap_device_destroy(t);
|
||||
vkb_pcache_device_destroy(t);
|
||||
vkb_emu_device_destroy(t);
|
||||
vkb_mem_free_all(t);
|
||||
t->real.vkDestroyDevice(dev, NULL);
|
||||
VKB_INFO("device %u destroyed", t->id);
|
||||
pthread_mutex_destroy(&t->lock);
|
||||
free(t);
|
||||
c->table = NULL;
|
||||
}
|
||||
@@ -0,0 +1,329 @@
|
||||
/* SPDX-License-Identifier: GPL-3.0-or-later
|
||||
*
|
||||
* vkbridge server entry point.
|
||||
*
|
||||
* libvkbridge_server.so --socket <path> [--log <file>] [--vulkan <libvulkan>] [--cache-dir <dir>] [--selftest]
|
||||
*
|
||||
* Packaged as a "library" so Android extracts it into the native library directory, from where
|
||||
* the app executes it like proot. It loads the system Vulkan loader (on the device: the vendor's
|
||||
* Mali driver behind /system/lib64/libvulkan.so), runs a self-test that decides how mapped memory
|
||||
* is shared with the Linux side, then serves the session's Vulkan calls until it is killed or its
|
||||
* parent dies.
|
||||
*/
|
||||
#define _GNU_SOURCE
|
||||
#include "vkb_server.h"
|
||||
|
||||
#include <dlfcn.h>
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <signal.h>
|
||||
#include <stdarg.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/prctl.h>
|
||||
#include <sys/socket.h>
|
||||
#include <sys/stat.h>
|
||||
#include <sys/un.h>
|
||||
#include <time.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#ifdef __ANDROID__
|
||||
#include <android/log.h>
|
||||
#elif defined(__GLIBC__)
|
||||
#include <execinfo.h>
|
||||
#endif
|
||||
|
||||
PFN_vkGetInstanceProcAddr vkb_gipa;
|
||||
vkb_dispatch vkb_global_dt;
|
||||
int vkb_verbose;
|
||||
|
||||
static FILE *log_file;
|
||||
static int log_level = VKB_LOG_INFO;
|
||||
static pthread_mutex_t log_lock = PTHREAD_MUTEX_INITIALIZER;
|
||||
|
||||
int vkb_log_level(void) { return log_level; }
|
||||
|
||||
void vkb_log(int level, const char *fmt, ...)
|
||||
{
|
||||
if (level > log_level) return;
|
||||
char msg[2048];
|
||||
va_list ap;
|
||||
va_start(ap, fmt);
|
||||
vsnprintf(msg, sizeof(msg), fmt, ap);
|
||||
va_end(ap);
|
||||
static const char *const tags[] = {"E", "W", "I", "D"};
|
||||
struct timespec ts;
|
||||
clock_gettime(CLOCK_REALTIME, &ts);
|
||||
struct tm tm;
|
||||
localtime_r(&ts.tv_sec, &tm);
|
||||
pthread_mutex_lock(&log_lock);
|
||||
FILE *f = log_file ? log_file : stderr;
|
||||
fprintf(f, "%02d:%02d:%02d.%03ld vkbridge-server %s %s\n", tm.tm_hour, tm.tm_min, tm.tm_sec,
|
||||
ts.tv_nsec / 1000000, tags[level & 3], msg);
|
||||
fflush(f);
|
||||
pthread_mutex_unlock(&log_lock);
|
||||
#ifdef __ANDROID__
|
||||
static const int prio[] = {ANDROID_LOG_ERROR, ANDROID_LOG_WARN, ANDROID_LOG_INFO, ANDROID_LOG_DEBUG};
|
||||
__android_log_write(prio[level & 3], "vkbridge", msg);
|
||||
#endif
|
||||
}
|
||||
|
||||
extern __thread const char *vkb_srv_current_cmd;
|
||||
|
||||
/* A crash is almost always the driver's: say in which call, then die as we would have. */
|
||||
__attribute__((unused)) static void on_crash(int sig)
|
||||
{
|
||||
char buf[256];
|
||||
const char *cmd = vkb_srv_current_cmd ? vkb_srv_current_cmd : "(no Vulkan call)";
|
||||
int n = snprintf(buf, sizeof(buf), "vkbridge-server E crashed with signal %d in %s\n", sig, cmd);
|
||||
if (log_file) {
|
||||
if (write(fileno(log_file), buf, (size_t)n) < 0) {}
|
||||
}
|
||||
if (write(2, buf, (size_t)n) < 0) {}
|
||||
#ifdef __ANDROID__
|
||||
__android_log_write(ANDROID_LOG_FATAL, "vkbridge", buf);
|
||||
#elif defined(__GLIBC__)
|
||||
void *frames[32];
|
||||
int nf = backtrace(frames, 32);
|
||||
backtrace_symbols_fd(frames, nf, 2);
|
||||
if (log_file) backtrace_symbols_fd(frames, nf, fileno(log_file));
|
||||
#endif
|
||||
signal(sig, SIG_DFL);
|
||||
raise(sig);
|
||||
}
|
||||
|
||||
static void *load_vulkan(const char *override)
|
||||
{
|
||||
const char *names[] = {
|
||||
override,
|
||||
#ifdef __ANDROID__
|
||||
"libvulkan.so",
|
||||
#else
|
||||
"libvulkan.so.1",
|
||||
"libvulkan.so",
|
||||
#endif
|
||||
};
|
||||
for (size_t i = 0; i < sizeof(names) / sizeof(names[0]); i++) {
|
||||
if (!names[i]) continue;
|
||||
void *h = dlopen(names[i], RTLD_NOW | RTLD_LOCAL);
|
||||
if (h) {
|
||||
VKB_INFO("Vulkan loader: %s", names[i]);
|
||||
return h;
|
||||
}
|
||||
VKB_WARN("cannot open %s: %s", names[i], dlerror());
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
static int listen_on(const char *path)
|
||||
{
|
||||
struct sockaddr_un a;
|
||||
if (strlen(path) >= sizeof(a.sun_path)) {
|
||||
VKB_ERR("socket path too long (%zu bytes): %s", strlen(path), path);
|
||||
return -1;
|
||||
}
|
||||
int fd = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0);
|
||||
if (fd < 0) {
|
||||
VKB_ERR("socket: %s", strerror(errno));
|
||||
return -1;
|
||||
}
|
||||
memset(&a, 0, sizeof(a));
|
||||
a.sun_family = AF_UNIX;
|
||||
strcpy(a.sun_path, path);
|
||||
unlink(path);
|
||||
if (bind(fd, (struct sockaddr *)&a, sizeof(a)) < 0) {
|
||||
VKB_ERR("bind %s: %s", path, strerror(errno));
|
||||
close(fd);
|
||||
return -1;
|
||||
}
|
||||
chmod(path, 0600);
|
||||
if (listen(fd, 128) < 0) {
|
||||
VKB_ERR("listen: %s", strerror(errno));
|
||||
close(fd);
|
||||
return -1;
|
||||
}
|
||||
return fd;
|
||||
}
|
||||
|
||||
/* Opens (or switches to) the log file; NULL keeps logging to stderr/logcat only. */
|
||||
static void open_log(const char *path)
|
||||
{
|
||||
FILE *f = path ? fopen(path, "ae") : NULL;
|
||||
if (path && !f) fprintf(stderr, "vkbridge-server: cannot open log %s: %s\n", path, strerror(errno));
|
||||
pthread_mutex_lock(&log_lock);
|
||||
FILE *old = log_file;
|
||||
log_file = f;
|
||||
pthread_mutex_unlock(&log_lock);
|
||||
if (old) fclose(old);
|
||||
}
|
||||
|
||||
/* Loads the Vulkan loader and runs the self-test; 0 when there is nothing to serve. */
|
||||
static int server_init(const char *vk_lib, const char *cache_dir)
|
||||
{
|
||||
VKB_INFO("starting (pid %d, protocol %016llx)", getpid(), (unsigned long long)VKB_PROTOCOL_HASH);
|
||||
void *lib = load_vulkan(vk_lib);
|
||||
if (!lib) {
|
||||
VKB_ERR("no Vulkan loader; nothing to serve");
|
||||
return 0;
|
||||
}
|
||||
vkb_gipa = (PFN_vkGetInstanceProcAddr)dlsym(lib, "vkGetInstanceProcAddr");
|
||||
if (!vkb_gipa) {
|
||||
VKB_ERR("the Vulkan loader exports no vkGetInstanceProcAddr");
|
||||
return 0;
|
||||
}
|
||||
vkb_dispatch_load_instance(&vkb_global_dt, vkb_gipa, VK_NULL_HANDLE);
|
||||
vkb_pcache_set_dir(cache_dir);
|
||||
vkb_selftest_all();
|
||||
return 1;
|
||||
}
|
||||
|
||||
#ifdef VKB_JNI
|
||||
/*
|
||||
* In the app's own process (the default on the device): Android chooses the GPU driver, Samsung's
|
||||
* updatable one included, while the app starts up, and only for the app's process - a separate
|
||||
* executable gets the plain /vendor driver, which on the Tab S10+ lacked VK_EXT_robustness2 and
|
||||
* more that the app itself sees. Winlator's Vortek runs its server in-process for the same reason.
|
||||
* Started once and kept for the app's life; each session only points the log at its own folder.
|
||||
*/
|
||||
#include <jni.h>
|
||||
|
||||
static pthread_mutex_t jni_lock = PTHREAD_MUTEX_INITIALIZER;
|
||||
static char jni_socket[256];
|
||||
static int jni_state; /* 0 not started, 1 serving, -1 failed */
|
||||
|
||||
static void *serve_thread(void *arg)
|
||||
{
|
||||
vkb_srv_serve((int)(intptr_t)arg);
|
||||
VKB_ERR("in-app server stopped serving");
|
||||
return NULL;
|
||||
}
|
||||
|
||||
static char *jstr(JNIEnv *env, jstring s)
|
||||
{
|
||||
if (!s) return NULL;
|
||||
const char *c = (*env)->GetStringUTFChars(env, s, NULL);
|
||||
char *r = c ? strdup(c) : NULL;
|
||||
if (c) (*env)->ReleaseStringUTFChars(env, s, c);
|
||||
return r;
|
||||
}
|
||||
|
||||
JNIEXPORT jint JNICALL Java_com_droiddeck_launcher_gpu_VkBridgeNative_nativeStart(JNIEnv *env, jclass cls, jstring jsocket,
|
||||
jstring jlog, jstring jcache)
|
||||
{
|
||||
(void)cls;
|
||||
char *sock = jstr(env, jsocket), *logp = jstr(env, jlog), *cache = jstr(env, jcache);
|
||||
pthread_mutex_lock(&jni_lock);
|
||||
open_log(logp);
|
||||
if (getenv("VKBRIDGE_DEBUG")) {
|
||||
vkb_verbose = 1;
|
||||
log_level = VKB_LOG_DEBUG;
|
||||
}
|
||||
int ok = 0;
|
||||
if (jni_state == 1 && sock && !strcmp(sock, jni_socket) && access(sock, F_OK) == 0) {
|
||||
VKB_INFO("in-app server already serving at %s (pid %d); this session's log continues here", sock, getpid());
|
||||
vkb_log_summary();
|
||||
ok = 1;
|
||||
} else if (jni_state == 1) {
|
||||
VKB_ERR("in-app server serves %s, asked for %s (or its socket is gone)", jni_socket, sock ? sock : "(none)");
|
||||
} else if (jni_state == 0 && sock) {
|
||||
jni_state = -1;
|
||||
if (server_init(NULL, cache)) {
|
||||
int lfd = listen_on(sock);
|
||||
pthread_t t;
|
||||
if (lfd >= 0 && pthread_create(&t, NULL, serve_thread, (void *)(intptr_t)lfd) == 0) {
|
||||
pthread_detach(t);
|
||||
snprintf(jni_socket, sizeof(jni_socket), "%s", sock);
|
||||
jni_state = 1;
|
||||
ok = 1;
|
||||
VKB_INFO("listening on %s (in the app's process)", sock);
|
||||
}
|
||||
}
|
||||
}
|
||||
pthread_mutex_unlock(&jni_lock);
|
||||
free(sock);
|
||||
free(logp);
|
||||
free(cache);
|
||||
return ok;
|
||||
}
|
||||
#else
|
||||
static void usage(void)
|
||||
{
|
||||
fprintf(stderr, "usage: vkbridge-server --socket PATH [--log FILE] [--vulkan LIB] [--cache-dir DIR] [--selftest] [--verbose]\n");
|
||||
}
|
||||
|
||||
static pid_t parent_pid;
|
||||
|
||||
static void *parent_watch(void *arg)
|
||||
{
|
||||
(void)arg;
|
||||
for (;;) {
|
||||
sleep(1);
|
||||
if (getppid() != parent_pid) {
|
||||
VKB_INFO("the app (pid %d) is gone; exiting", (int)parent_pid);
|
||||
_exit(0);
|
||||
}
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
static void start_parent_watch(void)
|
||||
{
|
||||
parent_pid = getppid();
|
||||
if (parent_pid <= 1) return; /* started by init or a shell that already left: nothing to watch */
|
||||
pthread_t t;
|
||||
pthread_attr_t a;
|
||||
pthread_attr_init(&a);
|
||||
pthread_attr_setdetachstate(&a, PTHREAD_CREATE_DETACHED);
|
||||
pthread_create(&t, &a, parent_watch, NULL);
|
||||
pthread_attr_destroy(&a);
|
||||
}
|
||||
|
||||
int main(int argc, char **argv)
|
||||
{
|
||||
const char *sock_path = getenv("VKBRIDGE_SOCKET");
|
||||
const char *log_path = getenv("VKBRIDGE_SERVER_LOG");
|
||||
const char *vk_lib = getenv("VKBRIDGE_SERVER_VULKAN");
|
||||
const char *cache_dir = getenv("VKBRIDGE_CACHE_DIR");
|
||||
int selftest_only = 0;
|
||||
for (int i = 1; i < argc; i++) {
|
||||
if (!strcmp(argv[i], "--socket") && i + 1 < argc) sock_path = argv[++i];
|
||||
else if (!strcmp(argv[i], "--log") && i + 1 < argc) log_path = argv[++i];
|
||||
else if (!strcmp(argv[i], "--vulkan") && i + 1 < argc) vk_lib = argv[++i];
|
||||
else if (!strcmp(argv[i], "--cache-dir") && i + 1 < argc) cache_dir = argv[++i];
|
||||
else if (!strcmp(argv[i], "--selftest")) selftest_only = 1;
|
||||
else if (!strcmp(argv[i], "--verbose")) vkb_verbose = 1;
|
||||
else {
|
||||
usage();
|
||||
return 2;
|
||||
}
|
||||
}
|
||||
if (getenv("VKBRIDGE_DEBUG")) vkb_verbose = 1;
|
||||
if (vkb_verbose) log_level = VKB_LOG_DEBUG;
|
||||
open_log(log_path);
|
||||
signal(SIGPIPE, SIG_IGN);
|
||||
signal(SIGSEGV, on_crash);
|
||||
signal(SIGBUS, on_crash);
|
||||
signal(SIGABRT, on_crash);
|
||||
signal(SIGILL, on_crash);
|
||||
signal(SIGFPE, on_crash);
|
||||
/* The server is the app's child: when the app dies, so does the session's GPU. Not with
|
||||
* PR_SET_PDEATHSIG: that fires when the parent THREAD exits, and Android's ProcessBuilder forks
|
||||
* from the session's start-up thread, which ends right after starting the guest (the server
|
||||
* was killed 6 ms into the first device run). The parent process is watched instead. */
|
||||
start_parent_watch();
|
||||
|
||||
if (!server_init(vk_lib, cache_dir)) return 1;
|
||||
if (selftest_only) return vkb_npds > 0 ? 0 : 1;
|
||||
|
||||
if (!sock_path) {
|
||||
usage();
|
||||
return 2;
|
||||
}
|
||||
int lfd = listen_on(sock_path);
|
||||
if (lfd < 0) return 1;
|
||||
VKB_INFO("listening on %s", sock_path);
|
||||
vkb_srv_serve(lfd);
|
||||
return 0;
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,834 @@
|
||||
/* SPDX-License-Identifier: GPL-3.0-or-later
|
||||
*
|
||||
* Host-visible memory shared with the client.
|
||||
*
|
||||
* A Linux program maps Vulkan memory and writes to it directly; those writes must land in the
|
||||
* pages the GPU reads. The server makes such memory shareable in one of three ways, chosen per
|
||||
* GPU by a self-test at startup that checks the GPU and both CPU mappings really see the same
|
||||
* bytes:
|
||||
* hostptr the client creates a memfd, the server maps it and imports it
|
||||
* (VK_EXT_external_memory_host);
|
||||
* dmabuf the server allocates exportable memory and hands the client its dma-buf
|
||||
* (VK_EXT_external_memory_dma_buf), which the client maps;
|
||||
* ahb the server allocates a BLOB AHardwareBuffer, imports it, and hands the client the
|
||||
* dma-buf behind it (Android only);
|
||||
* dmaheap the server allocates from /dev/dma_heap (system-uncached, else system), imports that
|
||||
* dma-buf into the driver and hands it to the client - what GameNative's wrapper does on
|
||||
* Mali when the driver will not export one (Android; root-only on desktops).
|
||||
* VKBRIDGE_MEMORY=hostptr|dmabuf|dmaheap|ahb forces one.
|
||||
*/
|
||||
#define _GNU_SOURCE
|
||||
#ifdef __ANDROID__
|
||||
#define VK_USE_PLATFORM_ANDROID_KHR 1
|
||||
#endif
|
||||
#include "vkb_server.h"
|
||||
|
||||
#include <dlfcn.h>
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/mman.h>
|
||||
#include <sys/ioctl.h>
|
||||
#include <sys/syscall.h>
|
||||
#include <linux/dma-heap.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#ifdef __ANDROID__
|
||||
#include <vulkan/vulkan_android.h>
|
||||
/* libnativewindow, opened at run time (getNativeHandle is not in the NDK headers). */
|
||||
typedef struct {
|
||||
uint32_t width, height, layers, format;
|
||||
uint64_t usage;
|
||||
uint32_t stride, rfu0;
|
||||
uint64_t rfu1;
|
||||
} vkb_ahb_desc;
|
||||
typedef struct {
|
||||
int version, numFds, numInts;
|
||||
int data[0];
|
||||
} vkb_native_handle;
|
||||
static int (*p_AHardwareBuffer_allocate)(const vkb_ahb_desc *, struct AHardwareBuffer **);
|
||||
static void (*p_AHardwareBuffer_release)(struct AHardwareBuffer *);
|
||||
static const vkb_native_handle *(*p_AHardwareBuffer_getNativeHandle)(const struct AHardwareBuffer *);
|
||||
#define AHB_FORMAT_BLOB 0x21
|
||||
#define AHB_USAGE_CPU_READ_OFTEN 3ull
|
||||
#define AHB_USAGE_CPU_WRITE_OFTEN (3ull << 4)
|
||||
#define AHB_USAGE_GPU_DATA_BUFFER (1ull << 24)
|
||||
|
||||
static int ahb_load(void)
|
||||
{
|
||||
static int state;
|
||||
if (state) return state > 0;
|
||||
void *h = dlopen("libnativewindow.so", RTLD_NOW);
|
||||
if (!h) h = dlopen("libandroid.so", RTLD_NOW);
|
||||
if (h) {
|
||||
p_AHardwareBuffer_allocate = dlsym(h, "AHardwareBuffer_allocate");
|
||||
p_AHardwareBuffer_release = dlsym(h, "AHardwareBuffer_release");
|
||||
p_AHardwareBuffer_getNativeHandle = dlsym(h, "AHardwareBuffer_getNativeHandle");
|
||||
}
|
||||
state = (p_AHardwareBuffer_allocate && p_AHardwareBuffer_release && p_AHardwareBuffer_getNativeHandle) ? 1 : -1;
|
||||
if (state < 0) VKB_WARN("AHardwareBuffer functions unavailable");
|
||||
return state > 0;
|
||||
}
|
||||
#endif
|
||||
|
||||
static const char *const ext_hostptr[] = {"VK_KHR_external_memory", "VK_EXT_external_memory_host"};
|
||||
static const char *const ext_dmabuf[] = {"VK_KHR_external_memory", "VK_KHR_external_memory_fd", "VK_EXT_external_memory_dma_buf"};
|
||||
#ifdef __ANDROID__
|
||||
static const char *const ext_ahb[] = {"VK_KHR_external_memory", "VK_ANDROID_external_memory_android_hardware_buffer",
|
||||
"VK_EXT_queue_family_foreign", "VK_KHR_sampler_ycbcr_conversion",
|
||||
"VK_KHR_dedicated_allocation", "VK_KHR_get_memory_requirements2"};
|
||||
#endif
|
||||
|
||||
const char *const *vkb_mem_required_extensions(uint32_t strategy, uint32_t *count)
|
||||
{
|
||||
switch (strategy) {
|
||||
case VKB_MEM_HOSTPTR: *count = 2; return ext_hostptr;
|
||||
case VKB_MEM_DMABUF: *count = 3; return ext_dmabuf;
|
||||
case VKB_MEM_DMAHEAP: *count = 3; return ext_dmabuf;
|
||||
#ifdef __ANDROID__
|
||||
case VKB_MEM_AHB: *count = 6; return ext_ahb;
|
||||
#endif
|
||||
default: *count = 0; return NULL;
|
||||
}
|
||||
}
|
||||
|
||||
static uint32_t strategy_handle_type(uint32_t s)
|
||||
{
|
||||
switch (s) {
|
||||
case VKB_MEM_HOSTPTR: return VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT;
|
||||
case VKB_MEM_DMABUF: return VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT;
|
||||
case VKB_MEM_DMAHEAP: return VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT;
|
||||
#ifdef __ANDROID__
|
||||
case VKB_MEM_AHB: return VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID;
|
||||
#endif
|
||||
default: return 0;
|
||||
}
|
||||
}
|
||||
|
||||
int vkb_memfd(const char *name, size_t size)
|
||||
{
|
||||
int fd = (int)syscall(SYS_memfd_create, name, 1u /* MFD_CLOEXEC */);
|
||||
if (fd < 0) return -1;
|
||||
if (ftruncate(fd, (off_t)size) < 0) {
|
||||
close(fd);
|
||||
return -1;
|
||||
}
|
||||
return fd;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ tracking */
|
||||
|
||||
static unsigned mem_hash(VkDeviceMemory m)
|
||||
{
|
||||
uint64_t v = (uint64_t)(uintptr_t)m;
|
||||
v ^= v >> 17;
|
||||
v *= 0x9E3779B97F4A7C15ull;
|
||||
return (unsigned)(v >> 56);
|
||||
}
|
||||
|
||||
void vkb_mem_track(vkb_srv_table *dev, vkb_srv_mem *m)
|
||||
{
|
||||
pthread_mutex_lock(&dev->lock);
|
||||
unsigned h = mem_hash(m->mem);
|
||||
m->next = dev->mems[h];
|
||||
dev->mems[h] = m;
|
||||
pthread_mutex_unlock(&dev->lock);
|
||||
}
|
||||
|
||||
vkb_srv_mem *vkb_mem_find(vkb_srv_table *dev, VkDeviceMemory mem, int remove)
|
||||
{
|
||||
pthread_mutex_lock(&dev->lock);
|
||||
vkb_srv_mem **pp = &dev->mems[mem_hash(mem)];
|
||||
while (*pp && (*pp)->mem != mem) pp = &(*pp)->next;
|
||||
vkb_srv_mem *m = *pp;
|
||||
if (m && remove) *pp = m->next;
|
||||
pthread_mutex_unlock(&dev->lock);
|
||||
return m;
|
||||
}
|
||||
|
||||
/* Frees the server-side resources of an allocation (the VkDeviceMemory must already be freed). */
|
||||
static void mem_release_backing(vkb_srv_mem *m)
|
||||
{
|
||||
if (m->host_ptr) munmap(m->host_ptr, m->host_len);
|
||||
#ifdef __ANDROID__
|
||||
if (m->ahb) p_AHardwareBuffer_release(m->ahb);
|
||||
#endif
|
||||
free(m);
|
||||
}
|
||||
|
||||
void vkb_mem_release(vkb_srv_table *dev, vkb_srv_mem *m)
|
||||
{
|
||||
if (m->mapped) dev->real.vkUnmapMemory(dev->device, m->mem);
|
||||
dev->real.vkFreeMemory(dev->device, m->mem, NULL);
|
||||
mem_release_backing(m);
|
||||
}
|
||||
|
||||
void vkb_mem_free_all(vkb_srv_table *dev)
|
||||
{
|
||||
for (int i = 0; i < 256; i++) {
|
||||
vkb_srv_mem *m = dev->mems[i];
|
||||
dev->mems[i] = NULL;
|
||||
while (m) {
|
||||
vkb_srv_mem *n = m->next;
|
||||
vkb_mem_release(dev, m);
|
||||
m = n;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* The dma-heap the dmaheap strategy allocates from, opened once: system-uncached first (the GPU
|
||||
* and the client both write through it without cache maintenance), else the cached system heap. */
|
||||
static int dmaheap_fd(void)
|
||||
{
|
||||
static int fd = -2;
|
||||
static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
|
||||
pthread_mutex_lock(&lock);
|
||||
if (fd == -2) {
|
||||
const char *names[] = {"/dev/dma_heap/system-uncached", "/dev/dma_heap/system"};
|
||||
if (getenv("VKBRIDGE_DMAHEAP_CACHED")) names[0] = "/dev/dma_heap/system";
|
||||
fd = -1;
|
||||
for (int i = 0; i < 2 && fd < 0; i++) {
|
||||
fd = open(names[i], O_RDONLY | O_CLOEXEC);
|
||||
if (fd >= 0) VKB_INFO("dmaheap: allocating from %s", names[i]);
|
||||
else VKB_INFO("dmaheap: %s: %s", names[i], strerror(errno));
|
||||
}
|
||||
}
|
||||
int r = fd;
|
||||
pthread_mutex_unlock(&lock);
|
||||
return r;
|
||||
}
|
||||
|
||||
/* Unlinks every structure of type t from the chain starting at *head. */
|
||||
static void chain_drop(const void **head, VkStructureType t)
|
||||
{
|
||||
const VkBaseInStructure **pp = (const VkBaseInStructure **)head;
|
||||
while (*pp) {
|
||||
if ((*pp)->sType == t) *pp = (*pp)->pNext;
|
||||
else pp = (const VkBaseInStructure **)&((VkBaseInStructure *)*pp)->pNext;
|
||||
}
|
||||
}
|
||||
|
||||
/* The driver's vkGetDeviceProcAddr (for entry points the dispatch table does not carry). */
|
||||
PFN_vkGetDeviceProcAddr vkb_mem_gdpa;
|
||||
|
||||
/* ------------------------------------------------------------------ allocation */
|
||||
|
||||
/*
|
||||
* Allocates shared memory with strategy `s`. `ai` is the app's (or the self-test's) allocate
|
||||
* info; for hostptr, `client_fd` is the client's memfd (consumed). On success *out_fd is the fd
|
||||
* to send to the client (-1 for hostptr, where the client already has its pages).
|
||||
*/
|
||||
static VkResult alloc_shared(const vkb_dispatch *dt, VkDevice dev, uint32_t s, const VkMemoryAllocateInfo *ai,
|
||||
int client_fd, vkb_srv_mem **out, int *out_fd)
|
||||
{
|
||||
*out_fd = -1;
|
||||
*out = NULL;
|
||||
vkb_srv_mem *m = calloc(1, sizeof(*m));
|
||||
if (!m) {
|
||||
if (client_fd >= 0) close(client_fd);
|
||||
return VK_ERROR_OUT_OF_HOST_MEMORY;
|
||||
}
|
||||
m->size = ai->allocationSize;
|
||||
m->type = ai->memoryTypeIndex;
|
||||
m->strategy = s;
|
||||
VkMemoryAllocateInfo info = *ai;
|
||||
VkResult r = VK_ERROR_FEATURE_NOT_PRESENT;
|
||||
switch (s) {
|
||||
case VKB_MEM_HOSTPTR: {
|
||||
if (client_fd < 0) break;
|
||||
void *p = mmap(NULL, (size_t)ai->allocationSize, PROT_READ | PROT_WRITE, MAP_SHARED, client_fd, 0);
|
||||
close(client_fd);
|
||||
client_fd = -1;
|
||||
if (p == MAP_FAILED) {
|
||||
VKB_ERR("hostptr: mmap of the client's memory failed: %s", strerror(errno));
|
||||
r = VK_ERROR_OUT_OF_HOST_MEMORY;
|
||||
break;
|
||||
}
|
||||
m->host_ptr = p;
|
||||
m->host_len = (size_t)ai->allocationSize;
|
||||
VkMemoryHostPointerPropertiesEXT hp = {VK_STRUCTURE_TYPE_MEMORY_HOST_POINTER_PROPERTIES_EXT};
|
||||
if (!dt->vkGetMemoryHostPointerPropertiesEXT ||
|
||||
dt->vkGetMemoryHostPointerPropertiesEXT(dev, VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT, p, &hp) != VK_SUCCESS ||
|
||||
!(hp.memoryTypeBits & (1u << ai->memoryTypeIndex))) {
|
||||
r = VK_ERROR_INVALID_EXTERNAL_HANDLE;
|
||||
break;
|
||||
}
|
||||
VkImportMemoryHostPointerInfoEXT imp = {VK_STRUCTURE_TYPE_IMPORT_MEMORY_HOST_POINTER_INFO_EXT, info.pNext,
|
||||
VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT, p};
|
||||
info.pNext = &imp;
|
||||
r = dt->vkAllocateMemory(dev, &info, NULL, &m->mem);
|
||||
break;
|
||||
}
|
||||
case VKB_MEM_DMABUF: {
|
||||
VkExportMemoryAllocateInfo exp = {VK_STRUCTURE_TYPE_EXPORT_MEMORY_ALLOCATE_INFO, info.pNext,
|
||||
VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT};
|
||||
/* An export the app asked for itself is merged rather than duplicated. */
|
||||
for (VkBaseOutStructure *b = (VkBaseOutStructure *)info.pNext; b; b = b->pNext) {
|
||||
if (b->sType == VK_STRUCTURE_TYPE_EXPORT_MEMORY_ALLOCATE_INFO) {
|
||||
((VkExportMemoryAllocateInfo *)b)->handleTypes |= VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT;
|
||||
exp.sType = VK_STRUCTURE_TYPE_MAX_ENUM;
|
||||
}
|
||||
}
|
||||
if (exp.sType != VK_STRUCTURE_TYPE_MAX_ENUM) info.pNext = &exp;
|
||||
r = dt->vkAllocateMemory(dev, &info, NULL, &m->mem);
|
||||
if (r != VK_SUCCESS) {
|
||||
VKB_INFO("dmabuf: exportable allocation of %llu bytes (type %u) failed: %d", (unsigned long long)info.allocationSize,
|
||||
info.memoryTypeIndex, r);
|
||||
break;
|
||||
}
|
||||
VkMemoryGetFdInfoKHR gi = {VK_STRUCTURE_TYPE_MEMORY_GET_FD_INFO_KHR, NULL, m->mem, VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT};
|
||||
int fd = -1;
|
||||
VkResult fr = dt->vkGetMemoryFdKHR ? dt->vkGetMemoryFdKHR(dev, &gi, &fd) : VK_ERROR_EXTENSION_NOT_PRESENT;
|
||||
if (fr != VK_SUCCESS || fd < 0) {
|
||||
VKB_INFO("dmabuf: vkGetMemoryFdKHR %s: %d (fd %d)", dt->vkGetMemoryFdKHR ? "failed" : "not loaded", fr, fd);
|
||||
dt->vkFreeMemory(dev, m->mem, NULL);
|
||||
m->mem = VK_NULL_HANDLE;
|
||||
r = VK_ERROR_INVALID_EXTERNAL_HANDLE;
|
||||
break;
|
||||
}
|
||||
*out_fd = fd;
|
||||
break;
|
||||
}
|
||||
case VKB_MEM_DMAHEAP: {
|
||||
int hfd = dmaheap_fd();
|
||||
if (hfd < 0) break;
|
||||
uint64_t len = (ai->allocationSize + 4095) & ~4095ull;
|
||||
struct dma_heap_allocation_data hd = {len, 0, O_RDWR | O_CLOEXEC, 0};
|
||||
if (ioctl(hfd, DMA_HEAP_IOCTL_ALLOC, &hd) < 0) {
|
||||
VKB_INFO("dmaheap: allocating %llu bytes failed: %s", (unsigned long long)len, strerror(errno));
|
||||
r = VK_ERROR_OUT_OF_DEVICE_MEMORY;
|
||||
break;
|
||||
}
|
||||
int fd = (int)hd.fd;
|
||||
VkMemoryFdPropertiesKHR fp = {VK_STRUCTURE_TYPE_MEMORY_FD_PROPERTIES_KHR};
|
||||
VkResult pr = dt->vkGetMemoryFdPropertiesKHR
|
||||
? dt->vkGetMemoryFdPropertiesKHR(dev, VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT, fd, &fp)
|
||||
: VK_ERROR_EXTENSION_NOT_PRESENT;
|
||||
if (pr != VK_SUCCESS || !(fp.memoryTypeBits & (1u << ai->memoryTypeIndex))) {
|
||||
VKB_INFO("dmaheap: fd properties %d, memory types 0x%x (want type %u)", pr, fp.memoryTypeBits, ai->memoryTypeIndex);
|
||||
close(fd);
|
||||
r = VK_ERROR_INVALID_EXTERNAL_HANDLE;
|
||||
break;
|
||||
}
|
||||
/* The import takes its own fd; ours goes to the client. A dedicated-allocation struct
|
||||
* with an imported dma-buf crashes some Mali drivers (GameNative mesa PR #8): dropped. */
|
||||
int imp_fd = fcntl(fd, F_DUPFD_CLOEXEC, 0);
|
||||
VkImportMemoryFdInfoKHR imp = {VK_STRUCTURE_TYPE_IMPORT_MEMORY_FD_INFO_KHR, info.pNext,
|
||||
VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT, imp_fd};
|
||||
chain_drop(&imp.pNext, VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO);
|
||||
chain_drop(&imp.pNext, VK_STRUCTURE_TYPE_EXPORT_MEMORY_ALLOCATE_INFO);
|
||||
info.pNext = &imp;
|
||||
info.allocationSize = len;
|
||||
r = imp_fd >= 0 ? dt->vkAllocateMemory(dev, &info, NULL, &m->mem) : VK_ERROR_TOO_MANY_OBJECTS;
|
||||
if (r != VK_SUCCESS) {
|
||||
VKB_INFO("dmaheap: import of %llu bytes failed: %d", (unsigned long long)len, r);
|
||||
if (imp_fd >= 0) close(imp_fd); /* a failed import leaves the fd with us */
|
||||
close(fd);
|
||||
break;
|
||||
}
|
||||
*out_fd = fd;
|
||||
break;
|
||||
}
|
||||
#ifdef __ANDROID__
|
||||
case VKB_MEM_AHB: {
|
||||
if (!ahb_load()) break;
|
||||
/* Through the device's own vkGetDeviceProcAddr: Android's loader answers NULL for it from
|
||||
* vkGetInstanceProcAddr(NULL, ...), which desktop loaders allow (the first device run). */
|
||||
PFN_vkGetAndroidHardwareBufferPropertiesANDROID get_props = NULL;
|
||||
if (vkb_mem_gdpa)
|
||||
get_props = (PFN_vkGetAndroidHardwareBufferPropertiesANDROID)vkb_mem_gdpa(dev, "vkGetAndroidHardwareBufferPropertiesANDROID");
|
||||
if (!get_props) {
|
||||
VKB_INFO("ahb: vkGetAndroidHardwareBufferPropertiesANDROID not found");
|
||||
break;
|
||||
}
|
||||
uint64_t sz = ai->allocationSize;
|
||||
if (sz > 0xFFFFFFFFull) {
|
||||
r = VK_ERROR_OUT_OF_DEVICE_MEMORY;
|
||||
break;
|
||||
}
|
||||
/* CPU usage decides how gralloc caches the pages; VKBRIDGE_AHB_RARELY=1 asks for uncached. */
|
||||
uint64_t cpu = getenv("VKBRIDGE_AHB_RARELY") ? (2ull | (2ull << 4)) : (AHB_USAGE_CPU_READ_OFTEN | AHB_USAGE_CPU_WRITE_OFTEN);
|
||||
vkb_ahb_desc d = {(uint32_t)sz, 1, 1, AHB_FORMAT_BLOB, cpu | AHB_USAGE_GPU_DATA_BUFFER, 0, 0, 0};
|
||||
struct AHardwareBuffer *ahb = NULL;
|
||||
int ar = p_AHardwareBuffer_allocate(&d, &ahb);
|
||||
if (ar != 0 || !ahb) {
|
||||
VKB_INFO("ahb: AHardwareBuffer_allocate(%u bytes) failed: %d", (unsigned)sz, ar);
|
||||
r = VK_ERROR_OUT_OF_DEVICE_MEMORY;
|
||||
break;
|
||||
}
|
||||
m->ahb = ahb;
|
||||
VkAndroidHardwareBufferPropertiesANDROID props = {VK_STRUCTURE_TYPE_ANDROID_HARDWARE_BUFFER_PROPERTIES_ANDROID};
|
||||
VkResult pr = get_props(dev, ahb, &props);
|
||||
if (pr != VK_SUCCESS || !(props.memoryTypeBits & (1u << ai->memoryTypeIndex))) {
|
||||
VKB_INFO("ahb: properties %d, memory types 0x%x (want type %u)", pr, props.memoryTypeBits, ai->memoryTypeIndex);
|
||||
r = VK_ERROR_INVALID_EXTERNAL_HANDLE;
|
||||
break;
|
||||
}
|
||||
VkImportAndroidHardwareBufferInfoANDROID imp = {VK_STRUCTURE_TYPE_IMPORT_ANDROID_HARDWARE_BUFFER_INFO_ANDROID, info.pNext, ahb};
|
||||
info.pNext = &imp;
|
||||
info.allocationSize = props.allocationSize;
|
||||
r = dt->vkAllocateMemory(dev, &info, NULL, &m->mem);
|
||||
if (r != VK_SUCCESS) {
|
||||
VKB_INFO("ahb: import of %llu bytes failed: %d", (unsigned long long)info.allocationSize, r);
|
||||
break;
|
||||
}
|
||||
const vkb_native_handle *nh = p_AHardwareBuffer_getNativeHandle(ahb);
|
||||
if (!nh || nh->numFds < 1) {
|
||||
VKB_INFO("ahb: no fd in the native handle (%d)", nh ? nh->numFds : -1);
|
||||
dt->vkFreeMemory(dev, m->mem, NULL);
|
||||
m->mem = VK_NULL_HANDLE;
|
||||
r = VK_ERROR_INVALID_EXTERNAL_HANDLE;
|
||||
break;
|
||||
}
|
||||
/* Mali's gralloc can put more than one fd in the handle (metadata beside the pages): the
|
||||
* memory is the one at least as large as the allocation. */
|
||||
int pick = -1;
|
||||
for (int i = 0; i < nh->numFds && pick < 0; i++) {
|
||||
off_t end = lseek(nh->data[i], 0, SEEK_END);
|
||||
if (end >= (off_t)sz) pick = nh->data[i];
|
||||
if (nh->numFds > 1) VKB_INFO("ahb: handle fd %d of %d is %lld bytes", i + 1, nh->numFds, (long long)end);
|
||||
}
|
||||
if (pick < 0) {
|
||||
VKB_INFO("ahb: no fd in the handle covers %llu bytes", (unsigned long long)sz);
|
||||
dt->vkFreeMemory(dev, m->mem, NULL);
|
||||
m->mem = VK_NULL_HANDLE;
|
||||
r = VK_ERROR_INVALID_EXTERNAL_HANDLE;
|
||||
break;
|
||||
}
|
||||
*out_fd = fcntl(pick, F_DUPFD_CLOEXEC, 0);
|
||||
break;
|
||||
}
|
||||
#endif
|
||||
default:
|
||||
break;
|
||||
}
|
||||
if (client_fd >= 0) close(client_fd);
|
||||
if (r != VK_SUCCESS) {
|
||||
mem_release_backing(m);
|
||||
return r;
|
||||
}
|
||||
*out = m;
|
||||
return VK_SUCCESS;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ handlers */
|
||||
|
||||
static void close_import_fds(const void *pNext)
|
||||
{
|
||||
for (const VkBaseInStructure *b = pNext; b; b = b->pNext)
|
||||
if (b->sType == VK_STRUCTURE_TYPE_IMPORT_MEMORY_FD_INFO_KHR) vkb_close_fd(((const VkImportMemoryFdInfoKHR *)b)->fd);
|
||||
}
|
||||
|
||||
void vkb_sv_vkAllocateMemory(vkb_srv_call *c)
|
||||
{
|
||||
VkDevice dev = (VkDevice)(uintptr_t)vkb_dec_u64(&c->d);
|
||||
VkMemoryAllocateInfo ai;
|
||||
int have = vkb_dec_u8(&c->d);
|
||||
if (have) vkb_dec_VkMemoryAllocateInfo(&c->d, &ai);
|
||||
uint32_t mode = vkb_dec_u32(&c->d);
|
||||
int client_fd = vkb_dec_fd(&c->d);
|
||||
vkb_srv_table *t = c->table;
|
||||
if (c->d.err || !have || !t || !t->is_device || t->device != dev) {
|
||||
if (client_fd >= 0) close(client_fd);
|
||||
vkb_srv_bad_message(c);
|
||||
return;
|
||||
}
|
||||
VkResult r;
|
||||
vkb_srv_mem *m = NULL;
|
||||
int out_fd = -1;
|
||||
if (mode == VKB_ALLOC_SHARED) {
|
||||
uint32_t s = t->pd ? t->pd->info.strategy : VKB_MEM_NONE;
|
||||
r = alloc_shared(c->dt, dev, s, &ai, client_fd, &m, &out_fd);
|
||||
if (r != VK_SUCCESS) VKB_WARN("shared allocation of %llu bytes (type %u, %s) failed: %d",
|
||||
(unsigned long long)ai.allocationSize, ai.memoryTypeIndex, vkb_mem_strategy_name(s), r);
|
||||
} else {
|
||||
if (client_fd >= 0) close(client_fd);
|
||||
m = calloc(1, sizeof(*m));
|
||||
m->size = ai.allocationSize;
|
||||
m->type = ai.memoryTypeIndex;
|
||||
r = c->dt->vkAllocateMemory(dev, &ai, NULL, &m->mem);
|
||||
if (r != VK_SUCCESS) {
|
||||
close_import_fds(ai.pNext);
|
||||
free(m);
|
||||
m = NULL;
|
||||
}
|
||||
}
|
||||
if (m) vkb_mem_track(t, m);
|
||||
vkb_enc_u32(&c->r, (uint32_t)r);
|
||||
vkb_enc_u64(&c->r, m ? (uint64_t)(uintptr_t)m->mem : 0);
|
||||
vkb_enc_fd(&c->r, out_fd);
|
||||
if (out_fd >= 0) vkb_srv_close_after_send(c, out_fd);
|
||||
vkb_enc_u64(&c->r, m ? (uint64_t)m->size : 0);
|
||||
}
|
||||
|
||||
void vkb_sv_vkFreeMemory(vkb_srv_call *c)
|
||||
{
|
||||
VkDevice dev = (VkDevice)(uintptr_t)vkb_dec_u64(&c->d);
|
||||
VkDeviceMemory mem;
|
||||
vkb_dec_bytes(&c->d, &mem, sizeof(mem));
|
||||
vkb_srv_table *t = c->table;
|
||||
if (c->d.err || !t || !t->is_device || t->device != dev) {
|
||||
vkb_srv_bad_message(c);
|
||||
return;
|
||||
}
|
||||
if (!mem) return;
|
||||
vkb_srv_mem *m = vkb_mem_find(t, mem, 1);
|
||||
if (m) {
|
||||
vkb_mem_release(t, m);
|
||||
} else {
|
||||
VKB_WARN("vkFreeMemory of untracked memory");
|
||||
c->dt->vkFreeMemory(dev, mem, NULL);
|
||||
}
|
||||
}
|
||||
|
||||
static VkResult ensure_server_map(vkb_srv_table *t, vkb_srv_mem *m)
|
||||
{
|
||||
if (m->mapped) return VK_SUCCESS;
|
||||
pthread_mutex_lock(&t->lock);
|
||||
VkResult r = VK_SUCCESS;
|
||||
if (!m->mapped) r = t->real.vkMapMemory(t->device, m->mem, 0, VK_WHOLE_SIZE, 0, &m->mapped);
|
||||
pthread_mutex_unlock(&t->lock);
|
||||
return r;
|
||||
}
|
||||
|
||||
static void flush_or_invalidate(vkb_srv_call *c, int flush)
|
||||
{
|
||||
VkDevice dev = (VkDevice)(uintptr_t)vkb_dec_u64(&c->d);
|
||||
uint32_t n = vkb_dec_u32(&c->d);
|
||||
vkb_srv_table *t = c->table;
|
||||
if (c->d.err || !t || !t->is_device || t->device != dev || n > 65536) {
|
||||
vkb_srv_bad_message(c);
|
||||
return;
|
||||
}
|
||||
VkMappedMemoryRange *ranges = vkb_dec_alloc(&c->d, (n ? n : 1) * sizeof(*ranges));
|
||||
for (uint32_t i = 0; ranges && i < n; i++) vkb_dec_VkMappedMemoryRange(&c->d, &ranges[i]);
|
||||
if (c->d.err) {
|
||||
vkb_srv_bad_message(c);
|
||||
return;
|
||||
}
|
||||
VkResult r = VK_SUCCESS;
|
||||
for (uint32_t i = 0; i < n && r == VK_SUCCESS; i++) {
|
||||
vkb_srv_mem *m = vkb_mem_find(t, ranges[i].memory, 0);
|
||||
if (m) r = ensure_server_map(t, m);
|
||||
}
|
||||
if (r == VK_SUCCESS && n) {
|
||||
r = flush ? c->dt->vkFlushMappedMemoryRanges(dev, n, ranges) : c->dt->vkInvalidateMappedMemoryRanges(dev, n, ranges);
|
||||
}
|
||||
vkb_enc_u32(&c->r, (uint32_t)r);
|
||||
}
|
||||
|
||||
void vkb_sv_vkFlushMappedMemoryRanges(vkb_srv_call *c) { flush_or_invalidate(c, 1); }
|
||||
void vkb_sv_vkInvalidateMappedMemoryRanges(vkb_srv_call *c) { flush_or_invalidate(c, 0); }
|
||||
|
||||
/* ------------------------------------------------------------------ self-test */
|
||||
|
||||
typedef struct {
|
||||
const vkb_dispatch *idt;
|
||||
vkb_dispatch dt;
|
||||
VkPhysicalDevice pd;
|
||||
VkDevice dev;
|
||||
VkQueue queue;
|
||||
VkCommandPool pool;
|
||||
uint32_t qf;
|
||||
VkPhysicalDeviceMemoryProperties mp;
|
||||
VkDeviceSize import_align;
|
||||
} selftest;
|
||||
|
||||
static int submit_and_wait(selftest *st, VkCommandBuffer cb)
|
||||
{
|
||||
VkFenceCreateInfo fci = {VK_STRUCTURE_TYPE_FENCE_CREATE_INFO};
|
||||
VkFence f;
|
||||
if (st->dt.vkCreateFence(st->dev, &fci, NULL, &f) != VK_SUCCESS) return 0;
|
||||
VkSubmitInfo si = {VK_STRUCTURE_TYPE_SUBMIT_INFO, NULL, 0, NULL, NULL, 1, &cb, 0, NULL};
|
||||
int ok = st->dt.vkQueueSubmit(st->queue, 1, &si, f) == VK_SUCCESS &&
|
||||
st->dt.vkWaitForFences(st->dev, 1, &f, VK_TRUE, 5000000000ull) == VK_SUCCESS;
|
||||
st->dt.vkDestroyFence(st->dev, f, NULL);
|
||||
return ok;
|
||||
}
|
||||
|
||||
#define TEST_SIZE (256u * 1024u)
|
||||
|
||||
/* One allocation of `type` with strategy `s`, checked from both sides. 1 = shared and coherent
|
||||
* (no flush needed), 2 = shared when flushed, 0 = not shared. */
|
||||
static int test_type_mode(selftest *st, uint32_t s, uint32_t type, int no_flush);
|
||||
|
||||
/* Without flushes first: imported pages from an uncached heap are coherent in practice even where
|
||||
* the driver's type does not say HOST_COHERENT (Mali-G720: dma-heap imports land in type 1,
|
||||
* HOST_CACHED without COHERENT, and pass with no flush). Only if that fails, with flushes. */
|
||||
static int test_type(selftest *st, uint32_t s, uint32_t type)
|
||||
{
|
||||
int coherent_flag = (st->mp.memoryTypes[type].propertyFlags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT) != 0;
|
||||
if (!coherent_flag && !getenv("VKBRIDGE_SELFTEST_NOFLUSH")) {
|
||||
int r = test_type_mode(st, s, type, 1);
|
||||
if (r) {
|
||||
VKB_INFO(" %s, type %u: coherent in practice (no flushes needed)", vkb_mem_strategy_name(s), type);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
return test_type_mode(st, s, type, 0);
|
||||
}
|
||||
|
||||
static int test_type_mode(selftest *st, uint32_t s, uint32_t type, int no_flush)
|
||||
{
|
||||
const vkb_dispatch *dt = &st->dt;
|
||||
int result = 0;
|
||||
VkExternalMemoryBufferCreateInfo ext = {VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_BUFFER_CREATE_INFO, NULL, strategy_handle_type(s)};
|
||||
VkBufferCreateInfo bci = {VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, &ext, 0, TEST_SIZE,
|
||||
VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT |
|
||||
VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT |
|
||||
VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT,
|
||||
VK_SHARING_MODE_EXCLUSIVE, 0, NULL};
|
||||
VkBuffer buf = VK_NULL_HANDLE;
|
||||
if (dt->vkCreateBuffer(st->dev, &bci, NULL, &buf) != VK_SUCCESS) return 0;
|
||||
VkMemoryRequirements req;
|
||||
dt->vkGetBufferMemoryRequirements(st->dev, buf, &req);
|
||||
if (!(req.memoryTypeBits & (1u << type))) {
|
||||
dt->vkDestroyBuffer(st->dev, buf, NULL);
|
||||
return 0;
|
||||
}
|
||||
VkDeviceSize size = req.size;
|
||||
if (s == VKB_MEM_HOSTPTR) size = (size + st->import_align - 1) & ~(st->import_align - 1);
|
||||
VkMemoryAllocateInfo ai = {VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, NULL, size, type};
|
||||
int cfd = -1;
|
||||
if (s == VKB_MEM_HOSTPTR) {
|
||||
cfd = vkb_memfd("vkbridge-selftest", (size_t)size);
|
||||
if (cfd < 0) {
|
||||
dt->vkDestroyBuffer(st->dev, buf, NULL);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
int keep_fd = s == VKB_MEM_HOSTPTR ? fcntl(cfd, F_DUPFD_CLOEXEC, 0) : -1;
|
||||
vkb_srv_mem *m = NULL;
|
||||
int out_fd = -1;
|
||||
VkResult r = alloc_shared(dt, st->dev, s, &ai, cfd, &m, &out_fd);
|
||||
if (r != VK_SUCCESS) {
|
||||
VKB_INFO(" %s, type %u: allocation failed (%d)", vkb_mem_strategy_name(s), type, r);
|
||||
if (keep_fd >= 0) close(keep_fd);
|
||||
dt->vkDestroyBuffer(st->dev, buf, NULL);
|
||||
return 0;
|
||||
}
|
||||
int map_fd = s == VKB_MEM_HOSTPTR ? keep_fd : out_fd;
|
||||
uint8_t *cmap = mmap(NULL, (size_t)m->size, PROT_READ | PROT_WRITE, MAP_SHARED, map_fd, 0);
|
||||
if (map_fd >= 0) close(map_fd);
|
||||
void *smap = NULL;
|
||||
if (cmap == MAP_FAILED) {
|
||||
VKB_INFO(" %s, type %u: the client cannot map the memory (%s)", vkb_mem_strategy_name(s), type, strerror(errno));
|
||||
cmap = NULL;
|
||||
goto out;
|
||||
}
|
||||
if (dt->vkBindBufferMemory(st->dev, buf, m->mem, 0) != VK_SUCCESS ||
|
||||
dt->vkMapMemory(st->dev, m->mem, 0, VK_WHOLE_SIZE, 0, &smap) != VK_SUCCESS) {
|
||||
VKB_INFO(" %s, type %u: bind/map failed", vkb_mem_strategy_name(s), type);
|
||||
goto out;
|
||||
}
|
||||
int coherent = (st->mp.memoryTypes[type].propertyFlags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT) != 0;
|
||||
/* VKBRIDGE_SELFTEST_NOFLUSH=1 forces it for every type. */
|
||||
if (no_flush || getenv("VKBRIDGE_SELFTEST_NOFLUSH")) coherent = 1;
|
||||
VkMappedMemoryRange whole = {VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE, NULL, m->mem, 0, VK_WHOLE_SIZE};
|
||||
|
||||
/* 1: the two CPU mappings are the same pages. */
|
||||
for (uint32_t i = 0; i < TEST_SIZE / 4; i += 997) ((volatile uint32_t *)cmap)[i] = 0x11220000u + i;
|
||||
__sync_synchronize();
|
||||
for (uint32_t i = 0; i < TEST_SIZE / 4; i += 997) {
|
||||
if (((volatile uint32_t *)smap)[i] != 0x11220000u + i) {
|
||||
VKB_INFO(" %s, type %u: CPU mappings differ at word %u", vkb_mem_strategy_name(s), type, i);
|
||||
goto out;
|
||||
}
|
||||
}
|
||||
/* 2: GPU writes, client reads. 3: client writes, GPU copies, client reads the copy. */
|
||||
for (uint32_t i = TEST_SIZE / 8; i < TEST_SIZE / 8 + TEST_SIZE / 32; i++) ((volatile uint32_t *)cmap)[i] = 0x5a000000u ^ (i * 2654435761u);
|
||||
if (!coherent) dt->vkFlushMappedMemoryRanges(st->dev, 1, &whole);
|
||||
VkCommandBufferAllocateInfo cai = {VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, NULL, st->pool, VK_COMMAND_BUFFER_LEVEL_PRIMARY, 1};
|
||||
VkCommandBuffer cb;
|
||||
if (dt->vkAllocateCommandBuffers(st->dev, &cai, &cb) != VK_SUCCESS) goto out;
|
||||
VkCommandBufferBeginInfo bi = {VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, NULL, VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT, NULL};
|
||||
dt->vkBeginCommandBuffer(cb, &bi);
|
||||
dt->vkCmdFillBuffer(cb, buf, 0, TEST_SIZE / 8, 0xA5A5A5A5u);
|
||||
/* Layout (bytes): [0, N/8) GPU fill; [N/2, N/2 + N/8) written by the client and copied by
|
||||
* the GPU to [3N/4, 3N/4 + N/8). */
|
||||
VkBufferCopy region = {TEST_SIZE / 2, TEST_SIZE / 4 * 3, TEST_SIZE / 8};
|
||||
dt->vkCmdCopyBuffer(cb, buf, buf, 1, ®ion);
|
||||
VkMemoryBarrier mb = {VK_STRUCTURE_TYPE_MEMORY_BARRIER, NULL, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_HOST_READ_BIT};
|
||||
dt->vkCmdPipelineBarrier(cb, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_HOST_BIT, 0, 1, &mb, 0, NULL, 0, NULL);
|
||||
dt->vkEndCommandBuffer(cb);
|
||||
int submitted = submit_and_wait(st, cb);
|
||||
dt->vkFreeCommandBuffers(st->dev, st->pool, 1, &cb);
|
||||
if (!submitted) {
|
||||
VKB_INFO(" %s, type %u: GPU submission failed", vkb_mem_strategy_name(s), type);
|
||||
goto out;
|
||||
}
|
||||
if (!coherent) dt->vkInvalidateMappedMemoryRanges(st->dev, 1, &whole);
|
||||
for (uint32_t i = 0; i < TEST_SIZE / 32; i++) {
|
||||
if (((volatile uint32_t *)cmap)[i] != 0xA5A5A5A5u) {
|
||||
VKB_INFO(" %s, type %u: the client does not see a GPU write (word %u = 0x%08x)", vkb_mem_strategy_name(s), type, i,
|
||||
((volatile uint32_t *)cmap)[i]);
|
||||
goto out;
|
||||
}
|
||||
}
|
||||
for (uint32_t i = 0; i < TEST_SIZE / 32; i++) {
|
||||
uint32_t want = 0x5a000000u ^ ((TEST_SIZE / 8 + i) * 2654435761u);
|
||||
uint32_t got = ((volatile uint32_t *)cmap)[TEST_SIZE / 16 * 3 + i];
|
||||
if (got != want) {
|
||||
VKB_INFO(" %s, type %u: the GPU does not see a client write (word %u = 0x%08x, want 0x%08x)", vkb_mem_strategy_name(s),
|
||||
type, i, got, want);
|
||||
goto out;
|
||||
}
|
||||
}
|
||||
result = coherent ? 1 : 2;
|
||||
VKB_INFO(" %s, type %u (flags 0x%x): shared OK%s", vkb_mem_strategy_name(s), type, st->mp.memoryTypes[type].propertyFlags,
|
||||
coherent ? ", coherent" : ", needs flushes");
|
||||
out:
|
||||
if (cmap) munmap(cmap, (size_t)m->size);
|
||||
if (smap) dt->vkUnmapMemory(st->dev, m->mem);
|
||||
dt->vkDestroyBuffer(st->dev, buf, NULL);
|
||||
dt->vkFreeMemory(st->dev, m->mem, NULL);
|
||||
mem_release_backing(m);
|
||||
return result;
|
||||
}
|
||||
|
||||
static int has_ext(const VkExtensionProperties *e, uint32_t n, const char *name)
|
||||
{
|
||||
for (uint32_t i = 0; i < n; i++)
|
||||
if (!strcmp(e[i].extensionName, name)) return 1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* What the driver says it can do with each kind of external buffer memory (the device runs). */
|
||||
static void log_external_props(const vkb_dispatch *idt, VkPhysicalDevice pd)
|
||||
{
|
||||
if (!idt->vkGetPhysicalDeviceExternalBufferProperties) return;
|
||||
static const struct { uint32_t bit; const char *name; } types[] = {
|
||||
{VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT, "opaque fd"},
|
||||
{VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT, "dma-buf"},
|
||||
{VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT, "host allocation"},
|
||||
#ifdef __ANDROID__
|
||||
{VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID, "AHB"},
|
||||
#endif
|
||||
};
|
||||
for (size_t i = 0; i < sizeof(types) / sizeof(types[0]); i++) {
|
||||
VkPhysicalDeviceExternalBufferInfo bi = {VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_BUFFER_INFO, NULL, 0,
|
||||
VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT |
|
||||
VK_BUFFER_USAGE_STORAGE_BUFFER_BIT,
|
||||
(VkExternalMemoryHandleTypeFlagBits)types[i].bit};
|
||||
VkExternalBufferProperties ep = {VK_STRUCTURE_TYPE_EXTERNAL_BUFFER_PROPERTIES};
|
||||
idt->vkGetPhysicalDeviceExternalBufferProperties(pd, &bi, &ep);
|
||||
const VkExternalMemoryProperties *p = &ep.externalMemoryProperties;
|
||||
VKB_INFO("external buffers, %s: features 0x%x (%s%s%s), export from 0x%x, compatible 0x%x", types[i].name,
|
||||
p->externalMemoryFeatures,
|
||||
p->externalMemoryFeatures & VK_EXTERNAL_MEMORY_FEATURE_DEDICATED_ONLY_BIT ? "dedicated-only " : "",
|
||||
p->externalMemoryFeatures & VK_EXTERNAL_MEMORY_FEATURE_EXPORTABLE_BIT ? "exportable " : "",
|
||||
p->externalMemoryFeatures & VK_EXTERNAL_MEMORY_FEATURE_IMPORTABLE_BIT ? "importable" : "",
|
||||
p->exportFromImportedHandleTypes, p->compatibleHandleTypes);
|
||||
}
|
||||
}
|
||||
|
||||
void vkb_mem_selftest(vkb_pd_knowledge *k, VkInstance inst, const vkb_dispatch *idt, VkPhysicalDevice pd)
|
||||
{
|
||||
selftest st;
|
||||
memset(&st, 0, sizeof(st));
|
||||
st.idt = idt;
|
||||
st.pd = pd;
|
||||
idt->vkGetPhysicalDeviceMemoryProperties(pd, &st.mp);
|
||||
|
||||
uint32_t nq = 0;
|
||||
idt->vkGetPhysicalDeviceQueueFamilyProperties(pd, &nq, NULL);
|
||||
VkQueueFamilyProperties qp[16];
|
||||
if (nq > 16) nq = 16;
|
||||
idt->vkGetPhysicalDeviceQueueFamilyProperties(pd, &nq, qp);
|
||||
st.qf = 0;
|
||||
for (uint32_t i = 0; i < nq; i++)
|
||||
if (qp[i].queueFlags & (VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT)) {
|
||||
st.qf = i;
|
||||
break;
|
||||
}
|
||||
|
||||
uint32_t ne = 0;
|
||||
idt->vkEnumerateDeviceExtensionProperties(pd, NULL, &ne, NULL);
|
||||
VkExtensionProperties *ex = calloc(ne ? ne : 1, sizeof(*ex));
|
||||
idt->vkEnumerateDeviceExtensionProperties(pd, NULL, &ne, ex);
|
||||
|
||||
uint32_t candidates[4];
|
||||
int nc = 0;
|
||||
const char *force = getenv("VKBRIDGE_MEMORY");
|
||||
/* GameNative's order on Mali: the driver's own export, a dma-heap import, then an AHB. */
|
||||
uint32_t order[] = {VKB_MEM_HOSTPTR, VKB_MEM_DMABUF, VKB_MEM_DMAHEAP, VKB_MEM_AHB};
|
||||
for (int i = 0; i < 4; i++) {
|
||||
uint32_t s = order[i];
|
||||
if (force && strcmp(force, vkb_mem_strategy_name(s))) continue;
|
||||
uint32_t n;
|
||||
const char *const *req = vkb_mem_required_extensions(s, &n);
|
||||
if (!req) continue;
|
||||
int ok = 1;
|
||||
for (uint32_t j = 0; j < n; j++)
|
||||
if (strcmp(req[j], "VK_KHR_external_memory") && strcmp(req[j], "VK_KHR_sampler_ycbcr_conversion") &&
|
||||
strcmp(req[j], "VK_KHR_dedicated_allocation") && strcmp(req[j], "VK_KHR_get_memory_requirements2") &&
|
||||
!has_ext(ex, ne, req[j]))
|
||||
ok = 0;
|
||||
if (ok) candidates[nc++] = s;
|
||||
else VKB_INFO("memory sharing: %s unavailable (driver lacks its extensions)", vkb_mem_strategy_name(s));
|
||||
}
|
||||
|
||||
/* One test device with every candidate's extensions. */
|
||||
const char *exts[16];
|
||||
uint32_t nx = 0;
|
||||
for (int i = 0; i < nc; i++) {
|
||||
uint32_t n;
|
||||
const char *const *req = vkb_mem_required_extensions(candidates[i], &n);
|
||||
for (uint32_t j = 0; j < n; j++) {
|
||||
if (!has_ext(ex, ne, req[j])) continue;
|
||||
int dup = 0;
|
||||
for (uint32_t q = 0; q < nx; q++) dup |= !strcmp(exts[q], req[j]);
|
||||
if (!dup && nx < 16) exts[nx++] = req[j];
|
||||
}
|
||||
}
|
||||
free(ex);
|
||||
float prio = 1.0f;
|
||||
VkDeviceQueueCreateInfo qci = {VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO, NULL, 0, st.qf, 1, &prio};
|
||||
VkDeviceCreateInfo dci = {VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO, NULL, 0, 1, &qci, 0, NULL, nx, exts, NULL};
|
||||
if (idt->vkCreateDevice(pd, &dci, NULL, &st.dev) != VK_SUCCESS) {
|
||||
VKB_ERR("memory self-test: cannot create a device");
|
||||
return;
|
||||
}
|
||||
st.dt = *idt;
|
||||
PFN_vkGetDeviceProcAddr gdpa = (PFN_vkGetDeviceProcAddr)vkb_gipa(inst, "vkGetDeviceProcAddr");
|
||||
vkb_mem_gdpa = gdpa;
|
||||
log_external_props(idt, pd);
|
||||
vkb_dispatch_load_device(&st.dt, gdpa, st.dev);
|
||||
st.dt.vkGetDeviceQueue(st.dev, st.qf, 0, &st.queue);
|
||||
VkCommandPoolCreateInfo pci = {VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO, NULL, 0, st.qf};
|
||||
st.dt.vkCreateCommandPool(st.dev, &pci, NULL, &st.pool);
|
||||
|
||||
VkPhysicalDeviceExternalMemoryHostPropertiesEXT hostp = {VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_MEMORY_HOST_PROPERTIES_EXT};
|
||||
VkPhysicalDeviceProperties2 p2 = {VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &hostp};
|
||||
idt->vkGetPhysicalDeviceProperties2(pd, &p2);
|
||||
st.import_align = hostp.minImportedHostPointerAlignment ? hostp.minImportedHostPointerAlignment : 4096;
|
||||
if (st.import_align < 4096) st.import_align = 4096;
|
||||
|
||||
k->info.strategy = VKB_MEM_NONE;
|
||||
for (int i = 0; i < nc; i++) {
|
||||
uint32_t s = candidates[i];
|
||||
uint32_t shareable = 0, coherent = 0;
|
||||
for (uint32_t t = 0; t < st.mp.memoryTypeCount; t++) {
|
||||
if (!(st.mp.memoryTypes[t].propertyFlags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT)) continue;
|
||||
if (st.mp.memoryTypes[t].propertyFlags & VK_MEMORY_PROPERTY_PROTECTED_BIT) continue;
|
||||
int res = test_type(&st, s, t);
|
||||
if (res) shareable |= 1u << t;
|
||||
if (res == 1) coherent |= 1u << t;
|
||||
}
|
||||
if (coherent) {
|
||||
k->info.strategy = s;
|
||||
k->info.buffer_handle_types = strategy_handle_type(s);
|
||||
k->info.shareable_types = shareable;
|
||||
k->info.coherent_types = coherent;
|
||||
k->info.import_alignment = st.import_align;
|
||||
break;
|
||||
}
|
||||
VKB_INFO("memory sharing: %s failed the self-test", vkb_mem_strategy_name(s));
|
||||
}
|
||||
if (k->info.strategy == VKB_MEM_NONE)
|
||||
VKB_ERR("memory sharing: no method works on %s; Linux programs will get no host-visible memory", k->name);
|
||||
|
||||
st.dt.vkDestroyCommandPool(st.dev, st.pool, NULL);
|
||||
st.dt.vkDestroyDevice(st.dev, NULL);
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
/* SPDX-License-Identifier: GPL-3.0-or-later
|
||||
*
|
||||
* Descriptor update templates. The client repacks the app's data to the layout of the template
|
||||
* it created on the server (entries rewritten to packed offsets), so the blob is used as is.
|
||||
*/
|
||||
#define _GNU_SOURCE
|
||||
#include "vkb_server.h"
|
||||
|
||||
#include <string.h>
|
||||
|
||||
void vkb_sv_vkbDescUpdateRaw(vkb_srv_call *c)
|
||||
{
|
||||
VkDevice dev = (VkDevice)(uintptr_t)vkb_dec_u64(&c->d);
|
||||
VkDescriptorSet set;
|
||||
VkDescriptorUpdateTemplate tmpl;
|
||||
vkb_dec_bytes(&c->d, &set, sizeof(set));
|
||||
vkb_dec_bytes(&c->d, &tmpl, sizeof(tmpl));
|
||||
size_t n = 0;
|
||||
const void *data = vkb_dec_blob(&c->d, &n);
|
||||
if (c->d.err || !c->table) {
|
||||
vkb_srv_bad_message(c);
|
||||
return;
|
||||
}
|
||||
if (!c->dt->vkUpdateDescriptorSetWithTemplate) {
|
||||
vkb_srv_missing(c, "vkUpdateDescriptorSetWithTemplate");
|
||||
return;
|
||||
}
|
||||
c->dt->vkUpdateDescriptorSetWithTemplate(dev, set, tmpl, data);
|
||||
}
|
||||
|
||||
void vkb_sv_vkbPushDescRaw(vkb_srv_call *c)
|
||||
{
|
||||
VkCommandBuffer cb = (VkCommandBuffer)(uintptr_t)vkb_dec_u64(&c->d);
|
||||
VkDescriptorUpdateTemplate tmpl;
|
||||
VkPipelineLayout layout;
|
||||
vkb_dec_bytes(&c->d, &tmpl, sizeof(tmpl));
|
||||
vkb_dec_bytes(&c->d, &layout, sizeof(layout));
|
||||
uint32_t set = vkb_dec_u32(&c->d);
|
||||
size_t n = 0;
|
||||
const void *data = vkb_dec_blob(&c->d, &n);
|
||||
if (c->d.err || !c->table) {
|
||||
vkb_srv_bad_message(c);
|
||||
return;
|
||||
}
|
||||
if (!c->dt->vkCmdPushDescriptorSetWithTemplate) {
|
||||
vkb_srv_missing(c, "vkCmdPushDescriptorSetWithTemplate");
|
||||
return;
|
||||
}
|
||||
extern __thread size_t vkb_emu_push_size;
|
||||
vkb_emu_push_size = n;
|
||||
c->dt->vkCmdPushDescriptorSetWithTemplate(cb, tmpl, layout, set, data);
|
||||
vkb_emu_push_size = 0;
|
||||
}
|
||||
@@ -0,0 +1,291 @@
|
||||
/* SPDX-License-Identifier: GPL-3.0-or-later
|
||||
*
|
||||
* Persistent pipeline cache. Mali compiles every pipeline from scratch in each new process unless
|
||||
* it is handed a VkPipelineCache; games through DXVK pass none. With a cache directory set
|
||||
* (--cache-dir), each device gets a cache loaded from <dir>/<vendor>-<device>-<cacheUUID>.vkpc:
|
||||
* - pipelines created without a cache use it;
|
||||
* - caches the app creates empty start from it, and are merged back into it when destroyed;
|
||||
* - it is written back every few seconds while new pipelines come in (the app stops the server
|
||||
* with SIGKILL, so there is no reliable last chance) and when the device goes away.
|
||||
* The file's header is checked against the GPU before the driver sees it.
|
||||
*/
|
||||
#define _GNU_SOURCE
|
||||
#include "vkb_server.h"
|
||||
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/stat.h>
|
||||
#include <time.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#define PC_MAX_FILE (256u << 20)
|
||||
#define PC_SAVE_PERIOD_S 10
|
||||
|
||||
typedef struct vkb_pcache {
|
||||
vkb_srv_table *t;
|
||||
VkPipelineCache cache;
|
||||
char path[512];
|
||||
int dirty;
|
||||
size_t saved_size;
|
||||
PFN_vkCreateGraphicsPipelines create_gfx;
|
||||
PFN_vkCreateComputePipelines create_compute;
|
||||
PFN_vkCreatePipelineCache create_cache;
|
||||
PFN_vkDestroyPipelineCache destroy_cache;
|
||||
struct vkb_pcache *next;
|
||||
} vkb_pcache;
|
||||
|
||||
static const char *pc_dir;
|
||||
static pthread_mutex_t pc_lock = PTHREAD_MUTEX_INITIALIZER;
|
||||
static vkb_pcache *pc_list;
|
||||
static int pc_thread_started;
|
||||
|
||||
void vkb_pcache_set_dir(const char *dir)
|
||||
{
|
||||
if (!dir || !*dir) return;
|
||||
mkdir(dir, 0700);
|
||||
/* A copy: the JNI entry frees its string once the server is up, and the pointer kept before
|
||||
* printed "pipeline cache \xef\xbf\xbdRYp/13b5-..." and wrote the cache under that name. */
|
||||
char *copy = strdup(dir);
|
||||
if (!copy) return;
|
||||
pc_dir = copy;
|
||||
VKB_INFO("pipeline cache directory %s", dir);
|
||||
}
|
||||
|
||||
static vkb_pcache *cur(void)
|
||||
{
|
||||
vkb_srv_table *t = vkb_srv_current_table();
|
||||
return t ? t->pcache : NULL;
|
||||
}
|
||||
|
||||
/* The header every pipeline cache starts with (VkPipelineCacheHeaderVersionOne). */
|
||||
static int header_ok(const vkb_srv_table *t, const uint8_t *data, size_t size)
|
||||
{
|
||||
VkPipelineCacheHeaderVersionOne h;
|
||||
if (size < sizeof(h)) return 0;
|
||||
memcpy(&h, data, sizeof(h));
|
||||
VkPhysicalDeviceProperties props;
|
||||
t->real.vkGetPhysicalDeviceProperties(t->physical, &props);
|
||||
return h.headerSize >= sizeof(h) && h.headerVersion == VK_PIPELINE_CACHE_HEADER_VERSION_ONE &&
|
||||
h.vendorID == props.vendorID && h.deviceID == props.deviceID &&
|
||||
!memcmp(h.pipelineCacheUUID, props.pipelineCacheUUID, VK_UUID_SIZE);
|
||||
}
|
||||
|
||||
static uint8_t *read_file(const char *path, size_t *size)
|
||||
{
|
||||
*size = 0;
|
||||
int fd = open(path, O_RDONLY | O_CLOEXEC);
|
||||
if (fd < 0) return NULL;
|
||||
struct stat st;
|
||||
uint8_t *buf = NULL;
|
||||
if (fstat(fd, &st) == 0 && st.st_size > 0 && (uint64_t)st.st_size <= PC_MAX_FILE && (buf = malloc((size_t)st.st_size))) {
|
||||
size_t got = 0;
|
||||
while (got < (size_t)st.st_size) {
|
||||
ssize_t r = read(fd, buf + got, (size_t)st.st_size - got);
|
||||
if (r <= 0) break;
|
||||
got += (size_t)r;
|
||||
}
|
||||
if (got == (size_t)st.st_size) {
|
||||
*size = got;
|
||||
} else {
|
||||
free(buf);
|
||||
buf = NULL;
|
||||
}
|
||||
}
|
||||
close(fd);
|
||||
return buf;
|
||||
}
|
||||
|
||||
/* Writes the cache next to its file and renames it over, so a kill mid-write loses nothing. */
|
||||
static void save(vkb_pcache *p)
|
||||
{
|
||||
vkb_srv_table *t = p->t;
|
||||
size_t size = 0;
|
||||
if (t->real.vkGetPipelineCacheData(t->device, p->cache, &size, NULL) != VK_SUCCESS || !size || size > PC_MAX_FILE) return;
|
||||
if (size == p->saved_size) {
|
||||
/* Nothing new was compiled (merges of what it already had leave the size alone). */
|
||||
p->dirty = 0;
|
||||
return;
|
||||
}
|
||||
uint8_t *buf = malloc(size);
|
||||
if (!buf) return;
|
||||
VkResult r = t->real.vkGetPipelineCacheData(t->device, p->cache, &size, buf);
|
||||
if (r == VK_SUCCESS) {
|
||||
char tmp[600];
|
||||
snprintf(tmp, sizeof(tmp), "%s.%d.tmp", p->path, (int)getpid());
|
||||
int fd = open(tmp, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0600);
|
||||
int ok = fd >= 0;
|
||||
for (size_t done = 0; ok && done < size;) {
|
||||
ssize_t w = write(fd, buf + done, size - done);
|
||||
if (w < 0 && errno == EINTR) continue;
|
||||
if (w <= 0) ok = 0;
|
||||
else done += (size_t)w;
|
||||
}
|
||||
if (fd >= 0 && fsync(fd) != 0) ok = 0;
|
||||
if (fd >= 0) close(fd);
|
||||
if (ok && rename(tmp, p->path) == 0) {
|
||||
VKB_INFO("device %u: pipeline cache saved (%zu KB)", t->id, size >> 10);
|
||||
p->saved_size = size;
|
||||
p->dirty = 0;
|
||||
} else {
|
||||
VKB_WARN("device %u: pipeline cache not saved to %s: %s", t->id, p->path, strerror(errno));
|
||||
unlink(tmp);
|
||||
}
|
||||
}
|
||||
free(buf);
|
||||
}
|
||||
|
||||
static void *saver(void *arg)
|
||||
{
|
||||
(void)arg;
|
||||
for (;;) {
|
||||
struct timespec ts = {PC_SAVE_PERIOD_S, 0};
|
||||
nanosleep(&ts, NULL);
|
||||
pthread_mutex_lock(&pc_lock);
|
||||
for (vkb_pcache *p = pc_list; p; p = p->next)
|
||||
if (__atomic_load_n(&p->dirty, __ATOMIC_RELAXED)) save(p);
|
||||
pthread_mutex_unlock(&pc_lock);
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ wrappers */
|
||||
|
||||
static VkResult VKAPI_CALL pc_CreateGraphicsPipelines(VkDevice device, VkPipelineCache cache, uint32_t n,
|
||||
const VkGraphicsPipelineCreateInfo *ci, const VkAllocationCallbacks *a,
|
||||
VkPipeline *out)
|
||||
{
|
||||
vkb_pcache *p = cur();
|
||||
if (!cache) {
|
||||
cache = p->cache;
|
||||
__atomic_store_n(&p->dirty, 1, __ATOMIC_RELAXED);
|
||||
}
|
||||
return p->create_gfx(device, cache, n, ci, a, out);
|
||||
}
|
||||
|
||||
static VkResult VKAPI_CALL pc_CreateComputePipelines(VkDevice device, VkPipelineCache cache, uint32_t n,
|
||||
const VkComputePipelineCreateInfo *ci, const VkAllocationCallbacks *a,
|
||||
VkPipeline *out)
|
||||
{
|
||||
vkb_pcache *p = cur();
|
||||
if (!cache) {
|
||||
cache = p->cache;
|
||||
__atomic_store_n(&p->dirty, 1, __ATOMIC_RELAXED);
|
||||
}
|
||||
return p->create_compute(device, cache, n, ci, a, out);
|
||||
}
|
||||
|
||||
static VkResult VKAPI_CALL pc_CreatePipelineCache(VkDevice device, const VkPipelineCacheCreateInfo *ci,
|
||||
const VkAllocationCallbacks *a, VkPipelineCache *out)
|
||||
{
|
||||
vkb_pcache *p = cur();
|
||||
if (ci->initialDataSize) return p->create_cache(device, ci, a, out);
|
||||
size_t size = 0;
|
||||
uint8_t *buf = NULL;
|
||||
if (p->t->real.vkGetPipelineCacheData(device, p->cache, &size, NULL) == VK_SUCCESS && size && (buf = malloc(size)) &&
|
||||
p->t->real.vkGetPipelineCacheData(device, p->cache, &size, buf) != VK_SUCCESS)
|
||||
size = 0;
|
||||
VkPipelineCacheCreateInfo seeded = *ci;
|
||||
seeded.initialDataSize = buf ? size : 0;
|
||||
seeded.pInitialData = buf;
|
||||
VkResult r = p->create_cache(device, &seeded, a, out);
|
||||
free(buf);
|
||||
return r;
|
||||
}
|
||||
|
||||
static void VKAPI_CALL pc_DestroyPipelineCache(VkDevice device, VkPipelineCache cache, const VkAllocationCallbacks *a)
|
||||
{
|
||||
vkb_pcache *p = cur();
|
||||
if (cache && cache != p->cache && p->t->real.vkMergePipelineCaches(device, p->cache, 1, &cache) == VK_SUCCESS)
|
||||
__atomic_store_n(&p->dirty, 1, __ATOMIC_RELAXED);
|
||||
p->destroy_cache(device, cache, a);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ device hooks */
|
||||
|
||||
void vkb_pcache_device_init(vkb_srv_table *t)
|
||||
{
|
||||
if (!pc_dir || !t->real.vkCreatePipelineCache || !t->real.vkGetPipelineCacheData || !t->real.vkMergePipelineCaches) return;
|
||||
vkb_pcache *p = calloc(1, sizeof(*p));
|
||||
if (!p) return;
|
||||
p->t = t;
|
||||
VkPhysicalDeviceProperties props;
|
||||
t->real.vkGetPhysicalDeviceProperties(t->physical, &props);
|
||||
char uuid[2 * VK_UUID_SIZE + 1];
|
||||
for (int i = 0; i < VK_UUID_SIZE; i++) snprintf(uuid + 2 * i, 3, "%02x", props.pipelineCacheUUID[i]);
|
||||
snprintf(p->path, sizeof(p->path), "%s/%04x-%04x-%s.vkpc", pc_dir, props.vendorID, props.deviceID, uuid);
|
||||
|
||||
size_t size;
|
||||
uint8_t *data = read_file(p->path, &size);
|
||||
if (data && !header_ok(t, data, size)) {
|
||||
VKB_WARN("device %u: %s is not this GPU's pipeline cache; starting empty", t->id, p->path);
|
||||
free(data);
|
||||
data = NULL;
|
||||
size = 0;
|
||||
}
|
||||
VkPipelineCacheCreateInfo ci = {VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO, NULL, 0, data ? size : 0, data};
|
||||
VkResult r = t->real.vkCreatePipelineCache(t->device, &ci, NULL, &p->cache);
|
||||
if (r != VK_SUCCESS && data) {
|
||||
VKB_WARN("device %u: driver refused the saved pipeline cache (%d); starting empty", t->id, r);
|
||||
ci.initialDataSize = 0;
|
||||
ci.pInitialData = NULL;
|
||||
r = t->real.vkCreatePipelineCache(t->device, &ci, NULL, &p->cache);
|
||||
}
|
||||
free(data);
|
||||
if (r != VK_SUCCESS) {
|
||||
VKB_WARN("device %u: no pipeline cache (%d)", t->id, r);
|
||||
free(p);
|
||||
return;
|
||||
}
|
||||
p->saved_size = size;
|
||||
VKB_INFO("device %u: pipeline cache %s (%zu KB loaded)", t->id, p->path, size >> 10);
|
||||
|
||||
vkb_dispatch *dt = &t->dt;
|
||||
p->create_gfx = dt->vkCreateGraphicsPipelines;
|
||||
p->create_compute = dt->vkCreateComputePipelines;
|
||||
p->create_cache = dt->vkCreatePipelineCache;
|
||||
p->destroy_cache = dt->vkDestroyPipelineCache;
|
||||
dt->vkCreateGraphicsPipelines = pc_CreateGraphicsPipelines;
|
||||
dt->vkCreateComputePipelines = pc_CreateComputePipelines;
|
||||
dt->vkCreatePipelineCache = pc_CreatePipelineCache;
|
||||
dt->vkDestroyPipelineCache = pc_DestroyPipelineCache;
|
||||
t->pcache = p;
|
||||
|
||||
pthread_mutex_lock(&pc_lock);
|
||||
p->next = pc_list;
|
||||
pc_list = p;
|
||||
if (!pc_thread_started) {
|
||||
pthread_t th;
|
||||
pthread_attr_t at;
|
||||
pthread_attr_init(&at);
|
||||
pthread_attr_setdetachstate(&at, PTHREAD_CREATE_DETACHED);
|
||||
pc_thread_started = pthread_create(&th, &at, saver, NULL) == 0;
|
||||
pthread_attr_destroy(&at);
|
||||
}
|
||||
pthread_mutex_unlock(&pc_lock);
|
||||
}
|
||||
|
||||
/* Before the device is destroyed: last save, then the cache goes. */
|
||||
void vkb_pcache_device_destroy(vkb_srv_table *t)
|
||||
{
|
||||
vkb_pcache *p = t->pcache;
|
||||
if (!p) return;
|
||||
pthread_mutex_lock(&pc_lock);
|
||||
for (vkb_pcache **pp = &pc_list; *pp; pp = &(*pp)->next) {
|
||||
if (*pp == p) {
|
||||
*pp = p->next;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (p->dirty) save(p);
|
||||
pthread_mutex_unlock(&pc_lock);
|
||||
t->dt.vkCreateGraphicsPipelines = p->create_gfx;
|
||||
t->dt.vkCreateComputePipelines = p->create_compute;
|
||||
t->dt.vkCreatePipelineCache = p->create_cache;
|
||||
t->dt.vkDestroyPipelineCache = p->destroy_cache;
|
||||
t->real.vkDestroyPipelineCache(t->device, p->cache, NULL);
|
||||
t->pcache = NULL;
|
||||
free(p);
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
/* SPDX-License-Identifier: GPL-3.0-or-later
|
||||
*
|
||||
* SPIR-V fixes for Mali's shader compiler, applied to every module the app hands the driver.
|
||||
*
|
||||
* DXVK (1.7.3 and later) guards texture reads with OpSelect(cond, texel, vec4(0)) where cond is an
|
||||
* OpConstantComposite of OpSpecConstantTrue/False. Mali's compiler folds that composite as if it
|
||||
* were a plain constant - taking the spec constants at their default - and every texture reads
|
||||
* black. Declaring the composite OpSpecConstantComposite (same operands, same length) keeps it
|
||||
* specializable and the fold away. Found by leegao (bionic-vulkan-wrapper issue #93,
|
||||
* "OpCompositeConstant" write-up, 2025-08-10); Vortek patches the same pattern.
|
||||
*
|
||||
* The code is patched in place: it lives in the server's receive buffer (vkCreateShaderModule's
|
||||
* pCode, or a VkShaderModuleCreateInfo chained to a pipeline stage), so nothing is copied.
|
||||
* On for ARM GPUs; VKBRIDGE_SPIRV_FIX=1/0 forces it (host tests).
|
||||
*/
|
||||
#define _GNU_SOURCE
|
||||
#include "vkb_server.h"
|
||||
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#define OP_SPEC_CONSTANT_TRUE 48
|
||||
#define OP_SPEC_CONSTANT_FALSE 49
|
||||
#define OP_SPEC_CONSTANT 50
|
||||
#define OP_SPEC_CONSTANT_COMPOSITE 51
|
||||
#define OP_SPEC_CONSTANT_OP 52
|
||||
#define OP_CONSTANT_COMPOSITE 44
|
||||
#define OP_FUNCTION 54
|
||||
|
||||
typedef struct vkb_spvfix {
|
||||
PFN_vkCreateShaderModule create_module;
|
||||
PFN_vkCreateGraphicsPipelines create_gfx;
|
||||
PFN_vkCreateComputePipelines create_compute;
|
||||
unsigned long patched; /* composites changed, for the log */
|
||||
} vkb_spvfix;
|
||||
|
||||
static vkb_spvfix *cur(void)
|
||||
{
|
||||
vkb_srv_table *t = vkb_srv_current_table();
|
||||
return t ? t->spvfix : NULL;
|
||||
}
|
||||
|
||||
/* Patches one module in place; returns the number of composites changed. */
|
||||
static unsigned fix_module(uint32_t *w, size_t bytes)
|
||||
{
|
||||
size_t n = bytes / 4;
|
||||
if (n < 5 || w[0] != 0x07230203u) return 0;
|
||||
uint32_t bound = w[3];
|
||||
if (!bound || bound > (1u << 24)) return 0;
|
||||
uint8_t *spec = calloc(bound, 1);
|
||||
if (!spec) return 0;
|
||||
unsigned changed = 0;
|
||||
for (size_t i = 5; i < n;) {
|
||||
uint32_t op = w[i] & 0xffff, len = w[i] >> 16;
|
||||
if (!len || i + len > n) break;
|
||||
if (op == OP_FUNCTION) break; /* constants all come before the first function */
|
||||
if ((op == OP_SPEC_CONSTANT_TRUE || op == OP_SPEC_CONSTANT_FALSE || op == OP_SPEC_CONSTANT ||
|
||||
op == OP_SPEC_CONSTANT_COMPOSITE || op == OP_SPEC_CONSTANT_OP) && len >= 3 && w[i + 2] < bound) {
|
||||
spec[w[i + 2]] = 1;
|
||||
} else if (op == OP_CONSTANT_COMPOSITE && len >= 3 && w[i + 2] < bound) {
|
||||
int any = 0;
|
||||
for (uint32_t k = 3; k < len; k++) any |= w[i + k] < bound && spec[w[i + k]];
|
||||
if (any) {
|
||||
/* A composite of spec constants is itself one: declared so, it is no longer folded. */
|
||||
w[i] = (len << 16) | OP_SPEC_CONSTANT_COMPOSITE;
|
||||
spec[w[i + 2]] = 1;
|
||||
changed++;
|
||||
}
|
||||
}
|
||||
i += len;
|
||||
}
|
||||
free(spec);
|
||||
return changed;
|
||||
}
|
||||
|
||||
static void note(vkb_spvfix *f, unsigned changed)
|
||||
{
|
||||
if (!changed) return;
|
||||
unsigned long before = __atomic_fetch_add(&f->patched, changed, __ATOMIC_RELAXED);
|
||||
if (!before) VKB_INFO("SPIR-V fix: spec-constant composites redeclared for Mali's compiler (first in this device)");
|
||||
}
|
||||
|
||||
static void fix_stages(vkb_spvfix *f, uint32_t n, const VkPipelineShaderStageCreateInfo *st)
|
||||
{
|
||||
for (uint32_t i = 0; i < n; i++)
|
||||
for (const VkBaseInStructure *b = st[i].pNext; b; b = b->pNext)
|
||||
if (b->sType == VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO) {
|
||||
const VkShaderModuleCreateInfo *mi = (const void *)b;
|
||||
note(f, fix_module((uint32_t *)mi->pCode, mi->codeSize));
|
||||
}
|
||||
}
|
||||
|
||||
static VkResult VKAPI_CALL fx_CreateShaderModule(VkDevice device, const VkShaderModuleCreateInfo *ci, const VkAllocationCallbacks *a,
|
||||
VkShaderModule *out)
|
||||
{
|
||||
vkb_spvfix *f = cur();
|
||||
note(f, fix_module((uint32_t *)ci->pCode, ci->codeSize));
|
||||
return f->create_module(device, ci, a, out);
|
||||
}
|
||||
|
||||
static VkResult VKAPI_CALL fx_CreateGraphicsPipelines(VkDevice device, VkPipelineCache cache, uint32_t n,
|
||||
const VkGraphicsPipelineCreateInfo *ci, const VkAllocationCallbacks *a,
|
||||
VkPipeline *out)
|
||||
{
|
||||
vkb_spvfix *f = cur();
|
||||
for (uint32_t i = 0; i < n; i++) fix_stages(f, ci[i].stageCount, ci[i].pStages);
|
||||
return f->create_gfx(device, cache, n, ci, a, out);
|
||||
}
|
||||
|
||||
static VkResult VKAPI_CALL fx_CreateComputePipelines(VkDevice device, VkPipelineCache cache, uint32_t n,
|
||||
const VkComputePipelineCreateInfo *ci, const VkAllocationCallbacks *a,
|
||||
VkPipeline *out)
|
||||
{
|
||||
vkb_spvfix *f = cur();
|
||||
for (uint32_t i = 0; i < n; i++) fix_stages(f, 1, &ci[i].stage);
|
||||
return f->create_compute(device, cache, n, ci, a, out);
|
||||
}
|
||||
|
||||
void vkb_spvfix_device_init(vkb_srv_table *t)
|
||||
{
|
||||
VkPhysicalDeviceProperties p;
|
||||
t->real.vkGetPhysicalDeviceProperties(t->physical, &p);
|
||||
const char *env = getenv("VKBRIDGE_SPIRV_FIX");
|
||||
int on = env ? strcmp(env, "0") != 0 : p.vendorID == 0x13B5; /* ARM */
|
||||
if (!on || !t->dt.vkCreateShaderModule) return;
|
||||
vkb_spvfix *f = calloc(1, sizeof(*f));
|
||||
if (!f) return;
|
||||
vkb_dispatch *dt = &t->dt;
|
||||
f->create_module = dt->vkCreateShaderModule;
|
||||
f->create_gfx = dt->vkCreateGraphicsPipelines;
|
||||
f->create_compute = dt->vkCreateComputePipelines;
|
||||
dt->vkCreateShaderModule = fx_CreateShaderModule;
|
||||
dt->vkCreateGraphicsPipelines = fx_CreateGraphicsPipelines;
|
||||
dt->vkCreateComputePipelines = fx_CreateComputePipelines;
|
||||
t->spvfix = f;
|
||||
VKB_INFO("device %u: Mali SPIR-V fixes on", t->id);
|
||||
}
|
||||
|
||||
void vkb_spvfix_device_destroy(vkb_srv_table *t)
|
||||
{
|
||||
vkb_spvfix *f = t->spvfix;
|
||||
if (!f) return;
|
||||
t->dt.vkCreateShaderModule = f->create_module;
|
||||
t->dt.vkCreateGraphicsPipelines = f->create_gfx;
|
||||
t->dt.vkCreateComputePipelines = f->create_compute;
|
||||
if (f->patched) VKB_INFO("device %u: SPIR-V fix changed %lu composites", t->id, f->patched);
|
||||
free(f);
|
||||
t->spvfix = NULL;
|
||||
}
|
||||
@@ -0,0 +1,328 @@
|
||||
/* SPDX-License-Identifier: GPL-3.0-or-later */
|
||||
#include "spirv_edit.h"
|
||||
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
int spv_parse(spv_mod *m, const uint32_t *code, size_t bytes)
|
||||
{
|
||||
memset(m, 0, sizeof(*m));
|
||||
if (bytes < 20 || (bytes & 3) || code[0] != 0x07230203u) return -1;
|
||||
memcpy(m->header, code, 20);
|
||||
size_t words = bytes / 4, pos = 5;
|
||||
while (pos < words) {
|
||||
uint32_t n = code[pos] >> 16, op = code[pos] & 0xffff;
|
||||
if (n == 0 || pos + n > words) return -1;
|
||||
spv_insert(m, m->count, (uint16_t)op, code + pos + 1, (uint16_t)(n - 1));
|
||||
if (m->err) return -1;
|
||||
pos += n;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
size_t spv_write(const spv_mod *m, uint32_t **out)
|
||||
{
|
||||
size_t words = 5;
|
||||
for (uint32_t i = 0; i < m->count; i++) words += m->ins[i].n;
|
||||
uint32_t *buf = malloc(words * 4);
|
||||
if (!buf) return 0;
|
||||
memcpy(buf, m->header, 20);
|
||||
size_t pos = 5;
|
||||
for (uint32_t i = 0; i < m->count; i++) {
|
||||
const spv_inst *in = &m->ins[i];
|
||||
buf[pos++] = ((uint32_t)in->n << 16) | in->op;
|
||||
memcpy(buf + pos, in->w, (size_t)(in->n - 1) * 4);
|
||||
pos += in->n - 1;
|
||||
}
|
||||
*out = buf;
|
||||
return words * 4;
|
||||
}
|
||||
|
||||
void spv_free(spv_mod *m)
|
||||
{
|
||||
for (uint32_t i = 0; i < m->count; i++) free(m->ins[i].w);
|
||||
free(m->ins);
|
||||
memset(m, 0, sizeof(*m));
|
||||
}
|
||||
|
||||
uint32_t spv_insert(spv_mod *m, uint32_t at, uint16_t op, const uint32_t *ops, uint16_t nops)
|
||||
{
|
||||
if (m->count == m->cap) {
|
||||
uint32_t nc = m->cap ? m->cap * 2 : 1024;
|
||||
spv_inst *ni = realloc(m->ins, nc * sizeof(*ni));
|
||||
if (!ni) {
|
||||
m->err = 1;
|
||||
return 0;
|
||||
}
|
||||
m->ins = ni;
|
||||
m->cap = nc;
|
||||
}
|
||||
if (at > m->count) at = m->count;
|
||||
memmove(&m->ins[at + 1], &m->ins[at], (m->count - at) * sizeof(spv_inst));
|
||||
spv_inst *in = &m->ins[at];
|
||||
in->op = op;
|
||||
in->n = (uint16_t)(nops + 1);
|
||||
in->w = malloc((size_t)(nops ? nops : 1) * 4);
|
||||
if (!in->w) m->err = 1;
|
||||
else if (nops) memcpy(in->w, ops, (size_t)nops * 4);
|
||||
m->count++;
|
||||
return at;
|
||||
}
|
||||
|
||||
void spv_remove(spv_mod *m, uint32_t at)
|
||||
{
|
||||
if (at >= m->count) return;
|
||||
free(m->ins[at].w);
|
||||
memmove(&m->ins[at], &m->ins[at + 1], (m->count - at - 1) * sizeof(spv_inst));
|
||||
m->count--;
|
||||
}
|
||||
|
||||
int spv_find_op(const spv_mod *m, uint16_t op, uint32_t from)
|
||||
{
|
||||
for (uint32_t i = from; i < m->count; i++)
|
||||
if (m->ins[i].op == op) return (int)i;
|
||||
return -1;
|
||||
}
|
||||
|
||||
static int is_type(uint16_t op) { return op >= 19 && op <= 38; }
|
||||
static int is_const(uint16_t op) { return (op >= 41 && op <= 46) || (op >= 48 && op <= 52); }
|
||||
|
||||
uint32_t spv_result_id(const spv_inst *in)
|
||||
{
|
||||
if (in->n < 2) return 0;
|
||||
if (is_type(in->op) || in->op == SpvOpLabel || in->op == SpvOpString || in->op == SpvOpExtInstImport || in->op == 73)
|
||||
return in->w[0];
|
||||
switch (in->op) {
|
||||
case SpvOpName: case SpvOpMemberName: case SpvOpDecorate: case SpvOpMemberDecorate: case SpvOpEntryPoint:
|
||||
case SpvOpExecutionMode: case SpvOpCapability: case SpvOpExtension: case SpvOpMemoryModel: case SpvOpStore:
|
||||
case SpvOpBranch: case SpvOpBranchConditional: case SpvOpSelectionMerge: case SpvOpReturn: case SpvOpKill:
|
||||
case SpvOpFunctionEnd: case SpvOpLine: case SpvOpNoLine: case SpvOpSource: case SpvOpSourceExtension:
|
||||
case SpvOpDecorateId: case SpvOpDecorateString: case SpvOpMemberDecorateString: case SpvOpModuleProcessed:
|
||||
case SpvOpExecutionModeId: case 246 /* LoopMerge */: case 251 /* Switch */: case 254 /* ReturnValue */:
|
||||
case 255 /* Unreachable */: case 74: case 75: case 224 /* ControlBarrier */: case 225 /* MemoryBarrier */:
|
||||
case SpvOpTerminateInvocation:
|
||||
return 0;
|
||||
default:
|
||||
return in->n >= 3 ? in->w[1] : 0;
|
||||
}
|
||||
}
|
||||
|
||||
int spv_find_def(const spv_mod *m, uint32_t id)
|
||||
{
|
||||
for (uint32_t i = 0; i < m->count; i++)
|
||||
if (spv_result_id(&m->ins[i]) == id) return (int)i;
|
||||
return -1;
|
||||
}
|
||||
|
||||
uint32_t spv_types_end(const spv_mod *m)
|
||||
{
|
||||
int f = spv_find_op(m, SpvOpFunction, 0);
|
||||
return f < 0 ? m->count : (uint32_t)f;
|
||||
}
|
||||
|
||||
uint32_t spv_annotations_end(const spv_mod *m)
|
||||
{
|
||||
uint32_t end = spv_types_end(m);
|
||||
for (uint32_t i = 0; i < end; i++) {
|
||||
uint16_t op = m->ins[i].op;
|
||||
if (is_type(op) || is_const(op) || op == SpvOpVariable || op == SpvOpUndef) return i;
|
||||
}
|
||||
return end;
|
||||
}
|
||||
|
||||
static uint32_t add_global(spv_mod *m, uint16_t op, const uint32_t *ops, uint16_t n)
|
||||
{
|
||||
uint32_t at = spv_types_end(m);
|
||||
spv_insert(m, at, op, ops, n);
|
||||
return at;
|
||||
}
|
||||
|
||||
uint32_t spv_type_float(spv_mod *m, uint32_t width)
|
||||
{
|
||||
for (uint32_t i = 0; i < m->count; i++)
|
||||
if (m->ins[i].op == SpvOpTypeFloat && m->ins[i].w[1] == width && m->ins[i].n == 3) return m->ins[i].w[0];
|
||||
uint32_t id = spv_new_id(m), ops[2] = {id, width};
|
||||
add_global(m, SpvOpTypeFloat, ops, 2);
|
||||
return id;
|
||||
}
|
||||
|
||||
uint32_t spv_type_int(spv_mod *m, uint32_t width, uint32_t sign)
|
||||
{
|
||||
for (uint32_t i = 0; i < m->count; i++)
|
||||
if (m->ins[i].op == SpvOpTypeInt && m->ins[i].w[1] == width && m->ins[i].w[2] == sign) return m->ins[i].w[0];
|
||||
uint32_t id = spv_new_id(m), ops[3] = {id, width, sign};
|
||||
add_global(m, SpvOpTypeInt, ops, 3);
|
||||
return id;
|
||||
}
|
||||
|
||||
uint32_t spv_type_bool(spv_mod *m)
|
||||
{
|
||||
for (uint32_t i = 0; i < m->count; i++)
|
||||
if (m->ins[i].op == SpvOpTypeBool) return m->ins[i].w[0];
|
||||
uint32_t id = spv_new_id(m);
|
||||
add_global(m, SpvOpTypeBool, &id, 1);
|
||||
return id;
|
||||
}
|
||||
|
||||
uint32_t spv_type_pointer(spv_mod *m, uint32_t storage, uint32_t pointee)
|
||||
{
|
||||
for (uint32_t i = 0; i < m->count; i++)
|
||||
if (m->ins[i].op == SpvOpTypePointer && m->ins[i].w[1] == storage && m->ins[i].w[2] == pointee) return m->ins[i].w[0];
|
||||
uint32_t id = spv_new_id(m), ops[3] = {id, storage, pointee};
|
||||
add_global(m, SpvOpTypePointer, ops, 3);
|
||||
return id;
|
||||
}
|
||||
|
||||
uint32_t spv_type_array(spv_mod *m, uint32_t elem, uint32_t len_const)
|
||||
{
|
||||
for (uint32_t i = 0; i < m->count; i++) {
|
||||
if (m->ins[i].op == SpvOpTypeArray && m->ins[i].w[1] == elem && m->ins[i].w[2] == len_const &&
|
||||
spv_get_decoration(m, m->ins[i].w[0], 6 /* ArrayStride */) < 0)
|
||||
return m->ins[i].w[0];
|
||||
}
|
||||
uint32_t id = spv_new_id(m), ops[3] = {id, elem, len_const};
|
||||
add_global(m, SpvOpTypeArray, ops, 3);
|
||||
return id;
|
||||
}
|
||||
|
||||
uint32_t spv_const_u32(spv_mod *m, uint32_t v)
|
||||
{
|
||||
uint32_t t = spv_type_int(m, 32, 0);
|
||||
for (uint32_t i = 0; i < m->count; i++)
|
||||
if (m->ins[i].op == SpvOpConstant && m->ins[i].w[0] == t && m->ins[i].n == 4 && m->ins[i].w[2] == v) return m->ins[i].w[1];
|
||||
uint32_t id = spv_new_id(m), ops[3] = {t, id, v};
|
||||
add_global(m, SpvOpConstant, ops, 3);
|
||||
return id;
|
||||
}
|
||||
|
||||
uint32_t spv_const_f32(spv_mod *m, float v)
|
||||
{
|
||||
uint32_t t = spv_type_float(m, 32), bits;
|
||||
memcpy(&bits, &v, 4);
|
||||
for (uint32_t i = 0; i < m->count; i++)
|
||||
if (m->ins[i].op == SpvOpConstant && m->ins[i].w[0] == t && m->ins[i].n == 4 && m->ins[i].w[2] == bits) return m->ins[i].w[1];
|
||||
uint32_t id = spv_new_id(m), ops[3] = {t, id, bits};
|
||||
add_global(m, SpvOpConstant, ops, 3);
|
||||
return id;
|
||||
}
|
||||
|
||||
int64_t spv_get_decoration(const spv_mod *m, uint32_t id, uint32_t decoration)
|
||||
{
|
||||
for (uint32_t i = 0; i < m->count; i++) {
|
||||
const spv_inst *in = &m->ins[i];
|
||||
if (in->op == SpvOpDecorate && in->w[0] == id && in->w[1] == decoration) return in->n > 3 ? (int64_t)in->w[2] : 0;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
void spv_remove_decoration(spv_mod *m, uint32_t id, uint32_t decoration)
|
||||
{
|
||||
for (uint32_t i = 0; i < m->count;) {
|
||||
const spv_inst *in = &m->ins[i];
|
||||
if (in->op == SpvOpDecorate && in->w[0] == id && in->w[1] == decoration) spv_remove(m, i);
|
||||
else i++;
|
||||
}
|
||||
}
|
||||
|
||||
int spv_has_capability(const spv_mod *m, uint32_t cap)
|
||||
{
|
||||
for (uint32_t i = 0; i < m->count; i++)
|
||||
if (m->ins[i].op == SpvOpCapability && m->ins[i].w[0] == cap) return 1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
void spv_remove_capability(spv_mod *m, uint32_t cap)
|
||||
{
|
||||
for (uint32_t i = 0; i < m->count;) {
|
||||
if (m->ins[i].op == SpvOpCapability && m->ins[i].w[0] == cap) spv_remove(m, i);
|
||||
else i++;
|
||||
}
|
||||
}
|
||||
|
||||
void spv_add_capability(spv_mod *m, uint32_t cap)
|
||||
{
|
||||
if (!spv_has_capability(m, cap)) spv_insert(m, 0, SpvOpCapability, &cap, 1);
|
||||
}
|
||||
|
||||
int spv_execution_model(const spv_mod *m)
|
||||
{
|
||||
int e = spv_find_op(m, SpvOpEntryPoint, 0);
|
||||
return e < 0 ? -1 : (int)m->ins[e].w[0];
|
||||
}
|
||||
|
||||
void spv_add_interface(spv_mod *m, uint32_t var)
|
||||
{
|
||||
for (uint32_t i = 0; i < m->count; i++) {
|
||||
spv_inst *in = &m->ins[i];
|
||||
if (in->op != SpvOpEntryPoint) continue;
|
||||
uint32_t *nw = realloc(in->w, (size_t)in->n * 4);
|
||||
if (!nw) {
|
||||
m->err = 1;
|
||||
return;
|
||||
}
|
||||
nw[in->n - 1] = var;
|
||||
in->w = nw;
|
||||
in->n++;
|
||||
}
|
||||
}
|
||||
|
||||
uint32_t spv_array_length(const spv_mod *m, uint32_t array_type)
|
||||
{
|
||||
int d = spv_find_def(m, array_type);
|
||||
if (d < 0 || m->ins[d].op != SpvOpTypeArray) return 0;
|
||||
int c = spv_find_def(m, m->ins[d].w[2]);
|
||||
if (c < 0 || m->ins[c].op != SpvOpConstant) return 0;
|
||||
return m->ins[c].w[2];
|
||||
}
|
||||
|
||||
/* Number of locations a type occupies. */
|
||||
static uint32_t loc_count(const spv_mod *m, uint32_t type, int depth)
|
||||
{
|
||||
int d = spv_find_def(m, type);
|
||||
if (d < 0 || depth > 16) return 1;
|
||||
const spv_inst *in = &m->ins[d];
|
||||
switch (in->op) {
|
||||
case SpvOpTypeArray: return spv_array_length(m, type) * loc_count(m, in->w[1], depth + 1);
|
||||
case 24 /* Matrix */: return in->w[2] * loc_count(m, in->w[1], depth + 1);
|
||||
case SpvOpTypeStruct: {
|
||||
uint32_t s = 0;
|
||||
for (uint32_t k = 1; k < (uint32_t)in->n - 1; k++) s += loc_count(m, in->w[k], depth + 1);
|
||||
return s;
|
||||
}
|
||||
case SpvOpTypeVector: {
|
||||
int e = spv_find_def(m, in->w[1]);
|
||||
uint32_t width = e >= 0 ? m->ins[e].w[1] : 32;
|
||||
return (width == 64 && in->w[2] > 2) ? 2 : 1;
|
||||
}
|
||||
default: return 1;
|
||||
}
|
||||
}
|
||||
|
||||
int spv_max_location(const spv_mod *m, uint32_t storage)
|
||||
{
|
||||
int max = -1;
|
||||
for (uint32_t i = 0; i < m->count; i++) {
|
||||
const spv_inst *in = &m->ins[i];
|
||||
if (in->op != SpvOpVariable || in->w[2] != storage) continue;
|
||||
int p = spv_find_def(m, in->w[0]);
|
||||
if (p < 0) continue;
|
||||
uint32_t pointee = m->ins[p].w[2];
|
||||
int64_t loc = spv_get_decoration(m, in->w[1], SpvDecorationLocation);
|
||||
if (loc >= 0) {
|
||||
int top = (int)loc + (int)loc_count(m, pointee, 0) - 1;
|
||||
if (top > max) max = top;
|
||||
continue;
|
||||
}
|
||||
/* A block with member locations. */
|
||||
for (uint32_t k = 0; k < m->count; k++) {
|
||||
const spv_inst *md = &m->ins[k];
|
||||
if (md->op == SpvOpMemberDecorate && md->w[0] == pointee && md->w[2] == SpvDecorationLocation) {
|
||||
int st = spv_find_def(m, pointee);
|
||||
uint32_t mt = st >= 0 && md->w[1] + 1 < m->ins[st].n ? m->ins[st].w[1 + md->w[1]] : 0;
|
||||
int top = (int)md->w[3] + (int)loc_count(m, mt, 0) - 1;
|
||||
if (top > max) max = top;
|
||||
}
|
||||
}
|
||||
}
|
||||
return max;
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
/* SPDX-License-Identifier: GPL-3.0-or-later
|
||||
*
|
||||
* A small SPIR-V editor for the bridge's shader emulations: parse a module into instructions,
|
||||
* look things up, append/insert/remove instructions, and write it back.
|
||||
*/
|
||||
#ifndef VKB_SPIRV_EDIT_H
|
||||
#define VKB_SPIRV_EDIT_H
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
/* Opcodes and enums used (from the SPIR-V spec). */
|
||||
enum {
|
||||
SpvOpName = 5, SpvOpMemberName = 6, SpvOpExtension = 10, SpvOpExtInstImport = 11, SpvOpMemoryModel = 14,
|
||||
SpvOpEntryPoint = 15, SpvOpExecutionMode = 16, SpvOpCapability = 17, SpvOpTypeVoid = 19, SpvOpTypeBool = 20,
|
||||
SpvOpTypeInt = 21, SpvOpTypeFloat = 22, SpvOpTypeVector = 23, SpvOpTypeArray = 28, SpvOpTypeRuntimeArray = 29,
|
||||
SpvOpTypeStruct = 30, SpvOpTypePointer = 32, SpvOpTypeFunction = 33, SpvOpConstantTrue = 41,
|
||||
SpvOpConstantFalse = 42, SpvOpConstant = 43, SpvOpConstantComposite = 44, SpvOpFunction = 54,
|
||||
SpvOpFunctionParameter = 55, SpvOpFunctionEnd = 56, SpvOpVariable = 59, SpvOpLoad = 61, SpvOpStore = 62,
|
||||
SpvOpAccessChain = 65, SpvOpInBoundsAccessChain = 66, SpvOpDecorate = 71, SpvOpMemberDecorate = 72,
|
||||
SpvOpCompositeExtract = 81, SpvOpFOrdLessThan = 184, SpvOpLogicalOr = 166, SpvOpSelectionMerge = 247,
|
||||
SpvOpLabel = 248, SpvOpBranch = 249, SpvOpBranchConditional = 250, SpvOpReturn = 253, SpvOpKill = 252,
|
||||
SpvOpTerminateInvocation = 4416, SpvOpLine = 8, SpvOpNoLine = 317, SpvOpModuleProcessed = 330,
|
||||
SpvOpString = 7, SpvOpSource = 3, SpvOpSourceExtension = 4, SpvOpSourceContinued = 2, SpvOpExecutionModeId = 331,
|
||||
SpvOpDecorateId = 332, SpvOpDecorateString = 5632, SpvOpMemberDecorateString = 5633, SpvOpUndef = 1,
|
||||
SpvOpExtInst = 12, SpvOpIAdd = 128, SpvOpUDiv = 134, SpvOpISub = 130,
|
||||
};
|
||||
enum { SpvDecorationBuiltIn = 11, SpvDecorationLocation = 30, SpvDecorationComponent = 31, SpvDecorationBlock = 2,
|
||||
SpvDecorationFlat = 14, SpvDecorationPatch = 15 };
|
||||
enum { SpvBuiltInPosition = 0, SpvBuiltInPointSize = 1, SpvBuiltInClipDistance = 3, SpvBuiltInCullDistance = 4,
|
||||
SpvBuiltInInstanceIndex = 43, SpvBuiltInBaseInstance = 4425 };
|
||||
enum { SpvStorageClassInput = 1, SpvStorageClassOutput = 3, SpvStorageClassPrivate = 6, SpvStorageClassFunction = 7 };
|
||||
enum { SpvCapabilityClipDistance = 32, SpvCapabilityCullDistance = 33, SpvCapabilityTessellationPointSize = 23,
|
||||
SpvCapabilityGeometryPointSize = 24, SpvCapabilityDrawParameters = 4427 };
|
||||
enum { SpvExecutionModelVertex = 0, SpvExecutionModelTessellationControl = 1, SpvExecutionModelTessellationEvaluation = 2,
|
||||
SpvExecutionModelGeometry = 3, SpvExecutionModelFragment = 4, SpvExecutionModelGLCompute = 5 };
|
||||
|
||||
typedef struct spv_inst {
|
||||
uint16_t op;
|
||||
uint16_t n; /* word count including the first word */
|
||||
uint32_t *w; /* operand words (w[0] = first operand), n - 1 of them */
|
||||
} spv_inst;
|
||||
|
||||
typedef struct spv_mod {
|
||||
uint32_t header[5];
|
||||
spv_inst *ins;
|
||||
uint32_t count, cap;
|
||||
int err;
|
||||
} spv_mod;
|
||||
|
||||
int spv_parse(spv_mod *m, const uint32_t *code, size_t bytes);
|
||||
/* Writes the module into a malloc'd buffer; returns its size in bytes (0 on failure). */
|
||||
size_t spv_write(const spv_mod *m, uint32_t **out);
|
||||
void spv_free(spv_mod *m);
|
||||
|
||||
static inline uint32_t spv_version(const spv_mod *m) { return m->header[1]; }
|
||||
static inline uint32_t spv_new_id(spv_mod *m) { return m->header[3]++; }
|
||||
|
||||
/* Insert an instruction before index `at` (at = count appends). Operands copied. Returns index. */
|
||||
uint32_t spv_insert(spv_mod *m, uint32_t at, uint16_t op, const uint32_t *ops, uint16_t nops);
|
||||
void spv_remove(spv_mod *m, uint32_t at);
|
||||
|
||||
/* Index of the first instruction with this opcode (or of the defining instruction of `id`), or -1. */
|
||||
int spv_find_op(const spv_mod *m, uint16_t op, uint32_t from);
|
||||
int spv_find_def(const spv_mod *m, uint32_t id);
|
||||
/* The id an instruction defines (result id), or 0. */
|
||||
uint32_t spv_result_id(const spv_inst *in);
|
||||
|
||||
/* Section boundaries: index where new decorations / types / function code may be inserted. */
|
||||
uint32_t spv_types_end(const spv_mod *m); /* end of the types/constants/globals section */
|
||||
uint32_t spv_annotations_end(const spv_mod *m); /* end of the decoration section */
|
||||
|
||||
/* Types and constants: found when they already exist (non-aggregate types must be unique). */
|
||||
uint32_t spv_type_float(spv_mod *m, uint32_t width);
|
||||
uint32_t spv_type_int(spv_mod *m, uint32_t width, uint32_t sign);
|
||||
uint32_t spv_type_bool(spv_mod *m);
|
||||
uint32_t spv_type_pointer(spv_mod *m, uint32_t storage, uint32_t pointee);
|
||||
uint32_t spv_type_array(spv_mod *m, uint32_t elem, uint32_t len_const);
|
||||
uint32_t spv_const_u32(spv_mod *m, uint32_t v);
|
||||
uint32_t spv_const_f32(spv_mod *m, float v);
|
||||
|
||||
/* Decorations of an id: returns the operand (after the decoration) or -1. */
|
||||
int64_t spv_get_decoration(const spv_mod *m, uint32_t id, uint32_t decoration);
|
||||
void spv_remove_decoration(spv_mod *m, uint32_t id, uint32_t decoration);
|
||||
int spv_has_capability(const spv_mod *m, uint32_t cap);
|
||||
void spv_remove_capability(spv_mod *m, uint32_t cap);
|
||||
void spv_add_capability(spv_mod *m, uint32_t cap);
|
||||
/* The execution model of the (first) entry point, or -1. */
|
||||
int spv_execution_model(const spv_mod *m);
|
||||
/* Adds an interface variable to every entry point. */
|
||||
void spv_add_interface(spv_mod *m, uint32_t var);
|
||||
/* Highest Location used by variables of a storage class (members included), or -1. */
|
||||
int spv_max_location(const spv_mod *m, uint32_t storage);
|
||||
/* Length of an OpTypeArray (via its constant), or 0. */
|
||||
uint32_t spv_array_length(const spv_mod *m, uint32_t array_type);
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,153 @@
|
||||
/* SPDX-License-Identifier: GPL-3.0-or-later
|
||||
*
|
||||
* DroidDeck Vulkan bridge - server side (bionic on the device, glibc for host tests).
|
||||
*
|
||||
* The server owns the real Vulkan objects. Linux programs in the session talk to it through the
|
||||
* client ICD (tools/vkbridge/client) over a Unix socket; every connection is one client thread.
|
||||
*/
|
||||
#ifndef VKB_SERVER_H
|
||||
#define VKB_SERVER_H
|
||||
|
||||
#include <pthread.h>
|
||||
#include <stdint.h>
|
||||
|
||||
#include "vkb_server_iface.h"
|
||||
#include "vkb_proto.h"
|
||||
#include "vkb_log.h"
|
||||
#include "gen/vkb_server_gen.h"
|
||||
|
||||
#define VKB_MAX_TABLES 65536
|
||||
#define VKB_MAX_PDS 16
|
||||
|
||||
/* A client process (all connections that said hello with the same token). */
|
||||
#define VKB_SEQ_RING 65536
|
||||
|
||||
typedef struct vkb_srv_proc {
|
||||
uint64_t token;
|
||||
int pid;
|
||||
int conns;
|
||||
struct vkb_srv_proc *next;
|
||||
/* Ordering of the process's asynchronous requests (vkb_msg_hdr.seq/barrier). */
|
||||
pthread_mutex_t olock;
|
||||
pthread_cond_t ocond;
|
||||
uint64_t watermark; /* every async seq <= this has run */
|
||||
uint8_t done[VKB_SEQ_RING]; /* seqs above the watermark that have run */
|
||||
int conn_closed; /* a connection ended (a seq may never arrive) */
|
||||
int driver_crashed; /* the driver faulted serving it: its objects are left alone */
|
||||
} vkb_srv_proc;
|
||||
|
||||
typedef struct vkb_srv_conn {
|
||||
int sock;
|
||||
vkb_srv_proc *proc;
|
||||
/* Receive buffer: messages are parsed out of it in place (srv_recv). */
|
||||
uint8_t *rb;
|
||||
size_t rcap, rpos, rlen;
|
||||
int fdq[2 * VKB_MAX_FDS]; /* descriptors received ahead of their message's turn */
|
||||
int fdn;
|
||||
vkb_arena arena;
|
||||
pthread_t thread;
|
||||
} vkb_srv_conn;
|
||||
|
||||
/* Startup knowledge about each physical device (keyed by deviceUUID). */
|
||||
typedef struct vkb_pd_knowledge {
|
||||
uint8_t uuid[VK_UUID_SIZE];
|
||||
char name[VK_MAX_PHYSICAL_DEVICE_NAME_SIZE];
|
||||
vkb_server_pd_info info;
|
||||
int valid;
|
||||
} vkb_pd_knowledge;
|
||||
|
||||
/* A tracked device memory allocation. */
|
||||
typedef struct vkb_srv_mem {
|
||||
VkDeviceMemory mem;
|
||||
VkDeviceSize size;
|
||||
uint32_t type;
|
||||
uint32_t strategy;
|
||||
void *host_ptr; /* hostptr: server's mapping of the client's memfd */
|
||||
size_t host_len;
|
||||
void *mapped; /* server-side vkMapMemory pointer (for flush/invalidate) */
|
||||
void *ahb; /* AHardwareBuffer* (Android) */
|
||||
struct vkb_srv_mem *next;
|
||||
} vkb_srv_mem;
|
||||
|
||||
struct vkb_emu_device;
|
||||
|
||||
typedef struct vkb_srv_table {
|
||||
uint32_t id;
|
||||
int is_device;
|
||||
vkb_srv_proc *proc;
|
||||
VkInstance instance;
|
||||
VkDevice device;
|
||||
VkPhysicalDevice physical; /* device tables */
|
||||
struct vkb_srv_table *parent; /* device -> instance */
|
||||
vkb_dispatch dt; /* what handlers call (may hold emulation wrappers) */
|
||||
vkb_dispatch real; /* the driver's own entry points */
|
||||
uint32_t api_version;
|
||||
const vkb_pd_knowledge *pd;
|
||||
pthread_mutex_t lock;
|
||||
vkb_srv_mem *mems[256]; /* hash by handle */
|
||||
struct vkb_emu_device *emu;
|
||||
struct vkb_pcache *pcache; /* server_pcache.c */
|
||||
struct vkb_dsmap *dsmap; /* server_dsmap.c */
|
||||
struct vkb_spvfix *spvfix; /* server_spvfix.c */
|
||||
struct vkb_cbtrack *cbtrack; /* server_cbtrack.c */
|
||||
} vkb_srv_table;
|
||||
|
||||
/* server_main.c */
|
||||
extern PFN_vkGetInstanceProcAddr vkb_gipa;
|
||||
extern vkb_dispatch vkb_global_dt;
|
||||
extern int vkb_verbose;
|
||||
|
||||
void vkb_log_summary(void);
|
||||
|
||||
/* server_cbtrack.c: command buffers the device handed out; others are refused, not passed on. */
|
||||
void vkb_cbtrack_device_init(vkb_srv_table *t);
|
||||
void vkb_cbtrack_device_destroy(vkb_srv_table *t);
|
||||
int vkb_cbtrack_known(vkb_srv_table *t, VkCommandBuffer cb, const char *what);
|
||||
|
||||
/* server_spvfix.c */
|
||||
void vkb_spvfix_device_init(vkb_srv_table *t);
|
||||
void vkb_spvfix_device_destroy(vkb_srv_table *t);
|
||||
|
||||
/* server_dsmap.c */
|
||||
void vkb_dsmap_device_init(vkb_srv_table *t);
|
||||
void vkb_dsmap_device_destroy(vkb_srv_table *t);
|
||||
|
||||
/* server_pcache.c */
|
||||
void vkb_pcache_set_dir(const char *dir);
|
||||
void vkb_pcache_device_init(vkb_srv_table *t);
|
||||
void vkb_pcache_device_destroy(vkb_srv_table *t);
|
||||
|
||||
/* server_conn.c */
|
||||
void vkb_srv_serve(int listen_fd);
|
||||
vkb_srv_table *vkb_table_get(uint32_t id);
|
||||
uint32_t vkb_table_register(vkb_srv_table *t);
|
||||
void vkb_table_unregister(vkb_srv_table *t);
|
||||
void vkb_srv_reply_status(vkb_srv_call *c, uint32_t status);
|
||||
/* The table of the call being executed on this thread (emulation wrappers use it). */
|
||||
vkb_srv_table *vkb_srv_current_table(void);
|
||||
void vkb_srv_set_current_table(vkb_srv_table *t);
|
||||
void vkb_proc_cleanup(vkb_srv_proc *p);
|
||||
|
||||
/* server_instance.c */
|
||||
void vkb_selftest_all(void);
|
||||
const vkb_pd_knowledge *vkb_pd_lookup(const vkb_dispatch *dt, VkPhysicalDevice pd);
|
||||
extern vkb_pd_knowledge vkb_pds[VKB_MAX_PDS];
|
||||
extern int vkb_npds;
|
||||
|
||||
/* server_memory.c */
|
||||
extern PFN_vkGetDeviceProcAddr vkb_mem_gdpa;
|
||||
void vkb_mem_selftest(vkb_pd_knowledge *k, VkInstance inst, const vkb_dispatch *idt, VkPhysicalDevice pd);
|
||||
const char *const *vkb_mem_required_extensions(uint32_t strategy, uint32_t *count);
|
||||
void vkb_mem_track(vkb_srv_table *dev, vkb_srv_mem *m);
|
||||
vkb_srv_mem *vkb_mem_find(vkb_srv_table *dev, VkDeviceMemory mem, int remove);
|
||||
void vkb_mem_release(vkb_srv_table *dev, vkb_srv_mem *m);
|
||||
void vkb_mem_free_all(vkb_srv_table *dev);
|
||||
|
||||
/* emulation (server_emu*.c) */
|
||||
uint32_t vkb_emu_detect(const vkb_dispatch *idt, VkPhysicalDevice pd, uint32_t *missing);
|
||||
void vkb_emu_device_create_info(vkb_srv_table *inst, VkPhysicalDevice pd, uint32_t emu,
|
||||
VkDeviceCreateInfo *ci, vkb_arena *a);
|
||||
void vkb_emu_device_init(vkb_srv_table *dev, uint32_t emu);
|
||||
void vkb_emu_device_destroy(vkb_srv_table *dev);
|
||||
|
||||
#endif
|
||||
@@ -14,6 +14,7 @@ add_library(droiddeckwayland SHARED
|
||||
src/waylandcomp_jni.c
|
||||
src/droiddeck_ext.c
|
||||
src/wl_dmabuf.c
|
||||
src/wl_android_buffer.c
|
||||
src/wl_clipboard.c
|
||||
src/wl_text_input.c
|
||||
src/wl_toplevel_icon.c
|
||||
@@ -24,6 +25,7 @@ add_library(droiddeckwayland SHARED
|
||||
generated/color-management-v1-protocol.c
|
||||
generated/xdg-shell-protocol.c
|
||||
generated/linux-dmabuf-v1-protocol.c
|
||||
generated/wayland-android-protocol.c
|
||||
generated/viewporter-protocol.c
|
||||
generated/banner-desktop-v1-protocol.c
|
||||
generated/presentation-time-protocol.c
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
/* Generated by wayland-scanner 1.26.0 */
|
||||
|
||||
/*
|
||||
* Copyright © 2012 Collabora, Ltd.
|
||||
*
|
||||
* Permission to use, copy, modify, distribute, and sell this
|
||||
* software and its documentation for any purpose is hereby granted
|
||||
* without fee, provided that the above copyright notice appear in
|
||||
* all copies and that both that copyright notice and this permission
|
||||
* notice appear in supporting documentation, and that the name of
|
||||
* the copyright holders not be used in advertising or publicity
|
||||
* pertaining to distribution of the software without specific,
|
||||
* written prior permission. The copyright holders make no
|
||||
* representations about the suitability of this software for any
|
||||
* purpose. It is provided "as is" without express or implied
|
||||
* warranty.
|
||||
*
|
||||
* THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS
|
||||
* SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
|
||||
* FITNESS, IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY
|
||||
* SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
||||
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
|
||||
* AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
|
||||
* ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
|
||||
* THIS SOFTWARE.
|
||||
*/
|
||||
|
||||
#include <stdbool.h>
|
||||
#include <stdlib.h>
|
||||
#include <stdint.h>
|
||||
#include "wayland-util.h"
|
||||
|
||||
#ifndef __has_attribute
|
||||
# define __has_attribute(x) 0 /* Compatibility with non-clang compilers. */
|
||||
#endif
|
||||
|
||||
#if (__has_attribute(visibility) || defined(__GNUC__) && __GNUC__ >= 4)
|
||||
#define WL_PRIVATE __attribute__ ((visibility("hidden")))
|
||||
#else
|
||||
#define WL_PRIVATE
|
||||
#endif
|
||||
|
||||
extern const struct wl_interface android_wlegl_handle_interface;
|
||||
extern const struct wl_interface android_wlegl_server_buffer_handle_interface;
|
||||
extern const struct wl_interface wl_buffer_interface;
|
||||
|
||||
static const struct wl_interface *android_types[] = {
|
||||
NULL,
|
||||
NULL,
|
||||
&android_wlegl_handle_interface,
|
||||
NULL,
|
||||
NULL,
|
||||
&wl_buffer_interface,
|
||||
NULL,
|
||||
NULL,
|
||||
NULL,
|
||||
NULL,
|
||||
NULL,
|
||||
&android_wlegl_handle_interface,
|
||||
&android_wlegl_server_buffer_handle_interface,
|
||||
NULL,
|
||||
NULL,
|
||||
NULL,
|
||||
NULL,
|
||||
&wl_buffer_interface,
|
||||
NULL,
|
||||
NULL,
|
||||
};
|
||||
|
||||
static const struct wl_message android_wlegl_requests[] = {
|
||||
{ "create_handle", "nia", android_types + 2 },
|
||||
{ "create_buffer", "niiiiio", android_types + 5 },
|
||||
{ "get_server_buffer_handle", "2niiii", android_types + 12 },
|
||||
};
|
||||
|
||||
WL_PRIVATE const struct wl_interface android_wlegl_interface = {
|
||||
"android_wlegl", 3,
|
||||
3, android_wlegl_requests,
|
||||
0, NULL,
|
||||
};
|
||||
|
||||
static const struct wl_message android_wlegl_handle_requests[] = {
|
||||
{ "add_fd", "h", android_types + 0 },
|
||||
{ "destroy", "", android_types + 0 },
|
||||
};
|
||||
|
||||
WL_PRIVATE const struct wl_interface android_wlegl_handle_interface = {
|
||||
"android_wlegl_handle", 1,
|
||||
2, android_wlegl_handle_requests,
|
||||
0, NULL,
|
||||
};
|
||||
|
||||
static const struct wl_message android_wlegl_server_buffer_handle_events[] = {
|
||||
{ "buffer_fd", "h", android_types + 0 },
|
||||
{ "buffer_ints", "a", android_types + 0 },
|
||||
{ "buffer", "nii", android_types + 17 },
|
||||
{ "linear_layout", "3uu", android_types + 0 },
|
||||
};
|
||||
|
||||
WL_PRIVATE const struct wl_interface android_wlegl_server_buffer_handle_interface = {
|
||||
"android_wlegl_server_buffer_handle", 3,
|
||||
0, NULL,
|
||||
4, android_wlegl_server_buffer_handle_events,
|
||||
};
|
||||
@@ -0,0 +1,341 @@
|
||||
/* Generated by wayland-scanner 1.26.0 */
|
||||
|
||||
#ifndef ANDROID_SERVER_PROTOCOL_H
|
||||
#define ANDROID_SERVER_PROTOCOL_H
|
||||
|
||||
#include <stdint.h>
|
||||
#include <stddef.h>
|
||||
#include "wayland-server.h"
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
struct wl_client;
|
||||
struct wl_resource;
|
||||
|
||||
/**
|
||||
* @page page_android The android protocol
|
||||
* @section page_ifaces_android Interfaces
|
||||
* - @subpage page_iface_android_wlegl - Android EGL graphics buffer support
|
||||
* - @subpage page_iface_android_wlegl_handle - An Android native_handle_t object
|
||||
* - @subpage page_iface_android_wlegl_server_buffer_handle - a server allocated buffer
|
||||
* @section page_copyright_android Copyright
|
||||
* <pre>
|
||||
*
|
||||
* Copyright © 2012 Collabora, Ltd.
|
||||
*
|
||||
* Permission to use, copy, modify, distribute, and sell this
|
||||
* software and its documentation for any purpose is hereby granted
|
||||
* without fee, provided that the above copyright notice appear in
|
||||
* all copies and that both that copyright notice and this permission
|
||||
* notice appear in supporting documentation, and that the name of
|
||||
* the copyright holders not be used in advertising or publicity
|
||||
* pertaining to distribution of the software without specific,
|
||||
* written prior permission. The copyright holders make no
|
||||
* representations about the suitability of this software for any
|
||||
* purpose. It is provided "as is" without express or implied
|
||||
* warranty.
|
||||
*
|
||||
* THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS
|
||||
* SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
|
||||
* FITNESS, IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY
|
||||
* SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
||||
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
|
||||
* AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
|
||||
* ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
|
||||
* THIS SOFTWARE.
|
||||
* </pre>
|
||||
*/
|
||||
struct android_wlegl;
|
||||
struct android_wlegl_handle;
|
||||
struct android_wlegl_server_buffer_handle;
|
||||
struct wl_buffer;
|
||||
|
||||
#ifndef ANDROID_WLEGL_INTERFACE
|
||||
#define ANDROID_WLEGL_INTERFACE
|
||||
/**
|
||||
* @page page_iface_android_wlegl android_wlegl
|
||||
* @section page_iface_android_wlegl_desc Description
|
||||
*
|
||||
* Interface used in the Android wrapper libEGL to share
|
||||
* graphics buffers between the server and the client.
|
||||
* @section page_iface_android_wlegl_api API
|
||||
* See @ref iface_android_wlegl.
|
||||
*/
|
||||
/**
|
||||
* @defgroup iface_android_wlegl The android_wlegl interface
|
||||
*
|
||||
* Interface used in the Android wrapper libEGL to share
|
||||
* graphics buffers between the server and the client.
|
||||
*/
|
||||
extern const struct wl_interface android_wlegl_interface;
|
||||
#endif
|
||||
#ifndef ANDROID_WLEGL_HANDLE_INTERFACE
|
||||
#define ANDROID_WLEGL_HANDLE_INTERFACE
|
||||
/**
|
||||
* @page page_iface_android_wlegl_handle android_wlegl_handle
|
||||
* @section page_iface_android_wlegl_handle_desc Description
|
||||
*
|
||||
* The Android native_handle_t is a semi-opaque object, that
|
||||
* contains an EGL implementation specific number of int32
|
||||
* values and file descriptors.
|
||||
*
|
||||
* We cannot send a variable size array of file descriptors
|
||||
* over the Wayland protocol, so we send them one by one.
|
||||
* @section page_iface_android_wlegl_handle_api API
|
||||
* See @ref iface_android_wlegl_handle.
|
||||
*/
|
||||
/**
|
||||
* @defgroup iface_android_wlegl_handle The android_wlegl_handle interface
|
||||
*
|
||||
* The Android native_handle_t is a semi-opaque object, that
|
||||
* contains an EGL implementation specific number of int32
|
||||
* values and file descriptors.
|
||||
*
|
||||
* We cannot send a variable size array of file descriptors
|
||||
* over the Wayland protocol, so we send them one by one.
|
||||
*/
|
||||
extern const struct wl_interface android_wlegl_handle_interface;
|
||||
#endif
|
||||
#ifndef ANDROID_WLEGL_SERVER_BUFFER_HANDLE_INTERFACE
|
||||
#define ANDROID_WLEGL_SERVER_BUFFER_HANDLE_INTERFACE
|
||||
/**
|
||||
* @page page_iface_android_wlegl_server_buffer_handle android_wlegl_server_buffer_handle
|
||||
* @section page_iface_android_wlegl_server_buffer_handle_desc Description
|
||||
*
|
||||
* On creation a server_side_buffer object will immediately send
|
||||
* the "buffer_fd" and "buffer_ints" events needed by the client to
|
||||
* reference the gralloc buffer, followed by the "buffer" event carrying
|
||||
* the wl_buffer object.
|
||||
* @section page_iface_android_wlegl_server_buffer_handle_api API
|
||||
* See @ref iface_android_wlegl_server_buffer_handle.
|
||||
*/
|
||||
/**
|
||||
* @defgroup iface_android_wlegl_server_buffer_handle The android_wlegl_server_buffer_handle interface
|
||||
*
|
||||
* On creation a server_side_buffer object will immediately send
|
||||
* the "buffer_fd" and "buffer_ints" events needed by the client to
|
||||
* reference the gralloc buffer, followed by the "buffer" event carrying
|
||||
* the wl_buffer object.
|
||||
*/
|
||||
extern const struct wl_interface android_wlegl_server_buffer_handle_interface;
|
||||
#endif
|
||||
|
||||
#ifndef ANDROID_WLEGL_ERROR_ENUM
|
||||
#define ANDROID_WLEGL_ERROR_ENUM
|
||||
enum android_wlegl_error {
|
||||
ANDROID_WLEGL_ERROR_BAD_HANDLE = 0,
|
||||
ANDROID_WLEGL_ERROR_BAD_VALUE = 1,
|
||||
};
|
||||
#endif /* ANDROID_WLEGL_ERROR_ENUM */
|
||||
|
||||
#ifndef ANDROID_WLEGL_ERROR_ENUM_IS_VALID
|
||||
#define ANDROID_WLEGL_ERROR_ENUM_IS_VALID
|
||||
/**
|
||||
* @ingroup iface_android_wlegl
|
||||
* Validate a android_wlegl error value.
|
||||
*
|
||||
* @return true on success, false on error.
|
||||
* @ref android_wlegl_error
|
||||
*/
|
||||
static inline bool
|
||||
android_wlegl_error_is_valid(uint32_t value, uint32_t version) {
|
||||
switch (value) {
|
||||
case ANDROID_WLEGL_ERROR_BAD_HANDLE:
|
||||
return version >= 1;
|
||||
case ANDROID_WLEGL_ERROR_BAD_VALUE:
|
||||
return version >= 1;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
#endif /* ANDROID_WLEGL_ERROR_ENUM_IS_VALID */
|
||||
|
||||
/**
|
||||
* @ingroup iface_android_wlegl
|
||||
* @struct android_wlegl_interface
|
||||
*/
|
||||
struct android_wlegl_interface {
|
||||
/**
|
||||
* Create an Android native_handle_t object
|
||||
*
|
||||
* This creator method initialises the native_handle_t object
|
||||
* with everything except the file descriptors, which have to be
|
||||
* submitted separately.
|
||||
* @param ints an array of int32_t
|
||||
*/
|
||||
void (*create_handle)(struct wl_client *client,
|
||||
struct wl_resource *resource,
|
||||
uint32_t id,
|
||||
int32_t num_fds,
|
||||
struct wl_array *ints);
|
||||
/**
|
||||
* Create a wl_buffer from the native handle
|
||||
*
|
||||
* Pass the Android native_handle_t to the server and attach it
|
||||
* to the new wl_buffer object.
|
||||
*
|
||||
* The android_wlegl_handle object must be destroyed immediately
|
||||
* after this request.
|
||||
*/
|
||||
void (*create_buffer)(struct wl_client *client,
|
||||
struct wl_resource *resource,
|
||||
uint32_t id,
|
||||
int32_t width,
|
||||
int32_t height,
|
||||
int32_t stride,
|
||||
int32_t format,
|
||||
int32_t usage,
|
||||
struct wl_resource *native_handle);
|
||||
/**
|
||||
* @since 2
|
||||
*/
|
||||
void (*get_server_buffer_handle)(struct wl_client *client,
|
||||
struct wl_resource *resource,
|
||||
uint32_t id,
|
||||
int32_t width,
|
||||
int32_t height,
|
||||
int32_t format,
|
||||
int32_t usage);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* @ingroup iface_android_wlegl
|
||||
*/
|
||||
#define ANDROID_WLEGL_CREATE_HANDLE_SINCE_VERSION 1
|
||||
/**
|
||||
* @ingroup iface_android_wlegl
|
||||
*/
|
||||
#define ANDROID_WLEGL_CREATE_BUFFER_SINCE_VERSION 1
|
||||
/**
|
||||
* @ingroup iface_android_wlegl
|
||||
*/
|
||||
#define ANDROID_WLEGL_GET_SERVER_BUFFER_HANDLE_SINCE_VERSION 2
|
||||
|
||||
#ifndef ANDROID_WLEGL_HANDLE_ERROR_ENUM
|
||||
#define ANDROID_WLEGL_HANDLE_ERROR_ENUM
|
||||
enum android_wlegl_handle_error {
|
||||
ANDROID_WLEGL_HANDLE_ERROR_TOO_MANY_FDS = 0,
|
||||
};
|
||||
#endif /* ANDROID_WLEGL_HANDLE_ERROR_ENUM */
|
||||
|
||||
#ifndef ANDROID_WLEGL_HANDLE_ERROR_ENUM_IS_VALID
|
||||
#define ANDROID_WLEGL_HANDLE_ERROR_ENUM_IS_VALID
|
||||
/**
|
||||
* @ingroup iface_android_wlegl_handle
|
||||
* Validate a android_wlegl_handle error value.
|
||||
*
|
||||
* @return true on success, false on error.
|
||||
* @ref android_wlegl_handle_error
|
||||
*/
|
||||
static inline bool
|
||||
android_wlegl_handle_error_is_valid(uint32_t value, uint32_t version) {
|
||||
switch (value) {
|
||||
case ANDROID_WLEGL_HANDLE_ERROR_TOO_MANY_FDS:
|
||||
return version >= 1;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
#endif /* ANDROID_WLEGL_HANDLE_ERROR_ENUM_IS_VALID */
|
||||
|
||||
/**
|
||||
* @ingroup iface_android_wlegl_handle
|
||||
* @struct android_wlegl_handle_interface
|
||||
*/
|
||||
struct android_wlegl_handle_interface {
|
||||
/**
|
||||
*/
|
||||
void (*add_fd)(struct wl_client *client,
|
||||
struct wl_resource *resource,
|
||||
int32_t fd);
|
||||
/**
|
||||
*/
|
||||
void (*destroy)(struct wl_client *client,
|
||||
struct wl_resource *resource);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* @ingroup iface_android_wlegl_handle
|
||||
*/
|
||||
#define ANDROID_WLEGL_HANDLE_ADD_FD_SINCE_VERSION 1
|
||||
/**
|
||||
* @ingroup iface_android_wlegl_handle
|
||||
*/
|
||||
#define ANDROID_WLEGL_HANDLE_DESTROY_SINCE_VERSION 1
|
||||
|
||||
#define ANDROID_WLEGL_SERVER_BUFFER_HANDLE_BUFFER_FD 0
|
||||
#define ANDROID_WLEGL_SERVER_BUFFER_HANDLE_BUFFER_INTS 1
|
||||
#define ANDROID_WLEGL_SERVER_BUFFER_HANDLE_BUFFER 2
|
||||
#define ANDROID_WLEGL_SERVER_BUFFER_HANDLE_LINEAR_LAYOUT 3
|
||||
|
||||
/**
|
||||
* @ingroup iface_android_wlegl_server_buffer_handle
|
||||
*/
|
||||
#define ANDROID_WLEGL_SERVER_BUFFER_HANDLE_BUFFER_FD_SINCE_VERSION 1
|
||||
/**
|
||||
* @ingroup iface_android_wlegl_server_buffer_handle
|
||||
*/
|
||||
#define ANDROID_WLEGL_SERVER_BUFFER_HANDLE_BUFFER_INTS_SINCE_VERSION 1
|
||||
/**
|
||||
* @ingroup iface_android_wlegl_server_buffer_handle
|
||||
*/
|
||||
#define ANDROID_WLEGL_SERVER_BUFFER_HANDLE_BUFFER_SINCE_VERSION 1
|
||||
/**
|
||||
* @ingroup iface_android_wlegl_server_buffer_handle
|
||||
*/
|
||||
#define ANDROID_WLEGL_SERVER_BUFFER_HANDLE_LINEAR_LAYOUT_SINCE_VERSION 3
|
||||
|
||||
|
||||
/**
|
||||
* @ingroup iface_android_wlegl_server_buffer_handle
|
||||
* Sends an buffer_fd event to the client owning the resource.
|
||||
* @param resource_ The client's resource
|
||||
*/
|
||||
static inline void
|
||||
android_wlegl_server_buffer_handle_send_buffer_fd(struct wl_resource *resource_, int32_t fd)
|
||||
{
|
||||
wl_resource_post_event(resource_, ANDROID_WLEGL_SERVER_BUFFER_HANDLE_BUFFER_FD, fd);
|
||||
}
|
||||
|
||||
/**
|
||||
* @ingroup iface_android_wlegl_server_buffer_handle
|
||||
* Sends an buffer_ints event to the client owning the resource.
|
||||
* @param resource_ The client's resource
|
||||
*/
|
||||
static inline void
|
||||
android_wlegl_server_buffer_handle_send_buffer_ints(struct wl_resource *resource_, struct wl_array *ints)
|
||||
{
|
||||
wl_resource_post_event(resource_, ANDROID_WLEGL_SERVER_BUFFER_HANDLE_BUFFER_INTS, ints);
|
||||
}
|
||||
|
||||
/**
|
||||
* @ingroup iface_android_wlegl_server_buffer_handle
|
||||
* Sends an buffer event to the client owning the resource.
|
||||
* @param resource_ The client's resource
|
||||
*/
|
||||
static inline void
|
||||
android_wlegl_server_buffer_handle_send_buffer(struct wl_resource *resource_, struct wl_resource *buffer, int32_t format, int32_t stride)
|
||||
{
|
||||
wl_resource_post_event(resource_, ANDROID_WLEGL_SERVER_BUFFER_HANDLE_BUFFER, buffer, format, stride);
|
||||
}
|
||||
|
||||
/**
|
||||
* @ingroup iface_android_wlegl_server_buffer_handle
|
||||
* Sends an linear_layout event to the client owning the resource.
|
||||
* @param resource_ The client's resource
|
||||
*/
|
||||
static inline void
|
||||
android_wlegl_server_buffer_handle_send_linear_layout(struct wl_resource *resource_, uint32_t drm_format, uint32_t stride)
|
||||
{
|
||||
wl_resource_post_event(resource_, ANDROID_WLEGL_SERVER_BUFFER_HANDLE_LINEAR_LAYOUT, drm_format, stride);
|
||||
}
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,139 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<protocol name="android">
|
||||
|
||||
<copyright>
|
||||
Copyright © 2012 Collabora, Ltd.
|
||||
|
||||
Permission to use, copy, modify, distribute, and sell this
|
||||
software and its documentation for any purpose is hereby granted
|
||||
without fee, provided that the above copyright notice appear in
|
||||
all copies and that both that copyright notice and this permission
|
||||
notice appear in supporting documentation, and that the name of
|
||||
the copyright holders not be used in advertising or publicity
|
||||
pertaining to distribution of the software without specific,
|
||||
written prior permission. The copyright holders make no
|
||||
representations about the suitability of this software for any
|
||||
purpose. It is provided "as is" without express or implied
|
||||
warranty.
|
||||
|
||||
THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS
|
||||
SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
|
||||
FITNESS, IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY
|
||||
SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
||||
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
|
||||
AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
|
||||
ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
|
||||
THIS SOFTWARE.
|
||||
</copyright>
|
||||
|
||||
<interface name="android_wlegl" version="3">
|
||||
<description summary="Android EGL graphics buffer support">
|
||||
Interface used in the Android wrapper libEGL to share
|
||||
graphics buffers between the server and the client.
|
||||
</description>
|
||||
|
||||
<enum name="error">
|
||||
<entry name="bad_handle" value="0" />
|
||||
<entry name="bad_value" value="1" />
|
||||
</enum>
|
||||
|
||||
<request name="create_handle">
|
||||
<description summary="Create an Android native_handle_t object">
|
||||
This creator method initialises the native_handle_t object
|
||||
with everything except the file descriptors, which have to be
|
||||
submitted separately.
|
||||
</description>
|
||||
|
||||
<arg name="id" type="new_id" interface="android_wlegl_handle" />
|
||||
<arg name="num_fds" type="int" />
|
||||
<arg name="ints" type="array" summary="an array of int32_t" />
|
||||
</request>
|
||||
|
||||
<request name="create_buffer">
|
||||
<description summary="Create a wl_buffer from the native handle">
|
||||
Pass the Android native_handle_t to the server and attach it
|
||||
to the new wl_buffer object.
|
||||
|
||||
The android_wlegl_handle object must be destroyed immediately
|
||||
after this request.
|
||||
</description>
|
||||
|
||||
<arg name="id" type="new_id" interface="wl_buffer" />
|
||||
<arg name="width" type="int" />
|
||||
<arg name="height" type="int" />
|
||||
<arg name="stride" type="int" />
|
||||
<arg name="format" type="int" />
|
||||
<arg name="usage" type="int" />
|
||||
<arg name="native_handle" type="object" interface="android_wlegl_handle" />
|
||||
</request>
|
||||
|
||||
|
||||
<request name="get_server_buffer_handle" since="2">
|
||||
<arg name="id" type="new_id" interface="android_wlegl_server_buffer_handle"/>
|
||||
<arg name="width" type="int"/>
|
||||
<arg name="height" type="int"/>
|
||||
<arg name="format" type="int"/>
|
||||
<arg name="usage" type="int"/>
|
||||
</request>
|
||||
|
||||
</interface>
|
||||
|
||||
<interface name="android_wlegl_handle" version="1">
|
||||
<description summary="An Android native_handle_t object">
|
||||
The Android native_handle_t is a semi-opaque object, that
|
||||
contains an EGL implementation specific number of int32
|
||||
values and file descriptors.
|
||||
|
||||
We cannot send a variable size array of file descriptors
|
||||
over the Wayland protocol, so we send them one by one.
|
||||
</description>
|
||||
|
||||
<enum name="error">
|
||||
<entry name="too_many_fds" value="0" />
|
||||
</enum>
|
||||
|
||||
<request name="add_fd">
|
||||
<arg name="fd" type="fd" />
|
||||
</request>
|
||||
|
||||
<request name="destroy" type="destructor" />
|
||||
|
||||
</interface>
|
||||
|
||||
|
||||
<interface name="android_wlegl_server_buffer_handle" version="3">
|
||||
<description summary="a server allocated buffer">
|
||||
On creation a server_side_buffer object will immediately send
|
||||
the "buffer_fd" and "buffer_ints" events needed by the client to
|
||||
reference the gralloc buffer, followed by the "buffer" event carrying
|
||||
the wl_buffer object.
|
||||
</description>
|
||||
<event name="buffer_fd">
|
||||
<arg name="fd" type="fd"/>
|
||||
</event>
|
||||
<event name="buffer_ints">
|
||||
<arg name="ints" type="array"/>
|
||||
</event>
|
||||
<event name="buffer">
|
||||
<description summary="the wl_buffer">
|
||||
This event will be sent after the ints and all the fds have been sent
|
||||
</description>
|
||||
<arg name="buffer" type="new_id" interface="wl_buffer"/>
|
||||
<arg name="format" type="int"/>
|
||||
<arg name="stride" type="int"/>
|
||||
</event>
|
||||
<event name="linear_layout" since="3">
|
||||
<description summary="verified single-plane linear allocation">
|
||||
Optional metadata sent before the buffer event. The first buffer_fd
|
||||
contains one uncompressed 32-bit RGB plane at byte offset zero.
|
||||
drm_format is its DRM FourCC and stride is its row pitch in bytes.
|
||||
The server has verified the layout and allocation bounds using
|
||||
Android mapper metadata, not inferred them from opaque handle ints.
|
||||
Absence of this event means the layout is unspecified.
|
||||
</description>
|
||||
<arg name="drm_format" type="uint"/>
|
||||
<arg name="stride" type="uint"/>
|
||||
</event>
|
||||
</interface>
|
||||
|
||||
</protocol>
|
||||
@@ -86,6 +86,9 @@ static struct ahb_buf *find_buf(uint64_t id) {
|
||||
}
|
||||
|
||||
static void buf_free(struct ahb_buf *ab) {
|
||||
/* A display release does not prove the compositor's Vulkan reads finished.
|
||||
* Keep the AHB reference and its DMA-BUF record even if the client is gone. */
|
||||
if (vkp_completion_unknown()) return;
|
||||
if (ab->resource) { wl_list_remove(&ab->resource_destroy.link); ab->resource = NULL; }
|
||||
if (ab->fence_src) { wl_event_source_remove(ab->fence_src); ab->fence_src = NULL; }
|
||||
if (ab->fence_fd >= 0) { close(ab->fence_fd); ab->fence_fd = -1; }
|
||||
@@ -112,6 +115,7 @@ static void on_buffer_resource_destroyed(struct wl_listener *l, void *data) {
|
||||
/* ---- release: SurfaceFlinger is done with the buffer -> the game's next acquire waits, then wl_buffer.release */
|
||||
|
||||
static void send_deferred_release(struct ahb_buf *ab) {
|
||||
if (vkp_completion_unknown()) return;
|
||||
if (ab->release_pending && ab->resource)
|
||||
droiddeck_release_buffer(ab->surface, ab->resource, ab->surface != NULL, ab->deferred_ns);
|
||||
ab->release_pending = 0;
|
||||
|
||||
@@ -377,6 +377,62 @@ static void perf_note_release(int64_t since_ns) {
|
||||
|
||||
/* ------------------------------------------------------------------ buffer release pacing */
|
||||
|
||||
/* Completion-unknown is terminal for externally owned DMA-BUF contents too.
|
||||
* Keeping a VkImage alone cannot stop the client from overwriting its backing
|
||||
* memory after wl_buffer.release. All paths (including cursors and idle roles)
|
||||
* use this gate; copied SHM buffers retain their normal release behaviour. */
|
||||
static struct dmabuf_buffer *get_dmabuf(struct wl_resource *buffer);
|
||||
static int buffer_release_blocked(struct wl_resource *buffer) {
|
||||
return vkp_completion_unknown() && get_dmabuf(buffer) != NULL;
|
||||
}
|
||||
/* Buffer tracing on a GPU that is not an Adreno (no KGSL node): every attach and release of the
|
||||
* first 400 buffer events, by wl_buffer id and the line that sent it, and any release of a buffer
|
||||
* already released and not attached again since (gamescope: "Compositor released us but we were
|
||||
* not acquired"). Off on an Adreno. */
|
||||
static int g_buf_trace = -1;
|
||||
static int g_buf_trace_left = 400;
|
||||
static uint32_t g_released_ids[128];
|
||||
static int buf_trace_on(void) {
|
||||
if (g_buf_trace < 0) g_buf_trace = access("/dev/kgsl-3d0", F_OK) != 0;
|
||||
return g_buf_trace;
|
||||
}
|
||||
static void buf_trace_attach(struct wl_resource *buffer) {
|
||||
if (!buffer || !buf_trace_on()) return;
|
||||
uint32_t id = wl_resource_get_id(buffer);
|
||||
for (int i = 0; i < 128; i++) if (g_released_ids[i] == id) g_released_ids[i] = 0;
|
||||
if (g_buf_trace_left > 0) { g_buf_trace_left--; droiddeck_log("buffer", "attach id %u", id); }
|
||||
}
|
||||
static void buf_trace_release(struct wl_resource *buffer, int line) {
|
||||
if (!buffer || !buf_trace_on()) return;
|
||||
uint32_t id = wl_resource_get_id(buffer);
|
||||
int twice = 0, slot = -1;
|
||||
for (int i = 0; i < 128; i++) {
|
||||
if (g_released_ids[i] == id) twice = 1;
|
||||
if (slot < 0 && g_released_ids[i] == 0) slot = i;
|
||||
}
|
||||
if (twice) droiddeck_log("buffer", "DOUBLE release id %u (line %d): released again without an attach", id, line);
|
||||
else if (slot >= 0) g_released_ids[slot] = id;
|
||||
if (g_buf_trace_left > 0) { g_buf_trace_left--; droiddeck_log("buffer", "release id %u (line %d)", id, line); }
|
||||
}
|
||||
|
||||
#define send_buffer_release(b) send_buffer_release_at((b), __LINE__)
|
||||
static void send_buffer_release_at(struct wl_resource *buffer, int line) {
|
||||
if (!buffer_release_blocked(buffer)) { buf_trace_release(buffer, line); wl_buffer_send_release(buffer); }
|
||||
}
|
||||
|
||||
/* Whether a surface other than `except` is showing this buffer right now. gamescope's Wayland
|
||||
* backend moves one buffer between its planes (the game's frame goes from the window to a
|
||||
* subsurface above a black backing while a Steam notification is up): releasing it when the first
|
||||
* surface lets go handed gamescope a buffer still on screen ("Compositor released us but we were
|
||||
* not acquired"). Only the last surface to let go releases it. */
|
||||
static int buffer_shown_elsewhere(struct wl_resource *buffer, const struct surface *except) {
|
||||
struct surface *o;
|
||||
if (!buffer) return 0;
|
||||
wl_list_for_each(o, &g_surfaces, link)
|
||||
if (o != except && o->dmabuf == buffer) return 1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void pending_release_free(struct pending_release *pr) {
|
||||
if (pr->surface && pr->surface->releases_pending > 0) pr->surface->releases_pending--;
|
||||
wl_list_remove(&pr->destroy.link);
|
||||
@@ -384,7 +440,8 @@ static void pending_release_free(struct pending_release *pr) {
|
||||
free(pr);
|
||||
}
|
||||
|
||||
/* A surface is going away: its queued releases still go out on time, they just stop counting. */
|
||||
/* A surface is going away: detach its accounting pointer, including queued
|
||||
* DMA-BUF releases held in the completion-unknown state. */
|
||||
static void pending_releases_forget_surface(struct surface *s) {
|
||||
struct pending_release *pr;
|
||||
wl_list_for_each(pr, &g_pending_releases, link)
|
||||
@@ -401,7 +458,8 @@ static void arm_release_timer(void) {
|
||||
int64_t earliest = 0;
|
||||
if (g_release_timer_fd < 0) return;
|
||||
wl_list_for_each(pr, &g_pending_releases, link)
|
||||
if (!earliest || pr->at_ns < earliest) earliest = pr->at_ns;
|
||||
if (!buffer_release_blocked(pr->buffer) && (!earliest || pr->at_ns < earliest))
|
||||
earliest = pr->at_ns;
|
||||
struct itimerspec its = {0};
|
||||
if (earliest) { its.it_value.tv_sec = earliest / 1000000000LL; its.it_value.tv_nsec = earliest % 1000000000LL; }
|
||||
timerfd_settime(g_release_timer_fd, TFD_TIMER_ABSTIME, &its, NULL);
|
||||
@@ -413,8 +471,13 @@ static int on_release_timer(int fd, uint32_t mask, void *data) {
|
||||
int64_t now = now_ns() + 300000; /* anything due within 0.3 ms goes now */
|
||||
if (read(fd, &expirations, sizeof(expirations)) < 0 && errno != EAGAIN) return 0;
|
||||
wl_list_for_each_safe(pr, tmp, &g_pending_releases, link) {
|
||||
if (pr->at_ns <= now) {
|
||||
wl_buffer_send_release(pr->buffer);
|
||||
if (pr->at_ns <= now && !buffer_release_blocked(pr->buffer)) {
|
||||
/* Attached again since (to its surface or another): that surface releases it later. */
|
||||
if (buffer_shown_elsewhere(pr->buffer, NULL)) {
|
||||
pending_release_free(pr);
|
||||
continue;
|
||||
}
|
||||
send_buffer_release(pr->buffer);
|
||||
perf_note_release(pr->since_ns);
|
||||
pending_release_free(pr);
|
||||
}
|
||||
@@ -435,6 +498,9 @@ static int on_release_timer(int fd, uint32_t mask, void *data) {
|
||||
* delivered (a swapchain rebuild destroys buffers with queued releases) or that a coarser earlier
|
||||
* limit had spaced out, and the game's first frames after that waited on empty slots. */
|
||||
static void release_buffer(struct surface *s, struct wl_resource *buffer, int64_t since_ns) {
|
||||
/* No allocation or immediate-release fallback is allowed for a quarantined
|
||||
* DMA-BUF. Existing queued releases stay held; their timer is disarmed. */
|
||||
if (buffer_release_blocked(buffer)) return;
|
||||
const int limit = g_fps_limit;
|
||||
/* Without a limit of its own a game is paced to the screen. A swapchain that does not wait for
|
||||
* frame callbacks (MAILBOX, IMMEDIATE) is held back by nothing else here, so handing a replaced
|
||||
@@ -443,7 +509,7 @@ static void release_buffer(struct surface *s, struct wl_resource *buffer, int64_
|
||||
* One release per refresh is the back-pressure X11 gives, and the screen shows the same frames
|
||||
* either way. */
|
||||
const int64_t interval = limit > 0 ? 1000000000LL / limit : g_refresh_ns;
|
||||
if (interval <= 0 || g_release_timer_fd < 0) { wl_buffer_send_release(buffer); perf_note_release(since_ns); return; }
|
||||
if (interval <= 0 || g_release_timer_fd < 0) { send_buffer_release(buffer); perf_note_release(since_ns); return; }
|
||||
int64_t now = now_ns();
|
||||
int64_t at = s->next_release_ns + interval;
|
||||
int64_t latest = now + interval * (int64_t)(s->releases_pending + 1);
|
||||
@@ -451,7 +517,7 @@ static void release_buffer(struct surface *s, struct wl_resource *buffer, int64_
|
||||
if (at > latest) at = latest;
|
||||
s->next_release_ns = at;
|
||||
struct pending_release *pr = calloc(1, sizeof(*pr));
|
||||
if (!pr) { wl_buffer_send_release(buffer); perf_note_release(since_ns); return; }
|
||||
if (!pr) { send_buffer_release(buffer); perf_note_release(since_ns); return; }
|
||||
pr->buffer = buffer;
|
||||
pr->surface = s;
|
||||
pr->at_ns = at;
|
||||
@@ -586,7 +652,10 @@ static void constraints_focus_entered(struct wl_resource *target, struct wl_clie
|
||||
/* ------------------------------------------------------------------ dmabuf buffers */
|
||||
|
||||
void dmabuf_buffer_unref(struct dmabuf_buffer *b) {
|
||||
if (!b || --b->refs > 0) return;
|
||||
/* Surface/client destruction must not close the backing FDs or free the
|
||||
* imported-buffer record while a GPU read may still be pending. Retain the
|
||||
* reference without allocating a quarantine node; process exit reclaims it. */
|
||||
if (!b || vkp_completion_unknown() || --b->refs > 0) return;
|
||||
vkp_image_destroy(b->img);
|
||||
for (int i = 0; i < b->n_planes; i++)
|
||||
if (b->fd[i] >= 0) close(b->fd[i]);
|
||||
@@ -677,15 +746,18 @@ static void unmap_toplevel(struct surface *s) {
|
||||
|
||||
/* Let go of the surface's dmabuf content. paced = 1: the buffer was replaced, give it back on the
|
||||
* limiter's cadence; paced = 0: the surface is going away, give it back at once (a buffer of a
|
||||
* destroyed surface is not shown again and must not sit unreleased with the client). */
|
||||
* destroyed surface is not shown again). Completion-unknown overrides both
|
||||
* release modes: prior GPU reads may outlive the surface. */
|
||||
static void drop_dmabuf(struct surface *s, int paced) {
|
||||
if (s->dmabuf) {
|
||||
wl_list_remove(&s->dmabuf_destroy.link);
|
||||
/* A buffer on the zero-copy layer is the display's until SurfaceFlinger says otherwise:
|
||||
* ahb_swapchain.c releases it then. */
|
||||
if (!ahb_swapchain_defer_release(s->dmabuf_buf, s->dmabuf, s, paced)) {
|
||||
if (buffer_shown_elsewhere(s->dmabuf, s)) {
|
||||
/* still on another surface: released when that one lets go */
|
||||
} else if (!ahb_swapchain_defer_release(s->dmabuf_buf, s->dmabuf, s, paced)) {
|
||||
if (paced) release_buffer(s, s->dmabuf, now_ns());
|
||||
else wl_buffer_send_release(s->dmabuf);
|
||||
else send_buffer_release(s->dmabuf);
|
||||
}
|
||||
s->dmabuf = NULL;
|
||||
}
|
||||
@@ -735,7 +807,7 @@ static void take_shm(struct surface *s, struct wl_shm_buffer *shm, struct wl_res
|
||||
vkp_image_upload_shm(s->shm_img, wl_shm_buffer_get_data(shm), stride);
|
||||
wl_shm_buffer_end_access(shm);
|
||||
}
|
||||
wl_buffer_send_release(buffer);
|
||||
send_buffer_release(buffer);
|
||||
s->buf_w = w;
|
||||
s->buf_h = h;
|
||||
s->buf_alpha = wl_shm_buffer_get_format(shm) == WL_SHM_FORMAT_ARGB8888;
|
||||
@@ -753,7 +825,7 @@ static void take_pixel(struct surface *s, const uint8_t bgra[4], struct wl_resou
|
||||
}
|
||||
if (!s->shm_img) s->shm_img = vkp_image_create_shm(1, 1);
|
||||
if (s->shm_img) vkp_image_upload_shm(s->shm_img, bgra, 4);
|
||||
wl_buffer_send_release(buffer);
|
||||
send_buffer_release(buffer);
|
||||
s->buf_w = 1;
|
||||
s->buf_h = 1;
|
||||
s->buf_alpha = bgra[3] != 0xff;
|
||||
@@ -880,8 +952,9 @@ void **droiddeck_dmabuf_ahb_slot(struct dmabuf_buffer *b) { return &b->ahb_state
|
||||
void droiddeck_dmabuf_ref(struct dmabuf_buffer *b) { b->refs++; }
|
||||
void droiddeck_dmabuf_unref(struct dmabuf_buffer *b) { dmabuf_buffer_unref(b); }
|
||||
void droiddeck_release_buffer(struct surface *s, struct wl_resource *buffer, int paced, int64_t since_ns) {
|
||||
if (buffer_release_blocked(buffer)) return;
|
||||
if (paced && s) release_buffer(s, buffer, since_ns);
|
||||
else { wl_buffer_send_release(buffer); perf_note_release(since_ns); }
|
||||
else { send_buffer_release(buffer); perf_note_release(since_ns); }
|
||||
}
|
||||
void droiddeck_surface_describe(const struct surface *s, char *out, size_t size) { describe(s, out, size); }
|
||||
const struct droiddeck_color *droiddeck_surface_color(const struct surface *s) {
|
||||
@@ -1046,7 +1119,7 @@ static void surface_hold_idle(struct surface *s, struct wl_resource *buffer) {
|
||||
struct wl_shm_buffer *shm = db ? NULL : wl_shm_buffer_get(buffer);
|
||||
int64_t px = db ? (int64_t)db->width * db->height
|
||||
: shm ? (int64_t)wl_shm_buffer_get_width(shm) * wl_shm_buffer_get_height(shm) : 0;
|
||||
if (px <= 0 || px > CURSOR_MAX_PX) { wl_buffer_send_release(buffer); return; }
|
||||
if (px <= 0 || px > CURSOR_MAX_PX) { send_buffer_release(buffer); return; }
|
||||
s->idle_buffer = buffer;
|
||||
s->idle_buffer_destroy.notify = on_idle_buffer_destroyed;
|
||||
wl_resource_add_destroy_listener(buffer, &s->idle_buffer_destroy);
|
||||
@@ -1064,7 +1137,7 @@ static struct wl_resource *surface_take_idle(struct surface *s) {
|
||||
|
||||
static void surface_drop_idle(struct surface *s) {
|
||||
struct wl_resource *buffer = surface_take_idle(s);
|
||||
if (buffer) wl_buffer_send_release(buffer);
|
||||
if (buffer) send_buffer_release(buffer);
|
||||
}
|
||||
|
||||
static void surface_commit(struct wl_client *c, struct wl_resource *r) {
|
||||
@@ -1119,12 +1192,13 @@ static void surface_commit(struct wl_client *c, struct wl_resource *r) {
|
||||
cursor_publish_hidden(); /* wlroots clears its cursor surface to hide the pointer */
|
||||
} else {
|
||||
cursor_publish_buffer(s, buffer);
|
||||
wl_buffer_send_release(buffer);
|
||||
send_buffer_release(buffer);
|
||||
}
|
||||
} else if (s->role == ROLE_NONE) {
|
||||
/* Role-less surface: never drawn, but its buffer is kept for a set_cursor to come. */
|
||||
if (buffer) surface_hold_idle(s, buffer);
|
||||
} else if (db) {
|
||||
buf_trace_attach(buffer);
|
||||
take_dmabuf(s, db, buffer);
|
||||
} else if (shm) {
|
||||
drop_dmabuf(s, 1);
|
||||
@@ -1135,7 +1209,7 @@ static void surface_commit(struct wl_client *c, struct wl_resource *r) {
|
||||
} else {
|
||||
drop_dmabuf(s, 1);
|
||||
s->has_content = 0;
|
||||
if (buffer) wl_buffer_send_release(buffer);
|
||||
if (buffer) send_buffer_release(buffer);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2322,7 +2396,7 @@ static void pointer_set_cursor(struct wl_client *c, struct wl_resource *r, uint3
|
||||
struct wl_resource *buffer = surface_take_idle(s);
|
||||
if (buffer) {
|
||||
cursor_publish_buffer(s, buffer);
|
||||
wl_buffer_send_release(buffer);
|
||||
send_buffer_release(buffer);
|
||||
} else if (g_cursor_shown == s) {
|
||||
cursor_publish_shown();
|
||||
}
|
||||
@@ -3534,6 +3608,7 @@ int droiddeck_wayland_run(void) {
|
||||
wl_global_create(display, &wl_output_interface, 4, NULL, bind_output);
|
||||
wl_global_create(display, &xdg_wm_base_interface, 1, NULL, bind_xdg_wm_base);
|
||||
wl_global_create(display, &zwp_linux_dmabuf_v1_interface, 4, NULL, bind_dmabuf);
|
||||
droiddeck_android_wlegl_init(display);
|
||||
/* gamescope's Wayland backend refuses a seat older than 8. */
|
||||
wl_global_create(display, &wl_seat_interface, 9, NULL, bind_seat);
|
||||
wl_global_create(display, &banner_desktop_v1_interface, 1, NULL, bind_desktop);
|
||||
|
||||
@@ -77,3 +77,6 @@ extern volatile int g_no_render_node; /* DROIDDECK_WAYLAND_NO_RENDER_NODE */
|
||||
/* ---- wl_dmabuf.c */
|
||||
COMPOSITOR_INTERNAL extern dev_t g_main_device; /* the render node clients are told to allocate on */
|
||||
COMPOSITOR_INTERNAL void bind_dmabuf(struct wl_client *c, void *data, uint32_t ver, uint32_t id);
|
||||
|
||||
/* ---- wl_android_buffer.c */
|
||||
COMPOSITOR_INTERNAL void droiddeck_android_wlegl_init(struct wl_display *display);
|
||||
@@ -0,0 +1,47 @@
|
||||
#ifndef VK_EXTERNAL_IMAGE_SYNC_H
|
||||
#define VK_EXTERNAL_IMAGE_SYNC_H
|
||||
|
||||
#include <vulkan/vulkan.h>
|
||||
|
||||
struct vkp_external_client_barrier_pair {
|
||||
VkImageMemoryBarrier acquire;
|
||||
VkImageMemoryBarrier release;
|
||||
};
|
||||
|
||||
static inline int vkp_is_external_client_image(int dmabuf, int blit_dst) {
|
||||
return dmabuf && !blit_dst;
|
||||
}
|
||||
|
||||
/* Client-owned dma-bufs, including AHardwareBuffers, live in GENERAL while
|
||||
* FOREIGN owns them. Layer pool dma-bufs are destinations with a separate
|
||||
* acquire/release lifecycle and must never take this source-image path. */
|
||||
static inline int vkp_external_client_barrier_pair(
|
||||
VkImage image, uint32_t queue_family, int dmabuf, int blit_dst,
|
||||
struct vkp_external_client_barrier_pair *pair) {
|
||||
if (!vkp_is_external_client_image(dmabuf, blit_dst) || !pair) return 0;
|
||||
|
||||
const VkImageSubresourceRange range = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
|
||||
pair->acquire = (VkImageMemoryBarrier){
|
||||
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER,
|
||||
.oldLayout = VK_IMAGE_LAYOUT_GENERAL,
|
||||
.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
|
||||
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_FOREIGN_EXT,
|
||||
.dstQueueFamilyIndex = queue_family,
|
||||
.image = image,
|
||||
.subresourceRange = range,
|
||||
.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT,
|
||||
};
|
||||
pair->release = (VkImageMemoryBarrier){
|
||||
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER,
|
||||
.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
|
||||
.newLayout = VK_IMAGE_LAYOUT_GENERAL,
|
||||
.srcQueueFamilyIndex = queue_family,
|
||||
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_FOREIGN_EXT,
|
||||
.image = image,
|
||||
.subresourceRange = range,
|
||||
.srcAccessMask = VK_ACCESS_MEMORY_READ_BIT,
|
||||
};
|
||||
return 1;
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -3,6 +3,7 @@
|
||||
#define _POSIX_C_SOURCE 200809L
|
||||
#include "vk_present.h"
|
||||
#include "vk_loader.h"
|
||||
#include "vk_external_image_sync.h"
|
||||
#include "sc_layer.h"
|
||||
#include "effects_chain.h"
|
||||
#include "framegen_bridge.h"
|
||||
@@ -35,15 +36,18 @@ struct vkp_image {
|
||||
int in_general; /* shm images: moved from PREINITIALIZED to GENERAL */
|
||||
VkFormat fmt;
|
||||
int sampled; /* created with SAMPLED usage: the alpha pass can read it */
|
||||
AHardwareBuffer *android_buffer;
|
||||
};
|
||||
|
||||
static ANativeWindow *g_window; /* the window frames go to; compositor thread only */
|
||||
static char *g_driver_path, *g_library_name, *g_native_lib_dir;
|
||||
static int g_dev_state; /* 0 = not yet, 1 = ok, -1 = failed, -2 = lost (VK_ERROR_DEVICE_LOST) */
|
||||
static int g_dev_state; /* 0 = not yet, 1 = ok, -1 = failed, -2 = lost, -3 = completion unknown */
|
||||
static void device_lost(const char *where);
|
||||
static VkInstance g_inst;
|
||||
static VkPhysicalDevice g_pd;
|
||||
static VkDevice g_dev;
|
||||
static VkQueue g_queue;
|
||||
static PFN_vkGetAndroidHardwareBufferPropertiesANDROID g_ahb_properties;
|
||||
static uint32_t g_qfam;
|
||||
static VkCommandPool g_pool;
|
||||
/* One command buffer + acquire/render-done semaphore pair per PRESENT. A scene frame is one
|
||||
@@ -112,11 +116,26 @@ static void perf_add(int64_t *sum, int64_t *max, unsigned *count, int64_t d) {
|
||||
if (d > *max) *max = d;
|
||||
(*count)++;
|
||||
}
|
||||
/* A timeout is not device loss and does not cancel a submit. Keep its images
|
||||
* and memory alive until this compositor process exits. Resuming
|
||||
* would reset a pending command buffer/fence or free memory still read by the GPU. */
|
||||
static void quarantine_pending_work(VkResult result, const char *where) {
|
||||
if (g_dev_state != 1) return;
|
||||
g_dev_state = -3;
|
||||
g_base_black = 0;
|
||||
LOGE("GPU completion unconfirmed (%d in %s): presenting stopped; pending resources retained; "
|
||||
"restart DroidDeck", (int)result, where);
|
||||
}
|
||||
|
||||
/* vkWaitForFences on the compositor's own work, timed for the perf line. */
|
||||
static VkResult timed_wait(VkFence fence, uint64_t timeout) {
|
||||
if (g_dev_state != 1)
|
||||
return g_dev_state == -2 ? VK_ERROR_DEVICE_LOST : VK_ERROR_UNKNOWN;
|
||||
int64_t t0 = perf_now();
|
||||
VkResult r = g_vk.WaitForFences(g_dev, 1, &fence, VK_TRUE, timeout);
|
||||
perf_add(&g_perf.wait_ns, &g_perf.wait_max_ns, &g_perf.waits, perf_now() - t0);
|
||||
if (r != VK_SUCCESS && r != VK_ERROR_DEVICE_LOST)
|
||||
quarantine_pending_work(r, "fence wait");
|
||||
return r;
|
||||
}
|
||||
|
||||
@@ -236,7 +255,12 @@ static void reset_sync(void) {
|
||||
static void destroy_swapchain(void) {
|
||||
g_base_black = 0; /* a new swapchain starts with nothing on it */
|
||||
if (g_dev_state != 1) return;
|
||||
g_vk.DeviceWaitIdle(g_dev);
|
||||
VkResult idle = g_vk.DeviceWaitIdle(g_dev);
|
||||
if (idle != VK_SUCCESS) {
|
||||
if (idle == VK_ERROR_DEVICE_LOST) device_lost("swapchain idle");
|
||||
else quarantine_pending_work(idle, "swapchain idle");
|
||||
return;
|
||||
}
|
||||
reset_sync();
|
||||
for (uint32_t i = 0; i < g_nimg; i++) blendp_forget_image(g_images[i]);
|
||||
if (g_swapchain) g_vk.DestroySwapchainKHR(g_dev, g_swapchain, NULL);
|
||||
@@ -302,6 +326,7 @@ int vkp_has_window(void) {
|
||||
}
|
||||
|
||||
int vkp_device_lost(void) { return g_dev_state == -2; }
|
||||
int vkp_completion_unknown(void) { return g_dev_state == -3; }
|
||||
|
||||
void vk_present_set_scale_mode(int mode, int alignment) {
|
||||
if (mode < VKP_MODE_OFF || mode > VKP_MODE_INTEGER) mode = VKP_MODE_FIT;
|
||||
@@ -463,18 +488,41 @@ static int dev_init(void) {
|
||||
}
|
||||
g_vk.GetPhysicalDeviceMemoryProperties(g_pd, &g_memprops);
|
||||
|
||||
/* Verify the dmabuf-import extensions are present, and log any that are missing. */
|
||||
const char *dev_exts[7] = {VK_KHR_SWAPCHAIN_EXTENSION_NAME, "VK_KHR_external_memory_fd",
|
||||
"VK_EXT_external_memory_dma_buf", "VK_EXT_image_drm_format_modifier",
|
||||
"VK_KHR_image_format_list", NULL, NULL};
|
||||
uint32_t n_dev_exts = 5;
|
||||
/* The dmabuf-import extensions are enabled only when present (David Cimo, Mali through Venus):
|
||||
* a vendor driver may lack one, and naming it would fail vkCreateDevice and leave the session
|
||||
* with no compositor. On an Adreno's Turnip all five are present, so nothing changes there. */
|
||||
static const char *const wanted_exts[5] = {VK_KHR_SWAPCHAIN_EXTENSION_NAME, "VK_KHR_external_memory_fd",
|
||||
"VK_EXT_external_memory_dma_buf", "VK_EXT_image_drm_format_modifier",
|
||||
"VK_KHR_image_format_list"};
|
||||
const char *dev_exts[9] = {0};
|
||||
uint32_t n_dev_exts = 0;
|
||||
uint32_t ne = 0;
|
||||
g_vk.EnumerateDeviceExtensionProperties(g_pd, NULL, &ne, NULL);
|
||||
VkExtensionProperties *exts = calloc(ne ? ne : 1, sizeof(*exts));
|
||||
g_vk.EnumerateDeviceExtensionProperties(g_pd, NULL, &ne, exts);
|
||||
for (unsigned i = 0; i < 5; i++)
|
||||
if (!has_ext(exts, ne, dev_exts[i]))
|
||||
LOGE("present: driver MISSING %s (dmabuf import will fail)", dev_exts[i]);
|
||||
/* The whole list, once, on a driver that is not Turnip: on a vendor driver it is what Venus
|
||||
* and the bridges can offer the session. Several lines, since a log line holds 512 bytes. */
|
||||
if (!g_library_name || !strstr(g_library_name, "freedreno")) {
|
||||
char names[440];
|
||||
size_t len = 0;
|
||||
names[0] = 0;
|
||||
droiddeck_log("gpu", "device extensions: %u", ne);
|
||||
for (uint32_t i = 0; i < ne; i++) {
|
||||
if (len + strlen(exts[i].extensionName) + 2 > sizeof(names)) {
|
||||
droiddeck_log("gpu", " %s", names);
|
||||
len = 0;
|
||||
names[0] = 0;
|
||||
}
|
||||
len += (size_t)snprintf(names + len, sizeof(names) - len, "%s%s", len ? " " : "", exts[i].extensionName);
|
||||
}
|
||||
if (len) droiddeck_log("gpu", " %s", names);
|
||||
}
|
||||
for (unsigned i = 0; i < 5; i++) {
|
||||
if (has_ext(exts, ne, wanted_exts[i]))
|
||||
dev_exts[n_dev_exts++] = wanted_exts[i];
|
||||
else
|
||||
LOGE("present: driver MISSING %s (dmabuf import will fail)", wanted_exts[i]);
|
||||
}
|
||||
/* HDR sessions only: the HDR10 swapchain (frame generation) can carry the game's metadata. */
|
||||
int want_hdr_md = 0;
|
||||
if (droiddeck_color_requested()) {
|
||||
@@ -485,6 +533,13 @@ static int dev_init(void) {
|
||||
* back to waiting for them on the CPU without it. */
|
||||
const int want_sem_fd = has_ext(exts, ne, VK_KHR_EXTERNAL_SEMAPHORE_FD_EXTENSION_NAME);
|
||||
if (want_sem_fd) dev_exts[n_dev_exts++] = VK_KHR_EXTERNAL_SEMAPHORE_FD_EXTENSION_NAME;
|
||||
const int want_ahb = !g_library_name &&
|
||||
has_ext(exts, ne, VK_ANDROID_EXTERNAL_MEMORY_ANDROID_HARDWARE_BUFFER_EXTENSION_NAME) &&
|
||||
has_ext(exts, ne, VK_EXT_QUEUE_FAMILY_FOREIGN_EXTENSION_NAME);
|
||||
if (want_ahb) {
|
||||
dev_exts[n_dev_exts++] = VK_ANDROID_EXTERNAL_MEMORY_ANDROID_HARDWARE_BUFFER_EXTENSION_NAME;
|
||||
dev_exts[n_dev_exts++] = VK_EXT_QUEUE_FAMILY_FOREIGN_EXTENSION_NAME;
|
||||
}
|
||||
free(exts);
|
||||
|
||||
float prio = 1.0f;
|
||||
@@ -511,6 +566,9 @@ static int dev_init(void) {
|
||||
}
|
||||
vk_loader_load_device(g_dev);
|
||||
g_vk.GetDeviceQueue(g_dev, g_qfam, 0, &g_queue);
|
||||
if (want_ahb)
|
||||
g_ahb_properties = (PFN_vkGetAndroidHardwareBufferPropertiesANDROID)
|
||||
g_vk.GetDeviceProcAddr(g_dev, "vkGetAndroidHardwareBufferPropertiesANDROID");
|
||||
if (want_sem_fd) {
|
||||
g_import_sem_fd = (PFN_vkImportSemaphoreFdKHR)g_vk.GetDeviceProcAddr(g_dev, "vkImportSemaphoreFdKHR");
|
||||
VkSemaphoreCreateInfo wsci = {.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO};
|
||||
@@ -546,6 +604,7 @@ static int dev_init(void) {
|
||||
g_dev_state = 1;
|
||||
reset_sync();
|
||||
init_black_image();
|
||||
if (g_dev_state != 1) return -1;
|
||||
vkp_framegen_device_ready(g_dev, g_queue, g_qfam, fg_features != NULL);
|
||||
return 0;
|
||||
}
|
||||
@@ -557,7 +616,7 @@ static int swap_init_locked(void);
|
||||
static int swap_init(void) {
|
||||
struct timespec ts;
|
||||
int64_t now;
|
||||
if (!g_window) return -1;
|
||||
if (!g_window || g_dev_state != 1) return -1;
|
||||
clock_gettime(CLOCK_MONOTONIC, &ts);
|
||||
now = (int64_t)ts.tv_sec * 1000000000LL + ts.tv_nsec;
|
||||
if (now < g_swap_retry_at_ns) return -1;
|
||||
@@ -842,10 +901,15 @@ static void init_black_image(void) {
|
||||
g_vk.EndCommandBuffer(cmd);
|
||||
VkSubmitInfo si = {.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO, .commandBufferCount = 1, .pCommandBuffers = &cmd};
|
||||
g_vk.ResetFences(g_dev, 1, &g_fence);
|
||||
if (g_vk.QueueSubmit(g_queue, 1, &si, g_fence) == VK_SUCCESS &&
|
||||
g_vk.WaitForFences(g_dev, 1, &g_fence, VK_TRUE, 1000000000ULL) == VK_SUCCESS)
|
||||
g_black_state = 1;
|
||||
else
|
||||
VkResult qr = g_vk.QueueSubmit(g_queue, 1, &si, g_fence);
|
||||
if (qr == VK_SUCCESS) {
|
||||
VkResult fr = timed_wait(g_fence, 1000000000ULL);
|
||||
if (fr == VK_SUCCESS) g_black_state = 1;
|
||||
else if (fr == VK_ERROR_DEVICE_LOST) device_lost("black image");
|
||||
} else if (qr == VK_ERROR_DEVICE_LOST) {
|
||||
device_lost("black image submit");
|
||||
}
|
||||
if (g_black_state != 1)
|
||||
droiddeck_log("gpu", "letterbox black image unavailable: the whole output is cleared every copy-path frame");
|
||||
}
|
||||
|
||||
@@ -949,7 +1013,98 @@ struct vkp_image *vkp_image_from_dmabuf(int fd, uint32_t drm_format, uint64_t mo
|
||||
return vkp_image_import_dmabuf(fd, drm_format, modifier, w, h, stride, offset, 0);
|
||||
}
|
||||
|
||||
int vkp_image_is_dmabuf(const struct vkp_image *img) { return img && img->dmabuf && !img->blit_dst; }
|
||||
/* Return client sources to FOREIGN after their final read. The consuming paths
|
||||
* wait for our fence before Wayland can release an ordinary dma-buf or an
|
||||
* android_wlegl AHardwareBuffer. Producer-fence synchronization is separate from
|
||||
* these image-layout and ownership transfers. */
|
||||
static void release_external_client_image(VkCommandBuffer cmd, struct vkp_image *img) {
|
||||
struct vkp_external_client_barrier_pair pair;
|
||||
if (!img || !vkp_external_client_barrier_pair(
|
||||
img->image, g_qfam, img->dmabuf, img->blit_dst, &pair))
|
||||
return;
|
||||
g_vk.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
|
||||
VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, 0, 0, NULL, 0, NULL, 1, &pair.release);
|
||||
}
|
||||
|
||||
static void release_external_client_draws(VkCommandBuffer cmd, const struct vkp_draw *draws, int count) {
|
||||
for (int i = 0; i < count; i++) {
|
||||
int seen = 0;
|
||||
for (int j = 0; j < i; j++) if (draws[j].img == draws[i].img) { seen = 1; break; }
|
||||
if (!seen) release_external_client_image(cmd, draws[i].img);
|
||||
}
|
||||
}
|
||||
|
||||
int vkp_image_is_dmabuf(const struct vkp_image *img) {
|
||||
return img && vkp_is_external_client_image(img->dmabuf, img->blit_dst);
|
||||
}
|
||||
|
||||
int vkp_android_buffer_supported(void) {
|
||||
return dev_init() == 0 && g_ahb_properties != NULL;
|
||||
}
|
||||
|
||||
struct vkp_image *vkp_image_from_android_buffer(AHardwareBuffer *buffer) {
|
||||
if (!buffer || !vkp_android_buffer_supported()) return NULL;
|
||||
AHardwareBuffer_Desc desc;
|
||||
AHardwareBuffer_describe(buffer, &desc);
|
||||
if (!desc.width || !desc.height || desc.layers != 1 ||
|
||||
(desc.usage & (AHARDWAREBUFFER_USAGE_PROTECTED_CONTENT | AHARDWAREBUFFER_USAGE_GPU_MIPMAP_COMPLETE)) ||
|
||||
!(desc.usage & AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE)) return NULL;
|
||||
VkAndroidHardwareBufferFormatPropertiesANDROID format = {
|
||||
.sType = VK_STRUCTURE_TYPE_ANDROID_HARDWARE_BUFFER_FORMAT_PROPERTIES_ANDROID};
|
||||
VkAndroidHardwareBufferPropertiesANDROID props = {
|
||||
.sType = VK_STRUCTURE_TYPE_ANDROID_HARDWARE_BUFFER_PROPERTIES_ANDROID, .pNext = &format};
|
||||
VkResult result = g_ahb_properties(g_dev, buffer, &props);
|
||||
if (result != VK_SUCCESS ||
|
||||
(format.format != VK_FORMAT_R8G8B8A8_UNORM && format.format != VK_FORMAT_R8G8B8A8_SRGB &&
|
||||
format.format != VK_FORMAT_B8G8R8A8_UNORM && format.format != VK_FORMAT_B8G8R8A8_SRGB) ||
|
||||
!props.memoryTypeBits ||
|
||||
!(format.formatFeatures & VK_FORMAT_FEATURE_BLIT_SRC_BIT)) {
|
||||
LOGE("android_wlegl: unsupported Android buffer import (%s, format %d)",
|
||||
vk_result_name(result), format.format);
|
||||
return NULL;
|
||||
}
|
||||
struct vkp_image *img = calloc(1, sizeof(*img));
|
||||
if (!img) return NULL;
|
||||
img->w = (int)desc.width; img->h = (int)desc.height;
|
||||
img->fmt = format.format; img->dmabuf = 1;
|
||||
const VkFormatFeatureFlags sampled = VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT |
|
||||
VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT;
|
||||
img->sampled = (format.formatFeatures & sampled) == sampled;
|
||||
VkExternalMemoryImageCreateInfo external = {
|
||||
.sType = VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO,
|
||||
.handleTypes = VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID};
|
||||
VkImageCreateInfo create = {
|
||||
.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, .pNext = &external,
|
||||
.imageType = VK_IMAGE_TYPE_2D, .format = img->fmt,
|
||||
.extent = {desc.width, desc.height, 1}, .mipLevels = 1, .arrayLayers = 1,
|
||||
.samples = VK_SAMPLE_COUNT_1_BIT, .tiling = VK_IMAGE_TILING_OPTIMAL,
|
||||
.usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT | (img->sampled ? VK_IMAGE_USAGE_SAMPLED_BIT : 0),
|
||||
.sharingMode = VK_SHARING_MODE_EXCLUSIVE, .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED};
|
||||
result = g_vk.CreateImage(g_dev, &create, NULL, &img->image);
|
||||
if (result != VK_SUCCESS) goto fail;
|
||||
/* AHB image requirements are not queryable before binding. The AHB query supplies them. */
|
||||
uint32_t memory_type = 0;
|
||||
while (!(props.memoryTypeBits & (1u << memory_type))) memory_type++;
|
||||
VkImportAndroidHardwareBufferInfoANDROID import = {
|
||||
.sType = VK_STRUCTURE_TYPE_IMPORT_ANDROID_HARDWARE_BUFFER_INFO_ANDROID, .buffer = buffer};
|
||||
VkMemoryDedicatedAllocateInfo dedicated = {
|
||||
.sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO,
|
||||
.pNext = &import, .image = img->image};
|
||||
VkMemoryAllocateInfo allocate = {
|
||||
.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, .pNext = &dedicated,
|
||||
.allocationSize = props.allocationSize, .memoryTypeIndex = memory_type};
|
||||
result = g_vk.AllocateMemory(g_dev, &allocate, NULL, &img->mem);
|
||||
if (result != VK_SUCCESS) goto fail;
|
||||
result = g_vk.BindImageMemory(g_dev, img->image, img->mem, 0);
|
||||
if (result != VK_SUCCESS) goto fail;
|
||||
AHardwareBuffer_acquire(buffer);
|
||||
img->android_buffer = buffer;
|
||||
return img;
|
||||
fail:
|
||||
LOGE("android_wlegl: Vulkan buffer import failed: %s", vk_result_name(result));
|
||||
vkp_image_destroy(img);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
struct vkp_image *vkp_image_import_dmabuf(int fd, uint32_t drm_format, uint64_t modifier, int w, int h,
|
||||
uint32_t stride, uint32_t offset, int as_blit_dst) {
|
||||
@@ -963,7 +1118,27 @@ struct vkp_image *vkp_image_import_dmabuf(int fd, uint32_t drm_format, uint64_t
|
||||
const VkImageUsageFlags sampled_usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_SAMPLED_BIT;
|
||||
img->sampled = !as_blit_dst && g_vk.GetPhysicalDeviceImageFormatProperties2 &&
|
||||
modifier_importable(img->fmt, modifier, sampled_usage);
|
||||
/* Each new format/modifier/size a client hands over, once, for the graphics report: a colour
|
||||
* or swizzle mismatch on a non-Adreno driver shows up as the pair it arrived as. */
|
||||
{
|
||||
static struct { uint32_t fmt; uint64_t mod; int w, h; } seen[32];
|
||||
static int nseen;
|
||||
int known = 0;
|
||||
for (int i = 0; i < nseen; i++)
|
||||
if (seen[i].fmt == drm_format && seen[i].mod == modifier && seen[i].w == w && seen[i].h == h) known = 1;
|
||||
if (!known && nseen < 32) {
|
||||
seen[nseen].fmt = drm_format; seen[nseen].mod = modifier; seen[nseen].w = w; seen[nseen].h = h; nseen++;
|
||||
droiddeck_log("gpu", "dmabuf import: %c%c%c%c %s %dx%d stride %u offset %u -> vk format %d, %s%s",
|
||||
drm_format & 0xff, (drm_format >> 8) & 0xff, (drm_format >> 16) & 0xff, (drm_format >> 24) & 0xff,
|
||||
vkp_modifier_name(modifier), w, h, stride, offset, (int)img->fmt,
|
||||
img->sampled ? "sampled" : "copied", as_blit_dst ? ", blit target" : "");
|
||||
}
|
||||
}
|
||||
|
||||
/* Venus reports a row pitch of 0 for gamescope's 1x1 root buffer, and a zero pitch fails
|
||||
* vkCreateImage, which left the whole window unshown (David Cimo). One packed, 64-byte aligned
|
||||
* row is what a linear buffer that small holds. */
|
||||
if (stride == 0 && modifier == 0) stride = ((uint32_t)w * 4 + 63) & ~63u;
|
||||
VkSubresourceLayout plane = {.offset = offset, .rowPitch = stride};
|
||||
VkImageDrmFormatModifierExplicitCreateInfoEXT modInfo = {
|
||||
.sType = VK_STRUCTURE_TYPE_IMAGE_DRM_FORMAT_MODIFIER_EXPLICIT_CREATE_INFO_EXT,
|
||||
@@ -1084,10 +1259,10 @@ struct vkp_image *vkp_image_create_shm(int w, int h) {
|
||||
return img;
|
||||
}
|
||||
|
||||
/* Renders are synchronous (we wait for the frame's fence), so writing between frames
|
||||
* never races the GPU. */
|
||||
/* Between successfully completed frames the GPU is idle. After an unconfirmed
|
||||
* wait, retain the mapped bytes too: the previous submit may still read them. */
|
||||
void vkp_image_upload_shm(struct vkp_image *img, const void *data, int stride) {
|
||||
if (!img || !img->map || !data) return;
|
||||
if (g_dev_state != 1 || !img || !img->map || !data) return;
|
||||
size_t rowbytes = (size_t)img->w * 4;
|
||||
if ((size_t)stride < rowbytes) rowbytes = (size_t)stride;
|
||||
for (int y = 0; y < img->h; y++)
|
||||
@@ -1100,12 +1275,14 @@ int vkp_image_height(const struct vkp_image *img) { return img ? img->h : 0; }
|
||||
|
||||
void vkp_image_destroy(struct vkp_image *img) {
|
||||
if (!img) return;
|
||||
if (g_dev_state == -3) return; /* completion unknown: retain GPU ownership */
|
||||
if (g_dev) {
|
||||
blendp_forget_image(img->image);
|
||||
if (img->map) g_vk.UnmapMemory(g_dev, img->mem);
|
||||
if (img->image) g_vk.DestroyImage(g_dev, img->image, NULL);
|
||||
if (img->mem) g_vk.FreeMemory(g_dev, img->mem, NULL);
|
||||
}
|
||||
if (img->android_buffer) AHardwareBuffer_release(img->android_buffer);
|
||||
free(img);
|
||||
}
|
||||
|
||||
@@ -1155,11 +1332,14 @@ static int draw_to_scene_blit(const struct vkp_draw *d, int scene_w, int scene_h
|
||||
static void record_draw(VkCommandBuffer cmd, const struct vkp_draw *d, const VkImageBlit *blit, VkImage target,
|
||||
VkFormat target_fmt, int target_w, int target_h, VkFilter filter) {
|
||||
const struct vkp_image *im = d->img;
|
||||
const int external_client = vkp_image_is_dmabuf(im);
|
||||
if (d->blend && im->sampled &&
|
||||
blendp_draw(cmd, im->image, im->fmt, im->w, im->h, !im->dmabuf, target, target_fmt, target_w, target_h,
|
||||
blendp_draw(cmd, im->image, im->fmt, im->w, im->h, !external_client,
|
||||
target, target_fmt, target_w, target_h,
|
||||
blit) == 0)
|
||||
return;
|
||||
g_vk.CmdBlitImage(cmd, im->image, im->dmabuf ? VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL : VK_IMAGE_LAYOUT_GENERAL,
|
||||
g_vk.CmdBlitImage(cmd, im->image,
|
||||
external_client ? VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL : VK_IMAGE_LAYOUT_GENERAL,
|
||||
target, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, blit, filter);
|
||||
}
|
||||
|
||||
@@ -1391,6 +1571,7 @@ static void record_screen_blit(VkCommandBuffer cmd, VkImage src, int src_w, int
|
||||
* so they never rebuild; they fail and the frame ends early. 0 on success. */
|
||||
static int acquire_image(int k, int first, uint32_t *img, VkResult *ar_out) {
|
||||
for (int attempt = 0; ; attempt++) {
|
||||
if (g_dev_state != 1) return -1;
|
||||
if (!g_swapchain && (!first || swap_init() != 0)) return -1;
|
||||
/* A bounded wait: a surface that went away without telling us must not park the
|
||||
* compositor thread forever (clients are paced from this thread). */
|
||||
@@ -1402,7 +1583,7 @@ static int acquire_image(int k, int first, uint32_t *img, VkResult *ar_out) {
|
||||
if (ar == VK_ERROR_OUT_OF_DATE_KHR || ar == VK_ERROR_SURFACE_LOST_KHR) {
|
||||
droiddeck_log("gpu", "screen surface %s on acquire: rebuilding the swapchain", vk_result_name(ar));
|
||||
destroy_swapchain();
|
||||
if (first && attempt == 0) continue;
|
||||
if (first && attempt == 0 && g_dev_state == 1) continue;
|
||||
return -1;
|
||||
}
|
||||
droiddeck_log("error", "present: acquire %d failed (%s %d)", k, vk_result_name(ar), (int)ar);
|
||||
@@ -1530,6 +1711,7 @@ static void send_hdr_metadata(const struct droiddeck_color *c) {
|
||||
static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, int n,
|
||||
const struct vkp_hdr_frame *hf, int *how) {
|
||||
if (how) *how = 0;
|
||||
if (g_dev_state < 0) return -1;
|
||||
vkp_apply_window_request();
|
||||
check_surface_changed(); /* a rotation or a fold the rebind did not cover: rebuild at the new size */
|
||||
if (g_dev_state == -2) return -1;
|
||||
@@ -1552,6 +1734,7 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i
|
||||
: "no HDR frames through the screen swapchain any more: rebuilding it as SDR");
|
||||
destroy_swapchain();
|
||||
}
|
||||
if (g_dev_state != 1) return -1;
|
||||
g_swap_hdr_want = want_hdr;
|
||||
|
||||
uint32_t img = 0;
|
||||
@@ -1625,13 +1808,11 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i
|
||||
int seen = 0;
|
||||
for (int j = 0; j < i; j++) if (draws[j].img == im) { seen = 1; break; }
|
||||
if (seen || !im) continue;
|
||||
if (im->dmabuf) {
|
||||
bars[nb++] = (VkImageMemoryBarrier){
|
||||
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
|
||||
.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
|
||||
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_FOREIGN_EXT, .dstQueueFamilyIndex = g_qfam,
|
||||
.image = im->image, .subresourceRange = range, .dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT};
|
||||
} else if (!im->in_general) {
|
||||
struct vkp_external_client_barrier_pair pair;
|
||||
if (vkp_external_client_barrier_pair(
|
||||
im->image, g_qfam, im->dmabuf, im->blit_dst, &pair)) {
|
||||
bars[nb++] = pair.acquire;
|
||||
} else if (!im->blit_dst && !im->in_general) {
|
||||
bars[nb++] = (VkImageMemoryBarrier){
|
||||
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_PREINITIALIZED,
|
||||
.newLayout = VK_IMAGE_LAYOUT_GENERAL,
|
||||
@@ -1698,6 +1879,7 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i
|
||||
drawn++;
|
||||
}
|
||||
|
||||
release_external_client_draws(cmd, draws, n);
|
||||
int ngen = 0;
|
||||
VkImage gens[VKP_FG_MAX_GENERATIONS] = {VK_NULL_HANDLE};
|
||||
VkImage result = scene_img;
|
||||
@@ -1762,6 +1944,10 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i
|
||||
if (k > 0) {
|
||||
VkResult ark;
|
||||
if (acquire_image(k, 0, &img, &ark) != 0) {
|
||||
/* Teardown may have retained this frame's pending work, or
|
||||
* acquire may have reported real device loss. Neither permits
|
||||
* a completion-marker submit or another fence wait. */
|
||||
if (g_dev_state != 1) return -1;
|
||||
droiddeck_log("framegen", "present %d/%d: no swapchain image; the frame ends early", k + 1, presents);
|
||||
pr = VK_ERROR_OUT_OF_DATE_KHR;
|
||||
break;
|
||||
@@ -1794,17 +1980,24 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i
|
||||
pr = g_vk.QueuePresentKHR(g_queue, &pi);
|
||||
perf_add(&g_perf.present_ns, &g_perf.present_max_ns, &g_perf.presents, perf_now() - t_pres);
|
||||
if (k < ngen) presented_gen++;
|
||||
if (pr == VK_ERROR_OUT_OF_DATE_KHR || pr == VK_ERROR_SURFACE_LOST_KHR || pr == VK_ERROR_DEVICE_LOST) break;
|
||||
if (pr == VK_ERROR_DEVICE_LOST) { device_lost("present"); return -1; }
|
||||
if (pr == VK_ERROR_OUT_OF_DATE_KHR || pr == VK_ERROR_SURFACE_LOST_KHR) break;
|
||||
}
|
||||
if (!fence_submitted) {
|
||||
/* Ended early: an empty submit carrying the fence is ordered after everything queued
|
||||
* above, so the wait below still means "this frame's work is done". */
|
||||
VkSubmitInfo si = {.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO};
|
||||
g_vk.QueueSubmit(g_queue, 1, &si, g_fence);
|
||||
VkResult marker = g_vk.QueueSubmit(g_queue, 1, &si, g_fence);
|
||||
if (marker != VK_SUCCESS) {
|
||||
if (marker == VK_ERROR_DEVICE_LOST) device_lost("frame completion submit");
|
||||
else quarantine_pending_work(marker, "frame completion submit");
|
||||
return -1; /* no fence was submitted; never wait on its unsignalled state */
|
||||
}
|
||||
}
|
||||
VkResult fr = timed_wait(g_fence, UINT64_MAX);
|
||||
if (fg) vkp_framegen_presented(presented_gen);
|
||||
if (fr == VK_ERROR_DEVICE_LOST || pr == VK_ERROR_DEVICE_LOST) { device_lost("present"); return -1; }
|
||||
if (fr != VK_SUCCESS) return -1;
|
||||
if (fg) vkp_framegen_presented(presented_gen);
|
||||
if (pr == VK_ERROR_OUT_OF_DATE_KHR || pr == VK_ERROR_SURFACE_LOST_KHR) {
|
||||
/* The surface changed or went away under this frame: rebuild before the next one. */
|
||||
droiddeck_log("gpu", "screen surface %s on present: rebuilding the swapchain", vk_result_name(pr));
|
||||
@@ -1878,6 +2071,7 @@ void vkp_signal_first_frame(void) {
|
||||
int vkp_update_map(int scene_w, int scene_h) {
|
||||
if (g_dev_state == -2 || dev_init() != 0 || !g_window || scene_w <= 0 || scene_h <= 0) return -1;
|
||||
check_surface_changed(); /* layer mode may present nothing on the base surface for a long time */
|
||||
if (g_dev_state != 1) return -1;
|
||||
if (!g_swapchain && swap_init() != 0) return -1;
|
||||
update_map(scene_w, scene_h);
|
||||
return g_map.valid ? 0 : -1;
|
||||
@@ -1903,7 +2097,7 @@ int vkp_map_draw(const struct vkp_draw *d, int out[8]) {
|
||||
* owned by the "foreign" queue family (the game's driver / the display) between our uses, so each
|
||||
* use acquires them and the destination is released back for the display to read. */
|
||||
int vkp_blit_image(struct vkp_image *src, struct vkp_image *dst, int wait_fd) {
|
||||
if (!src || !dst || !dst->blit_dst || g_dev_state == -2 || dev_init() != 0) {
|
||||
if (!src || src->blit_dst || !dst || !dst->blit_dst || g_dev_state == -2 || dev_init() != 0) {
|
||||
if (wait_fd >= 0) close(wait_fd);
|
||||
return -1;
|
||||
}
|
||||
@@ -1916,17 +2110,21 @@ int vkp_blit_image(struct vkp_image *src, struct vkp_image *dst, int wait_fd) {
|
||||
VkCommandBufferBeginInfo bi = {.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
|
||||
.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT};
|
||||
g_vk.BeginCommandBuffer(g_cmd, &bi);
|
||||
struct vkp_external_client_barrier_pair src_pair;
|
||||
const int src_external = vkp_external_client_barrier_pair(
|
||||
src->image, g_qfam, src->dmabuf, src->blit_dst, &src_pair);
|
||||
VkImageMemoryBarrier acq[2] = {
|
||||
{.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
|
||||
src_external ? src_pair.acquire : (VkImageMemoryBarrier){
|
||||
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
|
||||
.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
|
||||
.srcQueueFamilyIndex = src->dmabuf ? VK_QUEUE_FAMILY_FOREIGN_EXT : VK_QUEUE_FAMILY_IGNORED,
|
||||
.dstQueueFamilyIndex = src->dmabuf ? g_qfam : VK_QUEUE_FAMILY_IGNORED,
|
||||
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
|
||||
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
|
||||
.image = src->image, .subresourceRange = range, .dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT},
|
||||
{.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
|
||||
.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
|
||||
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_FOREIGN_EXT, .dstQueueFamilyIndex = g_qfam,
|
||||
.image = dst->image, .subresourceRange = range, .dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT}};
|
||||
if (!src->dmabuf) { /* shm image: host-written, GENERAL */
|
||||
if (!src_external) { /* shm image: host-written, GENERAL */
|
||||
acq[0].oldLayout = src->in_general ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_PREINITIALIZED;
|
||||
acq[0].newLayout = VK_IMAGE_LAYOUT_GENERAL;
|
||||
acq[0].srcAccessMask = VK_ACCESS_HOST_WRITE_BIT;
|
||||
@@ -1940,8 +2138,9 @@ int vkp_blit_image(struct vkp_image *src, struct vkp_image *dst, int wait_fd) {
|
||||
.dstSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1},
|
||||
.dstOffsets = {{0, 0, 0}, {bw, bh, 1}}};
|
||||
g_vk.CmdBlitImage(g_cmd, src->image,
|
||||
src->dmabuf ? VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL : VK_IMAGE_LAYOUT_GENERAL,
|
||||
src_external ? VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL : VK_IMAGE_LAYOUT_GENERAL,
|
||||
dst->image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &blit, VK_FILTER_NEAREST);
|
||||
release_external_client_image(g_cmd, src);
|
||||
VkImageMemoryBarrier rel = {
|
||||
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
|
||||
.newLayout = VK_IMAGE_LAYOUT_GENERAL, .srcQueueFamilyIndex = g_qfam,
|
||||
@@ -1976,7 +2175,7 @@ int vkp_blit_image(struct vkp_image *src, struct vkp_image *dst, int wait_fd) {
|
||||
static struct vkp_image *g_rb; /* the readback image, kept for the next shape */
|
||||
|
||||
int vkp_image_readback(struct vkp_image *src, uint32_t *out, int max_px) {
|
||||
if (!src || !out || src->w <= 0 || src->h <= 0 || src->w * src->h > max_px ||
|
||||
if (!src || src->blit_dst || !out || src->w <= 0 || src->h <= 0 || src->w * src->h > max_px ||
|
||||
g_dev_state == -2 || dev_init() != 0)
|
||||
return -1;
|
||||
if (g_rb && (g_rb->w != src->w || g_rb->h != src->h)) { vkp_image_destroy(g_rb); g_rb = NULL; }
|
||||
@@ -2017,11 +2216,15 @@ int vkp_image_readback(struct vkp_image *src, uint32_t *out, int max_px) {
|
||||
VkCommandBufferBeginInfo bi = {.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
|
||||
.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT};
|
||||
g_vk.BeginCommandBuffer(cmd, &bi);
|
||||
struct vkp_external_client_barrier_pair src_pair;
|
||||
const int src_external = vkp_external_client_barrier_pair(
|
||||
src->image, g_qfam, src->dmabuf, src->blit_dst, &src_pair);
|
||||
VkImageMemoryBarrier acq[2] = {
|
||||
{.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
|
||||
src_external ? src_pair.acquire : (VkImageMemoryBarrier){
|
||||
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
|
||||
.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
|
||||
.srcQueueFamilyIndex = src->dmabuf ? VK_QUEUE_FAMILY_FOREIGN_EXT : VK_QUEUE_FAMILY_IGNORED,
|
||||
.dstQueueFamilyIndex = src->dmabuf ? g_qfam : VK_QUEUE_FAMILY_IGNORED,
|
||||
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
|
||||
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
|
||||
.image = src->image, .subresourceRange = range, .dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT},
|
||||
{.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
|
||||
.newLayout = VK_IMAGE_LAYOUT_GENERAL, .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
|
||||
@@ -2039,16 +2242,20 @@ int vkp_image_readback(struct vkp_image *src, uint32_t *out, int max_px) {
|
||||
{.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_GENERAL,
|
||||
.newLayout = VK_IMAGE_LAYOUT_GENERAL, .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
|
||||
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, .image = g_rb->image, .subresourceRange = range,
|
||||
.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT, .dstAccessMask = VK_ACCESS_HOST_READ_BIT},
|
||||
/* the client's buffer goes back to it */
|
||||
{.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
|
||||
.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT, .dstAccessMask = VK_ACCESS_HOST_READ_BIT}};
|
||||
uint32_t done_count = 1;
|
||||
if (!src_external) {
|
||||
done[done_count++] = (VkImageMemoryBarrier){
|
||||
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
|
||||
.newLayout = VK_IMAGE_LAYOUT_GENERAL,
|
||||
.srcQueueFamilyIndex = src->dmabuf ? g_qfam : VK_QUEUE_FAMILY_IGNORED,
|
||||
.dstQueueFamilyIndex = src->dmabuf ? VK_QUEUE_FAMILY_FOREIGN_EXT : VK_QUEUE_FAMILY_IGNORED,
|
||||
.image = src->image, .subresourceRange = range, .srcAccessMask = VK_ACCESS_TRANSFER_READ_BIT}};
|
||||
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
|
||||
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
|
||||
.image = src->image, .subresourceRange = range, .srcAccessMask = VK_ACCESS_TRANSFER_READ_BIT};
|
||||
}
|
||||
g_vk.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT,
|
||||
VK_PIPELINE_STAGE_HOST_BIT | VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
|
||||
0, 0, NULL, 0, NULL, 2, done);
|
||||
0, 0, NULL, 0, NULL, done_count, done);
|
||||
release_external_client_image(cmd, src);
|
||||
g_vk.EndCommandBuffer(cmd);
|
||||
VkSubmitInfo si = {.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO, .commandBufferCount = 1, .pCommandBuffers = &cmd};
|
||||
g_vk.ResetFences(g_dev, 1, &g_fence);
|
||||
@@ -2116,6 +2323,7 @@ static int pass_begin_impl(int scene_w, int scene_h, const struct vkp_draw *draw
|
||||
if (g_pass.active) vkp_pass_abort();
|
||||
if (g_dev_state == -2 || dev_init() != 0 || !g_window || scene_w <= 0 || scene_h <= 0) return -1;
|
||||
check_surface_changed(); /* as in render_impl: the effects pass maps onto the output's size */
|
||||
if (g_dev_state != 1) return -1;
|
||||
if (!g_swapchain && swap_init() != 0) return -1; /* the mapping is in output pixels */
|
||||
update_map(scene_w, scene_h);
|
||||
if (!g_map.valid) return -1;
|
||||
@@ -2151,13 +2359,11 @@ static int pass_begin_impl(int scene_w, int scene_h, const struct vkp_draw *draw
|
||||
int seen = 0;
|
||||
for (int j = 0; j < i; j++) if (draws[j].img == im) { seen = 1; break; }
|
||||
if (seen || !im) continue;
|
||||
if (im->dmabuf) {
|
||||
bars[nb++] = (VkImageMemoryBarrier){
|
||||
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
|
||||
.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
|
||||
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_FOREIGN_EXT, .dstQueueFamilyIndex = g_qfam,
|
||||
.image = im->image, .subresourceRange = range, .dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT};
|
||||
} else if (!im->in_general) {
|
||||
struct vkp_external_client_barrier_pair pair;
|
||||
if (vkp_external_client_barrier_pair(
|
||||
im->image, g_qfam, im->dmabuf, im->blit_dst, &pair)) {
|
||||
bars[nb++] = pair.acquire;
|
||||
} else if (!im->blit_dst && !im->in_general) {
|
||||
bars[nb++] = (VkImageMemoryBarrier){
|
||||
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_PREINITIALIZED,
|
||||
.newLayout = VK_IMAGE_LAYOUT_GENERAL,
|
||||
@@ -2198,6 +2404,7 @@ static int pass_begin_impl(int scene_w, int scene_h, const struct vkp_draw *draw
|
||||
if (vkp_effects_active()) vkp_effects_set_formats(VK_FORMAT_R8G8B8A8_UNORM, VK_FORMAT_R8G8B8A8_UNORM);
|
||||
}
|
||||
|
||||
release_external_client_draws(cmd, draws, n);
|
||||
int mapped_w = (int)(scene_w * g_map.kx + 0.5f), mapped_h = (int)(scene_h * g_map.ky + 0.5f);
|
||||
g_pass.rw = scene_w; g_pass.rh = scene_h;
|
||||
g_pass.result = vkp_effects_run(cmd, scene_img, scene_w, scene_h, mapped_w, mapped_h,
|
||||
@@ -2211,8 +2418,9 @@ static int pass_begin_impl(int scene_w, int scene_h, const struct vkp_draw *draw
|
||||
int vkp_pass_copy_to(struct vkp_image *dst, int wait_fd) {
|
||||
if (!g_pass.active) { if (wait_fd >= 0) close(wait_fd); return -1; }
|
||||
g_pass.active = 0;
|
||||
if (g_dev_state != 1) { if (wait_fd >= 0) close(wait_fd); return -1; }
|
||||
VkCommandBuffer cmd = g_cmds[0];
|
||||
if (!dst || !dst->blit_dst || g_dev_state == -2) {
|
||||
if (!dst || !dst->blit_dst) {
|
||||
if (wait_fd >= 0) close(wait_fd);
|
||||
g_vk.EndCommandBuffer(cmd);
|
||||
return -1;
|
||||
@@ -2267,5 +2475,6 @@ int vkp_pass_copy_to(struct vkp_image *dst, int wait_fd) {
|
||||
void vkp_pass_abort(void) {
|
||||
if (!g_pass.active) return;
|
||||
g_pass.active = 0;
|
||||
g_vk.EndCommandBuffer(g_cmds[0]); /* never submitted; the buffer is reset before its next use */
|
||||
if (g_dev_state == 1)
|
||||
g_vk.EndCommandBuffer(g_cmds[0]); /* never submitted; reset before its next use */
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
#define VK_PRESENT_H
|
||||
#include <stdint.h>
|
||||
#include <android/native_window.h>
|
||||
#include <android/hardware_buffer.h>
|
||||
/*
|
||||
* Android-surface render backend for the embedded Wayland compositor.
|
||||
* Owns a Turnip VkDevice + a swapchain on the SurfaceView's ANativeWindow. Each
|
||||
@@ -39,6 +40,11 @@ void vkp_output_size(int *w, int *h);
|
||||
|
||||
struct vkp_image;
|
||||
|
||||
/* android_wlegl clients share complete Android buffer handles, not guessed DMA-BUF layouts.
|
||||
* The image retains its own AHB reference. Call only from the compositor thread. */
|
||||
int vkp_android_buffer_supported(void);
|
||||
struct vkp_image *vkp_image_from_android_buffer(AHardwareBuffer *buffer);
|
||||
|
||||
/* DRM format modifiers this backend knows the memory layout of (both single-plane on Adreno):
|
||||
* LINEAR, and QCOM_COMPRESSED = UBWC (drm_fourcc.h: fourcc_mod_code(QCOM = 0x05, 1)). */
|
||||
#define VKP_MOD_LINEAR 0x0000000000000000ULL
|
||||
@@ -91,6 +97,10 @@ int vkp_ready(void);
|
||||
int vkp_has_window(void);
|
||||
/* 1 once the Vulkan device was lost: nothing is presented any more (the session must restart). */
|
||||
int vkp_device_lost(void);
|
||||
/* Compositor thread only. Submitted reads may still be pending: retain imported
|
||||
* buffer references and withhold DMA-BUF releases until the app process exits.
|
||||
* This terminal state is distinct from genuine device loss. */
|
||||
int vkp_completion_unknown(void);
|
||||
|
||||
// Clear to black, blit the draws in order (first = bottom) and present.
|
||||
// Returns 0 on success, -1 if nothing could be presented (no window yet, etc.).
|
||||
|
||||
@@ -0,0 +1,216 @@
|
||||
/* android_wlegl buffer import for the existing libhybris Wayland WSI.
|
||||
* Protocol: Collabora/libhybris, vendored with its license in protocols/wayland-android.xml.
|
||||
* Native handles are cloned through Android; opaque vendor integers are never interpreted. */
|
||||
#include "compositor_internal.h"
|
||||
#include "droiddeck_ext.h"
|
||||
#include "wayland-android-server-protocol.h"
|
||||
#include <android/hardware_buffer.h>
|
||||
#include <dlfcn.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <unistd.h>
|
||||
|
||||
/* Stable native_handle_t ABI, unavailable in the public NDK. */
|
||||
struct android_native_handle {
|
||||
int version, num_fds, num_ints;
|
||||
int data[];
|
||||
};
|
||||
struct wire_handle {
|
||||
struct android_native_handle *handle;
|
||||
int received;
|
||||
};
|
||||
enum { MAX_HANDLE_FDS = 64, MAX_HANDLE_INTS = 256, MAX_BUFFER_SIDE = 8192 };
|
||||
/* VNDK ABI (not exposed by the NDK): frameworks/native/libs/nativewindow/include/
|
||||
* vndk/hardware_buffer.h, AHARDWAREBUFFER_CREATE_FROM_HANDLE_METHOD_CLONE = 3.
|
||||
* Method 1 is not accepted by AHardwareBuffer_createFromHandle. */
|
||||
enum { CREATE_FROM_HANDLE_CLONE = 3 };
|
||||
static int (*import_handle)(const AHardwareBuffer_Desc *, const struct android_native_handle *,
|
||||
int32_t, AHardwareBuffer **);
|
||||
static const struct android_native_handle *(*native_handle)(const AHardwareBuffer *);
|
||||
|
||||
static int valid_description(int32_t width, int32_t height, int32_t stride, int32_t format) {
|
||||
return width > 0 && height > 0 && width <= MAX_BUFFER_SIDE && height <= MAX_BUFFER_SIDE &&
|
||||
stride >= width && stride <= MAX_BUFFER_SIDE * 4 &&
|
||||
(format == 1 || format == 2 || format == 5);
|
||||
}
|
||||
|
||||
static void handle_resource_destroy(struct wl_resource *resource) {
|
||||
struct wire_handle *wire = wl_resource_get_user_data(resource);
|
||||
if (!wire) return;
|
||||
for (int i = 0; i < wire->received; i++) close(wire->handle->data[i]);
|
||||
free(wire->handle);
|
||||
free(wire);
|
||||
}
|
||||
|
||||
static void handle_add_fd(struct wl_client *client, struct wl_resource *resource, int32_t fd) {
|
||||
struct wire_handle *wire = wl_resource_get_user_data(resource);
|
||||
if (wire->received >= wire->handle->num_fds) {
|
||||
close(fd);
|
||||
wl_resource_post_error(resource, ANDROID_WLEGL_HANDLE_ERROR_TOO_MANY_FDS,
|
||||
"more native handle descriptors than declared");
|
||||
return;
|
||||
}
|
||||
wire->handle->data[wire->received++] = fd;
|
||||
}
|
||||
|
||||
static void handle_destroy(struct wl_client *client, struct wl_resource *resource) {
|
||||
wl_resource_destroy(resource);
|
||||
}
|
||||
|
||||
static const struct android_wlegl_handle_interface handle_impl = {
|
||||
.add_fd = handle_add_fd, .destroy = handle_destroy,
|
||||
};
|
||||
|
||||
static void create_handle(struct wl_client *client, struct wl_resource *resource,
|
||||
uint32_t id, int32_t fds, struct wl_array *ints) {
|
||||
if (fds < 0 || fds > MAX_HANDLE_FDS || ints->size % sizeof(int32_t) ||
|
||||
ints->size > MAX_HANDLE_INTS * sizeof(int32_t)) {
|
||||
wl_resource_post_error(resource, ANDROID_WLEGL_ERROR_BAD_VALUE, "invalid native handle size");
|
||||
return;
|
||||
}
|
||||
struct wire_handle *wire = calloc(1, sizeof(*wire));
|
||||
if (!wire) { wl_client_post_no_memory(client); return; }
|
||||
wire->handle = calloc(1, sizeof(*wire->handle) + (size_t)fds * sizeof(int32_t) + ints->size);
|
||||
if (!wire->handle) { free(wire); wl_client_post_no_memory(client); return; }
|
||||
wire->handle->version = sizeof(*wire->handle);
|
||||
wire->handle->num_fds = fds;
|
||||
wire->handle->num_ints = (int)(ints->size / sizeof(int32_t));
|
||||
if (ints->size) memcpy(wire->handle->data + fds, ints->data, ints->size);
|
||||
struct wl_resource *handle = wl_resource_create(client, &android_wlegl_handle_interface, 1, id);
|
||||
if (!handle) {
|
||||
free(wire->handle); free(wire); wl_client_post_no_memory(client); return;
|
||||
}
|
||||
wl_resource_set_implementation(handle, &handle_impl, wire, handle_resource_destroy);
|
||||
}
|
||||
|
||||
static void buffer_resource_destroy(struct wl_resource *resource) {
|
||||
dmabuf_buffer_unref(wl_resource_get_user_data(resource));
|
||||
}
|
||||
|
||||
static struct wl_resource *create_android_buffer(struct wl_client *client, uint32_t id,
|
||||
AHardwareBuffer *hardware) {
|
||||
AHardwareBuffer_Desc desc;
|
||||
AHardwareBuffer_describe(hardware, &desc);
|
||||
struct vkp_image *image = vkp_image_from_android_buffer(hardware);
|
||||
if (!image) return NULL;
|
||||
struct dmabuf_buffer *buffer = calloc(1, sizeof(*buffer));
|
||||
if (!buffer) { vkp_image_destroy(image); wl_client_post_no_memory(client); return NULL; }
|
||||
buffer->refs = 1;
|
||||
buffer->width = (int32_t)desc.width; buffer->height = (int32_t)desc.height;
|
||||
buffer->format = desc.format == 5 ? DRM_ARGB8888 : desc.format == 2 ? DRM_XBGR8888 : DRM_ABGR8888;
|
||||
buffer->modifier = MOD_INVALID; /* No DMA-BUF layout was inferred from the native handle. */
|
||||
buffer->img = image;
|
||||
for (int i = 0; i < MAX_PLANES; i++) buffer->fd[i] = -1;
|
||||
struct wl_resource *result = wl_resource_create(client, &wl_buffer_interface, 1, id);
|
||||
if (!result) { dmabuf_buffer_unref(buffer); wl_client_post_no_memory(client); return NULL; }
|
||||
wl_resource_set_implementation(result, &dbuf_buffer_impl, buffer, buffer_resource_destroy);
|
||||
struct client_info *info = client_info_of(client);
|
||||
if (info) info->dmabuf_buffers++;
|
||||
return result;
|
||||
}
|
||||
|
||||
static void create_buffer(struct wl_client *client, struct wl_resource *resource, uint32_t id,
|
||||
int32_t width, int32_t height, int32_t stride, int32_t format,
|
||||
int32_t usage, struct wl_resource *handle_resource) {
|
||||
/* Some vendor allocators (Samsung Xclipse) record no stride for GPU-only buffers. The import
|
||||
* must pass that 0 back unchanged: gralloc validates it against the handle's own value. */
|
||||
if (!valid_description(width, height, stride ? stride : width, format) ||
|
||||
!wl_resource_instance_of(handle_resource, &android_wlegl_handle_interface, &handle_impl)) {
|
||||
droiddeck_log("display", "android_wlegl rejected: %dx%d stride=%d format=%d usage=0x%x",
|
||||
width, height, stride, format, (uint32_t)usage);
|
||||
wl_resource_post_error(resource, ANDROID_WLEGL_ERROR_BAD_VALUE, "invalid Android buffer description");
|
||||
return;
|
||||
}
|
||||
struct wire_handle *wire = wl_resource_get_user_data(handle_resource);
|
||||
if (wire->received != wire->handle->num_fds || !wire->received) {
|
||||
wl_resource_post_error(resource, ANDROID_WLEGL_ERROR_BAD_HANDLE, "incomplete native handle");
|
||||
return;
|
||||
}
|
||||
AHardwareBuffer_Desc desc = {
|
||||
.width = (uint32_t)width, .height = (uint32_t)height, .layers = 1,
|
||||
.format = (uint32_t)format, .usage = (uint32_t)usage, .stride = (uint32_t)stride};
|
||||
AHardwareBuffer *hardware = NULL;
|
||||
int status = import_handle(&desc, wire->handle, CREATE_FROM_HANDLE_CLONE, &hardware);
|
||||
if (status != 0 || !hardware) {
|
||||
droiddeck_log("display", "android_wlegl import failed: status=%d %dx%d stride=%d format=%d usage=0x%x fds=%d ints=%d",
|
||||
status, width, height, stride, format, (uint32_t)usage,
|
||||
wire->handle->num_fds, wire->handle->num_ints);
|
||||
wl_resource_post_error(resource, ANDROID_WLEGL_ERROR_BAD_HANDLE,
|
||||
"Android rejected the native handle (status %d)", status);
|
||||
return;
|
||||
}
|
||||
struct wl_resource *buffer = create_android_buffer(client, id, hardware);
|
||||
AHardwareBuffer_release(hardware);
|
||||
if (!buffer) wl_resource_post_error(resource, ANDROID_WLEGL_ERROR_BAD_HANDLE, "Vulkan cannot import this buffer");
|
||||
}
|
||||
|
||||
static void get_server_buffer(struct wl_client *client, struct wl_resource *resource, uint32_t id,
|
||||
int32_t width, int32_t height, int32_t format, int32_t usage) {
|
||||
if (!format) format = 1;
|
||||
if (!valid_description(width, height, width, format)) {
|
||||
wl_resource_post_error(resource, ANDROID_WLEGL_ERROR_BAD_VALUE, "invalid buffer allocation request");
|
||||
return;
|
||||
}
|
||||
AHardwareBuffer_Desc desc = {
|
||||
.width = (uint32_t)width, .height = (uint32_t)height, .layers = 1,
|
||||
.format = (uint32_t)format,
|
||||
.usage = (uint32_t)usage | AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE | AHARDWAREBUFFER_USAGE_GPU_COLOR_OUTPUT};
|
||||
AHardwareBuffer *hardware = NULL;
|
||||
if (AHardwareBuffer_allocate(&desc, &hardware) != 0 || !hardware) {
|
||||
wl_resource_post_error(resource, ANDROID_WLEGL_ERROR_BAD_VALUE, "Android buffer allocation failed");
|
||||
return;
|
||||
}
|
||||
AHardwareBuffer_describe(hardware, &desc);
|
||||
const struct android_native_handle *handle = native_handle(hardware);
|
||||
if (!handle || handle->num_fds < 1 || handle->num_fds > MAX_HANDLE_FDS ||
|
||||
handle->num_ints < 0 || handle->num_ints > MAX_HANDLE_INTS) {
|
||||
AHardwareBuffer_release(hardware);
|
||||
wl_resource_post_error(resource, ANDROID_WLEGL_ERROR_BAD_HANDLE, "invalid allocated native handle");
|
||||
return;
|
||||
}
|
||||
struct wl_resource *buffer = create_android_buffer(client, 0, hardware);
|
||||
if (!buffer) {
|
||||
AHardwareBuffer_release(hardware);
|
||||
wl_resource_post_error(resource, ANDROID_WLEGL_ERROR_BAD_HANDLE, "Vulkan cannot import allocated buffer");
|
||||
return;
|
||||
}
|
||||
struct wl_resource *reply = wl_resource_create(client, &android_wlegl_server_buffer_handle_interface,
|
||||
wl_resource_get_version(resource), id);
|
||||
if (!reply) {
|
||||
wl_resource_destroy(buffer); AHardwareBuffer_release(hardware);
|
||||
wl_client_post_no_memory(client); return;
|
||||
}
|
||||
struct wl_array ints = {.size = (size_t)handle->num_ints * sizeof(int32_t),
|
||||
.alloc = 0, .data = (void *)(handle->data + handle->num_fds)};
|
||||
android_wlegl_server_buffer_handle_send_buffer_ints(reply, &ints);
|
||||
for (int i = 0; i < handle->num_fds; i++)
|
||||
android_wlegl_server_buffer_handle_send_buffer_fd(reply, handle->data[i]);
|
||||
/* No linear_layout event: Android's opaque allocation need not be linear. */
|
||||
android_wlegl_server_buffer_handle_send_buffer(reply, buffer, (int32_t)desc.format, (int32_t)desc.stride);
|
||||
wl_resource_destroy(reply);
|
||||
AHardwareBuffer_release(hardware);
|
||||
}
|
||||
|
||||
static const struct android_wlegl_interface wlegl_impl = {
|
||||
.create_handle = create_handle, .create_buffer = create_buffer,
|
||||
.get_server_buffer_handle = get_server_buffer,
|
||||
};
|
||||
|
||||
static void bind_android_wlegl(struct wl_client *client, void *data, uint32_t version, uint32_t id) {
|
||||
struct wl_resource *resource = wl_resource_create(client, &android_wlegl_interface,
|
||||
version < 3 ? version : 3, id);
|
||||
if (!resource) { wl_client_post_no_memory(client); return; }
|
||||
wl_resource_set_implementation(resource, &wlegl_impl, NULL, NULL);
|
||||
}
|
||||
|
||||
void droiddeck_android_wlegl_init(struct wl_display *display) {
|
||||
if (!vkp_android_buffer_supported()) return;
|
||||
void *library = dlopen("libnativewindow.so", RTLD_NOW | RTLD_LOCAL);
|
||||
if (!library) return;
|
||||
import_handle = dlsym(library, "AHardwareBuffer_createFromHandle");
|
||||
native_handle = dlsym(library, "AHardwareBuffer_getNativeHandle");
|
||||
if (!import_handle || !native_handle) { dlclose(library); return; }
|
||||
/* Keep the platform entry points valid for the compositor's lifetime. */
|
||||
if (wl_global_create(display, &android_wlegl_interface, 3, NULL, bind_android_wlegl))
|
||||
droiddeck_log("display", "android_wlegl v3: Android buffer import available");
|
||||
}
|
||||
@@ -12,10 +12,12 @@ import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.runtime.mutableIntStateOf
|
||||
import com.droiddeck.launcher.gpu.DriverBundle
|
||||
import com.droiddeck.launcher.core.DeviceSupport
|
||||
import com.droiddeck.launcher.gpu.DriverPairs
|
||||
import com.droiddeck.launcher.gpu.GpuInfo
|
||||
import com.droiddeck.launcher.gpu.LinuxVulkanDriver
|
||||
import com.droiddeck.launcher.gpu.LinuxVulkanDriverManager
|
||||
import com.droiddeck.launcher.gpu.SystemVulkanDriver
|
||||
import com.droiddeck.launcher.gpu.TurnipDriver
|
||||
import com.droiddeck.launcher.gpu.TurnipReleases
|
||||
import com.droiddeck.launcher.session.SessionService
|
||||
@@ -44,7 +46,8 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
|
||||
/** Asset name -> download percent, while it downloads. */
|
||||
private val releaseProgress = HashMap<String, Int>()
|
||||
var linuxSelected by mutableStateOf("")
|
||||
val gpu: GpuInfo = GpuInfo.detect()
|
||||
var gpu: GpuInfo = GpuInfo.detect()
|
||||
private set
|
||||
// Read in refreshDrivers/ensureAuto: the activity has no context yet while its fields are made.
|
||||
var mode by mutableStateOf(SessionPrefs.GPU_DRIVERS_AUTO)
|
||||
var pairRows by mutableStateOf<List<PairRow>>(emptyList())
|
||||
@@ -58,13 +61,14 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
|
||||
private var autoCheckedThisProcess = false
|
||||
|
||||
fun state() = GpuDriversState(
|
||||
gpuName = gpu.displayName(activity), gpuFamily = gpu.family.label(activity), soc = gpu.soc, supportText = gpu.supportText(activity),
|
||||
gpuName = gpu.displayName(activity), gpuFamily = if (gpu.name.contains("Xclipse", ignoreCase = true)) gpu.family.label(gpu.name) else gpu.family.label(activity), soc = gpu.soc, supportText = gpu.supportText(activity),
|
||||
supported = gpu.support == GpuInfo.Support.TESTED, unsupported = gpu.support == GpuInfo.Support.UNSUPPORTED,
|
||||
auto = mode == SessionPrefs.GPU_DRIVERS_AUTO, pairs = pairRows, busy = pairBusy, percent = pairPercent,
|
||||
autoStatus = autoStatus, releaseStatus = releaseStatus.ifEmpty { activity.getString(R.string.drivers_not_checked) }, checking = releaseChecking,
|
||||
linuxRows = linuxRows, linuxSelected = linuxSelected, androidRows = androidRows, androidSelected = androidSelected,
|
||||
linuxDownloads = linuxDownloads, androidDownloads = androidDownloads, canRestoreBundled = canRestoreBundled,
|
||||
activeBundle = activeBundle,
|
||||
activeBundle = activeBundle, powerVr = gpu.family == GpuInfo.Family.POWERVR,
|
||||
systemPowerVr = SystemVulkanDriver.usesDefault(linuxSelected),
|
||||
)
|
||||
var androidRows by mutableStateOf<List<DriverRow>>(emptyList())
|
||||
var androidSelected by mutableStateOf("")
|
||||
@@ -77,7 +81,7 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
|
||||
DriverRow(id, it.label, activity.getString(if (linux) R.string.drivers_bundle_sets_display else R.string.drivers_bundle_sets_runtime), true, DriverRow.BUNDLE)
|
||||
}
|
||||
linuxRows = LinuxVulkanDriver.optionValues(activity).map { id ->
|
||||
if (id.isEmpty()) DriverRow("", activity.getString(R.string.gpu_runtime_default), activity.getString(R.string.drivers_runtime_builtin), false)
|
||||
if (id.isEmpty()) DriverRow("", activity.getString(if (gpu.family == GpuInfo.Family.POWERVR) R.string.gpu_system_powervr else R.string.gpu_runtime_default), activity.getString(R.string.drivers_runtime_builtin), false)
|
||||
else bundleRow(id, linux = true) ?: DriverRow(
|
||||
id, lm.getDriverName(id),
|
||||
listOfNotNull(
|
||||
@@ -110,6 +114,7 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
|
||||
/** One line for the settings row that opens this: "Auto · WinNative · Balanced". */
|
||||
fun summary(): String {
|
||||
val active = pairRows.firstOrNull { it.active }?.name ?: activeBundle
|
||||
?: if (SystemVulkanDriver.usesDefault(linuxSelected) && androidSelected == TurnipDriver.AUTO) activity.getString(R.string.gpu_system_powervr) else null
|
||||
val label = activity.getString(if (mode == SessionPrefs.GPU_DRIVERS_AUTO) R.string.common_auto else R.string.drivers_manual)
|
||||
return active?.let { activity.getString(R.string.drivers_summary, label, it) } ?: label
|
||||
}
|
||||
@@ -130,8 +135,10 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
|
||||
detail = if (!p.complete) activity.getString(R.string.drivers_half_published) else activity.getString(R.string.drivers_pair_size, mb),
|
||||
recommended = p.key == recommended, suits = p.suits(gpu), complete = p.complete,
|
||||
installed = displayId != null && linuxId != null,
|
||||
active = displayId != null && linuxId != null &&
|
||||
SessionPrefs.androidDriver(activity) == displayId && SessionPrefs.linuxDriver(activity) == linuxId,
|
||||
active = displayId != null && linuxId != null && SessionPrefs.linuxDriver(activity) == linuxId &&
|
||||
(SessionPrefs.androidDriver(activity) == displayId ||
|
||||
// A Mali pair under Auto: the display is the phone's own driver.
|
||||
(gpu.family.mali && DriverPairs.isNonAdreno(p.key) && SessionPrefs.androidDriver(activity) == TurnipDriver.AUTO)),
|
||||
)
|
||||
}.sortedByDescending { it.recommended }
|
||||
}
|
||||
@@ -152,8 +159,47 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
|
||||
fun ensureAuto(force: Boolean) {
|
||||
mode = SessionPrefs.gpuDriverMode(activity)
|
||||
if (mode != SessionPrefs.GPU_DRIVERS_AUTO || pairBusy != null || releaseChecking) return
|
||||
if (gpu.family == GpuInfo.Family.POWERVR && !SystemVulkanDriver.isXclipse()) {
|
||||
// Auto owns both choices. Manual imports remain available when Manual is selected.
|
||||
SessionPrefs.ensurePowerVrAutoDrivers(activity)
|
||||
autoStatus = activity.getString(R.string.drivers_powervr_builtin)
|
||||
refreshDrivers()
|
||||
return
|
||||
}
|
||||
// A Mali pair set by an earlier build put its PanVK Android half on the display, which fails
|
||||
// on Mali gralloc. Under Auto the display is the phone's own driver (Android's loader).
|
||||
if (gpu.family.mali) {
|
||||
val display = SessionPrefs.androidDriver(activity)
|
||||
if (display.isNotEmpty() && DriverPairs.isNonAdreno(DriverBundle.containing(activity, display, false)?.id)) {
|
||||
SessionPrefs.setAndroidDriver(activity, TurnipDriver.AUTO)
|
||||
Log.i(TAG, "auto: Mali display back on the phone's own driver (was $display)")
|
||||
}
|
||||
}
|
||||
if (!force && autoCheckedThisProcess) return
|
||||
autoCheckedThisProcess = true
|
||||
if (gpu.family.mali && DriverPairs.recommendedKey(gpu, emptyList()) == null &&
|
||||
com.droiddeck.launcher.gpu.VulkanInfo.cachedOrNull() == null) {
|
||||
// No name for this Mali yet: ask its own Vulkan driver (it creates an instance, so off
|
||||
// the main thread), then decide again with the name it gives.
|
||||
autoStatus = activity.getString(R.string.drivers_checking_latest)
|
||||
Thread({
|
||||
com.droiddeck.launcher.gpu.VulkanInfo.query()
|
||||
ui.post {
|
||||
gpu = GpuInfo.detect()
|
||||
Log.i(TAG, "auto: Mali named by its driver: ${gpu.name} -> ${gpu.family}")
|
||||
autoCheckedThisProcess = false
|
||||
ensureAuto(force)
|
||||
}
|
||||
}, "gpu-name").start()
|
||||
return
|
||||
}
|
||||
Log.i(TAG, "auto: ${gpu.name} (${gpu.family}) -> " + (DriverPairs.recommendedKey(gpu, emptyList()) ?: "no pair"))
|
||||
if (gpu.family.mali && DriverPairs.recommendedKey(gpu, emptyList()) == null) {
|
||||
useMaliBridge()
|
||||
autoStatus = activity.getString(R.string.drivers_mali_bridge_auto)
|
||||
refreshDrivers()
|
||||
return
|
||||
}
|
||||
if (DriverPairs.recommendedKey(gpu, emptyList()) == null) {
|
||||
autoStatus = activity.getString(R.string.drivers_none_to_set, gpu.supportText(activity).lowercase())
|
||||
return
|
||||
@@ -162,8 +208,12 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
|
||||
autoStatus = activity.getString(R.string.drivers_checking_latest)
|
||||
Thread({
|
||||
val cached = TurnipReleases.cached(activity)
|
||||
val stale = cached == null || System.currentTimeMillis() - cached.checkedAt > 24 * 3_600_000L ||
|
||||
cached.assets.none { it.pair.isNotEmpty() }
|
||||
// The open non-Adreno drivers are rebuilt in place while they are tested: an hour.
|
||||
val maxAge = if (DeviceSupport.adreno()) 24 * 3_600_000L else 3_600_000L
|
||||
val stale = cached == null || System.currentTimeMillis() - cached.checkedAt > maxAge ||
|
||||
cached.assets.none { it.pair.isNotEmpty() } ||
|
||||
// A list checked before this device's open drivers were offered has none of them.
|
||||
(!DeviceSupport.adreno() && cached.assets.none { DriverPairs.isNonAdreno(it.pair) })
|
||||
val problem = if (force || stale) runCatching { TurnipReleases.refresh(activity) }.exceptionOrNull()?.message else null
|
||||
ui.post {
|
||||
releaseChecking = false
|
||||
@@ -176,6 +226,18 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
|
||||
when {
|
||||
row?.active == true -> autoStatus = problem?.let { activity.getString(R.string.drivers_up_to_date_check_failed, it) }
|
||||
?: activity.getString(R.string.upd_current_status)
|
||||
gpu.family == GpuInfo.Family.POWERVR && (pair == null || !pair.complete) -> {
|
||||
// RADV is not published right now: the Xclipse falls back to the system route.
|
||||
SessionPrefs.ensurePowerVrAutoDrivers(activity)
|
||||
autoStatus = activity.getString(R.string.drivers_powervr_builtin)
|
||||
refreshDrivers()
|
||||
}
|
||||
gpu.family.mali && (pair == null || !pair.complete) -> {
|
||||
// No open driver for this Mali published yet: draw through the bridge.
|
||||
useMaliBridge()
|
||||
autoStatus = activity.getString(R.string.drivers_mali_bridge_fallback, key?.let { DriverPairs.nonAdrenoName(it) } ?: gpu.name)
|
||||
refreshDrivers()
|
||||
}
|
||||
pair == null || !pair.complete ->
|
||||
autoStatus = problem?.let { activity.getString(R.string.upd_couldnt_check, it) } ?: activity.getString(R.string.drivers_recommended_unpublished)
|
||||
else -> installPair(pair, auto = true)
|
||||
@@ -184,6 +246,18 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
|
||||
}, "gpu-driver-auto").start()
|
||||
}
|
||||
|
||||
/**
|
||||
* Auto on a Mali without an open driver pair: the Vulkan bridge draws instead, on the phone's
|
||||
* own driver, so a pair Auto set earlier is unset rather than left half-working.
|
||||
*/
|
||||
private fun useMaliBridge() {
|
||||
if (DeviceSupport.openDriverActive(activity)) {
|
||||
SessionPrefs.setAndroidDriver(activity, TurnipDriver.AUTO)
|
||||
SessionPrefs.setLinuxDriver(activity, "")
|
||||
}
|
||||
SessionPrefs.setVkBridge(activity, true)
|
||||
}
|
||||
|
||||
/** Manual: install (if need be) and set both halves of a pair. */
|
||||
fun selectPair(key: String) {
|
||||
if (pairBusy != null) return
|
||||
@@ -216,10 +290,19 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
|
||||
ui.post {
|
||||
pairBusy = null
|
||||
pairPercent = -1
|
||||
result.onSuccess { (displayId, linuxId) ->
|
||||
result.onSuccess { (pairDisplayId, linuxId) ->
|
||||
// A Mali pair under Auto: the compositor draws on the phone's own Mali driver
|
||||
// (dma-buf, modifiers and AHB all work there) and the guest runs the pair's
|
||||
// PanVK. Its Android half stays installed for a manual pick.
|
||||
// The same when the pair is picked by hand: a PanVK Android half on the display
|
||||
// stalls Mali gralloc ("Waiting for Steam's first frame"); it stays a manual pick
|
||||
// under "Runtime and display drivers separately".
|
||||
val displayId = if (gpu.family.mali && DriverPairs.isNonAdreno(pair.key)) TurnipDriver.AUTO else pairDisplayId
|
||||
val displayChanged = SessionPrefs.androidDriver(activity) != displayId
|
||||
SessionPrefs.setAndroidDriver(activity, displayId)
|
||||
SessionPrefs.setLinuxDriver(activity, linuxId)
|
||||
// The Mali bridge switch is the user's and is left as it is: when it is on, the
|
||||
// bridge wins for the session (DeviceSupport.vkBridge) and the pair waits.
|
||||
val restart = displayChanged && CompositorHost.isStarted
|
||||
if (auto) {
|
||||
val previous = SessionPrefs.gpuAutoInstalled(activity)
|
||||
|
||||
@@ -146,6 +146,9 @@ class MainActivity : ComponentActivity() {
|
||||
private var gameCores by mutableStateOf<Set<Int>>(emptySet())
|
||||
private var tuSysmem by mutableStateOf(false)
|
||||
private var zinkLazy by mutableStateOf(false)
|
||||
private var vkBridge by mutableStateOf(false)
|
||||
private var venus by mutableStateOf(false)
|
||||
private val adrenoGpu by lazy { com.droiddeck.launcher.core.DeviceSupport.adreno() }
|
||||
private var noXalia by mutableStateOf(true)
|
||||
private var fastSync by mutableStateOf(false)
|
||||
private var syncFallback by mutableStateOf(true)
|
||||
@@ -366,6 +369,9 @@ class MainActivity : ComponentActivity() {
|
||||
private var runningLabel by mutableStateOf<String?>(null)
|
||||
private var logsEnabled by mutableStateOf(true)
|
||||
private var agentCommands by mutableStateOf(false)
|
||||
private var graphicsLogs by mutableStateOf(false)
|
||||
private var steamGpuDrawing by mutableStateOf(false)
|
||||
private var bridgeFellBack by mutableStateOf(false)
|
||||
private var showRoms by mutableStateOf(false)
|
||||
private var homeAppSelected by mutableStateOf(false)
|
||||
private var homeScreenEnabled by mutableStateOf(false)
|
||||
@@ -554,13 +560,14 @@ class MainActivity : ComponentActivity() {
|
||||
FrontEndScreen(
|
||||
FrontEndState(
|
||||
installed = installed, ready = ready, available = available?.version, removalPending = removalPending, runtimeActionsBlocked = runtimeChangesBlocked(),
|
||||
vkBridge = vkBridge, venus = venus, adreno = adrenoGpu,
|
||||
shortcutPicker = shortcutPicker,
|
||||
shortcutLibraryScanning = shortcutLibraryScanning,
|
||||
gameSyncFolder = gameSyncFolder,
|
||||
busy = busy, stage = stage, percent = percent,
|
||||
desktopInstalled = desktopInstalled, desktopPresent = desktopPresent,
|
||||
offlineAccount = offlineAccount, offline = offline,
|
||||
frameGenLabel = frameGenLabel, romsDir = romsDir, logsEnabled = logsEnabled, agentCommands = agentCommands,
|
||||
frameGenLabel = frameGenLabel, romsDir = romsDir, logsEnabled = logsEnabled, agentCommands = agentCommands, graphicsLogs = graphicsLogs, steamGpuDrawing = steamGpuDrawing, bridgeFellBack = bridgeFellBack,
|
||||
steamGames = steamGames, emulators = emulatorList, running = runningLabel,
|
||||
frameGen = FrameGen.mode(this),
|
||||
lossless = lossless,
|
||||
@@ -681,6 +688,8 @@ class MainActivity : ComponentActivity() {
|
||||
onInstallPackage = { id -> installPackage(id) },
|
||||
onRemovePackage = { id -> removePackage(id) },
|
||||
onRuntime = { onRuntimeButton() },
|
||||
onVkBridge = { on -> SessionPrefs.setVkBridge(this, on); vkBridge = on },
|
||||
onVenus = { on -> SessionPrefs.setVenus(this, on); venus = on },
|
||||
onFrameGenPick = { mode ->
|
||||
FrameGen.set(this, mode)
|
||||
frameGenLabel = FrameGen.label(this)
|
||||
@@ -705,6 +714,14 @@ class MainActivity : ComponentActivity() {
|
||||
SessionPrefs.setLogsEnabled(this, !SessionPrefs.logsEnabled(this))
|
||||
logsEnabled = SessionPrefs.logsEnabled(this)
|
||||
},
|
||||
onSteamGpuDrawing = {
|
||||
SessionPrefs.setSteamGpuCompositing(this, !SessionPrefs.steamGpuCompositing(this))
|
||||
steamGpuDrawing = SessionPrefs.steamGpuCompositing(this)
|
||||
},
|
||||
onGraphicsLogs = {
|
||||
SessionPrefs.setDetailedGraphicsLogs(this, !SessionPrefs.detailedGraphicsLogs(this))
|
||||
graphicsLogs = SessionPrefs.detailedGraphicsLogs(this)
|
||||
},
|
||||
onAgentCommands = {
|
||||
com.droiddeck.launcher.agent.AgentAccess.setCommandsEnabled(this, !com.droiddeck.launcher.agent.AgentAccess.commandsEnabled(this))
|
||||
agentCommands = com.droiddeck.launcher.agent.AgentAccess.commandsEnabled(this)
|
||||
@@ -1575,6 +1592,8 @@ class MainActivity : ComponentActivity() {
|
||||
gameCores = CpuCores.parse(SessionPrefs.gameCpus(this)).ifEmpty { CpuCores.all.toSet() }
|
||||
tuSysmem = SessionPrefs.tuSysmem(this)
|
||||
zinkLazy = SessionPrefs.zinkLazy(this)
|
||||
vkBridge = SessionPrefs.vkBridge(this)
|
||||
venus = SessionPrefs.venus(this)
|
||||
noXalia = SessionPrefs.noXalia(this)
|
||||
fastSync = SessionPrefs.fastSync(this)
|
||||
syncFallback = SessionPrefs.syncFallback(this)
|
||||
@@ -1601,6 +1620,9 @@ class MainActivity : ComponentActivity() {
|
||||
romsDir = SessionPrefs.romsDir(this).takeIf { it.isNotEmpty() }
|
||||
logsEnabled = SessionPrefs.logsEnabled(this)
|
||||
agentCommands = com.droiddeck.launcher.agent.AgentAccess.commandsEnabled(this)
|
||||
graphicsLogs = SessionPrefs.detailedGraphicsLogs(this)
|
||||
steamGpuDrawing = SessionPrefs.steamGpuCompositing(this)
|
||||
bridgeFellBack = SessionPrefs.bridgeFellBack(this)
|
||||
runningLabel = if (SessionState.running) when (SessionState.mode) {
|
||||
SessionService.MODE_DESKTOP -> getString(R.string.rail_desktop)
|
||||
SessionService.MODE_RUN -> Library.nameForProgram(SessionState.program)
|
||||
@@ -1677,7 +1699,7 @@ class MainActivity : ComponentActivity() {
|
||||
// The runtime draws with Turnip, an Adreno driver: on Mali, Xclipse or PowerVR the
|
||||
// compositor gets no usable Vulkan device and a session is sound over a black screen.
|
||||
// Said before the download, not after it; the user may still go ahead.
|
||||
if (installed == null && !com.droiddeck.launcher.core.DeviceSupport.adreno()) { showNonAdreno = release; return }
|
||||
if (installed == null && !com.droiddeck.launcher.core.DeviceSupport.canDraw(this)) { showNonAdreno = release; return }
|
||||
install(release)
|
||||
}
|
||||
|
||||
@@ -1689,7 +1711,7 @@ class MainActivity : ComponentActivity() {
|
||||
showPhantomGate = true
|
||||
return false
|
||||
}
|
||||
val warn = installed == null && !com.droiddeck.launcher.core.DeviceSupport.adreno()
|
||||
val warn = installed == null && !com.droiddeck.launcher.core.DeviceSupport.canDraw(this)
|
||||
if (warn && available != null) { showNonAdreno = available; return false }
|
||||
startActivity(intent)
|
||||
return true
|
||||
|
||||
@@ -588,6 +588,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
)
|
||||
SessionDrawer(drawerOpen, drawerPage, drawerControllerActive, onPageChange = { drawerPage = it }, a = DrawerActions(
|
||||
steam = SessionState.mode == SessionService.MODE_STEAM,
|
||||
systemPowerVr = com.droiddeck.launcher.gpu.SystemVulkanDriver.usesDefault(
|
||||
SessionPrefs.linuxDriver(this@SessionActivity)),
|
||||
title = if (SessionState.mode == SessionService.MODE_RUN)
|
||||
com.droiddeck.launcher.frontend.Library.nameForProgram(SessionState.program) ?: getString(R.string.session_title_game) else null,
|
||||
isHomeApp = isHomeApp,
|
||||
@@ -1288,8 +1290,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
// the evdev codes we inject.
|
||||
FileUtils.copyAsset(this, "wayland/keymap.xkb", File(runtimeDir, "keymap.xkb"))
|
||||
|
||||
// Turnip, not the system Adreno driver: importing the dma-bufs gamescope commits needs
|
||||
// VK_EXT_image_drm_format_modifier, which the system driver does not implement.
|
||||
// Adreno imports dma-bufs with Turnip. PowerVR uses its system Vulkan driver
|
||||
// to import the Android hardware buffers supplied by the runtime bridge.
|
||||
val turnip = TurnipDriver(this)
|
||||
val driverId = if (CompositorHost.isStarted) null else turnip.install()
|
||||
|
||||
|
||||
@@ -183,22 +183,46 @@ public class PulseAudioComponent extends SessionPart {
|
||||
*/
|
||||
private void ensureClientSink(java.io.PrintWriter out) {
|
||||
try {
|
||||
long deadline = System.currentTimeMillis() + 15000L;
|
||||
// Nothing that may block (a sink whose AAudio open hangs: a Galaxy S24 FE (US) hung the
|
||||
// daemon's start-up loading one from default.pa) is loaded by the daemon itself; the
|
||||
// fallbacks are loaded here, after it is up, each pactl call bounded by its timeout.
|
||||
long started = System.currentTimeMillis();
|
||||
long deadline = started + 30000L;
|
||||
String sinks = null;
|
||||
boolean socketSeen = false;
|
||||
while (System.currentTimeMillis() < deadline && pid > 1) {
|
||||
if (socket().exists() && (sinks = pactl("list", "short", "sinks")) != null) break;
|
||||
socketSeen |= socket().exists();
|
||||
if (socketSeen && (sinks = pactl("list", "short", "sinks")) != null) break;
|
||||
try { Thread.sleep(250L); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return; }
|
||||
}
|
||||
note(out, "client sink: daemon " + (sinks != null ? "answered" : "did not answer") + " after "
|
||||
+ (System.currentTimeMillis() - started) + " ms (socket " + (socketSeen ? "present" : "never appeared") + ", pactl "
|
||||
+ (new File(workingDir, "pactl").isFile() ? "present" : "MISSING") + ", daemon pid " + pid + ")");
|
||||
String line;
|
||||
if (sinks == null) {
|
||||
line = "== client sink: the daemon did not answer in 15 s; no fallback attempted";
|
||||
line = "== client sink: the daemon did not answer in 30 s; no fallback attempted";
|
||||
} else if (sinks.contains("\tDirectAudio\t") || sinks.startsWith("DirectAudio\t") || sinks.contains("\tDirectAudio\n") || sinks.matches("(?s).*\\bDirectAudio\\b.*")) {
|
||||
line = "== client sink: DirectAudio (module-directaudio-native-sink)";
|
||||
} else {
|
||||
boolean loaded = pactl("load-module", "module-aaudio-sink", "sink_name=AAudioSink", "performance_mode=1", "adaptive=1", "volume=1.0") != null
|
||||
&& pactl("set-default-sink", "AAudioSink") != null;
|
||||
line = loaded ? "== client sink: DirectAudio did not come up; FALLBACK to the plain AAudio sink (AAudioSink)"
|
||||
: "== client sink: DirectAudio did not come up and the AAudio fallback failed too - no client sound";
|
||||
// AAudio can refuse the first open with AAUDIO_ERROR_DISCONNECTED while Android is
|
||||
// still switching the output route as the session starts (seen on a Galaxy S24 FE):
|
||||
// try DirectAudio again, then the plain sink, a few times over ten seconds.
|
||||
String loadedAs = null;
|
||||
for (int attempt = 1; attempt <= 5 && loadedAs == null && pid > 1; attempt++) {
|
||||
try { Thread.sleep(2000L); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return; }
|
||||
if (pactl("load-module", "module-directaudio-native-sink", "sink_name=DirectAudio", "performance_mode=1",
|
||||
"adaptive=1", "decay=0", "limiter=1", "watchdog=1", "volume=1.0") != null
|
||||
&& pactl("set-default-sink", "DirectAudio") != null) {
|
||||
loadedAs = "DirectAudio on attempt " + attempt;
|
||||
} else if (pactl("load-module", "module-aaudio-sink", "sink_name=AAudioSink",
|
||||
"performance_mode=" + (attempt == 1 ? "1" : "0"), "adaptive=1", "volume=1.0") != null
|
||||
&& pactl("set-default-sink", "AAudioSink") != null) {
|
||||
loadedAs = "the plain AAudio sink (AAudioSink) on attempt " + attempt;
|
||||
}
|
||||
}
|
||||
line = loadedAs != null ? "== client sink: DirectAudio did not come up at start; retried and got " + loadedAs
|
||||
: "== client sink: DirectAudio did not come up and the AAudio fallback failed too after 5 retries - no client sound."
|
||||
+ " If audio.log shows AAUDIO_ERROR_DISCONNECTED, Android refused the audio output: rebooting the phone usually fixes this";
|
||||
Log.w(TAG, line);
|
||||
}
|
||||
Log.i(TAG, line);
|
||||
@@ -208,6 +232,13 @@ public class PulseAudioComponent extends SessionPart {
|
||||
}
|
||||
}
|
||||
|
||||
/** A timestamped line in the session's audio log. */
|
||||
private void note(java.io.PrintWriter out, String what) {
|
||||
String line = "== " + new java.text.SimpleDateFormat("HH:mm:ss.SSS", java.util.Locale.US).format(new java.util.Date()) + " " + what;
|
||||
Log.i(TAG, line);
|
||||
if (out != null) synchronized (out) { out.println(line); out.flush(); }
|
||||
}
|
||||
|
||||
/** Runs pactl against this daemon; its stdout, or null when it failed or timed out. */
|
||||
private String pactl(String... args) {
|
||||
File pactl = new File(workingDir, "pactl");
|
||||
|
||||
@@ -6,6 +6,8 @@ import android.os.Build
|
||||
import android.os.Environment
|
||||
import android.os.StatFs
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.gpu.DeviceInfo
|
||||
import com.droiddeck.launcher.gpu.SystemVulkanDriver
|
||||
import com.droiddeck.launcher.gpu.LinuxVulkanDriver
|
||||
import com.droiddeck.launcher.gpu.LinuxVulkanDriverManager
|
||||
import com.droiddeck.launcher.gpu.TurnipDriver
|
||||
@@ -59,6 +61,7 @@ object DeviceReport {
|
||||
runCatching {
|
||||
val info = context.packageManager.getPackageInfo(context.packageName, 0)
|
||||
k("Version", "${info.versionName} (${info.longVersionCode})")
|
||||
k("App build", "${com.droiddeck.launcher.BuildConfig.BUILD_LABEL} (source ${com.droiddeck.launcher.BuildConfig.SOURCE_COMMIT})")
|
||||
}
|
||||
k("Package", context.packageName)
|
||||
k("targetSdk", context.applicationInfo.targetSdkVersion)
|
||||
@@ -103,7 +106,11 @@ object DeviceReport {
|
||||
h("GPU")
|
||||
k("KGSL gpu_model", readSys("/sys/class/kgsl/kgsl-3d0/gpu_model"))
|
||||
k("KGSL chip id", readSys("/sys/class/kgsl/kgsl-3d0/gpu_chipid"))
|
||||
k("System Vulkan ICD", if (File("/vendor/lib64/hw/vulkan.adreno.so").exists()) "/vendor/lib64/hw/vulkan.adreno.so" else "not at the usual path")
|
||||
k("System Vulkan ICD", when {
|
||||
SystemVulkanDriver.isPowerVr() -> SystemVulkanDriver.hal()
|
||||
File("/vendor/lib64/hw/vulkan.adreno.so").exists() -> "/vendor/lib64/hw/vulkan.adreno.so"
|
||||
else -> "not at the usual path"
|
||||
})
|
||||
|
||||
h("Display")
|
||||
k("Session output", SessionState.outputSize?.let { "${it.first}x${it.second}" })
|
||||
@@ -118,25 +125,31 @@ object DeviceReport {
|
||||
|
||||
h("Drivers")
|
||||
val gpu = com.droiddeck.launcher.gpu.GpuInfo.detect()
|
||||
k("GPU", "${gpu.name} · ${gpu.family.label} · ${gpu.supportText}" + if (gpu.oneUi8Gen2) " · One UI 8 Gen 2" else "")
|
||||
k("GPU", "${gpu.name} · ${gpu.family.label(gpu.name)} · ${gpu.supportText}" + if (gpu.oneUi8Gen2) " · One UI 8 Gen 2" else "")
|
||||
k("Driver mode", SessionPrefs.gpuDriverMode(context) +
|
||||
(com.droiddeck.launcher.gpu.DriverPairs.recommendedKey(gpu, com.droiddeck.launcher.gpu.DriverPairs.from(
|
||||
com.droiddeck.launcher.gpu.TurnipReleases.cached(context)))?.let { " (recommended pair: $it)" } ?: ""))
|
||||
val turnip = TurnipDriver(context)
|
||||
val androidChoice = SessionPrefs.androidDriver(context)
|
||||
k("Display driver (chosen)", if (androidChoice.isEmpty()) "Auto -> ${turnip.autoId()}" else androidChoice)
|
||||
k(" name / version", "${turnip.displayName(if (androidChoice.isEmpty()) turnip.autoId() else androidChoice)} ${turnip.driverVersion(if (androidChoice.isEmpty()) turnip.autoId() else androidChoice)}".trim())
|
||||
val displayId = androidChoice.ifEmpty { turnip.autoId() }
|
||||
val displayLabel = if (displayId == "system") DeviceInfo.builtinDriverLabel(SystemVulkanDriver.isPowerVr(), runtime = false)
|
||||
else "${turnip.displayName(displayId)} ${turnip.driverVersion(displayId)}".trim()
|
||||
k("Display driver (chosen)", if (androidChoice.isEmpty()) "Auto -> $displayLabel" else androidChoice)
|
||||
k(" name / version", displayLabel)
|
||||
k(" imported available", turnip.enumerateImported().ifEmpty { listOf("none") }.joinToString(", "))
|
||||
val lm = LinuxVulkanDriverManager(context)
|
||||
run {
|
||||
val id = SessionPrefs.linuxDriver(context)
|
||||
val label = if (id.isEmpty()) "runtime default (the Turnip built into the runtime)"
|
||||
val label = if (id.isEmpty()) DeviceInfo.builtinDriverLabel(SystemVulkanDriver.isPowerVr(), runtime = true)
|
||||
else "${lm.getDriverName(id)} ${lm.getDriverVersion(id)}".trim() +
|
||||
lm.getMinGlibc(id).let { if (it.isEmpty()) "" else " (glibc $it+)" } +
|
||||
if (lm.isInstalled(id)) "" else " [MISSING - falls back to the runtime's own]"
|
||||
if (lm.isInstalled(id)) "" else if (SystemVulkanDriver.isPowerVr()) " [MISSING - select an installed driver or Auto]"
|
||||
else " [MISSING - falls back to the runtime's own]"
|
||||
k("Linux driver", label)
|
||||
}
|
||||
k("Runtime's own ICD", LinuxRuntime.vulkanIcd(context)?.path)
|
||||
k("Mali (Venus)", if (com.droiddeck.launcher.session.VenusComponent.wanted(context)) "in use"
|
||||
else if (com.droiddeck.launcher.session.VenusComponent.available(context)) "available, off" else "not in this build")
|
||||
|
||||
h("Runtime")
|
||||
k("Installed version", LinuxRuntimeInstaller.installedVersion(context))
|
||||
|
||||
@@ -3,21 +3,61 @@ package com.droiddeck.launcher.core
|
||||
import android.content.Context
|
||||
import android.os.Build
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.gpu.SystemVulkanDriver
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* Whether this device can draw a Linux session at all.
|
||||
*
|
||||
* The runtime draws with Turnip, an Adreno driver. On Mali, Xclipse and PowerVR the compositor
|
||||
* gets no usable Vulkan device and a session comes up as sound over a black screen - a failure
|
||||
* with nothing in it to read. The app cannot fix that, so it says so before the download rather
|
||||
* than after it. Adreno is recognised by what only Qualcomm's stack has: the KGSL node, or the
|
||||
* vendor's own Vulkan driver at its usual path.
|
||||
*/
|
||||
/** Whether this device has a graphics backend the runtime can use. Adreno uses Turnip;
|
||||
* PowerVR uses its vendor Vulkan driver through the bundled runtime bridge. Other GPU families
|
||||
* still need a supported backend before a session can display frames. */
|
||||
object DeviceSupport {
|
||||
fun adreno(): Boolean =
|
||||
File("/sys/class/kgsl/kgsl-3d0").exists() || File("/vendor/lib64/hw/vulkan.adreno.so").exists()
|
||||
|
||||
fun graphicsAvailable(): Boolean = graphicsAvailable(adreno(), SystemVulkanDriver.isAvailable())
|
||||
|
||||
internal fun graphicsAvailable(adreno: Boolean, powerVrReady: Boolean): Boolean = adreno || powerVrReady
|
||||
|
||||
/**
|
||||
* Whether the Linux side draws through the Vulkan bridge (tools/vkbridge, PR #517): asked for in
|
||||
* Setup, and only on a GPU that is neither an Adreno nor one the system-Vulkan path (PowerVR,
|
||||
* Xclipse) already handles. An Adreno keeps Turnip whatever the setting says.
|
||||
*/
|
||||
fun vkBridge(context: Context): Boolean =
|
||||
bridgeUsable() && !com.droiddeck.launcher.session.VenusComponent.wanted(context) &&
|
||||
com.droiddeck.launcher.session.SessionPrefs.vkBridge(context)
|
||||
|
||||
/** Whether this phone can use the Mali bridge at all: a Mali (kbase) without a system-driver route. */
|
||||
/** A Mali GPU (its kbase device is there, or the GPU reports a Mali family). Never an Adreno. */
|
||||
fun mali(): Boolean = isMali
|
||||
|
||||
private val isMali by lazy {
|
||||
!adreno() && (File("/dev/mali0").exists() ||
|
||||
com.droiddeck.launcher.gpu.GpuInfo.detect().family.name.startsWith("MALI"))
|
||||
}
|
||||
|
||||
fun bridgeUsable(): Boolean = !adreno() && !SystemVulkanDriver.isAvailable() && File("/dev/mali0").exists()
|
||||
|
||||
/**
|
||||
* Whether an open non-Adreno driver pair (PanVK for Mali, RADV for Xclipse) is the one in use:
|
||||
* it and the bridge are alternatives, and the pair wins. Always false on an Adreno.
|
||||
*/
|
||||
fun openDriverActive(context: Context): Boolean {
|
||||
if (adreno()) return false
|
||||
if (com.droiddeck.launcher.session.VenusComponent.wanted(context)) return false
|
||||
// The Mali bridge switch, when on and usable, wins over a pair (the user's choice in Setup).
|
||||
if (bridgeUsable() && com.droiddeck.launcher.session.SessionPrefs.vkBridge(context)) return false
|
||||
// The runtime half is what counts: a Mali pair may run with the system driver as its display.
|
||||
val linux = com.droiddeck.launcher.session.SessionPrefs.linuxDriver(context).ifEmpty { return false }
|
||||
return com.droiddeck.launcher.gpu.DriverPairs.isNonAdreno(com.droiddeck.launcher.gpu.DriverBundle.containing(context, linux, true)?.id)
|
||||
}
|
||||
|
||||
/**
|
||||
* A session can draw: Adreno with Turnip, PowerVR/Xclipse on the system driver, an open
|
||||
* non-Adreno driver pair, or the bridge.
|
||||
*/
|
||||
fun canDraw(context: Context): Boolean = graphicsAvailable() || openDriverActive(context) || vkBridge(context) ||
|
||||
com.droiddeck.launcher.session.VenusComponent.wanted(context)
|
||||
|
||||
/** The chip as the device names it, for the card that explains the refusal. */
|
||||
fun gpuName(context: Context): String {
|
||||
val soc = if (Build.VERSION.SDK_INT >= 31) Build.SOC_MODEL.takeIf { it.isNotBlank() && it != Build.UNKNOWN } else null
|
||||
|
||||
@@ -21,6 +21,8 @@ object SteamRedists {
|
||||
"228988" to ("vcredist2019_dll" to "VC++ 2019"),
|
||||
"228989" to ("vcredist2022_dll" to "VC++ 2022"),
|
||||
"228990" to ("d3dx9" to "DirectX (June 2010)"),
|
||||
// OpenAL 2.0.7.0 (Hotline Miami lists it; without it HotlineGL.exe fails to load, c0000135).
|
||||
"229020" to ("oalinst_dll" to "OpenAL"),
|
||||
)
|
||||
private val BLOCK = Regex("\"SharedDepots\"\\s*\\{([^}]*)\\}", RegexOption.IGNORE_CASE)
|
||||
private val ENTRY = Regex("\"(\\d+)\"\\s+\"\\d+\"")
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
package com.droiddeck.launcher.gpu
|
||||
|
||||
import android.content.Context
|
||||
import android.os.Build
|
||||
import android.os.PowerManager
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.core.SessionPart
|
||||
import java.io.File
|
||||
import java.io.FileWriter
|
||||
import java.text.SimpleDateFormat
|
||||
import java.util.Date
|
||||
import java.util.Locale
|
||||
|
||||
/**
|
||||
* Clocks and thermal state through a Mali bridge session, into the session folder
|
||||
* (vkbridge-clocks.log), for telling the bridge's overhead apart from the phone holding the chip
|
||||
* back: Samsung's SSRM lowers the CPU policies' scaling_max_freq when the device warms, so a
|
||||
* policy whose max is below its cpuinfo_max_freq is being clamped (upstream issue #64).
|
||||
*
|
||||
* Every [PERIOD_MS]: each CPU policy as cur/max(hardware max) MHz, the GPU clock from the first
|
||||
* Mali/MediaTek source the app may read, and Android's thermal status and headroom. Which GPU
|
||||
* sources were readable is logged once at the start - SELinux refuses apps most of them, each
|
||||
* vendor differently, and this is how the next run finds out which.
|
||||
*/
|
||||
class ClockLogComponent(private val logFile: File) : SessionPart() {
|
||||
@Volatile private var running = false
|
||||
private var thread: Thread? = null
|
||||
|
||||
override fun start() {
|
||||
running = true
|
||||
thread = Thread({ run() }, "clock-log").apply { isDaemon = true; start() }
|
||||
}
|
||||
|
||||
override fun stop() {
|
||||
running = false
|
||||
thread?.interrupt()
|
||||
thread = null
|
||||
}
|
||||
|
||||
private fun run() {
|
||||
val policies = File("/sys/devices/system/cpu/cpufreq").listFiles { f -> f.name.startsWith("policy") }
|
||||
?.sortedBy { it.name.removePrefix("policy").toIntOrNull() ?: 0 } ?: emptyList()
|
||||
val gpuCandidates = gpuSources()
|
||||
// The /proc status files hold several numbers: listed for whether they read, not taken as the clock.
|
||||
val gpu = gpuCandidates.firstOrNull { !it.startsWith("/proc/") && firstNumber(it) != null }
|
||||
val power = app().getSystemService(Context.POWER_SERVICE) as? PowerManager
|
||||
val time = SimpleDateFormat("HH:mm:ss", Locale.US)
|
||||
try {
|
||||
FileWriter(logFile, true).use { w ->
|
||||
w.write("== clocks: ${Build.MANUFACTURER} ${Build.MODEL} (${Build.HARDWARE}), every ${PERIOD_MS / 1000}s\n")
|
||||
w.write("cpu policies: ${policies.joinToString { p -> p.name + " " + (File(p, "related_cpus").readTextOrNull()?.trim() ?: "?") }}\n")
|
||||
for (source in gpuCandidates) {
|
||||
val f = File(source)
|
||||
val state = when {
|
||||
!f.exists() -> continue
|
||||
firstNumber(source) != null -> "readable"
|
||||
else -> "refused"
|
||||
}
|
||||
w.write("gpu source $source: $state\n")
|
||||
}
|
||||
w.write("gpu clock from: ${gpu ?: "nothing readable"}\n")
|
||||
w.flush()
|
||||
while (running && logFile.length() < MAX_BYTES) {
|
||||
val line = StringBuilder(time.format(Date()))
|
||||
for (p in policies) {
|
||||
val cur = firstNumber(File(p, "scaling_cur_freq").path)
|
||||
val max = firstNumber(File(p, "scaling_max_freq").path)
|
||||
val hw = firstNumber(File(p, "cpuinfo_max_freq").path)
|
||||
line.append(" ${p.name.removePrefix("policy").let { "p$it" }} ${mhz(cur)}/${mhz(max)}")
|
||||
if (hw != null && max != null && max < hw) line.append("(of ${mhz(hw)})")
|
||||
}
|
||||
gpu?.let { line.append(" | gpu ${mhz(firstNumber(it))} MHz") }
|
||||
if (power != null && Build.VERSION.SDK_INT >= 29) {
|
||||
line.append(" | thermal ${power.currentThermalStatus}")
|
||||
if (Build.VERSION.SDK_INT >= 30) {
|
||||
val h = power.getThermalHeadroom(10)
|
||||
if (!h.isNaN()) line.append(String.format(Locale.US, " headroom %.2f", h))
|
||||
}
|
||||
}
|
||||
w.write(line.append('\n').toString())
|
||||
w.flush()
|
||||
try { Thread.sleep(PERIOD_MS) } catch (e: InterruptedException) { break }
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "clock log stopped: $e")
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val TAG = "SessionService"
|
||||
private const val PERIOD_MS = 2000L
|
||||
private const val MAX_BYTES = 4L shl 20
|
||||
|
||||
/** Mali (Exynos, Tensor, MediaTek) and MediaTek GED clock files, plus any GPU devfreq node. */
|
||||
private fun gpuSources(): List<String> {
|
||||
val list = mutableListOf(
|
||||
"/sys/kernel/ged/hal/current_freqency", "/sys/kernel/ged/hal/current_frequency",
|
||||
"/proc/gpufreqv2/gpufreq_status", "/proc/gpufreq/gpufreq_var_dump",
|
||||
"/sys/kernel/gpu/gpu_clock", "/sys/class/misc/mali0/device/cur_freq",
|
||||
"/sys/class/misc/mali0/device/clock",
|
||||
)
|
||||
File("/sys/class/devfreq").list()?.sorted()?.forEach { node ->
|
||||
if (node.contains("mali", true) || node.contains("gpu", true)) list.add("/sys/class/devfreq/$node/cur_freq")
|
||||
}
|
||||
return list.distinct()
|
||||
}
|
||||
|
||||
private fun File.readTextOrNull(): String? = runCatching { readText() }.getOrNull()
|
||||
|
||||
private fun firstNumber(path: String): Long? =
|
||||
runCatching { Regex("\\d+").find(File(path).readText())?.value?.toLong() }.getOrNull()
|
||||
|
||||
/** Hz, kHz or MHz to MHz; "?" when unread. */
|
||||
private fun mhz(raw: Long?): String = when {
|
||||
raw == null -> "?"
|
||||
raw > 10_000_000 -> (raw / 1_000_000).toString()
|
||||
raw > 10_000 -> (raw / 1_000).toString()
|
||||
else -> raw.toString()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -61,7 +61,7 @@ object DeviceInfo {
|
||||
|
||||
private fun gpu(gpu: GpuInfo) = Section("GPU", buildList<Pair<String, String>> {
|
||||
add("GPU", gpu.name)
|
||||
add("Family", gpu.family.label)
|
||||
add("Family", gpu.family.label(gpu.name))
|
||||
add("Model found from", when (gpu.modelSource) {
|
||||
"kernel" -> "the kernel's GPU name"
|
||||
"vulkan" -> "the Vulkan driver (the kernel's name has no model)"
|
||||
@@ -157,10 +157,20 @@ object DeviceInfo {
|
||||
add("Driver mode", SessionPrefs.gpuDriverMode(context))
|
||||
val turnip = TurnipDriver(context)
|
||||
val choice = SessionPrefs.androidDriver(context).ifEmpty { turnip.autoId() }
|
||||
add("Display driver", "${turnip.displayName(choice)} ${turnip.driverVersion(choice)}".trim())
|
||||
val powerVr = gpu.family == GpuInfo.Family.POWERVR
|
||||
add("Display driver", if (choice == "system") builtinDriverLabel(powerVr, runtime = false)
|
||||
else "${turnip.displayName(choice)} ${turnip.driverVersion(choice)}".trim())
|
||||
val linux = LinuxVulkanDriverManager(context)
|
||||
val id = SessionPrefs.linuxDriver(context)
|
||||
add("Game driver", if (id.isEmpty()) "the runtime's own Turnip" else "${linux.getDriverName(id)} ${linux.getDriverVersion(id)}".trim())
|
||||
add("Game driver", if (id.isEmpty()) builtinDriverLabel(powerVr, runtime = true) else "${linux.getDriverName(id)} ${linux.getDriverVersion(id)}".trim())
|
||||
if (gpu.oneUi8Gen2) add("Note", "One UI on an 8 Gen 2: needs the OneUI Turnip build")
|
||||
})
|
||||
|
||||
/** Shared by the device card and the session report, which are written in English. */
|
||||
internal fun builtinDriverLabel(powerVr: Boolean, runtime: Boolean): String = when {
|
||||
powerVr -> "System PowerVR"
|
||||
runtime -> "the runtime's own Turnip"
|
||||
else -> "System Vulkan"
|
||||
}
|
||||
|
||||
}
|
||||
@@ -86,6 +86,13 @@ object DriverBundle {
|
||||
val manifest = File(work, MANIFEST).takeIf { it.isFile }
|
||||
?.let { runCatching { parseManifest(JSONObject(FileUtils.readString(it))) }.getOrNull() }
|
||||
?: throw IllegalArgumentException(context.getString(R.string.bundle_no_manifest))
|
||||
// The same open non-Adreno pair again (picked again after another one): replace it
|
||||
// rather than keeping a "-2" copy beside the old one. Adreno bundles keep their copies.
|
||||
val sameId = LinuxVulkanDriverManager.sanitizeId(manifest.tag.ifEmpty { "${manifest.name}-${manifest.version}" })
|
||||
get(context, sameId)?.takeIf { DriverPairs.isNonAdreno(it.id) }?.let { old ->
|
||||
Log.i(TAG, "replacing bundle ${old.id} (display ${old.androidId}, runtime ${old.linuxId})")
|
||||
remove(context, old)
|
||||
}
|
||||
val androidDir = File(work, manifest.androidPath)
|
||||
val linuxDir = File(work, manifest.linuxPath)
|
||||
|
||||
@@ -100,8 +107,8 @@ object DriverBundle {
|
||||
|
||||
val linuxStage = lm.newStagingDir()
|
||||
val linuxId = try {
|
||||
val library = linuxDir.listFiles()?.firstOrNull { it.isFile && it.name.startsWith("libvulkan_freedreno") && it.name.endsWith(".so") }
|
||||
library?.copyTo(File(linuxStage, LinuxVulkanDriverManager.LIB_NAME))
|
||||
val library = linuxDir.listFiles()?.firstOrNull { it.isFile && LinuxVulkanDriverManager.isDriverLibrary(it.name) }
|
||||
library?.copyTo(File(linuxStage, LinuxVulkanDriverManager.storedName(library.name)))
|
||||
val meta = File(linuxDir, LinuxVulkanDriverManager.META_NAME).takeIf { it.isFile }
|
||||
?.let { runCatching { JSONObject(FileUtils.readString(it)) }.getOrNull() }
|
||||
lm.adopt(linuxStage, library?.name, meta, manifest.name)
|
||||
|
||||
@@ -27,6 +27,44 @@ object DriverPairs {
|
||||
/** Each DD-Turnip release is its own pair: "dd-turnip:DD-Turnip-v0.1.0". */
|
||||
fun ddTurnip(tag: String) = "$DD_TURNIP:$tag"
|
||||
|
||||
/** The open non-Adreno drivers (The412Banner/droiddeck-nonadreno-drivers), one pair per driver. */
|
||||
const val NON_ADRENO = "nad"
|
||||
const val NAD_RADV_XCLIPSE = "nad:radv-xclipse"
|
||||
const val NAD_MALI_JM = "nad:panvk-mali-jm"
|
||||
const val NAD_MALI_G710 = "nad:panvk-mali-g710"
|
||||
const val NAD_MALI_G615 = "nad:panvk-mali-g615"
|
||||
const val NAD_MALI_G720 = "nad:panvk-mali-g720"
|
||||
/** One PanVK kbase binary for Mali v9-v13; its display half needs Android 15. */
|
||||
const val NAD_MALI_KBASE = "nad:panvk-mali-kbase"
|
||||
const val MALI_KBASE_MIN_SDK = 35
|
||||
/** faux123's PanVK builds for three handhelds: manual choices, never Auto. */
|
||||
const val NAD_FAUX_RP4PRO = "nad:panvk-faux123-rp4pro"
|
||||
const val NAD_FAUX_ACE = "nad:panvk-faux123-ace"
|
||||
const val NAD_FAUX_RG556 = "nad:panvk-faux123-rg556"
|
||||
/** The one Mali a device-specific build is for, by the number in the GPU's name. */
|
||||
private val DEVICE_BUILDS = mapOf(NAD_FAUX_RP4PRO to 77, NAD_FAUX_ACE to 610, NAD_FAUX_RG556 to 57)
|
||||
/** "PanVK-Mali-G720" (the release asset's id) to its pair key, "nad:panvk-mali-g720". */
|
||||
fun nonAdreno(id: String) = "$NON_ADRENO:" + id.lowercase()
|
||||
/** True for a non-Adreno pair's key, or a bundle installed from one ("PanVK-Mali-G720"). */
|
||||
fun isNonAdreno(keyOrBundleId: String?): Boolean = keyOrBundleId != null &&
|
||||
(keyOrBundleId.startsWith("$NON_ADRENO:") || Regex("""^(?i)(RADV-Xclipse|PanVK-[A-Za-z0-9]+)(-[A-Za-z0-9]+)*$""").matches(keyOrBundleId))
|
||||
|
||||
fun nonAdrenoName(key: String): String = describeNonAdreno(key).first
|
||||
|
||||
private fun describeNonAdreno(key: String): Pair<String, Set<Family>> = when (key) {
|
||||
NAD_RADV_XCLIPSE -> "RADV · Samsung Xclipse" to setOf(Family.POWERVR)
|
||||
NAD_MALI_JM -> "PanVK · Mali G52-G78" to setOf(Family.MALI_JM)
|
||||
NAD_MALI_G710 -> "PanVK · Mali-G610/G710" to setOf(Family.MALI_G610_G710)
|
||||
NAD_MALI_G615 -> "PanVK · Mali-G615" to setOf(Family.MALI_G615)
|
||||
NAD_MALI_G720 -> "PanVK · Mali-G720" to setOf(Family.MALI_G720)
|
||||
NAD_FAUX_RP4PRO -> "PanVK faux123 · Retroid Pocket 4 Pro (Mali-G77)" to setOf(Family.MALI_JM)
|
||||
NAD_FAUX_ACE -> "PanVK faux123 · GameForce Ace (Mali-G610)" to setOf(Family.MALI_G610_G710)
|
||||
NAD_FAUX_RG556 -> "PanVK faux123 · Anbernic RG556 (Mali-G57)" to setOf(Family.MALI_JM)
|
||||
NAD_MALI_KBASE -> "PanVK kbase · Mali G57-G925" to
|
||||
setOf(Family.MALI_JM, Family.MALI_G610_G710, Family.MALI_G615, Family.MALI_G720, Family.MALI_LATEST)
|
||||
else -> key.removePrefix("$NON_ADRENO:") to emptySet<Family>()
|
||||
}
|
||||
|
||||
class DriverPair(
|
||||
val key: String,
|
||||
/** "Banners-Turnip · Adreno 6xx/7xx", "WinNative · Balanced". */
|
||||
@@ -44,14 +82,22 @@ object DriverPairs {
|
||||
/** "r4 · 1.19 + 0.1.2": the build of each half. */
|
||||
val version: String
|
||||
get() = listOfNotNull(bundle?.tag, display?.tag, linux?.tag).distinct().joinToString(" + ") { it.removePrefix("linux-").removePrefix("DD-Turnip-") }
|
||||
fun suits(gpu: GpuInfo) = gpu.family in families ||
|
||||
(gpu.family == Family.ADRENO_UNKNOWN && (Family.A7XX in families || Family.A8XX in families))
|
||||
fun suits(gpu: GpuInfo) = when {
|
||||
// The system-driver family covers PowerVR and Xclipse; RADV is only for the Xclipse.
|
||||
key == NAD_RADV_XCLIPSE -> gpu.family == Family.POWERVR && gpu.name.contains("Xclipse", ignoreCase = true)
|
||||
// One binary for Mali v9-v13, not the older G52/G76 in the Job Manager family.
|
||||
key == NAD_MALI_KBASE -> gpu.family.mali && GpuInfo.maliKbaseCovered(gpu.name)
|
||||
key in DEVICE_BUILDS -> gpu.family.mali && GpuInfo.maliNumber(gpu.name) == DEVICE_BUILDS[key]
|
||||
else -> gpu.family in families ||
|
||||
(gpu.family == Family.ADRENO_UNKNOWN && (Family.A7XX in families || Family.A8XX in families))
|
||||
}
|
||||
}
|
||||
|
||||
private val ALL_ADRENO = setOf(Family.A6XX, Family.A7XX, Family.A7XX_LOW, Family.A8XX, Family.ADRENO_UNKNOWN)
|
||||
|
||||
private fun describe(key: String): Pair<String, Set<Family>> = when {
|
||||
key.startsWith(DD_TURNIP) -> "DroidDeck · DD-Turnip" to ALL_ADRENO
|
||||
key.startsWith("$NON_ADRENO:") -> describeNonAdreno(key)
|
||||
else -> describeFixed(key)
|
||||
}
|
||||
|
||||
@@ -68,7 +114,7 @@ object DriverPairs {
|
||||
/** Every pair the last release check found, in the order the list shows them. */
|
||||
fun from(check: TurnipReleases.Check?): List<DriverPair> {
|
||||
val assets = check?.assets.orEmpty().filter { it.pair.isNotEmpty() }
|
||||
val order = listOf(DD_TURNIP, BANNER, BANNER_A8XX, BANNER_ONEUI, BANNER_710, WN_BALANCED, WN_PERFORMANCE)
|
||||
val order = listOf(DD_TURNIP, BANNER, BANNER_A8XX, BANNER_ONEUI, BANNER_710, WN_BALANCED, WN_PERFORMANCE, NON_ADRENO)
|
||||
return assets.map { it.pair }.distinct()
|
||||
.sortedBy { key -> order.indexOf(key.substringBefore(':')).let { i -> if (i < 0) order.size else i } }
|
||||
.map { key ->
|
||||
@@ -92,8 +138,13 @@ object DriverPairs {
|
||||
* release is listed, the OneUI build for an 8 Gen 2 under One UI, the patched test builds for
|
||||
* the 710/720/722, and upstream Banners-Turnip for the rest. Null when nothing fits (not Adreno).
|
||||
*/
|
||||
fun recommendedKey(gpu: GpuInfo, pairs: List<DriverPair>): String? = when (gpu.family) {
|
||||
Family.NOT_ADRENO -> null
|
||||
fun recommendedKey(gpu: GpuInfo, pairs: List<DriverPair>, sdk: Int = android.os.Build.VERSION.SDK_INT): String? = when (gpu.family) {
|
||||
// Xclipse takes the RADV pair (testers: it boots to Steam where the system route's GL fails),
|
||||
// with the system route as its fallback; PowerVR keeps the system driver. A Mali no open
|
||||
// build covers draws through the Vulkan bridge (DriverMenus.ensureAuto).
|
||||
Family.POWERVR -> NAD_RADV_XCLIPSE.takeIf { gpu.name.contains("Xclipse", ignoreCase = true) }
|
||||
Family.NOT_ADRENO, Family.MALI_OTHER -> null
|
||||
Family.MALI_JM, Family.MALI_G610_G710, Family.MALI_G615, Family.MALI_G720, Family.MALI_LATEST -> maliKey(gpu, pairs, sdk)
|
||||
Family.A8XX -> if (gpu.model == 840) newestDdTurnip(pairs) ?: WN_BALANCED else WN_BALANCED
|
||||
Family.A7XX_LOW -> BANNER_710
|
||||
Family.A7XX -> if (gpu.oneUi8Gen2) BANNER_ONEUI else BANNER
|
||||
@@ -102,6 +153,25 @@ object DriverPairs {
|
||||
Family.ADRENO_UNKNOWN -> if (android.os.Build.VERSION.SDK_INT >= 36) WN_BALANCED else BANNER
|
||||
}
|
||||
|
||||
/**
|
||||
* A Mali's pair: the one-binary kbase build on Android 15+ for every Mali it covers, else the
|
||||
* build for the GPU's generation. A preferred pair the check did not find falls back to the
|
||||
* generation's own, and a G715/G725/G925 without the kbase build gets none (the bridge).
|
||||
*/
|
||||
private fun maliKey(gpu: GpuInfo, pairs: List<DriverPair>, sdk: Int): String? {
|
||||
val family = when (gpu.family) {
|
||||
Family.MALI_JM -> NAD_MALI_JM
|
||||
Family.MALI_G610_G710 -> NAD_MALI_G710
|
||||
Family.MALI_G615 -> NAD_MALI_G615
|
||||
Family.MALI_G720 -> NAD_MALI_G720
|
||||
else -> null
|
||||
}
|
||||
val kbase = NAD_MALI_KBASE.takeIf { sdk >= MALI_KBASE_MIN_SDK && GpuInfo.maliKbaseCovered(gpu.name) }
|
||||
if (pairs.isEmpty()) return kbase ?: family
|
||||
fun listed(key: String?) = key?.takeIf { k -> pairs.any { it.key == k && it.complete } }
|
||||
return listed(kbase) ?: listed(family) ?: kbase ?: family
|
||||
}
|
||||
|
||||
/** The complete DD-Turnip pair with the highest version, or null when none is listed. */
|
||||
fun newestDdTurnip(pairs: List<DriverPair>): String? = pairs
|
||||
.filter { it.key.startsWith("$DD_TURNIP:") && it.complete }
|
||||
|
||||
@@ -35,8 +35,23 @@ data class GpuInfo(
|
||||
A6XX("Adreno 6xx"),
|
||||
/** An Adreno whose model KGSL does not give: treated as the newest family it could be. */
|
||||
ADRENO_UNKNOWN("Adreno"),
|
||||
POWERVR("PowerVR"),
|
||||
/** Mali on Arm's kbase driver, by the open PanVK build each generation needs. */
|
||||
MALI_JM("Mali (G52-G78)"),
|
||||
MALI_G610_G710("Mali-G610/G710"),
|
||||
MALI_G615("Mali-G615"),
|
||||
MALI_G720("Mali-G720"),
|
||||
/** Mali-G715/G725/G925: only the one-binary PanVK kbase build covers them (Android 15+). */
|
||||
MALI_LATEST("Mali-G715/G725/G925"),
|
||||
/** A Mali no open driver build covers: the Vulkan bridge is its only path. */
|
||||
MALI_OTHER("Mali"),
|
||||
NOT_ADRENO("Not an Adreno GPU");
|
||||
|
||||
val mali: Boolean get() = name.startsWith("MALI_")
|
||||
|
||||
/** [label] for this GPU: the system-driver family is a Samsung Xclipse or a PowerVR. */
|
||||
fun label(gpuName: String): String = if (this == POWERVR && gpuName.contains("Xclipse", ignoreCase = true)) "Samsung Xclipse" else label
|
||||
|
||||
/** [label] in the app's language: the Adreno families are names, the rest is words. */
|
||||
fun label(context: Context): String = if (this == NOT_ADRENO) context.getString(R.string.gpuinfo_not_adreno) else label
|
||||
}
|
||||
@@ -56,15 +71,26 @@ data class GpuInfo(
|
||||
val supportText: String
|
||||
get() = when (support) {
|
||||
Support.TESTED -> "Supported"
|
||||
Support.UNTESTED -> if (family == Family.A7XX_LOW) "Experimental: its drivers are test builds"
|
||||
else "Outside tested hardware (Adreno 650, 725 and newer): it may not run"
|
||||
Support.UNSUPPORTED -> "Not supported: DroidDeck needs an Adreno (Snapdragon) GPU"
|
||||
Support.UNTESTED -> when (family) {
|
||||
Family.POWERVR -> if (name.contains("Xclipse", ignoreCase = true)) "Experimental: RADV or the system Xclipse driver"
|
||||
else "System PowerVR driver: compatibility varies by device"
|
||||
Family.MALI_OTHER -> "Experimental: Mali through the Vulkan bridge"
|
||||
Family.MALI_JM, Family.MALI_G610_G710, Family.MALI_G615, Family.MALI_G720, Family.MALI_LATEST -> "Experimental: open Mali driver (test builds)"
|
||||
Family.A7XX_LOW -> "Experimental: its drivers are test builds"
|
||||
else -> "Outside tested hardware (Adreno 650, 725 and newer): it may not run"
|
||||
}
|
||||
Support.UNSUPPORTED -> "Not supported: no compatible graphics backend is available for this GPU"
|
||||
}
|
||||
|
||||
/** [supportText] in the app's language. */
|
||||
fun supportText(context: Context): String = context.getString(when (support) {
|
||||
Support.TESTED -> R.string.gpuinfo_supported
|
||||
Support.UNTESTED -> if (family == Family.A7XX_LOW) R.string.gpuinfo_experimental else R.string.gpuinfo_below_tested
|
||||
Support.UNTESTED -> when (family) {
|
||||
Family.POWERVR -> if (name.contains("Xclipse", ignoreCase = true)) R.string.gpuinfo_xclipse else R.string.gpuinfo_powervr
|
||||
Family.A7XX_LOW -> R.string.gpuinfo_experimental
|
||||
Family.MALI_JM, Family.MALI_G610_G710, Family.MALI_G615, Family.MALI_G720, Family.MALI_LATEST, Family.MALI_OTHER -> R.string.gpuinfo_experimental
|
||||
else -> R.string.gpuinfo_below_tested
|
||||
}
|
||||
Support.UNSUPPORTED -> R.string.gpuinfo_unsupported
|
||||
})
|
||||
|
||||
@@ -94,10 +120,20 @@ data class GpuInfo(
|
||||
fromPlatform > 0 -> "platform"
|
||||
else -> ""
|
||||
}
|
||||
val family = familyOf(adreno, model)
|
||||
// Mali, named by the vendor's Vulkan driver ("Mali-G720-Immortalis MC12") or by kbase.
|
||||
val mali = if (adreno || !File("/dev/mali0").exists()) null else maliName()
|
||||
val family = familyOf(adreno, model, SystemVulkanDriver.isPowerVr(), mali)
|
||||
val samsung = Build.MANUFACTURER.equals("samsung", ignoreCase = true)
|
||||
return GpuInfo(
|
||||
name = if (!adreno) Build.HARDWARE.ifBlank { UNNAMED } else if (model > 0) "Adreno $model" else "Adreno",
|
||||
name = when {
|
||||
family == Family.POWERVR -> SystemVulkanDriver.gpuName().let { gpu ->
|
||||
VulkanInfo.cachedOrNull()?.get("device")?.takeIf { it.contains(gpu, ignoreCase = true) } ?: gpu
|
||||
}
|
||||
mali != null && mali.isNotEmpty() -> mali
|
||||
!adreno -> Build.HARDWARE.ifBlank { UNNAMED }
|
||||
model > 0 -> "Adreno $model"
|
||||
else -> "Adreno"
|
||||
},
|
||||
model = model, family = family, soc = soc,
|
||||
oneUi8Gen2 = samsung && model == 740,
|
||||
kgslName = raw.orEmpty(), modelSource = source,
|
||||
@@ -122,7 +158,68 @@ data class GpuInfo(
|
||||
""
|
||||
}
|
||||
|
||||
internal fun familyOf(adreno: Boolean, model: Int): Family = when {
|
||||
/**
|
||||
* The Mali's name, "" when nothing names it: the vendor Vulkan driver's own name when this
|
||||
* process has asked it, kbase's gpuinfo where SELinux lets the app read it (most phones do
|
||||
* not), else the GPU the chip is known to carry ([MALI_SOCS]).
|
||||
*/
|
||||
private fun maliName(): String =
|
||||
VulkanInfo.cachedOrNull()?.get("device")?.takeIf { it.contains("Mali", ignoreCase = true) }
|
||||
?: FileUtils.readString(File("/sys/class/misc/mali0/device/gpuinfo"))?.trim()?.takeIf { it.contains("Mali", ignoreCase = true) }
|
||||
?.substringBefore(" ")
|
||||
?: maliOfSoc(socIds())
|
||||
?: ""
|
||||
|
||||
/** The chip's names as the platform gives them: "mt6989", "MT6989", "gs201". */
|
||||
private fun socIds(): List<String> = listOfNotNull(
|
||||
if (Build.VERSION.SDK_INT >= 31) Build.SOC_MODEL else null,
|
||||
systemProperty("ro.board.platform"), systemProperty("ro.soc.model"), Build.HARDWARE, Build.BOARD,
|
||||
).filter { it.isNotBlank() }
|
||||
|
||||
/** Chips whose Mali is known for certain (MediaTek Dimensity / Helio / Kompanio, Google Tensor). */
|
||||
private val MALI_SOCS = mapOf(
|
||||
"mt6991" to "Mali-G925", "mt6989" to "Mali-G720", "mt6899" to "Mali-G720", "mt6985" to "Mali-G715",
|
||||
"mt6983" to "Mali-G710", "mt6897" to "Mali-G615", "mt6878" to "Mali-G615", "mt6895" to "Mali-G610",
|
||||
"mt6896" to "Mali-G610", "mt6886" to "Mali-G610", "mt6893" to "Mali-G77", "mt6891" to "Mali-G77",
|
||||
"mt6889" to "Mali-G77", "mt6885" to "Mali-G77", "mt6877" to "Mali-G68", "mt6853" to "Mali-G57",
|
||||
"mt6833" to "Mali-G57", "mt6835" to "Mali-G57", "mt6789" to "Mali-G57", "mt6785" to "Mali-G76",
|
||||
"mt6781" to "Mali-G52", "mt6769" to "Mali-G52", "mt8192" to "Mali-G57", "mt8195" to "Mali-G57",
|
||||
"gs101" to "Mali-G78", "gs201" to "Mali-G710", "zuma" to "Mali-G715", "zumapro" to "Mali-G715",
|
||||
"s5e8835" to "Mali-G68", "s5e8825" to "Mali-G68",
|
||||
)
|
||||
|
||||
/** The Mali [ids] name a chip of, "Mali-G720 (by chip mt6989)", or null for an unknown chip. */
|
||||
internal fun maliOfSoc(ids: List<String>): String? = ids.firstNotNullOfOrNull { id ->
|
||||
MALI_SOCS[id.trim().lowercase()]?.let { "$it (by chip ${id.trim().lowercase()})" }
|
||||
}
|
||||
|
||||
/** The number in a Mali's name: 720 for "Mali-G720-Immortalis MC12". */
|
||||
fun maliNumber(name: String): Int? =
|
||||
Regex("""G(\d{2,3})""", RegexOption.IGNORE_CASE).find(name)?.groupValues?.get(1)?.toIntOrNull()
|
||||
|
||||
/**
|
||||
* The Malis the one-binary PanVK kbase build covers (arch v9-v13): G57/G68/G77/G78,
|
||||
* G610/G710, G615/G715, G720/G725 and G925. Not the older Bifrost G52/G76.
|
||||
*/
|
||||
fun maliKbaseCovered(name: String): Boolean =
|
||||
maliNumber(name) in setOf(57, 68, 77, 78, 610, 710, 615, 715, 720, 725, 925)
|
||||
|
||||
/** The PanVK generation a Mali name belongs to; MALI_OTHER when none of the builds covers it. */
|
||||
internal fun maliFamily(name: String): Family {
|
||||
val number = maliNumber(name) ?: return Family.MALI_OTHER
|
||||
return when (number) {
|
||||
31, 51, 52, 57, 68, 71, 72, 76, 77, 78 -> Family.MALI_JM
|
||||
610, 710 -> Family.MALI_G610_G710
|
||||
615 -> Family.MALI_G615
|
||||
720 -> Family.MALI_G720
|
||||
715, 725, 925 -> Family.MALI_LATEST
|
||||
else -> Family.MALI_OTHER
|
||||
}
|
||||
}
|
||||
|
||||
internal fun familyOf(adreno: Boolean, model: Int, powerVr: Boolean = false, mali: String? = null): Family = when {
|
||||
!adreno && powerVr -> Family.POWERVR
|
||||
!adreno && mali != null -> maliFamily(mali)
|
||||
!adreno -> Family.NOT_ADRENO
|
||||
model == 0 -> Family.ADRENO_UNKNOWN
|
||||
model >= 800 -> Family.A8XX
|
||||
|
||||
@@ -3,8 +3,12 @@ package com.droiddeck.launcher.gpu;
|
||||
import android.content.Context;
|
||||
import android.util.Log;
|
||||
|
||||
import com.droiddeck.launcher.R;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
/**
|
||||
* The Vulkan driver a session draws with inside the runtime: in Steam mode the native client's
|
||||
@@ -17,7 +21,8 @@ import java.util.List;
|
||||
* these are glibc processes, that one is bionic.
|
||||
*
|
||||
* <p>"" (the default) means the driver the runtime was built with, at
|
||||
* {@code usr/lib/libvulkan_freedreno.so} inside it - nothing is set and nothing is touched.
|
||||
* {@code usr/lib/libvulkan_freedreno.so} on Adreno, or the bundled bridge to the system
|
||||
* PowerVR driver.
|
||||
* Otherwise the value is an imported driver's id ({@link LinuxVulkanDriverManager}), and the
|
||||
* session is handed that driver's ICD manifest in {@code BL_VK_DRIVER}: the session script points
|
||||
* the Vulkan loader at it with {@code VK_DRIVER_FILES} after checking both the manifest and the
|
||||
@@ -47,30 +52,44 @@ public final class LinuxVulkanDriver {
|
||||
}
|
||||
|
||||
/**
|
||||
* Label for a stored value. An id that is no longer installed says so - the launch path falls
|
||||
* back to the runtime's own driver for it.
|
||||
* Label for a stored value. Missing imports fall back to the runtime on Adreno;
|
||||
* PowerVR requires another explicit selection or Auto before launching.
|
||||
*/
|
||||
public static String optionLabel(Context context, String value) {
|
||||
if (value == null || value.isEmpty()) return "Runtime default (built into the runtime)";
|
||||
if (value == null || value.isEmpty()) return SystemVulkanDriver.isPowerVr()
|
||||
? context.getString(R.string.gpu_system_powervr) : "Runtime default (built into the runtime)";
|
||||
LinuxVulkanDriverManager m = new LinuxVulkanDriverManager(context);
|
||||
if (!m.isInstalled(value)) return value + " (imported, missing - uses the runtime default)";
|
||||
if (!m.isInstalled(value)) return value + (SystemVulkanDriver.isPowerVr()
|
||||
? " (imported, missing)" : " (imported, missing - uses the runtime default)");
|
||||
String ver = m.getDriverVersion(value);
|
||||
return m.getDriverName(value) + (ver.isEmpty() ? "" : " " + ver) + " (imported)";
|
||||
}
|
||||
|
||||
/**
|
||||
* The ICD manifest path to hand the session, or null to leave the runtime's own driver alone.
|
||||
* An id whose import is gone resolves to null rather than failing the launch.
|
||||
* A missing import uses the runtime's own driver on Adreno. PowerVR fails clearly instead:
|
||||
* its system backend needs environment setup that an explicit import does not receive.
|
||||
*/
|
||||
public static String resolveIcdPath(Context context, String value) {
|
||||
boolean powerVr = SystemVulkanDriver.isPowerVr();
|
||||
return resolveIcdPath(value, powerVr,
|
||||
() -> SystemVulkanDriver.icdPath(context), id -> {
|
||||
String icd = new LinuxVulkanDriverManager(context).getIcdPath(id);
|
||||
if (icd == null) Log.w(TAG, "imported Linux driver \"" + id + "\" is gone"
|
||||
+ (powerVr ? "" : "; using the runtime's own driver"));
|
||||
else Log.i(TAG, "Linux session draws with imported driver " + id + " (" + icd + ")");
|
||||
return icd;
|
||||
});
|
||||
}
|
||||
|
||||
/** Resolve the selected backend before looking up an imported driver. */
|
||||
static String resolveIcdPath(String value, boolean powerVr, Supplier<String> systemIcd,
|
||||
Function<String, String> importedIcd) {
|
||||
if (SystemVulkanDriver.usesDefault(powerVr, value)) return systemIcd.get();
|
||||
if (value == null || value.isEmpty()) return null;
|
||||
LinuxVulkanDriverManager m = new LinuxVulkanDriverManager(context);
|
||||
String icd = m.getIcdPath(value);
|
||||
if (icd == null) {
|
||||
Log.w(TAG, "imported Linux driver \"" + value + "\" is gone; using the runtime's own driver");
|
||||
return null;
|
||||
}
|
||||
Log.i(TAG, "Linux session draws with imported driver " + value + " (" + icd + ")");
|
||||
String icd = importedIcd.apply(value);
|
||||
if (powerVr && icd == null) throw new IllegalStateException(
|
||||
"Selected Linux Vulkan driver \"" + value + "\" is unavailable. Select an installed driver or use Auto.");
|
||||
return icd;
|
||||
}
|
||||
}
|
||||
@@ -70,7 +70,9 @@ public class LinuxVulkanDriverManager {
|
||||
public boolean isInstalled(String id) {
|
||||
if (id == null || id.isEmpty() || id.contains("/") || id.contains("..")) return false;
|
||||
File dir = getDriverDir(id);
|
||||
return new File(dir, LIB_NAME).isFile() && new File(dir, ICD_NAME).isFile();
|
||||
if (!new File(dir, ICD_NAME).isFile()) return false;
|
||||
for (String name : STORED_NAMES) if (new File(dir, name).isFile()) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
/** Absolute path of the driver's ICD manifest, or null when the id isn't installed. */
|
||||
@@ -141,10 +143,10 @@ public class LinuxVulkanDriverManager {
|
||||
// Flatten: only the base name matters, and it also defeats zip-slip paths.
|
||||
String base = new File(entry.getName()).getName();
|
||||
if (base.isEmpty()) continue;
|
||||
if (base.startsWith("libvulkan_freedreno") && base.endsWith(".so")) {
|
||||
if (soName != null) Log.w(TAG, "zip has several libvulkan_freedreno*.so; using the first (" + soName + ")");
|
||||
if (isDriverLibrary(base)) {
|
||||
if (soName != null) Log.w(TAG, "zip has several driver libraries; using the first (" + soName + ")");
|
||||
else {
|
||||
Files.copy(zis, new File(tmpDir, LIB_NAME).toPath(), StandardCopyOption.REPLACE_EXISTING);
|
||||
Files.copy(zis, new File(tmpDir, storedName(base)).toPath(), StandardCopyOption.REPLACE_EXISTING);
|
||||
soName = base;
|
||||
}
|
||||
} else if (base.equals(META_NAME)) {
|
||||
@@ -184,7 +186,8 @@ public class LinuxVulkanDriverManager {
|
||||
if (soName == null) {
|
||||
throw new IllegalArgumentException(context.getString(R.string.lvd_no_library));
|
||||
}
|
||||
File so = new File(tmpDir, LIB_NAME);
|
||||
String stored = storedName(soName);
|
||||
File so = new File(tmpDir, stored);
|
||||
if (!isAarch64Elf(so)) {
|
||||
throw new IllegalArgumentException(context.getString(R.string.lvd_not_aarch64, soName));
|
||||
}
|
||||
@@ -214,7 +217,7 @@ public class LinuxVulkanDriverManager {
|
||||
JSONObject icd = new JSONObject();
|
||||
icd.put("file_format_version", "1.0.0");
|
||||
JSONObject icdBody = new JSONObject();
|
||||
icdBody.put("library_path", new File(dir, LIB_NAME).getAbsolutePath());
|
||||
icdBody.put("library_path", new File(dir, stored).getAbsolutePath());
|
||||
icdBody.put("api_version", "1.1.274");
|
||||
icd.put("ICD", icdBody);
|
||||
if (!FileUtils.writeString(new File(tmpDir, ICD_NAME), icd.toString(2))) throw new IOException("cannot write icd.json");
|
||||
@@ -227,6 +230,7 @@ public class LinuxVulkanDriverManager {
|
||||
meta.put("libc", "glibc");
|
||||
meta.put("minGlibc", minGlibc);
|
||||
meta.put("sourceLibraryName", soName);
|
||||
meta.put("libraryName", stored);
|
||||
meta.put("importedAt", System.currentTimeMillis());
|
||||
if (!FileUtils.writeString(new File(tmpDir, META_NAME), meta.toString(2))) throw new IOException("cannot write meta.json");
|
||||
|
||||
@@ -245,6 +249,29 @@ public class LinuxVulkanDriverManager {
|
||||
return id;
|
||||
}
|
||||
|
||||
/**
|
||||
* A Linux Vulkan driver's library as release zips name it: Turnip (freedreno) on Adreno, PanVK
|
||||
* (panfrost) on Mali, RADV (radeon) on Xclipse. Whichever it is, it is installed as
|
||||
* {@link #LIB_NAME}; the ICD manifest loads it by that absolute path.
|
||||
*/
|
||||
/** The names an installed driver's library is kept under; Turnip keeps {@link #LIB_NAME}. */
|
||||
private static final String[] STORED_NAMES = {LIB_NAME, "libvulkan_panfrost.so", "libvulkan_radeon.so"};
|
||||
|
||||
/**
|
||||
* The name a driver library is installed under: its own driver's (PanVK, RADV), so the session
|
||||
* log and the graphics report say which driver it is; a Turnip build keeps {@link #LIB_NAME}.
|
||||
*/
|
||||
public static String storedName(String soName) {
|
||||
if (soName != null && soName.startsWith("libvulkan_panfrost")) return "libvulkan_panfrost.so";
|
||||
if (soName != null && soName.startsWith("libvulkan_radeon")) return "libvulkan_radeon.so";
|
||||
return LIB_NAME;
|
||||
}
|
||||
|
||||
public static boolean isDriverLibrary(String base) {
|
||||
return base.endsWith(".so") && (base.startsWith("libvulkan_freedreno")
|
||||
|| base.startsWith("libvulkan_panfrost") || base.startsWith("libvulkan_radeon"));
|
||||
}
|
||||
|
||||
static String sanitizeId(String name) {
|
||||
String s = name.trim().replaceAll("[^A-Za-z0-9._-]+", "_").replaceAll("^[._]+", "");
|
||||
if (s.length() > 64) s = s.substring(0, 64);
|
||||
|
||||
@@ -0,0 +1,261 @@
|
||||
package com.droiddeck.launcher.gpu;
|
||||
|
||||
import android.content.Context;
|
||||
import android.os.Build;
|
||||
import android.system.ErrnoException;
|
||||
import android.system.Os;
|
||||
import android.system.OsConstants;
|
||||
import com.droiddeck.launcher.core.FileUtils;
|
||||
import com.droiddeck.launcher.core.TarZst;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.BufferedReader;
|
||||
import java.io.InputStreamReader;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.util.List;
|
||||
import java.util.TreeSet;
|
||||
import java.util.UUID;
|
||||
import java.util.function.Predicate;
|
||||
import org.json.JSONObject;
|
||||
|
||||
/** Isolated glibc-to-Android Vulkan bridge. It does not replace the rootfs's Mesa libraries. */
|
||||
public final class SystemVulkanDriver {
|
||||
private static final String ASSET = "hybris/runtime.tzst";
|
||||
/** Vendor HALs the bridge loads. Samsung Xclipse (Exynos, sgpu) is experimental. */
|
||||
private static final String[] HALS = {
|
||||
"/vendor/lib64/hw/vulkan.powervr.so",
|
||||
"/vendor/lib64/hw/vulkan.samsung.so"
|
||||
};
|
||||
private static final String[] REQUIRED = {
|
||||
"lib/libhybris-vulkan-icd.so.0", "lib/libhybris-common.so.1",
|
||||
"lib/libhybris/linker/q.so", "lib/libVkLayer_hybris_compat.so",
|
||||
"run-proton.py", "wsi/libVkLayer_window_system_integration.so",
|
||||
"wsi/VkLayer_window_system_integration.json",
|
||||
"dxvk/x32/d3d8.dll", "dxvk/x32/d3d9.dll", "dxvk/x32/d3d10core.dll",
|
||||
"dxvk/x32/d3d11.dll", "dxvk/x32/dxgi.dll",
|
||||
"dxvk/x64/d3d8.dll", "dxvk/x64/d3d9.dll", "dxvk/x64/d3d10core.dll",
|
||||
"dxvk/x64/d3d11.dll", "dxvk/x64/dxgi.dll"
|
||||
};
|
||||
|
||||
/** Rootfs directory of the Xclipse layer the apk stages (SessionFiles). */
|
||||
private static final String XCLIPSE_LAYER_DIR = "/usr/local/lib/droiddeck-xclipse";
|
||||
|
||||
private SystemVulkanDriver() {}
|
||||
|
||||
/**
|
||||
* The first vendor HAL present, or null. An Exynos with a Mali (Exynos 1280/1380: /dev/mali0)
|
||||
* may name its HAL vulkan.samsung.so too; that is a Mali, not an Xclipse, and is not taken.
|
||||
*/
|
||||
public static String hal() {
|
||||
for (String path : HALS) {
|
||||
if (!new File(path).isFile()) continue;
|
||||
if (path.endsWith("/vulkan.samsung.so") && new File("/dev/mali0").exists()) continue;
|
||||
return path;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Samsung's Xclipse (Exynos, sgpu) rather than PowerVR. */
|
||||
public static boolean isXclipse() {
|
||||
String hal = hal();
|
||||
return hal != null && hal.endsWith("/vulkan.samsung.so");
|
||||
}
|
||||
|
||||
/** The system-driver GPU family, for labels. */
|
||||
public static String gpuName() { return isXclipse() ? "Xclipse" : "PowerVR"; }
|
||||
|
||||
/** Whether a system-driver GPU (PowerVR or Xclipse) is present; the name predates Xclipse. */
|
||||
public static boolean isPowerVr() { return hal() != null; }
|
||||
|
||||
/** HAL detection names the GPU; launching also needs the real DRM render node. */
|
||||
public static boolean isAvailable() { return isPowerVr() && renderNodeAvailable(); }
|
||||
|
||||
public static boolean renderNodeAvailable() {
|
||||
return renderNodePath() != null;
|
||||
}
|
||||
|
||||
/** Select the actual PowerVR node, including devices where another GPU owns renderD128. */
|
||||
public static String renderNodePath() {
|
||||
String[] nodes = new File("/dev/dri").list();
|
||||
if (nodes == null) nodes = new File("/sys/class/drm").list();
|
||||
return findRenderNode(nodes, SystemVulkanDriver::renderNodeAvailable);
|
||||
}
|
||||
|
||||
static String findRenderNode(String[] nodes, Predicate<String> available) {
|
||||
TreeSet<String> candidates = new TreeSet<>();
|
||||
// Android can deny directory listing while allowing direct access. Probe the kernel's
|
||||
// reserved render range too; directory entries also cover dynamically allocated minors.
|
||||
for (int minor = 128; minor < 192; minor++) candidates.add("renderD" + minor);
|
||||
if (nodes != null) for (String node : nodes)
|
||||
if (node.matches("renderD[0-9]+")) candidates.add(node);
|
||||
for (String node : candidates) {
|
||||
String path = "/dev/dri/" + node;
|
||||
if (available.test(path)) return path;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static boolean renderNodeAvailable(String node) {
|
||||
try {
|
||||
if (!renderNodeAvailable(OsConstants.S_ISCHR(Os.stat(node).st_mode),
|
||||
Os.access(node, OsConstants.R_OK), Os.access(node, OsConstants.W_OK))) return false;
|
||||
return powerVrDevice(new File("/sys/class/drm/" + new File(node).getName() + "/device"));
|
||||
} catch (ErrnoException error) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
static boolean powerVrDriver(String driver) {
|
||||
return "pvrsrvkm".equals(driver) || "pvr".equals(driver) || "powervr".equals(driver)
|
||||
|| "sgpu".equals(driver);
|
||||
}
|
||||
|
||||
static boolean powerVrDevice(File device) {
|
||||
try {
|
||||
return powerVrDriver(Files.readSymbolicLink(new File(device, "driver").toPath())
|
||||
.getFileName().toString());
|
||||
} catch (IOException error) {
|
||||
// Some Android policies expose uevent but deny reading the driver symlink.
|
||||
try (BufferedReader input = Files.newBufferedReader(
|
||||
new File(device, "uevent").toPath(), StandardCharsets.US_ASCII)) {
|
||||
String line;
|
||||
while ((line = input.readLine()) != null)
|
||||
if (line.startsWith("DRIVER=")) return powerVrDriver(line.substring(7));
|
||||
} catch (IOException ignored) { }
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
static boolean renderNodeAvailable(boolean characterDevice, boolean readable, boolean writable) {
|
||||
return characterDevice && readable && writable;
|
||||
}
|
||||
|
||||
public static boolean usesDefault(String choice) {
|
||||
return usesDefault(isPowerVr(), choice);
|
||||
}
|
||||
|
||||
static boolean usesDefault(boolean powerVr, String choice) {
|
||||
return powerVr && (choice == null || choice.isEmpty());
|
||||
}
|
||||
|
||||
/** APK-versioned directories stay intact while an older session still has libraries mapped. */
|
||||
public static synchronized File prepare(Context context) throws IOException {
|
||||
if (!isPowerVr()) throw new IOException("System PowerVR Vulkan driver is unavailable");
|
||||
if (!renderNodeAvailable()) throw new IOException(
|
||||
"System PowerVR requires an identifiable, readable and writable DRM render node");
|
||||
File target = runtimeDirectory(context);
|
||||
File base = target.getParentFile();
|
||||
if (complete(target)) return target;
|
||||
if (!base.isDirectory() && !base.mkdirs()) throw new IOException("Cannot create system Vulkan directory");
|
||||
File staged = new File(base, ".stage-" + UUID.randomUUID());
|
||||
try {
|
||||
if (!TarZst.extractAsset(context, ASSET, staged)) throw new IOException("Cannot unpack system Vulkan runtime");
|
||||
for (String name : REQUIRED)
|
||||
if (!present(staged, name)) throw new IOException("Missing system Vulkan component: " + name);
|
||||
if (!new File(staged, "run-proton.py").canExecute())
|
||||
throw new IOException("System Vulkan Proton wrapper is not executable");
|
||||
JSONObject library = new JSONObject();
|
||||
library.put("library_path", new File(target, REQUIRED[0]).getPath());
|
||||
library.put("api_version", "1.3.0");
|
||||
JSONObject manifest = new JSONObject();
|
||||
manifest.put("file_format_version", "1.0.0");
|
||||
manifest.put("ICD", library);
|
||||
Files.write(new File(staged, "icd.json").toPath(), manifest.toString().getBytes(StandardCharsets.UTF_8));
|
||||
if (target.exists()) throw new IOException("Incomplete system Vulkan runtime directory: " + target.getName());
|
||||
if (!staged.renameTo(target)) throw new IOException("Cannot publish system Vulkan runtime");
|
||||
return target;
|
||||
} catch (org.json.JSONException error) {
|
||||
throw new IOException("Cannot write system Vulkan manifest", error);
|
||||
} finally {
|
||||
if (staged.exists()) FileUtils.delete(staged);
|
||||
}
|
||||
}
|
||||
|
||||
/** The current APK's versioned runtime path, without extracting or modifying it. */
|
||||
public static File runtimeDirectory(Context context) throws IOException {
|
||||
String version;
|
||||
try (BufferedReader input = new BufferedReader(new InputStreamReader(
|
||||
context.getAssets().open("hybris/version.txt"), StandardCharsets.US_ASCII))) {
|
||||
version = input.readLine();
|
||||
}
|
||||
if (version == null || !version.matches("[0-9a-f]{64}")) throw new IOException("Invalid system Vulkan runtime version");
|
||||
return new File(new File(context.getFilesDir(), "system_vulkan"), version);
|
||||
}
|
||||
|
||||
/** Collect abandoned stages, and obsolete versions once older guests can no longer load them. */
|
||||
public static synchronized void pruneUnused(Context context, boolean guestsStopped) throws IOException {
|
||||
pruneUnused(runtimeDirectory(context), guestsStopped);
|
||||
}
|
||||
|
||||
static synchronized void pruneUnused(File current, boolean guestsStopped) {
|
||||
File base = current.getParentFile();
|
||||
if (base == null || Files.isSymbolicLink(base.toPath()) || Files.isSymbolicLink(current.toPath())) return;
|
||||
File[] entries = base.listFiles();
|
||||
if (entries == null) return;
|
||||
// Retain the previous good version if publishing the replacement failed.
|
||||
boolean pruneVersions = guestsStopped && complete(current);
|
||||
for (File entry : entries) {
|
||||
if (entry.equals(current)) continue;
|
||||
String name = entry.getName();
|
||||
boolean oldVersion = pruneVersions && name.matches("[0-9a-f]{64}");
|
||||
boolean abandonedStage = name.matches("\\.stage-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}");
|
||||
// The prepare monitor excludes any extraction still writing a .stage directory.
|
||||
if (oldVersion || abandonedStage) FileUtils.delete(entry);
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean complete(File directory) {
|
||||
if (!new File(directory, "icd.json").isFile()) return false;
|
||||
for (String name : REQUIRED) if (!present(directory, name)) return false;
|
||||
return new File(directory, "run-proton.py").canExecute();
|
||||
}
|
||||
|
||||
private static boolean present(File directory, String name) {
|
||||
File file = new File(directory, name);
|
||||
return file.isFile() && file.length() > 0;
|
||||
}
|
||||
|
||||
public static String icdPath(Context context) {
|
||||
try {
|
||||
return new File(prepare(context), "icd.json").getPath();
|
||||
} catch (IOException error) {
|
||||
throw new IllegalStateException("System Vulkan runtime is unavailable", error);
|
||||
}
|
||||
}
|
||||
|
||||
public static void addEnvironment(Context context, List<String> environment) {
|
||||
File directory;
|
||||
try { directory = prepare(context); }
|
||||
catch (IOException error) { throw new IllegalStateException("System Vulkan runtime is unavailable", error); }
|
||||
String node = renderNodePath();
|
||||
if (node == null) throw new IllegalStateException("System PowerVR render node is unavailable");
|
||||
environment.add("HYBRIS_ANDROID_SDK_VERSION=" + Build.VERSION.SDK_INT);
|
||||
environment.add("HYBRIS_VULKAN_HAL=" + hal());
|
||||
environment.add("HYBRIS_LINKER_DIR=" + new File(directory, "lib/libhybris/linker").getPath());
|
||||
// Prefer framework dependencies for the system Vulkan loader, including libbase.so.
|
||||
environment.add("HYBRIS_LD_LIBRARY_PATH=/system/lib64:/system_ext/lib64:/vendor/lib64/egl:/vendor/lib64/hw:/vendor/lib64");
|
||||
boolean xclipse = isXclipse();
|
||||
// Xclipse gets its own layer (tools/linuxfs/xclipse-layer) in front of everything: it sets
|
||||
// bionic's environ for the driver's shader compiler, among other driver workarounds. The
|
||||
// session's own clients need nothing else; games keep the compat layer's BC emulation.
|
||||
String layers = xclipse ? "VK_LAYER_DROIDDECK_xclipse" : "VK_LAYER_HYBRIS_compat";
|
||||
environment.add("VK_LAYER_PATH=" + new File(directory, "lib").getPath() + (xclipse ? ":" + XCLIPSE_LAYER_DIR : ""));
|
||||
environment.add("VK_INSTANCE_LAYERS=" + layers);
|
||||
// Proton game launches add their WSI layer in front of these (droiddeck-game-env).
|
||||
environment.add("DROIDDECK_HYBRIS_LAYERS=" + (xclipse ? layers + ":VK_LAYER_HYBRIS_compat" : layers));
|
||||
if (xclipse) environment.add("DROIDDECK_HYBRIS_LAYER_PATH=" + XCLIPSE_LAYER_DIR);
|
||||
// DXVK 3 needs 256 bytes of push constants; this driver has 128.
|
||||
if (xclipse) environment.add("DROIDDECK_HYBRIS_DXVK=dxvk-2.6.2");
|
||||
// The Android driver has a render node, but no KMS primary node. SDL presents
|
||||
// through the wrapper's Wayland Vulkan swapchain instead of a KMS-style path.
|
||||
environment.add("BL_GAMESCOPE_BACKEND=sdl");
|
||||
// The Android pvr kernel accepts Vulkan DMA-BUF imports but rejects PRIME GEM handles.
|
||||
environment.add("BL_POWERVR_DRM_HANDLES=1");
|
||||
environment.add("BL_POWERVR_RENDER_NODE=" + node);
|
||||
// Inner Gamescope/Xwayland lacks the bridge's Android-buffer WSI protocols.
|
||||
environment.add("BL_STEAM_GL_PRESENT=1");
|
||||
// Only actual Proton game launches use the bundled DXVK and X11 WSI layer.
|
||||
environment.add("DROIDDECK_POWERVR_RUNTIME=" + directory.getPath());
|
||||
}
|
||||
}
|
||||
@@ -25,9 +25,10 @@ import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipInputStream;
|
||||
|
||||
/**
|
||||
* The Vulkan driver the in-app compositor runs on. It has to be Turnip: the system Adreno driver
|
||||
* The Vulkan driver the in-app compositor runs on. Adreno uses Turnip: the system Adreno driver
|
||||
* does not implement VK_EXT_image_drm_format_modifier, so importing the dma-bufs gamescope hands
|
||||
* over fails and the session renders nothing. Two builds ship in the apk, one per Adreno
|
||||
* over fails and the session renders nothing. PowerVR uses the system driver and Android hardware
|
||||
* buffers instead. Two Turnip builds ship in the apk, one per Adreno
|
||||
* generation, and the GPU decides which is unpacked - unless the user has imported an AdrenoTools
|
||||
* zip of their own and chosen it, which then wins.
|
||||
*
|
||||
@@ -314,7 +315,24 @@ public final class TurnipDriver {
|
||||
* and falls through, so a stale preference never blocks a session.
|
||||
*/
|
||||
private String choose() {
|
||||
SessionPrefs.ensurePowerVrAutoDrivers(context);
|
||||
String chosen = SessionPrefs.androidDriver(context);
|
||||
// Mali (Venus): the phone's own driver draws the screen, as Venus replays on it.
|
||||
if (com.droiddeck.launcher.session.VenusComponent.wanted(context)) {
|
||||
Log.i(TAG, "Mali (Venus): display on the system Vulkan loader");
|
||||
return null;
|
||||
}
|
||||
// A Mali under Auto draws its display on Android's own Vulkan loader, whatever an earlier
|
||||
// build set: a PanVK Android half fails on Mali gralloc. A manual pick is respected.
|
||||
if (chosen != null && !chosen.isEmpty() && new File("/dev/mali0").exists()
|
||||
&& !com.droiddeck.launcher.core.DeviceSupport.INSTANCE.adreno()
|
||||
&& SessionPrefs.GPU_DRIVERS_AUTO.equals(SessionPrefs.INSTANCE.gpuDriverMode(context))) {
|
||||
DriverBundle.Bundle bundle = DriverBundle.INSTANCE.containing(context, chosen, false);
|
||||
if (bundle != null && DriverPairs.INSTANCE.isNonAdreno(bundle.getId())) {
|
||||
Log.i(TAG, "Mali under Auto: display on the system Vulkan loader, not " + chosen);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
if (chosen != null && !chosen.isEmpty()) {
|
||||
if (BUNDLED.contains(chosen)) {
|
||||
Log.i(TAG, "driver pinned by the user: " + chosen);
|
||||
@@ -339,6 +357,14 @@ public final class TurnipDriver {
|
||||
if (forced.startsWith("a8")) return DRIVER_A8XX;
|
||||
if (forced.startsWith("a7")) return DRIVER_A7XX;
|
||||
}
|
||||
if (SystemVulkanDriver.isPowerVr()) return null;
|
||||
// Not an Adreno (Mali, Xclipse...): Turnip cannot open a GPU without KGSL. The compositor
|
||||
// runs on the phone's own driver, which has the dma-buf import it needs (the Mali bridge
|
||||
// depends on it too).
|
||||
if (!com.droiddeck.launcher.core.DeviceSupport.INSTANCE.adreno()) {
|
||||
Log.i(TAG, "no KGSL: the compositor uses the system Vulkan driver");
|
||||
return null;
|
||||
}
|
||||
String model = gpuModel();
|
||||
Log.i(TAG, "gpu model: " + (model == null ? "unknown" : model));
|
||||
if (model != null) {
|
||||
|
||||
@@ -43,7 +43,8 @@ object TurnipReleases {
|
||||
/** What an asset is: a Linux build or not, the menu label, and the pair it belongs to. */
|
||||
private class Kind(val linux: Boolean, val label: String, val pair: String, val bundle: Boolean = false)
|
||||
|
||||
private class Source(val label: String, val repo: String, val classify: (name: String, tag: String) -> Kind?)
|
||||
/** [prerelease]: a source whose bundles are all test builds offers them from pre-releases too. */
|
||||
private class Source(val label: String, val repo: String, val prerelease: Boolean = false, val classify: (name: String, tag: String) -> Kind?)
|
||||
|
||||
private val SOURCES = listOf(
|
||||
// Turnip-<tag>[-variant][-Linux|-Wayland].zip; -Wayland is for a path this app does not have.
|
||||
@@ -77,8 +78,22 @@ object TurnipReleases {
|
||||
if (!Regex("""^DD-Turnip-v\d+\.\d+\.\d+\.zip$""").matches(name)) return@Source null
|
||||
Kind(false, "Android + Linux · all Adreno", DriverPairs.ddTurnip(tag), bundle = true)
|
||||
},
|
||||
// <Id>-Pair.zip: open drivers for GPUs that are not Adreno (PanVK for Mali, RADV for
|
||||
// Xclipse), both halves in one zip. One release per driver, replaced in place on each
|
||||
// rebuild; every one is a test build, published as a pre-release.
|
||||
Source("Non-Adreno", NON_ADRENO_REPO, prerelease = true) { name, _ ->
|
||||
val m = Regex("""^(RADV-Xclipse|PanVK-[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*?)-Pair\.zip$""").find(name) ?: return@Source null
|
||||
val key = DriverPairs.nonAdreno(m.groupValues[1])
|
||||
Kind(false, "Android + Linux · " + DriverPairs.nonAdrenoName(key), key, bundle = true)
|
||||
},
|
||||
)
|
||||
|
||||
private const val NON_ADRENO_REPO = "The412Banner/droiddeck-nonadreno-drivers"
|
||||
|
||||
/** The sources this device reads: an Adreno never asks the non-Adreno repo, so its list is as before. */
|
||||
private fun sources(): List<Source> =
|
||||
if (com.droiddeck.launcher.core.DeviceSupport.adreno()) SOURCES.filter { it.repo != NON_ADRENO_REPO } else SOURCES
|
||||
|
||||
/** The result of the last check, or null when the user has never checked. */
|
||||
fun cached(context: Context): Check? {
|
||||
val raw = prefs(context).getString(KEY_RELEASE, null) ?: return null
|
||||
@@ -94,7 +109,8 @@ object TurnipReleases {
|
||||
val latest = JSONArray()
|
||||
val failed = ArrayList<String>()
|
||||
var lastError: Exception? = null
|
||||
for (src in SOURCES) {
|
||||
val sources = sources()
|
||||
for (src in sources) {
|
||||
try {
|
||||
val releases = JSONArray(get(context, "https://api.github.com/repos/${src.repo}/releases?per_page=15"))
|
||||
val seen = HashSet<String>()
|
||||
@@ -110,7 +126,7 @@ object TurnipReleases {
|
||||
val name = a.getString("name")
|
||||
val kind = src.classify(name, tag) ?: continue
|
||||
// A bundle is only offered from an official release, never a pre-release.
|
||||
if (kind.bundle && r.optBoolean("prerelease")) continue
|
||||
if (kind.bundle && r.optBoolean("prerelease") && !src.prerelease) continue
|
||||
val linux = kind.linux
|
||||
val label = kind.label
|
||||
// Only assets GitHub has a sha256 for are offered: the download is checked against it.
|
||||
@@ -129,7 +145,7 @@ object TurnipReleases {
|
||||
lastError = e
|
||||
}
|
||||
}
|
||||
if (failed.size == SOURCES.size) throw lastError ?: IOException("no source answered")
|
||||
if (failed.size == sources.size) throw lastError ?: IOException("no source answered")
|
||||
val stored = JSONObject().put("assets", assets).put("latest", latest)
|
||||
.put("failed", JSONArray(failed)).put("checkedAt", System.currentTimeMillis())
|
||||
prefs(context).edit().putString(KEY_RELEASE, stored.toString()).apply()
|
||||
@@ -171,8 +187,16 @@ object TurnipReleases {
|
||||
}
|
||||
|
||||
/** The id an asset was installed as, when it was downloaded before and is still installed. */
|
||||
fun installedId(context: Context, asset: Asset, isInstalled: (String) -> Boolean): String? =
|
||||
downloads(context).optString(asset.name, "").takeIf { it.isNotEmpty() && isInstalled(it) }
|
||||
fun installedId(context: Context, asset: Asset, isInstalled: (String) -> Boolean): String? {
|
||||
val d = downloads(context)
|
||||
// The open non-Adreno drivers are rebuilt in place under the same asset name: one whose
|
||||
// digest changed since it was downloaded counts as not installed, so it is fetched again.
|
||||
if (DriverPairs.isNonAdreno(asset.pair) && asset.sha256.isNotEmpty() &&
|
||||
!asset.sha256.equals(d.optString(SHA_PREFIX + asset.name, asset.sha256), ignoreCase = true)) return null
|
||||
return d.optString(asset.name, "").takeIf { it.isNotEmpty() && isInstalled(it) }
|
||||
}
|
||||
|
||||
private const val SHA_PREFIX = "sha256:"
|
||||
|
||||
/** True when [id] came from a release download rather than a zip picked by hand. */
|
||||
fun isDownloaded(context: Context, id: String): Boolean {
|
||||
@@ -181,7 +205,9 @@ object TurnipReleases {
|
||||
}
|
||||
|
||||
fun recordDownload(context: Context, asset: Asset, id: String) {
|
||||
prefs(context).edit().putString(KEY_DOWNLOADS, downloads(context).put(asset.name, id).toString()).apply()
|
||||
val d = downloads(context).put(asset.name, id)
|
||||
if (DriverPairs.isNonAdreno(asset.pair) && asset.sha256.isNotEmpty()) d.put(SHA_PREFIX + asset.name, asset.sha256)
|
||||
prefs(context).edit().putString(KEY_DOWNLOADS, d.toString()).apply()
|
||||
}
|
||||
|
||||
/** Forget a deleted driver, so its release offers the download again. */
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
package com.droiddeck.launcher.gpu
|
||||
|
||||
import android.os.Process
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.core.HostProcess
|
||||
import com.droiddeck.launcher.core.SessionPart
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* The Vulkan bridge server (tools/vkbridge, app/src/main/cpp/vkbridge) for one session.
|
||||
*
|
||||
* On a GPU without Adreno's KGSL nothing inside the Linux runtime can reach the GPU: Turnip needs
|
||||
* KGSL, and the phone's own driver is a bionic library a glibc program cannot load. The server is
|
||||
* a bionic process the app starts here - executed from the native library directory like the
|
||||
* DirectAudio relay - which loads the system Vulkan loader and runs the Vulkan calls the
|
||||
* session's programs send it through the bridge ICD over a Unix socket. It is the app's child, so
|
||||
* it dies with the app (it also asks for that with PR_SET_PDEATHSIG).
|
||||
*
|
||||
* Started before the guest and waited for: the server runs a self-test first (which memory
|
||||
* sharing works on this GPU), and only then listens; a program that starts before the socket
|
||||
* exists would find no Vulkan driver.
|
||||
*/
|
||||
class VkBridgeComponent(private val socket: File, private val logFile: File) : SessionPart() {
|
||||
@Volatile private var pid = -1
|
||||
@Volatile private var exited = false
|
||||
|
||||
override fun start() {
|
||||
stop()
|
||||
val binary = File(app().applicationInfo.nativeLibraryDir, BINARY)
|
||||
if (!binary.isFile) {
|
||||
Log.e(TAG, "server missing at $binary; the session will have no Vulkan")
|
||||
return
|
||||
}
|
||||
socket.parentFile?.mkdirs()
|
||||
// Pipeline cache kept across sessions (Mali recompiles everything in a new process otherwise).
|
||||
val cacheDir = File(app().cacheDir, "vkbridge-pipelines").apply { mkdirs() }
|
||||
if (VkBridgeNative.start(app(), socket, logFile, cacheDir)) {
|
||||
Log.i(TAG, "server ready in the app's process at $socket")
|
||||
return
|
||||
}
|
||||
socket.delete()
|
||||
exited = false
|
||||
val cmd = listOf(binary.absolutePath, "--socket", socket.absolutePath, "--log", logFile.absolutePath,
|
||||
"--cache-dir", cacheDir.absolutePath)
|
||||
.joinToString(" ") { it.replace("\\", "\\\\").replace(" ", "\\ ") }
|
||||
val env = arrayOf("HOME=" + app().filesDir)
|
||||
pid = HostProcess.start(cmd, env, app().filesDir, { status ->
|
||||
exited = true
|
||||
Log.w(TAG, "server exited with status $status")
|
||||
runCatching { logFile.appendText("== vkbridge server exited with status $status\n") }
|
||||
}, { line -> Log.i(TAG, line) })
|
||||
// The self-test takes about a second; a cold driver can take longer.
|
||||
val deadline = System.currentTimeMillis() + 15_000L
|
||||
while (!socket.exists() && !exited && System.currentTimeMillis() < deadline) {
|
||||
try { Thread.sleep(50L) } catch (e: InterruptedException) { Thread.currentThread().interrupt(); break }
|
||||
}
|
||||
Log.i(TAG, if (socket.exists()) "server ready (pid $pid) at $socket" else "server NOT ready (pid $pid, exited=$exited); see $logFile")
|
||||
}
|
||||
|
||||
override fun stop() {
|
||||
// The in-app server outlives sessions: its socket stays.
|
||||
if (pid > 0) {
|
||||
Process.killProcess(pid)
|
||||
pid = -1
|
||||
}
|
||||
if (!VkBridgeNative.serving) socket.delete()
|
||||
}
|
||||
|
||||
override fun suspendPid(): Int = pid
|
||||
|
||||
companion object {
|
||||
private const val TAG = "VkBridge"
|
||||
/** The server, named as a library so Android extracts it and lets the app run it. */
|
||||
const val BINARY = "libvkbridge_server.so"
|
||||
/** Inside the runtime (staged by SessionFiles). */
|
||||
const val GUEST_ICD = "/usr/local/share/vkbridge/droidbridge_icd.json"
|
||||
const val GUEST_LIB = "/usr/local/lib/vkbridge/libvulkan_droidbridge.so"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package com.droiddeck.launcher.gpu
|
||||
|
||||
import android.content.Context
|
||||
import android.content.pm.ApplicationInfo
|
||||
import android.util.Log
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* The bridge server inside the app's own process (libvkbridge_jni.so, server_main.c).
|
||||
*
|
||||
* Android chooses the GPU driver - Samsung's updatable one included - while the app starts up, and
|
||||
* only for the app's process: the server run as a separate executable got the plain /vendor driver,
|
||||
* which on the Tab S10+ lacked VK_EXT_robustness2 and more that the app itself sees. Started by the
|
||||
* first bridge session and kept for the app's life; later sessions only point its log at their
|
||||
* own folder. VkBridgeComponent falls back to the executable when this cannot start.
|
||||
*/
|
||||
object VkBridgeNative {
|
||||
private const val TAG = "VkBridge"
|
||||
|
||||
@Volatile private var loaded: Boolean? = null
|
||||
|
||||
/**
|
||||
* The packaged library, or - in a debuggable build only - files/vkbridge/dev/libvkbridge_jni.so
|
||||
* when present, so a rebuilt server can be tried with `adb push` + `run-as cp` and an app
|
||||
* restart instead of a new APK (the app targets SDK 28 and may load code from its files).
|
||||
*/
|
||||
private fun load(context: Context): Boolean {
|
||||
loaded?.let { return it }
|
||||
val ok = try {
|
||||
val dev = File(context.filesDir, "vkbridge/dev/libvkbridge_jni.so")
|
||||
val debuggable = context.applicationInfo.flags and ApplicationInfo.FLAG_DEBUGGABLE != 0
|
||||
if (debuggable && dev.isFile) {
|
||||
Log.w(TAG, "in-app server from the development override $dev")
|
||||
System.load(dev.absolutePath)
|
||||
} else {
|
||||
System.loadLibrary("vkbridge_jni")
|
||||
}
|
||||
true
|
||||
} catch (e: Throwable) {
|
||||
Log.w(TAG, "in-app server unavailable: $e")
|
||||
false
|
||||
}
|
||||
loaded = ok
|
||||
return ok
|
||||
}
|
||||
|
||||
/** Whether the in-app server is serving (its socket must then be left alone). */
|
||||
@Volatile var serving = false
|
||||
private set
|
||||
|
||||
/** Starts the server, or points its log at [log] when it already runs; false when it cannot serve. */
|
||||
fun start(context: Context, socket: File, log: File, cacheDir: File): Boolean {
|
||||
if (!load(context)) return false
|
||||
val ok = try {
|
||||
nativeStart(socket.absolutePath, log.absolutePath, cacheDir.absolutePath) == 1
|
||||
} catch (e: Throwable) {
|
||||
Log.w(TAG, "in-app server failed to start: $e")
|
||||
false
|
||||
}
|
||||
if (ok) serving = true
|
||||
return ok
|
||||
}
|
||||
|
||||
@JvmStatic private external fun nativeStart(socket: String, log: String, cacheDir: String): Int
|
||||
}
|
||||
@@ -229,6 +229,7 @@ object BwrapSpawner {
|
||||
* own choice of driver (VK_ICD_FILENAMES, MESA_LOADER_DRIVER_OVERRIDE) is left alone.
|
||||
*/
|
||||
private fun gpu(rootfs: String, root: File, env: MutableMap<String, String>): List<Bind>? {
|
||||
env["VKBRIDGE_SOCKET"]?.let { sock -> if (File(sock).exists()) return bridgeGpu(rootfs, root, env, sock) }
|
||||
val lib = File(rootfs, "usr/lib")
|
||||
val driver = File(lib, "libvulkan_freedreno.so")
|
||||
if (!driver.isFile || !File("/dev/kgsl-3d0").exists()) return null
|
||||
@@ -258,6 +259,32 @@ object BwrapSpawner {
|
||||
return binds
|
||||
}
|
||||
|
||||
/**
|
||||
* The GPU through the Mali bridge (tools/vkbridge), for a sandbox started from a bridge
|
||||
* session: the bridge ICD (it needs nothing but libc) and the server's socket, at the paths
|
||||
* the session uses. Unlike Turnip on KGSL it can also present to KWin's shared-memory
|
||||
* windows, so desktop apps get it too. The session's own VK_DRIVER_FILES points at the
|
||||
* runtime's copy of the manifest, which the sandbox cannot see; it is replaced here.
|
||||
*/
|
||||
private fun bridgeGpu(rootfs: String, root: File, env: MutableMap<String, String>, socket: String): List<Bind>? {
|
||||
val driver = File(rootfs, "usr/local/lib/vkbridge/libvulkan_droidbridge.so")
|
||||
if (!driver.isFile) { Log.w(TAG, "gpu: vkbridge session but no bridge ICD in the runtime"); return null }
|
||||
val binds = ArrayList<Bind>()
|
||||
binds.add(Bind(driver.canonicalPath, "$GPU_DIR/libvulkan_droidbridge.so"))
|
||||
val sockDir = File(socket).parent ?: return null
|
||||
binds.add(Bind(sockDir, sockDir))
|
||||
val icd = File(root.parentFile, "vkbridge_icd.json")
|
||||
icd.writeText("{\"file_format_version\": \"1.0.0\", \"ICD\": {\"library_path\": \"$GPU_DIR/libvulkan_droidbridge.so\", \"api_version\": \"1.3.247\"}}\n")
|
||||
binds.add(Bind(icd.path, "$GPU_DIR/vkbridge_icd.json"))
|
||||
env["VK_DRIVER_FILES"] = "$GPU_DIR/vkbridge_icd.json"
|
||||
env["VK_ICD_FILENAMES"] = "$GPU_DIR/vkbridge_icd.json"
|
||||
if (!env.containsKey("MESA_LOADER_DRIVER_OVERRIDE") && !env.containsKey("GALLIUM_DRIVER")) {
|
||||
env["MESA_LOADER_DRIVER_OVERRIDE"] = "zink"
|
||||
env["GALLIUM_DRIVER"] = "zink"
|
||||
}
|
||||
return binds
|
||||
}
|
||||
|
||||
/**
|
||||
* What every program in the session preloads (SessionFiles writes /etc/ld.so.preload): the
|
||||
* session shim - SysV shared memory for X11, the network calls Android refuses - and the
|
||||
|
||||
@@ -6,6 +6,7 @@ import android.system.ErrnoException;
|
||||
import android.system.Os;
|
||||
import android.system.StructStat;
|
||||
import android.system.StructUtsname;
|
||||
import com.droiddeck.launcher.gpu.SystemVulkanDriver;
|
||||
import com.droiddeck.launcher.session.SessionPrefs;
|
||||
|
||||
|
||||
@@ -200,12 +201,23 @@ public final class LinuxRuntime {
|
||||
bind(cmd, "/dev");
|
||||
bind(cmd, "/proc");
|
||||
bind(cmd, "/sys");
|
||||
if (com.droiddeck.launcher.gpu.SystemVulkanDriver.isPowerVr()) {
|
||||
// The glibc bridge loads the device's existing Android HAL and its dependencies.
|
||||
// These read-only Android partitions remain subject to the app's normal permissions.
|
||||
for (String path : new String[]{"/system", "/vendor", "/apex", "/system_ext", "/product", "/odm"})
|
||||
if (new File(path).isDirectory()) bind(cmd, path);
|
||||
if (new File("/linkerconfig/ld.config.txt").isFile()) bind(cmd, "/linkerconfig/ld.config.txt");
|
||||
}
|
||||
bind(cmd, "/dev/urandom:/dev/random");
|
||||
bind(cmd, "/proc/self/fd:/dev/fd");
|
||||
bind(cmd, "/proc/self/fd/0:/dev/stdin");
|
||||
bind(cmd, "/proc/self/fd/1:/dev/stdout");
|
||||
bind(cmd, "/proc/self/fd/2:/dev/stderr");
|
||||
bind(cmd, new File(root, "etc/droiddeck/empty").getPath() + ":/sys/fs/selinux");
|
||||
// A kernel that refuses to list /sys/class/thermal (Pixel 10, Android 17) made mangoapp abort
|
||||
// at start ("filesystem_error ... Permission denied: '/sys/class/thermal/'") until its
|
||||
// wrapper gave up: it lists the directory for CPU temperatures. Empty there instead.
|
||||
if (new File("/sys/class/thermal").list() == null) bind(cmd, new File(root, "etc/droiddeck/empty").getPath() + ":/sys/class/thermal");
|
||||
bind(cmd, context.getFilesDir().getPath());
|
||||
bind(cmd, context.getCacheDir().getPath());
|
||||
if (runtimeDir != null) {
|
||||
@@ -277,7 +289,11 @@ public final class LinuxRuntime {
|
||||
bind(cmd, fake.getPath() + ":" + entry[1]);
|
||||
}
|
||||
}
|
||||
bindGpuNode(context, cmd);
|
||||
if (com.droiddeck.launcher.gpu.SystemVulkanDriver.isPowerVr()) {
|
||||
bindPowerVrGpuNode(context, cmd);
|
||||
} else {
|
||||
bindGpuNode(context, cmd);
|
||||
}
|
||||
bindAdrenoStats(cmd, extraBinds);
|
||||
bindCpuTemps(cmd, root);
|
||||
if (extraBinds != null) {
|
||||
@@ -288,6 +304,30 @@ public final class LinuxRuntime {
|
||||
return specs;
|
||||
}
|
||||
|
||||
/**
|
||||
* Tensor's render node is accessible directly, but Android denies listing its parent
|
||||
* directory. libdrm enumerates that directory even when given the device number. Expose
|
||||
* the real node through a listable private directory; retain its real sysfs identity.
|
||||
*/
|
||||
private static void bindPowerVrGpuNode(Context context, List<String> cmd) {
|
||||
if (new File("/dev/dri").list() != null) return;
|
||||
String node = SystemVulkanDriver.renderNodePath();
|
||||
if (node == null) return;
|
||||
String name = new File(node).getName();
|
||||
// Keep only this node listable even if a previous boot assigned a different minor.
|
||||
File dri = new File(context.getCacheDir(), "powervr-drm/" + name + "/dri");
|
||||
try {
|
||||
if (!dri.isDirectory() && !dri.mkdirs()) return;
|
||||
new File(dri, name).createNewFile();
|
||||
} catch (IOException e) {
|
||||
android.util.Log.w("LinuxRuntime", "Cannot expose the PowerVR render node", e);
|
||||
return;
|
||||
}
|
||||
bind(cmd, dri.getPath() + ":/dev/dri");
|
||||
bind(cmd, node + ":" + node);
|
||||
android.util.Log.i("LinuxRuntime", "PowerVR: exposing real " + name + " through a listable directory");
|
||||
}
|
||||
|
||||
/**
|
||||
* An app process may not open {@code /dev/dri} - the nodes exist but are labelled
|
||||
* {@code graphics_device}, which stock policy grants surfaceflinger and not us - yet libdrm and
|
||||
@@ -296,10 +336,43 @@ public final class LinuxRuntime {
|
||||
* may open) stands in: it appears as a render node with the sysfs entries libdrm reads, and our
|
||||
* Turnip build reports the same device numbers for it.
|
||||
*/
|
||||
/** Mali's kbase device, the stand-in render node on a Mali GPU (the Mali bridge's gamescope). */
|
||||
public static final String MALI_DEVICE = "/dev/mali0";
|
||||
|
||||
/**
|
||||
* The device that stands in for the GPU's render node: KGSL on an Adreno; with the Mali bridge
|
||||
* on, Mali's own device - nothing inside opens it for rendering (the bridge does that on the
|
||||
* Android side), but gamescope and libdrm need a render node to name before they offer
|
||||
* linux-dmabuf, and the bridge ICD reports this one's numbers. Null when there is none.
|
||||
*/
|
||||
public static String gpuStandIn(Context context) {
|
||||
if (new File(KGSL_DEVICE).exists()) return KGSL_DEVICE;
|
||||
if (com.droiddeck.launcher.core.DeviceSupport.INSTANCE.vkBridge(context) && new File(MALI_DEVICE).exists()) return MALI_DEVICE;
|
||||
// An open Mali driver pair (PanVK on kbase): gamescope needs a DRM node for the device the
|
||||
// driver reports, and the driver reports /dev/mali0's numbers as its primary and render node.
|
||||
if (com.droiddeck.launcher.core.DeviceSupport.INSTANCE.openDriverActive(context) && new File(MALI_DEVICE).exists()) return MALI_DEVICE;
|
||||
return null;
|
||||
}
|
||||
|
||||
/** "major:minor" of a device node, or null. */
|
||||
public static String deviceNumbers(String path) {
|
||||
try {
|
||||
long dev = Os.stat(path).st_rdev;
|
||||
long major = ((dev >> 8) & 0xfff) | ((dev >> 32) & ~0xfffL);
|
||||
long minor = (dev & 0xff) | ((dev >> 12) & ~0xffL);
|
||||
return major + ":" + minor;
|
||||
} catch (ErrnoException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static void bindGpuNode(Context context, List<String> cmd) {
|
||||
String standIn = gpuStandIn(context);
|
||||
if (standIn == null) return;
|
||||
boolean kgsl = standIn.equals(KGSL_DEVICE);
|
||||
StructStat st;
|
||||
try {
|
||||
st = Os.stat(KGSL_DEVICE);
|
||||
st = Os.stat(standIn);
|
||||
} catch (ErrnoException e) {
|
||||
return;
|
||||
}
|
||||
@@ -319,7 +392,8 @@ public final class LinuxRuntime {
|
||||
Files.write(new File(drm, "dev").toPath(),
|
||||
(major + ":" + minor + "\n").getBytes(StandardCharsets.UTF_8));
|
||||
Files.write(new File(device, "uevent").toPath(),
|
||||
"DRIVER=kgsl-3d0\nMODALIAS=platform:kgsl-3d0\n".getBytes(StandardCharsets.UTF_8));
|
||||
(kgsl ? "DRIVER=kgsl-3d0\nMODALIAS=platform:kgsl-3d0\n" : "DRIVER=mali\nMODALIAS=platform:mali\n")
|
||||
.getBytes(StandardCharsets.UTF_8));
|
||||
File subsystem = new File(device, "subsystem");
|
||||
if (!Files.isSymbolicLink(subsystem.toPath())) {
|
||||
Os.symlink("/sys/bus/platform", subsystem.getPath());
|
||||
@@ -327,7 +401,7 @@ public final class LinuxRuntime {
|
||||
// What MangoHud names a GPU's driver by; msm_drm is how an Adreno's render node reads
|
||||
// on a mainline kernel, and the driver it reads the load of (bindAdrenoStats).
|
||||
File driver = new File(device, "driver");
|
||||
if (!Files.isSymbolicLink(driver.toPath())) {
|
||||
if (kgsl && !Files.isSymbolicLink(driver.toPath())) {
|
||||
Os.symlink("/sys/bus/platform/drivers/msm_drm", driver.getPath());
|
||||
}
|
||||
} catch (IOException | ErrnoException e) {
|
||||
@@ -335,7 +409,7 @@ public final class LinuxRuntime {
|
||||
}
|
||||
bind(cmd, new File(base, "sys").getPath() + ":/sys/dev/char");
|
||||
bind(cmd, dri.getPath() + ":/dev/dri");
|
||||
bind(cmd, KGSL_DEVICE + ":/dev/dri/" + node);
|
||||
bind(cmd, standIn + ":/dev/dri/" + node);
|
||||
bindDrmClass(base, cmd, node, major + ":" + minor);
|
||||
}
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@ import com.droiddeck.launcher.core.Downloader
|
||||
import com.droiddeck.launcher.core.FileUtils
|
||||
import com.droiddeck.launcher.core.GameEnvironment
|
||||
import com.droiddeck.launcher.gpu.GpuInfo
|
||||
import com.droiddeck.launcher.gpu.SystemVulkanDriver
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import com.github.luben.zstd.ZstdInputStream
|
||||
import com.github.luben.zstd.ZstdOutputStream
|
||||
@@ -219,9 +220,13 @@ object ComponentsManager {
|
||||
COMPONENTS.mapNotNull { comp -> profile.optString(comp).takeIf(String::isNotEmpty)?.let { comp to it } }.toMap()
|
||||
}
|
||||
|
||||
fun setGameComponent(context: Context, scope: String, comp: String, file: String?) = synchronized(lock) {
|
||||
fun setGameComponent(context: Context, scope: String, comp: String, file: String?) =
|
||||
setGameComponent(context, scope, comp, file) { runtimeManaged(context, it) }
|
||||
|
||||
internal fun setGameComponent(context: Context, scope: String, comp: String, file: String?, managed: (String) -> Boolean) = synchronized(lock) {
|
||||
require(scope.matches(Regex("[1-9][0-9]{0,9}")) && scope.toLong() <= 4294967295L)
|
||||
require(comp in COMPONENTS)
|
||||
if (file != null) requireSelectable(context, comp, managed)
|
||||
val state = loadState(context)
|
||||
val profiles = state.sub("profiles")
|
||||
val profile = profiles.optJSONObject(scope) ?: JSONObject().also { profiles.put(scope, it) }
|
||||
@@ -694,6 +699,16 @@ object ComponentsManager {
|
||||
return PreparedLaunchState(lines.toString(), keep)
|
||||
}
|
||||
|
||||
/** DXVK is supplied at game launch by the selected system PowerVR runtime. */
|
||||
internal fun runtimeManaged(comp: String, systemPowerVr: Boolean): Boolean = comp == "dxvk" && systemPowerVr
|
||||
|
||||
private fun runtimeManaged(context: Context, comp: String): Boolean =
|
||||
runtimeManaged(comp, SystemVulkanDriver.usesDefault(SessionPrefs.linuxDriver(context)))
|
||||
|
||||
private fun requireSelectable(context: Context, comp: String, managed: (String) -> Boolean = { runtimeManaged(context, it) }) {
|
||||
check(!managed(comp)) { context.getString(R.string.cmgr_powervr_dxvk_managed) }
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ actions
|
||||
|
||||
/** Applies a package now, or queues it when a game is running on that Proton. Returns what happened. */
|
||||
@@ -701,6 +716,7 @@ object ComponentsManager {
|
||||
val p = proton(context, protonId)
|
||||
val wcp = File(packagesDir(context), safeName(file))
|
||||
val info = packageInfo(context, wcp)
|
||||
requireSelectable(context, info.comp)
|
||||
val state = loadState(context)
|
||||
if (inUse(context, p)) {
|
||||
state.sub("queued").sub(p.id).put(info.comp, JSONObject().put("kind", "package").put("file", wcp.name).put("label", info.version))
|
||||
@@ -724,6 +740,7 @@ object ComponentsManager {
|
||||
}
|
||||
|
||||
fun restore(context: Context, protonId: String, comp: String, protonVersion: String): String = synchronized(lock) {
|
||||
requireSelectable(context, comp)
|
||||
val p = proton(context, protonId)
|
||||
val wcp = File(originalsDir(context), "$protonId/${safeName(protonVersion)}/$comp.wcp")
|
||||
check(wcp.isFile) { context.getString(R.string.cmgr_original_missing) }
|
||||
@@ -750,7 +767,9 @@ object ComponentsManager {
|
||||
}
|
||||
|
||||
/** Runs the swaps that waited for a game to close. Cheap when nothing is queued. */
|
||||
fun applyQueued(context: Context): List<String> = synchronized(lock) {
|
||||
fun applyQueued(context: Context): List<String> = applyQueued(context) { runtimeManaged(context, it) }
|
||||
|
||||
internal fun applyQueued(context: Context, managed: (String) -> Boolean): List<String> = synchronized(lock) {
|
||||
val state = loadState(context)
|
||||
val queued = state.sub("queued")
|
||||
if (queued.length() == 0) return emptyList()
|
||||
@@ -762,6 +781,7 @@ object ComponentsManager {
|
||||
val comps = queued.optJSONObject(pid) ?: continue
|
||||
for (comp in comps.keys().asSequence().toList()) {
|
||||
val q = comps.optJSONObject(comp) ?: continue
|
||||
if (managed(comp)) continue
|
||||
runCatching {
|
||||
if (q.optString("kind") == "original") {
|
||||
val v = q.optString("protonVersion")
|
||||
|
||||
@@ -0,0 +1,231 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.content.Context
|
||||
import android.os.Build
|
||||
import android.system.Os
|
||||
import com.droiddeck.launcher.core.DeviceSupport
|
||||
import com.droiddeck.launcher.core.FileUtils
|
||||
import com.droiddeck.launcher.gpu.DriverBundle
|
||||
import com.droiddeck.launcher.gpu.DriverPairs
|
||||
import com.droiddeck.launcher.gpu.GpuInfo
|
||||
import com.droiddeck.launcher.gpu.SystemVulkanDriver
|
||||
import com.droiddeck.launcher.gpu.TurnipReleases
|
||||
import com.droiddeck.launcher.gpu.VulkanInfo
|
||||
import java.io.File
|
||||
import java.text.SimpleDateFormat
|
||||
import java.util.Date
|
||||
import java.util.Locale
|
||||
|
||||
/**
|
||||
* graphics-report.txt in each session's folder: which graphics path the session drew with and why,
|
||||
* the GPU and its device nodes, the environment the guest got, and at the end what the compositor
|
||||
* said about its driver. Written for a non-Adreno test report, where a black screen otherwise comes
|
||||
* with nothing to read; the Share logs zip takes the whole folder, so it travels with the logs.
|
||||
* Read-only: nothing here opens a GPU node or changes a setting.
|
||||
*/
|
||||
object GraphicsReport {
|
||||
const val FILE = "graphics-report.txt"
|
||||
const val GAMES_DIR = "games"
|
||||
|
||||
/** One file in games/ past this is cut to its first part at the session's end. */
|
||||
private const val GAME_FILE_MAX = 20L * 1024 * 1024
|
||||
/** All of games/ past this loses its oldest launches. */
|
||||
private const val GAMES_TOTAL_MAX = 120L * 1024 * 1024
|
||||
|
||||
/** The guest keys the report repeats: everything that decides which Vulkan driver loads. */
|
||||
private val ENV_PREFIXES = listOf(
|
||||
"VK_", "BL_VK", "BL_DRM", "BL_VKBRIDGE", "VKBRIDGE", "MESA_", "GALLIUM_", "ZINK", "TU_", "PANVK",
|
||||
"DROIDDECK_POWERVR", "DROIDDECK_HYBRIS", "BL_GAME_LOGS", "LIBGL_", "GAMESCOPE_DISABLE", "XWAYLAND",
|
||||
)
|
||||
|
||||
/** Per-game graphics logs and the guest's Vulkan summary: on for a non-Adreno GPU, or by Setup's switch. */
|
||||
fun detailed(context: Context): Boolean = !DeviceSupport.adreno() || SessionPrefs.detailedGraphicsLogs(context)
|
||||
|
||||
/** For finish(), which runs from the session's end without a context of its own. */
|
||||
@Volatile private var appContext: Context? = null
|
||||
|
||||
/** Writes the start of the report; never throws. */
|
||||
fun begin(context: Context, dir: File, guest: List<String>) {
|
||||
appContext = context.applicationContext
|
||||
runCatching { File(dir, FILE).writeText(start(context, guest)) }
|
||||
.onFailure { android.util.Log.w("GraphicsReport", "could not write $FILE", it) }
|
||||
}
|
||||
|
||||
private fun start(context: Context, guest: List<String>): String = buildString {
|
||||
val time = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US).format(Date())
|
||||
appendLine("== graphics report, session start $time")
|
||||
appendLine("build: ${com.droiddeck.launcher.BuildConfig.BUILD_LABEL} (source ${com.droiddeck.launcher.BuildConfig.SOURCE_COMMIT})")
|
||||
appendLine()
|
||||
val gpu = runCatching { GpuInfo.detect() }.getOrNull()
|
||||
appendLine("-- path")
|
||||
appendLine("path: " + path(context))
|
||||
appendLine("driver mode: " + SessionPrefs.gpuDriverMode(context))
|
||||
appendLine("display driver (compositor): " + SessionPrefs.androidDriver(context).ifEmpty {
|
||||
if (DeviceSupport.adreno()) "(auto: bundled Turnip)" else "(auto: the phone's own Vulkan driver, ${SystemVulkanDriver.hal() ?: "vendor HAL"})"
|
||||
})
|
||||
val display = SessionPrefs.androidDriver(context)
|
||||
appendLine("display driver chosen by: " + when {
|
||||
display.isEmpty() -> "auto (or a pair on a non-Adreno GPU: the phone's own driver)"
|
||||
DriverBundle.containing(context, display, false) != null -> "pair (its display half)"
|
||||
else -> "user (picked on its own)"
|
||||
})
|
||||
val linux = SessionPrefs.linuxDriver(context)
|
||||
appendLine("runtime driver: " + linux.ifEmpty { "(runtime default)" })
|
||||
if (linux.isNotEmpty()) {
|
||||
val dir = com.droiddeck.launcher.gpu.LinuxVulkanDriverManager(context).getDriverDir(linux)
|
||||
appendLine("runtime driver dir: ${dir.path} (" + (dir.listFiles()?.filter { it.name.endsWith(".so") }?.joinToString { it.name } ?: "missing") + ")")
|
||||
}
|
||||
val prefs = context.getSharedPreferences("graphics_report", Context.MODE_PRIVATE)
|
||||
val previous = prefs.getString("lastDrivers", null)
|
||||
val now = "display ${SessionPrefs.androidDriver(context).ifEmpty { "(auto)" }}, runtime ${linux.ifEmpty { "(default)" }}, bridge ${DeviceSupport.vkBridge(context)}, venus ${VenusComponent.wanted(context)}"
|
||||
appendLine("previous session's drivers: " + (previous ?: "(none recorded)") + if (previous != null && previous != now) " << CHANGED" else "")
|
||||
prefs.edit().putString("lastDrivers", now).apply()
|
||||
DriverBundle.active(context)?.let { b ->
|
||||
appendLine("pair: ${b.name} ${b.version} (bundle ${b.id})")
|
||||
release(context, b.id)?.let { appendLine("pair release: $it") }
|
||||
}
|
||||
if (gpu != null) {
|
||||
val pairs = DriverPairs.from(TurnipReleases.cached(context))
|
||||
appendLine("auto would pick: " + (DriverPairs.recommendedKey(gpu, pairs) ?: "(no pair: system driver or bridge)"))
|
||||
}
|
||||
appendLine("frame generation: " + runCatching { com.droiddeck.launcher.gpu.FrameGen.mode(context).toString() }.getOrDefault("?") +
|
||||
" (engine=off means it is switched off in Play settings; a driver that fails LSFG's gates logs \"device gates\" below)")
|
||||
appendLine("mali bridge setting: " + SessionPrefs.vkBridge(context) + ", in use: " + DeviceSupport.vkBridge(context))
|
||||
val standIn = runCatching { com.droiddeck.launcher.runtime.LinuxRuntime.gpuStandIn(context) }.getOrNull()
|
||||
appendLine("render node for the guest: " + (standIn?.let { node ->
|
||||
com.droiddeck.launcher.runtime.LinuxRuntime.deviceNumbers(node)?.let { n -> "/dev/dri/renderD${n.substringAfter(':')} -> $node ($n)" } ?: node
|
||||
} ?: if (SystemVulkanDriver.isPowerVr()) "the system GPU's own /dev/dri node (#570)" else "none"))
|
||||
appendLine()
|
||||
appendLine("-- gpu")
|
||||
if (gpu != null) {
|
||||
appendLine("family: ${gpu.family} (${gpu.supportText})")
|
||||
appendLine("name: ${gpu.name}" + if (gpu.model > 0) ", model ${gpu.model} (${gpu.modelSource})" else "")
|
||||
}
|
||||
appendLine("vulkan device (app): " + (VulkanInfo.cachedOrNull()?.get("device") ?: "(not probed)"))
|
||||
appendLine("system vulkan hal: " + (SystemVulkanDriver.hal() ?: "none"))
|
||||
read("/sys/class/misc/mali0/device/gpuinfo")?.let { appendLine("mali gpuinfo: $it") }
|
||||
appendLine("android: ${Build.VERSION.RELEASE} (sdk ${Build.VERSION.SDK_INT}), ${Build.MANUFACTURER} ${Build.MODEL}")
|
||||
val soc = if (Build.VERSION.SDK_INT >= 31) "${Build.SOC_MANUFACTURER} ${Build.SOC_MODEL}" else Build.HARDWARE
|
||||
appendLine("soc: $soc, board ${Build.BOARD}, hardware ${Build.HARDWARE}")
|
||||
appendLine("kernel: " + (System.getProperty("os.version") ?: "?"))
|
||||
appendLine()
|
||||
appendLine("-- gpu nodes (from the app; not opened)")
|
||||
val dri = File("/dev/dri").list()?.sorted()?.map { "/dev/dri/$it" }.orEmpty()
|
||||
for (path in listOf("/dev/kgsl-3d0", "/dev/mali0") + dri) appendLine(node(path))
|
||||
if (dri.isEmpty()) appendLine("/dev/dri: " + if (File("/dev/dri").exists()) "not listable" else "absent")
|
||||
appendLine()
|
||||
appendLine("-- guest environment (graphics)")
|
||||
guest.filter { e -> ENV_PREFIXES.any { e.startsWith(it) } }.sorted().forEach { appendLine(it) }
|
||||
appendLine()
|
||||
}
|
||||
|
||||
/** Which backend this session's Vulkan goes through, as the session decides it. */
|
||||
private fun path(context: Context): String = when {
|
||||
DeviceSupport.adreno() -> "Turnip (Adreno, KGSL)"
|
||||
VenusComponent.wanted(context) -> "Mali (Venus): Mesa Venus over vtest to the phone's own Vulkan driver, with the Mali compatibility layer"
|
||||
DeviceSupport.vkBridge(context) -> "Mali bridge (#517): the phone's own Vulkan driver through the bridge"
|
||||
DeviceSupport.openDriverActive(context) -> "open driver pair (PanVK / RADV)"
|
||||
SystemVulkanDriver.usesDefault(SessionPrefs.linuxDriver(context)) && SystemVulkanDriver.isAvailable() ->
|
||||
"system Vulkan (#570): ${SystemVulkanDriver.gpuName()} driver through libhybris"
|
||||
SessionPrefs.linuxDriver(context).isNotEmpty() -> "imported runtime driver ${SessionPrefs.linuxDriver(context)}"
|
||||
else -> "none for this GPU (no Adreno, no system HAL, no pair, bridge off)"
|
||||
}
|
||||
|
||||
/** The release tag and download a pair bundle came from, when the last release check knows it. */
|
||||
private fun release(context: Context, bundleId: String): String? {
|
||||
val asset = TurnipReleases.cached(context)?.assets?.firstOrNull { a ->
|
||||
val id = a.name.removeSuffix("-Pair.zip")
|
||||
a.bundle && (bundleId == id || bundleId.startsWith("$id-"))
|
||||
}
|
||||
?: return null
|
||||
return "${asset.tag} ${asset.url}"
|
||||
}
|
||||
|
||||
private fun node(path: String): String {
|
||||
val f = File(path)
|
||||
if (!f.exists()) return "$path: absent"
|
||||
val access = (if (f.canRead()) "r" else "-") + (if (f.canWrite()) "w" else "-")
|
||||
val rdev = runCatching { Os.stat(path).st_rdev }.getOrNull()
|
||||
val numbers = rdev?.let { " ${major(it)}:${minor(it)}" }.orEmpty()
|
||||
val label = runCatching { String(Os.getxattr(path, "security.selinux")).trimEnd('\u0000') }.getOrNull()
|
||||
return "$path: $access$numbers" + (label?.let { " $it" } ?: "")
|
||||
}
|
||||
|
||||
/** Linux's dev_t split (glibc's gnu_dev_major / gnu_dev_minor). */
|
||||
internal fun major(dev: Long): Long = ((dev ushr 8) and 0xfff) or ((dev ushr 32) and 0xfffff000L)
|
||||
internal fun minor(dev: Long): Long = (dev and 0xff) or ((dev ushr 12) and 0xffffff00L)
|
||||
|
||||
private fun read(path: String): String? = FileUtils.readString(File(path))?.trim()?.takeIf { it.isNotEmpty() }
|
||||
|
||||
/** The compositor's driver lines from the app's own log. */
|
||||
private val COMPOSITOR = Regex(
|
||||
"""vk_present|waylandcomp|vk_loader|compositor|vkCreateDevice|extension|adrenotools|TurnipDriver|""" +
|
||||
"""graphics driver|SystemVulkan|vkbridge|VkBridge|mali_gralloc|panvk|PanVK|radv|MESA|native buffer|first frame|present|""" +
|
||||
"""lsfg|FrameGen|device gates|AAudio|directaudio|pulse|gralloc|dma.?buf|modifier|import""",
|
||||
RegexOption.IGNORE_CASE,
|
||||
)
|
||||
|
||||
/** The session script's driver lines: what it exported, the bridge's self-test, vulkaninfo, gamescope's Vulkan errors. */
|
||||
private val GUEST = Regex("""== vulkan driver|== vkbridge|== vulkaninfo|vulkan:|panvk|PanVK|radv|primary node|No compatible|DRM format|kbase|AAUDIO|client sink|Xwayland|\(EE\)|glamor|XWAYLAND_NO_GLAMOR""", RegexOption.IGNORE_CASE)
|
||||
|
||||
/**
|
||||
* The end of the report, from the finished folder: the compositor's driver lines out of
|
||||
* app.log, and games/ held to its size limits. Never throws.
|
||||
*/
|
||||
fun finish(dir: File) {
|
||||
runCatching {
|
||||
val report = File(dir, FILE)
|
||||
if (!report.isFile) return
|
||||
val lines = File(dir, "app.log").takeIf { it.isFile }?.useLines { seq -> seq.filter { COMPOSITOR.containsMatchIn(it) }.take(400).toList() }.orEmpty()
|
||||
val games = File(dir, GAMES_DIR).listFiles()?.filter { it.isDirectory }?.sortedBy { it.name }.orEmpty()
|
||||
val guestLines = File(dir, "session.log").takeIf { it.isFile }?.useLines { seq ->
|
||||
seq.filter { GUEST.containsMatchIn(it) }.take(200).toList()
|
||||
}.orEmpty()
|
||||
val fellBack = File(dir, "vkbridge-fallback").takeIf { it.isFile }?.readText()?.trim()
|
||||
runCatching { SessionPrefs.setBridgeFellBack(appContext ?: return@runCatching, fellBack != null) }
|
||||
val limits = File(dir, "limits.txt").takeIf { it.isFile }?.readText()?.trim()
|
||||
val audio = File(dir, "audio.log").takeIf { it.isFile }?.readText().orEmpty()
|
||||
report.appendText(buildString {
|
||||
limits?.let { appendLine("open files limit: $it") }
|
||||
fellBack?.let { appendLine("!! MALI BRIDGE FELL BACK: the self-test failed images or draws; the session ran on $it") }
|
||||
if (audio.contains("AAUDIO_ERROR_DISCONNECTED")) {
|
||||
appendLine("!! SOUND: Android refused the audio output (AAUDIO_ERROR_DISCONNECTED) - rebooting the phone usually fixes this")
|
||||
}
|
||||
if (guestLines.any { it.contains("vkbridge", ignoreCase = true) && it.contains("FAIL") }) {
|
||||
appendLine("!! MALI BRIDGE SELF-TEST FAILED: this GPU's driver did not pass the bridge's checks (see below)")
|
||||
}
|
||||
if (guestLines.any { it.contains("MEM_EXEC_INIT") }) {
|
||||
appendLine("note: kbase refused KBASE_IOCTL_MEM_EXEC_INIT with EPERM. That answer comes from the kbase driver")
|
||||
appendLine(" itself (proot does not filter ioctls; Android's seccomp would kill or return ENOSYS; SELinux")
|
||||
appendLine(" would return EACCES), so it is the kernel's policy for this context, not the session's.")
|
||||
}
|
||||
appendLine("-- driver lines from the session log (${guestLines.size})")
|
||||
guestLines.forEach { appendLine(it) }
|
||||
appendLine()
|
||||
appendLine("-- compositor and driver lines from app.log (${lines.size})")
|
||||
lines.forEach { appendLine(it) }
|
||||
appendLine()
|
||||
appendLine("-- game launches with detailed logs: ${games.size}")
|
||||
games.forEach { appendLine(it.name) }
|
||||
appendLine("== session end " + SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US).format(Date()))
|
||||
})
|
||||
capGames(File(dir, GAMES_DIR))
|
||||
}.onFailure { android.util.Log.w("GraphicsReport", "could not finish $FILE", it) }
|
||||
}
|
||||
|
||||
/** Cuts each file in [games] to [GAME_FILE_MAX] and drops the oldest launches past [GAMES_TOTAL_MAX]. */
|
||||
internal fun capGames(games: File, fileMax: Long = GAME_FILE_MAX, totalMax: Long = GAMES_TOTAL_MAX) {
|
||||
if (!games.isDirectory) return
|
||||
games.walkTopDown().filter { it.isFile && it.length() > fileMax }.forEach { f ->
|
||||
runCatching { java.io.RandomAccessFile(f, "rw").use { it.setLength(fileMax) } }
|
||||
}
|
||||
val launches = games.listFiles()?.filter { it.isDirectory }?.sortedBy { it.name }.orEmpty().toMutableList()
|
||||
fun size(d: File) = d.walkTopDown().filter { it.isFile }.sumOf { it.length() }
|
||||
var total = launches.sumOf { size(it) }
|
||||
while (total > totalMax && launches.size > 1) {
|
||||
val oldest = launches.removeAt(0)
|
||||
total -= size(oldest)
|
||||
FileUtils.delete(oldest)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -27,6 +27,23 @@ object OrphanReaper {
|
||||
|
||||
fun release(pid: Int) { kept.remove(pid) }
|
||||
|
||||
/** Signal 0 checks ownership/liveness without sending a signal, even when /proc is unreadable. */
|
||||
fun hasOtherProcesses(): Boolean = hasOtherProcesses(
|
||||
File("/proc").list()?.mapNotNull { it.toIntOrNull() }, android.os.Process.myPid(),
|
||||
) { pid ->
|
||||
try {
|
||||
android.system.Os.kill(pid, 0)
|
||||
true
|
||||
} catch (error: android.system.ErrnoException) {
|
||||
error.errno != android.system.OsConstants.ESRCH && error.errno != android.system.OsConstants.EPERM
|
||||
} catch (error: SecurityException) {
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
internal fun hasOtherProcesses(pids: List<Int>?, ownPid: Int, signalable: (Int) -> Boolean): Boolean =
|
||||
pids == null || pids.any { it > 1 && it != ownPid && signalable(it) }
|
||||
|
||||
fun reap(reason: String): Int {
|
||||
val me = android.os.Process.myPid()
|
||||
val uid = android.os.Process.myUid()
|
||||
|
||||
@@ -53,6 +53,7 @@ object SessionFiles {
|
||||
"usr/local/bin/droiddeck-msi-install" to "usr/local/bin/droiddeck-msi-install",
|
||||
"usr/local/bin/droiddeck-esync" to "usr/local/bin/droiddeck-esync",
|
||||
"usr/local/bin/droiddeck-steam-compat" to "usr/local/bin/droiddeck-steam-compat",
|
||||
"usr/local/bin/droiddeck-steam-taskset" to "usr/local/libexec/droiddeck-steam/taskset",
|
||||
"usr/local/bin/droiddeck-fex" to "usr/local/bin/droiddeck-fex",
|
||||
"libblsession.so" to "usr/local/lib/libblsession.so",
|
||||
"libfakeinput.so" to "usr/local/lib/libfakeinput.so",
|
||||
@@ -129,6 +130,10 @@ object SessionFiles {
|
||||
"usr/local/lib/mangoapp/libtraceevent.so.1",
|
||||
"usr/local/lib/mangoapp/libtracefs.so.1",
|
||||
).map { it to it }
|
||||
// Samsung Xclipse driver workarounds (tools/linuxfs/xclipse-layer), the Vulkan layer
|
||||
// SystemVulkanDriver enables on that GPU.
|
||||
val xclipse = listOf("libVkLayer_droiddeck_xclipse.so", "VkLayer_droiddeck_xclipse.json")
|
||||
.map { "usr/local/lib/droiddeck-xclipse/$it" }
|
||||
// What the Windows components installer reads .msi packages with (tools/msitools).
|
||||
val msitools = listOf("msiinfo", "cabextract", "7z", "7z.so", "libmsi-1.0.so.0", "libgsf-1.so.114", "libgcab-1.0.so.0")
|
||||
.map { "usr/local/lib/droiddeck-msitools/$it" } +
|
||||
@@ -136,11 +141,23 @@ object SessionFiles {
|
||||
val fexPreloads = listOf("x86_64", "i386").flatMap { arch ->
|
||||
listOf("libblsession.so", "libfakeinput.so", "libfaultreport.so").map { "$arch/$it" to "usr/local/lib/droiddeck-fex/$arch/$it" }
|
||||
} + listOf("libthunkaudit.so", "libvulkan-thunk.so").map { "x86_64/$it" to "usr/local/lib/droiddeck-fex/x86_64/$it" }
|
||||
// The Mali compatibility layer (tools/venus/layer, David Cimo): an implicit Vulkan layer that
|
||||
// fills in the features DXVK requires and Mali lacks. Idle outside Wine and on GPUs that have them.
|
||||
// Never staged on an Adreno: an implicit layer is loaded into every Vulkan program there.
|
||||
val maliCompat = if (com.droiddeck.launcher.core.DeviceSupport.adreno()) emptyList() else listOf(
|
||||
"usr/local/lib/droiddeck-mali/libVkLayer_droiddeck_mali_compat.so",
|
||||
"usr/local/share/vulkan/implicit_layer.d/VkLayer_droiddeck_mali_compat.json",
|
||||
).map { it to it }
|
||||
val optional = (arrayOf(
|
||||
"usr/local/bin/gamescope" to "usr/local/bin/gamescope",
|
||||
// The Mali bridge's Linux side (tools/vkbridge): the ICD, its manifest and the self-test.
|
||||
"usr/local/lib/vkbridge/libvulkan_droidbridge.so" to "usr/local/lib/vkbridge/libvulkan_droidbridge.so",
|
||||
"usr/local/share/vkbridge/droidbridge_icd.json" to "usr/local/share/vkbridge/droidbridge_icd.json",
|
||||
"usr/local/bin/droiddeck-vkbridge-smoke" to "usr/local/bin/droiddeck-vkbridge-smoke",
|
||||
"usr/local/bin/droiddeck-glprobe" to "usr/local/bin/droiddeck-glprobe",
|
||||
"usr/local/lib/droiddeck/uruntime" to "usr/local/lib/droiddeck/uruntime",
|
||||
"usr/local/share/licenses/uruntime/LICENSE" to "usr/local/share/licenses/uruntime/LICENSE",
|
||||
) + mangoapp + listOf("comet", "GalaxyCommunication.exe", "update-permissions.exe", "LICENSE", "version").map { "usr/local/lib/droiddeck-comet/$it" to "usr/local/lib/droiddeck-comet/$it" } + msitools.map { it to it } + fexPreloads).filter { (asset, _) ->
|
||||
) + mangoapp + xclipse.map { it to it } + maliCompat + listOf("comet", "GalaxyCommunication.exe", "update-permissions.exe", "LICENSE", "version").map { "usr/local/lib/droiddeck-comet/$it" to "usr/local/lib/droiddeck-comet/$it" } + msitools.map { it to it } + fexPreloads).filter { (asset, _) ->
|
||||
val dir = asset.substringBeforeLast('/')
|
||||
runCatching { context.assets.list("linuxfs/$dir")?.contains(asset.substringAfterLast('/')) == true }.getOrDefault(false)
|
||||
}
|
||||
|
||||
@@ -8,6 +8,8 @@ import com.droiddeck.launcher.core.CpuAllocationDefaults
|
||||
import com.droiddeck.launcher.core.GameEnvironment
|
||||
import com.droiddeck.launcher.core.TextureFiltering
|
||||
import com.droiddeck.launcher.gpu.ScreenEffects
|
||||
import com.droiddeck.launcher.gpu.SystemVulkanDriver
|
||||
import com.droiddeck.launcher.gpu.TurnipDriver
|
||||
import org.json.JSONObject
|
||||
|
||||
/** The in-session switches: the HUD and how the on-screen controls decide to appear. */
|
||||
@@ -216,6 +218,19 @@ object SessionPrefs {
|
||||
p.edit().putString("gpuDriverMode", if (chosen) GPU_DRIVERS_MANUAL else GPU_DRIVERS_AUTO).apply()
|
||||
}
|
||||
|
||||
/** Also called by direct session launches, which may never open the driver settings. */
|
||||
@JvmStatic
|
||||
fun ensurePowerVrAutoDrivers(context: Context) {
|
||||
// An open driver pair Auto chose for this GPU (RADV on an Xclipse) is not undone here.
|
||||
if (com.droiddeck.launcher.core.DeviceSupport.openDriverActive(context)) return
|
||||
ensurePowerVrAutoDrivers(context, SystemVulkanDriver.isPowerVr())
|
||||
}
|
||||
|
||||
internal fun ensurePowerVrAutoDrivers(context: Context, powerVr: Boolean) {
|
||||
if (!powerVr || gpuDriverMode(context) != GPU_DRIVERS_AUTO) return
|
||||
prefs(context).edit().putString("linuxDriver", "").putString("androidDriver", TurnipDriver.AUTO).apply()
|
||||
}
|
||||
|
||||
/** Drivers Auto downloaded: the only ones it removes when a newer pair replaces them. */
|
||||
fun gpuAutoInstalled(context: Context): Set<String> =
|
||||
prefs(context).getStringSet("gpuAutoInstalled", emptySet()).orEmpty()
|
||||
@@ -486,6 +501,58 @@ object SessionPrefs {
|
||||
*/
|
||||
fun zinkLazy(context: Context): Boolean = prefs(context).getBoolean("zinkLazy", true)
|
||||
|
||||
/**
|
||||
* The Mali bridge (experimental): the session's Vulkan goes through the app's bridge server to
|
||||
* the phone's own driver instead of Turnip (tools/vkbridge). Only offered, and only used, on a
|
||||
* GPU without Adreno's KGSL; off by default everywhere.
|
||||
*/
|
||||
@JvmStatic
|
||||
fun vkBridge(context: Context): Boolean = prefs(context).getBoolean("vkBridge", false)
|
||||
|
||||
/**
|
||||
* Setup's "Mali (Venus)": the session's Vulkan through Mesa's Venus to the phone's own driver
|
||||
* (VenusComponent, David Cimo's route). Off by default; on a GPU that is not an Adreno only.
|
||||
*/
|
||||
fun venus(context: Context): Boolean = prefs(context).getBoolean("venus", false)
|
||||
|
||||
/** The last session's Mali bridge self-test failed and it ran on the pair instead (Setup says so). */
|
||||
fun bridgeFellBack(context: Context): Boolean = prefs(context).getBoolean("bridgeFellBack", false)
|
||||
|
||||
fun setBridgeFellBack(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("bridgeFellBack", on).apply()
|
||||
}
|
||||
|
||||
/**
|
||||
* Setup's "Steam interface: GPU drawing": with an open driver pair the Steam client composites
|
||||
* its web views in software (stale tiles on RADV/Xclipse); this turns GPU compositing back on.
|
||||
*/
|
||||
fun steamGpuCompositing(context: Context): Boolean {
|
||||
if (!steamGpuCompositingAllowed()) {
|
||||
// Never on a Mali: with PanVK it rebooted an Edge 60 (G615) twice as steamwebhelper
|
||||
// started. A value saved by the build that offered it is cleared.
|
||||
if (prefs(context).getBoolean("steamGpuCompositing", false))
|
||||
prefs(context).edit().putBoolean("steamGpuCompositing", false).apply()
|
||||
return false
|
||||
}
|
||||
return prefs(context).getBoolean("steamGpuCompositing", false)
|
||||
}
|
||||
|
||||
/** Setup offers "Steam interface: GPU drawing" on Xclipse (RADV) and other non-Mali, non-Adreno GPUs. */
|
||||
fun steamGpuCompositingAllowed(): Boolean =
|
||||
!com.droiddeck.launcher.core.DeviceSupport.adreno() && !com.droiddeck.launcher.core.DeviceSupport.mali()
|
||||
|
||||
fun setSteamGpuCompositing(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("steamGpuCompositing", on && steamGpuCompositingAllowed()).apply()
|
||||
}
|
||||
|
||||
fun setVenus(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("venus", on).apply()
|
||||
}
|
||||
|
||||
fun setVkBridge(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("vkBridge", on).putBoolean("bridgeFellBack", false).apply()
|
||||
}
|
||||
|
||||
fun setZinkLazy(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("zinkLazy", on).apply()
|
||||
}
|
||||
@@ -524,6 +591,17 @@ object SessionPrefs {
|
||||
prefs(context).edit().putBoolean("logs", on).apply()
|
||||
}
|
||||
|
||||
/**
|
||||
* Detailed graphics logs: per-game Proton, DXVK, vkd3d-proton and driver logs in the session's
|
||||
* folder. Always on for a GPU that is not an Adreno (test drivers); opt-in on an Adreno.
|
||||
*/
|
||||
fun detailedGraphicsLogs(context: Context): Boolean =
|
||||
prefs(context).getBoolean("detailedGraphicsLogs", false)
|
||||
|
||||
fun setDetailedGraphicsLogs(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("detailedGraphicsLogs", on).apply()
|
||||
}
|
||||
|
||||
/** Steam storage-call diagnostics are opt-in because they add timing work to file operations. */
|
||||
fun storageDiagnosticsEnabled(context: Context): Boolean =
|
||||
prefs(context).getBoolean("storageDiagnostics", false)
|
||||
|
||||
@@ -2,6 +2,7 @@ package com.droiddeck.launcher.session
|
||||
|
||||
import com.droiddeck.launcher.gpu.LinuxVulkanDriver
|
||||
import com.droiddeck.launcher.gpu.LinuxVulkanDriverManager
|
||||
import com.droiddeck.launcher.gpu.SystemVulkanDriver
|
||||
|
||||
import android.app.Notification
|
||||
import android.app.NotificationChannel
|
||||
@@ -283,6 +284,7 @@ class SessionService : Service() {
|
||||
*/
|
||||
private fun collectSessionArtifacts(dir: File) {
|
||||
try {
|
||||
GraphicsReport.finish(dir)
|
||||
SessionArtifacts.collect(this, dir, "session stopped")
|
||||
} finally {
|
||||
// Last, so everything above is in the file it is about - and only this session's:
|
||||
@@ -305,7 +307,24 @@ class SessionService : Service() {
|
||||
return lines
|
||||
}
|
||||
|
||||
/** Whether a kernel release ("6.1.157-android14-11") is older than [major].[minor]; false if unreadable. */
|
||||
internal fun kernelBefore(release: String, major: Int, minor: Int): Boolean {
|
||||
val m = Regex("""^(\d+)\.(\d+)""").find(release) ?: return false
|
||||
val (a, b) = m.destructured
|
||||
return a.toInt() < major || (a.toInt() == major && b.toInt() < minor)
|
||||
}
|
||||
|
||||
/** Whether the newest finished session's log shows Xwayland itself crashing. */
|
||||
private fun lastXwaylandCrashed(): Boolean = runCatching {
|
||||
val last = SessionPaths.sessionFolders(this).filter { it != SessionPaths.current() }.lastOrNull() ?: return false
|
||||
val log = File(last, "session.log").takeIf { it.isFile } ?: return false
|
||||
log.useLines { lines -> lines.any { it.contains("(EE) Segmentation fault") } } &&
|
||||
log.useLines { lines -> lines.any { it.contains("X11 I/O error") || it.contains("Xwayland", ignoreCase = true) } }
|
||||
}.getOrDefault(false)
|
||||
|
||||
private fun tuDebug(linuxDriverId: String): String? {
|
||||
// Turnip's switch; a non-Adreno GPU runs another driver (PanVK, RADV, the bridge).
|
||||
if (!com.droiddeck.launcher.core.DeviceSupport.adreno()) return null
|
||||
val override = File(Environment.getExternalStorageDirectory(), TU_DEBUG_SWITCH)
|
||||
.takeIf { it.isFile }?.let { FileUtils.readString(it)?.trim() }
|
||||
if (!override.isNullOrEmpty()) return override
|
||||
@@ -318,6 +337,7 @@ class SessionService : Service() {
|
||||
// ── The session ─────────────────────────────────────────────────────────────────────────
|
||||
|
||||
private fun runSession(gen: Int) {
|
||||
SessionPrefs.ensurePowerVrAutoDrivers(this)
|
||||
SessionTerminal.clear()
|
||||
try {
|
||||
LinuxRuntime.writeAccounts(this)
|
||||
@@ -331,7 +351,17 @@ class SessionService : Service() {
|
||||
val sessionRoot = LinuxRuntime.sessionRoot(this).apply { mkdirs() }
|
||||
val runtimeDir = File(filesDir, ".wayland-rt").apply { mkdirs() }
|
||||
killStragglers()
|
||||
SessionFiles.stage(this, root)
|
||||
try {
|
||||
if (SystemVulkanDriver.usesDefault(SessionPrefs.linuxDriver(this))) {
|
||||
SystemVulkanDriver.prepare(this)
|
||||
pruneSystemVulkanRuntime()
|
||||
}
|
||||
SessionFiles.stage(this, root)
|
||||
} catch (error: Exception) {
|
||||
Log.e(TAG, "Could not prepare the session graphics runtime", error)
|
||||
stopSession(-1)
|
||||
return
|
||||
}
|
||||
com.droiddeck.launcher.agent.AgentGuest.reset(this)
|
||||
// The compat tool asks for an Epic game's sign-in code at every launch, the client's Play button included.
|
||||
com.droiddeck.launcher.stores.gog.GogComet.begin()
|
||||
@@ -360,6 +390,10 @@ class SessionService : Service() {
|
||||
val fastPathAt = guest.size
|
||||
|
||||
val pulse = startAudio(guest, sessionDir)
|
||||
startVkBridge(guest, sessionDir)
|
||||
if (VenusComponent.wanted(this)) {
|
||||
components.add(VenusComponent(File(sessionDir, "venus.log")).also { it.attach(this) })
|
||||
}
|
||||
|
||||
guest.add("BL_WIDTH=" + size.first)
|
||||
guest.add("BL_HEIGHT=" + size.second)
|
||||
@@ -403,6 +437,10 @@ class SessionService : Service() {
|
||||
// The second library's name, for droiddeck-steam-library; the bind itself is made below.
|
||||
GameStorage.effective(this)?.let { guest.add("BL_LIBRARY_LABEL=" + it.label.replace('"', ' ')) }
|
||||
if (SessionState.mode == MODE_STEAM && SessionState.steamUi == "desktop") guest.add("BL_STEAM_UI=desktop")
|
||||
// Detailed graphics logs: per-game logs and the guest's Vulkan summary (a GPU that is not
|
||||
// an Adreno, or Setup's switch), and graphics-report.txt for every session.
|
||||
if (GraphicsReport.detailed(this)) guest.add("BL_GAME_LOGS=1")
|
||||
GraphicsReport.begin(this, sessionDir, guest)
|
||||
val shellGuest = ArrayList(guest).apply {
|
||||
add("SHELL=/bin/bash")
|
||||
add("TERM=xterm-256color")
|
||||
@@ -610,20 +648,74 @@ class SessionService : Service() {
|
||||
guest.add("MESA_LOADER_DRIVER_OVERRIDE=zink")
|
||||
guest.add("GALLIUM_DRIVER=zink")
|
||||
guest.add("LIBGL_KOPPER_DRI2=true")
|
||||
LinuxRuntime.vulkanIcd(this)?.let { guest.add("VK_ICD_FILENAMES=" + it.path) }
|
||||
val venus = VenusComponent.wanted(this)
|
||||
if (venus) {
|
||||
// Mali (Venus): the session's Vulkan is Mesa's Venus ICD over vtest to the phone's driver.
|
||||
VenusComponent.guestEnv(this).forEach { guest.add(it) }
|
||||
} else {
|
||||
LinuxRuntime.vulkanIcd(this)?.let { guest.add("VK_ICD_FILENAMES=" + it.path) }
|
||||
}
|
||||
// An imported glibc Turnip, when one is set (by the user, or by Auto): the session script
|
||||
// checks the manifest and its library from inside and points the loader at it with
|
||||
// VK_DRIVER_FILES, so the runtime's own driver above stays untouched and is what a bad
|
||||
// import falls back to. One driver for every session: the driver's shader cache is keyed on
|
||||
// its build, and with one per mode every emulator compiled its shaders twice.
|
||||
val linuxDriverId = SessionPrefs.linuxDriver(this)
|
||||
LinuxVulkanDriver.resolveIcdPath(this, linuxDriverId)
|
||||
// Mali bridge (PR #517) on: the bridge ICD is the driver (startVkBridge). Otherwise the system
|
||||
// PowerVR/Xclipse path (PR #570) or the imported/runtime Turnip, as before.
|
||||
val bridge = com.droiddeck.launcher.core.DeviceSupport.vkBridge(this)
|
||||
if (!bridge && !venus && SystemVulkanDriver.usesDefault(linuxDriverId)) {
|
||||
SystemVulkanDriver.addEnvironment(this, guest)
|
||||
}
|
||||
(if (bridge || venus) null else LinuxVulkanDriver.resolveIcdPath(this, linuxDriverId))
|
||||
?.let { guest.add(LinuxVulkanDriver.ENV + "=" + it) }
|
||||
// An open Mali driver pair: /dev/mali0 stands in as the render node (LinuxRuntime.bindGpuNode)
|
||||
// and the session shim answers gamescope's PRIME calls on it as on KGSL. It only covers
|
||||
// libdrm's PRIME/GEM entry points, which PanVK on kbase never calls on its own device.
|
||||
// Xwayland crashing in glamor (seen on Mali v9 with Zink on PanVK) left the last session at
|
||||
// "X11 I/O error" before Steam: the next one on this device starts Xwayland without glamor
|
||||
// (software 2D; Steam's GL still renders). Never on an Adreno.
|
||||
if (!com.droiddeck.launcher.core.DeviceSupport.adreno() && lastXwaylandCrashed()) {
|
||||
guest.add("XWAYLAND_NO_GLAMOR=1")
|
||||
Log.w(TAG, "xwayland: the last session's Xwayland crashed; glamor off for this one (XWAYLAND_NO_GLAMOR=1)")
|
||||
}
|
||||
// A Mali PanVK session ran out of file descriptors after ten minutes (sync files and
|
||||
// dma-bufs, "Too many open files"): the session script raises its open-files limit to the
|
||||
// hard limit for the whole session tree. Never on an Adreno.
|
||||
if (!com.droiddeck.launcher.core.DeviceSupport.adreno()) guest.add("BL_RAISE_NOFILE=1")
|
||||
// gamescope's explicit sync waits on DRM syncobj timelines through
|
||||
// DRM_IOCTL_SYNCOBJ_EVENTFD, which a kernel before 6.6 does not have (Exynos 2400e on 6.1:
|
||||
// hundreds of "timeline ... failed" and a game stuck at black), and Mali's stand-in node
|
||||
// (/dev/mali0) has no syncobjs at all. There clients use implicit sync instead
|
||||
// (tools/gamescope/patches/0126). Never on an Adreno.
|
||||
if (!com.droiddeck.launcher.core.DeviceSupport.adreno()) {
|
||||
val kernel = System.getProperty("os.version").orEmpty()
|
||||
val old = kernelBefore(kernel, 6, 6)
|
||||
val maliNode = LinuxRuntime.gpuStandIn(this) == LinuxRuntime.MALI_DEVICE
|
||||
if (old || maliNode) {
|
||||
guest.add("GAMESCOPE_DISABLE_EXPLICIT_SYNC=1")
|
||||
Log.i(TAG, "gamescope: explicit sync off (" + (if (old) "kernel $kernel has no SYNCOBJ_EVENTFD" else "Mali stand-in node has no syncobjs") + ")")
|
||||
}
|
||||
}
|
||||
if (!bridge && com.droiddeck.launcher.core.DeviceSupport.openDriverActive(this)) {
|
||||
// CEF's accelerated shared-texture output showed stale, half-written tiles on RADV
|
||||
// (Xclipse), as #570 found on PowerVR: web compositing in software, GPU raster kept.
|
||||
// Setup's "Steam interface: GPU drawing" turns GPU compositing back on (Xclipse users).
|
||||
if (SessionPrefs.steamGpuCompositing(this)) {
|
||||
Log.i(TAG, "steam: GPU web compositing (Setup's \"Steam interface: GPU drawing\")")
|
||||
} else {
|
||||
guest.add("BL_STEAM_SOFT_COMPOSITING=1")
|
||||
Log.i(TAG, "steam: software web compositing for the open driver pair (GPU raster kept)")
|
||||
}
|
||||
// droiddeck-game-env leaves vkd3d-proton to report the driver's own caps on this path.
|
||||
guest.add("BL_OPEN_DRIVER=1")
|
||||
LinuxRuntime.gpuStandIn(this)?.takeIf { it == LinuxRuntime.MALI_DEVICE }?.let { guest.add("BL_DRM_STANDIN=$it") }
|
||||
}
|
||||
// Turnip's own debug switches, for the runtime's driver and everything on it. The file in
|
||||
// Downloads holds the value verbatim ("sysmem", "sysmem,deck_emu"); with nothing there, an
|
||||
// imported driver from the A710/A720/A722 legs gets "sysmem" on its own, which is what both
|
||||
// its authors advise for those GPUs and what nothing else in the list needs.
|
||||
tuDebug(linuxDriverId)?.let { guest.add("TU_DEBUG=$it") }
|
||||
if (!venus) tuDebug(linuxDriverId)?.let { guest.add("TU_DEBUG=$it") }
|
||||
// Zink renders the client's UI (Chromium -> ANGLE -> Zink -> Turnip). Lazy descriptors is
|
||||
// the mode Zink recommends where the driver has no descriptor buffer, and what Ludashi ships
|
||||
// by default for its Zink path; a switch here because on one Fold the menus run at 14 fps.
|
||||
@@ -681,6 +773,41 @@ class SessionService : Service() {
|
||||
.takeIf { it.isNotEmpty() }?.let { guest.add("BL_GAME_CPUS=$it") }
|
||||
}
|
||||
|
||||
/**
|
||||
* The Mali bridge (Setup's experimental switch, non-Adreno GPUs only): the server that runs the
|
||||
* session's Vulkan calls on the phone's own driver, started before the guest. The session
|
||||
* script points the Vulkan loader at the bridge ICD when it sees BL_VKBRIDGE and runs the
|
||||
* bridge's self-test into the session log first; both sides log into the session folder.
|
||||
*/
|
||||
private fun startVkBridge(guest: MutableList<String>, sessionDir: File) {
|
||||
if (!com.droiddeck.launcher.core.DeviceSupport.vkBridge(this)) return
|
||||
// Under the files dir, which the session binds at its own path: one string for both sides.
|
||||
val socket = File(filesDir, "vkbridge/server.sock")
|
||||
val bridge = com.droiddeck.launcher.gpu.VkBridgeComponent(socket, File(sessionDir, "vkbridge-server.log"))
|
||||
bridge.attach(this)
|
||||
components.add(bridge)
|
||||
com.droiddeck.launcher.gpu.ClockLogComponent(File(sessionDir, "vkbridge-clocks.log")).let {
|
||||
it.attach(this)
|
||||
components.add(it)
|
||||
}
|
||||
guest.add("BL_VKBRIDGE=1")
|
||||
if (SessionPrefs.steamGpuCompositing(this)) guest.add("BL_STEAM_GPU_COMPOSITING=1")
|
||||
// If the bridge's self-test fails images or draws, the session script falls back to the
|
||||
// Mali driver pair set for the runtime (its ICD here), rather than crashing gamescope.
|
||||
SessionPrefs.linuxDriver(this).takeIf { it.isNotEmpty() }
|
||||
?.let { runCatching { LinuxVulkanDriver.resolveIcdPath(this, it) }.getOrNull() }
|
||||
?.let { guest.add("BL_VKBRIDGE_FALLBACK_ICD=$it") }
|
||||
guest.add("VKBRIDGE_SOCKET=" + socket.path)
|
||||
guest.add("VKBRIDGE_CLIENT_LOG=" + File(sessionDir, "vkbridge-client.log").path)
|
||||
// The render node gamescope sees is Mali's device standing in (LinuxRuntime.bindGpuNode):
|
||||
// the ICD reports its numbers, and the session shim answers PRIME calls on it as on KGSL.
|
||||
LinuxRuntime.gpuStandIn(this)?.let { node ->
|
||||
guest.add("BL_DRM_STANDIN=$node")
|
||||
LinuxRuntime.deviceNumbers(node)?.let { guest.add("VKBRIDGE_DRM_RENDER=$it") }
|
||||
}
|
||||
Log.i(TAG, "vkbridge: on (${com.droiddeck.launcher.core.DeviceSupport.gpuName(this)}), socket $socket")
|
||||
}
|
||||
|
||||
/** PulseAudio, and the DirectAudio relay when a path needs it; returns the daemon for suspend and resume. */
|
||||
private fun startAudio(guest: MutableList<String>, sessionDir: File): PulseAudioComponent {
|
||||
// PulseAudio always: the client is a native Linux program and has no other way to make a
|
||||
@@ -1477,6 +1604,12 @@ class SessionService : Service() {
|
||||
}.onFailure { Log.w(TAG, "could not request Steam wake", it) }
|
||||
}
|
||||
|
||||
/** Background-only: preserve old runtimes until all earlier guest processes are gone. */
|
||||
private fun pruneSystemVulkanRuntime() {
|
||||
runCatching { SystemVulkanDriver.pruneUnused(this, !OrphanReaper.hasOtherProcesses()) }
|
||||
.onFailure { Log.w(TAG, "could not prune unused system Vulkan runtimes", it) }
|
||||
}
|
||||
|
||||
private fun finishSessionStop(status: Int, stoppedGen: Int) {
|
||||
mainHandler.post {
|
||||
if (stoppedGen != sessionGen || SessionState.running) {
|
||||
@@ -1594,9 +1727,11 @@ class SessionService : Service() {
|
||||
auxiliary.forEach { (pid, started) -> teardown(pid, started) }
|
||||
if (prootPid > 1) teardown(prootPid)
|
||||
killGuestLeftovers()
|
||||
pruneSystemVulkanRuntime()
|
||||
finishSessionStop(status, stoppedGen)
|
||||
}, "session-teardown").start()
|
||||
} else {
|
||||
Thread({ pruneSystemVulkanRuntime() }, "system-vulkan-prune").start()
|
||||
Thread({ com.droiddeck.launcher.stores.gog.GogComet.end(stoppedSession); finishSessionStop(status, stoppedGen) }, "gog-session-stop").start()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.content.Context
|
||||
import android.os.Process
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.core.DeviceSupport
|
||||
import com.droiddeck.launcher.core.FileUtils
|
||||
import com.droiddeck.launcher.core.HostProcess
|
||||
import com.droiddeck.launcher.core.SessionPart
|
||||
import java.io.File
|
||||
import java.io.PrintWriter
|
||||
|
||||
/**
|
||||
* Vulkan for the session on a Mali, through Venus (the "Mali (Venus)" route; by David Cimo,
|
||||
* DavidCimo/droiddeck-mali, ported to this branch).
|
||||
*
|
||||
* The guest's processes are glibc and cannot load the vendor's bionic driver. Instead they load
|
||||
* Mesa's Venus ICD (libvulkan_virtio.so), which serializes every Vulkan call over a unix socket to
|
||||
* virglrenderer's vtest server. The server runs here, on the Android side, and replays the calls
|
||||
* on the device's own Vulkan driver. Both ends of the socket are under the app's files directory,
|
||||
* which the session binds at its own path, so the same path works inside and out.
|
||||
*/
|
||||
class VenusComponent(private val logFile: File?) : SessionPart() {
|
||||
@Volatile private var pid = -1
|
||||
|
||||
override fun start() {
|
||||
val context = app()
|
||||
stageIcd(context)
|
||||
val libDir = context.applicationInfo.nativeLibraryDir
|
||||
val socket = socket(context)
|
||||
socket.delete()
|
||||
val env = arrayOf(
|
||||
"LD_LIBRARY_PATH=$libDir",
|
||||
// vtest forks a render server per client; this is where its executable is.
|
||||
"RENDER_SERVER_EXEC_PATH=$libDir/libvirgl_render_server.so",
|
||||
"TMPDIR=" + context.cacheDir.path,
|
||||
)
|
||||
val command = "$libDir/libvirgl_test_server.so --venus --no-virgl --socket-path " + socket.path
|
||||
val out = logFile?.let { runCatching { PrintWriter(java.io.FileWriter(it, true)) }.getOrNull() }
|
||||
pid = HostProcess.start(command, env, context.filesDir, { status ->
|
||||
Log.w(TAG, "vtest server exited: $status")
|
||||
out?.let { synchronized(it) { it.println("vtest server exited: $status"); it.flush() } }
|
||||
}, { line ->
|
||||
Log.i(TAG, line)
|
||||
out?.let { synchronized(it) { it.println(line); it.flush() } }
|
||||
})
|
||||
Log.i(TAG, "vtest server pid $pid on $socket")
|
||||
}
|
||||
|
||||
override fun stop() {
|
||||
if (pid > 1) Process.killProcess(pid)
|
||||
pid = -1
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val TAG = "Venus"
|
||||
private const val ASSET = "venus/libvulkan_virtio.so"
|
||||
private const val DIR = "venus"
|
||||
private const val LIB = "libvulkan_virtio.so"
|
||||
private const val ICD = "virtio_icd.json"
|
||||
|
||||
/**
|
||||
* The selection rule: Venus when Setup's "Mali (Venus)" is on, on a GPU that is neither an
|
||||
* Adreno nor one the system-driver route covers (PowerVR, Xclipse), and the apk carries it.
|
||||
* It then replaces the Mali bridge and any open driver pair for the session.
|
||||
*/
|
||||
@JvmStatic
|
||||
fun wanted(context: Context): Boolean =
|
||||
!DeviceSupport.adreno() && !com.droiddeck.launcher.gpu.SystemVulkanDriver.isAvailable() &&
|
||||
SessionPrefs.venus(context) && available(context)
|
||||
|
||||
/** Whether this apk carries the Venus component (tools/venus, venus.tzst). */
|
||||
@JvmStatic
|
||||
fun available(context: Context): Boolean = runCatching {
|
||||
context.assets.list(DIR)?.contains(LIB) == true &&
|
||||
File(context.applicationInfo.nativeLibraryDir, "libvirgl_test_server.so").isFile
|
||||
}.getOrDefault(false)
|
||||
|
||||
@JvmStatic
|
||||
fun socket(context: Context): File = File(File(context.filesDir, DIR), "vtest.sock")
|
||||
|
||||
/** What the guest needs to find the ICD and the server. */
|
||||
@JvmStatic
|
||||
fun guestEnv(context: Context): List<String> {
|
||||
val dir = File(context.filesDir, DIR)
|
||||
return listOf(
|
||||
"VK_ICD_FILENAMES=" + File(dir, ICD).path,
|
||||
"VN_DEBUG=vtest",
|
||||
"VTEST_SOCKET_NAME=" + socket(context).path,
|
||||
// Xwayland has no DRI3 without a DRM node, so swapchains present through shared memory.
|
||||
"MESA_VK_WSI_DEBUG=sw",
|
||||
// The Mali compatibility layer in every process but gamescope, not only Wine: Zink
|
||||
// (Steam's GL, Xwayland's glamor) requires robustness2's nullDescriptor, which the
|
||||
// layer stands in for. The session script checks it and falls back to llvmpipe.
|
||||
"DROIDDECK_MALI_COMPAT=1",
|
||||
"BL_VENUS=1",
|
||||
// gamescope's composite layout without immutable YCbCr samplers from the start
|
||||
// (patch 0130): a Mali-G615 refused every composite pipeline with them, and testing
|
||||
// that through Venus took the render server down.
|
||||
"GAMESCOPE_NO_YCBCR_SAMPLERS=1",
|
||||
)
|
||||
}
|
||||
|
||||
/** Copies the ICD out of the APK when it changed, and writes its manifest with an absolute path. */
|
||||
private fun stageIcd(context: Context) {
|
||||
val dir = File(context.filesDir, DIR).apply { mkdirs() }
|
||||
val lib = File(dir, LIB)
|
||||
// Copied again after every app update: the asset is compressed, so its size is unknown up front.
|
||||
val installed = context.packageManager.getPackageInfo(context.packageName, 0).lastUpdateTime
|
||||
if (!lib.isFile || lib.lastModified() < installed) {
|
||||
val tmp = File(dir, "$LIB.tmp")
|
||||
context.assets.open(ASSET).use { input -> tmp.outputStream().use { input.copyTo(it) } }
|
||||
if (!tmp.renameTo(lib)) Log.e(TAG, "could not move the Venus ICD into place")
|
||||
Log.i(TAG, "staged $lib (${lib.length()} bytes)")
|
||||
}
|
||||
FileUtils.writeString(
|
||||
File(dir, ICD),
|
||||
"""{"file_format_version":"1.0.1","ICD":{"library_path":"${lib.path}","api_version":"1.4.354"}}""",
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -502,9 +502,10 @@ fun ComponentsPage(
|
||||
val active = gpu.activePair
|
||||
InUseBar(
|
||||
queued = gpu.busy != null,
|
||||
sentence = (active?.let { "${it.name} ${it.version}" } ?: gpu.activeBundle ?: stringResource(R.string.gpu_builtin))
|
||||
sentence = (active?.let { "${it.name} ${it.version}" } ?: gpu.activeBundle ?: stringResource(if (gpu.systemPowerVr) R.string.gpu_system_powervr else R.string.gpu_builtin))
|
||||
.let { if (gpu.auto) stringResource(R.string.gpu_bar_auto, it) else it },
|
||||
note = if (gpu.busy != null) (if (gpu.percent >= 0) "${gpu.percent}%" else "…")
|
||||
else if (gpu.systemPowerVr) stringResource(R.string.gpu_auto_system_hint)
|
||||
else gpu.autoStatus.ifEmpty { if (active != null || gpu.activeBundle != null) "" else gpu.pairs.firstOrNull { it.recommended }?.let { stringResource(R.string.gpu_recommended_for, it.name) } ?: stringResource(R.string.gpu_refresh_hint) },
|
||||
)
|
||||
}
|
||||
@@ -515,17 +516,27 @@ fun ComponentsPage(
|
||||
)
|
||||
else -> {
|
||||
val st = compState(l)
|
||||
val managedDxvk = ComponentsManager.runtimeManaged(l, gpu.systemPowerVr)
|
||||
val label = ComponentsManager.LABEL[l] ?: l
|
||||
if (st == null) InUseBar(false, stringResource(R.string.comp_no_proton), "")
|
||||
else {
|
||||
val reappliedAt = view?.reappliedAt?.takeIf { it > 0 }?.let { DateFormat.getTimeInstance(DateFormat.SHORT).format(Date(it * 1000)) }
|
||||
InUseBar(
|
||||
queued = st.queued != null,
|
||||
sentence = (if (st.queued != null) stringResource(R.string.comp_next_queued, st.queued) else stringResource(R.string.comp_in_use, label, st.inUse))
|
||||
.let { if (reappliedAt != null) stringResource(R.string.comp_reapplied, it, reappliedAt) else it },
|
||||
note = if (view?.inUseByGame == true) stringResource(R.string.comp_waits) else stringResource(R.string.comp_applies_next_game),
|
||||
onCancel = if (st.queued != null) onCancelQueued else null,
|
||||
)
|
||||
Column {
|
||||
InUseBar(
|
||||
queued = st.queued != null,
|
||||
sentence = (if (managedDxvk) stringResource(R.string.comp_in_use, label, stringResource(R.string.gpu_system_powervr)) +
|
||||
(st.queued?.let { "\n" + stringResource(R.string.cmgr_powervr_dxvk_queued, it) } ?: "")
|
||||
else if (st.queued != null) stringResource(R.string.comp_next_queued, st.queued) else stringResource(R.string.comp_in_use, label, st.inUse))
|
||||
.let { if (reappliedAt != null && !managedDxvk) stringResource(R.string.comp_reapplied, it, reappliedAt) else it },
|
||||
note = if (managedDxvk) "" else if (view?.inUseByGame == true) stringResource(R.string.comp_waits) else stringResource(R.string.comp_applies_next_game),
|
||||
onCancel = if (st.queued != null) onCancelQueued else null,
|
||||
maxLines = if (managedDxvk && st.queued != null) 3 else 2,
|
||||
)
|
||||
if (managedDxvk) Text(
|
||||
stringResource(R.string.cmgr_powervr_dxvk_managed),
|
||||
fontSize = 13.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(top = 8.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -552,11 +563,11 @@ fun ComponentsPage(
|
||||
GPU_TAB -> {
|
||||
val autoKey = "gpu:auto"
|
||||
ChoiceLine(
|
||||
stringResource(R.string.common_auto), stringResource(R.string.gpu_auto_keeps), gpu.auto, removable = false,
|
||||
stringResource(R.string.common_auto), stringResource(if (gpu.powerVr) R.string.gpu_auto_system_hint else R.string.gpu_auto_keeps), gpu.auto, removable = false,
|
||||
modifier = Modifier.focusRequester(firstRow).trackRow(autoKey, rowsAt),
|
||||
onSelect = {
|
||||
if (gpu.auto) return@ChoiceLine
|
||||
ask(autoKey, right, ctx.getString(R.string.gpu_use_title, ctx.getString(R.string.common_auto)), ctx.getString(R.string.gpu_auto_hint), ctx.getString(R.string.common_use), false, ctx.getString(R.string.common_auto)) {
|
||||
ask(autoKey, right, ctx.getString(R.string.gpu_use_title, ctx.getString(R.string.common_auto)), ctx.getString(if (gpu.powerVr) R.string.gpu_auto_system_hint else R.string.gpu_auto_hint), ctx.getString(R.string.common_use), false, ctx.getString(R.string.common_auto)) {
|
||||
gpuActions.onAuto(true); flyHome(autoKey, GPU_TAB)
|
||||
}
|
||||
},
|
||||
@@ -601,16 +612,17 @@ fun ComponentsPage(
|
||||
}
|
||||
else -> {
|
||||
val label = ComponentsManager.LABEL[l] ?: l
|
||||
val rows = installedFor(l, view, snapshot)
|
||||
val managedDxvk = ComponentsManager.runtimeManaged(l, gpu.systemPowerVr)
|
||||
val rows = installedFor(l, view, snapshot, managedDxvk)
|
||||
if (rows.isEmpty()) EmptyLine(stringResource(R.string.comp_nothing_stored, label))
|
||||
val p = view?.proton
|
||||
rows.forEachIndexed { i, item ->
|
||||
val key = "row:$l:${item.file ?: item.protonVersion}"
|
||||
ChoiceLine(
|
||||
item.name, item.detail, item.selected, item.removable, tag = item.tag,
|
||||
modifier = (if (i == 0) Modifier.focusRequester(firstRow) else Modifier).trackRow(key, rowsAt),
|
||||
item.name, item.detail, item.selected, item.removable, tag = item.tag, enabled = !managedDxvk,
|
||||
modifier = (if (i == 0 && !managedDxvk) Modifier.focusRequester(firstRow) else Modifier).trackRow(key, rowsAt),
|
||||
onSelect = {
|
||||
if (item.selected || p == null) return@ChoiceLine
|
||||
if (managedDxvk || item.selected || p == null) return@ChoiceLine
|
||||
val waits = if (view.inUseByGame) ctx.getString(R.string.comp_waits_long) else ctx.getString(R.string.comp_applies_long)
|
||||
if (item.file != null) ask(key, right, ctx.getString(R.string.comp_swap_title, label), ctx.getString(R.string.comp_swap_body, item.name, p.name, waits), ctx.getString(R.string.comp_swap), false, item.name) {
|
||||
onSwap(item.file); flyHome(key, l)
|
||||
@@ -712,14 +724,19 @@ fun ComponentsPage(
|
||||
}
|
||||
}
|
||||
else -> {
|
||||
SmallButton(stringResource(R.string.comp_import_wcp), onClick = onImport)
|
||||
val managedDxvk = ComponentsManager.runtimeManaged(l, gpu.systemPowerVr)
|
||||
SmallButton(
|
||||
stringResource(R.string.comp_import_wcp), onClick = onImport,
|
||||
modifier = if (managedDxvk) Modifier.focusRequester(firstRow) else Modifier,
|
||||
)
|
||||
val st = compState(l)
|
||||
val p = view?.proton
|
||||
val build = p?.let { ComponentsManager.safeName(it.version) }
|
||||
if (st != null && p != null && st.activeFile != null && view.originals.any { it.comp == l && it.protonVersion == build }) {
|
||||
val label = ComponentsManager.LABEL[l] ?: l
|
||||
Box(Modifier.trackRow("restore:$l", rowsAt)) {
|
||||
FocusText(stringResource(R.string.comp_restore_original), pal.signal) {
|
||||
if (managedDxvk) SmallButton(stringResource(R.string.comp_restore_original), enabled = false) {}
|
||||
else FocusText(stringResource(R.string.comp_restore_original), pal.signal) {
|
||||
ask("restore:$l", false, ctx.getString(R.string.comp_restore_title, label), ctx.getString(R.string.comp_restore_original_body, p.name, label), ctx.getString(R.string.common_restore), false, ctx.getString(R.string.comp_restore_original)) {
|
||||
onRestore(build!!); flyHome("restore:$l", l)
|
||||
}
|
||||
@@ -867,6 +884,7 @@ fun ComponentsPage(
|
||||
protonChoice = gameProtonChoice,
|
||||
packages = snapshot?.packages.orEmpty(),
|
||||
componentChoices = gameComponents,
|
||||
systemPowerVr = gpu.systemPowerVr,
|
||||
componentMenu = gameComponentMenu,
|
||||
protonMenu = gameProtonMenu,
|
||||
fexMenu = fexMenu,
|
||||
@@ -1010,11 +1028,11 @@ fun ComponentsPage(
|
||||
|
||||
/** The Installed rows of one component layer for the Proton the page shows. */
|
||||
@Composable
|
||||
private fun installedFor(l: String, view: ComponentsManager.ProtonView?, snapshot: Snapshot?): List<InstalledItem> {
|
||||
private fun installedFor(l: String, view: ComponentsManager.ProtonView?, snapshot: Snapshot?, runtimeManaged: Boolean = false): List<InstalledItem> {
|
||||
view ?: return emptyList()
|
||||
val st = view.components[l] ?: return emptyList()
|
||||
val build = ComponentsManager.safeName(view.proton.version)
|
||||
val activeIsOriginal = st.activeFile == null
|
||||
val activeIsOriginal = !runtimeManaged && st.activeFile == null
|
||||
return view.originals.filter { it.comp == l }.map { o ->
|
||||
val isCurrent = o.protonVersion == build
|
||||
InstalledItem(
|
||||
@@ -1023,7 +1041,7 @@ private fun installedFor(l: String, view: ComponentsManager.ProtonView?, snapsho
|
||||
"ORIGINAL", activeIsOriginal && isCurrent, !isCurrent, null, o.protonVersion,
|
||||
)
|
||||
} + (snapshot?.packages ?: emptyList()).filter { it.comp == l }.map { s ->
|
||||
InstalledItem(s.version, stringResource(R.string.common_size_mb, s.size / 1048576.0), "STORED", s.file == st.activeFile, true, s.file, null)
|
||||
InstalledItem(s.version, stringResource(R.string.common_size_mb, s.size / 1048576.0), "STORED", !runtimeManaged && s.file == st.activeFile, true, s.file, null)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1062,11 +1080,12 @@ private fun Stack(
|
||||
LayerCard(
|
||||
title = LayerTitle(l),
|
||||
value = when (l) {
|
||||
GPU_TAB -> if (gpu.auto) auto else gpu.activePair?.name ?: gpu.activeBundle ?: auto
|
||||
GPU_TAB -> if (gpu.systemPowerVr) stringResource(R.string.gpu_system_powervr) else if (gpu.auto) auto else gpu.activePair?.name ?: gpu.activeBundle ?: auto
|
||||
PROTON_TAB -> (view?.proton?.name ?: "") + " ▾"
|
||||
else -> st?.let { if (it.activeFile == null) original else it.inUse } ?: ""
|
||||
else -> if (ComponentsManager.runtimeManaged(l, gpu.systemPowerVr)) stringResource(R.string.gpu_system_powervr)
|
||||
else st?.let { if (it.activeFile == null) original else it.inUse } ?: ""
|
||||
},
|
||||
swapped = l in ComponentsManager.COMPONENTS && st?.activeFile != null,
|
||||
swapped = l in ComponentsManager.COMPONENTS && st?.activeFile != null && !ComponentsManager.runtimeManaged(l, gpu.systemPowerVr),
|
||||
selected = l == layer,
|
||||
landed = landed[l] ?: 0, ring = rings[l] ?: 0,
|
||||
modifier = Modifier.focusRequester(focus.getValue(l)).onGloballyPositioned { onPlaced(l, it.boundsInRoot()) },
|
||||
@@ -1137,7 +1156,7 @@ private fun LayerCard(
|
||||
|
||||
/** What is in use for the layer: a dot (green, or amber while a change waits), a sentence, and a note or Cancel. */
|
||||
@Composable
|
||||
private fun InUseBar(queued: Boolean, sentence: String, note: String, onCancel: (() -> Unit)? = null) {
|
||||
private fun InUseBar(queued: Boolean, sentence: String, note: String, onCancel: (() -> Unit)? = null, maxLines: Int = 2) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
Row(
|
||||
@@ -1146,7 +1165,7 @@ private fun InUseBar(queued: Boolean, sentence: String, note: String, onCancel:
|
||||
.border(1.dp, pal.line, RoundedCornerShape(12.dp)).padding(horizontal = 14.dp, vertical = 8.dp),
|
||||
) {
|
||||
Box(Modifier.size(8.dp).background(if (queued) QUEUED else pal.good, CircleShape))
|
||||
Text(sentence, fontSize = 14.sp, color = colors.onBackground, maxLines = 2, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f))
|
||||
Text(sentence, fontSize = 14.sp, color = colors.onBackground, maxLines = maxLines, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f))
|
||||
if (onCancel != null) FocusText(stringResource(R.string.common_cancel), pal.signal, onClick = onCancel)
|
||||
else if (note.isNotEmpty() && !LocalNarrowPane.current) Text(note, fontSize = 13.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
@@ -1182,6 +1201,7 @@ private fun GameComponentOverrides(
|
||||
protonChoice: ProtonDefault.GameChoice?,
|
||||
packages: List<ComponentsManager.Package>,
|
||||
componentChoices: Map<String, String>,
|
||||
systemPowerVr: Boolean,
|
||||
componentMenu: String?,
|
||||
protonMenu: Boolean,
|
||||
fexMenu: Boolean,
|
||||
@@ -1273,6 +1293,7 @@ private fun GameComponentOverrides(
|
||||
}
|
||||
GamePackageRow(
|
||||
comp = "dxvk",
|
||||
runtimeManaged = ComponentsManager.runtimeManaged("dxvk", systemPowerVr),
|
||||
packages = packages,
|
||||
selectedFile = componentChoices["dxvk"],
|
||||
open = componentMenu == "dxvk",
|
||||
@@ -1337,13 +1358,16 @@ private fun GamePackageRow(
|
||||
onMenu: (String?) -> Unit,
|
||||
onPick: (String, String?) -> Unit,
|
||||
onRuntimeOptions: (() -> Unit)? = null,
|
||||
runtimeManaged: Boolean = false,
|
||||
) {
|
||||
val choices = packages.filter { it.comp == comp }
|
||||
val selected = choices.firstOrNull { it.file == selectedFile }
|
||||
val title = ComponentsManager.LABEL[comp] ?: comp
|
||||
val enabled = !busy && (!runtimeManaged || selectedFile != null)
|
||||
SettingsRow(
|
||||
title,
|
||||
if (selected == null) {
|
||||
if (runtimeManaged) stringResource(R.string.cmgr_powervr_dxvk_managed)
|
||||
else if (selected == null) {
|
||||
if (proton == null) stringResource(R.string.comp_game_component_general)
|
||||
else stringResource(R.string.comp_game_component_runtime, proton.name)
|
||||
} else stringResource(R.string.comp_game_component_override, selected.version),
|
||||
@@ -1351,18 +1375,18 @@ private fun GamePackageRow(
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
Box {
|
||||
ValueChip(
|
||||
selected?.version ?: stringResource(R.string.comp_game_use_general),
|
||||
open,
|
||||
enabled = !busy,
|
||||
if (runtimeManaged) stringResource(R.string.gpu_system_powervr) else selected?.version ?: stringResource(R.string.comp_game_use_general),
|
||||
open && enabled,
|
||||
enabled = enabled,
|
||||
modifier = Modifier.widthIn(max = 240.dp),
|
||||
) { onMenu(if (open) null else comp) }
|
||||
AnchoredMenu(open, onDismiss = { onMenu(null) }, title = title) { first ->
|
||||
AnchoredMenu(open && enabled, onDismiss = { onMenu(null) }, title = title) { first ->
|
||||
MenuItem(
|
||||
stringResource(R.string.comp_game_use_general),
|
||||
checked = selected == null,
|
||||
focusRequester = first,
|
||||
) { onPick(comp, null); onMenu(null) }
|
||||
choices.forEach { option ->
|
||||
if (!runtimeManaged) choices.forEach { option ->
|
||||
MenuItem(option.version, checked = option.file == selectedFile, detail = option.description) {
|
||||
onPick(comp, option.file)
|
||||
onMenu(null)
|
||||
@@ -1492,13 +1516,13 @@ private fun Tag(text: String) {
|
||||
@Composable
|
||||
private fun ChoiceLine(
|
||||
name: String, detail: String, selected: Boolean, removable: Boolean,
|
||||
modifier: Modifier = Modifier, tag: String? = null, badge: String? = null, progress: Int? = null,
|
||||
modifier: Modifier = Modifier, tag: String? = null, badge: String? = null, progress: Int? = null, enabled: Boolean = true,
|
||||
onSelect: () -> Unit, onDelete: () -> Unit = {},
|
||||
) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val src = remember { MutableInteractionSource() }
|
||||
val hot = rememberHot(src)
|
||||
val hot = rememberHot(src) && enabled
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier = Modifier.fillMaxWidth()
|
||||
@@ -1508,8 +1532,8 @@ private fun ChoiceLine(
|
||||
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp),
|
||||
modifier = Modifier.weight(1f).heightIn(min = 56.dp).then(modifier)
|
||||
.glideBorder(hot, ROW_SHAPE, pal.signal)
|
||||
.hoverable(src).clickable(interactionSource = src, indication = null, role = Role.RadioButton, onClick = onSelect)
|
||||
.controllerConfirm(onClick = onSelect)
|
||||
.hoverable(src).clickable(interactionSource = src, indication = null, enabled = enabled, role = Role.RadioButton, onClick = onSelect)
|
||||
.controllerConfirm(enabled = enabled, onClick = onSelect)
|
||||
.padding(start = 14.dp, end = 8.dp, top = 8.dp, bottom = 8.dp),
|
||||
) {
|
||||
Box(contentAlignment = Alignment.Center, modifier = Modifier.size(20.dp).border(2.dp, if (selected) pal.signal else colors.onSurfaceVariant, CircleShape)) {
|
||||
@@ -1519,7 +1543,7 @@ private fun ChoiceLine(
|
||||
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Text(
|
||||
name, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, maxLines = 2, overflow = TextOverflow.Ellipsis,
|
||||
color = if (selected) pal.signal else colors.onBackground, modifier = Modifier.weight(1f, fill = false),
|
||||
color = if (!enabled) colors.onSurfaceVariant else if (selected) pal.signal else colors.onBackground, modifier = Modifier.weight(1f, fill = false),
|
||||
)
|
||||
if (tag != null) Tag(tag)
|
||||
}
|
||||
|
||||
@@ -99,6 +99,9 @@ class FrontEndState(
|
||||
val logsEnabled: Boolean,
|
||||
/** Setup's Debugging tools toggle (AgentAccess): off unless the user turns it on. */
|
||||
val agentCommands: Boolean = false,
|
||||
val graphicsLogs: Boolean = false,
|
||||
val steamGpuDrawing: Boolean = false,
|
||||
val bridgeFellBack: Boolean = false,
|
||||
val steamGames: List<Library.SteamGame>,
|
||||
val emulators: List<Library.Emulator>,
|
||||
val running: String?,
|
||||
@@ -130,6 +133,12 @@ class FrontEndState(
|
||||
val oscMode: String = SessionPrefs.OSC_AUTO,
|
||||
val controller: com.droiddeck.launcher.input.ControllerPrefs.Settings? = null,
|
||||
val phantomProcessStatus: PhantomProcessStatus = PhantomProcessStatus.NOT_APPLICABLE,
|
||||
/** The GPU is an Adreno (Turnip); otherwise Setup offers the experimental Mali bridge. */
|
||||
val adreno: Boolean = true,
|
||||
/** Setup's "Mali bridge (experimental)" (SessionPrefs.vkBridge). */
|
||||
val vkBridge: Boolean = false,
|
||||
/** Setup's "Mali (Venus)" (SessionPrefs.venus). */
|
||||
val venus: Boolean = false,
|
||||
val showPhantomGate: Boolean = false,
|
||||
val orientation: Int = android.content.pm.ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE,
|
||||
val launcherFullscreen: Boolean = true,
|
||||
@@ -187,6 +196,8 @@ class FrontEndActions(
|
||||
val onInstallPackage: (String) -> Unit,
|
||||
val onRemovePackage: (String) -> Unit,
|
||||
val onRuntime: () -> Unit,
|
||||
val onVkBridge: (Boolean) -> Unit = {},
|
||||
val onVenus: (Boolean) -> Unit = {},
|
||||
val onFrameGenPick: (FrameGen.Mode) -> Unit,
|
||||
val onImportLossless: () -> Unit,
|
||||
val onProtons: () -> Unit,
|
||||
@@ -203,6 +214,8 @@ class FrontEndActions(
|
||||
val onBrowseFiles: (File) -> Unit = {},
|
||||
val onLogs: () -> Unit,
|
||||
val onAgentCommands: () -> Unit = {},
|
||||
val onGraphicsLogs: () -> Unit = {},
|
||||
val onSteamGpuDrawing: () -> Unit = {},
|
||||
val onShareLogs: () -> Unit = {},
|
||||
val onClearLogs: () -> Unit = {},
|
||||
val onOffline: () -> Unit,
|
||||
|
||||
@@ -211,10 +211,29 @@ internal fun SetupPanel(
|
||||
},
|
||||
when (gpu.support) {
|
||||
com.droiddeck.launcher.gpu.GpuInfo.Support.TESTED -> stringResource(R.string.setup_gpu_detail, gpu.displayName(ctx), gpuName)
|
||||
com.droiddeck.launcher.gpu.GpuInfo.Support.UNTESTED -> stringResource(R.string.setup_gpu_untested_detail, gpu.displayName(ctx), gpu.supportText(ctx).replaceFirstChar { it.lowercase() })
|
||||
else -> stringResource(R.string.setup_gpu_unsupported_detail, gpuName)
|
||||
com.droiddeck.launcher.gpu.GpuInfo.Support.UNTESTED ->
|
||||
if (!s.adreno && s.vkBridge && !com.droiddeck.launcher.core.DeviceSupport.bridgeUsable()) stringResource(R.string.setup_gpu_bridge_unusable, gpu.displayName(ctx))
|
||||
else if (!s.adreno && s.vkBridge && s.bridgeFellBack) stringResource(R.string.setup_gpu_bridge_fell_back, gpu.displayName(ctx))
|
||||
else stringResource(R.string.setup_gpu_untested_detail, gpu.displayName(ctx), gpu.supportText(ctx).replaceFirstChar { it.lowercase() })
|
||||
else -> if (s.vkBridge && !com.droiddeck.launcher.core.DeviceSupport.bridgeUsable()) stringResource(R.string.setup_gpu_bridge_unusable, gpuName)
|
||||
else if (s.vkBridge && s.bridgeFellBack) stringResource(R.string.setup_gpu_bridge_fell_back, gpuName)
|
||||
else if (s.vkBridge) stringResource(R.string.setup_gpu_bridge_detail, gpuName)
|
||||
else stringResource(R.string.setup_gpu_unsupported_detail, gpuName)
|
||||
},
|
||||
divider = divider,
|
||||
// Not an Adreno: the experimental Vulkan bridge is the one way to draw.
|
||||
action = if (s.adreno) null else { {
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
SecondaryButton(
|
||||
stringResource(if (s.venus) R.string.setup_gpu_venus_on else R.string.setup_gpu_venus_off),
|
||||
enabled = !s.sessionRunning, compact = true, onClick = { a.onVenus(!s.venus) },
|
||||
)
|
||||
SecondaryButton(
|
||||
stringResource(if (s.vkBridge) R.string.setup_gpu_bridge_on else R.string.setup_gpu_bridge_off),
|
||||
enabled = !s.sessionRunning, compact = true, onClick = { a.onVkBridge(!s.vkBridge) },
|
||||
)
|
||||
}
|
||||
} },
|
||||
)
|
||||
}
|
||||
val runtimeCheck: @Composable (Boolean) -> Unit = { divider ->
|
||||
@@ -402,6 +421,8 @@ internal fun SetupPanel(
|
||||
SettingsGroup(stringResource(R.string.setup_tab_diagnostics)) {
|
||||
ToggleRow(host, "logs", stringResource(R.string.setup_logs), stringResource(R.string.setup_logs_hint), s.logsEnabled) { a.onLogs() }
|
||||
ToggleRow(host, "agent-commands", stringResource(R.string.setup_agent_commands), null, s.agentCommands) { a.onAgentCommands() }
|
||||
ToggleRow(host, "graphics-logs", stringResource(R.string.setup_graphics_logs), stringResource(R.string.setup_graphics_logs_hint), s.graphicsLogs) { a.onGraphicsLogs() }
|
||||
if (!s.adreno && com.droiddeck.launcher.session.SessionPrefs.steamGpuCompositingAllowed()) ToggleRow(host, "steam-gpu-drawing", stringResource(R.string.setup_steam_gpu_drawing), stringResource(R.string.setup_steam_gpu_drawing_hint), s.steamGpuDrawing) { a.onSteamGpuDrawing() }
|
||||
ActionRow(stringResource(R.string.setup_latest_logs), stringResource(R.string.drawer_logs_hint), stringResource(R.string.drawer_share_logs), a.onShareLogs,
|
||||
progress = com.droiddeck.launcher.session.SessionLogShare.progress)
|
||||
ActionRow(stringResource(R.string.setup_saved_logs), stringResource(R.string.setup_saved_logs_hint, com.droiddeck.launcher.session.SessionPaths.KEEP_SESSIONS), stringResource(R.string.setup_clear_logs), a.onClearLogs)
|
||||
|
||||
@@ -84,6 +84,9 @@ class GpuDriversState(
|
||||
val supported: Boolean = true,
|
||||
val unsupported: Boolean = false,
|
||||
val auto: Boolean = true,
|
||||
val powerVr: Boolean = false,
|
||||
/** The selected runtime supplies DXVK for PowerVR game launches. */
|
||||
val systemPowerVr: Boolean = false,
|
||||
val pairs: List<PairRow> = emptyList(),
|
||||
/** The pair key being installed, and how far along (-1 = unknown). */
|
||||
val busy: String? = null,
|
||||
|
||||
@@ -263,6 +263,8 @@ class DrawerActions(
|
||||
val onClose: () -> Unit,
|
||||
/** Games tab: every Proton with what it uses; null until first read. */
|
||||
val components: ComponentsManager.Snapshot? = null,
|
||||
/** DXVK is supplied by the selected system PowerVR runtime. */
|
||||
val systemPowerVr: Boolean = false,
|
||||
/** Re-reads the Protons (and runs swaps that waited for a game to close). */
|
||||
val onComponentsRefresh: () -> Unit = {},
|
||||
/** Installed games available for profile inspection in the session drawer. */
|
||||
@@ -1049,7 +1051,11 @@ private fun SelectedGameProfileGroup(host: MenuHost, a: DrawerActions, track: (S
|
||||
for (component in ComponentsManager.COMPONENTS) {
|
||||
val value = profile.components.getValue(component)
|
||||
if (!value.inherited) {
|
||||
ProfileSummaryRow(ComponentsManager.LABEL.getValue(component), profileValueLabel(value))
|
||||
ProfileSummaryRow(
|
||||
ComponentsManager.LABEL.getValue(component),
|
||||
if (ComponentsManager.runtimeManaged(component, a.systemPowerVr)) stringResource(R.string.gpu_system_powervr)
|
||||
else profileValueLabel(value),
|
||||
)
|
||||
}
|
||||
}
|
||||
if (profile.startWithoutSteam) {
|
||||
@@ -1151,20 +1157,23 @@ private fun ComponentsDrawerPage(host: MenuHost, a: DrawerActions, track: (Strin
|
||||
}
|
||||
for (comp in ComponentsManager.COMPONENTS) {
|
||||
val value = gameProfile.components.getValue(comp)
|
||||
val managedDxvk = ComponentsManager.runtimeManaged(comp, a.systemPowerVr)
|
||||
val options: List<Pair<String?, String>> =
|
||||
listOf(null to stringResource(R.string.comp_game_use_general)) +
|
||||
snap.packages.filter { it.comp == comp }.map { it.file to it.version }
|
||||
if (managedDxvk) emptyList() else snap.packages.filter { it.comp == comp }.map { it.file to it.version }
|
||||
DrawerStackedChoice(
|
||||
host = host,
|
||||
key = "game-cmp-$comp",
|
||||
label = ComponentsManager.LABEL.getValue(comp),
|
||||
hint = if (value.inherited) {
|
||||
hint = if (managedDxvk) stringResource(R.string.cmgr_powervr_dxvk_managed) else if (value.inherited) {
|
||||
stringResource(R.string.drawer_component_inherited, value.value)
|
||||
} else {
|
||||
null
|
||||
},
|
||||
options = options,
|
||||
selected = gameProfile.componentFiles[comp],
|
||||
enabled = !managedDxvk || gameProfile.componentFiles[comp] != null,
|
||||
valueLabel = if (managedDxvk) stringResource(R.string.gpu_system_powervr) else null,
|
||||
chipModifier = track("cmp-$comp"),
|
||||
onPick = { file -> a.onGameComponent(gameProfile.appId, comp, file) },
|
||||
)
|
||||
@@ -1200,7 +1209,11 @@ private fun ComponentsDrawerPage(host: MenuHost, a: DrawerActions, track: (Strin
|
||||
for (comp in ComponentsManager.COMPONENTS) {
|
||||
Row(modifier = Modifier.fillMaxWidth().padding(top = 3.dp)) {
|
||||
Text(ComponentsManager.LABEL.getValue(comp), fontSize = 12.sp, color = colors.onSurfaceVariant, modifier = Modifier.width(96.dp))
|
||||
Text(r.components.getValue(comp).inUse, fontSize = 12.sp, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
Text(
|
||||
if (ComponentsManager.runtimeManaged(comp, a.systemPowerVr)) stringResource(R.string.gpu_system_powervr)
|
||||
else r.components.getValue(comp).inUse,
|
||||
fontSize = 12.sp, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1228,17 +1241,22 @@ private fun ComponentsDrawerPage(host: MenuHost, a: DrawerActions, track: (Strin
|
||||
val build = ComponentsManager.safeName(p.version)
|
||||
for (comp in ComponentsManager.COMPONENTS) {
|
||||
val st = view.components.getValue(comp)
|
||||
val managedDxvk = ComponentsManager.runtimeManaged(comp, a.systemPowerVr)
|
||||
val originals = view.originals.filter { it.comp == comp }
|
||||
val options = originals.map { "orig:${it.protonVersion}" to (if (it.protonVersion == build) originalLabel else stringResource(R.string.comp_original, it.protonVersion)) } +
|
||||
snap.packages.filter { it.comp == comp }.map { it.file to it.version }
|
||||
if (options.isEmpty()) continue
|
||||
if (options.isEmpty() && !managedDxvk) continue
|
||||
val current = st.activeFile ?: "orig:$build"
|
||||
val shown = options.firstOrNull { it.first == current }?.second
|
||||
DrawerStackedChoice(
|
||||
host, "cmp-$comp", ComponentsManager.LABEL.getValue(comp),
|
||||
// The box already shows the choice: only say more when there is more to say.
|
||||
st.queued?.let { stringResource(R.string.comp_next_queued, it) } ?: st.inUse.takeIf { it != shown },
|
||||
if (managedDxvk) stringResource(R.string.cmgr_powervr_dxvk_managed) +
|
||||
(st.queued?.let { "\n" + stringResource(R.string.cmgr_powervr_dxvk_queued, it) } ?: "")
|
||||
else st.queued?.let { stringResource(R.string.comp_next_queued, it) } ?: st.inUse.takeIf { it != shown },
|
||||
options, current,
|
||||
enabled = !managedDxvk,
|
||||
valueLabel = if (managedDxvk) stringResource(R.string.gpu_system_powervr) else null,
|
||||
note = if (view.inUseByGame) stringResource(R.string.comp_waits_long) else stringResource(R.string.comp_applies_long),
|
||||
chipModifier = track("cmp-$comp"),
|
||||
onPick = { v -> if (v != current || st.queued != null) a.onComponentSwap(p.id, comp, v) },
|
||||
@@ -1259,11 +1277,11 @@ private fun ComponentsDrawerPage(host: MenuHost, a: DrawerActions, track: (Strin
|
||||
private fun <T> DrawerStackedChoice(
|
||||
host: MenuHost, key: String, label: String, hint: String?,
|
||||
options: List<Pair<T, String>>, selected: T, note: String? = null,
|
||||
chipModifier: Modifier = Modifier, onPick: (T) -> Unit,
|
||||
chipModifier: Modifier = Modifier, enabled: Boolean = true, valueLabel: String? = null, onPick: (T) -> Unit,
|
||||
) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val open = host.open == key
|
||||
val open = host.open == key && enabled
|
||||
Column(
|
||||
modifier = Modifier.fillMaxWidth()
|
||||
.background(if (open) pal.signal.copy(alpha = 0.10f) else Color.Transparent)
|
||||
@@ -1271,7 +1289,7 @@ private fun <T> DrawerStackedChoice(
|
||||
) {
|
||||
Text(label, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground)
|
||||
Box(modifier = Modifier.fillMaxWidth().padding(top = 6.dp)) {
|
||||
ValueChip(options.firstOrNull { it.first == selected }?.second ?: "-", open, modifier = chipModifier.fillMaxWidth()) {
|
||||
ValueChip(valueLabel ?: options.firstOrNull { it.first == selected }?.second ?: "-", open, enabled = enabled, modifier = chipModifier.fillMaxWidth()) {
|
||||
host.open = if (open) null else key
|
||||
}
|
||||
AnchoredMenu(open, onDismiss = { if (host.open == key) host.open = null }, title = label, note = note) { firstItemFocus ->
|
||||
|
||||
@@ -588,7 +588,7 @@
|
||||
<string name="setup_gpu_unsupported">GPU no compatible</string>
|
||||
<string name="setup_gpu_detail">%1$s · %2$s</string>
|
||||
<string name="setup_gpu_untested_detail">%1$s: %2$s</string>
|
||||
<string name="setup_gpu_unsupported_detail">Steam necesita un controlador Adreno; %1$s puede mostrar una pantalla negra</string>
|
||||
<string name="setup_gpu_unsupported_detail">No hay un motor gráfico compatible disponible; %1$s puede mostrar una pantalla negra</string>
|
||||
<string name="setup_runtime">Runtime de Linux</string>
|
||||
<string name="setup_runtime_progress">%1$s · %2$d%%</string>
|
||||
<string name="setup_runtime_missing">No instalado · unos 3 GB, se instala al jugar por primera vez</string>
|
||||
@@ -1107,10 +1107,10 @@
|
||||
<string name="main_wadb_unavailable">La Depuración inalámbrica no está disponible</string>
|
||||
<string name="main_adb_copied">Comando ADB copiado</string>
|
||||
<string name="main_pick_roms">Elige la carpeta de ROMs</string>
|
||||
<string name="main_non_adreno_title">La GPU no es Adreno</string>
|
||||
<string name="main_non_adreno_title">GPU no compatible</string>
|
||||
|
||||
<!-- %1$s is the GPU's name, %2$.0f the download size in MB -->
|
||||
<string name="main_non_adreno_text">Turnip es compatible con GPU Adreno. En %1$s, Steam puede mostrar una pantalla negra. Descarga: %2$.0f MB.</string>
|
||||
<string name="main_non_adreno_text">No hay un motor gráfico compatible disponible para %1$s. Steam puede mostrar una pantalla negra. Descarga: %2$.0f MB.</string>
|
||||
<string name="main_install_anyway">Instalar de todos modos</string>
|
||||
<string name="main_remove_runtime_title">Eliminar el runtime de Linux</string>
|
||||
<string name="main_remove_runtime_text">Esto elimina el runtime, el cliente de Steam que contiene y todos los juegos instalados en él.</string>
|
||||
@@ -1934,7 +1934,7 @@
|
||||
<string name="gpuinfo_supported">Compatible</string>
|
||||
<string name="gpuinfo_experimental">Experimental: sus controladores son versiones de prueba</string>
|
||||
<string name="gpuinfo_below_tested">Por debajo del hardware probado (Adreno 725 y posteriores): puede que no funcione</string>
|
||||
<string name="gpuinfo_unsupported">No compatible: DroidDeck necesita una GPU Adreno (Snapdragon)</string>
|
||||
<string name="gpuinfo_unsupported">No compatible: no hay un motor gráfico compatible disponible para esta GPU</string>
|
||||
|
||||
<!-- Driver downloads and imports -->
|
||||
<string name="turnip_rate_limited">Se alcanzó el límite de solicitudes de GitHub - inténtalo más tarde</string>
|
||||
|
||||
@@ -471,7 +471,7 @@
|
||||
<string name="setup_gpu_unsupported">GPU non pris en charge</string>
|
||||
<string name="setup_gpu_detail">%1$s · %2$s</string>
|
||||
<string name="setup_gpu_untested_detail">%1$s : %2$s</string>
|
||||
<string name="setup_gpu_unsupported_detail">Steam nécessite un pilote Adreno ; %1$s peut afficher un écran noir.</string>
|
||||
<string name="setup_gpu_unsupported_detail">Aucun moteur graphique compatible n’est disponible ; %1$s peut afficher un écran noir.</string>
|
||||
<string name="setup_runtime">Environnement d\'exécution Linux</string>
|
||||
<string name="setup_runtime_progress">%1$s · %2$d%%</string>
|
||||
<string name="setup_runtime_missing">Non installé · Environ 3 Go, installé lors du premier lancement d\'un jeu</string>
|
||||
|
||||
@@ -584,7 +584,7 @@
|
||||
<string name="setup_gpu_unsupported">GPUはサポートされていません</string>
|
||||
<string name="setup_gpu_detail">%1$s · %2$s</string>
|
||||
<string name="setup_gpu_untested_detail">%1$s:%2$s</string>
|
||||
<string name="setup_gpu_unsupported_detail">SteamにはAdrenoドライバーが必要です。%1$sでは画面が真っ暗になる可能性があります。</string>
|
||||
<string name="setup_gpu_unsupported_detail">利用できる互換グラフィックスバックエンドがありません。%1$sでは画面が真っ暗になる可能性があります。</string>
|
||||
<string name="setup_runtime">Linux実行環境</string>
|
||||
<string name="setup_runtime_progress">%1$s · %2$d%%</string>
|
||||
<string name="setup_runtime_missing">未インストール · 約3GB、初回ゲーム起動時にインストール</string>
|
||||
@@ -1089,10 +1089,10 @@
|
||||
<string name="main_wadb_unavailable">ワイヤレスデバッグは利用できません</string>
|
||||
<string name="main_adb_copied">ADBコマンドをコピーしました</string>
|
||||
<string name="main_pick_roms">ROMフォルダを選択</string>
|
||||
<string name="main_non_adreno_title">Adreno GPUではありません</string>
|
||||
<string name="main_non_adreno_title">サポート対象外のGPU</string>
|
||||
|
||||
<!-- %1$s is the GPU's name, %2$.0f the download size in MB -->
|
||||
<string name="main_non_adreno_text">TurnipはAdreno GPUをサポートしています。%1$sでは、Steamの画面が真っ暗になる可能性があります。ダウンロード:%2$.0f MB。</string>
|
||||
<string name="main_non_adreno_text">%1$sで利用できる互換グラフィックスバックエンドがありません。Steamの画面が真っ暗になる可能性があります。ダウンロード:%2$.0f MB。</string>
|
||||
<string name="main_install_anyway">インストールする</string>
|
||||
<string name="main_remove_runtime_title">Linux実行環境を削除</string>
|
||||
<string name="main_remove_runtime_text">実行環境、その中のSteamクライアント、そこにインストールされたすべてのゲームが削除されます。</string>
|
||||
@@ -1894,7 +1894,7 @@
|
||||
<string name="gpuinfo_supported">サポート対象</string>
|
||||
<string name="gpuinfo_experimental">実験的:ドライバーはテストビルドです</string>
|
||||
<string name="gpuinfo_below_tested">テスト済みハードウェア(Adreno 725以降)未満:動作しない可能性があります</string>
|
||||
<string name="gpuinfo_unsupported">サポート対象外:DroidDeckにはAdreno(Snapdragon)GPUが必要です</string>
|
||||
<string name="gpuinfo_unsupported">サポート対象外:このGPUで利用できる互換グラフィックスバックエンドがありません</string>
|
||||
|
||||
<!-- Driver downloads and imports -->
|
||||
<string name="turnip_rate_limited">GitHubのレート制限に達しました。後でもう一度お試しください</string>
|
||||
|
||||
@@ -584,7 +584,7 @@
|
||||
<string name="setup_gpu_unsupported">GPU 지원되지 않음</string>
|
||||
<string name="setup_gpu_detail">%1$s · %2$s</string>
|
||||
<string name="setup_gpu_untested_detail">%1$s: %2$s</string>
|
||||
<string name="setup_gpu_unsupported_detail">Steam에는 Adreno 드라이버가 필요합니다. %1$s에서 화면이 검게 변할 수 있습니다.</string>
|
||||
<string name="setup_gpu_unsupported_detail">사용할 수 있는 호환 그래픽 백엔드가 없습니다. %1$s에서 화면이 검게 표시될 수 있습니다.</string>
|
||||
<string name="setup_runtime">Linux 런타임</string>
|
||||
<string name="setup_runtime_progress">%1$s · %2$d%%</string>
|
||||
<string name="setup_runtime_missing">설치되지 않음 · 약 3GB, 처음 \"Steam 실행\" 시 설치</string>
|
||||
@@ -1089,10 +1089,10 @@
|
||||
<string name="main_wadb_unavailable">무선 디버깅을 사용할 수 없습니다</string>
|
||||
<string name="main_adb_copied">ADB 명령이 복사되었습니다</string>
|
||||
<string name="main_pick_roms">ROM 폴더 선택</string>
|
||||
<string name="main_non_adreno_title">Adreno GPU가 아님</string>
|
||||
<string name="main_non_adreno_title">지원되지 않는 GPU</string>
|
||||
|
||||
<!-- %1$s is the GPU's name, %2$.0f the download size in MB -->
|
||||
<string name="main_non_adreno_text">Turnip은 Adreno GPU를 지원합니다. %1$s에서는 Steam 화면이 검게 표시될 수 있습니다. 다운로드: %2$.0f MB.</string>
|
||||
<string name="main_non_adreno_text">%1$s에서 사용할 수 있는 호환 그래픽 백엔드가 없습니다. Steam 화면이 검게 표시될 수 있습니다. 다운로드: %2$.0f MB.</string>
|
||||
<string name="main_install_anyway">그래도 설치</string>
|
||||
<string name="main_remove_runtime_title">Linux 런타임 제거</string>
|
||||
<string name="main_remove_runtime_text">런타임과 그 안의 Steam 클라이언트, 그리고 런타임에 설치된 모든 게임이 삭제됩니다.</string>
|
||||
@@ -1894,7 +1894,7 @@
|
||||
<string name="gpuinfo_supported">지원됨</string>
|
||||
<string name="gpuinfo_experimental">실험적: 드라이버가 테스트 빌드입니다</string>
|
||||
<string name="gpuinfo_below_tested">테스트된 하드웨어(Adreno 725 이상)보다 낮음: 실행되지 않을 수 있습니다</string>
|
||||
<string name="gpuinfo_unsupported">지원되지 않음: DroidDeck에는 Adreno(Snapdragon) GPU가 필요합니다</string>
|
||||
<string name="gpuinfo_unsupported">지원되지 않음: 이 GPU에서 사용할 수 있는 호환 그래픽 백엔드가 없습니다</string>
|
||||
|
||||
<!-- Driver downloads and imports -->
|
||||
<string name="turnip_rate_limited">GitHub 요청 한도에 도달했습니다. 나중에 다시 시도하세요</string>
|
||||
|
||||
@@ -546,7 +546,7 @@
|
||||
<string name="setup_gpu_unsupported">GPU не поддерживается</string>
|
||||
<string name="setup_gpu_detail">%1$s · %2$s</string>
|
||||
<string name="setup_gpu_untested_detail">%1$s: %2$s</string>
|
||||
<string name="setup_gpu_unsupported_detail">Steam требует драйвер Adreno; на %1$s возможен черный экран.</string>
|
||||
<string name="setup_gpu_unsupported_detail">Совместимый графический бэкенд недоступен; на %1$s возможен черный экран.</string>
|
||||
<string name="setup_runtime">Среда выполнения Linux</string>
|
||||
<string name="setup_runtime_progress">%1$s · %2$d%%</string>
|
||||
<string name="setup_runtime_missing">Не установлено · около 3 ГБ, устанавливается при первом запуске игры</string>
|
||||
|
||||
@@ -584,7 +584,7 @@
|
||||
<string name="setup_gpu_unsupported">GPU 不受支持</string>
|
||||
<string name="setup_gpu_detail">%1$s · %2$s</string>
|
||||
<string name="setup_gpu_untested_detail">%1$s:%2$s</string>
|
||||
<string name="setup_gpu_unsupported_detail">Steam 需要 Adreno 驱动;%1$s 可能显示黑屏</string>
|
||||
<string name="setup_gpu_unsupported_detail">没有可用的兼容图形后端;%1$s 可能显示黑屏</string>
|
||||
<string name="setup_runtime">Linux 运行时</string>
|
||||
<string name="setup_runtime_progress">%1$s · %2$d%%</string>
|
||||
<string name="setup_runtime_missing">未安装 · 约 3 GB,首次点“游玩”时安装</string>
|
||||
@@ -1089,10 +1089,10 @@
|
||||
<string name="main_wadb_unavailable">无线调试不可用</string>
|
||||
<string name="main_adb_copied">已复制 ADB 命令</string>
|
||||
<string name="main_pick_roms">选择 ROM 文件夹</string>
|
||||
<string name="main_non_adreno_title">不是 Adreno GPU</string>
|
||||
<string name="main_non_adreno_title">不受支持的 GPU</string>
|
||||
|
||||
<!-- %1$s is the GPU's name, %2$.0f the download size in MB -->
|
||||
<string name="main_non_adreno_text">Turnip 支持 Adreno GPU。在 %1$s 上,Steam 可能显示黑屏。需下载:%2$.0f MB。</string>
|
||||
<string name="main_non_adreno_text">没有适用于 %1$s 的兼容图形后端。Steam 可能显示黑屏。需下载:%2$.0f MB。</string>
|
||||
<string name="main_install_anyway">仍要安装</string>
|
||||
<string name="main_remove_runtime_title">移除 Linux 运行时</string>
|
||||
<string name="main_remove_runtime_text">这会删除运行时、其中的 Steam 客户端,以及安装在其中的所有游戏。</string>
|
||||
@@ -1894,7 +1894,7 @@
|
||||
<string name="gpuinfo_supported">受支持</string>
|
||||
<string name="gpuinfo_experimental">实验性:其驱动为测试构建</string>
|
||||
<string name="gpuinfo_below_tested">低于已测试的硬件(Adreno 725 及更新):可能无法运行</string>
|
||||
<string name="gpuinfo_unsupported">不受支持:DroidDeck 需要 Adreno(骁龙)GPU</string>
|
||||
<string name="gpuinfo_unsupported">不受支持:没有适用于此 GPU 的兼容图形后端</string>
|
||||
|
||||
<!-- Driver downloads and imports -->
|
||||
<string name="turnip_rate_limited">已达到 GitHub 的请求频率限制 — 请稍后重试</string>
|
||||
|
||||
@@ -584,7 +584,7 @@
|
||||
<string name="setup_gpu_unsupported">GPU 不受支援</string>
|
||||
<string name="setup_gpu_detail">%1$s · %2$s</string>
|
||||
<string name="setup_gpu_untested_detail">%1$s:%2$s</string>
|
||||
<string name="setup_gpu_unsupported_detail">Steam 需要 Adreno 驅動程式;%1$s 可能會出現黑畫面</string>
|
||||
<string name="setup_gpu_unsupported_detail">沒有可用的兼容圖形後端;%1$s 可能會出現黑畫面</string>
|
||||
<string name="setup_runtime">Linux 運行環境</string>
|
||||
<string name="setup_runtime_progress">%1$s · %2$d%%</string>
|
||||
<string name="setup_runtime_missing">未安裝 · 約 3 GB,首次開啟 Steam 時安裝</string>
|
||||
@@ -1089,10 +1089,10 @@
|
||||
<string name="main_wadb_unavailable">無法使用無線偵錯</string>
|
||||
<string name="main_adb_copied">已複製 ADB 指令</string>
|
||||
<string name="main_pick_roms">選擇 ROM 資料夾</string>
|
||||
<string name="main_non_adreno_title">不是 Adreno GPU</string>
|
||||
<string name="main_non_adreno_title">不受支援的 GPU</string>
|
||||
|
||||
<!-- %1$s is the GPU's name, %2$.0f the download size in MB -->
|
||||
<string name="main_non_adreno_text">Turnip 支援 Adreno GPU。在 %1$s 上,Steam 可能會出現黑畫面。下載大小:%2$.0f MB。</string>
|
||||
<string name="main_non_adreno_text">沒有適用於 %1$s 的兼容圖形後端。Steam 可能會出現黑畫面。下載大小:%2$.0f MB。</string>
|
||||
<string name="main_install_anyway">仍要安裝</string>
|
||||
<string name="main_remove_runtime_title">移除 Linux 運行環境</string>
|
||||
<string name="main_remove_runtime_text">此操作會刪除運行環境、其中的 Steam 用戶端,以及安裝在其中的所有遊戲。</string>
|
||||
@@ -1894,7 +1894,7 @@
|
||||
<string name="gpuinfo_supported">受支援</string>
|
||||
<string name="gpuinfo_experimental">實驗性:其驅動程式為測試版本</string>
|
||||
<string name="gpuinfo_below_tested">低於已測試的硬件(Adreno 725 或更新):可能無法執行</string>
|
||||
<string name="gpuinfo_unsupported">不受支援:DroidDeck 需要 Adreno (Snapdragon) GPU</string>
|
||||
<string name="gpuinfo_unsupported">不受支援:沒有適用於此 GPU 的兼容圖形後端</string>
|
||||
|
||||
<!-- Driver downloads and imports -->
|
||||
<string name="turnip_rate_limited">已達 GitHub 的速率限制 - 請稍後再試</string>
|
||||
|
||||
@@ -584,7 +584,7 @@
|
||||
<string name="setup_gpu_unsupported">GPU 不受支援</string>
|
||||
<string name="setup_gpu_detail">%1$s · %2$s</string>
|
||||
<string name="setup_gpu_untested_detail">%1$s:%2$s</string>
|
||||
<string name="setup_gpu_unsupported_detail">Steam 需要 Adreno 驅動程式;%1$s 可能出現黑畫面。</string>
|
||||
<string name="setup_gpu_unsupported_detail">沒有可用的相容圖形後端;%1$s 可能出現黑畫面。</string>
|
||||
<string name="setup_runtime">Linux 執行環境</string>
|
||||
<string name="setup_runtime_progress">%1$s · %2$d%%</string>
|
||||
<string name="setup_runtime_missing">未安裝 · 約 3 GB,首次點擊「執行」時安裝</string>
|
||||
@@ -1089,10 +1089,10 @@
|
||||
<string name="main_wadb_unavailable">無法使用無線偵錯</string>
|
||||
<string name="main_adb_copied">已複製 ADB 指令</string>
|
||||
<string name="main_pick_roms">選擇 ROM 資料夾</string>
|
||||
<string name="main_non_adreno_title">不是 Adreno GPU</string>
|
||||
<string name="main_non_adreno_title">不受支援的 GPU</string>
|
||||
|
||||
<!-- %1$s is the GPU's name, %2$.0f the download size in MB -->
|
||||
<string name="main_non_adreno_text">Turnip 支援 Adreno GPU。在 %1$s 上,Steam 可能會出現黑畫面。下載大小:%2$.0f MB。</string>
|
||||
<string name="main_non_adreno_text">沒有適用於 %1$s 的相容圖形後端。Steam 可能會出現黑畫面。下載大小:%2$.0f MB。</string>
|
||||
<string name="main_install_anyway">仍要安裝</string>
|
||||
<string name="main_remove_runtime_title">移除 Linux 執行環境</string>
|
||||
<string name="main_remove_runtime_text">這會刪除執行環境、其中的 Steam 用戶端,以及安裝在其中的所有遊戲。</string>
|
||||
@@ -1894,7 +1894,7 @@
|
||||
<string name="gpuinfo_supported">受支援</string>
|
||||
<string name="gpuinfo_experimental">實驗性:其驅動程式為測試版本</string>
|
||||
<string name="gpuinfo_below_tested">低於已測試的硬體(Adreno 725 及更新機型):可能無法執行</string>
|
||||
<string name="gpuinfo_unsupported">不受支援:DroidDeck 需要 Adreno(Snapdragon)GPU</string>
|
||||
<string name="gpuinfo_unsupported">不受支援:沒有適用於此 GPU 的相容圖形後端</string>
|
||||
|
||||
<!-- Driver downloads and imports -->
|
||||
<string name="turnip_rate_limited">已達 GitHub 速率限制 - 請稍後再試</string>
|
||||
|
||||
@@ -651,7 +651,7 @@
|
||||
<string name="setup_gpu_unsupported">GPU not supported</string>
|
||||
<string name="setup_gpu_detail">%1$s · %2$s</string>
|
||||
<string name="setup_gpu_untested_detail">%1$s: %2$s</string>
|
||||
<string name="setup_gpu_unsupported_detail">Steam needs an Adreno driver; %1$s may show a black screen</string>
|
||||
<string name="setup_gpu_unsupported_detail">No compatible graphics backend is available; %1$s may show a black screen</string>
|
||||
<string name="setup_runtime">Linux runtime</string>
|
||||
<string name="setup_runtime_progress">%1$s · %2$d%%</string>
|
||||
<string name="setup_runtime_missing">Not installed · about 3 GB, installed on first Play</string>
|
||||
@@ -679,6 +679,11 @@
|
||||
<string name="setup_logs">Session logs</string>
|
||||
<string name="setup_logs_hint">Saved after each session</string>
|
||||
<string name="setup_agent_commands">Debugging tools</string>
|
||||
<string name="setup_graphics_logs">Detailed graphics logs</string>
|
||||
<string name="setup_steam_gpu_drawing">Steam interface: GPU drawing</string>
|
||||
<string name="setup_steam_gpu_drawing_hint">With the Xclipse driver pair, Steam draws its pages in software (GPU drawing showed broken tiles). Turn on for a faster Steam interface if it looks right on this phone.</string>
|
||||
<string name="setup_gpu_bridge_fell_back">The Mali bridge failed its self-test on %1$s last session (images or draws), so the session used the PanVK driver pair instead.</string>
|
||||
<string name="setup_graphics_logs_hint">Each game\'s Proton, DXVK and driver logs in the session\'s logs. Always on when the GPU is not an Adreno.</string>
|
||||
<string name="setup_latest_logs">Latest session logs</string>
|
||||
<string name="setup_saved_logs">Saved session logs</string>
|
||||
<string name="setup_saved_logs_hint">Keeps the newest %1$d</string>
|
||||
@@ -1183,9 +1188,9 @@
|
||||
<string name="main_wadb_unavailable">Wireless debugging is unavailable</string>
|
||||
<string name="main_adb_copied">ADB command copied</string>
|
||||
<string name="main_pick_roms">Choose the ROMs folder</string>
|
||||
<string name="main_non_adreno_title">Not an Adreno GPU</string>
|
||||
<string name="main_non_adreno_title">Unsupported GPU</string>
|
||||
<!-- %1$s is the GPU's name, %2$.0f the download size in MB -->
|
||||
<string name="main_non_adreno_text">Turnip supports Adreno GPUs. On %1$s, Steam may show a black screen. Download: %2$.0f MB.</string>
|
||||
<string name="main_non_adreno_text">No compatible graphics backend is available for %1$s. Steam may show a black screen. Download: %2$.0f MB.</string>
|
||||
<string name="main_install_anyway">Install anyway</string>
|
||||
<string name="main_remove_runtime_title">Remove Linux runtime</string>
|
||||
<string name="main_remove_runtime_text">This deletes the runtime, the Steam client inside it, and every game installed there.</string>
|
||||
@@ -1902,10 +1907,19 @@
|
||||
|
||||
<!-- GPU support line -->
|
||||
<string name="gpuinfo_not_adreno">Not an Adreno GPU</string>
|
||||
<string name="gpuinfo_powervr">System PowerVR driver: compatibility varies by device</string>
|
||||
<string name="gpuinfo_xclipse">Experimental: RADV or the system Xclipse driver</string>
|
||||
<string name="gpu_system_powervr">System PowerVR</string>
|
||||
<string name="gpu_auto_system_hint">Uses the built-in drivers for this GPU</string>
|
||||
<string name="drivers_powervr_builtin">The system PowerVR driver is selected for the runtime and display.</string>
|
||||
<string name="drivers_mali_bridge_auto">No open driver covers this Mali yet: the Mali bridge is on.</string>
|
||||
<string name="drivers_mali_bridge_fallback">%1$s isn\'t published yet: the Mali bridge is on until it is.</string>
|
||||
<string name="cmgr_powervr_dxvk_queued">Queued: %1$s (waiting for a different runtime driver)</string>
|
||||
<string name="cmgr_powervr_dxvk_managed">DXVK is provided by the system PowerVR runtime. Other DXVK packages can be stored but are not applied with this driver.</string>
|
||||
<string name="gpuinfo_supported">Supported</string>
|
||||
<string name="gpuinfo_experimental">Experimental: its drivers are test builds</string>
|
||||
<string name="gpuinfo_below_tested">Below tested hardware (Adreno 725 and newer): it may not run</string>
|
||||
<string name="gpuinfo_unsupported">Not supported: DroidDeck needs an Adreno (Snapdragon) GPU</string>
|
||||
<string name="gpuinfo_unsupported">Not supported: no compatible graphics backend is available for this GPU</string>
|
||||
|
||||
<!-- Driver downloads and imports -->
|
||||
<string name="turnip_rate_limited">GitHub\'s rate limit was hit - try again later</string>
|
||||
@@ -2316,4 +2330,10 @@
|
||||
<string name="gog_achievements_enable_store">Enable GOG achievements in Stores settings</string>
|
||||
<string name="gog_achievements_unavailable">Achievements unavailable; check session logs</string>
|
||||
<string name="achievement_unlocked">Achievement unlocked</string>
|
||||
<string name="setup_gpu_venus_off">Mali (Venus): off</string>
|
||||
<string name="setup_gpu_venus_on">Mali (Venus): on</string>
|
||||
<string name="setup_gpu_bridge_off">Mali bridge: off</string>
|
||||
<string name="setup_gpu_bridge_unusable">%1$s cannot use the Mali bridge (it needs a Mali GPU without a system-driver route), so this switch has no effect here.</string>
|
||||
<string name="setup_gpu_bridge_on">Mali bridge: on</string>
|
||||
<string name="setup_gpu_bridge_detail">%1$s is not an Adreno. The experimental Vulkan bridge is on: the session draws through the phone\'s own driver. Expect bugs; send the session logs.</string>
|
||||
</resources>
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.droiddeck.launcher.core
|
||||
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class DeviceSupportTest {
|
||||
@Test fun runtimeDownloadAcceptsOnlyRecognizedGraphicsBackends() {
|
||||
assertTrue(DeviceSupport.graphicsAvailable(adreno = true, powerVrReady = false))
|
||||
assertTrue(DeviceSupport.graphicsAvailable(adreno = false, powerVrReady = true))
|
||||
// A PowerVR HAL without usable DRM access also reaches this unavailable case.
|
||||
assertFalse(DeviceSupport.graphicsAvailable(adreno = false, powerVrReady = false))
|
||||
}
|
||||
}
|
||||
@@ -60,6 +60,8 @@ class WinCompSourcesTest {
|
||||
|
||||
@Test fun steamworksSharedDepotsMapToComponents() {
|
||||
assertEquals(listOf("vcredist2015_dll" to "VC++ 2015", "d3dx9" to "DirectX (June 2010)"), WinCompSources.steamDepots(listOf("228986", "228990", "999")))
|
||||
// Hotline Miami's OpenAL depot: the DLL-copy entry, which installs without running anything.
|
||||
assertEquals(listOf("oalinst_dll" to "OpenAL"), WinCompSources.steamDepots(listOf("229020")))
|
||||
}
|
||||
|
||||
// ---- per source ----
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.droiddeck.launcher.gpu
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
|
||||
class DeviceInfoTest {
|
||||
@Test fun builtinLabelsDistinguishPowerVrFromTurnipAndGenericSystemVulkan() {
|
||||
assertEquals("System PowerVR", DeviceInfo.builtinDriverLabel(powerVr = true, runtime = true))
|
||||
assertEquals("System PowerVR", DeviceInfo.builtinDriverLabel(powerVr = true, runtime = false))
|
||||
assertEquals("the runtime's own Turnip", DeviceInfo.builtinDriverLabel(powerVr = false, runtime = true))
|
||||
assertEquals("System Vulkan", DeviceInfo.builtinDriverLabel(powerVr = false, runtime = false))
|
||||
}
|
||||
}
|
||||
@@ -42,6 +42,23 @@ class DriverPairsTest {
|
||||
assertEquals(GpuInfo.Support.UNSUPPORTED, gpu(0, adreno = false).support)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun powerVrUsesItsOwnFamilyWithoutClaimingAllModelsAreTested() {
|
||||
assertEquals(Family.POWERVR, GpuInfo.familyOf(false, 0, powerVr = true))
|
||||
assertEquals(Family.NOT_ADRENO, GpuInfo.familyOf(false, 0, powerVr = false))
|
||||
assertEquals(Family.A7XX, GpuInfo.familyOf(true, 740, powerVr = true))
|
||||
val powerVr = GpuInfo("PowerVR", 0, Family.POWERVR, "", false)
|
||||
assertEquals(GpuInfo.Support.UNTESTED, powerVr.support)
|
||||
assertNull("PowerVR never downloads an Adreno driver pair", DriverPairs.recommendedKey(powerVr, emptyList()))
|
||||
val pairs = DriverPairs.from(TurnipReleases.Check(
|
||||
listOf(asset("Turnip-r4.zip", "r4", false, DriverPairs.BANNER),
|
||||
asset("Turnip-r4-Linux.zip", "r4", true, DriverPairs.BANNER)),
|
||||
emptyList(), emptyList(), 0L,
|
||||
))
|
||||
assertFalse(pairs.single().suits(powerVr))
|
||||
assertNull(DriverPairs.recommendedKey(powerVr, pairs))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun autoPicksWinNativeBalancedOn8xxAndBannersElsewhere() {
|
||||
assertEquals(DriverPairs.WN_BALANCED, DriverPairs.recommendedKey(gpu(830), emptyList()))
|
||||
@@ -114,4 +131,111 @@ class DriverPairsTest {
|
||||
assertEquals(DriverPairs.WN_BALANCED, DriverPairs.recommendedKey(gpu(825), pairs))
|
||||
assertEquals(DriverPairs.BANNER, DriverPairs.recommendedKey(gpu(740), pairs))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun maliFamiliesFollowTheOpenDriverBuilds() {
|
||||
assertEquals(Family.MALI_JM, GpuInfo.familyOf(false, 0, mali = "Mali-G57 MC2"))
|
||||
assertEquals(Family.MALI_JM, GpuInfo.familyOf(false, 0, mali = "Mali-G77"))
|
||||
assertEquals(Family.MALI_G610_G710, GpuInfo.familyOf(false, 0, mali = "Mali-G710"))
|
||||
assertEquals(Family.MALI_G615, GpuInfo.familyOf(false, 0, mali = "Mali-G615 MC6"))
|
||||
assertEquals(Family.MALI_G720, GpuInfo.familyOf(false, 0, mali = "Mali-G720-Immortalis MC12"))
|
||||
assertEquals(Family.MALI_LATEST, GpuInfo.familyOf(false, 0, mali = "Mali-G925-Immortalis MC12"))
|
||||
assertEquals(Family.MALI_OTHER, GpuInfo.familyOf(false, 0, mali = "Mali-T880"))
|
||||
assertEquals(Family.MALI_OTHER, GpuInfo.familyOf(false, 0, mali = ""))
|
||||
// An Adreno is an Adreno whatever else the device reports, and the system HAL keeps priority.
|
||||
assertEquals(Family.A7XX, GpuInfo.familyOf(true, 740, mali = "Mali-G720"))
|
||||
assertEquals(Family.POWERVR, GpuInfo.familyOf(false, 0, powerVr = true, mali = "Mali-G720"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun autoPicksTheOpenDriverForEachMaliAndNothingForTheRest() {
|
||||
fun mali(name: String) = GpuInfo(name, 0, GpuInfo.familyOf(false, 0, mali = name), "", false)
|
||||
// Android 14: the per-generation builds; the newest Malis have none and use the bridge.
|
||||
assertEquals(DriverPairs.NAD_MALI_JM, DriverPairs.recommendedKey(mali("Mali-G57"), emptyList(), sdk = 34))
|
||||
assertEquals(DriverPairs.NAD_MALI_G710, DriverPairs.recommendedKey(mali("Mali-G710"), emptyList(), sdk = 34))
|
||||
assertEquals(DriverPairs.NAD_MALI_G615, DriverPairs.recommendedKey(mali("Mali-G615"), emptyList(), sdk = 34))
|
||||
assertEquals(DriverPairs.NAD_MALI_G720, DriverPairs.recommendedKey(mali("Mali-G720"), emptyList(), sdk = 34))
|
||||
assertNull(DriverPairs.recommendedKey(mali("Mali-G925-Immortalis MC12"), emptyList(), sdk = 34))
|
||||
// Android 15+: the one-binary kbase build for every Mali it covers, not the Bifrost G52/G76.
|
||||
assertEquals(DriverPairs.NAD_MALI_KBASE, DriverPairs.recommendedKey(mali("Mali-G57"), emptyList(), sdk = 35))
|
||||
assertEquals(DriverPairs.NAD_MALI_KBASE, DriverPairs.recommendedKey(mali("Mali-G720"), emptyList(), sdk = 36))
|
||||
assertEquals(DriverPairs.NAD_MALI_KBASE, DriverPairs.recommendedKey(mali("Mali-G925-Immortalis MC12"), emptyList(), sdk = 36))
|
||||
assertEquals(DriverPairs.NAD_MALI_JM, DriverPairs.recommendedKey(mali("Mali-G52 MC2"), emptyList(), sdk = 36))
|
||||
assertNull("a Mali no build covers uses the bridge", DriverPairs.recommendedKey(mali("Mali-T880"), emptyList(), sdk = 36))
|
||||
assertEquals(DriverPairs.BANNER, DriverPairs.recommendedKey(gpu(740), emptyList()))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aMissingKbaseReleaseFallsBackToTheGenerationsPair() {
|
||||
val g720 = GpuInfo("Mali-G720", 0, Family.MALI_G720, "", false)
|
||||
fun bundle(id: String) = TurnipReleases.Asset("Non-Adreno", id.lowercase(), "$id-Pair.zip", "https://example/$id", 9_000_000,
|
||||
false, "label", "0".repeat(64), DriverPairs.nonAdreno(id), bundle = true)
|
||||
val onlyG720 = DriverPairs.from(TurnipReleases.Check(listOf(bundle("PanVK-Mali-G720")), emptyList(), emptyList(), 0L))
|
||||
assertEquals(DriverPairs.NAD_MALI_G720, DriverPairs.recommendedKey(g720, onlyG720, sdk = 36))
|
||||
val both = DriverPairs.from(TurnipReleases.Check(listOf(bundle("PanVK-Mali-G720"), bundle("PanVK-Mali-kbase")), emptyList(), emptyList(), 0L))
|
||||
assertEquals(DriverPairs.NAD_MALI_KBASE, DriverPairs.recommendedKey(g720, both, sdk = 36))
|
||||
assertTrue(both.single { it.key == DriverPairs.NAD_MALI_KBASE }.suits(g720))
|
||||
assertFalse(both.single { it.key == DriverPairs.NAD_MALI_KBASE }.suits(GpuInfo("Mali-G52", 0, Family.MALI_JM, "", false)))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun nonAdrenoPairsComeFromTheirBundlesAndSuitOnlyTheirGpu() {
|
||||
val pairs = DriverPairs.from(TurnipReleases.Check(
|
||||
listOf(
|
||||
TurnipReleases.Asset("Non-Adreno", "panvk-mali-g720", "PanVK-Mali-G720-Pair.zip", "https://example/a", 9_000_000,
|
||||
false, "label", "0".repeat(64), DriverPairs.nonAdreno("PanVK-Mali-G720"), bundle = true),
|
||||
TurnipReleases.Asset("Non-Adreno", "radv-xclipse", "RADV-Xclipse-Pair.zip", "https://example/b", 9_000_000,
|
||||
false, "label", "0".repeat(64), DriverPairs.nonAdreno("RADV-Xclipse"), bundle = true),
|
||||
),
|
||||
emptyList(), emptyList(), 0L,
|
||||
))
|
||||
val g720 = pairs.single { it.key == DriverPairs.NAD_MALI_G720 }
|
||||
val radv = pairs.single { it.key == DriverPairs.NAD_RADV_XCLIPSE }
|
||||
assertTrue(g720.complete)
|
||||
assertTrue(g720.suits(GpuInfo("Mali-G720", 0, Family.MALI_G720, "", false)))
|
||||
assertFalse(g720.suits(gpu(740)))
|
||||
assertTrue(radv.suits(GpuInfo("Xclipse", 0, Family.POWERVR, "", false)))
|
||||
assertFalse("RADV is not for a PowerVR Pixel", radv.suits(GpuInfo("PowerVR", 0, Family.POWERVR, "", false)))
|
||||
assertTrue(DriverPairs.isNonAdreno("PanVK-Mali-G720"))
|
||||
assertTrue(DriverPairs.isNonAdreno("RADV-Xclipse-2"))
|
||||
assertFalse(DriverPairs.isNonAdreno("DD-Turnip-v0.1.0"))
|
||||
assertFalse(DriverPairs.isNonAdreno(null))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun deviceBuildsAreOfferedOnlyForTheirMaliAndNeverByAuto() {
|
||||
fun bundle(id: String) = TurnipReleases.Asset("Non-Adreno", id.lowercase(), "$id-Pair.zip", "https://example/$id", 9_000_000,
|
||||
false, "label", "0".repeat(64), DriverPairs.nonAdreno(id), bundle = true)
|
||||
val pairs = DriverPairs.from(TurnipReleases.Check(
|
||||
listOf(bundle("PanVK-faux123-RP4Pro"), bundle("PanVK-faux123-Ace"), bundle("PanVK-faux123-RG556")),
|
||||
emptyList(), emptyList(), 0L))
|
||||
val g77 = GpuInfo("Mali-G77 MC9", 0, Family.MALI_JM, "", false)
|
||||
val g57 = GpuInfo("Mali-G57 MC2", 0, Family.MALI_JM, "", false)
|
||||
val g610 = GpuInfo("Mali-G610 MC6", 0, Family.MALI_G610_G710, "", false)
|
||||
assertTrue(pairs.single { it.key == DriverPairs.NAD_FAUX_RP4PRO }.suits(g77))
|
||||
assertFalse(pairs.single { it.key == DriverPairs.NAD_FAUX_RP4PRO }.suits(g57))
|
||||
assertTrue(pairs.single { it.key == DriverPairs.NAD_FAUX_RG556 }.suits(g57))
|
||||
assertTrue(pairs.single { it.key == DriverPairs.NAD_FAUX_ACE }.suits(g610))
|
||||
assertEquals(DriverPairs.NAD_MALI_JM, DriverPairs.recommendedKey(g77, pairs, sdk = 34))
|
||||
assertTrue(DriverPairs.isNonAdreno("PanVK-faux123-RP4Pro"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aMaliTheDeviceDoesNotNameIsKnownByItsChip() {
|
||||
assertEquals("Mali-G720 (by chip mt6989)", GpuInfo.maliOfSoc(listOf("", "mt6989")))
|
||||
assertEquals("Mali-G710 (by chip gs201)", GpuInfo.maliOfSoc(listOf("GS201")))
|
||||
assertEquals(null, GpuInfo.maliOfSoc(listOf("unknown-chip")))
|
||||
// An Exynos with a Mali, and a Helio G99, by board name.
|
||||
assertEquals(Family.MALI_JM, GpuInfo.familyOf(false, 0, mali = GpuInfo.maliOfSoc(listOf("s5e8835"))))
|
||||
assertEquals(Family.MALI_JM, GpuInfo.familyOf(false, 0, mali = GpuInfo.maliOfSoc(listOf("MT6789"))))
|
||||
assertEquals(Family.MALI_G720, GpuInfo.familyOf(false, 0, mali = "Mali-G720 (by chip mt6989)"))
|
||||
assertEquals(Family.MALI_LATEST, GpuInfo.familyOf(false, 0, mali = "Mali-G925 (by chip mt6991)"))
|
||||
assertTrue(GpuInfo.maliKbaseCovered("Mali-G720 (by chip mt6989)"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun autoTakesRadvOnAnXclipseAndLeavesPowerVrOnTheSystemDriver() {
|
||||
assertEquals(DriverPairs.NAD_RADV_XCLIPSE, DriverPairs.recommendedKey(GpuInfo("Samsung Xclipse 940", 0, Family.POWERVR, "", false), emptyList()))
|
||||
assertNull(DriverPairs.recommendedKey(GpuInfo("PowerVR", 0, Family.POWERVR, "", false), emptyList()))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
package com.droiddeck.launcher.gpu
|
||||
|
||||
import java.io.File
|
||||
import java.nio.file.Files
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.rules.TemporaryFolder
|
||||
|
||||
class SystemVulkanPruningTest {
|
||||
@get:Rule val temporary = TemporaryFolder()
|
||||
|
||||
@Test fun completedReplacementCollectsOnlyManagedOldDirectories() {
|
||||
val base = temporary.newFolder("system_vulkan")
|
||||
val current = completeRuntime(base, "a".repeat(64))
|
||||
val old = completeRuntime(base, "b".repeat(64))
|
||||
val stage = abandonedStage(base)
|
||||
val unrelated = File(base, "notes").apply { mkdir(); File(this, "keep").writeText("keep") }
|
||||
|
||||
SystemVulkanDriver.pruneUnused(current, true)
|
||||
|
||||
assertEquals("current ICD", File(current, "icd.json").readText())
|
||||
assertTrue(File(current, "run-proton.py").canExecute())
|
||||
assertFalse(old.exists())
|
||||
assertFalse(stage.exists())
|
||||
assertEquals("keep", File(unrelated, "keep").readText())
|
||||
}
|
||||
|
||||
@Test fun aSurvivingGuestKeepsOldVersionsButNotAbandonedStages() {
|
||||
val base = temporary.newFolder("system_vulkan")
|
||||
val current = completeRuntime(base, "a".repeat(64))
|
||||
val old = completeRuntime(base, "b".repeat(64))
|
||||
val stage = abandonedStage(base)
|
||||
|
||||
SystemVulkanDriver.pruneUnused(current, false)
|
||||
|
||||
assertTrue(current.isDirectory)
|
||||
assertTrue(old.isDirectory)
|
||||
assertFalse(stage.exists())
|
||||
SystemVulkanDriver.pruneUnused(current, true)
|
||||
assertFalse("collect the old version once guests stop", old.exists())
|
||||
}
|
||||
|
||||
@Test fun failedReplacementPreservesThePreviousGoodRuntime() {
|
||||
val base = temporary.newFolder("system_vulkan")
|
||||
val current = File(base, "a".repeat(64))
|
||||
val old = completeRuntime(base, "b".repeat(64))
|
||||
val stage = abandonedStage(base)
|
||||
|
||||
SystemVulkanDriver.pruneUnused(current, true)
|
||||
assertTrue("missing replacement", old.isDirectory)
|
||||
assertFalse(stage.exists())
|
||||
|
||||
current.mkdir()
|
||||
File(current, "icd.json").writeText("incomplete")
|
||||
SystemVulkanDriver.pruneUnused(current, true)
|
||||
assertEquals("current ICD", File(old, "icd.json").readText())
|
||||
}
|
||||
|
||||
@Test fun deletingOldRuntimeDoesNotFollowItsSymlinks() {
|
||||
val base = temporary.newFolder("system_vulkan")
|
||||
val current = completeRuntime(base, "a".repeat(64))
|
||||
val old = File(base, "b".repeat(64)).apply { mkdir() }
|
||||
val outside = temporary.newFolder("outside")
|
||||
val sentinel = File(outside, "keep").apply { writeText("keep") }
|
||||
Files.createSymbolicLink(File(old, "outside").toPath(), outside.toPath())
|
||||
|
||||
SystemVulkanDriver.pruneUnused(current, true)
|
||||
|
||||
assertFalse(old.exists())
|
||||
assertEquals("keep", sentinel.readText())
|
||||
}
|
||||
|
||||
@Test fun linkedBaseOrCurrentRuntimePreventsCleanup() {
|
||||
val base = temporary.newFolder("system_vulkan")
|
||||
val old = completeRuntime(base, "b".repeat(64))
|
||||
val current = File(base, "a".repeat(64))
|
||||
Files.createSymbolicLink(current.toPath(), old.toPath())
|
||||
SystemVulkanDriver.pruneUnused(current, true)
|
||||
assertTrue(old.isDirectory)
|
||||
|
||||
Files.delete(current.toPath())
|
||||
completeRuntime(base, current.name)
|
||||
val alias = File(temporary.root, "alias")
|
||||
Files.createSymbolicLink(alias.toPath(), base.toPath())
|
||||
SystemVulkanDriver.pruneUnused(File(alias, current.name), true)
|
||||
assertTrue(old.isDirectory)
|
||||
}
|
||||
|
||||
private fun abandonedStage(base: File) =
|
||||
File(base, ".stage-12345678-1234-1234-1234-123456789abc").apply { mkdir(); File(this, "partial").writeText("partial") }
|
||||
|
||||
private fun completeRuntime(base: File, version: String): File {
|
||||
val directory = File(base, version).apply { mkdir() }
|
||||
val components = listOf(
|
||||
"lib/libhybris-vulkan-icd.so.0", "lib/libhybris-common.so.1", "lib/libhybris/linker/q.so",
|
||||
"lib/libVkLayer_hybris_compat.so", "run-proton.py",
|
||||
"wsi/libVkLayer_window_system_integration.so", "wsi/VkLayer_window_system_integration.json",
|
||||
) + listOf("x32", "x64").flatMap { arch ->
|
||||
listOf("d3d8", "d3d9", "d3d10core", "d3d11", "dxgi").map { "dxvk/$arch/$it.dll" }
|
||||
}
|
||||
components.forEach { path -> File(directory, path).apply { parentFile!!.mkdirs(); writeText("component") } }
|
||||
File(directory, "run-proton.py").setExecutable(true)
|
||||
File(directory, "icd.json").writeText("current ICD")
|
||||
return directory
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
package com.droiddeck.launcher.gpu
|
||||
|
||||
import java.io.File
|
||||
import java.nio.file.Files
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Assert.assertThrows
|
||||
import org.junit.Test
|
||||
|
||||
class SystemVulkanSelectionTest {
|
||||
@Test fun defaultPowerVrUsesTheSystemBridge() {
|
||||
assertTrue(SystemVulkanDriver.usesDefault(true, ""))
|
||||
assertTrue(SystemVulkanDriver.usesDefault(true, null))
|
||||
}
|
||||
|
||||
@Test fun otherGpusAndExplicitImportsKeepTheirDriver() {
|
||||
assertFalse(SystemVulkanDriver.usesDefault(false, ""))
|
||||
assertFalse(SystemVulkanDriver.usesDefault(false, null))
|
||||
assertFalse(SystemVulkanDriver.usesDefault(true, "custom-driver"))
|
||||
}
|
||||
@Test fun renderNodeRequiresARealCharacterDeviceAndBothAccessModes() {
|
||||
assertTrue(SystemVulkanDriver.renderNodeAvailable(true, true, true))
|
||||
assertFalse("a regular placeholder is not a DRM device", SystemVulkanDriver.renderNodeAvailable(false, true, true))
|
||||
assertFalse("read access is required", SystemVulkanDriver.renderNodeAvailable(true, false, true))
|
||||
assertFalse("write access is required", SystemVulkanDriver.renderNodeAvailable(true, true, false))
|
||||
assertFalse("a missing node is unavailable", SystemVulkanDriver.renderNodeAvailable(false, false, false))
|
||||
}
|
||||
|
||||
@Test fun renderNodeDriverMustIdentifyPowerVrExactly() {
|
||||
for (name in listOf("pvrsrvkm", "pvr", "powervr"))
|
||||
assertTrue(name, SystemVulkanDriver.powerVrDriver(name))
|
||||
for (name in listOf(null, "", "msm", "panfrost", "not-pvr"))
|
||||
assertFalse(name, SystemVulkanDriver.powerVrDriver(name))
|
||||
}
|
||||
|
||||
@Test fun samsungXclipseGpuNodeIsSelectedOverItsDisplayNode() {
|
||||
assertTrue(SystemVulkanDriver.powerVrDriver("sgpu"))
|
||||
assertFalse("the display controller is not the GPU", SystemVulkanDriver.powerVrDriver("exynos-drm"))
|
||||
// Galaxy A56 (Exynos 1580): the GPU owns renderD128, the display controller renderD129.
|
||||
val drivers = mapOf("/dev/dri/renderD128" to "sgpu", "/dev/dri/renderD129" to "exynos-drm")
|
||||
assertEquals("/dev/dri/renderD128", SystemVulkanDriver.findRenderNode(null) { path ->
|
||||
SystemVulkanDriver.powerVrDriver(drivers[path])
|
||||
})
|
||||
}
|
||||
|
||||
@Test fun renderNodeIdentityUsesTheDriverLinkOrUevent() {
|
||||
val device = Files.createTempDirectory("powervr-device").toFile()
|
||||
try {
|
||||
assertFalse("missing identity is unavailable", SystemVulkanDriver.powerVrDevice(device))
|
||||
val uevent = File(device, "uevent")
|
||||
uevent.writeText("DRIVER=pvrsrvkm\nOF_NAME=gpu0\n")
|
||||
assertTrue(SystemVulkanDriver.powerVrDevice(device))
|
||||
uevent.writeText("DRIVER=msm\nOF_COMPATIBLE_0=not-pvr\n")
|
||||
assertFalse(SystemVulkanDriver.powerVrDevice(device))
|
||||
val driver = File(device, "driver").toPath()
|
||||
Files.createSymbolicLink(driver, File("../../drivers/pvrsrvkm").toPath())
|
||||
assertTrue(SystemVulkanDriver.powerVrDevice(device))
|
||||
Files.delete(driver)
|
||||
Files.createSymbolicLink(driver, File("../../drivers/msm").toPath())
|
||||
uevent.writeText("DRIVER=pvrsrvkm\n")
|
||||
assertFalse("an unrelated driver link must not fall back", SystemVulkanDriver.powerVrDevice(device))
|
||||
} finally {
|
||||
device.deleteRecursively()
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun renderNodeDiscoverySkipsOtherDriversAndDeniedNodes() {
|
||||
val drivers = mapOf(
|
||||
"/dev/dri/renderD128" to "msm",
|
||||
"/dev/dri/renderD129" to "pvr",
|
||||
"/dev/dri/renderD130" to "pvrsrvkm",
|
||||
)
|
||||
assertEquals("/dev/dri/renderD129", SystemVulkanDriver.findRenderNode(null) { path ->
|
||||
SystemVulkanDriver.powerVrDriver(drivers[path])
|
||||
})
|
||||
assertEquals("/dev/dri/renderD130", SystemVulkanDriver.findRenderNode(null) { path ->
|
||||
SystemVulkanDriver.powerVrDriver(drivers[path]) &&
|
||||
SystemVulkanDriver.renderNodeAvailable(true, path != "/dev/dri/renderD129", true)
|
||||
})
|
||||
}
|
||||
|
||||
@Test fun renderNodesAreDiscoveredWithoutDirectoryListing() {
|
||||
for (minor in listOf(128, 129, 191)) {
|
||||
val expected = "/dev/dri/renderD$minor"
|
||||
assertEquals(expected, SystemVulkanDriver.findRenderNode(null) { it == expected })
|
||||
}
|
||||
assertNull(SystemVulkanDriver.findRenderNode(null) { false })
|
||||
}
|
||||
|
||||
@Test fun listedRenderNodesCoverExtendedMinorNumbers() {
|
||||
assertEquals("/dev/dri/renderD256", SystemVulkanDriver.findRenderNode(
|
||||
arrayOf("card0", "renderD256", "renderD128/device", "../renderD129"),
|
||||
) { path ->
|
||||
assertTrue(path, path.matches(Regex("/dev/dri/renderD[0-9]+")))
|
||||
path == "/dev/dri/renderD256"
|
||||
})
|
||||
}
|
||||
|
||||
@Test fun defaultPowerVrResolvesToTheSystemIcd() {
|
||||
assertEquals("system/icd.json", LinuxVulkanDriver.resolveIcdPath("", true,
|
||||
{ "system/icd.json" }, { error("default must not resolve an import") }))
|
||||
}
|
||||
|
||||
@Test fun defaultAdrenoLeavesTheRuntimeIcdUnchanged() {
|
||||
assertNull(LinuxVulkanDriver.resolveIcdPath("", false,
|
||||
{ error("Adreno must not prepare the system bridge") }, { error("default must not resolve an import") }))
|
||||
}
|
||||
|
||||
@Test fun missingManualPowerVrImportFailsWithoutSwitchingBackends() {
|
||||
val failure = assertThrows(IllegalStateException::class.java) {
|
||||
LinuxVulkanDriver.resolveIcdPath("missing-driver", true,
|
||||
{ error("manual preference must not silently switch to the system backend") }, { null })
|
||||
}
|
||||
assertTrue(failure.message!!.contains("missing-driver"))
|
||||
assertTrue(failure.message!!.contains("use Auto"))
|
||||
}
|
||||
|
||||
@Test fun missingAdrenoImportKeepsTheExistingRuntimeFallback() {
|
||||
assertNull(LinuxVulkanDriver.resolveIcdPath("missing-driver", false,
|
||||
{ error("Adreno must not prepare the system bridge") }, { null }))
|
||||
}
|
||||
|
||||
@Test fun manualPowerVrResolvesTheChosenImport() {
|
||||
assertEquals("imports/chosen/icd.json", LinuxVulkanDriver.resolveIcdPath("chosen", true,
|
||||
{ error("manual must not prepare the system bridge") }, { "imports/$it/icd.json" }))
|
||||
}
|
||||
}
|
||||
@@ -130,6 +130,34 @@ class ForcedPackageTest {
|
||||
assertDefaultDxvkRestoreRow(protonName)
|
||||
}
|
||||
|
||||
@Test fun systemPowerVrRejectsNewGameDxvkSelectionsWithoutChangingSavedProfiles() {
|
||||
writeGameProfile("42", "dxvk", "custom-dxvk.wcp")
|
||||
val state = File(context.filesDir, "components/state.json")
|
||||
val saved = state.readText()
|
||||
|
||||
assertThrows(IllegalStateException::class.java) {
|
||||
ComponentsManager.setGameComponent(context, "42", "dxvk", "replacement.wcp") {
|
||||
ComponentsManager.runtimeManaged(it, true)
|
||||
}
|
||||
}
|
||||
|
||||
assertEquals(saved, state.readText())
|
||||
assertEquals("custom-dxvk.wcp", ComponentsManager.gameComponents(context, "42")["dxvk"])
|
||||
assertFalse(launchState().exists())
|
||||
}
|
||||
|
||||
@Test fun systemPowerVrAllowsClearingASavedGameDxvkSelection() {
|
||||
proton("proton-exp")
|
||||
writeGameProfile("42", "dxvk", "custom-dxvk.wcp")
|
||||
|
||||
ComponentsManager.setGameComponent(context, "42", "dxvk", null) {
|
||||
ComponentsManager.runtimeManaged(it, true)
|
||||
}
|
||||
|
||||
assertTrue(ComponentsManager.gameComponents(context, "42").isEmpty())
|
||||
assertDefaultDxvkRestoreRow("proton-exp")
|
||||
}
|
||||
|
||||
@Test fun aNewProtonIsCapturedWhenTheLastOverrideIsReset() {
|
||||
proton("existing")
|
||||
writeGameProfile("42", "dxvk", "custom-dxvk.wcp")
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.rules.TemporaryFolder
|
||||
import java.io.File
|
||||
|
||||
class GraphicsReportTest {
|
||||
@get:Rule val tmp = TemporaryFolder()
|
||||
|
||||
@Test fun deviceNumbersSplitAsLinuxDoes() {
|
||||
// /dev/mali0 on the testers' phones: 10:103 (misc); a DRM render node: 226:128.
|
||||
assertEquals(10L, GraphicsReport.major(10L shl 8 or 103L))
|
||||
assertEquals(103L, GraphicsReport.minor(10L shl 8 or 103L))
|
||||
assertEquals(226L, GraphicsReport.major(226L shl 8 or 128L))
|
||||
assertEquals(128L, GraphicsReport.minor(226L shl 8 or 128L))
|
||||
}
|
||||
|
||||
@Test fun gameLogsAreCutPerFileAndOldestLaunchesGoFirst() {
|
||||
val games = tmp.newFolder("games")
|
||||
fun launch(name: String, bytes: Int) = File(games, name).apply { mkdirs() }.also { File(it, "steam-1.log").writeBytes(ByteArray(bytes)) }
|
||||
val old = launch("20261012-100000-1", 60)
|
||||
val mid = launch("20261012-110000-2", 60)
|
||||
val new = launch("20261012-120000-3", 200)
|
||||
GraphicsReport.capGames(games, fileMax = 100, totalMax = 170)
|
||||
assertEquals(100L, File(new, "steam-1.log").length())
|
||||
assertFalse(old.exists())
|
||||
assertTrue(mid.exists())
|
||||
assertTrue(new.exists())
|
||||
}
|
||||
|
||||
@Test fun aMissingGamesFolderIsFine() {
|
||||
GraphicsReport.capGames(File(tmp.root, "none"))
|
||||
GraphicsReport.finish(tmp.newFolder("session"))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class OrphanReaperProcessTest {
|
||||
@Test fun unavailableProcessListDefersCleanup() {
|
||||
assertTrue(OrphanReaper.hasOtherProcesses(null, 100) { false })
|
||||
}
|
||||
|
||||
@Test fun theAppAndForeignProcessesDoNotKeepOldRuntimes() {
|
||||
assertFalse(OrphanReaper.hasOtherProcesses(listOf(0, 1, 100, 200), 100) { pid ->
|
||||
check(pid == 200) { "do not probe self or process groups" }
|
||||
false
|
||||
})
|
||||
}
|
||||
|
||||
@Test fun anyRemainingAppProcessDefersCleanup() {
|
||||
assertTrue(OrphanReaper.hasOtherProcesses(listOf(100, 200, 300), 100) { it == 300 })
|
||||
assertFalse(OrphanReaper.hasOtherProcesses(emptyList(), 100) { true })
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.content.Context
|
||||
import org.robolectric.RuntimeEnvironment
|
||||
import com.droiddeck.launcher.gpu.TurnipDriver
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.annotation.Config
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [28], manifest = Config.NONE)
|
||||
class PowerVrAutoDriversTest {
|
||||
private val context: Context = RuntimeEnvironment.getApplication()
|
||||
|
||||
@Before fun reset() {
|
||||
context.getSharedPreferences("session", Context.MODE_PRIVATE).edit().clear().commit()
|
||||
SessionPrefs.setLinuxDriver(context, "imported-linux")
|
||||
SessionPrefs.setAndroidDriver(context, "imported-display")
|
||||
}
|
||||
|
||||
@Test fun autoRepairsStaleAdrenoSelectionsOnPowerVr() {
|
||||
SessionPrefs.setGpuDriverMode(context, SessionPrefs.GPU_DRIVERS_AUTO)
|
||||
SessionPrefs.ensurePowerVrAutoDrivers(context, powerVr = true)
|
||||
assertEquals("", SessionPrefs.linuxDriver(context))
|
||||
assertEquals(TurnipDriver.AUTO, SessionPrefs.androidDriver(context))
|
||||
}
|
||||
|
||||
@Test fun explicitManualChoicesRemainOnPowerVr() {
|
||||
SessionPrefs.setGpuDriverMode(context, SessionPrefs.GPU_DRIVERS_MANUAL)
|
||||
SessionPrefs.ensurePowerVrAutoDrivers(context, powerVr = true)
|
||||
assertEquals("imported-linux", SessionPrefs.linuxDriver(context))
|
||||
assertEquals("imported-display", SessionPrefs.androidDriver(context))
|
||||
}
|
||||
|
||||
@Test fun adrenoAutoChoicesRemain() {
|
||||
SessionPrefs.setGpuDriverMode(context, SessionPrefs.GPU_DRIVERS_AUTO)
|
||||
SessionPrefs.ensurePowerVrAutoDrivers(context, powerVr = false)
|
||||
assertEquals("imported-linux", SessionPrefs.linuxDriver(context))
|
||||
assertEquals("imported-display", SessionPrefs.androidDriver(context))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class PowerVrComponentsTest {
|
||||
@Test fun onlyDxvkIsManagedWithTheSystemPowerVrRuntime() {
|
||||
assertTrue(ComponentsManager.runtimeManaged("dxvk", systemPowerVr = true))
|
||||
assertFalse(ComponentsManager.runtimeManaged("dxvk", systemPowerVr = false))
|
||||
assertFalse(ComponentsManager.runtimeManaged("fex", systemPowerVr = true))
|
||||
assertFalse(ComponentsManager.runtimeManaged("vkd3d", systemPowerVr = true))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.content.Context
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import org.json.JSONObject
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.RuntimeEnvironment
|
||||
import org.robolectric.annotation.Config
|
||||
import java.io.File
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [28], manifest = Config.NONE)
|
||||
class PowerVrQueuedComponentsTest {
|
||||
@Test fun managedDxvkQueueRemainsVisibleAndCanBeCancelled() {
|
||||
val context: Context = RuntimeEnvironment.getApplication()
|
||||
val root = LinuxRuntime.rootDir(context)
|
||||
root.deleteRecursively()
|
||||
val data = File(context.filesDir, "components")
|
||||
data.deleteRecursively()
|
||||
data.mkdirs()
|
||||
val proton = File(root, "root/.local/share/Steam/compatibilitytools.d/test-proton")
|
||||
File(proton, "files/lib/wine").mkdirs()
|
||||
File(proton, "proton").writeText("# test Proton\n")
|
||||
File(proton, "version").writeText("1 test-build\n")
|
||||
File(data, "state.json").writeText(JSONObject().put("queued", JSONObject().put("test-proton",
|
||||
JSONObject().put("dxvk", JSONObject().put("kind", "package").put("file", "chosen.wcp").put("label", "chosen DXVK"))
|
||||
)).toString())
|
||||
|
||||
assertTrue(ComponentsManager.applyQueued(context) { ComponentsManager.runtimeManaged(it, true) }.isEmpty())
|
||||
val deferred = ComponentsManager.snapshot(context).protons.single().components.getValue("dxvk")
|
||||
assertEquals("chosen DXVK", deferred.queued)
|
||||
|
||||
ComponentsManager.cancelQueued(context, "test-proton", "dxvk")
|
||||
assertNull(ComponentsManager.snapshot(context).protons.single().components.getValue("dxvk").queued)
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,23 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import android.app.Application
|
||||
import androidx.compose.ui.semantics.Role
|
||||
import androidx.compose.ui.semantics.SemanticsProperties
|
||||
import androidx.compose.ui.test.SemanticsMatcher
|
||||
import androidx.compose.ui.test.assertCountEquals
|
||||
import androidx.compose.ui.test.assertIsEnabled
|
||||
import androidx.compose.ui.test.assertIsNotEnabled
|
||||
import androidx.compose.ui.test.hasText
|
||||
import androidx.compose.ui.test.onAllNodesWithText
|
||||
import androidx.compose.ui.test.onLast
|
||||
import androidx.compose.ui.test.onNodeWithText
|
||||
import androidx.compose.ui.test.performClick
|
||||
import androidx.compose.ui.test.performScrollTo
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.frontend.Library
|
||||
import com.droiddeck.launcher.session.ComponentsManager
|
||||
import java.io.File
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
@@ -11,8 +25,9 @@ import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.RuntimeEnvironment
|
||||
import org.robolectric.annotation.Config
|
||||
|
||||
// Exercise the component UI without starting App's process-wide servers or crash handler.
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [28])
|
||||
@Config(sdk = [28], application = Application::class)
|
||||
class ComponentsPageProfileTest {
|
||||
@get:Rule val compose = createRobolectricComposeRule()
|
||||
|
||||
@@ -56,4 +71,143 @@ class ComponentsPageProfileTest {
|
||||
compose.onNodeWithText(context.getString(R.string.comp_scope_general)).performClick()
|
||||
compose.onNodeWithText(stackHeading).assertExists()
|
||||
}
|
||||
|
||||
@Test @Config(qualifiers = "w1280dp-h1000dp")
|
||||
fun systemPowerVrKeepsStoredDxvkDisabledAndQueuedDxvkCancellable() {
|
||||
val context = RuntimeEnvironment.getApplication()
|
||||
var cancelled = 0
|
||||
var imported = 0
|
||||
var swapped = 0
|
||||
var restored = 0
|
||||
showDxvk(
|
||||
systemPowerVr = true,
|
||||
onCancel = { cancelled++ },
|
||||
onImport = { imported++ },
|
||||
onSwap = { swapped++ },
|
||||
onRestore = { restored++ },
|
||||
)
|
||||
|
||||
compose.onNodeWithText(context.getString(R.string.cmgr_powervr_dxvk_managed)).assertExists()
|
||||
compose.onNodeWithText(context.getString(R.string.cmgr_powervr_dxvk_queued, "Next DXVK"), substring = true).assertExists()
|
||||
compose.onNodeWithText("Stored DXVK").assertIsNotEnabled()
|
||||
compose.onNodeWithText(context.getString(R.string.comp_original, "1.0")).assertIsNotEnabled()
|
||||
compose.onNodeWithText(context.getString(R.string.comp_restore_original)).assertIsNotEnabled()
|
||||
compose.onNodeWithText(context.getString(R.string.common_cancel)).performClick()
|
||||
compose.onNodeWithText(context.getString(R.string.comp_import_wcp)).performScrollTo().assertIsEnabled().performClick()
|
||||
compose.runOnIdle {
|
||||
assertEquals(1, cancelled)
|
||||
assertEquals(1, imported)
|
||||
assertEquals(0, swapped)
|
||||
assertEquals(0, restored)
|
||||
}
|
||||
}
|
||||
|
||||
@Test @Config(qualifiers = "w1280dp-h1000dp")
|
||||
fun manualRuntimeKeepsDxvkSelectionAvailable() {
|
||||
val context = RuntimeEnvironment.getApplication()
|
||||
showDxvk(systemPowerVr = false)
|
||||
|
||||
compose.onNode(hasText("Stored DXVK") and SemanticsMatcher.expectValue(SemanticsProperties.Role, Role.RadioButton)).assertIsEnabled()
|
||||
compose.onNodeWithText(context.getString(R.string.comp_original, "1.0")).assertIsEnabled()
|
||||
compose.onNodeWithText(context.getString(R.string.comp_restore_original)).assertIsEnabled()
|
||||
compose.onNodeWithText(context.getString(R.string.cmgr_powervr_dxvk_managed)).assertDoesNotExist()
|
||||
}
|
||||
|
||||
@Test @Config(qualifiers = "w1280dp-h1000dp")
|
||||
fun systemPowerVrGameProfileKeepsOtherComponentChoicesAndRuntimeOptionsAvailable() {
|
||||
val context = RuntimeEnvironment.getApplication()
|
||||
showDxvk(systemPowerVr = true)
|
||||
compose.onNodeWithText(context.getString(R.string.comp_scope_general)).performClick()
|
||||
compose.onNodeWithText("Game A").performClick()
|
||||
compose.waitUntil(5_000) {
|
||||
compose.onAllNodesWithText(context.getString(R.string.comp_game_reset)).fetchSemanticsNodes().isNotEmpty()
|
||||
}
|
||||
|
||||
compose.onNodeWithText(context.getString(R.string.gpu_system_powervr)).assertIsNotEnabled()
|
||||
compose.onNodeWithText(context.getString(R.string.cmgr_powervr_dxvk_managed)).assertExists()
|
||||
val inheritedChoices = compose.onAllNodesWithText(context.getString(R.string.comp_game_use_general))
|
||||
inheritedChoices.assertCountEquals(4) // FEX preset, FEX package, Proton and VKD3D remain selectable.
|
||||
repeat(4) { inheritedChoices[it].assertIsEnabled() }
|
||||
val runtimeOptions = compose.onAllNodesWithText(context.getString(R.string.comp_game_runtime_options))
|
||||
runtimeOptions.assertCountEquals(2)
|
||||
repeat(2) { runtimeOptions[it].assertIsEnabled() }
|
||||
compose.onNodeWithText(context.getString(R.string.comp_this_proton).uppercase()).assertDoesNotExist()
|
||||
|
||||
compose.onNodeWithText("Game A").performClick()
|
||||
compose.onNodeWithText(context.getString(R.string.comp_scope_general)).performClick()
|
||||
compose.onNodeWithText(context.getString(R.string.comp_this_proton).uppercase()).assertExists()
|
||||
}
|
||||
|
||||
@Test @Config(qualifiers = "w1280dp-h1000dp")
|
||||
fun systemPowerVrGameProfileCanClearAnExistingDxvkOverrideWithoutSelectingAnother() {
|
||||
val context = RuntimeEnvironment.getApplication()
|
||||
showDxvk(systemPowerVr = true, gameDxvkOverride = true)
|
||||
compose.onNodeWithText(context.getString(R.string.comp_scope_general)).performClick()
|
||||
compose.onNodeWithText("Game A").performClick()
|
||||
compose.waitUntil(5_000) {
|
||||
compose.onAllNodesWithText(context.getString(R.string.comp_game_reset)).fetchSemanticsNodes().isNotEmpty()
|
||||
}
|
||||
|
||||
compose.onNodeWithText(context.getString(R.string.gpu_system_powervr)).performScrollTo().assertIsEnabled().performClick()
|
||||
compose.onNodeWithText("Stored DXVK").assertDoesNotExist()
|
||||
compose.onAllNodesWithText(context.getString(R.string.comp_game_use_general)).onLast().performClick()
|
||||
compose.waitUntil(5_000) { "dxvk" !in ComponentsManager.gameComponents(context, "42") }
|
||||
compose.onNodeWithText(context.getString(R.string.gpu_system_powervr)).assertIsNotEnabled()
|
||||
}
|
||||
|
||||
private fun showDxvk(
|
||||
systemPowerVr: Boolean,
|
||||
gameDxvkOverride: Boolean = false,
|
||||
onCancel: () -> Unit = {},
|
||||
onImport: () -> Unit = {},
|
||||
onSwap: (String) -> Unit = {},
|
||||
onRestore: (String) -> Unit = {},
|
||||
) {
|
||||
val context = RuntimeEnvironment.getApplication()
|
||||
File(context.filesDir, "components/state.json").apply {
|
||||
parentFile!!.mkdirs()
|
||||
writeText(if (gameDxvkOverride) """{"profiles":{"42":{"dxvk":"stored.wcp"}}}""" else "{}")
|
||||
}
|
||||
val proton = ComponentsManager.Proton(
|
||||
"test-proton", "Test Proton", File(context.filesDir, "test-proton"), "/test-proton", "1.0", false,
|
||||
)
|
||||
val snapshot = ComponentsManager.Snapshot(
|
||||
protons = listOf(ComponentsManager.ProtonView(
|
||||
proton = proton,
|
||||
components = mapOf("dxvk" to ComponentsManager.Component("1.0", "", "Stored DXVK", "", "stored.wcp", "Next DXVK")),
|
||||
originals = listOf(ComponentsManager.Original("dxvk", "1.0", "Original DXVK", 1)),
|
||||
inUseByGame = false,
|
||||
)),
|
||||
packages = listOf(ComponentsManager.Package("stored.wcp", "dxvk", "Stored DXVK", "", 1)),
|
||||
)
|
||||
compose.setContent {
|
||||
DroidDeckTheme {
|
||||
ComponentsPage(
|
||||
snapshot = snapshot,
|
||||
catalog = emptyList(),
|
||||
catalogAt = 0,
|
||||
protonId = proton.id,
|
||||
comp = "dxvk",
|
||||
checking = false,
|
||||
busy = null,
|
||||
downloads = emptyMap(),
|
||||
onProton = {},
|
||||
onComp = {},
|
||||
onSwap = onSwap,
|
||||
onRestore = onRestore,
|
||||
onCancelQueued = onCancel,
|
||||
onDeletePackage = {},
|
||||
onDeleteOriginal = {},
|
||||
onDownload = {},
|
||||
onRefresh = {},
|
||||
onImport = onImport,
|
||||
onBack = {},
|
||||
gpu = GpuDriversState(powerVr = true, systemPowerVr = systemPowerVr),
|
||||
games = listOf(Library.SteamGame(42, "Game A", null, "internal")),
|
||||
requestInitialFocus = false,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
# American Nightmare on Pixel: rendering workaround and remaining limits
|
||||
|
||||
Local engineering results from 2026-10-11/12. Steam game 202750 was tested on a
|
||||
Pixel 11 Pro Fold using the Pixel Lab runtime. These observations do not establish
|
||||
compatibility across the Pixel family or a fix for the system resets.
|
||||
|
||||
## Rendering result
|
||||
|
||||
The bright dotted triangle edges over textured rocks, boards and the player are
|
||||
not an application wireframe setting: traced input and driver pipelines all used
|
||||
`VK_POLYGON_MODE_FILL`, with no dynamic polygon mode. The original affected path
|
||||
used 2x MSAA, RGBA16F color and D24S8 depth. The game's minimum UI AA setting and
|
||||
`d3d11.disableMsaa` did not disable its D3D9 multisampling.
|
||||
|
||||
A real single-sample D3D9 comparison removed the visible bright triangle edges.
|
||||
Trial 16 verified 114 input and 114 driver pipelines, all single-sample. Trial 17
|
||||
retained correct meshes/textures through movement and turning, with 119 pipelines
|
||||
in each phase, all single-sample. This isolates a useful workaround to the MSAA
|
||||
path; it does not identify the precise faulty operation or prove a vendor bug.
|
||||
The override also changes effective surface descriptors, so the application may
|
||||
select different AA-aware shader/rendering paths.
|
||||
|
||||
`tools/dxvk/patches/0004-d3d9-force-single-sample.patch` adds an explicit per-game
|
||||
`d3d9.forceSingleSample` option, default **False**. After validating the original
|
||||
sample request, D3D9 surface normalization selects `D3DMULTISAMPLE_NONE` and quality
|
||||
0. GetDesc, image creation, resolves and sample-dependent state use this effective
|
||||
description. This intentionally disables MSAA, per-sample masks and
|
||||
alpha-to-coverage. It is a compatibility override, not transparent MSAA emulation
|
||||
or a universal PowerVR default. Existing low32, BC-format, present synchronization
|
||||
and tiler workarounds must remain intact.
|
||||
|
||||
Swapchain backbuffers have a separate creation path. With the override enabled,
|
||||
that path now validates a copy of the original requested descriptor and transfers
|
||||
the effective sample type/quality before allocation, so automatic depth surfaces
|
||||
and backbuffers agree. Validation uses the application's lockable-backbuffer flag;
|
||||
the internal lockability required for GDI fallback is retained on the allocated
|
||||
backbuffer. With the override disabled the original backbuffer path is unchanged.
|
||||
This correction addresses official PR602 review 5486295088. Its CPU harness
|
||||
compiles the actual DXVK sample decoder, surface normalizer and backbuffer method,
|
||||
plus the automatic-depth descriptor and framebuffer depth-binding excerpts.
|
||||
Fifteen cases cover on/off, NONMASKABLE quality, matching depth, no-depth operation,
|
||||
unsupported/invalid/lockable requests, allocation cleanup and recreation. Backend
|
||||
images and adapter capabilities are mocked; these are not GPU or gameplay tests.
|
||||
|
||||
## Independent HUD correction
|
||||
|
||||
The diagnostic frametimes HUD bound an R8_UINT storage texel buffer to a shader
|
||||
whose SPIR-V image format was Unknown. This required formatless buffer writes
|
||||
which the device did not report for that format, producing VUID 07029.
|
||||
`0003-hud-explicit-r8-texel-format.patch` declares `r8ui` to match the actual host
|
||||
view. No capabilities are fabricated. The build now compiles and validates the
|
||||
actual shader, and checks binding 3 for DimBuffer/storage/R8ui. The original shader
|
||||
fails that contract; the patched shader passes. Real-game trial 15 used the new
|
||||
DLLs, removed 07029, and retained the original triangle edges. This HUD bug is
|
||||
separate from the rendering workaround, and is not a proven reset cause.
|
||||
|
||||
VUID 06479 for color-format comparison descriptors remains under investigation.
|
||||
The D3D9 shader uses a conditional comparison path; static validation output alone
|
||||
does not prove that the offending branch executes. No warning suppression or
|
||||
false format-feature claims are proposed. Trial 14's LOG+FAIL with a duplicate
|
||||
limit blocked only the first message of each kind, not every invalid API call;
|
||||
subsequent trials used logging only. Do not describe these runs as fully blocked
|
||||
validation or GPU-assisted validation.
|
||||
|
||||
## Responsiveness, performance and stability
|
||||
|
||||
Paired screenshots prove movement and camera changes, rather than relying on an
|
||||
input receipt. Trial 17 completed eight samples without a black viewport. Its
|
||||
cold sample was 3.2 FPS; later recognized samples were 19.1-29.9 FPS, with roughly
|
||||
2.54 CPU-core equivalents. Camera/workload, capture overhead and thermals were
|
||||
not controlled; this is not a reliable A/B benchmark.
|
||||
|
||||
The planned eight-minute trial 17 stopped at a focus/session guard after the last
|
||||
confirmed sample at 315.6 seconds. Steam owned focus; the target game was still
|
||||
available for a single client quit. Its temporary settings were successfully
|
||||
restored, and the phone boot counter remained 12. The focus change's cause is
|
||||
unknown. The run is **incomplete**, not an eight-minute pass or a demonstrated
|
||||
game crash. Controls, focus ownership and sustained stability still need broader
|
||||
coverage beyond these short tests.
|
||||
|
||||
### Final production configuration and user confirmation
|
||||
|
||||
The clean production configuration was persisted only for game 202750 through
|
||||
the application's per-game environment UI. It selects the tested DXVK component
|
||||
and sets `d3d9.forceSingleSample = True`, retaining the existing low32, BC,
|
||||
presentation-sync and `dxvk.tilerMode = False` workarounds. Shared configuration
|
||||
and other games were unchanged. Shader audit layers, validation and the
|
||||
frametimes HUD are not enabled in this production configuration.
|
||||
|
||||
A final automated production trial loaded the existing saved game, verified
|
||||
turning/movement with five paired non-black screenshots, and observed 115 seconds
|
||||
without the bright triangle edges or another phone reset. It then quit normally;
|
||||
the saved per-game environment remained unchanged. This is bounded observation,
|
||||
not a long-duration stability or controlled performance benchmark.
|
||||
|
||||
On 2026-10-11 (America/Toronto), the device owner separately confirmed that this
|
||||
stage worked and authorized publication. No duration, frame rate or full-game
|
||||
completion was supplied with that confirmation. It is additional user validation
|
||||
of the stage, not a claim that all Pixel devices or the GNOC resets are fixed.
|
||||
|
||||
## Native guards, resets and diagnostic controls
|
||||
|
||||
The Pixel base is e589e3ae21959c9c74c490d917cebf256acc8ac8. PR561's 9e6fe314 and
|
||||
3c363910 guards were integrated in an isolated worktree; 26 selected production-C
|
||||
regressions and a full APK/runtime verification passed. Pixel AHB support remains
|
||||
present. The existing Lab app was updated without uninstalling or resetting its
|
||||
Steam account. This APK preceded a second system reset, so the native guards are
|
||||
not a verified reset fix.
|
||||
|
||||
Two resets changed the boot counter 10 -> 11 -> 12. After personal unlock, narrow
|
||||
kernel/firmware projections confirmed GNOC/access-control details for the first,
|
||||
and `reset,warm,gnoc_error` with a fresh GNOC numeric record for the second. The
|
||||
specific faulty component/operation and any relation to rendering are unknown.
|
||||
`tools/pixel_reset_diagnostics.py` exports only fixed fault categories/numeric
|
||||
fields, lock state, boot counter and entry times; never arbitrary log text or
|
||||
account data. Boot-property and kernel last-boot reasons use the same exact
|
||||
allowlist of canonical categories and the observed `reset,warm,gnoc_error` value;
|
||||
unknown reasons and custom suffixes produce `unknown`, never their original text.
|
||||
Primary-user states are likewise limited to recognized lifecycle categories.
|
||||
Output files are created exclusively with mode `0600` before any bytes are
|
||||
written (POSIX), and existing files/symlinks are refused. Host regressions cover
|
||||
these boundaries as well as freshness, unlock gating and narrow output.
|
||||
Dropbox's offset-free local timestamp is not assigned a guessed instant during
|
||||
a DST transition: repeated hours report `ambiguous_device_local_time`, skipped
|
||||
hours report `nonexistent_device_local_time`. Neither is attributed to the trial
|
||||
or used to project kernel-body categories until its time can be established.
|
||||
|
||||
Private opt-in diagnostics captured maintenance5 inline modules, which the older
|
||||
shim path missed. Materialization passed nine actual-C ASan/UBSan cases; benign
|
||||
pipeline-chain planning passed twelve. Real-game NoContraction, scaled vertex
|
||||
conversion and force-clip rewrites were actually applied and did not remove the
|
||||
edges. None is a production default. Sixty-two valid bounded, owned offscreen GPU
|
||||
cases passed exact pixel readback, fences and validation, covering interpolation,
|
||||
seams, perspective meshes, interface widening, scaled fetch, HDR/depth prepasses,
|
||||
real clipping and nonconstant depth. Invalid initial fixtures are excluded. These
|
||||
passing controls do not exonerate every driver/rendering path.
|
||||
|
||||
## Reproducibility and recovery
|
||||
|
||||
The runtime artifact supplies both architectures, exact DLL hashes, public patched
|
||||
DXVK sources, all four patches, wrapper and build recipe. It contains no game
|
||||
assets, bytecode, saves, account files, screenshots or raw device logs. Source
|
||||
patches apply cleanly to pinned DXVK revision 25ca63f17f34bdc05a39873ee63907d3cbbfa030.
|
||||
All five runtime DLL targets were built for both architectures.
|
||||
|
||||
Stop further load tests after a full reset. Wait for personal unlock and inspect a
|
||||
fresh narrow projection before another launch. Temporary profile restoration checks
|
||||
baseline/current hashes and unchanged shared/other-game settings; it never rolls
|
||||
back saved game progress. Persistent selection must affect only 202750 and leave
|
||||
private shader audit layers, validation settings and frametimes HUD disabled.
|
||||
Routine Heartbeat must not launch games or automatically resume this engineering.
|
||||
|
||||
## Submission scope
|
||||
|
||||
These opt-in runtime tools are submitted directly against official DroidDeck
|
||||
`main`. The standalone DXVK build recipe, source pin, BC-format prerequisite and
|
||||
presentation-semaphore patch/check are imported verbatim from the PowerVR proposal
|
||||
<https://github.com/Droid-Deck/DroidDeck/pull/570> at
|
||||
`d0f7264ea8e402d30c868779198dc2fd74e7431c`. That proposal's attribution and existing
|
||||
source/license provenance are retained. The semaphore correction originated in
|
||||
<https://github.com/wallentx/DroidDeck/pull/3>. No Android app changes, managed pack
|
||||
or the experimental fork's development history are imported with those recipes.
|
||||
|
||||
The source tools can be reviewed and built independently. Automatic PowerVR
|
||||
integration and delivery in DroidDeck require the separately reviewed #570
|
||||
foundation and a new managed-runtime release. This submission does not change
|
||||
managed-pack manifests/checksums or globally enable any override. The earlier
|
||||
fork-only stage <https://github.com/wallentx/DroidDeck/pull/4> is superseded by the
|
||||
official submission; its review history is preserved.
|
||||
|
||||
For standalone verification, run
|
||||
`python3 -m unittest discover -s tools/tests -p test_pixel_reset_diagnostics.py`
|
||||
on the host. On native 64-bit Linux/glibc,
|
||||
`tools/hybris/low32/build.sh /absolute/output-dir` builds and runs the CPU integrity
|
||||
and independent mmap/mmap64 preload-chain regressions (both library orders in
|
||||
off, trace and low32 modes). Optional Vulkan headers produce `gpu-copy-native`
|
||||
for the selected native host architecture, not a hardcoded ARM64 filename.
|
||||
`python3 -m unittest discover -s tools/tests -p test_dxvk_build.py` verifies output
|
||||
isolation with a synthetic toolchain, without fetching or compiling DXVK.
|
||||
The DXVK component recipe is `tools/dxvk/build.sh /absolute/output-dir`;
|
||||
it requires the pinned DXVK build prerequisites, including Meson/Ninja, MinGW
|
||||
cross compilers, glslangValidator and SPIR-V Tools. It retains both architectures,
|
||||
source/license provenance and downstream patches, without editing an installed
|
||||
runtime or APK. Its output directory must be new or empty (including hidden
|
||||
entries). Prior or partially built outputs are refused before fetching sources,
|
||||
left untouched and never included in a new DLL manifest. Use a fresh directory
|
||||
after a failed build.
|
||||
The recipe also requires a native C++17 compiler for
|
||||
`python3 tools/dxvk/check_d3d9_single_sample.py /path/to/patched-dxvk` before DLL
|
||||
compilation. Add `--sanitize` on supported hosts to run its ASan/UBSan controls.
|
||||
|
||||
The compositor ownership safeguards are independently proposed in
|
||||
<https://github.com/Droid-Deck/DroidDeck/pull/561>. Those native changes were present
|
||||
in the integrated Pixel Lab APK used for the game experiments, but are not part
|
||||
of this runtime PR's diff. The original BC emulation is a prerequisite supplied by
|
||||
the separately proposed PowerVR runtime. This submission supplies source and reproducibility tools,
|
||||
not an APK, proprietary driver, game data or private diagnostic archive.
|
||||
@@ -0,0 +1,88 @@
|
||||
# Compositor work whose completion is unknown
|
||||
|
||||
A timed-out fence wait does not cancel submitted GPU work. Continuing after
|
||||
that result can reset a command buffer or fence still in use, or destroy an
|
||||
image and its memory while the GPU may still read them. Previously the finite
|
||||
wait paths returned without putting the compositor into a terminal state, and
|
||||
swapchain teardown ignored the result of `vkDeviceWaitIdle`.
|
||||
|
||||
An unsuccessful completion check other than real `VK_ERROR_DEVICE_LOST` now
|
||||
puts the compositor in a distinct completion-unknown state. It stops subsequent
|
||||
presentation and retains potentially pending image/memory and swapchain
|
||||
resources until the DroidDeck app process exits. Device loss continues through
|
||||
the existing device-loss path. This is deliberate retention rather than an
|
||||
automatic recovery; restarting a guest session cannot reset the in-process GPU
|
||||
state, so the diagnostic asks for an app restart.
|
||||
|
||||
Initialization checks the black-image submit and fence result. An unsuccessful
|
||||
empty completion-marker submit no longer causes a wait on an unsignalled fence.
|
||||
Surface-rebuild and effect-map paths stop when teardown cannot establish idle.
|
||||
Acquire retries also stop: retaining the old swapchain is not permission to
|
||||
acquire from it again. A later frame-generation acquire that ends in a terminal
|
||||
state returns before the completion marker, fence wait or any further recording.
|
||||
Real device loss on present is handled before attempting that marker, too.
|
||||
Mapped SHM bytes are retained unchanged, including same-size `wl_shm` and
|
||||
single-pixel commits; keeping only the allocation would still race a GPU read.
|
||||
Off-screen pass copy/abort and the internal fence wait reject terminal states
|
||||
without further Vulkan calls. Release fds are still consumed on rejected copies.
|
||||
The normal frame fence still has its existing infinite timeout; this change is
|
||||
not a general GPU hang watchdog.
|
||||
|
||||
Externally owned DMA-BUF contents need the same protection. `vkp_completion_unknown()`
|
||||
exposes the terminal state to compositor-thread lifecycle paths. Replacement,
|
||||
surface/client destruction, cursor/idle-role releases, previously queued paced
|
||||
releases and SurfaceFlinger callbacks no longer return a DMA-BUF to its client
|
||||
after quarantine. The compositor retains DMA-BUF references/backing FDs and AHB
|
||||
references until app process exit. A display fence alone does not establish that
|
||||
the compositor's Vulkan reads completed. Queued releases detach destroyed surfaces
|
||||
and remain held without repeatedly arming an expired timer. New terminal releases
|
||||
require no allocation, so allocation failure cannot fall back to an unsafe release.
|
||||
Copied SHM releases and healthy/genuine-device-loss cleanup keep their existing
|
||||
behaviour. This intentionally prevents further client buffer reuse; restarting
|
||||
the Android app process, not just the guest session, is required.
|
||||
|
||||
## Regression coverage
|
||||
|
||||
`python3 -m unittest discover -s tools/tests -p test_vk_pending_completion.py -v`
|
||||
compiles the production wait/destructor and swapchain teardown functions with a
|
||||
fake Vulkan dispatch table. The two cases cover success, timeout, host-memory
|
||||
errors, genuine device loss, resource retention and suppressed repeated teardown.
|
||||
No real GPU fault is injected. The harness matches main's Vulkan-image resources;
|
||||
it does not assume the experimental PowerVR branch's additional AHB fields.
|
||||
|
||||
`python3 -m unittest discover -s tools/tests -p test_vk_terminal_callers.py -v`
|
||||
additionally compiles the **entire production `vk_present.c`**, with fake Vulkan
|
||||
dispatch callbacks and stub external modules. The compositor's `take_shm` and
|
||||
`take_pixel` callers are inserted verbatim, not rewritten. It needs the Android
|
||||
NDK's Vulkan-Headers (`ANDROID_HOME`/`ANDROID_SDK_ROOT`/`NDK`), a host Vulkan
|
||||
development package, or `DROIDDECK_VULKAN_INCLUDE`; absent headers are explicitly
|
||||
reported as a skip. No Android runtime or GPU is required.
|
||||
|
||||
The 12 scenarios include first/later OUT_OF_DATE and SURFACE_LOST followed by an
|
||||
idle failure, a finite blit timeout followed by same-size SHM/single-pixel
|
||||
uploads, normal presentation/frame generation, a healthy later acquire timeout
|
||||
whose earlier work still needs draining, real acquire/present device loss, and
|
||||
terminal off-screen pass entry. Every work-issuing fake callback asserts the
|
||||
device is live. After quarantine, the tests verify retained handles and unchanged
|
||||
mapped bytes, and probe the public render/blit/readback/import/pass entry points
|
||||
for suppressed acquire/submit/wait/reset and destruction. Consumed fds are checked.
|
||||
Against PR #560's `68dc1c45` the same harness compiles, but nine scenarios fail
|
||||
(the three healthy controls pass); the corrected production unit passes all 12.
|
||||
|
||||
The baseline production fence/destructor compiles but fails the timeout-state
|
||||
oracle; the corrected functions pass both cases with `-Wall -Wextra -Werror`.
|
||||
The change was also exercised in an independently integrated Pixel PowerVR Lab,
|
||||
but its short game observations do not establish the cause of the earlier GNOC
|
||||
reboot or sustained device stability. Main's native CI and APK build remain
|
||||
separate validation.
|
||||
|
||||
`python3 -m unittest discover -s tools/tests -p test_vk_dmabuf_quarantine.py -v`
|
||||
compiles the production compositor/AHB release, reference and listener functions
|
||||
verbatim, using the real Wayland list layouts/macros with fake IPC/timer/AHB
|
||||
endpoints. It covers paced replacement, immediate surface cleanup, already queued
|
||||
releases, a mixed DMA-BUF/SHM queue, client destruction, a display-fence callback,
|
||||
healthy cleanup and genuine device loss. It checks withheld releases, retained
|
||||
FDs/references/AHB ownership, removal of surface listeners and disarmed timers.
|
||||
The same harness can test an old source directory via
|
||||
`DROIDDECK_DMABUF_TEST_SOURCE`; it does not inject a real driver fault or prove
|
||||
long-term device stability.
|
||||
@@ -0,0 +1,340 @@
|
||||
# DroidDeck on Mali (Pixel 9 Pro) through Venus
|
||||
|
||||
Handoff notes for the next session.
|
||||
Upstream DroidDeck 0.3.1 runs on Adreno only.
|
||||
This branch makes it run on the user's Pixel 9 Pro (Tensor G4, Mali-G715, Android 17).
|
||||
|
||||
## Status (2026-10-08, night)
|
||||
|
||||
Prototype 13 is the APK on the phone, a release build (not debuggable).
|
||||
Prototypes 12 and 13 are published as GitHub prereleases.
|
||||
Steam Big Picture shows a clean, live picture, and Slay the Spire 2 runs at about 40 fps.
|
||||
|
||||
Direct3D 9-11 games run through DXVK.
|
||||
Test game: Hollow Knight Silksong (Unity, D3D11), app id 1030300.
|
||||
- Prototype 12: 35-40 fps in game, stable, with good audio. The phone was not throttling.
|
||||
- Prototype 13 (cached frame readback, see Performance): 45-52 fps, averaging 47-52.
|
||||
|
||||
Done and verified on the phone:
|
||||
- The Mali compatibility layer (`tools/venus/layer`) loads and reports the six features DXVK requires.
|
||||
- DXVK accepts the GPU and creates its device. D3D11 runs at feature level 11_0.
|
||||
- Silksong loads and plays.
|
||||
- The APK carries the layer and the Venus ICD; nothing on the phone is installed by hand any more.
|
||||
|
||||
Fixed: a crash in the Venus guest driver, about 20 s after launch, with a black screen until then.
|
||||
- Where: `vtest_vcmd_submit_cmd2` (`src/virtio/vulkan/vn_renderer_vtest.c`), on the `dxvk-submit` thread inside `vkQueueSubmit2`.
|
||||
- What: it reads `batch->syncs[1]->sync_id` and `syncs[1]` is the pointer `0x1`.
|
||||
- Cause: two threads submit to the same queue at once.
|
||||
- Venus's async present thread (`vn_wsi`) makes the WSI submits. On vtest, `vn_wsi_fence_wait` drops the queue lock while it waits on a fence.
|
||||
- It assumes one submit per swapchain. But `wsi_queue_submit2_unordered` makes a second, empty submit for DXVK's present fence.
|
||||
- DXVK's thread passes `vn_wsi_flush` in that window and submits at the same time.
|
||||
- Both use the per-queue scratch buffer `queue->storage`. The empty submit's `sync_vals[0] = 1` lands on DXVK's `syncs[1]`.
|
||||
- gamescope and Zink use no present fences, so Steam and Slay the Spire 2 never hit it.
|
||||
- Fix: `vn_queue_submit` holds a new per-queue `submit_mutex`. Verified with Silksong.
|
||||
|
||||
Other open problems:
|
||||
- Steam's UI blocks 30 s at a time on `IClientFriends::GetVoiceMicrophoneVolume`. A launch looks stuck on "Launching" even after the game died.
|
||||
- The render server aborts ("pthread_mutex_lock called on a destroyed mutex") when a context dies after an error. Not fixed.
|
||||
- The phone runs short of memory: about 1-2 GB free during a session. BC decoding makes textures 4-8x bigger.
|
||||
- Prototype 13 is not debuggable, so `adb run-as` fails and the hand-install loop below does not work.
|
||||
- To debug again: add `debuggable true` to the `release` build type in `app/build.gradle`, rebuild, reinstall. Keep it out of commits.
|
||||
- A debuggable build shows a harmless "not 16 KB-compatible" dialog.
|
||||
|
||||
## Performance
|
||||
|
||||
How a game frame reaches the screen (Silksong, 1280x720):
|
||||
1. The game draws through Venus. gamescope's WSI layer turns its X11 window into a Wayland surface on gamescope.
|
||||
2. Venus's present thread (`vn_wsi[0,0]`) runs WSI's software path (`MESA_VK_WSI_DEBUG=sw`).
|
||||
- It blits the image into a host-visible buffer, waits for the GPU, and `memcpy`s the buffer into a `wl_shm` buffer (3.6 MB).
|
||||
3. gamescope uploads that `wl_shm` buffer into a texture (patch 0114), composites, and hands a dma-buf to the app.
|
||||
4. The app's compositor draws it at 60 Hz. Its own work is about 2-3 ms a frame (`wayland.log`, `perf` lines).
|
||||
|
||||
Measured with `tools/venus/measure-present.patch` (see "Measuring a frame" below):
|
||||
|
||||
| Per frame | Prototype 12 | Prototype 13 |
|
||||
|---|---|---|
|
||||
| Frame interval | 26-29 ms | ~20 ms |
|
||||
| `memcpy` out of the readback buffer | 7-10 ms (~400 MB/s) | ~1.3 ms, cache sync included |
|
||||
| Present thread total | 17-20 ms | ~12 ms |
|
||||
| GPU fence waits (two per present) | ~4 ms | ~4.5 ms |
|
||||
| Game blocked in `vn_wsi_flush` | ~0.4 ms | ~0.01 ms |
|
||||
|
||||
Why the copy was slow: Venus hid Mali's cached memory type.
|
||||
- Mali's native types (`memtypes` probe): 0 = device-local, host-visible, coherent (uncached); 1 = device-local, host-visible, cached (not coherent).
|
||||
- `vn_physical_device_init_memory_properties` strips host-visible from cached types that are not coherent, and labels type 0 "cached" for app compatibility.
|
||||
- So WSI's readback buffer landed on uncached memory, and the CPU read it at ~400 MB/s.
|
||||
|
||||
The fix (prototype 13):
|
||||
- Venus allocates WSI's readback buffer in the hidden cached type (`vn_wsi_memory_type_index`). Apps still never see that type.
|
||||
- The vtest renderer keeps that buffer's dma-buf fd and implements flush and invalidate as `DMA_BUF_IOCTL_SYNC`.
|
||||
- WSI calls `vkInvalidateMappedMemoryRanges` before every CPU read of a frame (Wayland and X11 software paths).
|
||||
- The render server allocates cached memory types from the cached dma-buf heap (`/dev/dma_heap/system`).
|
||||
|
||||
What is left on the present thread (~12 ms):
|
||||
- ~4.5 ms in two GPU fence waits. WSI makes a second, empty submit for DXVK's present fence, and Venus waits on each.
|
||||
- ~6 ms in those two submits and their Venus round trips.
|
||||
- Thread sample (`top -H`, prototype 12): no thread at 100%. Game main thread 48%, `vn_wsi` 30%, `dxvk-frame` 30%, Unity render thread 25%.
|
||||
- `dxvk-frame` mostly waits for presents; 30% CPU looks like Venus polling in its semaphore waits.
|
||||
|
||||
## State outside the repo and the APK
|
||||
|
||||
On the phone, changed by hand (read this before testing anything):
|
||||
- `/sdcard/Download/droiddeck-env` holds `PROTON_LOG=1`. Every game writes a full Proton log to `/root/steam-<appid>.log`.
|
||||
- Delete it when debugging is done: `adb shell rm /sdcard/Download/droiddeck-env`.
|
||||
- `/data/local/tmp` holds copies of the pushed files and `watch-maps.sh`.
|
||||
|
||||
Published: prototypes 12 and 13 as the prereleases `mali-venus-proto12` and `mali-venus-proto13`. Prototypes 7 to 11 were never published.
|
||||
|
||||
## Where things are
|
||||
|
||||
- **Source:** `C:\Users\derab\source\repos\DroidDeck`, branch `mali-venus` (off tag `0.3.1`).
|
||||
- **Remote:** `mine` = https://github.com/DavidCimo/droiddeck-mali. It's public; the user made it public to download on the phone.
|
||||
- The gh account is `DavidCimo`.
|
||||
- Releases `mali-venus-proto1`…`proto6`, `proto12` and `proto13` hold the APKs. Proto 7 to 11 were installed over ADB only.
|
||||
- Publish with `gh release create mali-venus-proto<n> -R DavidCimo/droiddeck-mali --prerelease --target mali-venus --title "0.3.1 + Venus prototype <n>" --notes-file … <apk>`, after pushing the branch.
|
||||
- **Build outputs:** `C:\Users\derab\source\repos\droiddeck-mali\`
|
||||
- `DroidDeck-0.3.1.apk`: the official APK. Prebuilt assets and proot come from it.
|
||||
- `venus-out/`: the Mesa Venus ICD.
|
||||
- `layer/`: the Mali compatibility layer and its manifest.
|
||||
- `libblsession.so`: the session preload with `venus.c`.
|
||||
- `gamescope`: gamescope 3.16.29 with the app's patches plus 0114.
|
||||
- `venus.patch`: the source diff the APK build applies.
|
||||
- `DroidDeck-0.3.1-mali-venus-<n>.apk`: the builds.
|
||||
- **WSL Ubuntu** (`wsl -d Ubuntu`, user `delo`; use `-u root` for apt, there's no passwordless sudo):
|
||||
- `/home/delo/android-sdk`: SDK, NDK 27.3.13750724, CMake 3.22.1, build-tools 34.
|
||||
- `/home/delo/mali`: virglrenderer 1.3.0 (patched), Mesa 26.2.4 checkout (patched), libepoxy, Vulkan-Headers, `android-out/`.
|
||||
- `/home/delo/DroidDeck`: the clean LF clone the APK is built in.
|
||||
- The Edit and Read tools open WSL files at `\\wsl.localhost\Ubuntu\home\delo\...`.
|
||||
- **ADB:** `C:\Users\derab\tools\platform-tools\adb.exe`, paired with the Pixel over wireless debugging.
|
||||
- **DXVK source** for reference: `git clone https://github.com/doitsujin/dxvk` at commit `25ca63f17f34` (v3.1.1-27), the one in Proton Experimental ARM64 11.0-20260924.
|
||||
- Its shader compiler is the `subprojects/dxbc-spirv` submodule.
|
||||
|
||||
## How it works
|
||||
|
||||
The session's Linux processes (glibc) cannot load Mali's Android (bionic) Vulkan driver.
|
||||
Venus bridges them:
|
||||
|
||||
1. The guest loads Mesa's Venus ICD (`libvulkan_virtio.so`) with `VN_DEBUG=vtest`.
|
||||
2. The ICD serializes Vulkan calls over a unix socket: `files/venus/vtest.sock`.
|
||||
3. virglrenderer's `virgl_test_server --venus --no-virgl` runs on the Android side as an app child process.
|
||||
4. Per client, it forks `virgl_render_server`, which replays the calls on Mali's system Vulkan driver.
|
||||
|
||||
For Wine games, the Mali compatibility layer sits between DXVK (via winevulkan) and the Venus ICD.
|
||||
|
||||
The app's own compositor uses Mali's system driver directly.
|
||||
|
||||
## Mali compatibility layer (`tools/venus/layer`)
|
||||
|
||||
Why: DXVK 3.1.1 refuses any GPU without six features, and Mali-G715 has none of them.
|
||||
The list comes from `dxvk/dxvk_device_info.cpp`, `getFeatureList`, compared with `vulkaninfo` through Venus.
|
||||
Everything else DXVK requires is present: Vulkan 1.4, geometry and tessellation shaders, maxPushConstantsSize 256.
|
||||
|
||||
What it does, per feature:
|
||||
- `fillModeNonSolid`: LINE and POINT polygon modes draw as FILL.
|
||||
- `multiViewport`: reports maxViewports 16. Pipelines and `vkCmdSet{Viewport,Scissor}[WithCount]` keep only the first.
|
||||
- `robustBufferAccess2`: the device gets `robustBufferAccess` (version 1) instead.
|
||||
- `shaderClipDistance`: emulated per pipeline.
|
||||
- The last pre-rasterization stage writes the distances to a free varying location.
|
||||
- The fragment shader reads them and runs `OpKill` when one is negative.
|
||||
- Only when that stage is the only one using distances and the fragment shader's code is known.
|
||||
- Otherwise the distances are dropped. Depth-only passes lose clipping too.
|
||||
- DXVK passes shader code inline (`VkShaderModuleCreateInfo` in the stage), so its pipelines qualify.
|
||||
- Mali has no `graphicsPipelineLibraryIndependentInterpolationDecoration`, so DXVK compiles whole pipelines and the layer sees both stages.
|
||||
- `shaderCullDistance`: dropped.
|
||||
- `textureCompressionBC`: BC1-BC7 images are created as RGBA8, R8, RG8 or RGBA16F.
|
||||
- Every upload into one is decoded on the CPU with `bcdec` while the copy is recorded.
|
||||
- The source must be memory the application has mapped; DXVK's staging memory is.
|
||||
- Decoded texels go through the layer's own staging buffers, recycled when the command buffer is reset.
|
||||
- Copies from a BC image into a buffer, and between BC and uncompressed images, are skipped with a warning.
|
||||
|
||||
Files:
|
||||
- `layer.c`: loader plumbing, feature and limit reporting, device creation, the hook table.
|
||||
- `pipeline.c`: pipelines, shader modules, viewports.
|
||||
- `spirv.c`: the SPIR-V rewriter for clip and cull distances.
|
||||
- `bc.c`: BC formats, images and uploads.
|
||||
- `VkLayer_droiddeck_mali_compat.json`: implicit layer manifest.
|
||||
|
||||
When it is active:
|
||||
- Only in Wine processes (`WINEPREFIX` set), and only for features the GPU lacks.
|
||||
- `DROIDDECK_MALI_COMPAT=1` forces it on, `0` off. `DROIDDECK_MALI_COMPAT_DISABLE=1` keeps the loader from loading it.
|
||||
- Wine's own `explorer.exe` uses Zink, so it gets the layer too.
|
||||
- It logs one line per device: `droiddeck-mali-compat: emulating …`.
|
||||
|
||||
How it ships:
|
||||
- `build-apk.sh` copies `layer/` into the APK's `assets/linuxfs/usr/local/…`.
|
||||
- `SessionFiles.kt` stages both files into the guest at every session start (its `optional` list).
|
||||
- Guest paths: `usr/local/lib/droiddeck-mali/` and `usr/local/share/vulkan/implicit_layer.d/`.
|
||||
|
||||
Not done yet:
|
||||
- Unit tests for the SPIR-V rewriter. It is untested beyond DXVK's shaders, and unknown whether Silksong's shaders used clip distances at all.
|
||||
- Performance: BC decoding on the CPU makes loads slow. A compute-shader decoder would be the next step.
|
||||
|
||||
## Changes on the branch
|
||||
|
||||
App (Kotlin/C):
|
||||
- `session/VenusComponent.kt` (new): on a non-Adreno GPU, starts the vtest server and stages the ICD to `files/venus/`.
|
||||
- It sets the guest env: `VK_ICD_FILENAMES`, `VN_DEBUG=vtest`, `VTEST_SOCKET_NAME`, `MESA_VK_WSI_DEBUG=sw`.
|
||||
- `session/SessionService.kt`: uses the Venus env instead of the Turnip ICD, and adds the component.
|
||||
- `gpu/TurnipDriver.java`: the compositor uses the system Vulkan driver on non-Adreno.
|
||||
- `cpp/waylandcomp/src/vk_present.c`:
|
||||
- Enables only the dma-buf extensions the driver has.
|
||||
- Logs the driver's full extension list.
|
||||
- Gives a zero row pitch a packed 64-byte row (gamescope's 1x1 root buffer).
|
||||
- `gpu/GpuInfo.kt`, `MainActivity.kt`, `core/DeviceReport.kt`: wording, plus a "Venus" line in `device.txt`.
|
||||
- `session/SessionFiles.kt`: stages the Mali compatibility layer when the APK carries it.
|
||||
- `tools/linuxfs/preload/venus.c` (new, part of `libblsession`): unsets `LIBGL_KOPPER_DISABLE` when `VN_DEBUG` has `vtest`.
|
||||
- Steam's `steamwebhelper.sh` sets it unconditionally.
|
||||
- Without kopper and without DRI3, Zink gets no GL context, and the Steam UI crash-loops.
|
||||
- Steam restores that script when it verifies its install, so it cannot be edited.
|
||||
|
||||
`tools/venus/mesa-venus-vtest.patch` (Mesa 26.2.4, guest side):
|
||||
- No `VK_EXT_physical_device_drm` under vtest. gamescope otherwise demanded a primary node.
|
||||
- Sync-fd export for fences and semaphores under vtest: a CPU wait that returns -1 (already signaled). gamescope requires `VK_KHR_external_semaphore_fd`.
|
||||
- WSI skips attaching a -1 sync file to a dma-buf.
|
||||
- `vn_queue_submission_init_syncs` submits only the sync slots it filled.
|
||||
- Timeline semaphores free all `queue_count + 1` renderer syncs. Upstream freed one too few and leaked a vtest sync each.
|
||||
- `vn_queue_submit` runs under a per-queue `submit_mutex`. The async present thread raced the app's submits; see Status.
|
||||
- WSI's CPU readback buffer goes to Mali's hidden cached memory type; see Performance.
|
||||
- `vn_physical_device`: keeps the renderer's real memory flags, and picks the hidden type under vtest.
|
||||
- `vn_renderer_vtest.c`: flush and invalidate of incoherent memory are `DMA_BUF_IOCTL_SYNC` on the bo's dma-buf.
|
||||
- WSI common code: `vkInvalidateMappedMemoryRanges` before every CPU read of a frame.
|
||||
|
||||
`tools/venus/measure-present.patch`: per-frame present timings on stderr, applied on top for `MEASURE=1` builds only.
|
||||
|
||||
`tools/venus/virglrenderer-android.patch` (virglrenderer 1.3.0, host side):
|
||||
- Mali on Android can import dma-bufs but cannot export any memory.
|
||||
- Buffers report dma_buf features 0x4 (importable only); opaque fd reports nothing.
|
||||
- virglrenderer's minigbm fallback does not exist on Android.
|
||||
- On Android the server allocates the dma-buf itself and imports it.
|
||||
- Source for coherent types: `/dev/dma_heap/system-uncached`, then `/dev/dma_heap/system`, then an `AHardwareBuffer` fd.
|
||||
- Uncached because Mali here is not cache-coherent with the CPU, and nobody calls `DMA_BUF_IOCTL_SYNC` on coherent memory.
|
||||
- The guest maps coherent memory without syncs, and on the cached heap frames tore at cache-line granularity: the streaks.
|
||||
- Cached types (not coherent) come from `/dev/dma_heap/system`. Whoever maps them syncs through the dma-buf.
|
||||
- The fd rides the existing udmabuf plumbing.
|
||||
- Image and buffer queries report "importable dma-buf" as exportable too. gamescope keeps only exportable modifiers.
|
||||
- Exports of any memory type go through that allocator.
|
||||
- Logs what the driver reports, and failed allocations.
|
||||
|
||||
`tools/gamescope/patches/0114-shm-buffers-upload-every-commit.patch`:
|
||||
- Xwayland has no glamor here, so it reuses about three wl_shm buffers with new pixels.
|
||||
- gamescope cached one texture per buffer, copied at first import.
|
||||
- The screen cycled through three stale frames: the flicker. Input and audio still worked.
|
||||
- The patch caches dma-buf textures only, and uploads shm buffers on every commit.
|
||||
- See `tools/gamescope/PATCHES.md`.
|
||||
- The session stages gamescope from the APK assets every start, so it needs an APK rebuild.
|
||||
|
||||
## Build
|
||||
|
||||
Run each step after its inputs change:
|
||||
|
||||
1. Android side (WSL): `bash /mnt/c/Users/derab/source/repos/DroidDeck/tools/venus/build-virgl-android.sh`
|
||||
- It does a full clean rebuild; `ninja -C /home/delo/mali/virgl-build install` is enough for code changes.
|
||||
- After editing `/home/delo/mali/virglrenderer`, refresh the patch: `git -C /home/delo/mali/virglrenderer diff > .../tools/venus/virglrenderer-android.patch`.
|
||||
2. Guest ICD (Git Bash, Docker Desktop running): `MSYS_NO_PATHCONV=1 bash tools/venus/build-venus-icd.sh`
|
||||
- It clones Mesa fresh and applies `tools/venus/mesa-venus-vtest.patch`. About 5 minutes.
|
||||
- To change Venus: edit `/home/delo/mali/mesa`, then refresh the patch from Git Bash:
|
||||
`MSYS_NO_PATHCONV=1 wsl -d Ubuntu -u delo -- git -C /home/delo/mali/mesa diff > tools/venus/mesa-venus-vtest.patch`
|
||||
3. Mali compatibility layer (Git Bash, Docker): `MSYS_NO_PATHCONV=1 bash tools/venus/build-layer.sh`
|
||||
- Fetches Vulkan-Headers and SPIRV-Headers (vulkan-sdk-1.4.357.0) and `bcdec.h` at a pinned commit. Under a minute.
|
||||
4. Preload (Git Bash, Docker): `MSYS_NO_PATHCONV=1 bash tools/venus/build-libblsession.sh`
|
||||
5. gamescope (Git Bash, Docker): `MSYS_NO_PATHCONV=1 bash tools/venus/build-gamescope.sh`
|
||||
- Emulated arm64, so it takes most of an hour.
|
||||
- Prototype 11's binary came from the same steps run by hand; the script itself has not run yet.
|
||||
6. Source patch (Git Bash): `git diff 0.3.1 > ../droiddeck-mali/venus.patch`
|
||||
- Run `git add -N` on new files first.
|
||||
7. APK (WSL): `bash /mnt/c/Users/derab/source/repos/DroidDeck/tools/venus/build-apk.sh <n>`
|
||||
- It packs the outputs of steps 1-5. Rebuild those first if their sources changed.
|
||||
|
||||
Gotchas:
|
||||
- Run Docker from Git Bash, not WSL: Docker Desktop's WSL integration is off.
|
||||
- Prefix Git Bash commands with `MSYS_NO_PATHCONV=1`, or paths given to `wsl`, `docker` and `adb` get mangled.
|
||||
- `wsl -- bash -c '…'` loses `$VARIABLES`; put the commands in a script file and run `wsl -- bash /mnt/c/…/script.sh`.
|
||||
- `adb pull` needs a Windows path as its target.
|
||||
- The APK is signed with the project's public test key, so it installs over earlier prototypes but not over the official app.
|
||||
- Use `git -c core.autocrlf=false -c core.eol=lf archive` to export files for a Linux build; plain `git archive` writes CRLF.
|
||||
|
||||
## Test loop over ADB
|
||||
|
||||
```sh
|
||||
A=/c/Users/derab/tools/platform-tools/adb.exe; export MSYS_NO_PATHCONV=1
|
||||
$A mdns services # find the phone's connect port if it dropped
|
||||
timeout 300 $A install -r "C:/Users/derab/source/repos/droiddeck-mali/DroidDeck-0.3.1-mali-venus-<n>.apk"
|
||||
$A shell am force-stop com.droiddeck.launcher
|
||||
$A shell monkey -p com.droiddeck.launcher -c android.intent.category.LAUNCHER 1
|
||||
$A shell input tap 897 1064 # "Play Steam" on the main page
|
||||
$A exec-out screencap -p > shot.png
|
||||
```
|
||||
|
||||
- The phone must be awake and unlocked, or `adb install` hangs.
|
||||
- Tap "Play Steam" only once MainActivity is the top resumed activity; an earlier tap is lost.
|
||||
- Wrap a remote `run-as ... sh -c` command in double quotes as one argument, or adb splits it. Longer scripts: push a file and run it with `run-as … sh /data/local/tmp/x.sh`.
|
||||
- Session logs: `/sdcard/Download/DroidDeck/<newest>/`
|
||||
- `session.log`: gamescope, Steam and game stdout and stderr.
|
||||
- `venus.log`: the vtest and render servers.
|
||||
- `wayland.log`: the compositor; frames on screen and windows open.
|
||||
- `events.jsonl`: `frame.first` means the loading overlay lifted.
|
||||
- `crash.log`.
|
||||
- Steam's own logs, live: `$A shell run-as com.droiddeck.launcher sh -c 'cd files/linuxfs/root/.local/share/Steam/logs; ...'`
|
||||
- The useful ones are `webhelper.txt`, `webhelper_gpu.txt`, `cef_log.txt`, `console_log.txt` and `gameprocess_log.txt`.
|
||||
- The session script copies those logs into `<session>/steam/` only on a clean exit.
|
||||
- Clean exit: "Stop session" on the DroidDeck notification. Leaving the app only suspends the session.
|
||||
- `Download/droiddeck-env` (KEY=VALUE lines) adds guest env without a rebuild. It is read at session start only.
|
||||
- First Steam start downloads and unpacks about 670 MB. On later starts Steam "verifies" and re-extracts changed files.
|
||||
|
||||
Faster iteration on GPU code, without an APK (needs a debuggable build, see Status):
|
||||
- Venus ICD: push it, then replace `files/venus/libvulkan_virtio.so` with `cp` to a new name and `mv` over it.
|
||||
- `mv` keeps the running gamescope and Steam on their old copy; overwriting in place could crash them.
|
||||
- Layer: copy the two files to the guest paths above. New processes load it. The next session start restages the APK's copy.
|
||||
- What the guest sees: `MSYS_NO_PATHCONV=1 bash tools/venus/guest-vulkaninfo.sh [0|1]` with a session running.
|
||||
|
||||
Debugging a game:
|
||||
- Proton log: `PROTON_LOG=1` in `droiddeck-env`, restart the session, launch. The log is `files/linuxfs/root/steam-<appid>.log`.
|
||||
- DXVK's lines start with `info:`, `warn:`, `err:`. Proton otherwise turns DXVK logging off.
|
||||
- Unity games: `Player.log` in the prefix, `pfx/drive_c/users/steamuser/AppData/LocalLow/<company>/<game>/`.
|
||||
- A crash in Linux code shows in the Proton log as `handle_syscall_fault … pc=0x…`, then `Exception 0xc0000005 in Unix call`.
|
||||
1. Before the launch, run `tools/venus/watch-maps.sh '<game>.exe'` on the phone (see its header).
|
||||
2. After the crash, find the library whose range holds the pc in `cache/game-maps.txt`. Offset = pc - range start + file offset.
|
||||
3. Resolve it in WSL: `bash /mnt/c/…/tools/venus/addr2line.sh <library in droiddeck-mali> <offset>`.
|
||||
- The thread name is in the log: `Thread renamed to "dxvk-submit"`.
|
||||
- Untested idea for launching a game without the user: write `steam://rungameid/<appid>` into `files/linuxfs/root/.steam/steam.pipe`.
|
||||
|
||||
Measuring a frame (needs a debuggable build):
|
||||
1. `MEASURE=1 MSYS_NO_PATHCONV=1 bash tools/venus/build-venus-icd.sh` builds the ICD with `measure-present.patch` into `droiddeck-mali/venus-out-measure/`.
|
||||
2. Install it by hand (see "Faster iteration"), with `PROTON_LOG=1` in `droiddeck-env`.
|
||||
3. Every 120 presents the game's Proton log gets two lines:
|
||||
- `MEASURE wl`: frame interval, the `memcpy` out of the readback buffer, the whole Wayland present. Average/max in ms.
|
||||
- `MEASURE vn`: the present thread, its GPU fence waits, and how long the game blocked in `vn_wsi_flush`.
|
||||
4. Per-thread CPU while playing: `adb shell "top -H -b -n 2 -d 8 -o TID,PID,%CPU,S,CMD,NAME"`, sorted by the third column.
|
||||
5. `wayland.log` in the session folder has the compositor's fps and per-frame costs every 10 s, without any special build.
|
||||
|
||||
## Failure history (prototype → cause → fix)
|
||||
|
||||
1. Official APK installed → Turnip ICD, no GPU → install the prototype.
|
||||
2. gamescope: "physical device has no primary node" → Mesa: drop `EXT_physical_device_drm` under vtest.
|
||||
3. gamescope: missing `VK_KHR_external_semaphore_fd` → Mesa: CPU-wait sync-fd export.
|
||||
4. Hang on loading: server "minigbm_allocation is not enabled" → virgl: relax the export check. Not enough: Mali exports nothing.
|
||||
5. Same hang → virgl: allocate a dma-buf (dma-heap or AHB) and import it.
|
||||
6. gamescope assert `modifiers.size() > 0` → virgl: report importable dma-buf as exportable; route exports through the allocator.
|
||||
7. Updater "zink: could not create swapchain"; Xwayland has no glamor, so no DRI3 → `MESA_VK_WSI_DEBUG=sw`.
|
||||
8. steamwebhelper restart loop, "failed to acquire a gl context" → `venus.c` preload unsets `LIBGL_KOPPER_DISABLE`.
|
||||
9. Frames reach the compositor but "0 windows open" and the overlay stays → compositor: fix stride 0 on gamescope's 1x1 root buffer.
|
||||
10. Sign-in screen shows, with dash streaks across it → virgl: allocate from the uncached dma-heap.
|
||||
11. Picture looks frozen or flickers between old frames, though clicks play sounds → gamescope patch 0114.
|
||||
12. Steam sign-in and Slay the Spire 2 at about 40 fps. Silksong: "d3d11: failed to create factory"; DXVK skips the GPU for `fillModeNonSolid` → the Mali compatibility layer.
|
||||
13. Silksong: D3D11 starts, black screen, then a crash in Venus's `vtest_vcmd_submit_cmd2` → Mesa: serialize queue submits against the async present thread. Silksong plays at 35-40 fps.
|
||||
14. Silksong held at 35-40 fps; Venus's present thread spent half its time copying frames from uncached memory → cached readback buffer (prototype 13), 47-52 fps.
|
||||
|
||||
## Next steps
|
||||
|
||||
1. Performance, measured first with `MEASURE=1` (see Performance):
|
||||
- The two GPU fence waits and two submits per present (~10 ms on the present thread).
|
||||
- The `dxvk-frame` thread at 30% CPU, probably Venus polling in semaphore waits.
|
||||
2. Silksong: check BC textures look right and loading time is bearable.
|
||||
3. Test more games on different engines: GameMaker, FNA (Celeste, Stardew Valley), Unity D3D9, Godot. Fix shared gaps in the layer, never per game.
|
||||
4. Direct3D 12 games use VKD3D-Proton, which has its own requirement list. Check it the same way.
|
||||
5. Clean up: delete `droiddeck-env` when debugging is done.
|
||||
|
||||
Rules from the user:
|
||||
- Never enter credentials for the user. They type the password and handle Steam Guard themselves.
|
||||
- Test every build on the phone over wireless debugging.
|
||||
- Fixes go in shared layers (Venus, the compatibility layer), not per game.
|
||||
@@ -13,7 +13,7 @@ else
|
||||
fi
|
||||
sdk_dir=${ANDROID_HOME:-${ANDROID_SDK_ROOT:-"${HOME}/Library/Android/sdk"}}
|
||||
java_dir=${JAVA_HOME:-"/opt/homebrew/opt/openjdk@17/libexec/openjdk.jdk/Contents/Home"}
|
||||
image_name=${DROIDDECK_BUILD_IMAGE:-droiddeck-local-cross:24.04-v3}
|
||||
image_name=${DROIDDECK_BUILD_IMAGE:-droiddeck-local-cross:24.04-v4}
|
||||
build_variant=${DROIDDECK_BUILD_VARIANT:-release}
|
||||
case "$build_variant" in
|
||||
debug) gradle_task=assembleDebug ;;
|
||||
@@ -102,7 +102,13 @@ docker run --rm --platform linux/amd64 \
|
||||
aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -pthread \
|
||||
-o "$d/libssbs.so" tools/linuxfs/ssbs/ssbs_adapter.c -ldl
|
||||
aarch64-linux-gnu-strip --strip-unneeded "$d/libssbs.so"
|
||||
mkdir -p "$d/usr/local/lib/droiddeck-xclipse"
|
||||
aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -Wextra -Wno-unused-parameter -fvisibility=hidden -pthread \
|
||||
-o "$d/usr/local/lib/droiddeck-xclipse/libVkLayer_droiddeck_xclipse.so" tools/linuxfs/xclipse-layer/xclipse_layer.c -ldl
|
||||
aarch64-linux-gnu-strip --strip-unneeded "$d/usr/local/lib/droiddeck-xclipse/libVkLayer_droiddeck_xclipse.so"
|
||||
install -m644 tools/linuxfs/xclipse-layer/VkLayer_droiddeck_xclipse.json "$d/usr/local/lib/droiddeck-xclipse/"
|
||||
mkdir -p "$d/usr/local/bin"
|
||||
tools/vkbridge/build-client-linux.sh "$d" aarch64-linux-gnu-gcc
|
||||
aarch64-linux-gnu-gcc -O2 -Wall -Wextra -o "$d/usr/local/bin/droiddeck-clipboard" tools/linuxfs/clipboard/clipboard.c -ldl
|
||||
aarch64-linux-gnu-strip --strip-unneeded "$d/usr/local/bin/droiddeck-clipboard"
|
||||
for script in tools/linuxfs/overlay/usr/local/bin/droiddeck-* tools/linuxfs/overlay/usr/local/bin/steam-compatibility; do
|
||||
@@ -322,6 +328,7 @@ fi
|
||||
cd "${repo_root}"
|
||||
python3 tools/quest/build-driver.py "${NDK}"
|
||||
bash tools/comet/build-local.sh
|
||||
python3 tools/powervr/fetch.py
|
||||
python3 tools/release/runtime_inputs.py record
|
||||
./gradlew "${gradle_task}" --console=plain -PndkVersion="${ndk_version}" ${gradle_rust_arg}
|
||||
python3 tools/release/check_session_assets.py "app/build/outputs/apk/${build_variant}/app-${build_variant}.apk"
|
||||
|
||||
Executable
+42
@@ -0,0 +1,42 @@
|
||||
#!/usr/bin/env bash
|
||||
# CI component build; this does not change the APK or an installed Proton depot.
|
||||
set -euo pipefail
|
||||
root=$(cd "$(dirname "$0")/../.." && pwd)
|
||||
. "$root/tools/dxvk/source.env"
|
||||
mkdir -p "${1:?output directory required}"
|
||||
out=$(cd "$1" && pwd)
|
||||
# Refuse to mix a pinned build with prior DLLs or an incomplete previous build.
|
||||
# Include dotfiles in the check and leave all existing contents untouched.
|
||||
shopt -s nullglob dotglob
|
||||
existing=("$out"/*)
|
||||
if ((${#existing[@]})); then
|
||||
printf '%s\n' 'output directory must be empty; use a fresh build directory' >&2
|
||||
exit 1
|
||||
fi
|
||||
shopt -u nullglob dotglob
|
||||
work=$(mktemp -d)
|
||||
trap 'rm -rf "$work"' EXIT
|
||||
git init -q "$work/source"
|
||||
git -C "$work/source" fetch --depth=1 https://github.com/doitsujin/dxvk.git "$DXVK_REVISION"
|
||||
git -C "$work/source" checkout -q --detach FETCH_HEAD
|
||||
test "$(git -C "$work/source" rev-parse HEAD)" = "$DXVK_REVISION"
|
||||
git -C "$work/source" submodule update --init --recursive --depth=1
|
||||
for patch in "$root"/tools/dxvk/patches/*.patch; do
|
||||
git -C "$work/source" apply --check "$patch"
|
||||
git -C "$work/source" apply "$patch"
|
||||
done
|
||||
python3 "$root/tools/dxvk/check_present_sync.py" "$work/source/src/dxvk/dxvk_presenter.cpp"
|
||||
python3 "$root/tools/dxvk/check_hud_storage_format.py" "$work/source/src/dxvk/hud/shaders/hud_frame_time_eval.comp"
|
||||
python3 "$root/tools/dxvk/check_d3d9_single_sample.py" "$work/source"
|
||||
for arch in 32 64; do
|
||||
meson setup "$work/build$arch" "$work/source" --cross-file "$work/source/build-win$arch.txt" \
|
||||
--buildtype release --prefix "$out" --bindir "x$arch" --libdir "x$arch" -Db_ndebug=if-release --strip
|
||||
meson compile -C "$work/build$arch" -j 4
|
||||
meson install -C "$work/build$arch"
|
||||
done
|
||||
cp "$work/source/LICENSE" "$out/LICENSE"
|
||||
printf '%s\n' "$DXVK_REVISION" > "$out/source-commit"
|
||||
git -C "$work/source" submodule status --recursive > "$out/submodules.txt"
|
||||
git -C "$work/source" diff > "$out/downstream.patch"
|
||||
tar --exclude-vcs --zstd -cf "$out/source.tar.zst" -C "$work/source" .
|
||||
(cd "$out" && find x32 x64 -name '*.dll' -type f -print0 | sort -z | xargs -0 sha256sum > SHA256SUMS)
|
||||
@@ -0,0 +1,112 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Compile pinned DXVK's actual descriptor paths against a controlled backend.
|
||||
|
||||
This checks CPU control flow, not GPU rendering. No Wine/game/device is started.
|
||||
"""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
CASES = ('forced_msaa_depth', 'default_msaa_depth', 'forced_nonmaskable',
|
||||
'default_nonmaskable', 'forced_already_single', 'forced_no_depth',
|
||||
'forced_unsupported', 'forced_invalid_type', 'forced_lockable_msaa',
|
||||
'forced_lockable_single', 'forced_allocation_failure',
|
||||
'default_allocation_failure', 'forced_recreate', 'ordinary_surface',
|
||||
'ordinary_invalid_lockable')
|
||||
|
||||
|
||||
def function(text, signature):
|
||||
start = text.index(signature)
|
||||
opening = text.index('{', start)
|
||||
# Ignore braces in comments and strings while preserving source positions.
|
||||
stripped = re.sub(r'//[^\n]*|/\*.*?\*/|"(?:\\.|[^"\\])*"|\'(?:\\.|[^\'\\])*\'',
|
||||
lambda m: ' ' * len(m.group()), text, flags=re.S)
|
||||
depth = 0
|
||||
for index in range(opening, len(stripped)):
|
||||
depth += (stripped[index] == '{') - (stripped[index] == '}')
|
||||
if depth == 0:
|
||||
return text[start:index + 1]
|
||||
raise ValueError('Unterminated source function: ' + signature)
|
||||
|
||||
|
||||
def production(source):
|
||||
base = source / 'src/d3d9'
|
||||
common = (base / 'd3d9_common_texture.cpp').read_text()
|
||||
header = (base / 'd3d9_common_texture.h').read_text()
|
||||
swap = (base / 'd3d9_swapchain.cpp').read_text()
|
||||
device = (base / 'd3d9_device.cpp').read_text()
|
||||
util = (base / 'd3d9_util.cpp').read_text()
|
||||
pieces = {
|
||||
'decode': function(util, 'HRESULT DecodeMultiSampleType('),
|
||||
'normalize': function(common, 'HRESULT D3D9CommonTexture::NormalizeTextureProperties('),
|
||||
'backbuffers': function(swap, 'HRESULT D3D9SwapChainEx::CreateBackBuffers('),
|
||||
'uses_image': function(header, 'static bool TextureUsesImage('),
|
||||
}
|
||||
reset = function(device, 'HRESULT D3D9DeviceEx::ResetSwapChain(')
|
||||
begin = reset.index('D3D9_COMMON_TEXTURE_DESC desc;', reset.index('if (pPresentationParameters->EnableAutoDepthStencil)'))
|
||||
end = reset.index('m_autoDepthStencil =', begin)
|
||||
pieces['auto_depth'] = reset[begin:end].rstrip()
|
||||
framebuffer = function(device, 'void D3D9DeviceEx::BindFramebuffer(')
|
||||
begin = framebuffer.index('const bool mismatch =')
|
||||
end = framebuffer.index(';', framebuffer.index('const bool bindDS =', begin)) + 1
|
||||
pieces['depth_binding'] = framebuffer[begin:end]
|
||||
return pieces
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('source', type=Path, help='Pinned DXVK tree with downstream patches applied')
|
||||
parser.add_argument('--cxx', default=os.environ.get('CXX', 'c++'))
|
||||
parser.add_argument('--sanitize', action='store_true', help='Enable ASan/UBSan on the CPU harness')
|
||||
args = parser.parse_args()
|
||||
pieces = production(args.source)
|
||||
harness = (Path(__file__).parent / 'tests/d3d9_single_sample.cpp').read_text()
|
||||
harness = harness.replace('/* PRODUCTION_USES_IMAGE */', pieces['uses_image'])
|
||||
with tempfile.TemporaryDirectory(prefix='dxvk-d3d9-') as directory:
|
||||
out = Path(directory)
|
||||
(out / 'harness.cpp').write_text(harness)
|
||||
include = '\n\n'.join(pieces[key] for key in ('decode', 'normalize', 'backbuffers'))
|
||||
include += '\nHRESULT auto_depth(D3D9DeviceEx* device, D3DPRESENT_PARAMETERS* pPresentationParameters, D3D9_COMMON_TEXTURE_DESC* output) {\n'
|
||||
include += 'auto* self = device;\n' + pieces['auto_depth'].replace('(this,', '(self,')
|
||||
include += '\n*output = desc; return D3D_OK;\n}\n'
|
||||
include += '\nbool depth_binds(const ImageInfo& color, const ImageInfo& dsInfo) {\n'
|
||||
include += 'auto sampleCount = color.sampleCount; auto renderArea = color.extent;\n'
|
||||
include += 'const bool noRT0Bound = false, ignoreRT0 = false;\n'
|
||||
include += pieces['depth_binding'] + '\nreturn bindDS;\n}\n'
|
||||
(out / 'd3d9_production.inc').write_text(include)
|
||||
command = [args.cxx, '-std=c++17', '-Wall', '-Wextra', '-Werror',
|
||||
'-Wno-unused-parameter', str(out / 'harness.cpp'), '-o', str(out / 'check')]
|
||||
# The original CreateBackBuffers does not use Flags; that known baseline
|
||||
# warning must not turn a negative control into a compiler-fixture error.
|
||||
if args.sanitize:
|
||||
command[1:1] = ['-fsanitize=address,undefined', '-fno-omit-frame-pointer']
|
||||
compilation = subprocess.run(command, capture_output=True, text=True)
|
||||
if compilation.returncode:
|
||||
raise SystemExit(compilation.stderr)
|
||||
results = []
|
||||
for case in CASES:
|
||||
process = subprocess.run([str(out / 'check'), case], capture_output=True,
|
||||
text=True, timeout=10, cwd=out,
|
||||
env={'ASAN_OPTIONS': 'detect_leaks=' +
|
||||
('0' if sys.platform == 'darwin' else '1')})
|
||||
results.append({'case': case, 'passed': process.returncode == 0,
|
||||
'exit': process.returncode, 'detail': process.stderr.strip()[-800:]})
|
||||
result = {'cases': results, 'passed': sum(row['passed'] for row in results),
|
||||
'failed': sum(not row['passed'] for row in results),
|
||||
'production_sha256': {key: hashlib.sha256(value.encode()).hexdigest()
|
||||
for key, value in pieces.items()},
|
||||
'backend_and_adapter_mocked': True, 'GPU_test': False,
|
||||
'sanitizers': args.sanitize,
|
||||
'leak_detection': args.sanitize and sys.platform != 'darwin'}
|
||||
print(json.dumps(result, indent=2))
|
||||
return bool(result['failed'])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,73 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Compile the actual HUD shader and verify its binding-3 R8_UINT contract.
|
||||
|
||||
The frame-time HUD binds an R8_UINT texel-buffer view. An Unknown SPIR-V image
|
||||
format requires STORAGE_WRITE_WITHOUT_FORMAT, which PowerVR does not report
|
||||
for that buffer format. Static spirv-val alone accepts both declarations;
|
||||
this check validates the shader against the known host-side binding contract.
|
||||
"""
|
||||
import argparse
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import struct
|
||||
import subprocess
|
||||
import tempfile
|
||||
|
||||
|
||||
def check(shader):
|
||||
compiler = shutil.which('glslangValidator')
|
||||
validator = shutil.which('spirv-val')
|
||||
if not compiler or not validator:
|
||||
raise RuntimeError('glslangValidator and spirv-val required')
|
||||
with tempfile.TemporaryDirectory(prefix='dxvk-hud-contract-') as directory:
|
||||
output = Path(directory) / 'hud.spv'
|
||||
for command in ([compiler, '-V', '--target-env', 'vulkan1.3', str(shader), '-o', str(output)],
|
||||
[validator, '--target-env', 'vulkan1.3', str(output)]):
|
||||
process = subprocess.run(command, capture_output=True, text=True, timeout=30)
|
||||
if process.returncode:
|
||||
raise RuntimeError('HUD shader compilation/SPIR-V validation failed')
|
||||
raw = output.read_bytes()
|
||||
if len(raw) < 20 or len(raw) % 4:
|
||||
raise RuntimeError('Malformed SPIR-V')
|
||||
words = struct.unpack('<' + str(len(raw) // 4) + 'I', raw)
|
||||
if words[0] != 0x07230203:
|
||||
raise RuntimeError('Unexpected SPIR-V magic')
|
||||
bindings, sets, variables, pointers, images = {}, {}, {}, {}, {}
|
||||
offset = 5
|
||||
while offset < len(words):
|
||||
size, opcode = words[offset] >> 16, words[offset] & 0xffff
|
||||
if not size or size > len(words) - offset:
|
||||
raise RuntimeError('Malformed SPIR-V instruction')
|
||||
instruction = words[offset:offset + size]
|
||||
if opcode == 71 and size == 4: # OpDecorate
|
||||
if instruction[2] == 33:
|
||||
bindings[instruction[1]] = instruction[3]
|
||||
elif instruction[2] == 34:
|
||||
sets[instruction[1]] = instruction[3]
|
||||
elif opcode == 59 and size >= 4: # OpVariable
|
||||
variables[instruction[2]] = instruction[1]
|
||||
elif opcode == 32 and size == 4: # OpTypePointer
|
||||
pointers[instruction[1]] = instruction[3]
|
||||
elif opcode == 25 and size >= 9: # OpTypeImage
|
||||
images[instruction[1]] = (instruction[3], instruction[7], instruction[8])
|
||||
offset += size
|
||||
targets = [images.get(pointers.get(variables.get(identifier)))
|
||||
for identifier, binding in bindings.items()
|
||||
if binding == 3 and sets.get(identifier) == 0]
|
||||
if targets != [(5, 2, 39)]: # DimBuffer, storage image, ImageFormatR8ui
|
||||
raise RuntimeError('HUD binding 3 must compile to a storage texel buffer with ImageFormatR8ui')
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('shader', type=Path)
|
||||
args = parser.parse_args()
|
||||
try:
|
||||
check(args.shader)
|
||||
except RuntimeError as error:
|
||||
parser.exit(1, str(error) + '\n')
|
||||
print('HUD binding 3: SPIR-V valid, explicit R8ui storage texel-buffer format')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,116 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Replay asynchronous WSI ownership using the pinned presenter's actual selections.
|
||||
|
||||
This checks semaphore selection, not the full Vulkan presenter. Real Vulkan
|
||||
validation and device testing remain separate gates. Requires a native C++ compiler.
|
||||
"""
|
||||
import argparse
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import subprocess
|
||||
import tempfile
|
||||
|
||||
|
||||
def selection_code(source):
|
||||
match = re.search(
|
||||
r"// Return relevant Vulkan objects for the acquired image\s*"
|
||||
r"(?P<acquire>.*?)\s*m_presentPending = true;", source, re.S)
|
||||
wait = re.search(r"info\.pWaitSemaphores\s*=.*?;", source, re.S)
|
||||
if not match or not wait:
|
||||
raise ValueError("unsupported pinned presenter layout")
|
||||
return match["acquire"], wait[0]
|
||||
|
||||
|
||||
HARNESS = r'''
|
||||
#include <array>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <vector>
|
||||
using VkSemaphore = uint64_t;
|
||||
struct Sync { VkSemaphore acquire, present; };
|
||||
struct Info { const VkSemaphore* pWaitSemaphores; };
|
||||
|
||||
struct Presenter {
|
||||
std::vector<Sync> m_semaphores;
|
||||
std::vector<unsigned> m_images = {0, 1, 2, 3};
|
||||
unsigned m_frameIndex = 0, m_imageIndex = 0;
|
||||
bool m_hasSwapchainMaintenance1;
|
||||
explicit Presenter(bool maintenance): m_hasSwapchainMaintenance1(maintenance) {
|
||||
for (unsigned i = 0; i < (maintenance ? 4u : 8u); ++i)
|
||||
m_semaphores.push_back({100 + i, 1 + i});
|
||||
}
|
||||
Sync acquire() {
|
||||
Sync sync{}; unsigned image;
|
||||
ACQUIRE_SELECTION
|
||||
(void)image;
|
||||
return sync;
|
||||
}
|
||||
VkSemaphore present() {
|
||||
auto& currSync = m_semaphores.at(m_frameIndex);
|
||||
Info info{};
|
||||
PRESENT_SELECTION
|
||||
return *info.pWaitSemaphores;
|
||||
}
|
||||
};
|
||||
|
||||
int replay(bool maintenance) {
|
||||
Presenter p(maintenance);
|
||||
std::array<VkSemaphore, 4> outstandingByImage{};
|
||||
std::array<VkSemaphore, 4> outstandingByFence{};
|
||||
// Deliberately delay reacquisition of image 2 beyond a full frame-ring cycle.
|
||||
const std::array<unsigned, 21> imageOrder = {
|
||||
2,0,3,0,1,3,0,1,1,2,3,1,0,3,2,2,0,1,3,0,2
|
||||
};
|
||||
for (unsigned iteration = 0; iteration < 200; ++iteration) {
|
||||
p.m_imageIndex = imageOrder[iteration % imageOrder.size()];
|
||||
if (maintenance) {
|
||||
// The existing fence path waits this frame's previous present fence.
|
||||
const auto completed = outstandingByFence.at(p.m_frameIndex);
|
||||
for (auto& pending : outstandingByImage)
|
||||
if (pending == completed) pending = 0;
|
||||
}
|
||||
// Acquisition and its GPU wait complete the last present of THIS image.
|
||||
outstandingByImage.at(p.m_imageIndex) = 0;
|
||||
const auto signal = p.acquire().present;
|
||||
const auto wait = p.present();
|
||||
if (signal != wait) {
|
||||
std::fprintf(stderr, "FAIL: render signal differs from present wait\n");
|
||||
return 2;
|
||||
}
|
||||
for (auto pending : outstandingByImage) {
|
||||
if (pending == signal) {
|
||||
std::fprintf(stderr, "FAIL: semaphore reused before presentation completion at frame %u\n", iteration);
|
||||
return 2;
|
||||
}
|
||||
}
|
||||
outstandingByImage.at(p.m_imageIndex) = signal;
|
||||
if (maintenance) outstandingByFence.at(p.m_frameIndex) = signal;
|
||||
p.m_frameIndex = (p.m_frameIndex + 1) % p.m_semaphores.size();
|
||||
}
|
||||
std::printf("PASS: %s, 200 out-of-order acquisitions\n", maintenance ? "present-fence path" : "no-present-fence path");
|
||||
return 0;
|
||||
}
|
||||
int main() {
|
||||
if (int status = replay(false)) return status;
|
||||
return replay(true);
|
||||
}
|
||||
'''
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("source", type=Path, help="pinned dxvk_presenter.cpp, after patching")
|
||||
args = parser.parse_args()
|
||||
acquire, present = selection_code(args.source.read_text())
|
||||
code = HARNESS.replace("ACQUIRE_SELECTION", acquire).replace("PRESENT_SELECTION", present)
|
||||
with tempfile.TemporaryDirectory(prefix="dxvk-present-sync-") as directory:
|
||||
cpp = Path(directory) / "replay.cpp"
|
||||
exe = Path(directory) / "replay"
|
||||
cpp.write_text(code)
|
||||
subprocess.run([os.environ.get("HOST_CXX", "c++"), "-std=c++17", "-Wall", "-Wextra", str(cpp), "-o", str(exe)], check=True)
|
||||
return subprocess.run([str(exe)]).returncode
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Loaded 100 of 285 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user