mirror of
https://github.com/MobileGL-Dev/MobileGL
synced 2026-11-25 02:32:16 +09:00
Compare commits
31
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5331106e90 | ||
|
|
ca981a8fc1 | ||
|
|
c90383db16 | ||
|
|
698f04574b | ||
|
|
f497ff9741 | ||
|
|
946e63d810 | ||
|
|
918d40dd4f | ||
|
|
f5b8fe48aa | ||
|
|
c5d25868cf | ||
|
|
c464947bdd | ||
|
|
4fb75f4e00 | ||
|
|
4d6904184d | ||
|
|
2f1a673513 | ||
|
|
88bc35b711 | ||
|
|
880be57bb6 | ||
|
|
70e4691b3a | ||
|
|
2d42414667 | ||
|
|
32d27b1491 | ||
|
|
78c5f8dae7 | ||
|
|
96bd540ba1 | ||
|
|
710beefd02 | ||
|
|
c1e957cb98 | ||
|
|
eb71b669b3 | ||
|
|
bb31f374a3 | ||
|
|
e5ee31b022 | ||
|
|
915882b293 | ||
|
|
963f4d8177 | ||
|
|
d627fca387 | ||
|
|
2de0d6dd25 | ||
|
|
66b47a101b | ||
|
|
4722fa38bb |
No files matched your search
@@ -72,7 +72,7 @@ bash scripts/build-android.sh # -> <worktree>/build-android/libMobileGL
|
||||
```
|
||||
The script runs, with the NDK toolchain:
|
||||
```
|
||||
-DANDROID_ABI=arm64-v8a -DANDROID_PLATFORM=android-26 -DCMAKE_BUILD_TYPE=RelWithDebInfo
|
||||
-DANDROID_ABI=arm64-v8a -DANDROID_PLATFORM=android-30 -DCMAKE_BUILD_TYPE=RelWithDebInfo
|
||||
-DMOBILEGL_PIPE_PUSH=ON -DMOBILEGL_BUILD_DISAGGREGATED=ON -DMOBILEGL_BUILD_DISAGGREGATED_INPROC=ON
|
||||
-DMOBILEGL_BUILD_TEST=OFF -DMOBILEGL_BUILD_BENCHMARK=OFF
|
||||
```
|
||||
|
||||
@@ -4,7 +4,8 @@
|
||||
# llvm-addr2line, it is what cyc.sh pushes). Stamp = worktree HEAD, so the container client
|
||||
# (xbuild.sh, same stamp) and the server agree on the build ("compatible wire with different build"
|
||||
# WARN otherwise). Env: MGL_WORKTREE, ANDROID_NDK, BUILD_DIR (default build-android), JOBS (12).
|
||||
# Log level is compiled to INFO.
|
||||
# Log level is compiled to INFO. android-30 = the APK's minSdk: thread_local is then the platform's
|
||||
# own TLS rather than the emulated one (which cost 7-12% of an apply thread on the API 26 build).
|
||||
set -euo pipefail
|
||||
. "$(dirname "$0")/env.sh"
|
||||
W=$MGL_WORKTREE
|
||||
@@ -12,7 +13,7 @@ B=$W/${BUILD_DIR:-build-android}
|
||||
STAMP=$(git -C "$W" rev-parse HEAD)
|
||||
if [ ! -f "$B/build.ninja" ]; then
|
||||
cmake -S "$W" -B "$B" -G Ninja -DCMAKE_TOOLCHAIN_FILE="$ANDROID_NDK/build/cmake/android.toolchain.cmake" \
|
||||
-DANDROID_ABI=arm64-v8a -DANDROID_PLATFORM=android-26 -DCMAKE_BUILD_TYPE=RelWithDebInfo \
|
||||
-DANDROID_ABI=arm64-v8a -DANDROID_PLATFORM=android-30 -DCMAKE_BUILD_TYPE=RelWithDebInfo \
|
||||
-DMOBILEGL_PIPE_PUSH=ON -DMOBILEGL_BUILD_DISAGGREGATED=ON -DMOBILEGL_BUILD_DISAGGREGATED_INPROC=ON \
|
||||
-DMOBILEGL_BUILD_TEST=OFF -DMOBILEGL_BUILD_BENCHMARK=OFF \
|
||||
-DCMAKE_CXX_FLAGS=-DMOBILEGL_LOG_ACTIVE_LEVEL=MOBILEGL_LOG_LEVEL_INFO \
|
||||
|
||||
@@ -18,6 +18,10 @@ on:
|
||||
- '**/*.md'
|
||||
workflow_dispatch:
|
||||
|
||||
env:
|
||||
# Software-rendered CI submissions may exceed the interactive GPU hang budget.
|
||||
MOBILEGL_GPU_HANG_BUDGET_MS: "0"
|
||||
|
||||
# ONE LIVE RUN PER BRANCH, as in test.yml: a superseded push is cancelled rather than left queued
|
||||
# behind its successor; a manual dispatch gets a group of its own; dev queues rather than cancels.
|
||||
concurrency:
|
||||
@@ -477,7 +481,7 @@ jobs:
|
||||
extra_retrace_args=()
|
||||
if [ "${MOBILEGL_CI_TRANSPORT}" = "inproc" ]; then
|
||||
extra_retrace_args+=(
|
||||
--env "MOBILEGL_TRANSPORT=inproc;MOBILEGL_IPC_ROLE_SPLIT_STATE=1;MOBILEGL_IPC_STRICT_ERRORS=1;MOBILEGL_IPC_RUN_AHEAD=1"
|
||||
--env "MOBILEGL_TRANSPORT=inproc;MOBILEGL_IPC_ROLE_SPLIT_STATE=1;MOBILEGL_IPC_STRICT_ERRORS=1;MOBILEGL_IPC_RUN_AHEAD=1;MOBILEGL_GPU_HANG_BUDGET_MS=${MOBILEGL_GPU_HANG_BUDGET_MS}"
|
||||
--require-inproc
|
||||
)
|
||||
elif [ "${MOBILEGL_CI_TRANSPORT}" = "spawn" ]; then
|
||||
@@ -493,12 +497,12 @@ jobs:
|
||||
# into the CLIENT's process and SetWindowHandle is refused on the way across with
|
||||
# Fatal{UnmigratedSurface, "AndroidNativeWindow@P12"} (Rule H).
|
||||
extra_retrace_args+=(
|
||||
--env "MOBILEGL_TRANSPORT=spawn;MOBILEGL_IPC_ROLE_SPLIT_STATE=1;MOBILEGL_IPC_STRICT_ERRORS=1;MOBILEGL_IPC_RUN_AHEAD=1"
|
||||
--env "MOBILEGL_TRANSPORT=spawn;MOBILEGL_IPC_ROLE_SPLIT_STATE=1;MOBILEGL_IPC_STRICT_ERRORS=1;MOBILEGL_IPC_RUN_AHEAD=1;MOBILEGL_GPU_HANG_BUDGET_MS=${MOBILEGL_GPU_HANG_BUDGET_MS}"
|
||||
--use-pbuffer
|
||||
--require-spawn
|
||||
)
|
||||
else
|
||||
extra_retrace_args+=(--env "MOBILEGL_TRANSPORT=monolith")
|
||||
extra_retrace_args+=(--env "MOBILEGL_TRANSPORT=monolith;MOBILEGL_GPU_HANG_BUDGET_MS=${MOBILEGL_GPU_HANG_BUDGET_MS}")
|
||||
fi
|
||||
# Bliss needs the newer signed ANGLE variant plus sampler mipmap
|
||||
# min-filter downgrading on ANGLE llvmpipe.
|
||||
|
||||
+35
-90
@@ -21,6 +21,10 @@ on:
|
||||
required: false
|
||||
default: "087685d1"
|
||||
|
||||
env:
|
||||
# Software-rendered CI submissions may exceed the interactive GPU hang budget.
|
||||
MOBILEGL_GPU_HANG_BUDGET_MS: "0"
|
||||
|
||||
# ONE LIVE RUN PER BRANCH. The disaggregation branch pushes (often docs-only) commits minutes apart
|
||||
# and each push fans out to ~330 retrace legs here and ~275 jobs in apk.yml; with no group, runs
|
||||
# sat queued for 10+ hours behind their own successors. A manual dispatch gets a group of its own,
|
||||
@@ -413,6 +417,12 @@ jobs:
|
||||
--discovery "${RUNNER_TEMP}/primary-inproc-lane.json" \
|
||||
--junit "${RUNNER_TEMP}/primary-inproc.xml" --output "${RUNNER_TEMP}/primary-inproc-proof.json"
|
||||
|
||||
# The run log needs a signed-in reader; annotations do not. Name every failed ctest entry,
|
||||
# with the lines of its output that say why, where anyone reading the run can see them.
|
||||
- name: Annotate failed entries
|
||||
if: failure()
|
||||
run: python3 scripts/ci/junit_annotate.py "${RUNNER_TEMP}"
|
||||
|
||||
- name: Upload integration lane evidence
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v7
|
||||
@@ -1169,6 +1179,12 @@ jobs:
|
||||
# arm proof read; verify-split-logs/ is whatever the control steps left behind, which for
|
||||
# twelve entries is a deliberately red re-run under the same name. Uploading only the
|
||||
# second - which is what this step did before the copy above existed - loses the first.
|
||||
# The run log needs a signed-in reader; annotations do not. Name every failed ctest entry,
|
||||
# with the lines of its output that say why, where anyone reading the run can see them.
|
||||
- name: Annotate failed entries
|
||||
if: failure()
|
||||
run: python3 scripts/ci/junit_annotate.py "${RUNNER_TEMP}"
|
||||
|
||||
- name: Upload verify-split lane logs
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v7
|
||||
@@ -1481,7 +1497,7 @@ jobs:
|
||||
working-directory: build-split
|
||||
env:
|
||||
MOBILEGL_ITEST_REQUIRE_GPU: "1"
|
||||
run: ctest --output-on-failure -L unit --no-tests=error -j "$(nproc)"
|
||||
run: ctest --output-on-failure -L unit --no-tests=error -j "$(nproc)" --output-junit "${RUNNER_TEMP}/unit-split.xml"
|
||||
|
||||
# P7 wave 2-F, PH-7 (1). THE TCP SUPERVISOR LANE NEEDS flatc, AND CI HAD NONE.
|
||||
#
|
||||
@@ -1648,6 +1664,12 @@ jobs:
|
||||
CONTROL_TMPDIR: ${{ runner.temp }}
|
||||
run: bash "${GITHUB_WORKSPACE}/scripts/ci/split_negative_controls.sh"
|
||||
|
||||
# The run log needs a signed-in reader; annotations do not. Name every failed ctest entry,
|
||||
# with the lines of its output that say why, where anyone reading the run can see them.
|
||||
- name: Annotate failed entries
|
||||
if: failure()
|
||||
run: python3 scripts/ci/junit_annotate.py "${RUNNER_TEMP}"
|
||||
|
||||
- name: Upload split lane logs
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v7
|
||||
@@ -1737,7 +1759,7 @@ jobs:
|
||||
env:
|
||||
MOBILEGL_ITEST_REQUIRE_GPU: "1"
|
||||
MOBILEGL_IPC_STRICT_ERRORS: "1"
|
||||
run: ctest --output-on-failure -L unit --no-tests=error -j "$(nproc)"
|
||||
run: ctest --output-on-failure -L unit --no-tests=error -j "$(nproc)" --output-junit "${RUNNER_TEMP}/unit-strict.xml"
|
||||
|
||||
# ---- P5e (ra), MG_Remote/CONTRACT-P5E.md §7: ONE STEP, TWO ARMS, AND THE TREE PICKS ----
|
||||
#
|
||||
@@ -2246,6 +2268,12 @@ jobs:
|
||||
slp.require_green(lane, sys.argv[3], names)
|
||||
PY
|
||||
|
||||
# The run log needs a signed-in reader; annotations do not. Name every failed ctest entry,
|
||||
# with the lines of its output that say why, where anyone reading the run can see them.
|
||||
- name: Annotate failed entries
|
||||
if: failure()
|
||||
run: python3 scripts/ci/junit_annotate.py "${RUNNER_TEMP}"
|
||||
|
||||
- name: Upload strict lane logs
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v7
|
||||
@@ -2751,7 +2779,11 @@ jobs:
|
||||
&& [ '${{ matrix.case }}' = 'improved-transparency-minecraft-26.3' ]; then
|
||||
export MOBILEGL_MAGMA_DISABLE_BLENDED_DEPTH_WRITE=1
|
||||
fi
|
||||
ctest -V --no-tests=error -R '^MobileGLTraceReplay\.${{ matrix.case }}\.${{ matrix.backend }}$'
|
||||
ctest -V --no-tests=error -R '^MobileGLTraceReplay\.${{ matrix.case }}\.${{ matrix.backend }}$' --output-junit "${RUNNER_TEMP}/retrace.xml"
|
||||
|
||||
- name: Annotate failed entries
|
||||
if: failure()
|
||||
run: python3 scripts/ci/junit_annotate.py --excerpts 1 "${RUNNER_TEMP}"
|
||||
|
||||
- name: Upload core dumps
|
||||
if: failure()
|
||||
@@ -3506,27 +3538,10 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
# Deliberately independent of build-linux: these are source-level gates, they take
|
||||
# seconds, and a broken build must not hide a drifted interface.
|
||||
env:
|
||||
# THE CURRENT PHASE's base ref, for the two G5 region gates below. It is 37da3c3a - P4a's
|
||||
# base ref, INTEGRATOR-DECISIONS ID-1 - and NOT the workflow's baseline_sha input: that input
|
||||
# is the SYMBOL baseline (087685d1, P1's G1 reading) and it is empty on a push, whereas these
|
||||
# gates ask "did the do-not-touch list move since the phase started".
|
||||
#
|
||||
# IT MOVED FROM P3a's 44c2b5cf TO P4a's 37da3c3a WITH THE PHASE, and that is a deliberate
|
||||
# narrowing rather than a loss: P3a's eleven functions were compared against 44c2b5cf at P3a's
|
||||
# own exit and were byte-identical there, so 37da3c3a carries the same bodies (measured: the
|
||||
# eleven shas at 37da3c3a are the eleven shas at 44c2b5cf, and FlushPendingRangesFrom's is
|
||||
# still the sha pinned in the script at 3e298c9a). What the two gates now both answer is "did
|
||||
# anything on the list move during P4a", which is the question this phase can act on.
|
||||
BASELINE: "37da3c3a"
|
||||
|
||||
steps:
|
||||
- name: Checkout repo
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
# The G5 gate reads Managers.cpp at BASELINE with `git show`, which a depth-1 checkout
|
||||
# does not have. Nothing else in this job needs history.
|
||||
fetch-depth: 0
|
||||
|
||||
# The seven generators all read MG_Pipe/*.def, so regenerating and diffing is what
|
||||
# keeps the two interface tables, the wire records, the verify comparators, the
|
||||
@@ -3655,76 +3670,6 @@ jobs:
|
||||
python3 tools/trace_replay/test_run_tcp_matrix.py
|
||||
python3 tools/trace_replay/test_compare_actuals.py
|
||||
|
||||
# A GATE as of P3a (G5). "pool 与延迟释放原样搬" (ROADMAP.md:19) is meant literally: the
|
||||
# buffer pool, the deferred-release drain and the three persistently mapped rings move
|
||||
# VERBATIM, and ARCHITECTURE.md:515 says why - their retire happens only inside Present, so
|
||||
# a batching or ordering change there starves them, and nothing else in this workflow can
|
||||
# see it. P3a rewrites the rest of Managers.cpp by design, so a file diff says nothing; the
|
||||
# script extracts the ELEVEN named bodies and compares their hashes on their own.
|
||||
#
|
||||
# Eleven and not ten (ID-15): Managers.cpp carries the three-tier flush drain TWICE, once
|
||||
# per preprocessor arm, and a push build compiles only FlushPendingRangesFrom while the
|
||||
# untouched FlushPendingRangesNow lives in the `#else`. Hashing the pull name alone would
|
||||
# protect text no shipping build compiles, so both are hashed - the pull ladder against
|
||||
# BASELINE, the push ladder against a sha pinned in the script at 3dadd4c1 (ID-41), because
|
||||
# that one was born in P3a and is compared against the reviewed body rather than against the
|
||||
# base ref.
|
||||
#
|
||||
# Scoped to the disaggregation branch and to a manual dispatch, deliberately: the question
|
||||
# is "did these eleven move since P3a started", and BASELINE is P3a's base ref. On dev,
|
||||
# where unrelated buffer fixes land on their own schedule, the same comparison would be
|
||||
# asking a question nobody posed - it belongs with the TEMPORARY trigger lines at the top
|
||||
# of this file and retires with them.
|
||||
#
|
||||
# --self-test is the half that keeps it honest, and it is not optional: a comparison that
|
||||
# silently stopped comparing produces exactly the same green as eleven untouched bodies. It
|
||||
# runs eight canned controls - eleven bodies extracted, an untouched copy compared equal, an
|
||||
# edit OUTSIDE them ignored, each of the three perturbation targets (ClearBufferPool and BOTH
|
||||
# flush ladders) reported BY NAME, plus the pin-precedence control and a one-token edit to the
|
||||
# pinned ladder compared against the pin - and fails if any of them does not answer.
|
||||
# Same shape as gen_pipe.py --self-test above.
|
||||
- name: P3a regions unchanged (G5)
|
||||
if: ${{ github.ref == 'refs/heads/feat/disaggregated' || github.event_name == 'workflow_dispatch' }}
|
||||
run: bash scripts/p3a_untouched_regions.sh "${BASELINE}" HEAD
|
||||
|
||||
- name: P3a untouched-region self-test (G5)
|
||||
if: ${{ github.ref == 'refs/heads/feat/disaggregated' || github.event_name == 'workflow_dispatch' }}
|
||||
run: bash scripts/p3a_untouched_regions.sh --self-test
|
||||
|
||||
# A GATE AS OF P4a (G5), and a SECOND script rather than an edit to the one above. P4a extends
|
||||
# the same claim to the rest of ARCHITECTURE.md:318's do-not-touch list - the unpack PBO ring's
|
||||
# staging repack and its two helpers, the attachment permutation, the D24S8 sampling-emulation
|
||||
# core and the format-caveat handler - which is SEVENTEEN regions across THREE files
|
||||
# (BRIEF-P4A.md D-N: P3a's eleven, which P4a must not touch either, plus P4a's six). The
|
||||
# parent's SOURCE_PATH is a single file, so the extension needed a per-region source path and
|
||||
# a region KIND (DepthStencilSamplingReadImpl is a namespace, not a function); everything else
|
||||
# about the extraction is its parent's, verbatim.
|
||||
#
|
||||
# Both scripts run. The parent keeps answering its own question against its own eleven, so a
|
||||
# regression in either half names itself, and neither gate can be silenced by editing the
|
||||
# other's list.
|
||||
#
|
||||
# Same feat/disaggregated-or-dispatch guard as the P3a step, for the same reason: the question
|
||||
# is "did these move since the phase started", and on dev - where unrelated buffer and texture
|
||||
# fixes land on their own schedule - it would be a question nobody posed. It belongs with the
|
||||
# TEMPORARY trigger lines at the top of this file and retires with them.
|
||||
#
|
||||
# --self-test is the half that keeps it honest and is not optional: a comparison that silently
|
||||
# stopped comparing produces exactly the same green as seventeen untouched regions. It runs
|
||||
# three positive controls (seventeen regions extracted, an untouched copy compared equal, an
|
||||
# edit OUTSIDE them invisible in all three files) and NINE negative ones - ClearBufferPool,
|
||||
# FlushPendingRangesNow, RecomputeBackendColorSlots and StageBlocksIntoUnpackRing, each
|
||||
# perturbed at its HEAD and at its TAIL and each required to be named BY NAME, plus a
|
||||
# one-token edit to the pinned FlushPendingRangesFrom body compared against the pin - and
|
||||
# fails if any of them does not answer.
|
||||
- name: P4a regions unchanged (G5)
|
||||
if: ${{ github.ref == 'refs/heads/feat/disaggregated' || github.event_name == 'workflow_dispatch' }}
|
||||
run: bash scripts/p4a_untouched_regions.sh "${BASELINE}" HEAD
|
||||
|
||||
- name: P4a untouched-region self-test (G5)
|
||||
if: ${{ github.ref == 'refs/heads/feat/disaggregated' || github.event_name == 'workflow_dispatch' }}
|
||||
run: bash scripts/p4a_untouched_regions.sh --self-test
|
||||
|
||||
# Warning only for now: the disaggregation documents are still being written, and a
|
||||
# lint that fails a rewrite in progress teaches people to ignore it. It becomes
|
||||
# --strict when the documents settle.
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
name: Arch WSL GPU smoke
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
push:
|
||||
branches:
|
||||
- ci/arch-wsl-gpu-runner
|
||||
paths:
|
||||
- .github/workflows/wsl-gpu-smoke.yml
|
||||
- docs/ci/arch-wsl-gpu-runner.md
|
||||
|
||||
permissions: {}
|
||||
|
||||
concurrency:
|
||||
group: arch-wsl-gpu-smoke
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
gpu-smoke:
|
||||
runs-on: [self-hosted, Linux, X64, arch, wsl, gpu, gles, vulkan]
|
||||
timeout-minutes: 5
|
||||
steps:
|
||||
- name: Report runner identity
|
||||
shell: bash
|
||||
run: |
|
||||
printf 'Runner: %s\n' "$RUNNER_NAME"
|
||||
uname -n
|
||||
uname -a
|
||||
- name: Verify hardware GLES and Vulkan
|
||||
shell: bash
|
||||
run: /usr/local/libexec/mobilegl-runner/gpu-smoke
|
||||
@@ -372,6 +372,7 @@ set(SOURCE_FILES
|
||||
MobileGL/MG_Util/ShaderTranspiler/SpirvPasses/FixIterationRPSubgroupScratchPass.cpp
|
||||
MobileGL/MG_Util/ShaderTranspiler/SpirvPasses/EmulateSubgroupsPass.cpp
|
||||
MobileGL/MG_Util/ShaderTranspiler/SpirvPasses/NormalizeRectCoordinatesPass.cpp
|
||||
MobileGL/MG_Util/ShaderTranspiler/SpirvPasses/DeduplicateImageTypesPass.cpp
|
||||
MobileGL/MG_Util/ShaderTranspiler/SpirvPasses/Lower1DArrayImagesPass.cpp
|
||||
MobileGL/MG_Util/ShaderTranspiler/SpirvPasses/Lower1DSampledImagesPass.cpp
|
||||
MobileGL/MG_Util/ShaderTranspiler/SpirvPasses/BakeImageFormatsPass.cpp
|
||||
|
||||
@@ -238,18 +238,6 @@ namespace MobileGL {
|
||||
#endif
|
||||
return true;
|
||||
}
|
||||
#if defined(__linux__) && !defined(__ANDROID__)
|
||||
// LIBGL_ALWAYS_SOFTWARE is how a process (or whoever launched it) asks the system's GL for a
|
||||
// software renderer. MobileGL is a GPU forwarder, so it steps aside and lets the system's
|
||||
// other implementation give the process what it asked for.
|
||||
{
|
||||
String software;
|
||||
if (MG_ConfigLoader::LookupSetting("LIBGL_ALWAYS_SOFTWARE", software) && !software.empty() &&
|
||||
software != "0" && software != "false") {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
// Not yet: the bring-up would dial the configured server and wait for it. Ask first.
|
||||
return MG_Remote::Client::ConfiguredServerAvailable();
|
||||
|
||||
@@ -9,9 +9,9 @@
|
||||
#pragma once
|
||||
#include <Includes.h>
|
||||
#include "MG_State/GLState/TextureState/TextureEnum.h"
|
||||
#include <MG_Util/Damage/Damage.h>
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
#include <MG_Pipe/MGPipeHandles.h>
|
||||
#include <MG_Util/Damage/Damage.h>
|
||||
#endif
|
||||
|
||||
namespace MobileGL {
|
||||
|
||||
@@ -17767,6 +17767,8 @@ namespace MobileGL::MG_Backend::DirectGLES {
|
||||
MGLOG_E_ONCE("DirectGLES::MakeCurrent failed: native eglMakeCurrent returned error 0x%04x", error);
|
||||
return false;
|
||||
}
|
||||
g_EGLFuncs.eglSwapBuffersWithDamageEXT =
|
||||
MG_Util::BackendLoader::ResolveSwapBuffersWithDamage(g_EGLFuncs);
|
||||
InvalidateEglVerifiedStamp();
|
||||
t_boundNativeContext = tuple.Context;
|
||||
t_boundNativeDraw = session.Draw;
|
||||
@@ -18613,16 +18615,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
|
||||
Bool YuvTarget = false;
|
||||
};
|
||||
|
||||
Bool HasExtensionWord(const char* list, const char* word) {
|
||||
if (list == nullptr) return false;
|
||||
const SizeT n = std::strlen(word);
|
||||
for (const char* at = std::strstr(list, word); at != nullptr; at = std::strstr(at + 1, word)) {
|
||||
const Bool startOk = at == list || at[-1] == ' ';
|
||||
const Bool endOk = at[n] == '\0' || at[n] == ' ';
|
||||
if (startOk && endOk) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
using MG_Util::BackendLoader::HasExtensionWord;
|
||||
|
||||
// None of these is in the loader's tables, and eglGetProcAddress hands back live-looking
|
||||
// stubs for entry points a driver lacks, so the extension strings decide first. Resolved
|
||||
|
||||
@@ -2898,16 +2898,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
|
||||
kT0MapReadBit | kT0MapWriteBit | kMapPersistentBit | kMapCoherentBit | kDynamicStorageBit;
|
||||
constexpr GLbitfield kT0MapFlags = kT0MapReadBit | kT0MapWriteBit | kMapPersistentBit | kMapCoherentBit;
|
||||
|
||||
Bool HasExtensionWord(const char* list, const char* word) {
|
||||
if (list == nullptr) return false;
|
||||
const SizeT n = std::strlen(word);
|
||||
for (const char* at = std::strstr(list, word); at != nullptr; at = std::strstr(at + 1, word)) {
|
||||
const Bool startOk = at == list || at[-1] == ' ';
|
||||
const Bool endOk = at[n] == '\0' || at[n] == ' ';
|
||||
if (startOk && endOk) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
using MG_Util::BackendLoader::HasExtensionWord;
|
||||
|
||||
Bool ResolveT0EntryPoints(String& why) {
|
||||
if (g_t0GetNativeClientBuffer != nullptr && g_t0BufferStorageExternal != nullptr) return true;
|
||||
@@ -3903,8 +3894,13 @@ namespace MobileGL::MG_Backend::DirectGLES {
|
||||
MG_Pipe::MGPipeSetResourceOps(&g_glesResourceOps);
|
||||
#endif
|
||||
// Frontend writes issued while ops were unregistered advanced change
|
||||
// serials with no per-op bump; re-open every draw-clean memo.
|
||||
BumpBufferMutationEpoch();
|
||||
// serials with no per-op bump; re-open every draw-clean memo. Advanced directly,
|
||||
// past BumpBufferMutationEpoch's apply-thread pin: a registration mutates no buffer
|
||||
// and only makes every memo probe again, and with several sessions in one process
|
||||
// a new session's backend registers on its own thread while another session's
|
||||
// apply thread is already running - which the pin would otherwise read as a
|
||||
// client-thread producer and, under the strict lane, abort the server for.
|
||||
g_bufferMutationEpoch.fetch_add(1, std::memory_order_release);
|
||||
}
|
||||
|
||||
void UnregisterBufferBackendOps() {
|
||||
|
||||
@@ -66,7 +66,11 @@ namespace MobileGL::MG_Backend::DirectVulkan {
|
||||
FreeRetiredCommandBuffers(frame);
|
||||
}
|
||||
vkFreeCommandBuffers(device, commandPool, frameCount * 2, commandBuffers.data());
|
||||
if (!m_spareCommandBuffers.empty())
|
||||
vkFreeCommandBuffers(device, commandPool, static_cast<Uint32>(m_spareCommandBuffers.size()),
|
||||
m_spareCommandBuffers.data());
|
||||
}
|
||||
m_spareCommandBuffers.clear();
|
||||
m_frames.clear();
|
||||
currentFrameIndex = 0;
|
||||
m_device = VK_NULL_HANDLE;
|
||||
@@ -362,21 +366,16 @@ namespace MobileGL::MG_Backend::DirectVulkan {
|
||||
MOBILEGL_ASSERT(!frame.isPreCommandRecording,
|
||||
"RetireCurrentCommandBuffer called while the pre-pass stream is still recording");
|
||||
|
||||
VkCommandBufferAllocateInfo allocInfo{};
|
||||
allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
|
||||
allocInfo.commandPool = m_commandPool;
|
||||
allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
|
||||
allocInfo.commandBufferCount = 1;
|
||||
VkCommandBuffer replacement = VK_NULL_HANDLE;
|
||||
VkResult result = vkAllocateCommandBuffers(m_device, &allocInfo, &replacement);
|
||||
VkResult result = TakeCommandBuffer(replacement);
|
||||
if (result != VK_SUCCESS) {
|
||||
return result;
|
||||
}
|
||||
if (retirePreCommandBuffer) {
|
||||
VkCommandBuffer preReplacement = VK_NULL_HANDLE;
|
||||
result = vkAllocateCommandBuffers(m_device, &allocInfo, &preReplacement);
|
||||
result = TakeCommandBuffer(preReplacement);
|
||||
if (result != VK_SUCCESS) {
|
||||
vkFreeCommandBuffers(m_device, m_commandPool, 1, &replacement);
|
||||
RecycleCommandBuffer(replacement);
|
||||
return result;
|
||||
}
|
||||
frame.retiredCommandBuffers.push_back({frame.preCommandBuffer, frame.lastSubmitIndex});
|
||||
@@ -411,8 +410,7 @@ namespace MobileGL::MG_Backend::DirectVulkan {
|
||||
SizeT completedCount = 0;
|
||||
while (completedCount < frame.retiredCommandBuffers.size() &&
|
||||
frame.retiredCommandBuffers[completedCount].submitIndex <= completedSubmitIndex) {
|
||||
vkFreeCommandBuffers(m_device, m_commandPool, 1,
|
||||
&frame.retiredCommandBuffers[completedCount].commandBuffer);
|
||||
RecycleCommandBuffer(frame.retiredCommandBuffers[completedCount].commandBuffer);
|
||||
++completedCount;
|
||||
}
|
||||
if (completedCount > 0) {
|
||||
@@ -422,6 +420,31 @@ namespace MobileGL::MG_Backend::DirectVulkan {
|
||||
}
|
||||
}
|
||||
|
||||
VkResult FrameContext::TakeCommandBuffer(VkCommandBuffer& out) {
|
||||
if (!m_spareCommandBuffers.empty()) {
|
||||
out = m_spareCommandBuffers.back();
|
||||
m_spareCommandBuffers.pop_back();
|
||||
return VK_SUCCESS;
|
||||
}
|
||||
VkCommandBufferAllocateInfo allocInfo{};
|
||||
allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
|
||||
allocInfo.commandPool = m_commandPool;
|
||||
allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
|
||||
allocInfo.commandBufferCount = 1;
|
||||
return vkAllocateCommandBuffers(m_device, &allocInfo, &out);
|
||||
}
|
||||
|
||||
void FrameContext::RecycleCommandBuffer(VkCommandBuffer commandBuffer) {
|
||||
// A handful covers the buffers in flight between two completions; beyond that, free.
|
||||
constexpr SizeT kSpareCommandBuffers = 8;
|
||||
if (commandBuffer == VK_NULL_HANDLE) return;
|
||||
if (m_spareCommandBuffers.size() < kSpareCommandBuffers) {
|
||||
m_spareCommandBuffers.push_back(commandBuffer);
|
||||
return;
|
||||
}
|
||||
vkFreeCommandBuffers(m_device, m_commandPool, 1, &commandBuffer);
|
||||
}
|
||||
|
||||
void FrameContext::FreeAllRetiredCommandBuffers() {
|
||||
for (auto& frame : m_frames) {
|
||||
FreeRetiredCommandBuffers(frame);
|
||||
|
||||
@@ -150,5 +150,10 @@ namespace MobileGL::MG_Backend::DirectVulkan {
|
||||
// Stored at Initialize for retired-command-buffer management.
|
||||
VkDevice m_device = VK_NULL_HANDLE;
|
||||
VkCommandPool m_commandPool = VK_NULL_HANDLE;
|
||||
// Completed command buffers kept for the next retirement instead of being freed and
|
||||
// reallocated: the pool resets a buffer implicitly at its next vkBeginCommandBuffer.
|
||||
Vector<VkCommandBuffer> m_spareCommandBuffers;
|
||||
VkResult TakeCommandBuffer(VkCommandBuffer& out);
|
||||
void RecycleCommandBuffer(VkCommandBuffer commandBuffer);
|
||||
};
|
||||
} // namespace MobileGL::MG_Backend::DirectVulkan
|
||||
@@ -0,0 +1,27 @@
|
||||
// MobileGL - MobileGL/MG_Backend/DirectVulkan/Renderer/RenderPassGuard.h
|
||||
// Copyright (c) 2025-2026 MobileGL-Dev
|
||||
// Licensed under the GNU Lesser General Public License v3.0:
|
||||
// https://www.gnu.org/licenses/gpl-3.0.txt
|
||||
// https://www.gnu.org/licenses/lgpl-3.0.txt
|
||||
// SPDX-License-Identifier: LGPL-3.0-only
|
||||
// End of Source File Header
|
||||
|
||||
#pragma once
|
||||
#include "../VkIncludes.h"
|
||||
#include <Includes.h>
|
||||
|
||||
namespace MobileGL::MG_Backend::DirectVulkan {
|
||||
// Ends the render pass that is active on `commandBuffer`, if there is one. Called right before
|
||||
// recording a command a render pass may not contain (a barrier, a copy, a blit, a clear of an
|
||||
// image) into a command buffer that may hold an open pass: the wire draw path keeps its pass
|
||||
// open across consecutive draws to the same attachments, so the resource work that falls
|
||||
// between two draws must close it first. A pass on another command buffer is left alone.
|
||||
void EndActiveRenderPassOn(VkCommandBuffer commandBuffer);
|
||||
|
||||
// A counter that moves whenever images may have been written since it was last read: a render
|
||||
// pass ended (its attachments), resource work recorded outside a pass (copies, clears, blits,
|
||||
// dispatches all close the pass first), or a draw with storage images. A sampled image needs
|
||||
// the memory barrier that makes earlier writes visible only when this moved since the last one.
|
||||
Uint64 WireImageWriteEpoch();
|
||||
void BumpWireImageWriteEpoch();
|
||||
} // namespace MobileGL::MG_Backend::DirectVulkan
|
||||
@@ -6,6 +6,7 @@
|
||||
// SPDX-License-Identifier: LGPL-3.0-only
|
||||
// End of Source File Header
|
||||
|
||||
#include "RenderPassGuard.h"
|
||||
#include "UniformManager.h"
|
||||
|
||||
#include "MG_Backend/DirectVulkan/DirectVulkanResourceState.h"
|
||||
@@ -251,11 +252,18 @@ namespace MobileGL::MG_Backend::DirectVulkan {
|
||||
WireDescriptorFatal("image-descriptor-transition");
|
||||
// A second descriptor/draw can keep GENERAL after a shader write. A layout
|
||||
// equality fast return is not a memory dependency for that prior write.
|
||||
VkMemoryBarrier memory{VK_STRUCTURE_TYPE_MEMORY_BARRIER};
|
||||
memory.srcAccessMask = VK_ACCESS_MEMORY_WRITE_BIT;
|
||||
memory.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT;
|
||||
vkCmdPipelineBarrier(commandBuffer, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
|
||||
0, 1, &memory, 0, nullptr, 0, nullptr);
|
||||
// Only when something may have written an image since the last such barrier
|
||||
// (WireImageWriteEpoch): with nothing written in between, consecutive draws keep their
|
||||
// render pass open instead of closing it for a barrier that orders nothing.
|
||||
if (WireImageWriteEpoch() != m_wireImageBarrierEpoch) {
|
||||
VkMemoryBarrier memory{VK_STRUCTURE_TYPE_MEMORY_BARRIER};
|
||||
memory.srcAccessMask = VK_ACCESS_MEMORY_WRITE_BIT;
|
||||
memory.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT;
|
||||
EndActiveRenderPassOn(commandBuffer);
|
||||
vkCmdPipelineBarrier(commandBuffer, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
|
||||
0, 1, &memory, 0, nullptr, 0, nullptr);
|
||||
m_wireImageBarrierEpoch = WireImageWriteEpoch();
|
||||
}
|
||||
VkImageViewCreateInfo info{VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO};
|
||||
info.image = resource->image;
|
||||
info.viewType = type;
|
||||
|
||||
@@ -660,5 +660,7 @@ namespace MobileGL::MG_Backend::DirectVulkan {
|
||||
m_samplerResolveMemoHighWater = binding + 1;
|
||||
}
|
||||
}
|
||||
// WireImageWriteEpoch() when ResolveWireImageDescriptor last made image writes visible.
|
||||
mutable Uint64 m_wireImageBarrierEpoch = 0;
|
||||
};
|
||||
} // namespace MobileGL::MG_Backend::DirectVulkan
|
||||
@@ -6,6 +6,7 @@
|
||||
// SPDX-License-Identifier: LGPL-3.0-only
|
||||
// End of Source File Header
|
||||
|
||||
#include "RenderPassGuard.h"
|
||||
#include "VkBufferManager.h"
|
||||
#include "../DirectVulkan.h"
|
||||
#include "VulkanRenderer.h"
|
||||
@@ -337,6 +338,7 @@ namespace MobileGL::MG_Backend::DirectVulkan {
|
||||
VkMemoryBarrier barrier{VK_STRUCTURE_TYPE_MEMORY_BARRIER};
|
||||
barrier.srcAccessMask = VK_ACCESS_MEMORY_WRITE_BIT;
|
||||
barrier.dstAccessMask = VK_ACCESS_HOST_READ_BIT | VK_ACCESS_HOST_WRITE_BIT;
|
||||
EndActiveRenderPassOn(commands);
|
||||
vkCmdPipelineBarrier(commands, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_HOST_BIT,
|
||||
0, 1, &barrier, 0, nullptr, 0, nullptr);
|
||||
// P8-D: counted here, past the idle early-out, so `whw` is waits TAKEN, not calls.
|
||||
@@ -531,13 +533,16 @@ namespace MobileGL::MG_Backend::DirectVulkan {
|
||||
VkMemoryBarrier before{VK_STRUCTURE_TYPE_MEMORY_BARRIER};
|
||||
before.srcAccessMask = VK_ACCESS_MEMORY_WRITE_BIT | VK_ACCESS_HOST_WRITE_BIT;
|
||||
before.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT;
|
||||
EndActiveRenderPassOn(commands);
|
||||
vkCmdPipelineBarrier(commands, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT | VK_PIPELINE_STAGE_HOST_BIT,
|
||||
VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 1, &before, 0, nullptr, 0, nullptr);
|
||||
const VkBufferCopy copy{offset, dst.offset, size};
|
||||
EndActiveRenderPassOn(commands);
|
||||
vkCmdCopyBuffer(commands, resource->buffer.GetHandle(), dst.buffer, 1, ©);
|
||||
VkMemoryBarrier after{VK_STRUCTURE_TYPE_MEMORY_BARRIER};
|
||||
after.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
|
||||
after.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT;
|
||||
EndActiveRenderPassOn(commands);
|
||||
vkCmdPipelineBarrier(commands, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
|
||||
0, 1, &after, 0, nullptr, 0, nullptr);
|
||||
resource->lastUseSerial = m_frameSerial;
|
||||
@@ -575,22 +580,27 @@ namespace MobileGL::MG_Backend::DirectVulkan {
|
||||
VkMemoryBarrier before{VK_STRUCTURE_TYPE_MEMORY_BARRIER};
|
||||
before.srcAccessMask = VK_ACCESS_MEMORY_WRITE_BIT | VK_ACCESS_HOST_WRITE_BIT;
|
||||
before.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT;
|
||||
EndActiveRenderPassOn(commands);
|
||||
vkCmdPipelineBarrier(commands, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT | VK_PIPELINE_STAGE_HOST_BIT,
|
||||
VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 1, &before, 0, nullptr, 0, nullptr);
|
||||
const VkBufferCopy widen{alignedOffset, staging.offset, stagedSize};
|
||||
EndActiveRenderPassOn(commands);
|
||||
vkCmdCopyBuffer(commands, resource->buffer.GetHandle(), staging.buffer, 1, &widen);
|
||||
// The shift reads what the widening copy just wrote, so it needs its own edge even
|
||||
// though both halves are transfers on one command buffer.
|
||||
VkMemoryBarrier staged{VK_STRUCTURE_TYPE_MEMORY_BARRIER};
|
||||
staged.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
|
||||
staged.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
|
||||
EndActiveRenderPassOn(commands);
|
||||
vkCmdPipelineBarrier(commands, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT,
|
||||
0, 1, &staged, 0, nullptr, 0, nullptr);
|
||||
const VkBufferCopy shift{staging.offset + headPad, dst.offset + dstSkip, size};
|
||||
EndActiveRenderPassOn(commands);
|
||||
vkCmdCopyBuffer(commands, staging.buffer, dst.buffer, 1, &shift);
|
||||
VkMemoryBarrier after{VK_STRUCTURE_TYPE_MEMORY_BARRIER};
|
||||
after.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
|
||||
after.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT;
|
||||
EndActiveRenderPassOn(commands);
|
||||
vkCmdPipelineBarrier(commands, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
|
||||
0, 1, &after, 0, nullptr, 0, nullptr);
|
||||
resource->lastUseSerial = m_frameSerial;
|
||||
@@ -908,14 +918,18 @@ namespace MobileGL::MG_Backend::DirectVulkan {
|
||||
VkMemoryBarrier hostWrites{VK_STRUCTURE_TYPE_MEMORY_BARRIER};
|
||||
hostWrites.srcAccessMask = VK_ACCESS_HOST_WRITE_BIT;
|
||||
hostWrites.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT;
|
||||
EndActiveRenderPassOn(commands);
|
||||
vkCmdPipelineBarrier(commands, VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 1,
|
||||
&hostWrites, 0, nullptr, 0, nullptr);
|
||||
VkBufferCopy region{0, 0, kWords * 4};
|
||||
EndActiveRenderPassOn(commands);
|
||||
vkCmdCopyBuffer(commands, imported.buffer, staging.buffer, 1, ®ion);
|
||||
EndActiveRenderPassOn(commands);
|
||||
vkCmdFillBuffer(commands, imported.buffer, kFillAt, kWords * 4, kFillWord);
|
||||
VkMemoryBarrier toHost{VK_STRUCTURE_TYPE_MEMORY_BARRIER};
|
||||
toHost.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
|
||||
toHost.dstAccessMask = VK_ACCESS_HOST_READ_BIT;
|
||||
EndActiveRenderPassOn(commands);
|
||||
vkCmdPipelineBarrier(commands, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_HOST_BIT, 0, 1, &toHost,
|
||||
0, nullptr, 0, nullptr);
|
||||
vkEndCommandBuffer(commands);
|
||||
@@ -965,11 +979,15 @@ namespace MobileGL::MG_Backend::DirectVulkan {
|
||||
verdict = "steady: the second submission could not be recorded";
|
||||
break;
|
||||
}
|
||||
EndActiveRenderPassOn(commands);
|
||||
vkCmdPipelineBarrier(commands, VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 1,
|
||||
&hostWrites, 0, nullptr, 0, nullptr);
|
||||
VkBufferCopy steadyRegion{kSteadyAt, 0, kWords * 4};
|
||||
EndActiveRenderPassOn(commands);
|
||||
vkCmdCopyBuffer(commands, imported.buffer, staging.buffer, 1, &steadyRegion);
|
||||
EndActiveRenderPassOn(commands);
|
||||
vkCmdFillBuffer(commands, imported.buffer, kFillAt, kWords * 4, kSteadyFillWord);
|
||||
EndActiveRenderPassOn(commands);
|
||||
vkCmdPipelineBarrier(commands, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_HOST_BIT, 0, 1, &toHost,
|
||||
0, nullptr, 0, nullptr);
|
||||
vkEndCommandBuffer(commands);
|
||||
@@ -1488,6 +1506,7 @@ namespace MobileGL::MG_Backend::DirectVulkan {
|
||||
VkMemoryBarrier beforeBarrier{VK_STRUCTURE_TYPE_MEMORY_BARRIER};
|
||||
beforeBarrier.srcAccessMask = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT;
|
||||
beforeBarrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
|
||||
EndActiveRenderPassOn(commandBuffer);
|
||||
vkCmdPipelineBarrier(commandBuffer, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 1,
|
||||
&beforeBarrier, 0, nullptr, 0, nullptr);
|
||||
|
||||
@@ -1495,11 +1514,13 @@ namespace MobileGL::MG_Backend::DirectVulkan {
|
||||
region.srcOffset = staging.offset;
|
||||
region.dstOffset = static_cast<VkDeviceSize>(offset);
|
||||
region.size = static_cast<VkDeviceSize>(size);
|
||||
EndActiveRenderPassOn(commandBuffer);
|
||||
vkCmdCopyBuffer(commandBuffer, staging.buffer, resource.buffer.GetHandle(), 1, ®ion);
|
||||
|
||||
VkMemoryBarrier afterBarrier{VK_STRUCTURE_TYPE_MEMORY_BARRIER};
|
||||
afterBarrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
|
||||
afterBarrier.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT;
|
||||
EndActiveRenderPassOn(commandBuffer);
|
||||
vkCmdPipelineBarrier(commandBuffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, 1,
|
||||
&afterBarrier, 0, nullptr, 0, nullptr);
|
||||
|
||||
@@ -1534,6 +1555,7 @@ namespace MobileGL::MG_Backend::DirectVulkan {
|
||||
VkMemoryBarrier beforeBarrier{VK_STRUCTURE_TYPE_MEMORY_BARRIER};
|
||||
beforeBarrier.srcAccessMask = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT;
|
||||
beforeBarrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
|
||||
EndActiveRenderPassOn(commandBuffer);
|
||||
vkCmdPipelineBarrier(commandBuffer, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 1,
|
||||
&beforeBarrier, 0, nullptr, 0, nullptr);
|
||||
|
||||
@@ -1541,11 +1563,13 @@ namespace MobileGL::MG_Backend::DirectVulkan {
|
||||
region.srcOffset = staging.offset;
|
||||
region.dstOffset = static_cast<VkDeviceSize>(offset);
|
||||
region.size = static_cast<VkDeviceSize>(size);
|
||||
EndActiveRenderPassOn(commandBuffer);
|
||||
vkCmdCopyBuffer(commandBuffer, staging.buffer, resource.buffer.GetHandle(), 1, ®ion);
|
||||
|
||||
VkMemoryBarrier afterBarrier{VK_STRUCTURE_TYPE_MEMORY_BARRIER};
|
||||
afterBarrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
|
||||
afterBarrier.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT;
|
||||
EndActiveRenderPassOn(commandBuffer);
|
||||
vkCmdPipelineBarrier(commandBuffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, 1,
|
||||
&afterBarrier, 0, nullptr, 0, nullptr);
|
||||
|
||||
|
||||
@@ -7,6 +7,8 @@
|
||||
// End of Source File Header
|
||||
|
||||
#include "VkRenderPassManager.h"
|
||||
#include "RenderPassGuard.h"
|
||||
#include <atomic>
|
||||
|
||||
#include "MG_Impl/GLImpl/Framebuffer/GL_Framebuffer.h"
|
||||
#include "MG_State/GLState/TextureState/TextureObject2D.h"
|
||||
@@ -1666,6 +1668,7 @@ namespace MobileGL::MG_Backend::DirectVulkan {
|
||||
s_clearManager.Get()->PopPendingClear(pending.key);
|
||||
}
|
||||
}
|
||||
s_activeRenderPass.Get().commandBuffer = commandBuffer;
|
||||
s_activeRenderPass.Get().hash = renderPassEntry.hash;
|
||||
s_activeRenderPass.Get().compatibilityHash = renderPassEntry.compatibilityHash;
|
||||
s_activeRenderPass.Get().trackedAttachmentLayouts = renderPassEntry.trackedAttachmentLayouts;
|
||||
@@ -1676,15 +1679,24 @@ namespace MobileGL::MG_Backend::DirectVulkan {
|
||||
}
|
||||
|
||||
Bool VkRenderPassManager::EndRenderPass(VkCommandBuffer commandBuffer) {
|
||||
BumpWireImageWriteEpoch();
|
||||
auto* activeRenderPass = GetActiveRenderPass();
|
||||
Vector<TrackedAttachmentLayoutInfo> trackedAttachmentLayouts;
|
||||
if (activeRenderPass != nullptr) {
|
||||
trackedAttachmentLayouts = Move(activeRenderPass->trackedAttachmentLayouts);
|
||||
}
|
||||
vkCmdEndRenderPass(commandBuffer);
|
||||
// Layout reconciliation below may record barriers, whose guard closes an active
|
||||
// pass. Detach the ended pass first so that guard cannot recursively end it again.
|
||||
s_activeRenderPass.Get() = {};
|
||||
s_hasActiveRenderPass.Get() = false;
|
||||
// The fast-path memo reuses the ACTIVE render pass; once the pass ends it must not carry
|
||||
// over (the next span may be a different FBO resolved before its render pass is begun).
|
||||
if (s_renderPassManager.Get() != nullptr) {
|
||||
s_renderPassManager.Get()->m_rpFastValid = false;
|
||||
}
|
||||
if (activeRenderPass != nullptr && !activeRenderPass->trackedAttachmentLayouts.empty()) {
|
||||
for (const auto& trackedAttachment : activeRenderPass->trackedAttachmentLayouts) {
|
||||
if (!trackedAttachmentLayouts.empty()) {
|
||||
for (const auto& trackedAttachment : trackedAttachmentLayouts) {
|
||||
switch (trackedAttachment.target) {
|
||||
case TrackedAttachmentTarget::Texture:
|
||||
MOBILEGL_ASSERT(s_textureManager.Get() != nullptr, "EndRenderPass: texture manager is null");
|
||||
@@ -1726,12 +1738,23 @@ namespace MobileGL::MG_Backend::DirectVulkan {
|
||||
}
|
||||
}
|
||||
}
|
||||
s_activeRenderPass.Get() = {};
|
||||
s_hasActiveRenderPass.Get() = false;
|
||||
return true;
|
||||
}
|
||||
|
||||
ActiveRenderPassInfo* VkRenderPassManager::GetActiveRenderPass() {
|
||||
return s_hasActiveRenderPass.Get() ? &s_activeRenderPass.Get() : nullptr;
|
||||
}
|
||||
namespace {
|
||||
std::atomic<Uint64> g_wireImageWriteEpoch{1};
|
||||
}
|
||||
Uint64 WireImageWriteEpoch() { return g_wireImageWriteEpoch.load(std::memory_order_relaxed); }
|
||||
void BumpWireImageWriteEpoch() { g_wireImageWriteEpoch.fetch_add(1, std::memory_order_relaxed); }
|
||||
|
||||
void EndActiveRenderPassOn(VkCommandBuffer commandBuffer) {
|
||||
BumpWireImageWriteEpoch();
|
||||
const auto* active = VkRenderPassManager::GetActiveRenderPass();
|
||||
if (active != nullptr && active->commandBuffer == commandBuffer && commandBuffer != VK_NULL_HANDLE)
|
||||
VkRenderPassManager::EndRenderPass(commandBuffer);
|
||||
}
|
||||
|
||||
} // namespace MobileGL::MG_Backend::DirectVulkan
|
||||
@@ -185,6 +185,7 @@ namespace MobileGL::MG_Backend::DirectVulkan {
|
||||
struct ActiveRenderPassInfo {
|
||||
Uint64 hash = 0;
|
||||
Uint64 compatibilityHash = 0;
|
||||
VkCommandBuffer commandBuffer = VK_NULL_HANDLE;
|
||||
Vector<TrackedAttachmentLayoutInfo> trackedAttachmentLayouts;
|
||||
IntVec2 extent = {0, 0};
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
// SPDX-License-Identifier: LGPL-3.0-only
|
||||
// End of Source File Header
|
||||
|
||||
#include "RenderPassGuard.h"
|
||||
#include "VkTextureManager.h"
|
||||
|
||||
#include "ProgramFactory.h"
|
||||
@@ -55,6 +56,22 @@ namespace MobileGL::MG_Backend::DirectVulkan {
|
||||
};
|
||||
static SessionLocal<SampledReadStages> s_sampledReadStagesSlot;
|
||||
|
||||
static VkImageUsageFlags ResolveTextureUsage(VkImageAspectFlags aspect,
|
||||
VkFormatFeatureFlags formatFeatures,
|
||||
Bool supportsStorageImage) {
|
||||
VkImageUsageFlags usage = VK_IMAGE_USAGE_SAMPLED_BIT;
|
||||
if (supportsStorageImage) usage |= VK_IMAGE_USAGE_STORAGE_BIT;
|
||||
// A color aspect does not imply renderability (for example, RGB9_E5).
|
||||
if ((aspect & VK_IMAGE_ASPECT_COLOR_BIT) &&
|
||||
(formatFeatures & VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT)) {
|
||||
usage |= VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
|
||||
}
|
||||
if (aspect & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT)) {
|
||||
usage |= VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT;
|
||||
}
|
||||
return usage;
|
||||
}
|
||||
|
||||
static Uint32 ComputeFullMipLevelCount(const IntVec3& baseTexelSize) {
|
||||
Int maxDimension = std::max<Int>(baseTexelSize.x(),
|
||||
std::max<Int>(baseTexelSize.y(), std::max<Int>(baseTexelSize.z(), 1)));
|
||||
@@ -376,6 +393,7 @@ namespace MobileGL::MG_Backend::DirectVulkan {
|
||||
copyRegions.push_back(copy);
|
||||
}
|
||||
|
||||
EndActiveRenderPassOn(commandBuffer);
|
||||
vkCmdCopyImage(commandBuffer,
|
||||
oldResource.image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
|
||||
newResource.image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
|
||||
@@ -1658,6 +1676,7 @@ namespace MobileGL::MG_Backend::DirectVulkan {
|
||||
std::max(source->depth >> level, 1u)};
|
||||
copyRegions.push_back(copy);
|
||||
}
|
||||
EndActiveRenderPassOn(commandBuffer);
|
||||
vkCmdCopyImage(commandBuffer, source->image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, snapshot.image,
|
||||
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, static_cast<Uint32>(copyRegions.size()), copyRegions.data());
|
||||
|
||||
@@ -1772,6 +1791,7 @@ namespace MobileGL::MG_Backend::DirectVulkan {
|
||||
// slices" but will read as "depth slice 0" once VK_KHR_maintenance9 is enabled. The
|
||||
// validation layer warns about that literal 1 by name.
|
||||
barrier.subresourceRange.layerCount = VK_REMAINING_ARRAY_LAYERS;
|
||||
EndActiveRenderPassOn(commandBuffer);
|
||||
vkCmdPipelineBarrier(commandBuffer, srcStageMask, dstStageMask, 0, 0, nullptr, 0, nullptr, 1, &barrier);
|
||||
|
||||
trackedLayout = newLayout;
|
||||
@@ -2252,13 +2272,7 @@ namespace MobileGL::MG_Backend::DirectVulkan {
|
||||
}
|
||||
|
||||
VkImageUsageFlags desiredUsage =
|
||||
VK_IMAGE_USAGE_SAMPLED_BIT | (supportsStorageImage ? VK_IMAGE_USAGE_STORAGE_BIT : 0) |
|
||||
((aspect & VK_IMAGE_ASPECT_COLOR_BIT) &&
|
||||
(formatProperties.optimalTilingFeatures & VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT)
|
||||
? VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT : 0) |
|
||||
(((aspect & VK_IMAGE_ASPECT_DEPTH_BIT) || (aspect & VK_IMAGE_ASPECT_STENCIL_BIT))
|
||||
? VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT
|
||||
: 0);
|
||||
ResolveTextureUsage(aspect, formatProperties.optimalTilingFeatures, supportsStorageImage);
|
||||
// Multisample attachments are also transfer sources for vkCmdResolveImage.
|
||||
desiredUsage |= VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT;
|
||||
|
||||
@@ -2734,9 +2748,11 @@ namespace MobileGL::MG_Backend::DirectVulkan {
|
||||
stencilCopy.imageSubresource.aspectMask = VK_IMAGE_ASPECT_STENCIL_BIT;
|
||||
stencilCopy.bufferOffset = stagingBase + item.offset + static_cast<VkDeviceSize>(texelCount) * 4;
|
||||
const VkBufferImageCopy copies[2] = {depthCopy, stencilCopy};
|
||||
EndActiveRenderPassOn(commandBuffer);
|
||||
vkCmdCopyBufferToImage(commandBuffer, stagingBuffer, resource.image,
|
||||
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 2, copies);
|
||||
} else {
|
||||
EndActiveRenderPassOn(commandBuffer);
|
||||
vkCmdCopyBufferToImage(commandBuffer, stagingBuffer, resource.image,
|
||||
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, ©);
|
||||
}
|
||||
@@ -3211,6 +3227,7 @@ namespace MobileGL::MG_Backend::DirectVulkan {
|
||||
if ((aspect & copyAspect) == 0) continue;
|
||||
copy.srcSubresource.aspectMask = copyAspect;
|
||||
copy.dstSubresource.aspectMask = copyAspect;
|
||||
EndActiveRenderPassOn(commandBuffer);
|
||||
vkCmdCopyImage(commandBuffer, old.image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, grown.image,
|
||||
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, ©);
|
||||
}
|
||||
@@ -3506,12 +3523,7 @@ namespace MobileGL::MG_Backend::DirectVulkan {
|
||||
}
|
||||
|
||||
VkImageUsageFlags desiredUsage =
|
||||
VK_IMAGE_USAGE_SAMPLED_BIT |
|
||||
(supportsStorageImage ? VK_IMAGE_USAGE_STORAGE_BIT : 0) |
|
||||
((aspect & VK_IMAGE_ASPECT_COLOR_BIT) ? VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT : 0) |
|
||||
(((aspect & VK_IMAGE_ASPECT_DEPTH_BIT) || (aspect & VK_IMAGE_ASPECT_STENCIL_BIT)) ?
|
||||
VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT :
|
||||
0);
|
||||
ResolveTextureUsage(aspect, formatProperties.optimalTilingFeatures, supportsStorageImage);
|
||||
if (!isMultisampleTexture) {
|
||||
desiredUsage |= VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT;
|
||||
}
|
||||
@@ -4770,6 +4782,7 @@ namespace MobileGL::MG_Backend::DirectVulkan {
|
||||
rectCopies[rectCopyCount++] = rectCopy;
|
||||
runningOffset += static_cast<VkDeviceSize>(rect.TexelCount() * item.texelBytes);
|
||||
}
|
||||
EndActiveRenderPassOn(commandBuffer);
|
||||
vkCmdCopyBufferToImage(commandBuffer, stagingBuffer, outResource.image,
|
||||
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, rectCopyCount, rectCopies.data());
|
||||
continue;
|
||||
@@ -4811,10 +4824,12 @@ namespace MobileGL::MG_Backend::DirectVulkan {
|
||||
stencilCopy.imageSubresource.aspectMask = VK_IMAGE_ASPECT_STENCIL_BIT;
|
||||
stencilCopy.bufferOffset = stagingBase + item.offset + static_cast<VkDeviceSize>(texelCount) * 4;
|
||||
const VkBufferImageCopy copies[2] = {depthCopy, stencilCopy};
|
||||
EndActiveRenderPassOn(commandBuffer);
|
||||
vkCmdCopyBufferToImage(commandBuffer, stagingBuffer, outResource.image,
|
||||
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 2, copies);
|
||||
continue;
|
||||
}
|
||||
EndActiveRenderPassOn(commandBuffer);
|
||||
vkCmdCopyBufferToImage(commandBuffer, stagingBuffer, outResource.image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
|
||||
1, ©);
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
// SPDX-License-Identifier: LGPL-3.0-only
|
||||
// End of Source File Header
|
||||
|
||||
#include "RenderPassGuard.h"
|
||||
#include "VulkanRenderer.h"
|
||||
#include "SubmitFencePrefix.h"
|
||||
#include "MG_Util/X11/DisplayGuard.h"
|
||||
@@ -5200,6 +5201,7 @@ void main() {
|
||||
static_cast<Uint32>(dstTexelSize.x()), static_cast<Uint32>(dstTexelSize.y())
|
||||
};
|
||||
|
||||
EndActiveRenderPassOn(frame.commandBuffer);
|
||||
vkCmdBeginRenderPass(frame.commandBuffer, &renderPassBeginInfo, VK_SUBPASS_CONTENTS_INLINE);
|
||||
|
||||
VkViewport viewport{};
|
||||
@@ -7829,6 +7831,7 @@ void main() {
|
||||
}
|
||||
|
||||
MGLOG_D("DirectVulkan: glDispatchCompute(%u, %u, %u)", numGroupsX, numGroupsY, numGroupsZ);
|
||||
EndActiveRenderPassOn(frame.commandBuffer);
|
||||
vkCmdDispatch(frame.commandBuffer, numGroupsX, numGroupsY, numGroupsZ);
|
||||
}
|
||||
|
||||
@@ -7906,6 +7909,7 @@ void main() {
|
||||
}
|
||||
|
||||
MGLOG_D("DirectVulkan: glDispatchComputeIndirect(offset=%zu)", static_cast<SizeT>(indirect));
|
||||
EndActiveRenderPassOn(frame.commandBuffer);
|
||||
vkCmdDispatchIndirect(frame.commandBuffer, slice.buffer, slice.offset + static_cast<VkDeviceSize>(indirect));
|
||||
}
|
||||
|
||||
@@ -8750,6 +8754,7 @@ void main() {
|
||||
beginInfo.clearValueCount = 1;
|
||||
beginInfo.pClearValues = &clearValue;
|
||||
// The load op is the whole operation: begin and end with nothing in between.
|
||||
EndActiveRenderPassOn(commandBuffer);
|
||||
vkCmdBeginRenderPass(commandBuffer, &beginInfo, VK_SUBPASS_CONTENTS_INLINE);
|
||||
vkCmdEndRenderPass(commandBuffer);
|
||||
|
||||
@@ -10673,15 +10678,6 @@ void main() {
|
||||
return;
|
||||
}
|
||||
|
||||
auto& frame = m_frameContext.GetCurrent();
|
||||
if (!frame.isCommandRecording) {
|
||||
m_frameContext.BeginCommandRecording();
|
||||
}
|
||||
|
||||
if (VkRenderPassManager::GetActiveRenderPass() != nullptr) {
|
||||
VkRenderPassManager::EndRenderPass(frame.commandBuffer);
|
||||
}
|
||||
|
||||
// One resolver for both object kinds. The texture arm is the same
|
||||
// SyncTextureAndGetDescriptor the copy always used; the renderbuffer arm goes through the
|
||||
// render-pass manager, which is where a renderbuffer's VkImage lives.
|
||||
@@ -10933,6 +10929,16 @@ void main() {
|
||||
}
|
||||
#endif
|
||||
|
||||
// Syncing either endpoint can flush and retire the current command buffer for
|
||||
// a texture upload. Prepare recording only after both images and uploads are ready.
|
||||
auto& frame = m_frameContext.GetCurrent();
|
||||
if (!frame.isCommandRecording) {
|
||||
m_frameContext.BeginCommandRecording();
|
||||
}
|
||||
if (VkRenderPassManager::GetActiveRenderPass() != nullptr) {
|
||||
VkRenderPassManager::EndRenderPass(frame.commandBuffer);
|
||||
}
|
||||
|
||||
const auto materializeClear = [this, &frame](const CopyImageEndpoint& endpoint) {
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
if (MG_Config::Transport != MG_Config::TransportMode::Monolith) return true;
|
||||
@@ -16035,6 +16041,7 @@ void main() {
|
||||
}
|
||||
}
|
||||
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
// YUV shared images (WireYuvImage.inc) are sampled through a VkSamplerYcbcrConversion, a
|
||||
// feature of its own; asked only where AHardwareBuffers are imported at all.
|
||||
m_samplerYcbcrConversion = false;
|
||||
@@ -16051,6 +16058,7 @@ void main() {
|
||||
m_samplerYcbcrConversion = true;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
// VK_EXT_multi_draw: tier 1 of the multi-draw dispatch - one vkCmdDrawMulti(Indexed)EXT
|
||||
// for a whole glMultiDraw* batch (VkMultiDrawIndexedInfoEXT carries per-draw
|
||||
|
||||
@@ -146,6 +146,10 @@ namespace MobileGL::MG_Backend::DirectVulkan {
|
||||
// IBufferCopyCommandProvider: recording command buffer, outside any
|
||||
// render pass, for immediate staged buffer copies.
|
||||
VkCommandBuffer AcquireBufferCopyCommandBuffer() override;
|
||||
// EGL_BUFFER_AGE_EXT of the active target's default framebuffer for the next frame: the age
|
||||
// of the swapchain image acquired for it (SwapchainObject::BufferAgeOf). Asking makes the
|
||||
// target keep its presented images' content from then on.
|
||||
Int32 CurrentDrawBufferAge();
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
VkBufferManager& GetWireBufferManager() { return m_bufferManager; }
|
||||
Bool FlushWirePendingCommandsForTextureUpdate() {
|
||||
@@ -201,10 +205,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
|
||||
// submission's sync_file in `*fence` (-1: none, and the work is waited out here), and - for
|
||||
// a session that writes images - the boundary PublishSharedImageAccesses makes.
|
||||
Bool ExportNativeFence(int* fence);
|
||||
// EGL_BUFFER_AGE_EXT of the active target's default framebuffer for the next frame: the age
|
||||
// of the swapchain image acquired for it (SwapchainObject::BufferAgeOf). Asking makes the
|
||||
// target keep its presented images' content from then on.
|
||||
Int32 CurrentDrawBufferAge();
|
||||
// The reading side's per-use hook (WireSharedImage.inc): every shared-image texture the
|
||||
// wire draw or dispatch being set up samples (VkTextureManager::NoteSharedImageUse) is
|
||||
// acquired from the foreign family before it, when it moved or is not held.
|
||||
|
||||
@@ -378,6 +378,7 @@
|
||||
begin.renderPass = target->renderPass;
|
||||
begin.framebuffer = framebuffer;
|
||||
begin.renderArea = {{0, 0}, destination.extent};
|
||||
EndActiveRenderPassOn(frame.commandBuffer);
|
||||
vkCmdBeginRenderPass(frame.commandBuffer, &begin, VK_SUBPASS_CONTENTS_INLINE);
|
||||
vkCmdBindPipeline(frame.commandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, target->pipeline);
|
||||
const VkViewport viewport{0.0f, 0.0f, static_cast<float>(destination.extent.width),
|
||||
|
||||
@@ -299,6 +299,7 @@
|
||||
begin.renderPass = target->renderPass;
|
||||
begin.framebuffer = framebuffer;
|
||||
begin.renderArea = {{0, 0}, destination.extent};
|
||||
EndActiveRenderPassOn(frame.commandBuffer);
|
||||
vkCmdBeginRenderPass(frame.commandBuffer, &begin, VK_SUBPASS_CONTENTS_INLINE);
|
||||
vkCmdBindPipeline(frame.commandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, target->pipeline);
|
||||
const VkViewport viewport{0.0f, 0.0f, static_cast<float>(destination.extent.width),
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
// PrimitivesGeneratedNoXfbProbe.cpp): one throwaway command buffer, a bounded fence wait that
|
||||
// leaks rather than idle-waits a hung GPU, teardown on every other path.
|
||||
|
||||
#include "RenderPassGuard.h"
|
||||
#include "WireDepthResolveProbe.h"
|
||||
|
||||
#include <MG_Util/Debug/Log.h>
|
||||
@@ -237,6 +238,7 @@ namespace MobileGL::MG_Backend::DirectVulkan {
|
||||
// The RECTANGLE is the render area, exactly as the render-pass arm's renderArea is - the
|
||||
// scratch outside it is never read.
|
||||
begin.renderArea = rect;
|
||||
EndActiveRenderPassOn(commandBuffer);
|
||||
vkCmdBeginRenderPass(commandBuffer, &begin, VK_SUBPASS_CONTENTS_INLINE);
|
||||
vkCmdBindPipeline(commandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline);
|
||||
// THE VIEWPORT IS THE WHOLE ATTACHMENT AND THE SCISSOR IS THE RECT, and the two are not
|
||||
@@ -746,6 +748,7 @@ namespace MobileGL::MG_Backend::DirectVulkan {
|
||||
begin.renderPass = clear.pass;
|
||||
begin.framebuffer = clear.framebuffer;
|
||||
begin.renderArea = fullRect;
|
||||
EndActiveRenderPassOn(cmd);
|
||||
vkCmdBeginRenderPass(cmd, &begin, VK_SUBPASS_CONTENTS_INLINE);
|
||||
VkClearAttachment attachment{};
|
||||
attachment.aspectMask = clear.aspects;
|
||||
@@ -772,6 +775,7 @@ namespace MobileGL::MG_Backend::DirectVulkan {
|
||||
begin.renderPass = item.resolvePass;
|
||||
begin.framebuffer = item.resolveFramebuffer;
|
||||
begin.renderArea = fullRect;
|
||||
EndActiveRenderPassOn(cmd);
|
||||
vkCmdBeginRenderPass(cmd, &begin, VK_SUBPASS_CONTENTS_INLINE);
|
||||
vkCmdEndRenderPass(cmd);
|
||||
}
|
||||
|
||||
@@ -215,7 +215,10 @@
|
||||
MakeXfbWritesVisible();
|
||||
const auto* fbo = state.DrawFramebuffer();
|
||||
if (!fbo) MagmaWireFatal("draw-framebuffer-record");
|
||||
RetireWireDrawPass();
|
||||
// THE PREVIOUS DRAW'S RENDER PASS STAYS OPEN until this draw's attachments are known: a
|
||||
// draw to the same attachments continues it (below), and on a tiler a pass per draw also
|
||||
// loaded and stored every attachment once per draw. Resource work in between that may not
|
||||
// sit inside a pass (a barrier, a copy, a clear) closes it itself (RenderPassGuard.h).
|
||||
// CPU preparation may synchronize GPU-produced vertex/index bytes. Do
|
||||
// not rewind an arena while this draw owns as-yet-unrecorded slices.
|
||||
WirePreparationScope preparing(m_wirePreparationDepth);
|
||||
@@ -490,6 +493,7 @@
|
||||
// attachments below resolve the same index, so this key has to be taken after it.
|
||||
passKey.swapchainImageIndex = DefaultFramebufferWriteIndex(true);
|
||||
}
|
||||
Vector<WireImage> sameLayoutAttachments;
|
||||
const auto add = [&](const MG_Pipe::MGPSurface& surface, VkImageAspectFlags aspect) -> Uint32 {
|
||||
WireImage image = ResolveWireImage(*fbo, surface, aspect, /*isWriteTarget=*/true);
|
||||
if (!image.image) return VK_ATTACHMENT_UNUSED;
|
||||
@@ -499,7 +503,10 @@
|
||||
MGB_CTX->IsCapabilityEnabled(CapabilityInput::FramebufferSrgb));
|
||||
const VkImageLayout layout = aspect == VK_IMAGE_ASPECT_COLOR_BIT ?
|
||||
VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_GENERAL;
|
||||
TransitionWireImage(image, layout);
|
||||
// Already in its attachment layout: its barrier (which closes any open pass) waits until
|
||||
// it is known whether the open pass continues with this very attachment.
|
||||
if (image.layout == layout) sameLayoutAttachments.push_back(image);
|
||||
else TransitionWireImage(image, layout);
|
||||
VkImageViewCreateInfo info{VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO};
|
||||
info.image = image.image;
|
||||
info.viewType = image.viewType;
|
||||
@@ -565,7 +572,17 @@
|
||||
passInfo.pAttachments = attachments.data();
|
||||
passInfo.subpassCount = 1;
|
||||
passInfo.pSubpasses = &subpass;
|
||||
if (!AcquireCachedWireDrawPass(passKey)) {
|
||||
const Bool continuing = m_wireDrawPass && m_wireDrawPassKey == passKey;
|
||||
{
|
||||
const auto* active = VkRenderPassManager::GetActiveRenderPass();
|
||||
const Bool stillOpen = continuing && active != nullptr && active->commandBuffer == frame.commandBuffer;
|
||||
// A new pass orders itself after earlier writes to its attachments; a continued one
|
||||
// is the same pass, whose attachment writes are ordered by rasterization.
|
||||
if (!stillOpen)
|
||||
for (auto& image : sameLayoutAttachments) TransitionWireImage(image, VK_IMAGE_LAYOUT_GENERAL);
|
||||
}
|
||||
if (!continuing) RetireWireDrawPass();
|
||||
if (!continuing && !AcquireCachedWireDrawPass(passKey)) {
|
||||
m_wireDrawPassKey = Move(passKey);
|
||||
Vector<VkImageView> views;
|
||||
views.reserve(viewInfos.size());
|
||||
@@ -629,13 +646,20 @@
|
||||
vkCmdBindVertexBuffers(frame.commandBuffer, binding++, 1, &slice.buffer, &slice.offset);
|
||||
}
|
||||
if (indexSlice.IsValid()) vkCmdBindIndexBuffer(frame.commandBuffer, indexSlice.buffer, indexSlice.offset, indexType);
|
||||
if (!VkRenderPassManager::BeginRenderPass(frame.commandBuffer, pass)) {
|
||||
// Still open from the previous draw (nothing closed it, same command buffer): continue.
|
||||
const auto* active = VkRenderPassManager::GetActiveRenderPass();
|
||||
const Bool open = continuing && active != nullptr && active->commandBuffer == frame.commandBuffer &&
|
||||
active->hash == pass.hash;
|
||||
if (!open && active != nullptr) VkRenderPassManager::EndRenderPass(frame.commandBuffer);
|
||||
if (!open && !VkRenderPassManager::BeginRenderPass(frame.commandBuffer, pass)) {
|
||||
MGL_WIRE_DECLINE_AT(BeginRenderPass, "the render pass for this draw could not be begun");
|
||||
return false;
|
||||
}
|
||||
vkCmdBindPipeline(frame.commandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline);
|
||||
ApplyDynamicDrawStateTail(frame, pass.extent, fbo->IsDefault,
|
||||
ResolveDrawViewportCount(programObj.writesViewportIndexBuiltin));
|
||||
// Storage images this draw writes are what the next sampled-image barrier must cover.
|
||||
if (programObj.hasStorageImages) BumpWireImageWriteEpoch();
|
||||
if (MG_Util::PipeStats::Enabled()) MG_Util::PipeStats::AddCalls(MG_Util::PipeStats::CallClass::Draws, 1);
|
||||
return true;
|
||||
}
|
||||
@@ -800,6 +824,7 @@
|
||||
return;
|
||||
}
|
||||
vkCmdBindPipeline(frame.commandBuffer, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline);
|
||||
EndActiveRenderPassOn(frame.commandBuffer);
|
||||
vkCmdDispatch(frame.commandBuffer, x, y, z);
|
||||
}
|
||||
|
||||
@@ -878,6 +903,7 @@
|
||||
return;
|
||||
}
|
||||
vkCmdBindPipeline(dispatchFrame.commandBuffer, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline);
|
||||
EndActiveRenderPassOn(dispatchFrame.commandBuffer);
|
||||
vkCmdDispatchIndirect(dispatchFrame.commandBuffer, parameters.buffer,
|
||||
parameters.offset + static_cast<VkDeviceSize>(offset));
|
||||
if (MG_Util::PipeStats::Enabled())
|
||||
|
||||
@@ -233,6 +233,13 @@
|
||||
void VulkanRenderer::ClearWireFramebuffer(const MG_Pipe::MGPFramebufferState& fbo,
|
||||
const ClearAttachmentPayload& payload, GLint drawbuffer) {
|
||||
RetireWireDrawPass();
|
||||
// A stream that neither presents nor finishes (an off-screen loop) never submits, so its
|
||||
// recording and the per-clear objects retired below would grow until host memory runs
|
||||
// out. Past a bound, submit what is recorded: the objects then retire with that work.
|
||||
constexpr SizeT kRetiredObjectsBeforeSubmit = 1024;
|
||||
if (m_wireRetiredObjects.size() >= kRetiredObjectsBeforeSubmit && m_wirePreparationDepth == 0 &&
|
||||
HasPendingRecordedWork())
|
||||
(void)FlushPendingCommands();
|
||||
if (MGB_CTX->IsCapabilityEnabled(CapabilityInput::RasterizerDiscard)) return;
|
||||
const auto clearSurface = [&](const MG_Pipe::MGPSurface& surface, VkImageAspectFlags aspect,
|
||||
Uint32 colorIndex) {
|
||||
@@ -319,6 +326,7 @@
|
||||
if (!color) clear.clearValue.depthStencil = {payload.depth, payload.stencil};
|
||||
VkClearRect rect{area, 0, image.layers};
|
||||
auto& frame = m_frameContext.GetCurrent();
|
||||
EndActiveRenderPassOn(frame.commandBuffer);
|
||||
vkCmdBeginRenderPass(frame.commandBuffer, &begin, VK_SUBPASS_CONTENTS_INLINE);
|
||||
vkCmdClearAttachments(frame.commandBuffer, 1, &clear, 1, &rect);
|
||||
vkCmdEndRenderPass(frame.commandBuffer);
|
||||
@@ -830,6 +838,7 @@
|
||||
begin.renderPass = pass;
|
||||
begin.framebuffer = framebuffer;
|
||||
begin.renderArea = {{sxMin, syMin}, {static_cast<Uint32>(width), static_cast<Uint32>(height)}};
|
||||
EndActiveRenderPassOn(m_frameContext.GetCurrent().commandBuffer);
|
||||
vkCmdBeginRenderPass(m_frameContext.GetCurrent().commandBuffer, &begin, VK_SUBPASS_CONTENTS_INLINE);
|
||||
vkCmdEndRenderPass(m_frameContext.GetCurrent().commandBuffer);
|
||||
} else if (!resolvedByShader) {
|
||||
|
||||
@@ -215,6 +215,7 @@
|
||||
VkRenderPassBeginInfo begin{VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO};
|
||||
begin.renderPass = image.clearPass; begin.framebuffer = image.clearFramebuffer;
|
||||
begin.renderArea.extent = {1, 1}; begin.clearValueCount = 1; begin.pClearValues = &clear;
|
||||
EndActiveRenderPassOn(commands);
|
||||
vkCmdBeginRenderPass(commands, &begin, VK_SUBPASS_CONTENTS_INLINE);
|
||||
vkCmdEndRenderPass(commands);
|
||||
image.layout = VK_IMAGE_LAYOUT_GENERAL;
|
||||
@@ -226,6 +227,7 @@
|
||||
const VkImageSubresourceRange range{image.aspect, 0, 1, 0, image.layers};
|
||||
if (shadow) {
|
||||
const VkClearDepthStencilValue depth{0.0f, 0};
|
||||
EndActiveRenderPassOn(commands);
|
||||
vkCmdClearDepthStencilImage(commands, image.image, image.layout, &depth, 1, &range);
|
||||
} else vkCmdClearColorImage(commands, image.image, image.layout, &clear.color, 1, &range);
|
||||
if (!VkTextureManager::TransitionImageLayout(commands, image.image, image.layout,
|
||||
@@ -236,6 +238,7 @@
|
||||
VkMemoryBarrier visible{VK_STRUCTURE_TYPE_MEMORY_BARRIER};
|
||||
visible.srcAccessMask = multisample ? VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT : VK_ACCESS_TRANSFER_WRITE_BIT;
|
||||
visible.dstAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
|
||||
EndActiveRenderPassOn(commands);
|
||||
vkCmdPipelineBarrier(commands, multisample ? VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT : VK_PIPELINE_STAGE_TRANSFER_BIT,
|
||||
VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, 1, &visible, 0, nullptr, 0, nullptr);
|
||||
}
|
||||
|
||||
@@ -410,6 +410,7 @@
|
||||
acquire.dstQueueFamilyIndex = family;
|
||||
acquire.image = source->image;
|
||||
acquire.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
|
||||
EndActiveRenderPassOn(frame.commandBuffer);
|
||||
vkCmdPipelineBarrier(frame.commandBuffer, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
|
||||
VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, 0, 0, nullptr, 0, nullptr, 1, &acquire);
|
||||
|
||||
@@ -487,6 +488,7 @@
|
||||
release.newLayout = VK_IMAGE_LAYOUT_GENERAL;
|
||||
release.srcQueueFamilyIndex = family;
|
||||
release.dstQueueFamilyIndex = VK_QUEUE_FAMILY_FOREIGN_EXT;
|
||||
EndActiveRenderPassOn(frame.commandBuffer);
|
||||
vkCmdPipelineBarrier(frame.commandBuffer, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT,
|
||||
VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, 0, 0, nullptr, 0, nullptr, 1, &release);
|
||||
// GENERAL, the layout every wire descriptor samples in, with the pass's writes made visible.
|
||||
|
||||
@@ -610,7 +610,7 @@ namespace MobileGL::MG_Impl::GLImpl {
|
||||
// GL_OES_EGL_image_external(_essl3) only where the server samples YUV images: an
|
||||
// external texture is a 2D texture holding the image converted to RGBA, which needs
|
||||
// the server to hold the YUV image in the first place (EGLImpl::SharedImageYuvAvailable).
|
||||
static const auto build = [](Bool images, Bool external, Bool es) {
|
||||
static const auto build = [](Bool images, Bool external, Bool es, Bool esApi) {
|
||||
Vector<const char*> list;
|
||||
if (images) list.push_back("GL_OES_EGL_image");
|
||||
if (images && external) {
|
||||
@@ -627,15 +627,30 @@ namespace MobileGL::MG_Impl::GLImpl {
|
||||
list.push_back("GL_EXT_texture_format_BGRA8888");
|
||||
list.push_back("GL_EXT_read_format_bgra");
|
||||
}
|
||||
// Any context created for the OpenGL ES API, whatever it calls itself: the ES 2.0
|
||||
// names of what desktop GL has in core - RGB8/RGBA8 and DEPTH_COMPONENT24
|
||||
// renderbuffers, and glMapBuffer (exported under its OES names as well).
|
||||
if (esApi) {
|
||||
list.push_back("GL_OES_rgb8_rgba8");
|
||||
list.push_back("GL_OES_depth24");
|
||||
list.push_back("GL_OES_mapbuffer");
|
||||
}
|
||||
return list;
|
||||
};
|
||||
static const Vector<const char*> lists[8] = {
|
||||
build(false, false, false), build(false, false, true), build(false, true, false),
|
||||
build(false, true, true), build(true, false, false), build(true, false, true),
|
||||
build(true, true, false), build(true, true, true)};
|
||||
static const Vector<const char*> lists[16] = {
|
||||
build(false, false, false, false), build(false, false, false, true),
|
||||
build(false, false, true, false), build(false, false, true, true),
|
||||
build(false, true, false, false), build(false, true, false, true),
|
||||
build(false, true, true, false), build(false, true, true, true),
|
||||
build(true, false, false, false), build(true, false, false, true),
|
||||
build(true, false, true, false), build(true, false, true, true),
|
||||
build(true, true, false, false), build(true, true, false, true),
|
||||
build(true, true, true, false), build(true, true, true, true)};
|
||||
const Bool images = MG_Impl::EGLImpl::SharedImagesAvailable();
|
||||
const Bool external = images && MG_Impl::EGLImpl::SharedImageYuvAvailable();
|
||||
return lists[(images ? 4 : 0) + (external ? 2 : 0) + (EsIdentityActive() ? 1 : 0)];
|
||||
const Bool esApi = MG_State::pEGLContext &&
|
||||
MG_State::pEGLContext->GetCurrentContextClientAPI() == EGL_OPENGL_ES_API;
|
||||
return lists[(images ? 8 : 0) + (external ? 4 : 0) + (EsIdentityActive() ? 2 : 0) + (esApi ? 1 : 0)];
|
||||
}
|
||||
|
||||
// Robust buffer access as GL 4.5 / KHR_robust_buffer_access_behavior define it: the backend
|
||||
|
||||
@@ -246,6 +246,10 @@ namespace MobileGL::MG_Impl {
|
||||
GETPROC(glBufferSubData, name);
|
||||
GETPROC(glGetBufferSubData, name);
|
||||
GETPROC(glMapBuffer, name);
|
||||
// GL_OES_mapbuffer (ES contexts): the same three calls under their OES names.
|
||||
if (strcmp(name, "glMapBufferOES") == 0) return (void*)glMapBuffer;
|
||||
if (strcmp(name, "glUnmapBufferOES") == 0) return (void*)glUnmapBuffer;
|
||||
if (strcmp(name, "glGetBufferPointervOES") == 0) return (void*)glGetBufferPointerv;
|
||||
GETPROC(glUnmapBuffer, name);
|
||||
GETPROC(glGetBufferParameteriv, name);
|
||||
GETPROC(glGetBufferPointerv, name);
|
||||
|
||||
@@ -234,7 +234,9 @@ namespace MobileGL::MG_Pipe {
|
||||
m_vertices.push_back(static_cast<Uint64>(vertex));
|
||||
}
|
||||
}
|
||||
std::sort(m_vertices.begin(), m_vertices.end());
|
||||
// An array draw's single range arrives ascending already; sorting it again was most of
|
||||
// the client's time on a client-array draw.
|
||||
if (!std::is_sorted(m_vertices.begin(), m_vertices.end())) std::sort(m_vertices.begin(), m_vertices.end());
|
||||
m_vertices.erase(std::unique(m_vertices.begin(), m_vertices.end()), m_vertices.end());
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -34,6 +34,12 @@ namespace MobileGL::MG_Pipe {
|
||||
MGPipeVertexInputEmitterInstance().EmitVertexBuffers(m_context, m_baseInstance);
|
||||
if (m_indexBindingChanged)
|
||||
MGPipeVertexInputEmitterInstance().EmitIndexBuffer(m_context);
|
||||
// The bindings no longer name them: the buffers go back to the share group for the
|
||||
// next client-array draw. Their next respecify orphans the store this draw reads.
|
||||
auto& group = *m_context.GetShareGroup();
|
||||
for (auto& buffer : m_vertexBuffers)
|
||||
if (buffer) group.ReturnClientArrayBuffer(std::move(buffer));
|
||||
if (m_indexBuffer) group.ReturnClientArrayBuffer(std::move(m_indexBuffer));
|
||||
}
|
||||
|
||||
Bool Prepare(MGPDrawInfo& info, const MGPDrawRange* ranges, Uint32 rangeCount,
|
||||
@@ -46,7 +52,8 @@ namespace MobileGL::MG_Pipe {
|
||||
// Start remains an element offset, so base vertex and draw IDs are unchanged.
|
||||
if (clientIndexBytes != 0) {
|
||||
if (!clientIndices || clientIndexBytes > std::numeric_limits<Uint32>::max()) return false;
|
||||
m_indexBuffer = MakeOwnedBuffer(clientIndices, static_cast<SizeT>(clientIndexBytes), BufferTarget::Index);
|
||||
m_indexBuffer = MakeOwnedBuffer(m_context, clientIndices, static_cast<SizeT>(clientIndexBytes),
|
||||
BufferTarget::Index);
|
||||
info.IndexResource = MGPipeResourceTrackerInstance().Find(*m_indexBuffer);
|
||||
info.Flags &= ~static_cast<Uint8>(kDrawHasUserIndices);
|
||||
MGPIndexBuffer binding{};
|
||||
@@ -115,8 +122,14 @@ namespace MobileGL::MG_Pipe {
|
||||
if (attribute.Offset == 0 || byteCount > std::numeric_limits<SizeT>::max() - attribute.Offset)
|
||||
return false;
|
||||
const auto* source = reinterpret_cast<const Uint8*>(attribute.Offset);
|
||||
const Uint64 first = referenced.front();
|
||||
if (stride == 0) {
|
||||
std::memcpy(bytes.data(), source, elementBytes);
|
||||
} else if (last - first + 1 == referenced.size()) {
|
||||
// Contiguous elements (every array draw, most indexed ones): the vertex
|
||||
// records from the first fetched one to the end of the last, in one copy.
|
||||
const SizeT begin = static_cast<SizeT>(first * stride);
|
||||
std::memcpy(bytes.data() + begin, source + begin, byteCount - begin);
|
||||
} else {
|
||||
// Only dereference fetched elements: sparse indices and first>0
|
||||
// do not grant permission to read intervening application memory.
|
||||
@@ -126,7 +139,7 @@ namespace MobileGL::MG_Pipe {
|
||||
}
|
||||
}
|
||||
}
|
||||
m_vertexBuffers[location] = MakeOwnedBuffer(bytes.data(), bytes.size(), BufferTarget::Vertex);
|
||||
m_vertexBuffers[location] = MakeOwnedBuffer(m_context, bytes.data(), bytes.size(), BufferTarget::Vertex);
|
||||
handles[location] = MGPipeResourceTrackerInstance().Find(*m_vertexBuffers[location]);
|
||||
}
|
||||
MGPipeVertexInputEmitterInstance().EmitVertexBuffers(m_context, info.StartInstance, &handles);
|
||||
@@ -173,8 +186,11 @@ namespace MobileGL::MG_Pipe {
|
||||
return attribute.Size > 0 && attribute.Size <= 4 ? component * attribute.Size : 0;
|
||||
}
|
||||
|
||||
static UniquePtr<Buffer> MakeOwnedBuffer(const void* bytes, SizeT size, BufferTarget target) {
|
||||
auto buffer = MakeUnique<Buffer>(0);
|
||||
static UniquePtr<Buffer> MakeOwnedBuffer(Context& context, const void* bytes, SizeT size, BufferTarget target) {
|
||||
// A kept buffer is already a published resource: respecifying it is fire-and-forget,
|
||||
// where a new one costs a blocking create (and a destroy after the draw).
|
||||
auto buffer = context.GetShareGroup()->TakeClientArrayBuffer();
|
||||
if (!buffer) buffer = MakeUnique<Buffer>(0);
|
||||
const auto handle = MGPipeResourceTrackerInstance().Find(*buffer);
|
||||
MGPipeResourceTrackerInstance().NoteBoundAs(handle, target);
|
||||
buffer->SetUsage(BufferUsage::StreamDraw);
|
||||
|
||||
@@ -70,6 +70,11 @@ namespace MobileGL::MG_Pipe {
|
||||
// The one door into PipeInputs' storage on the client side. A struct rather than a
|
||||
// list of friend functions so the header names exactly one friend.
|
||||
struct MGPipeFillAccess {
|
||||
static void CopyServerPackReference(PipeInputs& dst, const PipeInputs& actual,
|
||||
const PixelStoreParameters& pack) {
|
||||
dst.m_pixelStore[0] = pack;
|
||||
dst.m_pixelStore[1] = actual.m_pixelStore[1];
|
||||
}
|
||||
// Copies ONE field's storage out of the live context by calling the GLContext
|
||||
// accessor of the same name (P1 brief D4: no derivation logic is re-implemented
|
||||
// here, which is what keeps the copy semantically identical by construction).
|
||||
@@ -659,56 +664,6 @@ namespace MobileGL::MG_Pipe {
|
||||
if (!MGPipeVerifyInputs(inputs, g_snapshot, mask, &differing)) ReportDivergence(differing, "entry");
|
||||
}
|
||||
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
// ---- P7 wave 3 (V1): the compare-at-read oracle inside the server's read_pixels ----
|
||||
//
|
||||
// WHAT THE SPLIT ARM FOUND THE FIRST TIME VERIFY AND SPLIT SHARED A BUILD. Every
|
||||
// glReadPixels on the inproc arm - 8530 reads over 220 of the lane's 1068 entries, and the
|
||||
// VerifySplitArming. entries on both backends - aborted with
|
||||
//
|
||||
// MGPipe: verify read of GetPixelStoreParameters (index 0, 0) differs from the live context
|
||||
// MGPipe: Fatal{PipeVerifyDiffer, "GetPixelStoreParameters@ReadPixels", verb=6, where=read}
|
||||
//
|
||||
// on the server's apply thread, and it was the ONLY field that diverged anywhere in the
|
||||
// lane. The mechanism is ID-49 and is deliberate: the pack state never shapes the wire
|
||||
// answer, so MG_Remote/Server/PipeApplier.cpp's read_pixels body writes a NEUTRAL pack
|
||||
// into the applier's copy of the field (MGPipeApplySetPixelPackState), makes the backend
|
||||
// read, and restores the pushed one; the client then scatters the tight reply through the
|
||||
// application's own pack state. The frontend context - this comparator's oracle - still
|
||||
// holds the application's pack (Alignment 4 by default), so the backend's read of the
|
||||
// pack half answers {Alignment 1} where the live context says {Alignment 4}. On the
|
||||
// monolith arm the same neutral window is opened on the frontend context itself
|
||||
// (GL_Texture.cpp's ScopedNeutralPackState), which is why the monolith lane never saw it.
|
||||
//
|
||||
// SO THE ORACLE, NOT THE RULE, IS WHAT CHANGES, AND ONLY IN THAT WINDOW: under a server
|
||||
// stamp, on the ReadPixels verb, the pack half's expected value is the neutral pack the
|
||||
// applier reads with, and the UNPACK half and every other field keep the live context as
|
||||
// their oracle. A server read of the pack half that is neither the application's value
|
||||
// nor exactly the neutral one is still a divergence and still Fatal.
|
||||
//
|
||||
// WHAT THIS GIVES UP IS ONE VALUE, NOT THE FIELD (corrected in P7 wave 3's V1 fix round;
|
||||
// the first statement of it here said the comparator could no longer see a client that
|
||||
// pushed a WRONG pack state at all, which is too broad). PipeApplier.cpp's read_pixels
|
||||
// reads `savedPack` THROUGH THE ACCESSOR - and therefore through this hook - BEFORE it
|
||||
// installs the neutral value, so the pushed pack has already been compared against the
|
||||
// live one by then: a correct push is equal and returns, and a wrong push that is not
|
||||
// exactly the neutral pack fails both compares and is still Fatal. The blind spot is the
|
||||
// single value {SwapBytes 0, LSBFirst 0, RowLength 0, ImageHeight 0, Skip* 0, Alignment 1},
|
||||
// and only while the application's own pack differs from it. The client-side scatter that
|
||||
// consumes the real pack is covered by the readback matrix cases, which compare bytes,
|
||||
// not fields.
|
||||
Bool ServerReadsInsideTheNeutralPackWindow(const PipeInputs& self, MGPipeInputField field) {
|
||||
return field == MGPipeInputField::GetPixelStoreParameters && self.ServerStampedVerb() &&
|
||||
self.CurrentVerb() == MGPipeVerb::ReadPixels;
|
||||
}
|
||||
|
||||
// The constant itself is MG_Pipe's (MGPipeTypes.h's MGPipeNeutralReadPixelsPack), which is
|
||||
// the same function MG_Remote/Server/PipeApplier.cpp's read_pixels installs. It used to be
|
||||
// re-typed here, field for field, to avoid reaching into MG_Remote/Server from MG_Impl -
|
||||
// but the owner of MGPPixelPackState is MG_Pipe, both sites already include it, and a
|
||||
// drift between the two spellings would have cost a false divergence rather than a build
|
||||
// break.
|
||||
#endif // MOBILEGL_BUILD_DISAGGREGATED
|
||||
#endif // MOBILEGL_PIPE_VERIFY
|
||||
} // namespace
|
||||
|
||||
@@ -726,9 +681,28 @@ namespace MobileGL::MG_Pipe {
|
||||
}
|
||||
|
||||
void MGPipeVerifyReadHook(const PipeInputs& self, MGPipeInputField field, Uint index0, Uint index1) {
|
||||
if (&self != &gPipeInputs || !g_verify.Enabled || g_verify.InHook) return;
|
||||
if (&self != &gPipeInputs || !g_verify.Enabled) return;
|
||||
const auto index = static_cast<SizeT>(field);
|
||||
if (kMGPipeInputFieldSticky[index]) return;
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
if (self.ServerStampedVerb() && field == MGPipeInputField::GetPixelStoreParameters) {
|
||||
// Compare the backend's pack field against the last payload applied to this
|
||||
// context, including the neutral-pack override during readback. Never obtain
|
||||
// the reference by reading the field being checked, or consult the client's
|
||||
// GLContext from the server thread. Unpack has no server-side reader.
|
||||
static thread_local PipeInputs reference;
|
||||
MGPipeFillAccess::CopyServerPackReference(reference, self, MGPipeApplier().VerifyPixelPack);
|
||||
if (g_verify.Corrupt && *g_verify.Corrupt == field) {
|
||||
MGPipeApplyVerifyCorruption(reference, field);
|
||||
}
|
||||
if (!MGPipeInputsFieldEqual(field, self, reference)) {
|
||||
MGLOG_E("MGPipe: verify read of pixel pack differs from the applied pack payload");
|
||||
ReportDivergence(field, "read");
|
||||
}
|
||||
return;
|
||||
}
|
||||
#endif
|
||||
if (g_verify.InHook) return;
|
||||
auto* ctx = LiveContext();
|
||||
if (ctx == nullptr) return;
|
||||
// The whole field is re-read and compared - a superset of "the same indices", so a
|
||||
@@ -743,68 +717,13 @@ namespace MobileGL::MG_Pipe {
|
||||
// never recurses (and never reports the inner read against a half-copied scratch).
|
||||
g_verify.InHook = true;
|
||||
MGPipeFillAccess::CopyField(g_readScratch, *ctx, field);
|
||||
// P7 wave 3 (V1): NEGATIVE CONTROL A REACHES THIS ARM TOO. Until this line the knob only
|
||||
// ever perturbed EntryCompare's snapshot, so every red it could produce said `where=entry`
|
||||
// and was produced on the CLIENT thread - which left the compare-at-read hook, the arm
|
||||
// that runs on the server's apply thread and does the whole of the split lane's per-read
|
||||
// work, with no falsifier at all: a hook that had stopped comparing would have looked
|
||||
// exactly like a hook with nothing to report. The perturbation goes on the ORACLE, for
|
||||
// EntryCompare's reason: the arm under test is the stored value, so corrupting THAT would
|
||||
// be testing the corruption.
|
||||
//
|
||||
// WHICH READ THIS BLOCK TURNS RED (V1 fix round 2). The server reads the pack field TWICE
|
||||
// inside the ReadPixels verb window, and both reads sit inside
|
||||
// ServerReadsInsideTheNeutralPackWindow below (the verb stamp is up for the whole apply):
|
||||
// PipeApplier::read_pixels saves the application's pack through the accessor BEFORE it
|
||||
// installs the neutral one, and the backend's ReadPixels reads the field AFTER. This block
|
||||
// is what turns the FIRST of them red: at that read `self` still holds the application's
|
||||
// pack, so the first compare only reaches the window if this perturbation made it differ,
|
||||
// and inside the window the application's pack against the neutral oracle differs on its
|
||||
// own. It does nothing for the second read - `self` IS the neutral pack there - which is
|
||||
// what the re-application inside the window is for.
|
||||
// Corrupt the reference, not the backend field, to test the comparison itself.
|
||||
if (g_verify.Corrupt && *g_verify.Corrupt == field) {
|
||||
MGPipeApplyVerifyCorruption(g_readScratch, field);
|
||||
}
|
||||
const Bool equal = MGPipeInputsFieldEqual(field, self, g_readScratch);
|
||||
g_verify.InHook = false;
|
||||
if (equal) return;
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
if (ServerReadsInsideTheNeutralPackWindow(self, field)) {
|
||||
// The live context is the application's pack state and the server is, by ID-49,
|
||||
// reading with the neutral one; the oracle for THAT HALF is the neutral pack, and
|
||||
// every other byte of the field still has to match the live context.
|
||||
g_verify.InHook = true;
|
||||
PipeInputs::VisitStorage(field, g_readScratch, g_readScratch, [](auto& live, auto&) {
|
||||
if constexpr (std::is_same_v<std::remove_reference_t<decltype(live)>, PixelStoreParameters[2]>) {
|
||||
live[0] = MGPipeNeutralReadPixelsPack().Pack;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
// AND THE CONTROL IS RE-APPLIED, because the overwrite above replaces the pack half
|
||||
// WHOLESALE - the corruption included, since CorruptStorage perturbs an array's FIRST
|
||||
// ELEMENT and the pack half is element 0. This is the block for the POST-INSTALL read
|
||||
// (the backend's ReadPixels, after PipeApplier::read_pixels installed the neutral pack
|
||||
// into gPipeInputs): there `self` is the neutral pack, the overwrite just made the
|
||||
// oracle equal to it, and only a perturbation applied AFTER the overwrite can make
|
||||
// that compare differ - the block above cannot reach it. Without this line the one
|
||||
// window in which this arm is most load-bearing (the server's read_pixels, 8530 reads
|
||||
// over 220 of the lane's entries) would be the one window MOBILEGL_PIPE_VERIFY_CORRUPT=
|
||||
// GetPixelStoreParameters cannot turn red - and a control that accepted ONE report
|
||||
// would never notice, because the saved-pack read still reports through the block
|
||||
// above. The VerifySplitReadCorrupted. entries and the CI step therefore require at
|
||||
// least TWO `where=read` reports in the server half (V1 fix round 2). Measured: 3 on
|
||||
// DirectGLES (its backend reads the field twice after the install) / 2 on
|
||||
// DirectVulkan; without this block both drop to 1, without the block above
|
||||
// DirectVulkan drops to 1 while DirectGLES's two post-install reports keep it at 2 -
|
||||
// so this block is falsified on both backends and the one above on DirectVulkan.
|
||||
if (g_verify.Corrupt && *g_verify.Corrupt == field) {
|
||||
MGPipeApplyVerifyCorruption(g_readScratch, field);
|
||||
}
|
||||
const Bool equalToTheNeutralPack = MGPipeInputsFieldEqual(field, self, g_readScratch);
|
||||
g_verify.InHook = false;
|
||||
if (equalToTheNeutralPack) return;
|
||||
}
|
||||
#endif
|
||||
MGLOG_E("MGPipe: verify read of %s (index %u, %u) differs from the live context", kMGPipeInputFieldNames[index],
|
||||
index0, index1);
|
||||
ReportDivergence(field, "read");
|
||||
@@ -3988,6 +3907,7 @@ namespace MobileGL::MG_Pipe {
|
||||
}
|
||||
|
||||
void MGPipeClientDrainTextureUploads() {
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
if (MG_Config::Transport == MG_Config::TransportMode::Monolith) return;
|
||||
if (MG_Remote::Client::RunsAsTheServerRole()) return;
|
||||
auto* ctx = LiveContext();
|
||||
@@ -3999,6 +3919,7 @@ namespace MobileGL::MG_Pipe {
|
||||
P4aFamilyDependenciesAreSet(kMGPipeSubsystemTextureResources, pushMask)) {
|
||||
(void)MGPipeTextureEmitterInstance().DrainTextureSubData(*ctx);
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
|
||||
@@ -374,5 +374,47 @@ void main() { o_color = vec4(0.1, 0.2, 0.8, 1.0); }
|
||||
<< (std::fabs(blitted - 0.125f) < 1e-3f ? " - the destination kept its own clear" : "");
|
||||
}
|
||||
|
||||
TEST_F(LayeredAttachmentBarrierScenario, EndingAMiddleMipDrawPreservesOtherLevels) {
|
||||
if (!Ready()) return;
|
||||
GLuint texture = 0;
|
||||
glGenTextures(1, &texture);
|
||||
m_textures.push_back(texture);
|
||||
glBindTexture(GL_TEXTURE_2D, texture);
|
||||
glTexStorage2D(GL_TEXTURE_2D, 3, GL_RGBA8, 16, 16);
|
||||
for (int level = 0; level < 3; ++level) {
|
||||
const int size = 16 >> level;
|
||||
const std::vector<Rgba8> initial(size * size, LayerFill(level));
|
||||
glTexSubImage2D(GL_TEXTURE_2D, level, 0, 0, size, size,
|
||||
GL_RGBA, GL_UNSIGNED_BYTE, initial.data());
|
||||
}
|
||||
GLuint fbo = 0;
|
||||
glGenFramebuffers(1, &fbo);
|
||||
m_fbos.push_back(fbo);
|
||||
glBindFramebuffer(GL_FRAMEBUFFER, fbo);
|
||||
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture, 1);
|
||||
ASSERT_EQ(glCheckFramebufferStatus(GL_FRAMEBUFFER), GL_FRAMEBUFFER_COMPLETE);
|
||||
glViewport(0, 0, 8, 8);
|
||||
glDisable(GL_SCISSOR_TEST);
|
||||
glDisable(GL_DEPTH_TEST);
|
||||
glDisable(GL_BLEND);
|
||||
glDrawBuffer(GL_COLOR_ATTACHMENT0);
|
||||
DrawFullViewportQuad(m_program);
|
||||
// Ending this pass reconciles both lower and upper mip layouts. Their barriers
|
||||
// must not see the pass as active and recursively end it a second time.
|
||||
glFinish();
|
||||
for (int level = 0; level < 3; ++level) {
|
||||
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture, level);
|
||||
glReadBuffer(GL_COLOR_ATTACHMENT0);
|
||||
Rgba8 actual{};
|
||||
glReadPixels(0, 0, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, &actual);
|
||||
const Rgba8 expected = level == 1 ? kPaintedColor : LayerFill(level);
|
||||
EXPECT_NEAR(actual.r, expected.r, 2) << "level " << level;
|
||||
EXPECT_NEAR(actual.g, expected.g, 2);
|
||||
EXPECT_NEAR(actual.b, expected.b, 2);
|
||||
EXPECT_EQ(actual.a, expected.a);
|
||||
}
|
||||
EXPECT_EQ(FirstGLError(), 0u);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
} // namespace MGITest
|
||||
@@ -322,11 +322,14 @@ TEST_F(MagmaRunAheadScenario, PresentCreditActuallyParksTheClientAtItsConfigured
|
||||
Gl().EndFrame(); // credit + 1 must park before it can publish its present.
|
||||
stop.store(true); observer.join(); hold.Release();
|
||||
EXPECT_TRUE(sawPark.load()) << "no real producer park while the present window was full";
|
||||
const auto issuedBeforeFinish = PeekSplitRuntime().emitSeq;
|
||||
glFinish();
|
||||
const auto after=PeekSplitRuntime();
|
||||
EXPECT_EQ(after.presentCreditWaits,before.presentCreditWaits+1);
|
||||
EXPECT_EQ(after.presentAckSerial,before.presentCredit+1);
|
||||
EXPECT_EQ(after.appliedSeq,after.emitSeq);
|
||||
// Finish waits for prior work, then asynchronously destroys its internal fence.
|
||||
// That cleanup may still be queued when Finish returns.
|
||||
EXPECT_GE(after.appliedSeq,issuedBeforeFinish);
|
||||
RecordProperty("observed_present_credit",std::to_string(before.presentCredit));
|
||||
RecordProperty("observed_producer_park",sawPark.load() ? "yes" : "no");
|
||||
}
|
||||
|
||||
@@ -2097,6 +2097,9 @@ namespace MobileGL::MG_Pipe {
|
||||
}
|
||||
|
||||
void MGPipeApplySetPixelPackState(const MGPPixelPackState& pack) {
|
||||
#if MOBILEGL_PIPE_VERIFY
|
||||
MGPipeApplier().VerifyPixelPack = pack.Pack;
|
||||
#endif
|
||||
MGPipeApplyAccess::PackState(gPipeInputs) = pack.Pack;
|
||||
}
|
||||
|
||||
|
||||
@@ -602,6 +602,11 @@ namespace MobileGL::MG_Pipe {
|
||||
// The per-context half. Everything here is cleared by MGPipeApplierReset, EXCEPT the serials,
|
||||
// which only ever advance (see there).
|
||||
struct MGPipeWorkingState {
|
||||
#if MOBILEGL_PIPE_VERIFY
|
||||
// Reference from the pack-state payload, separate from the backend-visible storage.
|
||||
// The server has no frontend GLContext to use as a read-time oracle.
|
||||
PixelStoreParameters VerifyPixelPack{};
|
||||
#endif
|
||||
// Indexed by slot; slot 0 is the reserved null handle and is never live
|
||||
// (MGPipeHandles.h kMGPipeFirstAllocatableSlot).
|
||||
Vector<MGPipeRenderStateCsoRecord> RenderStateCsos;
|
||||
|
||||
@@ -2492,38 +2492,47 @@ namespace MobileGL::MG_Remote::Client {
|
||||
// LastPublishedSeq by construction and a second wait would only add a park on a
|
||||
// watermark that is already reached.
|
||||
if (!m_runAheadArmed || !m_started) return;
|
||||
const Uint64 target = m_producer.LastPublishedSeq();
|
||||
if (target == 0) return;
|
||||
if (m_producer.LastPublishedSeq() == 0) return;
|
||||
const auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(kBarrierTimeoutMs);
|
||||
const BarrierWaitScope waiting;
|
||||
const Transport::SessionWait wait =
|
||||
WaitForAppliedBudget(m_producer, *m_events, target, kBarrierTimeoutMs);
|
||||
if (wait == Transport::SessionWait::ShutDown) {
|
||||
// `dl`: the same two-events distinction the verb barrier makes. Only a peer that
|
||||
// HUNG UP is a device loss; Stop() reaches this path too.
|
||||
if (const Transport::Doorbell* bell = m_producer.SelfDoorbell();
|
||||
bell != nullptr && bell->PeerHungUp()) {
|
||||
LatchDeviceLost("a forced run-ahead wait woke on a peer that had hung up");
|
||||
for (;;) {
|
||||
const Uint64 target = m_producer.LastPublishedSeq();
|
||||
const auto now = std::chrono::steady_clock::now();
|
||||
const auto remaining = std::chrono::duration_cast<std::chrono::milliseconds>(deadline - now).count();
|
||||
const Transport::SessionWait wait = now >= deadline
|
||||
? Transport::SessionWait::TimedOut
|
||||
: m_producer.WaitForAppliedOrEventBacklog(
|
||||
target, static_cast<Uint32>(std::max<Int64>(remaining, 1)));
|
||||
if (wait == Transport::SessionWait::ShutDown) {
|
||||
// Only a peer that hung up is a device loss; Stop() reaches this path too.
|
||||
if (const Transport::Doorbell* bell = m_producer.SelfDoorbell();
|
||||
bell != nullptr && bell->PeerHungUp()) {
|
||||
LatchDeviceLost("a forced run-ahead wait woke on a peer that had hung up");
|
||||
}
|
||||
if (!DeviceLost())
|
||||
MGLOG_E("MG_Remote client: the forced wait for %s woke on a dead doorbell; the "
|
||||
"server is gone", why);
|
||||
return;
|
||||
}
|
||||
if (wait != Transport::SessionWait::Reached) {
|
||||
SessionFail(MGFatalFamily::BarrierTimeout, "MGPipe: Fatal{BarrierTimeout, \"%s\"} - a forced run-ahead wait did not "
|
||||
"reach appliedSeq %llu within %u ms. The forced waits of CONTRACT-P5E §2.5 "
|
||||
"are the points at which the client must be in step again, so a wedge here "
|
||||
"is a wedge in the queue and not a slow frame",
|
||||
why, static_cast<unsigned long long>(target), kBarrierTimeoutMs);
|
||||
}
|
||||
// Drain even when only the event backlog woke us: the server may need that
|
||||
// space before it can advance appliedSeq. SurfaceChanged callbacks and pin
|
||||
// destruction can themselves publish records, so the original target alone
|
||||
// no longer proves the applier is idle after these operations.
|
||||
DrainEventRing(*m_events);
|
||||
ReleaseFillPins();
|
||||
const auto* progress = m_producer.Progress();
|
||||
if (m_producer.LastPublishedSeq() == target && progress != nullptr &&
|
||||
Transport::Watermark::Reached(progress->appliedSeq, target)) {
|
||||
return;
|
||||
}
|
||||
// The doorbell died: teardown, not a fault - the same answer EmitAndWaitTails
|
||||
// gives, and for the same reason.
|
||||
if (!DeviceLost()) // see the barrier above: the latch already said it
|
||||
MGLOG_E("MG_Remote client: the forced wait for %s woke on a dead doorbell; the "
|
||||
"server is gone", why);
|
||||
return;
|
||||
}
|
||||
if (wait != Transport::SessionWait::Reached) {
|
||||
SessionFail(MGFatalFamily::BarrierTimeout, "MGPipe: Fatal{BarrierTimeout, \"%s\"} - a forced run-ahead wait did not "
|
||||
"reach appliedSeq %llu within %u ms. The forced waits of CONTRACT-P5E §2.5 "
|
||||
"are the points at which the client must be in step again, so a wedge here "
|
||||
"is a wedge in the queue and not a slow frame",
|
||||
why, static_cast<unsigned long long>(target), kBarrierTimeoutMs);
|
||||
}
|
||||
// EVERY WAIT EXIT DRAINS (§2.6). It is what the flow-control deadlock argument rests
|
||||
// on: the server blocks only on a full event ring, the client blocks only on
|
||||
// watermarks the server advances, and every client wait drains - so at most one side
|
||||
// is parked at any instant.
|
||||
DrainEventRing(*m_events);
|
||||
ReleaseFillPins();
|
||||
#else
|
||||
(void)why;
|
||||
#endif
|
||||
@@ -2551,8 +2560,10 @@ namespace MobileGL::MG_Remote::Client {
|
||||
// glFinish. Nothing goes on the wire - Flush and Finish have no record (ARCHITECTURE
|
||||
// §11) - and under lockstep there was nothing to do, because the client had already
|
||||
// waited out every command it issued. Under run-ahead "the commands issued so far have
|
||||
// completed" is a promise the queue can break, so this is where it is kept.
|
||||
// completed" is a promise the queue can break, so this is where it is kept - and
|
||||
// "completed" includes the GPU, so a fence round trip follows the apply.
|
||||
WaitForApplyToCatchUp("glFinish");
|
||||
EmitFinishWait();
|
||||
}
|
||||
|
||||
Uint64 ClientSession::AcquirePresentCredit() {
|
||||
|
||||
@@ -2085,6 +2085,23 @@ namespace MobileGL::MG_Remote::Client {
|
||||
|
||||
} // namespace
|
||||
|
||||
// glFinish's GPU half: a server fence created after everything the client issued, waited
|
||||
// with GL_SYNC_FLUSH_COMMANDS_BIT, then destroyed. Waiting for the apply thread alone left
|
||||
// the GPU queue unbounded behind a "finished" glFinish.
|
||||
void EmitFinishWait() {
|
||||
ClientSession* session = ClientSession::Active();
|
||||
if (session == nullptr || !session->Started() || session->DeviceLost()) return;
|
||||
const std::lock_guard<std::mutex> lock(g_fenceMutex);
|
||||
const MG_Pipe::MGPipeHandle handle = MG_Pipe::MGPipeSlots().Allocate(MG_Pipe::MGPipeKind::Fence);
|
||||
const MG_Pipe::MGPHandleOnly desc{handle, static_cast<Uint32>(MG_Pipe::MGPipeKind::Fence), 0};
|
||||
session->EmitAndWait(MG_Pipe::MGPWireOp::FenceCreate, &desc, sizeof(desc), nullptr, 0, nullptr, 0, nullptr);
|
||||
constexpr GLuint64 kFinishTimeoutNs = 10ull * 1000 * 1000 * 1000;
|
||||
const MG_Pipe::MGPFenceWait request{handle, kFinishTimeoutNs, GL_SYNC_FLUSH_COMMANDS_BIT, 0};
|
||||
(void)ReadFenceReply(*session, MG_Pipe::MGPWireOp::FenceWait, &request, sizeof(request));
|
||||
session->EmitAndWait(MG_Pipe::MGPWireOp::FenceDestroy, &desc, sizeof(desc), nullptr, 0, nullptr, 0, nullptr);
|
||||
MG_Pipe::MGPipeSlots().Free(MG_Pipe::MGPipeKind::Fence, handle);
|
||||
}
|
||||
|
||||
void NoteFenceSignaledByServer(MG_Pipe::MGPipeHandle fence) {
|
||||
RememberFenceSignaled(fence);
|
||||
g_fenceServerReports.fetch_add(1, std::memory_order_relaxed);
|
||||
|
||||
@@ -291,6 +291,8 @@ namespace MobileGL::MG_Remote::Client {
|
||||
//
|
||||
// The event drain's half: the server reported `fence` signaled (kEventFenceSignaled). Every
|
||||
// later glClientWaitSync / glGetSynciv(GL_SYNC_STATUS) on it answers without a round trip.
|
||||
// glFinish's wait for the GPU (a server fence created, waited and destroyed).
|
||||
void EmitFinishWait();
|
||||
void NoteFenceSignaledByServer(MG_Pipe::MGPipeHandle fence);
|
||||
|
||||
// What the fence polls cost, for the lanes. `LocalAnswers` = polls answered with no record
|
||||
|
||||
@@ -1085,6 +1085,7 @@ namespace MobileGL::MG_Remote::Server {
|
||||
static std::uint64_t sFrameRecords = 0;
|
||||
static std::uint64_t sFrameIndex = 0;
|
||||
Uint64 applied = 0;
|
||||
const bool timed = ServerFrameStatsEnabled();
|
||||
for (;;) {
|
||||
if (SessionLatched()) break;
|
||||
if (m_windowRequests.load(std::memory_order_acquire) != 0) {
|
||||
@@ -1093,15 +1094,25 @@ namespace MobileGL::MG_Remote::Server {
|
||||
}
|
||||
bool corrupt = false;
|
||||
const bool popped = consumer.ApplyOne(
|
||||
[this, &applier](const Transport::RingRecordView& record) {
|
||||
const auto applyStarted = std::chrono::steady_clock::now();
|
||||
applier.ApplyOne(record);
|
||||
[this, &applier, timed](const Transport::RingRecordView& record) {
|
||||
// Check after acquiring each record: a producer may publish more work
|
||||
// while this drain is running, after the outer-loop reset check.
|
||||
if (m_backend != nullptr && m_backend->LatchIfGpuFaulted()) return false;
|
||||
if (SessionLatched()) return false;
|
||||
// P65ServerFrame: timed around the ONE call that is the server's work, and
|
||||
// summed across the drains a frame spans. See the block above DrainRing's loop.
|
||||
sFrameApplyNs += static_cast<std::uint64_t>(
|
||||
std::chrono::duration_cast<std::chrono::nanoseconds>(
|
||||
std::chrono::steady_clock::now() - applyStarted)
|
||||
.count());
|
||||
// Only when the line is on: two clock reads per record were a measurable part
|
||||
// of a record's cost.
|
||||
if (timed) {
|
||||
const auto applyStarted = std::chrono::steady_clock::now();
|
||||
applier.ApplyOne(record);
|
||||
sFrameApplyNs += static_cast<std::uint64_t>(
|
||||
std::chrono::duration_cast<std::chrono::nanoseconds>(
|
||||
std::chrono::steady_clock::now() - applyStarted)
|
||||
.count());
|
||||
} else {
|
||||
applier.ApplyOne(record);
|
||||
}
|
||||
++sFrameRecords;
|
||||
// P9 W3, F2: outside the apply timing above; 0 in every run that is not F2.
|
||||
if (m_testLogFloodLines != 0) FloodLogForTest(m_testLogFloodLines);
|
||||
@@ -1155,6 +1166,7 @@ namespace MobileGL::MG_Remote::Server {
|
||||
// DrainedRecords() one behind appliedSeq on 1 run in ~40 under `-j 8`.
|
||||
// Per-record, before the publish, it can never be behind.
|
||||
m_drained.fetch_add(1, std::memory_order_acq_rel);
|
||||
return true;
|
||||
},
|
||||
&corrupt);
|
||||
if (corrupt) {
|
||||
|
||||
@@ -663,6 +663,16 @@ int RunSession(std::unique_ptr<SocketTransport> control, std::vector<std::uint8_
|
||||
|
||||
const char* forwarding = std::getenv("MOBILEGL_IPC_LOG_FORWARD");
|
||||
if (tcp && (!forwarding || std::strcmp(forwarding, "0") != 0)) {
|
||||
// F2 fault injection: bound the kernel queue as well as the log queue so a
|
||||
// non-reading peer reliably blocks the sender, regardless of host autotuning.
|
||||
if (const char* stalled = std::getenv("MOBILEGL_TEST_LOG_SMALL_SNDBUF");
|
||||
stalled && std::strcmp(stalled, "1") == 0) {
|
||||
const int bytes = 16 * 1024;
|
||||
if (::setsockopt(control->StreamFd(), SOL_SOCKET, SO_SNDBUF, &bytes, sizeof(bytes)) != 0) {
|
||||
WireLogError("MG_Remote server: could not set F2 control send buffer");
|
||||
return endSession(70);
|
||||
}
|
||||
}
|
||||
// P9 W3: the forward is a queue with a sender thread of its own, graded by severity
|
||||
// (LogForward.h): a client that stops reading control no longer holds any logging thread -
|
||||
// the apply thread above all - inside a socket write.
|
||||
|
||||
@@ -274,7 +274,10 @@ namespace MobileGL::MG_Remote::Transport {
|
||||
for (;;) {
|
||||
// Announce, FENCE, then re-test. The fence is the mechanism -
|
||||
// see the file header - so setting the flag itself is relaxed.
|
||||
parked.store(1, std::memory_order_relaxed);
|
||||
// Release, so a notifier that acquires this 1 also sees what the waiter wrote
|
||||
// before parking (RingControl::producerWakeSeq). The fence below is still what
|
||||
// closes the lost-wakeup window.
|
||||
parked.store(1, std::memory_order_release);
|
||||
std::atomic_thread_fence(std::memory_order_seq_cst);
|
||||
if (ready()) {
|
||||
parked.store(0, std::memory_order_relaxed);
|
||||
|
||||
@@ -497,11 +497,24 @@ namespace MobileGL::MG_Remote::Transport {
|
||||
return m_selfBell->Dead() ? SessionWait::ShutDown : SessionWait::TimedOut;
|
||||
}
|
||||
|
||||
// The wake target for the duration of one wait; 0 again afterwards, so a later wait that
|
||||
// needs any progress (or one outside this class on the same flag) is rung as before.
|
||||
namespace {
|
||||
struct ScopedWakeTarget {
|
||||
std::atomic<std::uint64_t>& target;
|
||||
ScopedWakeTarget(std::atomic<std::uint64_t>& t, std::uint64_t seq) : target(t) {
|
||||
target.store(seq, std::memory_order_seq_cst);
|
||||
}
|
||||
~ScopedWakeTarget() { target.store(0, std::memory_order_seq_cst); }
|
||||
};
|
||||
} // namespace
|
||||
|
||||
SessionWait SessionProducer::WaitForApplied(std::uint64_t seq, std::uint32_t timeoutMs) {
|
||||
if (!Valid()) {
|
||||
return SessionWait::TimedOut;
|
||||
}
|
||||
RingControl* control = m_control;
|
||||
const ScopedWakeTarget wake(control->producerWakeSeq, seq);
|
||||
return Park([control, seq] { return Watermark::Reached(control->Progress.appliedSeq, seq); },
|
||||
timeoutMs);
|
||||
}
|
||||
@@ -527,6 +540,7 @@ namespace MobileGL::MG_Remote::Transport {
|
||||
return SessionWait::TimedOut;
|
||||
}
|
||||
RingControl* control = m_control;
|
||||
const ScopedWakeTarget wake(control->producerWakeSeq, seq);
|
||||
return Park(
|
||||
[control, seq] {
|
||||
return Watermark::Reached(control->Progress.appliedSeq, seq) ||
|
||||
@@ -670,7 +684,16 @@ namespace MobileGL::MG_Remote::Transport {
|
||||
void SessionConsumer::NotifyClient() {
|
||||
if (m_link) m_link->ProgressChanged();
|
||||
if (m_control != nullptr && m_peerBell != nullptr) {
|
||||
NotifyIfParked(*m_peerBell, m_control->producerParked);
|
||||
// NotifyIfParked, narrowed by the client's wake target: a client parked for an
|
||||
// applied sequence the server has not reached yet is not rung (unless the event
|
||||
// ring filled, which that wait also wakes for).
|
||||
std::atomic_thread_fence(std::memory_order_seq_cst);
|
||||
if (m_control->producerParked.load(std::memory_order_acquire) == 0) return;
|
||||
const std::uint64_t target = m_control->producerWakeSeq.load(std::memory_order_seq_cst);
|
||||
if (target != 0 && !Watermark::Reached(m_control->Progress.appliedSeq, target) &&
|
||||
m_control->eventRingFull.load(std::memory_order_acquire) == 0)
|
||||
return;
|
||||
m_peerBell->Notify();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -164,6 +164,16 @@ namespace MobileGL::MG_Remote::Transport {
|
||||
std::atomic<std::uint32_t> producerParked; // client asleep, server must ring
|
||||
std::atomic<std::uint32_t> eventRingFull; // SEG_EVENT full, server stopped applying
|
||||
std::atomic<std::uint32_t> eventDropped; // dropped lossy events
|
||||
|
||||
// ---- the parked producer's wake target -------------------------------
|
||||
//
|
||||
// What a parked client is waiting for, so the server rings only when it is there: 0 =
|
||||
// any progress (present credit, ring space, events), otherwise the appliedSeq it needs.
|
||||
// Without it every record the server applied while the client waited for a later one
|
||||
// was a socket write and a futile wake-up. Written by the client before it parks (and
|
||||
// reset to 0 after), read by the server only after it saw producerParked set; on a link
|
||||
// without this shared page it stays 0, which is the old ring-on-any-progress rule.
|
||||
alignas(64) std::atomic<std::uint64_t> producerWakeSeq;
|
||||
};
|
||||
|
||||
static_assert(sizeof(RingControl) == 4096, "RingControl must be exactly one page");
|
||||
@@ -232,6 +242,10 @@ namespace MobileGL::MG_Remote::Transport {
|
||||
// The page's real content must fit the page it claims. sizeof(RingControl) == 4096
|
||||
// above cannot catch a member that grew, because alignas(4096) forces that number;
|
||||
// the struct's content ends far short of it and the tail is padding.
|
||||
static_assert(offsetof(RingControl, producerWakeSeq) / 64 != offsetof(RingControl, serverEpoch) / 64,
|
||||
"the wake target has a line of its own");
|
||||
static_assert(offsetof(RingControl, producerWakeSeq) + sizeof(std::uint64_t) <= 4096,
|
||||
"RingControl's members must fit the page it claims to be");
|
||||
static_assert(offsetof(RingControl, eventDropped) + sizeof(std::uint32_t) <= 4096,
|
||||
"RingControl's members must fit the page it claims to be");
|
||||
static_assert(alignof(RingControl) == 4096, "RingControl must be page aligned");
|
||||
|
||||
@@ -73,6 +73,7 @@
|
||||
|
||||
#include <atomic>
|
||||
#include <cstdint>
|
||||
#include <type_traits>
|
||||
|
||||
namespace MobileGL::MG_Remote::Transport {
|
||||
|
||||
@@ -462,7 +463,14 @@ namespace MobileGL::MG_Remote::Transport {
|
||||
if (!m_cmd->Pop(view, outCorrupt)) {
|
||||
return false;
|
||||
}
|
||||
apply(view);
|
||||
// A terminal rejection after Pop must not acknowledge an unapplied record.
|
||||
// A bool callback returning false ends this consumer's session; it cannot retry
|
||||
// the popped record. Existing void callbacks retain their original semantics.
|
||||
if constexpr (std::is_same_v<std::invoke_result_t<Apply, const RingRecordView&>, bool>) {
|
||||
if (!apply(view)) return false;
|
||||
} else {
|
||||
apply(view);
|
||||
}
|
||||
++m_appliedSeq;
|
||||
Watermark::AdvanceApplied(*m_control, m_appliedSeq);
|
||||
m_cmd->PublishApplied();
|
||||
|
||||
@@ -187,4 +187,26 @@ namespace MobileGL::MG_State::GLState {
|
||||
Bool ShareGroupState::ValidateRenderbufferObject(Uint index) const {
|
||||
return m_renderbufferObjects.find(index) != m_renderbufferObjects.end();
|
||||
}
|
||||
UniquePtr<BufferObject> ShareGroupState::TakeClientArrayBuffer() {
|
||||
const std::lock_guard<std::mutex> lock(m_clientArrayBuffersMutex);
|
||||
if (m_clientArrayBuffers.empty()) return nullptr;
|
||||
UniquePtr<BufferObject> buffer = std::move(m_clientArrayBuffers.back());
|
||||
m_clientArrayBuffers.pop_back();
|
||||
return buffer;
|
||||
}
|
||||
|
||||
void ShareGroupState::ReturnClientArrayBuffer(UniquePtr<BufferObject> buffer) {
|
||||
// Enough for a draw's every attribute plus its indices; more is never in use at once.
|
||||
constexpr SizeT kKeptClientArrayBuffers = 48;
|
||||
if (!buffer) return;
|
||||
{
|
||||
const std::lock_guard<std::mutex> lock(m_clientArrayBuffersMutex);
|
||||
if (m_clientArrayBuffers.size() < kKeptClientArrayBuffers) {
|
||||
m_clientArrayBuffers.push_back(std::move(buffer));
|
||||
return;
|
||||
}
|
||||
}
|
||||
// A surplus buffer is destroyed outside the lock (its destructor emits).
|
||||
}
|
||||
|
||||
} // namespace MobileGL::MG_State::GLState
|
||||
@@ -8,6 +8,7 @@
|
||||
|
||||
#pragma once
|
||||
#include <Includes.h>
|
||||
#include <mutex>
|
||||
#include <MG_Util/Miscellany/IndexGenerator.h>
|
||||
#include "BufferState/BufferObject.h"
|
||||
#include "ProgramState/ProgramState.h"
|
||||
@@ -67,6 +68,12 @@ namespace MobileGL::MG_State::GLState {
|
||||
ProgramState& Programs() { return m_programState; }
|
||||
const ProgramState& Programs() const { return m_programState; }
|
||||
|
||||
// Unnamed buffers that carried a draw's client-memory arrays, kept for the next such draw
|
||||
// so it respecifies one of them (a non-blocking record) instead of creating a resource
|
||||
// (a round trip) and destroying it again. Buffers are share-group objects, hence here.
|
||||
UniquePtr<BufferObject> TakeClientArrayBuffer();
|
||||
void ReturnClientArrayBuffer(UniquePtr<BufferObject> buffer);
|
||||
|
||||
private:
|
||||
Uint64 m_token = 0;
|
||||
UnorderedMap<Uint, SharedPtr<BufferObject>> m_bufferObjects;
|
||||
@@ -77,5 +84,7 @@ namespace MobileGL::MG_State::GLState {
|
||||
IndexGenerator<Uint> m_renderbufferNames{1024, 1};
|
||||
SamplerState m_samplerState;
|
||||
ProgramState m_programState;
|
||||
std::mutex m_clientArrayBuffersMutex;
|
||||
Vector<UniquePtr<BufferObject>> m_clientArrayBuffers;
|
||||
};
|
||||
} // namespace MobileGL::MG_State::GLState
|
||||
@@ -1590,6 +1590,19 @@ TEST(ComputeWorkGroupCapabilities, TakesEveryAxisFromTheIndexedQuery) {
|
||||
}
|
||||
|
||||
namespace {
|
||||
const char* g_damageExtensions = nullptr;
|
||||
EGLDisplay g_damageDisplay = EGL_NO_DISPLAY;
|
||||
bool g_damageExtAvailable = false;
|
||||
bool g_damageKhrAvailable = false;
|
||||
std::vector<std::string> g_damageQueries;
|
||||
|
||||
EGLDisplay FakeDamageDisplay() { return g_damageDisplay; }
|
||||
const char* FakeDamageQueryString(EGLDisplay display, EGLint name) {
|
||||
EXPECT_EQ(display, g_damageDisplay);
|
||||
EXPECT_EQ(name, EGL_EXTENSIONS);
|
||||
return g_damageExtensions;
|
||||
}
|
||||
|
||||
EGLBoolean FakeSwapBuffersWithDamage(EGLDisplay dpy, EGLSurface surface, const EGLint* rects, EGLint nRects) {
|
||||
(void)dpy;
|
||||
(void)surface;
|
||||
@@ -1597,6 +1610,14 @@ namespace {
|
||||
(void)nRects;
|
||||
return EGL_TRUE;
|
||||
}
|
||||
|
||||
__eglMustCastToProperFunctionPointerType FakeDamageGetProcAddress(const char* name) {
|
||||
g_damageQueries.emplace_back(name);
|
||||
const bool available = std::string(name) == "eglSwapBuffersWithDamageEXT"
|
||||
? g_damageExtAvailable : g_damageKhrAvailable;
|
||||
return available ? reinterpret_cast<__eglMustCastToProperFunctionPointerType>(&FakeSwapBuffersWithDamage)
|
||||
: nullptr;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
// EXT -> KHR -> nothing, the whole policy behind the loader's single damage-present slot.
|
||||
@@ -1609,13 +1630,46 @@ namespace {
|
||||
// call to either spelling is defined to be equivalent to that anyway.
|
||||
TEST(SwapBuffersWithDamageResolution, PrefersExtThenKhrThenAnswersNothing) {
|
||||
using namespace MobileGL;
|
||||
MG_External::EGL::eglSwapBuffersWithDamageEXT_PTR ext = &FakeSwapBuffersWithDamage;
|
||||
MG_External::EGL::eglSwapBuffersWithDamageKHR_PTR khr = &FakeSwapBuffersWithDamage;
|
||||
MG_External::EGLFunctionsTable funcs{};
|
||||
funcs.eglGetCurrentDisplay = &FakeDamageDisplay;
|
||||
funcs.eglQueryString = &FakeDamageQueryString;
|
||||
funcs.eglGetProcAddress = &FakeDamageGetProcAddress;
|
||||
g_damageDisplay = reinterpret_cast<EGLDisplay>(1);
|
||||
g_damageExtensions = "EGL_EXT_swap_buffers_with_damage EGL_KHR_swap_buffers_with_damage";
|
||||
g_damageExtAvailable = g_damageKhrAvailable = true;
|
||||
g_damageQueries.clear();
|
||||
EXPECT_EQ(MG_Util::BackendLoader::ResolveSwapBuffersWithDamage(funcs), &FakeSwapBuffersWithDamage);
|
||||
EXPECT_EQ(g_damageQueries, (std::vector<std::string>{"eglSwapBuffersWithDamageEXT"}));
|
||||
|
||||
EXPECT_EQ(MG_Util::BackendLoader::ResolveSwapBuffersWithDamage(ext, khr), ext)
|
||||
<< "a driver that exports both spellings is answered with the EXT one";
|
||||
EXPECT_EQ(MG_Util::BackendLoader::ResolveSwapBuffersWithDamage(nullptr, khr), khr)
|
||||
<< "the KHR spelling alone must still fill the slot";
|
||||
EXPECT_EQ(MG_Util::BackendLoader::ResolveSwapBuffersWithDamage(nullptr, nullptr), nullptr)
|
||||
<< "neither spelling stays null, so the caller keeps eglSwapBuffers";
|
||||
g_damageExtAvailable = false;
|
||||
g_damageQueries.clear();
|
||||
EXPECT_EQ(MG_Util::BackendLoader::ResolveSwapBuffersWithDamage(funcs), &FakeSwapBuffersWithDamage);
|
||||
EXPECT_EQ(g_damageQueries, (std::vector<std::string>{"eglSwapBuffersWithDamageEXT", "eglSwapBuffersWithDamageKHR"}));
|
||||
|
||||
g_damageExtensions = "EGL_KHR_swap_buffers_with_damage";
|
||||
g_damageQueries.clear();
|
||||
EXPECT_EQ(MG_Util::BackendLoader::ResolveSwapBuffersWithDamage(funcs), &FakeSwapBuffersWithDamage);
|
||||
EXPECT_EQ(g_damageQueries, (std::vector<std::string>{"eglSwapBuffersWithDamageKHR"}));
|
||||
|
||||
g_damageKhrAvailable = false;
|
||||
EXPECT_EQ(MG_Util::BackendLoader::ResolveSwapBuffersWithDamage(funcs), nullptr);
|
||||
|
||||
g_damageExtensions = "EGL_EXT_swap_buffers_with_damage";
|
||||
g_damageQueries.clear();
|
||||
g_damageKhrAvailable = true;
|
||||
EXPECT_EQ(MG_Util::BackendLoader::ResolveSwapBuffersWithDamage(funcs), nullptr);
|
||||
EXPECT_EQ(g_damageQueries, (std::vector<std::string>{"eglSwapBuffersWithDamageEXT"}));
|
||||
|
||||
g_damageExtAvailable = true;
|
||||
for (const char* extensions : {"", "EGL_EXT_swap_buffers_with_damage_extra", static_cast<const char*>(nullptr)}) {
|
||||
g_damageExtensions = extensions;
|
||||
g_damageQueries.clear();
|
||||
EXPECT_EQ(MG_Util::BackendLoader::ResolveSwapBuffersWithDamage(funcs), nullptr);
|
||||
EXPECT_TRUE(g_damageQueries.empty());
|
||||
}
|
||||
g_damageExtensions = "EGL_EXT_swap_buffers_with_damage EGL_KHR_swap_buffers_with_damage";
|
||||
g_damageDisplay = EGL_NO_DISPLAY;
|
||||
g_damageQueries.clear();
|
||||
EXPECT_EQ(MG_Util::BackendLoader::ResolveSwapBuffersWithDamage(funcs), nullptr);
|
||||
EXPECT_TRUE(g_damageQueries.empty());
|
||||
}
|
||||
@@ -123,11 +123,17 @@ TEST_F(ProgramUtilTest, UnformattedFloatStorageImagesKeepIntegerAtomicImagesType
|
||||
layout(local_size_x = 1, local_size_y = 1, local_size_z = 1) in;
|
||||
layout(rgba16, binding = 0) uniform image2D floatImage;
|
||||
layout(r32ui, binding = 1) uniform uimage2D atomicImage;
|
||||
layout(rgba32f, binding = 2) uniform image2D otherFloatImages[2];
|
||||
layout(std430, binding = 3) buffer Output0 { uint value0; };
|
||||
layout(std430, binding = 4) buffer Output1 { uint value1; };
|
||||
|
||||
void main() {
|
||||
ivec2 coordinate = ivec2(gl_GlobalInvocationID.xy);
|
||||
imageStore(floatImage, coordinate, imageLoad(floatImage, coordinate));
|
||||
imageStore(otherFloatImages[1], coordinate, imageLoad(otherFloatImages[0], coordinate));
|
||||
imageAtomicAdd(atomicImage, coordinate, 1u);
|
||||
value0 = 11u;
|
||||
value1 = 22u;
|
||||
}
|
||||
)";
|
||||
|
||||
@@ -174,6 +180,12 @@ void main() {
|
||||
<< outputText;
|
||||
EXPECT_EQ(countOccurrences(outputText, "OpCapability StorageImageWriteWithoutFormat"), 1u)
|
||||
<< outputText;
|
||||
EXPECT_EQ(countOccurrences(outputText, "2D 0 0 0 2 Unknown"), 1u) << outputText;
|
||||
EXPECT_NE(outputText.find("Binding 0"), String::npos) << outputText;
|
||||
EXPECT_NE(outputText.find("Binding 1"), String::npos) << outputText;
|
||||
EXPECT_NE(outputText.find("Binding 2"), String::npos) << outputText;
|
||||
EXPECT_NE(outputText.find("\"Output0\""), String::npos) << outputText;
|
||||
EXPECT_NE(outputText.find("\"Output1\""), String::npos) << outputText;
|
||||
EXPECT_TRUE(tools.Validate(outputBinary));
|
||||
|
||||
Vector<Uint32> secondOutputBinary;
|
||||
@@ -181,6 +193,67 @@ void main() {
|
||||
EXPECT_EQ(secondOutputBinary, outputBinary);
|
||||
}
|
||||
|
||||
TEST_F(ProgramUtilTest, LowerRectImagesMergesWithExisting2DImageTypes) {
|
||||
using namespace MG_Util::ShaderTranspiler;
|
||||
const String spirvText = R"(
|
||||
OpCapability Shader
|
||||
OpCapability ImageRect
|
||||
OpMemoryModel Logical GLSL450
|
||||
OpEntryPoint GLCompute %main "main"
|
||||
OpExecutionMode %main LocalSize 1 1 1
|
||||
OpName %Output0 "Output0"
|
||||
OpName %Output1 "Output1"
|
||||
OpDecorate %Output0 Block
|
||||
OpDecorate %Output1 Block
|
||||
OpMemberDecorate %Output0 0 Offset 0
|
||||
OpMemberDecorate %Output1 0 Offset 0
|
||||
OpDecorate %buffer0 DescriptorSet 0
|
||||
OpDecorate %buffer0 Binding 2
|
||||
OpDecorate %buffer1 DescriptorSet 0
|
||||
OpDecorate %buffer1 Binding 3
|
||||
OpDecorate %rect DescriptorSet 0
|
||||
OpDecorate %rect Binding 0
|
||||
OpDecorate %flat DescriptorSet 0
|
||||
OpDecorate %flat Binding 1
|
||||
%void = OpTypeVoid
|
||||
%uint = OpTypeInt 32 0
|
||||
%Output0 = OpTypeStruct %uint
|
||||
%Output1 = OpTypeStruct %uint
|
||||
%outputPtr0 = OpTypePointer StorageBuffer %Output0
|
||||
%outputPtr1 = OpTypePointer StorageBuffer %Output1
|
||||
%buffer0 = OpVariable %outputPtr0 StorageBuffer
|
||||
%buffer1 = OpVariable %outputPtr1 StorageBuffer
|
||||
%rectType = OpTypeImage %uint Rect 0 0 0 2 R32ui
|
||||
%flatType = OpTypeImage %uint 2D 0 0 0 2 R32ui
|
||||
%rectPtr = OpTypePointer UniformConstant %rectType
|
||||
%flatPtr = OpTypePointer UniformConstant %flatType
|
||||
%rect = OpVariable %rectPtr UniformConstant
|
||||
%flat = OpVariable %flatPtr UniformConstant
|
||||
%mainType = OpTypeFunction %void
|
||||
%main = OpFunction %void None %mainType
|
||||
%entry = OpLabel
|
||||
%r = OpLoad %rectType %rect
|
||||
%f = OpLoad %flatType %flat
|
||||
OpReturn
|
||||
OpFunctionEnd
|
||||
)";
|
||||
spvtools::SpirvTools tools(SPV_ENV_VULKAN_1_1);
|
||||
Vector<Uint32> inputBinary;
|
||||
ASSERT_TRUE(tools.Assemble(spirvText, &inputBinary));
|
||||
Vector<Uint32> outputBinary;
|
||||
ASSERT_TRUE(ShaderCompiler::LowerRectImages(inputBinary, outputBinary));
|
||||
EXPECT_TRUE(tools.Validate(outputBinary));
|
||||
String outputText;
|
||||
ASSERT_TRUE(tools.Disassemble(outputBinary, &outputText));
|
||||
EXPECT_NE(outputText.find("Binding 0"), String::npos);
|
||||
EXPECT_NE(outputText.find("Binding 1"), String::npos);
|
||||
const auto firstImage = outputText.find("OpTypeImage");
|
||||
ASSERT_NE(firstImage, String::npos);
|
||||
EXPECT_EQ(outputText.find("OpTypeImage", firstImage + 1), String::npos);
|
||||
EXPECT_NE(outputText.find("\"Output0\""), String::npos) << outputText;
|
||||
EXPECT_NE(outputText.find("\"Output1\""), String::npos) << outputText;
|
||||
}
|
||||
|
||||
TEST_F(ProgramUtilTest, UnformattedFloatStorageImagesKeepFloatAtomicImageTypesTyped) {
|
||||
using namespace MG_Util::ShaderTranspiler;
|
||||
|
||||
|
||||
@@ -141,7 +141,7 @@ namespace {
|
||||
// F2 (P9 W3). The flood: kFloodRecords records published while the peer reads nothing, each of
|
||||
// which makes the server's apply thread log kFloodWarnLinesPerRecord WARN lines of ~650 bytes and
|
||||
// one ERROR line (ServerLoop.cpp, MOBILEGL_TEST_APPLY_LOG_FLOOD) - about 16 MiB, against a
|
||||
// server send buffer this host caps at 4 MiB and a forward queue of 1 MiB for <= WARN.
|
||||
// deliberately small server send buffer and a forward queue of 1 MiB for <= WARN.
|
||||
constexpr std::uint32_t kFloodWarnLinesPerRecord = 64;
|
||||
constexpr std::uint32_t kFloodRecords = 400;
|
||||
// THE PEER'S RECEIVE BUFFER WHILE IT IS NOT READING. Without this the kernel absorbs the flood
|
||||
@@ -225,7 +225,10 @@ namespace {
|
||||
env.emplace_back("MOBILEGL_IPC_ROLE=server");
|
||||
env.emplace_back("MOBILEGL_IPC_DIAL=no");
|
||||
env.emplace_back(forwardLog ? "MOBILEGL_IPC_LOG_FORWARD=1" : "MOBILEGL_IPC_LOG_FORWARD=0");
|
||||
if (floodLines != 0) env.emplace_back("MOBILEGL_TEST_APPLY_LOG_FLOOD=" + std::to_string(floodLines));
|
||||
if (floodLines != 0) {
|
||||
env.emplace_back("MOBILEGL_TEST_APPLY_LOG_FLOOD=" + std::to_string(floodLines));
|
||||
env.emplace_back("MOBILEGL_TEST_LOG_SMALL_SNDBUF=1");
|
||||
}
|
||||
env.emplace_back(WaitKnobEntry(waitMs));
|
||||
env.emplace_back("MOBILEGL_LOG_FILE_PATH=" + logBase);
|
||||
const std::string image = ServerImage();
|
||||
@@ -358,6 +361,7 @@ namespace {
|
||||
// F2 (P9 W3).
|
||||
kNoControlReader = 22,
|
||||
kFloodPublish = 23,
|
||||
kControlBuffer = 24,
|
||||
};
|
||||
|
||||
// A pbuffer context on the server's apply thread, through the same forwarders
|
||||
@@ -381,11 +385,19 @@ namespace {
|
||||
// kFloodRecords set_patch_state records are published without waiting. set_patch_state because it
|
||||
// is pure applier state: no GL call, no reply, no event, so the only thing each one produces on
|
||||
// the server is the flood's log lines.
|
||||
int StopReadingControlAndFlood(Client::ClientSession& client) {
|
||||
int StopReadingControlAndFlood(Client::ClientSession& client, int& originalReceiveBuffer) {
|
||||
auto* control = client.ControlSocketForTest();
|
||||
if (control == nullptr) return kNoControlReader;
|
||||
socklen_t size = sizeof(originalReceiveBuffer);
|
||||
if (::getsockopt(control->StreamFd(), SOL_SOCKET, SO_RCVBUF, &originalReceiveBuffer, &size) != 0)
|
||||
return kControlBuffer;
|
||||
#if defined(__linux__)
|
||||
// Linux reports twice the SO_RCVBUF request, including bookkeeping space.
|
||||
originalReceiveBuffer /= 2;
|
||||
#endif
|
||||
const int receiveBuffer = kStalledReceiveBufferBytes;
|
||||
(void)::setsockopt(control->StreamFd(), SOL_SOCKET, SO_RCVBUF, &receiveBuffer, sizeof(receiveBuffer));
|
||||
if (::setsockopt(control->StreamFd(), SOL_SOCKET, SO_RCVBUF, &receiveBuffer, sizeof(receiveBuffer)) != 0)
|
||||
return kControlBuffer;
|
||||
if (!client.PauseControlReaderForTest(true)) return kNoControlReader;
|
||||
for (std::uint32_t i = 0; i < kFloodRecords; ++i) {
|
||||
MGP::MGPPatchState patch{};
|
||||
@@ -900,13 +912,16 @@ namespace {
|
||||
ConfigureClient(control);
|
||||
auto& client = Client::ClientSessionInstance();
|
||||
if (client.StartSpawned() != MOBILEGL_OK) ::_exit(kNoWelcome);
|
||||
int originalReceiveBuffer = 0;
|
||||
if (alsoStopDraining) {
|
||||
const int filled = FillTheEventRingWithoutDraining(client, [&client] { return StopReadingControlAndFlood(client); });
|
||||
const int filled = FillTheEventRingWithoutDraining(client, [&] {
|
||||
return StopReadingControlAndFlood(client, originalReceiveBuffer);
|
||||
});
|
||||
if (filled != kChildOk) ::_exit(filled);
|
||||
} else {
|
||||
const int up = BringUpPbufferContext();
|
||||
if (up != kChildOk) ::_exit(up);
|
||||
const int flooded = StopReadingControlAndFlood(client);
|
||||
const int flooded = StopReadingControlAndFlood(client, originalReceiveBuffer);
|
||||
if (flooded != kChildOk) ::_exit(flooded);
|
||||
}
|
||||
const char one = 1;
|
||||
@@ -914,7 +929,11 @@ namespace {
|
||||
char go = 0;
|
||||
(void)::read(release, &go, 1);
|
||||
if (alsoStopDraining) ::_exit(kChildOk);
|
||||
client.PauseControlReaderForTest(false);
|
||||
// End the receive-window fault before waiting for the ack behind the queued logs.
|
||||
if (::setsockopt(client.ControlSocketForTest()->StreamFd(), SOL_SOCKET, SO_RCVBUF,
|
||||
&originalReceiveBuffer, sizeof(originalReceiveBuffer)) != 0)
|
||||
::_exit(kControlBuffer);
|
||||
if (!client.PauseControlReaderForTest(false)) ::_exit(kNoControlReader);
|
||||
client.SyncPeerLog();
|
||||
(void)::write(synced, &one, 1);
|
||||
(void)::read(release, &go, 1);
|
||||
|
||||
@@ -322,12 +322,13 @@ namespace {
|
||||
EXPECT_EQ(r.glxLoaded, 1);
|
||||
EXPECT_EQ(r.clientQueries, 1);
|
||||
|
||||
// A process that asked for software rendering is left to the system's other GL, server or not.
|
||||
// Mesa's software-renderer selection must not disable MobileGL's EGL/GLX entry points.
|
||||
const EntryReport software = RunEntryPoints(server.endpoint, logBase, true);
|
||||
EXPECT_EQ(software.vendorDisplay, 0);
|
||||
EXPECT_EQ(software.getDisplay, 0);
|
||||
EXPECT_EQ(software.vendorDevices, 0);
|
||||
EXPECT_EQ(software.glxLoaded, 0);
|
||||
EXPECT_EQ(software.vendorDisplay, 1);
|
||||
EXPECT_EQ(software.getDisplay, 1);
|
||||
EXPECT_EQ(software.vendorDevices, 1);
|
||||
EXPECT_EQ(software.glxLoaded, 1);
|
||||
EXPECT_EQ(software.clientQueries, 1);
|
||||
std::error_code ec;
|
||||
std::filesystem::remove(Debug::RoleLogPath(logBase.c_str(), Debug::LogRole::Client), ec);
|
||||
}
|
||||
|
||||
@@ -470,6 +470,23 @@ TEST(SessionTest, AppliedSeqAdvancesExactlyOncePerRecordAndIsNeverBatched) {
|
||||
EXPECT_EQ(applied, kRecords);
|
||||
}
|
||||
|
||||
TEST(SessionTest, TerminalApplyRejectionDoesNotAcknowledgeTheRecord) {
|
||||
SessionFixture session;
|
||||
ASSERT_TRUE(session.Build(TestSizes()));
|
||||
ASSERT_NE(session.cmdProducer.Reserve(1, kRecNone, 8), nullptr);
|
||||
ASSERT_NE(session.cmdProducer.Reserve(1, kRecNone, 8), nullptr);
|
||||
session.producer.PublishAndNotify(2);
|
||||
ASSERT_TRUE(session.consumer.ApplyOne([](const RingRecordView&) { return true; }));
|
||||
bool checked = false;
|
||||
EXPECT_FALSE(session.consumer.ApplyOne([&](const RingRecordView&) {
|
||||
checked = true;
|
||||
return false;
|
||||
}));
|
||||
EXPECT_TRUE(checked);
|
||||
EXPECT_EQ(session.consumer.AppliedSeq(), 1u);
|
||||
EXPECT_EQ(session.Control().Progress.appliedSeq.load(), 1u);
|
||||
}
|
||||
|
||||
// retiredSeq: advanced once the SEG_STAGE bytes a record referenced are finished with, and the
|
||||
// staging allocator reclaims behind it. Late is merely slow; EARLY hands live bytes back to the
|
||||
// producer, so the advance clamps to appliedSeq rather than believing its caller.
|
||||
|
||||
@@ -21,6 +21,17 @@
|
||||
#endif
|
||||
|
||||
namespace MobileGL::MG_Util::BackendLoader {
|
||||
Bool HasExtensionWord(const char* list, const char* word) {
|
||||
if (list == nullptr || word == nullptr || *word == '\0') return false;
|
||||
const SizeT n = std::strlen(word);
|
||||
for (const char* at = std::strstr(list, word); at != nullptr; at = std::strstr(at + 1, word)) {
|
||||
const Bool startOk = at == list || at[-1] == ' ';
|
||||
const Bool endOk = at[n] == '\0' || at[n] == ' ';
|
||||
if (startOk && endOk) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
static Bool UseAngle() {
|
||||
return MG_Config::Features.EsprytUseAngle;
|
||||
}
|
||||
@@ -170,12 +181,30 @@ namespace MobileGL::MG_Util::BackendLoader {
|
||||
}
|
||||
|
||||
MG_External::EGL::eglSwapBuffersWithDamageEXT_PTR
|
||||
ResolveSwapBuffersWithDamage(MG_External::EGL::eglSwapBuffersWithDamageEXT_PTR ext,
|
||||
MG_External::EGL::eglSwapBuffersWithDamageKHR_PTR khr) {
|
||||
if (ext != nullptr) {
|
||||
return ext;
|
||||
ResolveSwapBuffersWithDamage(const MG_External::EGLFunctionsTable& funcs) {
|
||||
if (!funcs.eglGetCurrentDisplay || !funcs.eglQueryString || !funcs.eglGetProcAddress) {
|
||||
return nullptr;
|
||||
}
|
||||
return (MG_External::EGL::eglSwapBuffersWithDamageEXT_PTR)khr;
|
||||
const EGLDisplay display = funcs.eglGetCurrentDisplay();
|
||||
if (display == EGL_NO_DISPLAY) {
|
||||
return nullptr;
|
||||
}
|
||||
const char* extensions = funcs.eglQueryString(display, EGL_EXTENSIONS);
|
||||
if (HasExtensionWord(extensions, "EGL_EXT_swap_buffers_with_damage")) {
|
||||
auto ext = reinterpret_cast<MG_External::EGL::eglSwapBuffersWithDamageEXT_PTR>(
|
||||
funcs.eglGetProcAddress("eglSwapBuffersWithDamageEXT"));
|
||||
if (ext != nullptr) {
|
||||
return ext;
|
||||
}
|
||||
}
|
||||
if (HasExtensionWord(extensions, "EGL_KHR_swap_buffers_with_damage")) {
|
||||
auto khr = reinterpret_cast<MG_External::EGL::eglSwapBuffersWithDamageKHR_PTR>(
|
||||
funcs.eglGetProcAddress("eglSwapBuffersWithDamageKHR"));
|
||||
if (khr != nullptr) {
|
||||
return khr;
|
||||
}
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
void AcquireGLESFunctions(MG_External::GLESFunctionsTable& funcs,
|
||||
@@ -806,25 +835,8 @@ namespace MobileGL::MG_Util::BackendLoader {
|
||||
INIT_EGL_FUNC(eglWaitSync)
|
||||
}
|
||||
|
||||
{
|
||||
// One slot, two names. EGL_EXT_swap_buffers_with_damage and
|
||||
// EGL_KHR_swap_buffers_with_damage define the same entry point with the same
|
||||
// signature, and a driver may expose either, both or neither - Adreno exposes only
|
||||
// the KHR spelling - so the winner of the EXT -> KHR chain lands in the EXT slot.
|
||||
// Null when the driver offers neither, which is the normal "no damage-based present
|
||||
// here" answer: the caller keeps plain eglSwapBuffers (and note that a call with
|
||||
// n_rects == 0 is defined to be equivalent to eglSwapBuffers anyway).
|
||||
funcs.eglSwapBuffersWithDamageEXT = ResolveSwapBuffersWithDamage(
|
||||
reinterpret_cast<MG_External::EGL::eglSwapBuffersWithDamageEXT_PTR>(
|
||||
resolveEGLProc("eglSwapBuffersWithDamageEXT")),
|
||||
reinterpret_cast<MG_External::EGL::eglSwapBuffersWithDamageKHR_PTR>(
|
||||
resolveEGLProc("eglSwapBuffersWithDamageKHR")));
|
||||
if (funcs.eglSwapBuffersWithDamageEXT == nullptr) {
|
||||
MGLOG_I_ONCE("This driver has no damage-based present entry point (neither "
|
||||
"eglSwapBuffersWithDamageEXT nor eglSwapBuffersWithDamageKHR); "
|
||||
"present calls fall back to eglSwapBuffers");
|
||||
}
|
||||
}
|
||||
// Display extensions can only be checked after the display is initialized.
|
||||
funcs.eglSwapBuffersWithDamageEXT = nullptr;
|
||||
}
|
||||
|
||||
// Detects whether indirect draws leak the command's baseInstance word ("reserved, must
|
||||
|
||||
@@ -124,7 +124,7 @@ namespace MobileGL {
|
||||
EGL_FUNC_DECL(eglSurfaceAttrib)
|
||||
EGL_FUNC_DECL(eglSwapBuffers)
|
||||
// Holds whichever spelling of the damage-based present the driver provided, EXT
|
||||
// preferred; null when it provides neither (see AcquireEGLFunctions).
|
||||
// preferred; resolved after making the display current.
|
||||
EGL_FUNC_DECL(eglSwapBuffersWithDamageEXT)
|
||||
EGL_FUNC_DECL(eglSwapInterval)
|
||||
EGL_FUNC_DECL(eglTerminate)
|
||||
@@ -1364,17 +1364,19 @@ namespace MobileGL {
|
||||
} // namespace MG_External
|
||||
|
||||
namespace MG_Util::BackendLoader {
|
||||
// Match a complete name in a space-separated GLES/EGL extension string.
|
||||
Bool HasExtensionWord(const char* list, const char* word);
|
||||
void AcquireGLESFunctions(MG_External::GLESFunctionsTable& funcs,
|
||||
MG_External::EGL::eglGetProcAddress_PTR procAddress);
|
||||
void AcquireEGLFunctions(MG_External::EGLFunctionsTable& funcs);
|
||||
// The EXT -> KHR -> nothing chain for the damage-based present entry point. A null
|
||||
// Query the current display's extensions before resolving EXT -> KHR -> nothing.
|
||||
// Requires a current, initialized EGL display. A null
|
||||
// result is not a failure: it means this driver offers neither spelling, and the
|
||||
// caller presents with plain eglSwapBuffers, which a zero-rectangle call to either
|
||||
// spelling is defined to be equivalent to anyway. Exposed so MG_Test can pin the
|
||||
// preference order without a driver.
|
||||
MG_External::EGL::eglSwapBuffersWithDamageEXT_PTR
|
||||
ResolveSwapBuffersWithDamage(MG_External::EGL::eglSwapBuffersWithDamageEXT_PTR ext,
|
||||
MG_External::EGL::eglSwapBuffersWithDamageKHR_PTR khr);
|
||||
ResolveSwapBuffersWithDamage(const MG_External::EGLFunctionsTable& funcs);
|
||||
Bool FillInGLESCapabilities(MG_External::GLESCapabilities& caps,
|
||||
const MG_External::GLESFunctionsTable& glesFuncs);
|
||||
// Detects whether indirect draws leak the command's baseInstance word into
|
||||
|
||||
@@ -38,6 +38,7 @@
|
||||
#include "SpirvPasses/FixIterationRPBarrierPass.h"
|
||||
#include "SpirvPasses/FixIterationRPSubgroupScratchPass.h"
|
||||
#include "SpirvPasses/NormalizeRectCoordinatesPass.h"
|
||||
#include "SpirvPasses/DeduplicateImageTypesPass.h"
|
||||
#include "SpirvPasses/Lower1DArrayImagesPass.h"
|
||||
#include "SpirvPasses/Lower1DSampledImagesPass.h"
|
||||
#include "SpirvPasses/BakeImageFormatsPass.h"
|
||||
@@ -1813,6 +1814,8 @@ namespace MobileGL {
|
||||
using namespace spvtools;
|
||||
Optimizer optimizer(SPV_ENV_VULKAN_1_1);
|
||||
optimizer.RegisterPass(NormalizeRectCoordinatesPass::CreateNormalizeRectCoordinatesPass());
|
||||
// Rect and 2D images of the same format become the same type after lowering.
|
||||
optimizer.RegisterPass(DeduplicateImageTypesPass::Create());
|
||||
|
||||
return RunOptimizerChecked("LowerRectImages", optimizer, inputBinary, outputBinary, true, enableSpirvValidation);
|
||||
}
|
||||
@@ -2103,11 +2106,13 @@ namespace MobileGL {
|
||||
}
|
||||
outputBinary.insert(outputBinary.begin() + static_cast<std::ptrdiff_t>(capabilityInsertOffset),
|
||||
addedCapabilities.begin(), addedCapabilities.end());
|
||||
// Hand-rolled word walk, so no Optimizer wrapper ever sees this rewrite;
|
||||
// check the modified module explicitly in validating lanes.
|
||||
ValidateOrLatch("UseUnformattedFloatStorageImagesForVulkan", outputBinary,
|
||||
enableSpirvValidation);
|
||||
return true;
|
||||
// Erasing the format can make distinct image types identical. Use the same
|
||||
// image-only cleanup as rectangle lowering; named blocks retain their identity.
|
||||
spvtools::Optimizer optimizer(SPV_ENV_VULKAN_1_1);
|
||||
optimizer.RegisterPass(DeduplicateImageTypesPass::Create());
|
||||
Vector<Uint32> rewrittenBinary = std::move(outputBinary);
|
||||
return RunOptimizerChecked("UseUnformattedFloatStorageImagesForVulkan", optimizer,
|
||||
rewrittenBinary, outputBinary, true, enableSpirvValidation);
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
// MobileGL - MobileGL/MG_Util/ShaderTranspiler/SpirvPasses/DeduplicateImageTypesPass.cpp
|
||||
// Copyright (c) 2025-2026 MobileGL-Dev
|
||||
// Licensed under the GNU Lesser General Public License v3.0:
|
||||
// https://www.gnu.org/licenses/gpl-3.0.txt
|
||||
// https://www.gnu.org/licenses/lgpl-3.0.txt
|
||||
// SPDX-License-Identifier: LGPL-3.0-only
|
||||
// End of Source File Header
|
||||
|
||||
#include "DeduplicateImageTypesPass.h"
|
||||
#include "source/opt/decoration_manager.h"
|
||||
#include "source/opt/ir_context.h"
|
||||
#include "source/util/make_unique.h"
|
||||
#include <map>
|
||||
#include <unordered_set>
|
||||
#include <vector>
|
||||
|
||||
namespace MobileGL::MG_Util::ShaderTranspiler {
|
||||
spvtools::opt::Pass::Status DeduplicateImageTypesPass::Process() {
|
||||
using spvtools::opt::Instruction;
|
||||
std::unordered_set<uint32_t> imageTypes;
|
||||
std::map<std::vector<uint32_t>, std::vector<Instruction*>> canonical;
|
||||
std::vector<Instruction*> duplicates;
|
||||
for (auto& type : context()->types_values()) {
|
||||
bool imageRelated = false;
|
||||
switch (type.opcode()) {
|
||||
case spv::Op::OpTypeImage:
|
||||
imageRelated = true;
|
||||
break;
|
||||
case spv::Op::OpTypeSampledImage:
|
||||
case spv::Op::OpTypeArray:
|
||||
case spv::Op::OpTypeRuntimeArray:
|
||||
case spv::Op::OpTypePointer:
|
||||
case spv::Op::OpTypeFunction:
|
||||
type.ForEachInId([&](const uint32_t* id) {
|
||||
imageRelated |= imageTypes.count(*id) != 0;
|
||||
});
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
if (!imageRelated) continue;
|
||||
imageTypes.insert(type.result_id());
|
||||
|
||||
// Compare operand IDs, not structural equivalence. Distinct struct IDs
|
||||
// must never collapse just because their member layouts happen to match.
|
||||
std::vector<uint32_t> key{static_cast<uint32_t>(type.opcode())};
|
||||
for (uint32_t i = 0; i < type.NumInOperands(); ++i) {
|
||||
const auto& words = type.GetInOperand(i).words;
|
||||
key.insert(key.end(), words.begin(), words.end());
|
||||
}
|
||||
auto& candidates = canonical[key];
|
||||
Instruction* match = nullptr;
|
||||
for (auto* candidate : candidates) {
|
||||
if (context()->get_decoration_mgr()->HaveTheSameDecorations(
|
||||
type.result_id(), candidate->result_id())) {
|
||||
match = candidate;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!match) {
|
||||
candidates.push_back(&type);
|
||||
continue;
|
||||
}
|
||||
context()->KillNamesAndDecorates(type.result_id());
|
||||
context()->ReplaceAllUsesWith(type.result_id(), match->result_id());
|
||||
duplicates.push_back(&type);
|
||||
}
|
||||
for (auto* type : duplicates) context()->KillInst(type);
|
||||
return duplicates.empty() ? Status::SuccessWithoutChange : Status::SuccessWithChange;
|
||||
}
|
||||
|
||||
spvtools::Optimizer::PassToken DeduplicateImageTypesPass::Create() {
|
||||
return spvtools::Optimizer::PassToken(spvtools::MakeUnique<DeduplicateImageTypesPass>());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
// MobileGL - MobileGL/MG_Util/ShaderTranspiler/SpirvPasses/DeduplicateImageTypesPass.h
|
||||
// Copyright (c) 2025-2026 MobileGL-Dev
|
||||
// Licensed under the GNU Lesser General Public License v3.0:
|
||||
// https://www.gnu.org/licenses/gpl-3.0.txt
|
||||
// https://www.gnu.org/licenses/lgpl-3.0.txt
|
||||
// SPDX-License-Identifier: LGPL-3.0-only
|
||||
// End of Source File Header
|
||||
|
||||
#pragma once
|
||||
#include "spirv-tools/optimizer.hpp"
|
||||
#include "source/opt/pass.h"
|
||||
|
||||
namespace MobileGL::MG_Util::ShaderTranspiler {
|
||||
// Preserve named structs: GL reflection and cross-stage interfaces use their identity.
|
||||
class DeduplicateImageTypesPass final : public spvtools::opt::Pass {
|
||||
public:
|
||||
const char* name() const override { return "mobilegl-deduplicate-image-types"; }
|
||||
Status Process() override;
|
||||
static spvtools::Optimizer::PassToken Create();
|
||||
};
|
||||
}
|
||||
@@ -14,6 +14,8 @@
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <iostream>
|
||||
#include <memory>
|
||||
#include <unordered_map>
|
||||
#include <thread>
|
||||
|
||||
namespace {
|
||||
@@ -56,6 +58,7 @@ EglFns gEgl;
|
||||
EGLDisplay gDisplay = EGL_NO_DISPLAY;
|
||||
void *gMobileGl = nullptr;
|
||||
const glws::Drawable *gCurrentDrawable = nullptr;
|
||||
const glws::Drawable *gCurrentReadable = nullptr;
|
||||
EGLContext gCurrentContext = EGL_NO_CONTEXT;
|
||||
ANativeWindow *gNativeWindow = nullptr;
|
||||
int gRequestedWidth = 0;
|
||||
@@ -158,6 +161,16 @@ public:
|
||||
explicit AndroidVisual(glws::Profile prof) : Visual(prof) {}
|
||||
};
|
||||
|
||||
// Desktop traces can keep a probe drawable alive while creating the real window.
|
||||
// Both map to the Activity's single ANativeWindow, which accepts only one producer.
|
||||
struct AndroidWindowSurface {
|
||||
EGLDisplay display;
|
||||
EGLConfig config;
|
||||
EGLSurface surface;
|
||||
~AndroidWindowSurface() { gEgl.destroySurface(display, surface); }
|
||||
};
|
||||
std::unordered_map<ANativeWindow *, std::weak_ptr<AndroidWindowSurface>> gWindowSurfaces;
|
||||
|
||||
class AndroidDrawable final : public glws::Drawable {
|
||||
public:
|
||||
EGLSurface surface = EGL_NO_SURFACE;
|
||||
@@ -177,12 +190,36 @@ public:
|
||||
if (w == width && h == height) {
|
||||
return;
|
||||
}
|
||||
const auto *draw = static_cast<const AndroidDrawable *>(gCurrentDrawable);
|
||||
const auto *read = static_cast<const AndroidDrawable *>(gCurrentReadable);
|
||||
const EGLContext context = gCurrentContext;
|
||||
const bool wasCurrent = context != EGL_NO_CONTEXT && (draw == this || read == this);
|
||||
if (wasCurrent) {
|
||||
// Destroying a current EGL surface only defers its destruction. Release it
|
||||
// first so its Vulkan surface disconnects from the window before recreation.
|
||||
if (gEgl.makeCurrent(gDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT) != EGL_TRUE) {
|
||||
std::cerr << "error: eglMakeCurrent release before resize failed: 0x"
|
||||
<< std::hex << gEgl.getError() << std::dec << "\n";
|
||||
return;
|
||||
}
|
||||
gCurrentDrawable = nullptr;
|
||||
gCurrentReadable = nullptr;
|
||||
gCurrentContext = EGL_NO_CONTEXT;
|
||||
}
|
||||
destroySurface();
|
||||
width = w;
|
||||
height = h;
|
||||
createSurface();
|
||||
if (gCurrentDrawable == this && gCurrentContext != EGL_NO_CONTEXT) {
|
||||
gEgl.makeCurrent(gDisplay, surface, surface, gCurrentContext);
|
||||
if (wasCurrent && surface != EGL_NO_SURFACE) {
|
||||
if (gEgl.makeCurrent(gDisplay, draw ? draw->surface : EGL_NO_SURFACE,
|
||||
read ? read->surface : EGL_NO_SURFACE, context) == EGL_TRUE) {
|
||||
gCurrentDrawable = draw;
|
||||
gCurrentReadable = read;
|
||||
gCurrentContext = context;
|
||||
} else {
|
||||
std::cerr << "error: eglMakeCurrent restore after resize failed: 0x"
|
||||
<< std::hex << gEgl.getError() << std::dec << "\n";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -203,17 +240,31 @@ public:
|
||||
}
|
||||
|
||||
private:
|
||||
std::shared_ptr<AndroidWindowSurface> windowSurface;
|
||||
|
||||
void createSurface() {
|
||||
const int surfaceWidth = ResolveWidth(width);
|
||||
const int surfaceHeight = ResolveHeight(height);
|
||||
if (!pbuffer && gNativeWindow != nullptr) {
|
||||
const auto config = static_cast<const AndroidVisual *>(visual)->config;
|
||||
windowSurface = gWindowSurfaces[gNativeWindow].lock();
|
||||
if (windowSurface && windowSurface->config != config) {
|
||||
windowSurface.reset();
|
||||
std::cerr << "error: replay window already has a surface with a different EGL config\n";
|
||||
return;
|
||||
}
|
||||
EGLint nativeVisualId = static_cast<const AndroidVisual *>(visual)->nativeVisualId;
|
||||
ANativeWindow_setBuffersGeometry(gNativeWindow, surfaceWidth, surfaceHeight, nativeVisualId);
|
||||
surface = gEgl.createWindowSurface(
|
||||
gDisplay,
|
||||
static_cast<const AndroidVisual *>(visual)->config,
|
||||
gNativeWindow,
|
||||
nullptr);
|
||||
if (windowSurface) {
|
||||
surface = windowSurface->surface;
|
||||
} else {
|
||||
surface = gEgl.createWindowSurface(gDisplay, config, gNativeWindow, nullptr);
|
||||
if (surface != EGL_NO_SURFACE) {
|
||||
windowSurface = std::shared_ptr<AndroidWindowSurface>(
|
||||
new AndroidWindowSurface{gDisplay, config, surface});
|
||||
gWindowSurfaces[gNativeWindow] = windowSurface;
|
||||
}
|
||||
}
|
||||
} else if (!pbuffer && WantsServerOwnedWindow()) {
|
||||
// HEADLESS COMMAND-LINE REPLAY (P12 D9, same shape as the desktop glws_egl path):
|
||||
// the window is the MobileGL SERVER's (MOBILEGL_IPC_SURFACE=server,
|
||||
@@ -249,7 +300,11 @@ private:
|
||||
|
||||
void destroySurface() {
|
||||
if (surface != EGL_NO_SURFACE) {
|
||||
gEgl.destroySurface(gDisplay, surface);
|
||||
if (windowSurface) {
|
||||
windowSurface.reset();
|
||||
} else {
|
||||
gEgl.destroySurface(gDisplay, surface);
|
||||
}
|
||||
surface = EGL_NO_SURFACE;
|
||||
}
|
||||
}
|
||||
@@ -395,8 +450,11 @@ bool makeCurrentInternal(Drawable *drawable, Drawable *readable, Context *contex
|
||||
EGLSurface readSurface = readable == nullptr ? drawSurface : AsAndroidDrawable(readable)->surface;
|
||||
EGLContext eglContext = context == nullptr ? EGL_NO_CONTEXT : AsAndroidContext(context)->context;
|
||||
if (drawSurface == EGL_NO_SURFACE && readSurface == EGL_NO_SURFACE && eglContext == EGL_NO_CONTEXT) {
|
||||
gEgl.makeCurrent(gDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
|
||||
if (gEgl.makeCurrent(gDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT) != EGL_TRUE) {
|
||||
return false;
|
||||
}
|
||||
gCurrentDrawable = nullptr;
|
||||
gCurrentReadable = nullptr;
|
||||
gCurrentContext = EGL_NO_CONTEXT;
|
||||
return true;
|
||||
}
|
||||
@@ -404,6 +462,7 @@ bool makeCurrentInternal(Drawable *drawable, Drawable *readable, Context *contex
|
||||
return false;
|
||||
}
|
||||
gCurrentDrawable = drawable;
|
||||
gCurrentReadable = readable == nullptr ? drawable : readable;
|
||||
gCurrentContext = eglContext;
|
||||
mobilegl_trace_dump::InstallIfRequested();
|
||||
return true;
|
||||
|
||||
@@ -1,97 +1,186 @@
|
||||
# Handoff:anland 5.x + 内置 MobileGL 统一 server(post-P14)
|
||||
# Handoff: anland 5.x + MobileGL unified server
|
||||
|
||||
更新时间:2026-10-02。本文替换旧的 handoff-legacy-mobilegl-unified.md(那份描述的是 P14 之前的状态,已被事实淘汰)。
|
||||
Updated 2026-10-04. This replaces the 2026-10-02 (post-P14) handoff; git history keeps the old text.
|
||||
|
||||
## 任务与路线
|
||||
## What this is
|
||||
|
||||
anland 5.x 用 MobileGL:容器(Droidspaces,arch-kde-mgl)里的 Linux client 经 SHM pipe 连到 anland APK 内嵌的统一 server(`:mobilegl` 私有 Service,同 APK 同 UID),server 在 anland 自己的 Surface 上直接渲染(路线 B:`kgsl-as-server.md`)。不按应用 fork 渲染进程——session/context/share-group 状态归属在 MobileGL 库内解决(P14,[`../design/11-state-ownership.md`](../design/11-state-ownership.md))。
|
||||
MobileGL runs disaggregated on a rooted Android tablet:
|
||||
- **Client:** the glibc library in the Droidspaces container `arch-kde-mgl`, where it is the system-wide glvnd EGL/GLX vendor and the GBM backend.
|
||||
- **Transport:** the client streams pipe records over abstract socket `@anland-mobilegl`.
|
||||
- **Server:** runs in-process in the anland APK's `:mobilegl` foreground service.
|
||||
- **Backends:** Espryt (DirectGLES) or Magma (DirectVulkan), chosen in the app settings.
|
||||
|
||||
## 远端与分支
|
||||
KDE Plasma runs on top with zero-copy windows (server-allocated AHB dma-bufs over linux-dmabuf). Everything is vendor-agnostic: AHB, sync_file, EGL_ANDROID_*, VK_ANDROID_*; no kgsl or qcom specifics.
|
||||
|
||||
- MobileGL:<https://github.com/MobileGL-Dev/MobileGL> 分支 `feat/disaggregated`
|
||||
- anland:<https://github.com/MobileGL-Dev/anland> 分支 `legacy-mobilegl-unified`
|
||||
## Remotes and heads
|
||||
|
||||
### MobileGL 关键提交(新→旧)
|
||||
- MobileGL: <https://github.com/MobileGL-Dev/MobileGL> `feat/disaggregated`, head `2d424146`. Integration worktree: `.claude/worktrees/anland-unified`.
|
||||
- anland: <https://github.com/MobileGL-Dev/anland> `legacy-mobilegl-unified`, head `41ec066`. Integration worktree: `anland/.claude/worktrees/mgl-unified`.
|
||||
- Version: 26.10 (`MobileGL/Config.h`, `android-plugin/app/build.gradle.kts`).
|
||||
|
||||
| Commit | 内容 |
|
||||
## Where to start reading
|
||||
|
||||
| Topic | Doc |
|
||||
|---|---|
|
||||
| `4b388950` | Magma:VAO/元素缓冲指向一个 server 没有存储的 buffer(client 构造时就铸 handle,create 只随第一次 respecify 过线)时拒绝该 draw 而非 Fatal;纹理的内置 sampler CSO 缺失或已回收(CSO 按内容寻址、满 256 回收)时按 GL 默认参数采样——两处都与 DirectGLES 的「decline」行为对齐。glmark2 全场景(refract/effect2d 此前带走 server)通过 |
|
||||
| `7e76a98d` | **Magma 多 surface + 多 context**:一个 session 一个 `VulkanRenderer`(device 与全部 GL 资源),每个客户端 EGLSurface 只是一个「surface target」(VkSurfaceKHR + swapchain + render-finished 信号量 + 已获取图像 + pbuffer 的 AImageReader),切换时提交当前工作、用一次空提交消耗挂起的 acquire 信号量后停放,回来时原样换回(`ActivateSurfaceTarget`/`DestroySurfaceTarget`,此前每次切 surface 都重建整个 VkInstance/VkDevice,所有 buffer/纹理丢失 → Chrome `unknown-buffer-respecify`);默认帧缓冲 render pass 的 hash 带 target 序号;`bind_context` 时 Magma 后端切回该 context 最后一次 make-current 的 surface(`OnClientContextBound`,Qt 每窗口一线程一 context,此前读回落到别的窗口的 pbuffer);**wire resource ops 表在 server 进程里只要有 session 活着就不注销**(此前任一 session 的 renderer 关闭——比如 ksplash 退出——都把进程级表清空,之后所有 session 的 buffer create 被静默丢弃:plasmashell 面板/弹窗全透明) |
|
||||
| `15dbe78c` | **Magma 按 session 隔离**:Magma 原本一进程一 renderer,`pVulkanRenderer`、`g_activeBufferManager`、动态状态影子、render pass manager 的静态指针、各 `s_device`、renderer generation、swap interval 都是进程全局——多 session 下 KWin 的 buffer 写落进别的 session 的表(`buffer-write-range` Fatal)。新增 `MagmaSession`/`SessionLocal<T>`(`MG_Backend/DirectVulkan/MagmaSession.h`):按调用线程绑定的 session 解析,未绑定线程(monolith、client、单测)用进程默认 session,行为不变;served session 的 apply 线程在 `ServerLoop::ApplyThreadMain` 里经 `BackendObject::BindSessionStateToThisThread` 绑定;扩展函数指针改成 renderer 成员;哈希 scratch 状态、scratch 向量改 thread_local |
|
||||
| `168808d1` | Magma 也广告 GL_ARB_shader_objects/vertex_shader/fragment_shader/texture_non_power_of_two(KWin `checkSupported` 门槛,此前 KWin 在 Magma 上 "Could not initialize rendering context");Android 上 `debug.mobilegl.backend` 系统属性可覆盖 `MOBILEGL_BACKEND_TYPE`(可调试 APK 换后端无需重签) |
|
||||
| `cd610934` | **锁屏花屏/桌面变噪点的根因**:`object_death` 记录到达 server 时,`SlotTable::ReleaseTwinByHandle` 遍历进程内**所有** slot table(所有 session 的所有 bucket)释放该 handle 的 twin。handle 是各 client 自己的分配器编号,不同 session 的同一 `{slot, gen}` 是各自不相干的活对象——锁屏 greeter 退出时删除自己的纹理,同时把 KWin 同 handle 的 twin 也释放了(KWin 正在用的 driver 纹理被删,plasmashell 窗口采样到已释放显存:噪点 + 别的窗口的残影)。现在 slot table 记录自己所属 session,释放只走调用线程 session 的 bucket(同 session 的各 share group 都释放;无 session 的线程保持全进程遍历)。顺带修掉另外两类跨 session 隐患:DirectGLES 进程级「容器对象」(scratch/blit/resolve FBO、staging FBO、模拟绘制的 VAO)改为按原生 context 分(`PerNativeContext`/`NativeContextName`,按 context 生命期序号,context 销毁时遗忘);UBO/unpack/upload 三个持久映射 ring 改为每原生 context 一套,帧 fence 完成水位改为「连续」(任一更早的 fence 未 signal 都不前进,fence 环加深到 32 且回绕时等待旧 fence 而非丢弃) |
|
||||
| `4236b42a` | server:配置只在进程内第一个 session 接入时初始化一次——此前每个新 session 接入都重跑 `MG_ConfigLoader::Init()`,它先把 `Transport` 写回 Monolith 再被改回 Spawn,正在 apply 的别的 session 恰好读到就跳过 server stamp,`Fatal{UnmigratedPipeInput, "GetBoundVertexArray@DrawArrays"}` 带走整个 server 进程(整个桌面);转译:保留下来的非零 `layout(index = 1)`(双源混合)在 ESSL 里加 `#extension GL_EXT_blend_func_extended : require`(此前 Adreno 拒绝该 stage,程序整体不画) |
|
||||
| `0b6842ac` | 让 ANGLE 的 GL 后端跑在 MobileGL 上:EGL 声明 `EGL_KHR_platform_gbm`/`EGL_MESA_platform_gbm`(GBM display 当离屏 display,拒绝 gbm 窗口 surface;Chrome 的 Wayland GL 层对每个 display 都标 GBM 平台);平台标 GBM 但 native display 实为 wl_display 时按 Wayland 处理,wl_display 识别兼容自带一份 libwayland 的程序(按接口名 "wl_display" 判断,经 `process_vm_readv` 读,野指针不会崩);实现 `glGetShaderPrecisionFormat`(此前是空 stub,ANGLE 读到 0 精度即拒绝 ES 2.0);`GL_VERSION` 里不再出现 "OpenGL ES" 子串(ANGLE 用子串搜索判断 ES 驱动,"Direct (OpenGL ES) Backend" 让它把 MobileGL 当 ES 驱动、按 ES 扩展名查 BGRA 等能力,Chrome 的 shared image 全部创建失败) |
|
||||
| `47db68d5` | GLX:MobileGL 同时是 glvnd 的 GLX vendor(`__glx_Main`,装成 `/usr/lib/libGLX_mobilegl.so.0`,会话设 `__GLX_VENDOR_LIBRARY_NAME=mobilegl`;此前 X11 客户端经 Xwayland 拿到 Mesa vendor,报 `MESA-LOADER: failed to retrieve device information`);远端 X drawable(pbuffer)每次 `glXSwapBuffers` 回读并用 `xcb_put_image`(按服务器最大请求长度分带)上屏,resize 换新 pbuffer;GLX 出口持流锁;`eglReleaseThread` 在 MobileGL 已被 `eglTerminate` 拆掉后也返回 TRUE(glmark2 退出时的 "eglReleaseThread failed") |
|
||||
| `ccf8eb65` | 客户端:多线程 GL 流串行化——每个 GL/EGL 出口持同一把流锁,写入前按「最后真正发出的 `bind_context`」把 server 绑到调用线程的 context(Qt 每个窗口一个 QSGRenderThread,此前两线程记录在同一 ring 上交错、落进错的 applier、甚至撕裂记录);`MGPipeTracker` 按 context 的永不复用 id 判断换 context(指针 ABA);导出 `eglCreateImageKHR`/`eglDestroyImageKHR`(KWin 在 shm client 断开时调空指针 → 首个 KWin 约 2 秒必 SEGV);`eglGetPlatformDisplayEXT` 的 EGLint 属性表加宽;多窗口:surface 激活不再清空别的线程的 current 记录,swap 呈现本线程的 surface;Wayland 窗口 `wl_egl_window_resize` 在下一次 make-current/swap 生效 |
|
||||
| `0b314dda` | server:所有 session 的 apply 线程在一把 FIFO「backend turn」上串行(DirectGLES 是按单 GL 线程写的:单一 owner 线程、进程级绑定影子),换手时接管 owner 并清掉绑定影子;全部原生 context 进同一 share group(环、池、scratch 纹理是进程级 GL 对象);每个客户端 surface 一个原生 surface(激活时重绑而非新建),建 surface 后恢复当前 context 自己原来的 surface,释放 surface 只销毁它(此前 `DestroyEGLContext` 带走整个 session 的 context),`bind_context` 恢复 context 自己的 surface;pbuffer 背后的窗口 resize = 换新 pbuffer;session 结束时若别的 session 的 context 还活着,只清本 session 的东西(此前进程级 generation 被推进,所有活 session 的纹理/缓冲被当成死的空重建 → 关弹窗/退出 client 后全屏噪点);分块上传(stage chunk 切片)的 region 偏移按整层图像校验(此前 KWin 的 wl_shm 纹理在第 819 行后读到第 0 行);`SetSamplerViews.Count` 改为 per-session latch |
|
||||
| `30fef23d` | P14 收尾(统一 server 的两处进程级状态):server 的两个 staged store(纹理 level 声明、buffer shadow)按调用线程的 {session, share group} 分桶(与 S6 twin 表同一个探针),`DropAll` 只清本 session;`MGPipeServerSetContextLive` 的 live 标志从进程全局移进本 session 的 PipeInputs 块。各带单测(`StagedTextureStoreTest` 两例、`ServerContextLiveTest`) |
|
||||
| `d554c87c` | EGL loader 缺 `eglSwapBuffersWithDamageEXT` 不再 FATAL(EXT→KHR→eglSwapBuffers 回退 + GLES 符号 dlsym 回退防自指);stencil-only 存储格式配对修复;各带测试 |
|
||||
| `7a48521d` | DirectGLES:创建 server-owned window surface 前先销毁同窗口的残留 surface(此前第二个起的 session 必死 EGL_BAD_NATIVE_WINDOW) |
|
||||
| `5a0f13fd` | 广告 GL_ARB_shader_objects/vertex_shader/fragment_shader/texture_non_power_of_two(KWin `checkSupported` 的硬门槛) |
|
||||
| `ff212061` | P14 S6:后端 twin 表按 {session, share group} 键控 |
|
||||
| `4ed1c9ce` | P14 S1–S5:`bind_context`(opcode 84)+ CreateContext/DestroyContext 控制帧(control revision 6);同进程多 session(`SessionRuntime`、线程域解析、per-session latch,inproc unix supervisor 并发上限 `MOBILEGL_IPC_INPROC_MAX_SESSIONS`=16);前端 ShareGroupState/per-context GLContext/TLS pGLContext;DirectGLES per-(session,context) native tuple(不再无条件 teardown);applier 按 {session,context}/{session,shareGroup} 分桶 |
|
||||
| `ebc552a0`/`6fb880cd` | Wayland Present 失败回 EGL_BAD_SURFACE;GLX drawable 走远端 pbuffer;Linux libGL 别名 |
|
||||
| `d52c031c` | P14 设计文档 |
|
||||
| Reproduce the whole setup on a new machine or phone | `.claude/skills/anland-mobilegl-plasma/reproduce.md` (and `SKILL.md`) |
|
||||
| Day-to-day bring-up and checks | `runbook-plasma.md` |
|
||||
| Zero-copy windows | `plan-ahb-dmabuf.md` |
|
||||
| X11 on the GPU (glamor, DRI3/Present GLX) | `plan-x11-gpu.md` |
|
||||
| glmark2 performance: baseline and the optimization handoff | `../../../Performance/glmark2-baseline.md`, `../../../Performance/glmark2-handoff.md` |
|
||||
| VA-API driver on MediaCodec (plan only, nothing implemented) | `../../../MobileVA/plan.md` |
|
||||
|
||||
### anland 关键提交(新→旧)
|
||||
## State of the desktop (verified on the device, 2026-10-04)
|
||||
|
||||
| Commit | 内容 |
|
||||
- **App-driven bring-up:** opening the anland app starts daemon → server → container → Plasma. A foreground service keeps it alive, the server idles while the app is hidden (KWin DPMS off), and the notification has a "Stop desktop" action.
|
||||
- **Both backends** run the desktop: KWin, plasmashell, Kickoff, notifications, the lock screen, resize on extra-keys-bar toggle, and suspend/resume on window loss.
|
||||
- **Buffer age and damage** work end to end on both backends.
|
||||
- **glvnd vendor:** MobileGL is the system-wide vendor (`10_mobilegl.json`, `/etc/mobilegl/client.conf`). It steps aside for `LIBGL_ALWAYS_SOFTWARE`, foreign GBM devices, and when no server answers (falls through in about 0.1 s).
|
||||
- **X11:** Xwayland glamor on MobileGL. GLX presents through DRI3 + Present shared images, with a MIT-SHM readback fallback.
|
||||
- **Chrome:**
|
||||
- runs its GPU in a separate process with real EGL native fences, with no flicker;
|
||||
- recovers from device loss (as do KWin and plasmashell);
|
||||
- Shadertoy-style GPU faults are contained per session;
|
||||
- a hanging client is cut off on Magma (watchdog `MOBILEGL_GPU_HANG_BUDGET_MS`) and on Espryt (GUILTY reset).
|
||||
- **Chrome video:** hardware decode works through the container's VA-API driver. NV12/P010 dma-bufs are sampled via `GL_OES_EGL_image_external` on both backends. Foreign YUV buffers are CPU-copied into server YUV images, and 4K60 is fine. `MOBILEGL_CHROME_VIDEO_DECODE=software` opts out.
|
||||
- **Device state at handoff:**
|
||||
- MobileGL anland on Magma, Plasma up, server/client build `bb31f374`; later commits are docs, CI and a DirectGLES multi-session fix that is not yet deployed;
|
||||
- clocks NOT pinned (restored); the original anland APK is stopped;
|
||||
- pin and restore helpers: `su -c "sh /data/local/tmp/anl/pbclk.sh pin|restore"`.
|
||||
|
||||
## Work streams and where each one stopped
|
||||
|
||||
### 1. glmark2 performance (stopped at a handoff)
|
||||
Details: `docs/Performance/glmark2-handoff.md`.
|
||||
- **Now:** MobileGL beats the stock kgsl stack in windowed glmark2 on both backends (es2 800x600: Espryt ~1887, Magma ~1213, stock ~1100). Fullscreen is still about half of stock (Espryt ~561, Magma ~404, stock ~1177).
|
||||
- **Next, ranked:**
|
||||
1. render straight into the window's buffers (removes the fullscreen copy);
|
||||
2. non-blocking present;
|
||||
3. merge Magma's per-frame submissions;
|
||||
4. Magma descriptor and pipeline caching;
|
||||
5. profile terrain;
|
||||
6. Espryt per-draw state sync;
|
||||
7. non-blocking fences.
|
||||
- Bench scripts: `tools/device_bench/anland_glmark2/`.
|
||||
|
||||
### 2. GitHub Actions CI (stopped mid-way, no handoff from its agent)
|
||||
- **Background:** CI had been red since about 2026-09-26 (Test workflow) and since 2026-10-02 (APK workflow retraces). Most runs show `cancelled` only because each newer push cancels them.
|
||||
- **Landed:**
|
||||
|
||||
| Commit | What |
|
||||
|---|---|
|
||||
| `5f15240` | 会话可选后端:APK 的 `:mobilegl` worker 从 `files/mobilegl-backend` 读后端(`am start ... --es mobilegl_backend DirectVulkan` 写入),容器侧 `mobilegl-startup.sh` 从 `/etc/mobilegl/backend` 读并导出给 KWin drop-in 与 dbus 激活环境(server 一进程只服务一种后端,client 必须报同一种,否则 "Hello.backendType disagrees with pinned backend") |
|
||||
| `56b060c` | 恢复工具链入库 `producers/kde/Arch_v5/mobilegl-tools/`(KernelSU grant helper、源码同步与容器内 client 构建、EGL smoke 探针、设备侧部署/daemon 脚本) |
|
||||
| `1fb419a` | mobilegl-startup.sh:默认 socket 指向实验 daemon(/etc/environment 的 pam_env 会盖掉 systemd drop-in);plasma 模式改走 kwin_wayland_wrapper(BusName=org.kde.KWinWrapper 只在 wrapper 注册,直跑 kwin 90 秒被 systemd 杀);KWin 直写 surface 不加 FlipY(此前画面上下颠倒);sync-build-kwin.sh 容器侧 canonical 同步/增量构建/原子安装管线 |
|
||||
| `118ae52` | `MOBILEGL_BACKEND_TYPE=DirectGLES`(Espryt 只是别名,写错会被 pinned-backend 拒);eglChooseConfig 收 count≥1(MobileGL 默认有两份配置);compositor client 日志落文件 |
|
||||
| `da03d3b`/`35699f3` | consumer flap 时不再停 compositor;APK consumer 侧不再因 Surface 生命周期事件重启 native 管线 |
|
||||
| `33e496c` | 统一内嵌 server 宿主:`:mobilegl` Service 单 endpoint `@anland-mobilegl`;移除被否定的 MobileGLAppsService/按应用 fork 路径 |
|
||||
| `2ffa1f5` | KWin anland backend 的 `ANLAND_MOBILEGL=1` 路径(跳过 GPU/DRM probing,server-owned window) |
|
||||
| `6e1fa65` | 无 fd 的 MobileGL Surface 显示协议(DATA_MSG_MOBILEGL_SURFACE=201) |
|
||||
| `eb71b669` | The pull and verify builds compile again |
|
||||
| `c1e957cb` | Retired the P3a/P4a untouched-region gates; those phases closed and later work legitimately changed the regions |
|
||||
| `78c5f8da` | Census records `Refuse{Recover}` as a local refusal |
|
||||
| `32d27b14` | Real bug: a session's backend registration no longer trips the strict apply-thread pin while another session is applying (DirectGLES) |
|
||||
| `2d424146` | Failed ctest entries are annotated with their failure lines, so failures can be read from the check-run annotations without a signed-in log reader |
|
||||
|
||||
## 真机已验证(TB321FU,HA27Q3LQ)
|
||||
- **Run on `2d424146`:** in progress at handoff. Gates, include-closure and flatc are green; the builds and integration jobs were still running.
|
||||
- **Still open:**
|
||||
- the APK workflow's **retrace failures** (Retrace and validate), on DirectGLES for minecraft-1.21.11-main-menu, 1.21.4 startup/in-world/main-menu, 1.17-main-menu-854 and OpenRA, and on DirectVulkan for 1.17-main-menu-854;
|
||||
- they first appeared around `5accb098` / `8da082f8` (2026-10-02); last green APK run `2f64ede8`;
|
||||
- not yet bisected. Candidates:
|
||||
- the clear-colour default (0,0,0,0), which is GL-correct, so judge any golden against the spec;
|
||||
- anonymous-struct sampler handling in glslang;
|
||||
- sampler CSO publishing;
|
||||
- the scissor-shadow fix;
|
||||
- the inactive-fragment-output location fix;
|
||||
- the external-texture and YUV changes;
|
||||
- the perf commits.
|
||||
- **User guidance on judging checks:**
|
||||
- phase-era process gates may be overly strict, and superseded ones may be removed with a reason;
|
||||
- retraces and OpenGL-level checks must pass;
|
||||
- a feature a backend does not implement (e.g. iterationRP) may be excluded narrowly per backend.
|
||||
- **Reading CI without `gh`:** `curl https://api.github.com/repos/MobileGL-Dev/MobileGL/actions/runs?branch=feat/disaggregated`, then `/actions/runs/<id>/jobs` and `/check-runs/<job>/annotations`. Raw logs need sign-in.
|
||||
|
||||
以实际画面/输出为准:
|
||||
### 3. Chrome hardware video (landed) → vendor-agnostic VA-API (planned only)
|
||||
- **Container driver:** `/usr/lib/dri/msm_drm_drv_video.so` is an unpackaged third-party, Qualcomm-only driver. It drives V4L2 at `/dev/video32` with Qualcomm modes and copies frames on the CPU itself. libva picks it because the render node's DRM driver name is `msm_drm`.
|
||||
- **Plan in `docs/MobileVA/plan.md`:** a new `MobileVA/` directory; MediaCodec decode in the `:mobilegl` process; H.264 first, then VP9, AV1, HEVC/10-bit; the old driver kept as A/B fallback.
|
||||
- **Prerequisites the plan found:**
|
||||
- per-plane R8/GR88 dma-buf import, which mpv's GL path and KWin's NV12 path need;
|
||||
- YUV sampling paths that wait on the shared image's write fence (they appear not to).
|
||||
|
||||
- **链路绿屏**:client clear → server(Adreno 750 厂商驱动)→ Android Surface → 屏幕,截图可见(win-smoke,60 帧 swap 无错误)。
|
||||
- **egl-smoke**:pbuffer + clear + readback RGBA 精确(64,128,191,255)。
|
||||
- **eglinfo**:GLVND vendor JSON 正常,EGL 1.5,两组配置。
|
||||
- **glxinfo / glmark2(X11)**:经 glvnd 的 MobileGL GLX vendor,不需 `LD_LIBRARY_PATH`;glxinfo 报 Espryt (Adreno 750) GL 4.6;glmark2(X11 窗口经 Xwayland)画面正确上屏,shading 场景约 280 fps;glmark2-wayland / glmark2-es2-wayland 正常且退出无报错。
|
||||
- **KWin 6.7.4**:合成器存活并呈现(黑桌面+光标可见)。
|
||||
- **Konsole**:窗口完整正确渲染(标题栏、工具栏、shell 提示符,方向正确)。
|
||||
- **多 session**:两个 win-smoke 连续运行同一窗口均 exit 0(stale surface 修复生效)。
|
||||
- **Chrome 跑在 MobileGL 上(2026-10-02)**:会话的 Chrome 启动项(`mobilegl-startup.sh chrome`,plasma 模式写入用户级 `google-chrome.desktop` 覆盖)用 `--use-gl=angle --use-angle=gles --in-process-gpu --render-node-override=<不存在的节点> --disable-features=WaylandFractionalScaleV1`:ANGLE 报 `ANGLE (MobileGL-Dev…, Espryt…, OpenGL 4.6.0 MobileGL…)`,GPU 合成开启,标签栏/工具栏/网页正确合成,缩放正确。为什么这样配:Chrome 的独立 GPU 进程在 Wayland 上只能经 GBM dma-buf 上屏(MobileGL 与本 KWin 都不收),放进浏览器进程后改走 wl_egl_window(MobileGL 的 wl_shm 呈现);该路径下 Chrome 不发 fractional-scale 的 viewport,整数缩放才会发 `set_buffer_scale`。此前镜像自带的 `/usr/local/bin/google-chrome` 是 `--use-angle=vulkan` + renderD128,走的是容器里的 Turnip。
|
||||
- **Plasma 桌面可用(2026-10-02,`ccf8eb65`:server 与容器 client 同源)**:壁纸、面板、托盘、时钟、桌面图标、Kickoff 开始菜单、通知窗口都正确渲染;鼠标/触摸输入可用(点击打开 Kickoff);KWin 过渡动画正常;开/关托盘弹窗不再花屏;按返回键收起快捷键栏时输出 resize 跟随。三线程/三 context/三 surface 并发回读探针(`anland-egl-mt-readback-probe.c`)与大纹理分块上传探针(`anland-egl-upload-probe.c`)全过。
|
||||
- **Magma(DirectVulkan)与 Espryt 同等可用(2026-10-02,`4b388950`)**:KWin 合成(约 140 fps,apply 2–3 ms/帧)、plasmashell 真正经 Magma GPU 渲染(壁纸、面板、托盘、桌面图标、带模糊的 Kickoff、通知弹窗;托盘里不再有「正在使用的软件渲染器」)、glxinfo 报 `Magma (MobileGL Core) (Adreno (TM) 750, Vulkan 1.3.128…)`、glmark2(X11)全 16 场景跑完 score 47、glmark2-es2-wayland score 50、Chrome 正常(剩余问题与 Espryt 相同:WebGL 画布空白、扩展图标黑块)、`kscreenlocker_greet --testing` 正确渲染且退出后桌面无噪点。切后端:`setprop debug.mobilegl.backend DirectVulkan` + `/etc/mobilegl/backend` 写同名 + 重启 APK 与会话。
|
||||
- **Plasma 会话(早期,`30fef23d` 的 server + `ff212061` 的容器 client)**:`desktop-session.service` 持续 active(>1 分钟,此前约 7 秒必拆);面板完整渲染(启动器、固定应用、托盘、时钟);光标尺寸正常;多个 session 并发、逐个 reap 而其余继续服务。截图里壁纸有横向条带错位(见下面第 1 条)。
|
||||
### 4. MobileGL work landed since the previous handoff (newest first, grouped)
|
||||
- **Perf:**
|
||||
- `bb31f374` Magma keeps render passes open across draws;
|
||||
- `e5ee31b0` android-30 for native TLS;
|
||||
- `915882b2` record timing only with stats on;
|
||||
- `963f4d81` Magma command buffer reuse;
|
||||
- `d627fca3` the server wakes a parked client only when its sequence is applied;
|
||||
- `2de0d6dd` client-array buffer reuse;
|
||||
- `66b47a10` glFinish waits for the GPU, plus ES OES strings.
|
||||
- **YUV:** `7218bacb` NV12/P010 shared images, `GL_OES_EGL_image_external`, Espryt `GL_EXT_YUV_target`, Magma Ycbcr conversion.
|
||||
- **Device loss and hangs:**
|
||||
- `287e1df8` cut off the session that hangs the GPU;
|
||||
- `7823bcd9` client fresh-session recovery;
|
||||
- `90e63c9e` robustness extensions;
|
||||
- `58c3d9bd` per-session device-loss latch;
|
||||
- `36190b7c`, `cf763b40`, `1dd888cb`, `f22ae625`, `f52a5467` loss and teardown edge cases.
|
||||
- **Multi-thread and multi-context fixes:** `a9f22ebb`, `25a76c1b`, `393002a4`, `a84104a4`, `2acc6c41`, `8024b645`.
|
||||
- **Chrome:**
|
||||
- `4f6f4125` real EGL native fences;
|
||||
- `30977c18` opt-in ES identity for ES contexts (the GPU process on ANGLE);
|
||||
- `5accb098` glslang anonymous-struct samplers (Shadertoy page fault).
|
||||
- **X11:**
|
||||
- `198d6fea` GLX via DRI3/Present;
|
||||
- `08f23543` glFlush implicit sync for glamor;
|
||||
- `5de6ecd4`, `7fd965ce` shared-image upload and publish;
|
||||
- `cd58f048` inactive fragment output location;
|
||||
- `316ffe02` never dial its own X display.
|
||||
- **glvnd:** `69e96f5b`, `4095624f`, `4f679d66`, `3d69c375`, `552dd3d3`.
|
||||
- **Present:**
|
||||
- `74919a3b` / `7090e31d` buffer age and damage;
|
||||
- Espryt fixes `815217cc` (scissor shadow is per-session), `c822a9fe`, `228bd24c`;
|
||||
- `1ff7ca53` / `caa00995` frame-callback pacing;
|
||||
- `5a7b23f6` / `258b9460` / `16b07cf4` suspend, resume and resize.
|
||||
- **Shared images:** `38842985`, `3d17e8c1`, `350fc699`, `67226176`, `b5cab441`, `7520e53b`.
|
||||
- **Misc:**
|
||||
- `8da082f8` clear colour starts at (0,0,0,0);
|
||||
- `51c37bcb` sampler param conversion;
|
||||
- `15f9b27a` sampler CSO per share group;
|
||||
- `239fc228` gl_FragCoord access chains;
|
||||
- `bfa7987c` Magma declines invalid SPIR-V;
|
||||
- `6125f941` surfaceless/no-config EGL;
|
||||
- `4633ca22` frame-stats log gated (`MOBILEGL_SERVER_FRAME_STATS`);
|
||||
- `2a1889b8` gtest discovery at ctest start.
|
||||
|
||||
## 未完成 / 已知问题(按优先级)
|
||||
### 5. anland work landed (newest first)
|
||||
- `41ec066` / `f60b261`: Chrome video decode modes.
|
||||
- `e48874c`: KWin recovers from its own session loss.
|
||||
- `b9f8162` / `cf07bc7`: Chrome GPU process by default.
|
||||
- `3d8c4dd` / `5d30340`: Xwayland glamor.
|
||||
- `89894f1` / `a55e975`: DPMS off while hidden.
|
||||
- `74bd2d3`: the app starts the desktop, foreground service.
|
||||
- `0fd5d01` / `144f55c`: APK build guards.
|
||||
- `90c44d7`: system-wide vendor.
|
||||
- `23fc73f`: buffer age and damage in KWin.
|
||||
- `9773d1e` / `2dfda4a`: resize follow.
|
||||
- `f9e41df`: GBM device for linux-dmabuf.
|
||||
- `5f15240`: backend choice.
|
||||
|
||||
1. **Plasma:桌面已落地、基本可用,剩余问题**(按优先级):
|
||||
- ~~启动 Chrome 时 KWin 崩溃~~ 已修(anland `kwin.patch`):无 DRM 设备分支里 `waylandServer()->linuxDmabuf()` 会创建 linux-dmabuf global,而空 tranche 不建格式表,Chrome 请求 default feedback 时 KWin 解引用空表(`LinuxDmaBufV1FeedbackPrivate::send` → `FileDescriptor::get`)。现在该分支不碰 dmabuf,client 回落 wl_shm;Chrome 新标签页正常渲染。KWin shim 现在在 `/tmp/kwin-cores/<pid>/` 下运行,core 不会再被覆盖。
|
||||
- **某个 client 退出时 KWin 偶发 SEGV**(rc=139,core 被覆盖未取到);KWin 在 server 进程被杀时也会 SEGV(设备丢失路径),后者是预期外但可接受。
|
||||
- **ksplash 启动动画闪黑**:开机时 ksplash 帧间偶有整帧黑;单独 `ksplashqml --test` 在会话内不复现。约 13–15 fps(每帧 2560x1412 全尺寸回读 + wl_shm + KWin 重新上传),见第 3 条。
|
||||
- 合成成本:每个 Wayland 窗口每帧整幅 glReadPixels(2 MiB 一片)+ KWin 整幅 glTexSubImage,是当前帧率上限。
|
||||
- DirectGLES 里少量进程级「容器」对象(resolve FBO、scratch FBO、XFB helper、timer query 探测)不在 share group 里共享,多 session 交替使用时理论上会拿到别的 context 的名字——尚未观察到症状。
|
||||
- **Chrome 剩余渲染问题**:WebGL 画布不显示(get.webgl.org 的立方体区域空白、aquarium 只有底色,fps 计数正常),工具栏两个扩展图标是黑块;两边日志都无报错,待查(怀疑 shared image 的某种格式/swizzle 或画布合成路径)。
|
||||
- ~~锁屏界面花屏~~ 已修(见上表):复现方式 `kscreenlocker_greet --testing` 起一个测试模式 greeter 再杀掉(本会话的 logind session 类型不支持 `loginctl lock-session`,真锁屏后只能输密码解锁);修复前几乎每次都让桌面/面板变噪点,修复后多次 + 并发 client 压测均正常。定位手段:给 `BackendTextureObject` 记录创建 session,析构时 session 不符就打 `_Unwind_Backtrace` 栈(符号用 NDK `llvm-addr2line` 对未 strip 的 build-android/libMobileGL.so 解)。
|
||||
- **Plasma 的软件渲染回退是粘滞的**:server 崩溃时 plasmashell 收到 device lost,Plasma 会把 `[QtQuickRendererSettings] SceneGraphBackend=software` 写进 `~/.config/kdeglobals`,之后每次会话都用 CPU 渲染 Qt Quick(托盘出现「正在使用的软件渲染器」图标),即使 GL 已经修好。排查任何 plasmashell 渲染问题前先确认该键不存在:`kwriteconfig6 --file kdeglobals --group QtQuickRendererSettings --key SceneGraphBackend --delete`。
|
||||
- Magma 每个 session 自建 VkInstance/VkDevice(无跨 session 共享),首帧 apply 约 100 ms;内存开销随 client 数线性增长。
|
||||
2. **光标巨大化**:2026-10-02 的 Plasma 会话截图里光标尺寸正常,未再复现;若再现,查 output scale 与 cursor layer 的 buffer scale。
|
||||
3. **CPU blit 禁令**:用户明确要求最终形态上屏路径无 CPU blit——当前 Wayland wl_shm client 走 readback(`32c79f41`),只是过渡。目标:应用窗口内容也由 server 在 GPU 侧直接给 KWin 合成(server 侧 GPU buffer → 同进程共享给 compositor 的 share group → 合成上屏),不经过 CPU 回读。设计要进 11-state-ownership.md 的后续切片。
|
||||
4. **GLX 上屏是 CPU 回读**:每帧整幅 glReadPixels + `xcb_put_image`,同第 3 条的过渡方案;只处理 24/32 位深窗口;直接拿 X 窗口(未经 glXCreateWindow)当 drawable 的 surface 不会随窗口销毁回收。
|
||||
5. **surface loss**:Wayland 窗口 resize 已跟随(`ccf8eb65`);surface loss 仍结束活动 session(无损挂起未实现);server 进程被杀后,新进程下 KWin 拿不到窗口 surface(KWin 不会重连,需重启会话)。
|
||||
6. **AVC 审计未做**:全程在 Enforcing 下跑通(容器侧有 droidspacesd 的既有 permissive 规则),SCM_RIGHTS/memfd 的精确 AVC 采集没做。
|
||||
7. **wire stamp 漂移**:容器构建的 `MGGitHash.h` 因 tar 无 .git 而陈旧(日志 WARN "compatible wire with different build");两端应同 commit + 显式 `-DMOBILEGL_BUILD_STAMP` 重建。
|
||||
## Known open issues (rough priority)
|
||||
|
||||
## 设备与环境要点(复现用)
|
||||
1. **CI:** retrace failures (see stream 2) and whatever the `2d424146` run still shows red.
|
||||
2. **Fullscreen performance** at about half of stock (see stream 1).
|
||||
3. **Espryt's ~10 s Preemption-Fault hang path:** the driver doesn't report the reset to the server's contexts, so a hanging client stalls the desktop for 10 s per hang there.
|
||||
4. **YUV gaps:**
|
||||
- YUV sampling doesn't wait on the write fence (suspected);
|
||||
- no single-channel (R8/GR88) dma-buf import, so KWin advertises no YUV formats and mpv's GL interop won't work;
|
||||
- the CPU copy for foreign YUV buffers is a fallback, not zero-copy.
|
||||
5. **Chrome** doesn't use buffer age (full-frame repaints). The Magma text-caret frame costs about 24 ms.
|
||||
6. **A rare Magma X11 rectangle glitch.** The readback GLX fallback is slower with glamor.
|
||||
7. **Two GoldControllerTest failures** on Windows hosts. MSVC builds of this branch are broken; build tests in WSL with clang.
|
||||
8. **Leftovers:**
|
||||
- container probe files under `~swung0x48/yuvtest` and the local `v.html` tabs in the Chrome profile;
|
||||
- an empty directory `.claude/worktrees/quirky-poincare-df3f3e` (locked by Windows);
|
||||
- WSL `~/mgl-espryt*` / `~/mgl-magma*` directories of unknown owner (kept).
|
||||
|
||||
- 设备 HA27Q3LQ(Y700 TB321FU),clone `arch-kde-mgl`(arch-kde 保持不动),容器内 `/opt/mobilegl/{lib,bin,kwin}`。
|
||||
- **KernelSU grant**:`ksud profile` 无直授命令;管理器专属 ioctl 的解法:root 下 setuid 到 manager UID(10255)→ `reboot(0xDEADBEEF,0xCAFEBABE)` 拿 `[ksu_driver]` fd → `SET_APP_PROFILE`。helper 源码在 anland `producers/kde/Arch_v5/mobilegl-tools/ksu_grant.c`。已持久化进 `/data/adb/ksu/.allowlist`。
|
||||
- 实验 daemon:独立实例 `display_daemon /data/local/tmp/anland-mobilegl/display.sock`(原 daemon 不动);socket 需 666、目录 777(容器内 uid1000 要连)。
|
||||
- clone config 的目录 bind:`/data/local/tmp/display_daemon.sock:/run/display.sock`、`/data/local/tmp/anland-mobilegl:/run/anland-mobilegl`。
|
||||
- KWin 启动:`desktop-session.service` + drop-in ExecStart=mobilegl-startup.sh compositor|plasma;Qt 日志默认只出 warning(info 要 QT_LOGGING_RULES)。
|
||||
- **当前设备上的 server 库是手工替换的**:`libMobileGL.so` 直接 root 覆盖到已装 APK 的 `/data/app/.../lib/arm64/`(保留 owner/SELinux context,原件备份在 `/data/local/tmp/anland-mobilegl/libMobileGL.so.orig`)。这样不用重签 APK(换签名要卸载重装,UID 会变,KernelSU grant 要重做)。本机构建:NDK 27.2 + `cmake -DCMAKE_TOOLCHAIN_FILE=.../android.toolchain.cmake -DANDROID_ABI=arm64-v8a -DANDROID_PLATFORM=android-26 -DMOBILEGL_BUILD_DISAGGREGATED=ON -DMOBILEGL_BUILD_DISAGGREGATED_INPROC=ON -DMOBILEGL_BUILD_STAMP=<commit>`,`llvm-strip --strip-debug` 后推送。
|
||||
- **复现用探针**(anland `producers/kde/Arch_v5/mobilegl-tools/`):`anland-egl-upload-probe.c`(2560x1412 纹理整幅 + 跨分片的局部 TexSubImage 回读校验)、`anland-egl-mt-readback-probe.c`(三线程各自 context/pbuffer 并发绘制+整幅回读);在容器里以 swung0x48 身份、带 MobileGL 的 `__EGL_VENDOR_LIBRARY_FILENAMES`/`MOBILEGL_*` 环境运行。注入点击要用 `input mouse tap`(anland 抓了触摸屏 EVIOCGRAB,`input tap` 无效);不要对容器进程用 `debuggerd -b`(发 signal 35,glibc 进程直接被杀)。
|
||||
- **Chrome/ANGLE 排查手段**:`--gpu-launcher=<脚本>` 包 GPU 进程(strace 每进程 `-o file.$$`,Chrome 会多次重启 GPU 进程);ANGLE 只 `dlsym` 一个 `eglGetProcAddress`,其余入口全经它取,LD_PRELOAD 拦 `dlsym` 再包 `eglGetProcAddress` 才能看到 display 调用;headless Chrome + `--remote-debugging-port` + CDP `SystemInfo.getInfo` 能拿到 GL_RENDERER/扩展列表/featureStatus(`--dump-dom chrome://gpu` 在 headless 下拿到的是新标签页)。user manager 里 PAM 带进来的 Mesa/KGSL 变量 `systemctl --user unset-environment` 删不掉(返回 0 但无效),对 MobileGL 会话无害。
|
||||
- **诊断用的容器改动**:`/opt/mobilegl/kwin/bin/kwin_wayland` 现在是 shim(设 `MOBILEGL_LOG_FILE_PATH=/tmp/mgl-kwin-$$.log` 后 exec `/opt/mobilegl/kwin/real/kwin_wayland`;真二进制必须仍叫 `kwin_wayland`,否则 KWin 内置 QPA 插件拒绝加载);`~swung0x48/.config/systemd/user/plasma-plasmashell.service.d/mobilegl-log.conf` 给 plasmashell 单独日志 `/tmp/mgl-plasmashell.log`。MobileGL 打开日志是截断写,所以必须每进程一个文件。
|
||||
- 构建(之前那台机器的环境,本机没有 `/root/anland-mgl-build` 也没有 gitignored 的 `build_bundled_apk.sh`;APK 按 `consumers/anland_v5/android_consumer/MOBILEGL.md` 用 gradle + `MOBILEGL_DIST` 构建):Android dist 用 WSL(NDK r27c,stamp 显式指定);APK 用 anland worktree 的 `build/build_bundled_apk.sh`;容器 client 用 `producers/kde/Arch_v5/mobilegl-tools/anland-sync-source.sh build`(`MOBILEGL_REPO` 指向已 init 子模块的 MobileGL worktree;注意 `tools/trace_replay` 789MB 必须排除)。
|
||||
- 设备 30 秒无操作熄屏——熄屏可能 kill SurfaceView;长跑验证前 `svc power stayon true` 或调 screen_off_timeout。
|
||||
## Rules this work follows
|
||||
|
||||
- **Commits:** `--no-verify`, one short sentence, no Co-Authored-By trailer. No external project names in code or comments.
|
||||
- **Tests:** never run the DirectVulkan integration tests (`ctest -E DirectVulkan`); never run two ctest suites at once.
|
||||
- **Worktrees:** one worktree and build directory per task; remove the worktree, branch and build directories right after merging. Keep `anland-unified`, `mgl-unified`, WSL `~/mgl-xbuild-a64`, `~/mgl-anl-bld` and `~/sysroots`. Don't touch `wgl-host` or `~/repos/mobilegl-cts-gl33`.
|
||||
- **Core profile only:** don't use fixed-function test apps such as glxgears.
|
||||
- **Device:**
|
||||
- stop device work while the user is using the phone;
|
||||
- on USB power, watch the battery (stop below 40%);
|
||||
- wireless adb needs re-enabling after a reboot.
|
||||
@@ -0,0 +1,453 @@
|
||||
# glmark2 baseline: MobileGL (Espryt, Magma) vs the stock kgsl driver stack on anland
|
||||
|
||||
Measured 2026-10-04 on the anland Plasma desktop. **What was optimized since, the current numbers and the remaining work: [glmark2-handoff.md](glmark2-handoff.md).** This is the phase-1 baseline for the
|
||||
performance work: approximate numbers, how they were taken, where MobileGL loses, and a ranked list
|
||||
of general fixes. The goal was "where does MobileGL fall short", not lab-grade accuracy, so the
|
||||
scores are **approximate** (1-3 valid runs per configuration, see n in the tables); the profiling
|
||||
evidence is the load-bearing part.
|
||||
|
||||
**Headline (pinned clocks, glmark2 score; ratio to stock over the scenes all three stacks ran):**
|
||||
|
||||
| | stock | Espryt | Magma |
|
||||
|---|---|---|---|
|
||||
| es2, 800x600 window | ~1076 | ~1319 (1.19x) | ~778 (0.69x) |
|
||||
| es2, fullscreen 2560x1600 | ~1177 | ~572 (0.47x) | ~354 (0.29x) |
|
||||
| desktop GL, 800x600 window | ~1161 | ~1283 (1.12x) | ~743 (0.64x) |
|
||||
| desktop GL, fullscreen | ~1152 | ~559 (0.49x) | ~353 (0.31x) |
|
||||
|
||||
The windowed averages hide two stories. On light scenes (one or two draws per frame) Espryt is
|
||||
already 1.2-1.5x the stock stack and Magma 0.7-0.9x. Every scene with many draws, client-side
|
||||
vertex arrays or many render-target switches, and everything at full screen, falls far behind:
|
||||
|
||||
| es2 window, FPS | stock | Espryt | Magma |
|
||||
|---|---|---|---|
|
||||
| desktop (blur) | 976 | 275 (0.28) | 157 (0.16) |
|
||||
| desktop (shadow) | 1044 | 234 (0.22) | 125 (0.12) |
|
||||
| ideas | 688 | 138 (0.20) | 66 (0.10) |
|
||||
| terrain | 443 | 149 (0.34) | 115 (0.26) |
|
||||
| build use-vbo=false | 1095 | 467 (0.43) | 472 (0.43) |
|
||||
| refract | 838 | 981 (1.17) | 331 (0.39) |
|
||||
| texture, fullscreen | ~1430 | ~726 (0.51) | ~445 (0.31) |
|
||||
|
||||
## Stacks and environment
|
||||
|
||||
| | stock | MobileGL |
|
||||
|---|---|---|
|
||||
| Android app | `com.anland.consumer` 5.22-367a523 (the original anland) | `com.anland.consumer.mobilegl` 5.22-yuv-video-decode (anland `legacy-mobilegl-unified`) |
|
||||
| Container | `arch-kde` | `arch-kde-mgl` (a clone of it, plus `/opt/mobilegl`) |
|
||||
| Display daemon | the anland module's, `/data/local/tmp/display_daemon.sock` | the app's, `/data/local/tmp/anland-mobilegl/display.sock` |
|
||||
| Compositor | `/usr/bin/kwin_wayland` 6.7.4 (anland producer patch) | `/opt/mobilegl/kwin/bin/kwin_wayland` 6.7.4 (anland backend, renders through the server) |
|
||||
| Client GL | the stock kgsl driver stack: Mesa 26.3.0 freedreno over kgsl (`MESA_LOADER_DRIVER_OVERRIDE=kgsl`, `GALLIUM_DRIVER=kgsl`, `FD_FORCE_KGSL=1` from `/etc/environment`); glvnd vendor `50_mesa.json` only | `/opt/mobilegl/lib/libMobileGL.so` via glvnd `10_mobilegl.json` (sorts before `50_mesa.json`); `MOBILEGL_TRANSPORT=spawn`, `MOBILEGL_IPC_DATA=shm`; run-ahead armed, present credit 1 |
|
||||
| Server | - | the app's `:mobilegl` service; Espryt = DirectGLES, Magma = DirectVulkan (app setting) |
|
||||
| Window presentation | Mesa's Wayland EGL, its own dma-bufs | 3 server-allocated AHB shared images per window over `zwp_linux_dmabuf_v1` (client log: `presented through linux-dmabuf shared images (ABGR8888)`) |
|
||||
|
||||
- Both containers run **byte-identical glmark2 binaries** (glmark2 2023.01-2: md5 `048dcd34...`
|
||||
`glmark2-es2-wayland`, `fde07ceb...` `glmark2-wayland` in both rootfs images) and the same Mesa
|
||||
package; only the GL stack under the client changes.
|
||||
- MobileGL server in the APK: built from `18a5dba0`, code-identical to `3a289222` (the only commit
|
||||
between them is a doc). Client deployed from the same tree.
|
||||
- One desktop owns the display at a time. stock -> MobileGL: `am force-stop com.anland.consumer`,
|
||||
`droidspaces -C /data/local/Droidspaces/Containers/arch-kde/container.config stop`,
|
||||
`sh /data/local/tmp/anl/switch.sh DirectGLES|DirectVulkan` (after a server crash `switch.sh`
|
||||
does not restart a dead `:mobilegl`: send the STOP intent, force-stop the app, open it).
|
||||
MobileGL -> stock: STOP intent + force-stop `com.anland.consumer.mobilegl`,
|
||||
`droidspaces -C .../arch-kde/container.config start`,
|
||||
`monkey -p com.anland.consumer -c android.intent.category.LAUNCHER 1`.
|
||||
- The MobileGL app shows its extra-keys bar by default (`extra_keys_mode` unset = `always`), which
|
||||
shrinks the desktop to about 2560x1410; the original app has `with_keyboard`. For equal fullscreen
|
||||
sizes the MobileGL app got `extra_keys_mode=with_keyboard` in `shared_prefs/anland_settings.xml`
|
||||
for the measurements. Fullscreen = 2560x1600; the tablet was turned to portrait for the late
|
||||
stock runs (1600x2560, same pixel count; the stock app follows auto-rotate).
|
||||
- The MobileGL session restores a System Settings window at login; it was closed before each batch.
|
||||
|
||||
### Device state and clocks
|
||||
|
||||
Lenovo TB321FU (Snapdragon 8 Gen 3, Adreno 750), Android 15, AC power (battery 98-100%), screen on,
|
||||
auto brightness, Plasma idle, no Chrome. **All numbers are at pinned clocks** (the user allowed it;
|
||||
originals restored afterwards):
|
||||
|
||||
| | original | pinned |
|
||||
|---|---|---|
|
||||
| cpufreq policy0 (cpu0-1) | walt 902400-2265600 | min = max = 1804800 |
|
||||
| policy2 (cpu2-4) | walt 614400-3148800 | min = max = 2246400 |
|
||||
| policy5 (cpu5-6) | walt 499200-2956800 | min = max = 2246400 |
|
||||
| policy7 (cpu7) | walt 672000-3302400 | min = max = 2246400 |
|
||||
| kgsl-3d0 devfreq | msm-adreno-tz, 231-903 MHz | min_freq = max_freq = 680000000 |
|
||||
|
||||
```sh
|
||||
C=/sys/devices/system/cpu/cpufreq; G=/sys/class/kgsl/kgsl-3d0/devfreq
|
||||
for e in policy0:1804800 policy2:2246400 policy5:2246400 policy7:2246400; do
|
||||
p=${e%%:*}; f=${e##*:}
|
||||
echo $f > $C/$p/scaling_max_freq; echo $f > $C/$p/scaling_min_freq; echo $f > $C/$p/scaling_max_freq
|
||||
done
|
||||
echo 680000000 > $G/max_freq; echo 680000000 > $G/min_freq; echo 680000000 > $G/max_freq
|
||||
```
|
||||
|
||||
kgsl idle collapse was left on (`idle_timer` 80, `force_*` 0); sampled `cur_freq` read 680 MHz in
|
||||
every run, the CPU clocks held, CPU/GPU zones stayed at 40-62 C, nothing throttled. **Pinning is
|
||||
required:** unpinned, the stock stack scored 425 (es2 window) with the GPU at 310 MHz and the big
|
||||
cores at 672 MHz, every scene stuck at 330-440 fps; the stacks' different load patterns drive DVFS
|
||||
differently, so unpinned numbers do not compare.
|
||||
|
||||
### Method
|
||||
|
||||
- glmark2 default scene list with `-b :duration=5` (5 s per scene; same list). Configurations:
|
||||
`glmark2-es2-wayland` and `glmark2-wayland`, each 800x600 windowed and `--fullscreen`.
|
||||
- MobileGL runs: `MGLOG=/tmp/pb-<tag>.log mgrun offscreen bash -c '<glmark2 command>'` (as root in
|
||||
the container; `mgrun` is the anland-mobilegl-plasma skill's). Stock runs:
|
||||
`sudo -u swung0x48 bash -c 'set -a; . /etc/environment; set +a; export XDG_RUNTIME_DIR=/run/user/1000 WAYLAND_DISPLAY=wayland-0; <glmark2 command>'`.
|
||||
- Runs interleaved across stacks; before each run all CPU/GPU zones below 46 C (min 45 s wait).
|
||||
- Swap interval: glmark2 sets interval 0 on Wayland (`--swap-mode default`). Neither stack throttles
|
||||
the client: Mesa's interval 0 ignores frame callbacks; MobileGL's `FrameThrottle` waits only after
|
||||
a callback has been outstanding 200 ms. Both compositors repaint at ~125 Hz on the 165 Hz panel.
|
||||
- Frames shown: two screenshots 1 s apart 25 s into each run must differ, and SurfaceFlinger must
|
||||
latch buffers for the anland `SurfaceView` (64-126 per second during runs):
|
||||
`dumpsys SurfaceFlinger --latency "<SurfaceView[com.anland.consumer...](BLAST)#N>"`, counting
|
||||
present times within the last second. **The stock desktop intermittently turns black mid-run** (a
|
||||
pure-black 21707-byte screenshot) while SurfaceFlinger keeps latching ~125 buffers/s, and its score
|
||||
then jumps to ~1420-1500; a powerdevil inhibit (`kde-inhibit --power --screenSaver` +
|
||||
`kscreen-doctor --dpms on`) did not stop it, restarting the stock container + app clears it. Stock
|
||||
runs were therefore probed every 15 s and every run with a black probe was discarded (3 of 8, plus
|
||||
a first pinned round with a black screen throughout), so stock n is 1-2 per configuration.
|
||||
- Overall glmark2 score = mean scene FPS of the scenes that ran. MobileGL does not run the two
|
||||
`buffer ... update-method=map` scenes (`GL_OES_mapbuffer` is not in its ES extension string),
|
||||
whose stock FPS is low (330-408), so its raw score is flattered; the "common scenes" ratio is the
|
||||
fair one.
|
||||
- `--off-screen` is **not comparable**: on MobileGL glFinish does not wait for the GPU (C1 below), so
|
||||
`glmark2-wayland --off-screen` reported 6846 (Espryt) and 12117 (Magma) against 791 on stock, and
|
||||
Magma's server crashed in it (C2); `glmark2-es2-wayland --off-screen` does not start on MobileGL
|
||||
("Could not initialize canvas": glmark2 picks `GL_RGBA4` and no depth because `GL_OES_rgb8_rgba8`
|
||||
and `GL_OES_depth24` are not advertised).
|
||||
|
||||
### Profiling method
|
||||
|
||||
Single scenes, 18-30 s (`-b <scene>:duration=18`), after 7-9 s of warm-up:
|
||||
`simpleperf record -e cpu-clock -f 4000 -p <client>,<server>,<kwin> --duration 8`, `top -H -d 8`,
|
||||
`/sys/class/kgsl/kgsl-3d0/gpubusy`, and `MOBILEGL_PIPE_STATS=1` on the client
|
||||
(`P65LinkMetrics kind=frame|frame-op|frame-sent` per-frame lines: wall, client CPU, transport wait,
|
||||
blocking replies by wire op, records by wire op). Call graphs: `simpleperf record --trace-offcpu -g`.
|
||||
The container client is an ordinary process on the same kernel, so Android's simpleperf samples it.
|
||||
Symbolization: the APK's server lib is stripped; a RelWithDebInfo build of the same tree
|
||||
(`build-android.sh`) has every function at +0x80 (checked on all 7970 exported functions), so a
|
||||
server `vaddr_in_file` + 0x80 goes into `llvm-symbolizer`. For the container client simpleperf cannot
|
||||
read the ELF and prints offsets from the start of the executable mapping: add 0x4fb000 (the r-x
|
||||
segment's page-aligned vaddr) for the deployed client lib.
|
||||
|
||||
## Scores (approximate)
|
||||
|
||||
### Overall scores (median of runs; min-max in brackets; n = runs)
|
||||
|
||||
| Configuration | stock | Espryt | Magma | Espryt/stock | Magma/stock | Espryt/stock (common scenes) | Magma/stock (common scenes) |
|
||||
|---|---|---|---|---|---|---|---|
|
||||
| glmark2-es2-wayland, 800x600 window | 1076 [1076-1076] n=1 | 1319 [1298-1363] n=3 | 778 [743-813] n=2 | 1.23 | 0.72 | 1.19 | 0.69 |
|
||||
| glmark2-es2-wayland, fullscreen | 1177 [1172-1182] n=2 | 572 [556-577] n=3 | 354 [352-357] n=2 | 0.49 | 0.30 | 0.47 | 0.29 |
|
||||
| glmark2-wayland (desktop GL), 800x600 window | 1161 [1156-1166] n=2 | 1283 [1248-1299] n=3 | 743 [718-768] n=2 | 1.11 | 0.64 | 1.12 | 0.64 |
|
||||
| glmark2-wayland (desktop GL), fullscreen | 1152 [1152-1152] n=1 | 559 [558-566] n=3 | 353 [350-356] n=2 | 0.49 | 0.31 | 0.49 | 0.31 |
|
||||
|
||||
### Per-scene FPS: glmark2-es2-wayland, 800x600 window (median of runs)
|
||||
|
||||
| Scene | stock | Espryt | Magma | Espryt/stock | Magma/stock |
|
||||
|---|---|---|---|---|---|
|
||||
| build use-vbo=false | 1095 | 467 | 472 | 0.43 | 0.43 |
|
||||
| build use-vbo=true | 1287 | 1675 | 1062 | 1.30 | 0.83 |
|
||||
| texture texture-filter=nearest | 1276 | 1482 | 948 | 1.16 | 0.74 |
|
||||
| texture texture-filter=linear | 1269 | 1672 | 915 | 1.32 | 0.72 |
|
||||
| texture texture-filter=mipmap | 1283 | 1689 | 860 | 1.32 | 0.67 |
|
||||
| shading shading=gouraud | 1157 | 1433 | 873 | 1.24 | 0.75 |
|
||||
| shading shading=blinn-phong-inf | 1143 | 1779 | 997 | 1.56 | 0.87 |
|
||||
| shading shading=phong | 1137 | 1582 | 966 | 1.39 | 0.85 |
|
||||
| shading shading=cel | 1237 | 1786 | 854 | 1.44 | 0.69 |
|
||||
| bump bump-render=high-poly | 1265 | 1777 | 984 | 1.40 | 0.78 |
|
||||
| bump bump-render=normals | 1225 | 1647 | 1018 | 1.34 | 0.83 |
|
||||
| bump bump-render=height | 1232 | 1738 | 920 | 1.41 | 0.75 |
|
||||
| effect2d kernel=0,1,0;1,-4,1;0,1,0; | 1270 | 1706 | 929 | 1.34 | 0.73 |
|
||||
| effect2d kernel=1,1,1,1,1;1,1,1,1,1;1,1,1,1,1; | 1217 | 1707 | 908 | 1.40 | 0.75 |
|
||||
| pulsar light=false:quads=5:texture=false | 1298 | 1531 | 688 | 1.18 | 0.53 |
|
||||
| desktop blur-radius=5:effect=blur:passes=1:separable=true:windows=4 | 976 | 275 | 157 | 0.28 | 0.16 |
|
||||
| desktop effect=shadow:windows=4 | 1044 | 234 | 125 | 0.22 | 0.12 |
|
||||
| buffer columns=200:interleave=false:update-dispersion=0.9:update-fraction=0.5:update-method=map | 330 | unsupported | unsupported | - | - |
|
||||
| buffer columns=200:interleave=false:update-dispersion=0.9:update-fraction=0.5:update-method=subdata | 441 | 573 | 482 | 1.30 | 1.09 |
|
||||
| buffer columns=200:interleave=true:update-dispersion=0.9:update-fraction=0.5:update-method=map | 408 | unsupported | unsupported | - | - |
|
||||
| ideas speed=duration | 688 | 138 | 66 | 0.20 | 0.10 |
|
||||
| jellyfish <default> | 1185 | 1438 | 841 | 1.21 | 0.71 |
|
||||
| terrain <default> | 443 | 149 | 115 | 0.34 | 0.26 |
|
||||
| shadow <default> | 975 | 1139 | 644 | 1.17 | 0.66 |
|
||||
| refract <default> | 838 | 981 | 331 | 1.17 | 0.39 |
|
||||
| conditionals fragment-steps=0:vertex-steps=0 | 1291 | 1671 | 1023 | 1.29 | 0.79 |
|
||||
| conditionals fragment-steps=5:vertex-steps=0 | 1173 | 1649 | 886 | 1.41 | 0.76 |
|
||||
| conditionals fragment-steps=0:vertex-steps=5 | 1263 | 1512 | 1042 | 1.20 | 0.83 |
|
||||
| function fragment-complexity=low:fragment-steps=5 | 1280 | 1461 | 993 | 1.14 | 0.78 |
|
||||
| function fragment-complexity=medium:fragment-steps=5 | 1175 | 1745 | 1046 | 1.49 | 0.89 |
|
||||
| loop fragment-loop=false:fragment-steps=5:vertex-steps=5 | 1246 | 1647 | 985 | 1.32 | 0.79 |
|
||||
| loop fragment-steps=5:fragment-uniform=false:vertex-steps=5 | 1178 | 1697 | 976 | 1.44 | 0.83 |
|
||||
| loop fragment-steps=5:fragment-uniform=true:vertex-steps=5 | 1234 | 1531 | 1046 | 1.24 | 0.85 |
|
||||
|
||||
### Per-scene FPS: glmark2-es2-wayland, fullscreen (median of runs)
|
||||
|
||||
| Scene | stock | Espryt | Magma | Espryt/stock | Magma/stock |
|
||||
|---|---|---|---|---|---|
|
||||
| build use-vbo=false | 1355 | 366 | 322 | 0.27 | 0.24 |
|
||||
| build use-vbo=true | 1518 | 798 | 491 | 0.53 | 0.32 |
|
||||
| texture texture-filter=nearest | 1396 | 726 | 449 | 0.52 | 0.32 |
|
||||
| texture texture-filter=linear | 1430 | 726 | 442 | 0.51 | 0.31 |
|
||||
| texture texture-filter=mipmap | 1437 | 723 | 449 | 0.50 | 0.31 |
|
||||
| shading shading=gouraud | 1438 | 679 | 423 | 0.47 | 0.29 |
|
||||
| shading shading=blinn-phong-inf | 1495 | 687 | 259 | 0.46 | 0.17 |
|
||||
| shading shading=phong | 1431 | 682 | 438 | 0.48 | 0.31 |
|
||||
| shading shading=cel | 1478 | 679 | 435 | 0.46 | 0.29 |
|
||||
| bump bump-render=high-poly | 1481 | 745 | 463 | 0.50 | 0.31 |
|
||||
| bump bump-render=normals | 1434 | 780 | 465 | 0.54 | 0.32 |
|
||||
| bump bump-render=height | 1467 | 790 | 475 | 0.54 | 0.32 |
|
||||
| effect2d kernel=0,1,0;1,-4,1;0,1,0; | 1346 | 582 | 390 | 0.43 | 0.29 |
|
||||
| effect2d kernel=1,1,1,1,1;1,1,1,1,1;1,1,1,1,1; | 698 | 468 | 354 | 0.67 | 0.51 |
|
||||
| pulsar light=false:quads=5:texture=false | 1379 | 631 | 337 | 0.46 | 0.24 |
|
||||
| desktop blur-radius=5:effect=blur:passes=1:separable=true:windows=4 | 671 | 219 | 108 | 0.33 | 0.16 |
|
||||
| desktop effect=shadow:windows=4 | 1031 | 207 | 99 | 0.20 | 0.10 |
|
||||
| buffer columns=200:interleave=false:update-dispersion=0.9:update-fraction=0.5:update-method=map | 266 | unsupported | unsupported | - | - |
|
||||
| buffer columns=200:interleave=false:update-dispersion=0.9:update-fraction=0.5:update-method=subdata | 410 | 474 | 281 | 1.15 | 0.68 |
|
||||
| buffer columns=200:interleave=true:update-dispersion=0.9:update-fraction=0.5:update-method=map | 351 | unsupported | unsupported | - | - |
|
||||
| ideas speed=duration | 813 | 117 | 57 | 0.14 | 0.07 |
|
||||
| jellyfish <default> | 1346 | 616 | 277 | 0.46 | 0.21 |
|
||||
| terrain <default> | 141 | 113 | 92 | 0.80 | 0.65 |
|
||||
| shadow <default> | 796 | 656 | 401 | 0.82 | 0.50 |
|
||||
| refract <default> | 157 | 225 | 189 | 1.43 | 1.20 |
|
||||
| conditionals fragment-steps=0:vertex-steps=0 | 1457 | 649 | 421 | 0.45 | 0.29 |
|
||||
| conditionals fragment-steps=5:vertex-steps=0 | 1522 | 647 | 402 | 0.43 | 0.26 |
|
||||
| conditionals fragment-steps=0:vertex-steps=5 | 1445 | 649 | 430 | 0.45 | 0.30 |
|
||||
| function fragment-complexity=low:fragment-steps=5 | 1614 | 648 | 417 | 0.40 | 0.26 |
|
||||
| function fragment-complexity=medium:fragment-steps=5 | 1456 | 647 | 408 | 0.44 | 0.28 |
|
||||
| loop fragment-loop=false:fragment-steps=5:vertex-steps=5 | 1517 | 646 | 415 | 0.43 | 0.27 |
|
||||
| loop fragment-steps=5:fragment-uniform=false:vertex-steps=5 | 1561 | 651 | 416 | 0.42 | 0.27 |
|
||||
| loop fragment-steps=5:fragment-uniform=true:vertex-steps=5 | 1545 | 649 | 425 | 0.42 | 0.28 |
|
||||
|
||||
### Per-scene FPS: glmark2-wayland (desktop GL), 800x600 window (median of runs)
|
||||
|
||||
| Scene | stock | Espryt | Magma | Espryt/stock | Magma/stock |
|
||||
|---|---|---|---|---|---|
|
||||
| build use-vbo=false | 1216 | 457 | 474 | 0.38 | 0.39 |
|
||||
| build use-vbo=true | 1327 | 1805 | 1043 | 1.36 | 0.79 |
|
||||
| texture texture-filter=nearest | 1360 | 1557 | 923 | 1.14 | 0.68 |
|
||||
| texture texture-filter=linear | 1366 | 1781 | 1019 | 1.30 | 0.75 |
|
||||
| texture texture-filter=mipmap | 1372 | 1700 | 938 | 1.24 | 0.68 |
|
||||
| shading shading=gouraud | 1413 | 1324 | 990 | 0.94 | 0.70 |
|
||||
| shading shading=blinn-phong-inf | 1309 | 1768 | 930 | 1.35 | 0.71 |
|
||||
| shading shading=phong | 1349 | 1558 | 1021 | 1.15 | 0.76 |
|
||||
| shading shading=cel | 1268 | 1598 | 1068 | 1.26 | 0.84 |
|
||||
| bump bump-render=high-poly | 1319 | 1851 | 923 | 1.40 | 0.70 |
|
||||
| bump bump-render=normals | 1315 | 1451 | 1004 | 1.10 | 0.76 |
|
||||
| bump bump-render=height | 1363 | 1839 | 986 | 1.35 | 0.72 |
|
||||
| effect2d kernel=0,1,0;1,-4,1;0,1,0; | 1376 | 1533 | 663 | 1.11 | 0.48 |
|
||||
| effect2d kernel=1,1,1,1,1;1,1,1,1,1;1,1,1,1,1; | 1320 | 1743 | 603 | 1.32 | 0.46 |
|
||||
| pulsar light=false:quads=5:texture=false | 1302 | 1488 | 705 | 1.14 | 0.54 |
|
||||
| desktop blur-radius=5:effect=blur:passes=1:separable=true:windows=4 | 966 | 273 | 127 | 0.28 | 0.13 |
|
||||
| desktop effect=shadow:windows=4 | 1070 | 233 | 118 | 0.22 | 0.11 |
|
||||
| buffer columns=200:interleave=false:update-dispersion=0.9:update-fraction=0.5:update-method=map | 355 | 462 | 437 | 1.30 | 1.23 |
|
||||
| buffer columns=200:interleave=false:update-dispersion=0.9:update-fraction=0.5:update-method=subdata | 418 | 596 | 437 | 1.43 | 1.05 |
|
||||
| buffer columns=200:interleave=true:update-dispersion=0.9:update-fraction=0.5:update-method=map | 413 | 501 | 522 | 1.21 | 1.26 |
|
||||
| ideas speed=duration | 747 | 129 | 67 | 0.17 | 0.09 |
|
||||
| jellyfish <default> | 1218 | 1434 | 835 | 1.18 | 0.69 |
|
||||
| terrain <default> | 448 | 145 | 112 | 0.32 | 0.25 |
|
||||
| shadow <default> | 1056 | 1208 | 607 | 1.14 | 0.57 |
|
||||
| refract <default> | 831 | 928 | 310 | 1.12 | 0.37 |
|
||||
| conditionals fragment-steps=0:vertex-steps=0 | 1362 | 1773 | 1008 | 1.30 | 0.74 |
|
||||
| conditionals fragment-steps=5:vertex-steps=0 | 1353 | 1527 | 937 | 1.13 | 0.69 |
|
||||
| conditionals fragment-steps=0:vertex-steps=5 | 1317 | 1873 | 1047 | 1.42 | 0.80 |
|
||||
| function fragment-complexity=low:fragment-steps=5 | 1369 | 1545 | 961 | 1.13 | 0.70 |
|
||||
| function fragment-complexity=medium:fragment-steps=5 | 1322 | 1701 | 977 | 1.29 | 0.74 |
|
||||
| loop fragment-loop=false:fragment-steps=5:vertex-steps=5 | 1384 | 1779 | 863 | 1.28 | 0.62 |
|
||||
| loop fragment-steps=5:fragment-uniform=false:vertex-steps=5 | 1370 | 1556 | 1028 | 1.14 | 0.75 |
|
||||
| loop fragment-steps=5:fragment-uniform=true:vertex-steps=5 | 1376 | 1757 | 877 | 1.28 | 0.64 |
|
||||
|
||||
### Per-scene FPS: glmark2-wayland (desktop GL), fullscreen (median of runs)
|
||||
|
||||
| Scene | stock | Espryt | Magma | Espryt/stock | Magma/stock |
|
||||
|---|---|---|---|---|---|
|
||||
| build use-vbo=false | 1293 | 372 | 301 | 0.29 | 0.23 |
|
||||
| build use-vbo=true | 1479 | 797 | 500 | 0.54 | 0.34 |
|
||||
| texture texture-filter=nearest | 1368 | 725 | 440 | 0.53 | 0.32 |
|
||||
| texture texture-filter=linear | 1387 | 721 | 449 | 0.52 | 0.32 |
|
||||
| texture texture-filter=mipmap | 1411 | 726 | 446 | 0.51 | 0.32 |
|
||||
| shading shading=gouraud | 1484 | 676 | 426 | 0.46 | 0.29 |
|
||||
| shading shading=blinn-phong-inf | 1490 | 685 | 429 | 0.46 | 0.29 |
|
||||
| shading shading=phong | 1382 | 677 | 431 | 0.49 | 0.31 |
|
||||
| shading shading=cel | 1497 | 682 | 418 | 0.46 | 0.28 |
|
||||
| bump bump-render=high-poly | 1533 | 751 | 458 | 0.49 | 0.30 |
|
||||
| bump bump-render=normals | 1476 | 785 | 449 | 0.53 | 0.30 |
|
||||
| bump bump-render=height | 1418 | 789 | 465 | 0.56 | 0.33 |
|
||||
| effect2d kernel=0,1,0;1,-4,1;0,1,0; | 1340 | 582 | 389 | 0.43 | 0.29 |
|
||||
| effect2d kernel=1,1,1,1,1;1,1,1,1,1;1,1,1,1,1; | 656 | 467 | 329 | 0.71 | 0.50 |
|
||||
| pulsar light=false:quads=5:texture=false | 1404 | 627 | 353 | 0.45 | 0.25 |
|
||||
| desktop blur-radius=5:effect=blur:passes=1:separable=true:windows=4 | 673 | 232 | 108 | 0.34 | 0.16 |
|
||||
| desktop effect=shadow:windows=4 | 1027 | 196 | 95 | 0.19 | 0.09 |
|
||||
| buffer columns=200:interleave=false:update-dispersion=0.9:update-fraction=0.5:update-method=map | 267 | 331 | 284 | 1.24 | 1.06 |
|
||||
| buffer columns=200:interleave=false:update-dispersion=0.9:update-fraction=0.5:update-method=subdata | 423 | 494 | 263 | 1.17 | 0.62 |
|
||||
| buffer columns=200:interleave=true:update-dispersion=0.9:update-fraction=0.5:update-method=map | 345 | 301 | 300 | 0.87 | 0.87 |
|
||||
| ideas speed=duration | 818 | 120 | 67 | 0.15 | 0.08 |
|
||||
| jellyfish <default> | 1345 | 613 | 277 | 0.46 | 0.21 |
|
||||
| terrain <default> | 148 | 111 | 91 | 0.75 | 0.62 |
|
||||
| shadow <default> | 801 | 663 | 400 | 0.83 | 0.50 |
|
||||
| refract <default> | 157 | 223 | 189 | 1.42 | 1.20 |
|
||||
| conditionals fragment-steps=0:vertex-steps=0 | 1348 | 645 | 423 | 0.48 | 0.31 |
|
||||
| conditionals fragment-steps=5:vertex-steps=0 | 1480 | 645 | 417 | 0.44 | 0.28 |
|
||||
| conditionals fragment-steps=0:vertex-steps=5 | 1411 | 649 | 418 | 0.46 | 0.30 |
|
||||
| function fragment-complexity=low:fragment-steps=5 | 1425 | 650 | 431 | 0.46 | 0.30 |
|
||||
| function fragment-complexity=medium:fragment-steps=5 | 1398 | 647 | 411 | 0.46 | 0.29 |
|
||||
| loop fragment-loop=false:fragment-steps=5:vertex-steps=5 | 1446 | 645 | 418 | 0.45 | 0.29 |
|
||||
| loop fragment-steps=5:fragment-uniform=false:vertex-steps=5 | 1403 | 646 | 413 | 0.46 | 0.29 |
|
||||
| loop fragment-steps=5:fragment-uniform=true:vertex-steps=5 | 1546 | 648 | 395 | 0.42 | 0.26 |
|
||||
|
||||
## Where the time goes
|
||||
|
||||
Per-frame profile of the scenes that lose (es2 window unless noted, pinned; client = the glmark2
|
||||
thread, server = its `mgl-srv-apply` thread, % of one core over 8 s; waits = blocking
|
||||
client-to-server replies per frame; present RTT = wait for the shared-image present reply):
|
||||
|
||||
| Espryt | fps | records/frame | waits/frame (op) | client CPU | server apply thread | GPU busy | present RTT |
|
||||
|---|---|---|---|---|---|---|---|
|
||||
| texture | 1394 | 11 | 1 (SharedImage present) | 31% | 44% | 40% | 0.30 ms |
|
||||
| texture fullscreen | 721 | 11 | 1 | 24% | 35% | 98% | 0.60 ms |
|
||||
| desktop blur | 228 | 299 | 29 (28 ResourceCreate + present) | 40% | 51% | 13% | - |
|
||||
| desktop shadow | 173 | 395 | 53 (52 ResourceCreate + present) | 40% | 50% | 7% | - |
|
||||
| ideas | 118 | 587 (305 draws) | 1 | 30% | 45% | 7% | 5.6 ms |
|
||||
| terrain | 130 | 224 | 1 | 29% | 45% | 36% | 0.63 ms |
|
||||
| build use-vbo=false | 448 | 21 | 3 (2 ResourceCreate + present) | 33% | 36% | 15% | - |
|
||||
|
||||
| Magma | fps | waits/frame | client CPU | server apply thread | GPU busy | present RTT |
|
||||
|---|---|---|---|---|---|---|
|
||||
| texture | 916 | 1 | 28% | 50% | 37% | 0.58 ms |
|
||||
| texture fullscreen | 418 | 1 | 17% | 29% | 75% | 1.25 ms |
|
||||
| desktop blur | 118 | 29 | 35% | 52% | 9% | - |
|
||||
| desktop shadow | 115 | 53 | 38% | 53% | 9% | - |
|
||||
| ideas | 53 | 1 | 24% | 60% | 14% | 15.2 ms |
|
||||
| terrain | 108 | 1 | 31% | 49% | 27% | 0.91 ms |
|
||||
| build use-vbo=false | 498 | 3 | 42% | 49% | 26% | - |
|
||||
|
||||
**The common shape: nothing is saturated.** Outside fullscreen the GPU is 7-40% busy, and neither
|
||||
the client thread nor the server apply thread is near 100%. Both sides spend most of the frame
|
||||
waiting for each other, and each handoff costs a wake-up. Evidence that the handoffs, not the work,
|
||||
set the frame time:
|
||||
|
||||
- With **`MOBILEGL_IPC_SPIN_US=1000`** on the client only (Espryt; the server keeps its 50 us), the
|
||||
client spins through short replies instead of parking: ideas 94 -> 185 fps, terrain 132 -> 315,
|
||||
desktop shadow 187 -> 322, texture 1543 -> 1837 (8 s single-scene runs).
|
||||
- On Espryt's server in ideas the apply thread is 50% off-CPU, almost all of it parked in
|
||||
`SocketDoorbell::Park` waiting for records, and 18% of its on-CPU time is `SocketDoorbell::Notify`
|
||||
(a socket write that wakes the client). The client is 75% off-CPU in `poll`. The server's own
|
||||
frame work is ~2 ms (P65ServerFrame `apply_ms` for the ~600-record frames) of an 8.5 ms frame.
|
||||
|
||||
## Ranked bottlenecks and proposed general fixes
|
||||
|
||||
Gains are estimates from the evidence above, at the pinned clocks; none of the fixes is
|
||||
glmark2-specific.
|
||||
|
||||
### Shared: client library and pipe (both backends)
|
||||
|
||||
1. **Blocking ResourceCreate for client-memory vertex/index arrays.** Every draw that sources a
|
||||
client array makes a brand-new owned buffer per array (`MG_Impl/Pipe/OwnedDrawInputs.h`
|
||||
`MakeOwnedBuffer` -> `BufferObject` ctor -> `MGPipeEmitResourceCreate` -> `EmitCreateBlocking` ->
|
||||
`EmitAndWait`): one round trip per array per draw, plus a respecify, a subdata and a destroy
|
||||
record. desktop blur pays 28 and shadow 52 of them per frame; 55% of the client's samples are the
|
||||
spin in `SessionProducer::WaitForAppliedOrEventBacklog` under `EmitCreateBlocking`. The fetch plan
|
||||
also sorts the referenced vertex list per draw (`std::sort` = 27% of the client in build
|
||||
use-vbo=false) even for a `glDrawArrays` range that is contiguous.
|
||||
**Fix:** a per-context streaming upload buffer for client arrays (one long-lived server resource,
|
||||
sub-allocated per draw, reused once the frames that read it retired; grows on overflow), or
|
||||
client-minted creates that need no reply; plus a contiguous-range fast path (one memcpy of
|
||||
`[first, first+count)` per attribute, no sort). **Gain:** blocking waits/frame -> ~1; desktop
|
||||
blur/shadow 2-3x, build use-vbo=false ~2x, on both backends; helps every GLES2-style app.
|
||||
**Risk:** sub-allocation lifetime vs in-flight draws on both backends; validate with the
|
||||
OwnedDrawInputs/Pipe unit tests and the retrace CI.
|
||||
2. **Wake-up latency of every blocking wait and every ring handoff.** Doorbells are one byte on a
|
||||
unix socket; a parked waiter needs a socket write plus a scheduler wake-up (hundreds of us to ms
|
||||
at these clocks), and the server rings the client on every applied-watermark advance while the
|
||||
client is parked, even if the client waits for a much later sequence (18% of Espryt's apply
|
||||
thread is `SocketDoorbell::Notify`). **Fix:** (a) the waiter publishes the sequence it waits for
|
||||
and the server rings only when `applied >= target`; (b) a bounded adaptive spin sized from the
|
||||
recently measured reply latency, only while a reply is expected (never when idle); (c) optionally
|
||||
futex wait/wake on the shared ring page instead of socket bytes (same kernel). **Gain:** spin alone
|
||||
gave 1.2x (light) to 2.4x (terrain); expect 1.3-2x on draw-heavy scenes, both backends.
|
||||
**Risk:** lost wake-ups (keep the doorbell's two-fence protocol), CPU and power at idle; RingTest,
|
||||
MultiSession tests, idle CPU of the desktop.
|
||||
3. **Synchronous per-frame present.** `WindowSurface::Present` -> `PresentToSharedImage` ->
|
||||
`EmitSharedImage` is `EmitAndWait`: the client waits until the server has applied the whole frame
|
||||
and queued the blit, and eglSwapBuffers' Present record also holds a present credit of 1. The
|
||||
client cannot record frame N+1 while the server finishes N (texture: 0.71 ms frame = 0.26 ms of
|
||||
client CPU + 0.30 ms of wait). **Fix:** make the shared-image present asynchronous: commit the
|
||||
`wl_buffer` from the reply on the event ring (or let the server order the compositor's acquire of
|
||||
that image after the producer's present record), and allow credit 2. **Gain:** 1.3-1.8x on light
|
||||
scenes. **Risk:** ordering with the compositor's import (Chrome flicker test, KWin, desktop-verify).
|
||||
4. **Fullscreen pays an extra full-frame copy and full composition.** Every frame the server copies
|
||||
the client's default framebuffer (a server pbuffer / Magma swapchain image) into the shared image
|
||||
(Espryt `glBlitFramebuffer`, Magma `vkCmdCopyImage` in a second submission), and KWin composites
|
||||
the whole screen (85 buffers/s latched during Espryt fullscreen). At 2560x1600 the GPU is 98% busy
|
||||
(Espryt) on texture for 726 fps against ~1430 on stock, whose fullscreen is even faster than its
|
||||
windowed run. **Fix:** let the client render straight into the window's shared images (default
|
||||
framebuffer = the current back image; the row order can be expressed with linux-dmabuf's
|
||||
`Y_INVERT` flag instead of the flipping blit); separately, direct scanout of fullscreen clients in
|
||||
the anland KWin backend. **Gain:** fullscreen 1.5-2x on both backends. **Risk:** buffer age and
|
||||
damage, resize, device loss; desktop-verify and Chrome.
|
||||
5. **Per-record fixed cost on the server.** The server is built for `android-26`, so every
|
||||
`thread_local` goes through emulated TLS: `__emutls_get_address` + `pthread_getspecific` are 7-12%
|
||||
of Espryt's and ~3% of Magma's apply thread. `ServerLoop::DrainRing` takes two
|
||||
`steady_clock::now()` per record for the P65ServerFrame statistics even when they are off (5% on
|
||||
Espryt), and `MGPipeApplier()` / `ResolveThreadApplierKey` / `MGPipeApplierShareGroupKeyFor` (TLS
|
||||
+ mutex) run per record (~5%). **Fix:** resolve the applier/session once per drain and pass it
|
||||
down; time records only with the statistics on; consider ELF TLS (API 29+) for the anland server
|
||||
build. **Gain:** 10-15% of server CPU. **Risk:** low.
|
||||
6. **Small:** a one-draw frame sends 11 records; `CreateVertexElements` is re-sent per draw (ideas:
|
||||
76 per frame) instead of being deduplicated by content on the client.
|
||||
|
||||
### Espryt (DirectGLES)
|
||||
|
||||
1. **Per-draw state synchronization** (`DG::PrepareForDraw` 28% of the apply thread in ideas:
|
||||
`SyncCurrentProgramByHandle`, `BindCurrentProgramWithResources`, `SyncNeccessaryBuffers`, VAO
|
||||
`SyncToBackendFromApplier`, `ResolveVaoTwin` / `ResolveProgramTwin` registry lookups, texture
|
||||
sync). The same per-draw redundancy as on Minecraft: version-gated early-outs keyed on monotonic
|
||||
lifetime ids. **Gain:** 10-20% on draw-heavy scenes once the pipe is fixed. **Risk:** stale
|
||||
caches; the retrace CI.
|
||||
2. Parity: `GL_OES_mapbuffer`, `GL_OES_rgb8_rgba8`, `GL_OES_depth24` missing from ES contexts (two
|
||||
Unsupported scenes; es2 off-screen does not start).
|
||||
|
||||
### Magma (DirectVulkan)
|
||||
|
||||
1. **A VkRenderPass per draw.** `VulkanRenderer::SetupWireDraw` (`WireDraw.inc`) calls
|
||||
`RetireWireDrawPass()` unconditionally, which ends the active render pass, and begins a new one
|
||||
at the end of setup, for every draw. In ideas (305 draws/frame) `SetupWireDraw` is 41% of the
|
||||
apply thread and End/BeginRenderPass ~19%; on a tiler every pass also loads and stores its
|
||||
attachments. **Fix:** keep the pass open while the `WireDrawPassKey` (attachments, extent, epochs)
|
||||
is unchanged and nothing that must run outside a pass came in between (clear outside the pass,
|
||||
transfer, barrier, readback, layout change of an attachment, query); retire lazily. **Gain:**
|
||||
ideas, terrain, desktop 1.5-2x on Magma; less load/store bandwidth at full screen. **Risk:**
|
||||
attachment layout tracking and feedback loops; Magma unit tests (never the DirectVulkan
|
||||
integration tests), retrace CI.
|
||||
2. **Per-frame submission overhead.** Per frame: `FlushPendingCommands` for the frame, a second
|
||||
submission for the shared-image copy, and `Present()` of the client's own offscreen default
|
||||
surface (swapchain acquire + submit through libgui). `GpuProgressMarkers::SubmitBracketed` (hang
|
||||
watch) is 12% of texture fullscreen, and `FreeRetiredCommandBuffersCompletedUpTo` +
|
||||
`EndCommandRecording` ~25% of ideas (command buffers freed and reallocated rather than reset and
|
||||
reused). **Fix:** one submission per frame (append the copy), skip `Present` for a surface whose
|
||||
frames only go to shared images, recycle command buffers per frame slot, coalesce markers.
|
||||
**Gain:** light scenes 1.3-1.5x on Magma.
|
||||
3. **Allocation churn.** scudo malloc/free with lock contention (`__aarch64_cas4_acq` 20% + scudo
|
||||
~15% of the ideas apply thread): per-draw vectors (`BeginRenderPass` clear values, vertex input
|
||||
state objects, retired wire objects). **Fix:** per-frame arenas / small vectors. **Gain:** 10-20%.
|
||||
4. **A VkRenderPass + VkFramebuffer created per clear** (`WireFramebuffer.inc` ~306-311): 7% of
|
||||
texture fullscreen, and the objects pile up when nothing retires them (C2).
|
||||
|
||||
### Correctness found on the way
|
||||
|
||||
- **C1 glFinish does not wait for the GPU** on the remote path: `ClientSession::Finish` only waits
|
||||
for the server to apply (`WaitForApplyToCatchUp`). Off-screen glmark2 then reports 6846 / 12117
|
||||
and nothing bounds the GPU queue. It must reach the backend (driver finish / fence wait) and reply.
|
||||
- **C2 Magma server crash** under `glmark2-wayland --off-screen`: `VK_ERROR_OUT_OF_HOST_MEMORY` FATAL
|
||||
at `WireFramebuffer.inc:311` (`vkCreateFramebuffer` in `ClearWireFramebuffer`), then SIGSEGV in
|
||||
`vkCmdBeginRenderPass` (two server crashes in a row); the per-clear objects accumulate when the
|
||||
client runs ahead with no backpressure (C1).
|
||||
- **C3** ES extension parity (Espryt item 2).
|
||||
|
||||
## Next steps
|
||||
|
||||
In this order, each measured on the affected scenes at the pinned clocks, frames shown, Plasma /
|
||||
Chrome / lock-unlock checked on both backends: C1-C3, shared 1 (client arrays), shared 2
|
||||
(wake-ups), shared 3/4 (present), Magma 1 (render pass), shared 5 (per-record cost), then each
|
||||
backend's per-draw items.
|
||||
@@ -0,0 +1,201 @@
|
||||
# glmark2 performance work: handoff
|
||||
|
||||
Status on 2026-10-04 after the first optimization pass on top of the
|
||||
[baseline](glmark2-baseline.md). Everything here was measured on the anland Plasma desktop of the
|
||||
Lenovo TB321FU (Adreno 750) at **pinned clocks** (CPU 1.80 / 2.25 / 2.25 / 2.25 GHz, GPU 680 MHz;
|
||||
see the baseline). Single runs or two at most per point, so the numbers are **approximate**
|
||||
(light scenes vary about +-15% run to run). The tablet was in portrait for the later runs, so the
|
||||
"after" fullscreen numbers are 1600x2560 and the "before" ones 2560x1600 (same pixel count).
|
||||
|
||||
## Headline
|
||||
|
||||
glmark2 score, `-b :duration=5`, default scene list:
|
||||
|
||||
| | stock kgsl stack | Espryt before | Espryt now | Magma before | Magma now |
|
||||
|---|---|---|---|---|---|
|
||||
| es2, 800x600 window | ~1076-1180 | ~1319 | **~1887** | ~778 | **~1213** |
|
||||
| es2, fullscreen | ~1177 | ~572 | ~561 | ~354 | ~404 |
|
||||
| desktop GL, 800x600 window | ~1161 | ~1283 | **~1809** | ~743 | **~1186** |
|
||||
|
||||
The "now" es2 window scores include the two `buffer update-method=map` scenes, which MobileGL now
|
||||
runs (they were Unsupported before), so they are a fair comparison with stock's.
|
||||
|
||||
Per scene (es2 window unless marked F = fullscreen; FPS):
|
||||
|
||||
| scene | stock | Espryt before | Espryt now | Magma before | Magma now |
|
||||
|---|---|---|---|---|---|
|
||||
| texture | 1269 | 1672 | ~2210 | 915 | ~1580 |
|
||||
| build use-vbo=false | 1095 | 467 | ~1215 | 472 | ~1040-1190 |
|
||||
| build use-vbo=true | 1287 | 1675 | ~2450 | 1062 | ~1730 |
|
||||
| desktop blur | 976 | 275 | **~1000** | 157 | ~680 |
|
||||
| desktop shadow | 1044 | 234 | **~1000** | 125 | ~830 |
|
||||
| ideas | 688 | 138 | ~550 | 66 | ~354 |
|
||||
| terrain | 443 | 149 | ~220 | 115 | ~157 |
|
||||
| shadow | 975 | 1139 | ~1840 | 644 | ~1170 |
|
||||
| refract | 838 | 981 | ~1280 | 331 | ~520 |
|
||||
| jellyfish | 1185 | 1438 | ~2170 | 841 | ~1155 |
|
||||
| buffer map (2 scenes) | 330 / 408 | Unsupported | ~465 | Unsupported | ~431 |
|
||||
| texture F | ~1430 | ~726 | ~597 | ~445 | ~398 |
|
||||
| terrain F | - | - | ~142 | - | ~112 |
|
||||
|
||||
**Remaining gap:** Espryt is at or above stock in every windowed scene except **ideas (0.8x)** and
|
||||
**terrain (0.5x)**. Magma is behind on most draw-heavy scenes (ideas 0.5x, terrain 0.35x, desktop
|
||||
0.7-0.8x, refract 0.6x). **Fullscreen** is the biggest gap on both backends (0.4-0.5x of stock),
|
||||
and nothing landed here addresses it.
|
||||
|
||||
## Done (all on origin/feat/disaggregated)
|
||||
|
||||
| commit | change | why / evidence | effect (approx) |
|
||||
|---|---|---|---|
|
||||
| `4722fa38` | the baseline report | - | - |
|
||||
| `66b47a10` | **glFinish waits for the GPU** on the remote path (a server fence created, waited with `GL_SYNC_FLUSH_COMMANDS_BIT`, destroyed); **Magma submits** once 1024 retired per-clear objects pile up with nothing submitted; **ES contexts advertise** `GL_OES_rgb8_rgba8`, `GL_OES_depth24`, `GL_OES_mapbuffer` (with `glMapBufferOES` / `glUnmapBufferOES` / `glGetBufferPointervOES` exported as the core calls) | glFinish only waited for the server's apply, so off-screen rendering ran unbounded (glmark2 `--off-screen` "6846" / "12117" fps) and drove Magma's server to `VK_ERROR_OUT_OF_HOST_MEMORY` in `ClearWireFramebuffer`; es2 `--off-screen` could not start (glmark2 picked `GL_RGBA4` and no depth) | off-screen now real numbers (Espryt texture ~866, Magma ~800) and no crash; es2 `--off-screen` runs; the two buffer-map scenes run |
|
||||
| `2de0d6dd` | **client-array buffers are reused** from a per-share-group pool (respecify, a non-blocking record, instead of a blocking ResourceCreate + destroy per array per draw); contiguous element ranges copied in one memcpy; the fetch plan skips sorting an already ascending range | desktop blur/shadow paid 28/52 blocking creates per frame, build use-vbo=false 2; `std::sort` was 27% of the client in build use-vbo=false | build use-vbo=false Espryt 467 -> ~1100, Magma 472 -> ~1040; blocking replies per frame in desktop 29/53 -> 1 (fps of desktop barely moved at this step: the next item was the limit) |
|
||||
| `d627fca3` | **targeted wake-ups:** the client publishes the applied sequence it waits for (`RingControl::producerWakeSeq`, its own cache line); the server rings a parked client only once that sequence is applied (or the event ring filled); the parked flag is stored with release so the notifier sees the target | while the client waited for its present reply the server rang it after every record it applied: 18% of Espryt's apply thread was `SocketDoorbell::Notify`, and every ring was a futile wake-up and re-park on the client | Espryt desktop ~250 -> ~800, ideas 138 -> ~380, texture 1672 -> ~2190; Magma desktop ~150 -> ~550-650, ideas 45 -> ~137, refract 372 -> ~540 |
|
||||
| `963f4d81` | Magma **reuses completed command buffers** (pool resets them at the next begin) instead of `vkFreeCommandBuffers` + `vkAllocateCommandBuffers` per submission | `FreeRetiredCommandBuffersCompletedUpTo` was 15% of Magma's apply thread in ideas | small: Magma texture / desktop +~10% |
|
||||
| `915882b2` | the server **times records only when** `MOBILEGL_SERVER_FRAME_STATS` is on | two `steady_clock::now()` per record were ~5% of Espryt's apply thread | with the next row |
|
||||
| `e5ee31b0` | the anland server build uses **`android-30`** (the APK's minSdk) in `build-android.sh` / `reproduce.md`: `thread_local` is native ELF TLS instead of emulated TLS | `__emutls_get_address` + `pthread_getspecific` were 7-12% of Espryt's apply thread. **An existing build dir keeps its API level: reconfigure (delete it) to get android-30** | Espryt (with the row above) desktop ~800 -> ~1000, ideas ~380 -> ~550, terrain 168 -> ~220; Magma unchanged |
|
||||
| `bb31f374` | Magma **keeps the wire draw's render pass open** across draws to the same attachments. Every command that may not sit inside a pass (barriers, copies, clears, blits, dispatches, other passes' begins) in the resource managers and wire helpers first calls `EndActiveRenderPassOn(cb)` (`RenderPassGuard.h`); the per-draw "make image writes visible" barrier for sampled images is only recorded when an image may have been written since the last one (`WireImageWriteEpoch`, bumped by every pass end, out-of-pass work and storage-image draw); same-layout attachment barriers are skipped when the pass continues | `SetupWireDraw` ended and began a VkRenderPass for every draw (ideas: 305 passes per frame; End/Begin ~21% of the apply thread, plus `vkEndCommandBuffer` cost), and on a tiler each pass loads and stores its attachments | Magma ideas ~146 -> ~354, desktop shadow ~640 -> ~830; visually checked on ideas, terrain, shadow, refract, jellyfish, desktop, bump, conditionals, effect2d, Plasma, Chrome and the lock screen |
|
||||
|
||||
Each landed with the host unit tests green (WSL clang, `ctest -L unit -E DirectVulkan`, 2851
|
||||
tests) and a device check on both backends (frames shown, Plasma, Chrome page + scroll input,
|
||||
`kscreenlocker_greet --testing`).
|
||||
|
||||
## Findings
|
||||
|
||||
- **The common shape before the fixes: nothing was saturated.** GPU 7-40% busy, client and server
|
||||
threads each ~30-50% busy, both waiting for each other with a wake-up per handoff. Removing
|
||||
futile wake-ups (`d627fca3`) was worth more than any per-draw CPU saving.
|
||||
- **Espryt after the fixes:** the remaining windowed gaps are ideas and terrain. Its present reply
|
||||
is still a synchronous round trip per frame, and the server's per-draw state sync
|
||||
(`DG::PrepareForDraw`, 28% of the apply thread in ideas before) is now the larger share.
|
||||
- **Magma after the fixes:** CPU-bound on the server. Remaining per-draw costs in
|
||||
`SetupWireDraw` (descriptor sets, `GetOrCreateProgram` / pipeline hash, `BuildWireVertexInput`,
|
||||
vectors allocated per draw, scudo lock contention ~20% before), and per frame
|
||||
`BlitDefaultFramebufferToSharedImage` (~30% of the apply thread: frame flush + a second submit
|
||||
for the copy + `vkEndCommandBuffer`) plus `Present()` of the client's offscreen default surface
|
||||
(a swapchain acquire + submit that nobody looks at) and GPU progress markers per submit.
|
||||
- **Fullscreen:** every frame is rendered into the server's default framebuffer and then copied
|
||||
into the window's shared image (Espryt `glBlitFramebuffer`, Magma `vkCmdCopyImage`); at 4 MP the
|
||||
GPU is ~98% busy on texture at ~600 fps while stock does ~1430 and is even faster fullscreen than
|
||||
windowed (it presumably skips composition).
|
||||
|
||||
**Dead end: an adaptive client spin.** Growing the doorbell spin up to 1 ms towards the measured
|
||||
reply latency (and shrinking it on long waits) gave +30-80% on light scenes (texture, jellyfish,
|
||||
shadow) on Magma but cost refract -35% (370 -> 236) and fullscreen terrain -35% (90 -> 58),
|
||||
reproducibly; the present reply simply got slower while the client spun. Polling the shared line
|
||||
less often (backoff up to 64 iterations) did not change that, so it is not cache-line ping-pong. A
|
||||
static `MOBILEGL_IPC_SPIN_US=1000` on the client showed the same mixed picture on Espryt. Not
|
||||
landed; the targeted wake-up removed most of what the spin bought without the regressions.
|
||||
|
||||
**Traps:**
|
||||
- **Pin the clocks.** Unpinned, the stock stack's light scenes ran at GPU 310 MHz / big cores 672
|
||||
MHz and scored 425 instead of ~1100.
|
||||
- **glFinish and `--off-screen`.** Before `66b47a10` off-screen MobileGL numbers were meaningless.
|
||||
- **The stock desktop turns black mid-run** (a pure-black 21707-byte screenshot) while
|
||||
SurfaceFlinger keeps latching ~125 buffers/s, and its score then jumps to ~1420-1500. Probe the
|
||||
screen every ~15 s during stock runs and discard runs with a black probe; restart the stock
|
||||
container + app (`stfix.sh`) to get the picture back. A powerdevil inhibit did not prevent it.
|
||||
- **The MobileGL app's extra-keys bar** shrinks its desktop to ~2560x1410; set
|
||||
`extra_keys_mode=with_keyboard` for fullscreen comparisons (it was restored afterwards).
|
||||
- **The MobileGL session restores a System Settings window** at login; close it before measuring.
|
||||
- **Rotation:** the stock app follows auto-rotate; check glmark2's "Surface Size" line.
|
||||
- **Symbolizing:** the APK's server lib is stripped; a RelWithDebInfo build of the same tree was at
|
||||
+0x80 for every function (check with `llvm-nm -D` on both). Container clients: simpleperf prints
|
||||
offsets from the start of the executable mapping (add the r-x segment's page-aligned vaddr,
|
||||
0x4fb000 for the lib of 2026-10-04). Off-CPU (`sched_switch`) samples of container processes
|
||||
get their user frames attributed to Android's libs, so use the client's own `P65LinkMetrics` for
|
||||
its waits.
|
||||
- `pkill -f <script>` inside `su -c "..."` kills the command itself; use pids.
|
||||
|
||||
## Yet to do (ranked)
|
||||
|
||||
1. **Fullscreen: render straight into the window's shared images** (both backends). The default
|
||||
framebuffer becomes the current back shared image (an AHB-backed EGLImage FBO on Espryt, the
|
||||
imported image on Magma); the bottom-up row order goes to linux-dmabuf's `Y_INVERT` flag instead
|
||||
of the flipping blit. Gain: fullscreen ~1.5-2x. Risk: default-framebuffer semantics (reads,
|
||||
blits, buffer age, resize, device loss), KWin's handling of `Y_INVERT`. Verify: fullscreen
|
||||
glmark2, Chrome, desktop-verify, the retrace CI.
|
||||
2. **Asynchronous shared-image present.** Today `PresentToSharedImage` is `EmitAndWait`, so the
|
||||
client cannot record frame N+1 while the server finishes N. Commit the `wl_buffer` from the reply
|
||||
on the event ring (or order the compositor's acquire after the producer's present server-side),
|
||||
and allow present credit 2. Gain: light scenes 1.3-1.8x. Risk: frame ordering with the
|
||||
compositor, buffer reuse with 3 images, an app that draws one frame and idles. Verify: Chrome
|
||||
flicker barcode test, KWin, desktop-verify.
|
||||
3. **Magma per-frame submissions:** append the shared-image copy to the frame's command buffer (one
|
||||
submit per frame), skip `Present()` for a surface whose frames only go to shared images, coalesce
|
||||
GPU progress markers. Gain: Magma light scenes 1.2-1.4x. Risk: the copy's fence/semaphore
|
||||
export (`SI::PublishWrite`), hang-watch coverage. Verify: Magma unit tests, shared-image tests.
|
||||
4. **Magma per-draw CPU:** cache descriptor sets / pipeline lookups across draws when unchanged
|
||||
(keyed on monotonic lifetime ids), stop rebuilding the vertex input state per draw, replace the
|
||||
per-draw vectors with per-frame arenas. Gain: ideas/terrain 1.3-2x. Verify: retrace CI with
|
||||
Magma.
|
||||
5. **Terrain** (both backends at 0.35-0.5x of stock): not profiled after the fixes; it has 43
|
||||
respecifies, several FBO passes and a GenerateMipmap per frame. Profile first.
|
||||
6. **Espryt per-draw state sync** (`DG::PrepareForDraw`): the Minecraft roadmap's version-gated
|
||||
early-outs. Gain 10-20% on draw-heavy scenes. Risk: stale caches; retrace CI.
|
||||
7. **Blocking fence create/destroy:** `EmitFenceSync` / `EmitDeleteSync` are `EmitAndWait`; an app
|
||||
that makes a fence per frame (Minecraft, Chrome) pays two round trips. Make them fire-and-forget
|
||||
(the client already mints the handle).
|
||||
8. **Client-to-server doorbell:** the server parks between records and the client pays a socket
|
||||
write per record while it streams. Try a server-side spin sized to the inter-record gap of an
|
||||
actively streaming client (watch the spin regression above), or ring only at batch boundaries.
|
||||
9. `CreateVertexElements` is re-sent per draw (ideas: 76 per frame); deduplicate by content on the
|
||||
client.
|
||||
|
||||
## Device state at handoff (2026-10-04 ~18:50 device time)
|
||||
|
||||
- **Up:** the MobileGL anland (`com.anland.consumer.mobilegl`) on **Magma** (DirectVulkan), Plasma
|
||||
running (KWin + plasmashell, no sticky software renderer). The original anland
|
||||
(`com.anland.consumer`) is force-stopped and its `arch-kde` container is stopped.
|
||||
- **Deployed build = `bb31f374`** (code of every commit above; the later commits on the branch are
|
||||
docs and CI): the server is a RelWithDebInfo NDK build for android-29 swapped into the installed
|
||||
APK (`/data/app/.../com.anland.consumer.mobilegl-*/lib/arm64/libMobileGL.so`), the client the
|
||||
Release cross build in the container's `/opt/mobilegl/lib/libMobileGL.so`. The APK's previous
|
||||
server lib (`18a5dba0`) is kept at `/data/local/tmp/anl/srv-apk.so`.
|
||||
- **Clocks: back at the original governors and limits** (CPU walt 902400-2265600 / 614400-3148800 /
|
||||
499200-2956800 / 672000-3302400, GPU msm-adreno-tz 231-903 MHz). They were restored just before
|
||||
the request to leave them pinned arrived, and were left as they are. The saved originals stay in
|
||||
`/data/local/tmp/anl/pb-clocks.orig`. To pin again for measuring and to restore afterwards:
|
||||
|
||||
```sh
|
||||
adb shell 'su -c "sh /data/local/tmp/anl/pbclk.sh pin"' # CPU 1.80/2.25/2.25/2.25 GHz, GPU 680 MHz
|
||||
adb shell 'su -c "sh /data/local/tmp/anl/pbclk.sh restore"' # back to pb-clocks.orig
|
||||
# the restore did not take on two limits once; write them again if `pbclk.sh show` disagrees:
|
||||
adb shell 'su -c "echo 614400 > /sys/devices/system/cpu/cpufreq/policy2/scaling_min_freq; echo 231000000 > /sys/class/kgsl/kgsl-3d0/devfreq/min_freq"'
|
||||
```
|
||||
- The MobileGL app's `extra_keys_mode` is back at its original (unset = the bar is shown).
|
||||
- The phone-side helper scripts and run outputs are in `/data/local/tmp/anl/` (`pb/`, `prof/`,
|
||||
`pb-unpinned/`), the container's in `/root/pb` of both containers.
|
||||
|
||||
## How to reproduce
|
||||
|
||||
Helper scripts: `tools/device_bench/anland_glmark2/` (copied verbatim from the session; the phone
|
||||
side expects them in `/data/local/tmp/anl/`, push with `adb push <file> /data/local/tmp/anl/`).
|
||||
|
||||
| script | where | does |
|
||||
|---|---|---|
|
||||
| `pbclk.sh save\|pin\|restore\|show` | phone, root | saves the governors/limits to `/data/local/tmp/anl/pb-clocks.orig`, pins CPU 1.80/2.25/2.25/2.25 GHz + GPU 680 MHz, restores |
|
||||
| `pbbatch.sh <container> <stock\|mgl> <label> <cfg...>` | phone, root | per config (`es2w es2f glw glf es2o glo`): cool-down (`pbcool.sh`), samples (`pbsamp.sh`), screenshots + SurfaceFlinger frames (`pbshown.sh`), 15 s screen probes (`pbprobe.sh`), runs glmark2 through `pbrun.sh` in the container (`/root/pbrun.sh`), black-screen restart for stock (`stfix.sh`) |
|
||||
| `ab.sh <container> <tag> <cmd...>` / `pbset.sh <tag> [env]` | phone, root | one run / the affected-scene set |
|
||||
| `lm.sh <tag>` | phone, root | per-frame `P65LinkMetrics` averages of a run made with `MOBILEGL_PIPE_STATS=1` |
|
||||
| `pbprof.sh`, `profrun.sh`, `gprof.sh` | phone, root | `simpleperf` (flat, per-thread `top -H`, GPU busy) and `--trace-offcpu -g` call graphs of the server apply thread + client |
|
||||
| `visset.sh <tag>` | phone, root | mid-run screenshots of ten scenes |
|
||||
| `dep.sh`, `smoke.sh`, `wtest.sh` | host | deploy a server + client build and restart on a backend; Chrome + lock screen smoke check; WSL unit tests |
|
||||
| `pbparse.py`, `mktables.py` | host | glmark2 outputs -> per-scene tables |
|
||||
| `symagg.py`, `incl.py`, `offcpu.py`, `callers.py`, `timeline.py` | host | symbolize and aggregate simpleperf output (flat by function, inclusive call graph, off-CPU waits, callers of a function, on/off-CPU timeline) |
|
||||
|
||||
```sh
|
||||
# clocks (phone, root)
|
||||
sh /data/local/tmp/anl/pbclk.sh save; sh /data/local/tmp/anl/pbclk.sh pin
|
||||
sh /data/local/tmp/anl/pbclk.sh restore # when done (also on abort)
|
||||
# backends / stacks
|
||||
sh /data/local/tmp/anl/switch.sh DirectGLES|DirectVulkan # MobileGL anland (skill script)
|
||||
am force-stop com.anland.consumer.mobilegl; droidspaces -C /data/local/Droidspaces/Containers/arch-kde/container.config start
|
||||
monkey -p com.anland.consumer -c android.intent.category.LAUNCHER 1 # stock
|
||||
# one glmark2 run in the MobileGL container (root shell in the container)
|
||||
MGLOG=/tmp/pb-x.log mgrun offscreen bash -c 'MOBILEGL_PIPE_STATS=1 glmark2-es2-wayland -b ideas:duration=10'
|
||||
# profile the busiest server apply thread + the client
|
||||
simpleperf record --trace-offcpu -e cpu-clock -f 2000 -g -t <apply tid>,<client pid> --duration 6 -o x.data
|
||||
simpleperf report-sample -i x.data --show-callchain > x.samples
|
||||
python incl.py x.samples <tid> <unstripped libMobileGL.so> <offset> com.anland.consumer.mobilegl
|
||||
```
|
||||
@@ -0,0 +1,110 @@
|
||||
# MiniPC-8845 Arch WSL GPU Runner
|
||||
|
||||
Configuration recorded on 2026-10-05.
|
||||
|
||||
## Host
|
||||
|
||||
| Component | Configuration |
|
||||
| --- | --- |
|
||||
| Hostname | `MiniPC-8845` |
|
||||
| Windows build | `10.0.26200.9445` |
|
||||
| GPU | AMD Radeon 780M Graphics |
|
||||
| Windows GPU driver | `32.0.12033.1030` |
|
||||
| WSL version | `2.7.3.0` |
|
||||
| Distribution | `archlinux`, Arch Linux on WSL 2 |
|
||||
| Linux kernel | `6.6.114.1-microsoft-standard-WSL2` |
|
||||
| Init system | systemd |
|
||||
| WSL networking | Mirrored |
|
||||
| GPU access | `/dev/dxg` and `/usr/lib/wsl/lib` |
|
||||
|
||||
## GitHub Actions Runner
|
||||
|
||||
| Setting | Value |
|
||||
| --- | --- |
|
||||
| Repository | `MobileGL-Dev/MobileGL` |
|
||||
| Runner name | `minipc-8845-arch-wsl-gpu` |
|
||||
| Runner version | `2.337.0`, automatic updates enabled |
|
||||
| Labels | `self-hosted`, `Linux`, `X64`, `arch`, `wsl`, `gpu`, `gles`, `vulkan`, `d3d12` |
|
||||
| Concurrent jobs | 1 |
|
||||
| Linux account | `github-runner`, UID 1001, no sudo configuration |
|
||||
| Installation directory | `/opt/actions-runner/mobilegl` |
|
||||
| Work directory | `/opt/actions-runner/mobilegl/_work` |
|
||||
| Environment file | `/etc/mobilegl-runner/gpu.env` |
|
||||
|
||||
Workflow runner selector:
|
||||
|
||||
```yaml
|
||||
runs-on: [self-hosted, Linux, X64, arch, wsl, gpu, gles, vulkan]
|
||||
```
|
||||
|
||||
## Graphics
|
||||
|
||||
| Component | Configuration |
|
||||
| --- | --- |
|
||||
| Mesa | `26.2.1-arch1.1` |
|
||||
| OpenGL / GLES driver | Mesa D3D12 |
|
||||
| Renderer | `D3D12 (AMD Radeon 780M Graphics)` |
|
||||
| EGL | 1.5 |
|
||||
| OpenGL | 4.6 |
|
||||
| OpenGL ES | 3.1 |
|
||||
| Vulkan driver | Mesa Dozen, translating Vulkan to D3D12 |
|
||||
| Vulkan device API | 1.2.354 |
|
||||
| Vulkan ICD | `/usr/share/vulkan/icd.d/dzn_icd.json` |
|
||||
| Default EGL platform | Surfaceless |
|
||||
|
||||
Dozen reports a non-conformant Vulkan implementation. The exposed capabilities
|
||||
are GLES 3.1 and Vulkan 1.2; GLES 3.2 and full Vulkan conformance are not available.
|
||||
|
||||
The runner service selects the Radeon GPU with these environment variables:
|
||||
|
||||
```sh
|
||||
DISPLAY=:0
|
||||
WAYLAND_DISPLAY=wayland-0
|
||||
XDG_RUNTIME_DIR=/mnt/wslg/runtime-dir
|
||||
LD_LIBRARY_PATH=/usr/lib/wsl/lib
|
||||
MESA_LOADER_DRIVER_OVERRIDE=d3d12
|
||||
GALLIUM_DRIVER=d3d12
|
||||
MESA_D3D12_DEFAULT_ADAPTER_NAME="AMD Radeon 780M Graphics"
|
||||
VK_ICD_FILENAMES=/usr/share/vulkan/icd.d/dzn_icd.json
|
||||
EGL_PLATFORM=surfaceless
|
||||
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
|
||||
```
|
||||
|
||||
The installed GPU probe is `/usr/local/libexec/mobilegl-runner/gpu-smoke`.
|
||||
Its GLES source is `/usr/local/libexec/mobilegl-runner/gles-smoke.c`, and the
|
||||
recorded verification log is `/var/log/mobilegl-runner/gpu-smoke.log`.
|
||||
|
||||
## Build Tools
|
||||
|
||||
Installed tools include GCC, Clang 22, CMake, Ninja, ccache, LLD, libc++, Git LFS,
|
||||
GitHub CLI, and EGL/GLES/Vulkan development headers.
|
||||
|
||||
## Service and Startup
|
||||
|
||||
| Setting | Value |
|
||||
| --- | --- |
|
||||
| systemd unit | `actions.runner.MobileGL-Dev-MobileGL.minipc-8845-arch-wsl-gpu.service` |
|
||||
| Service drop-in | `/etc/systemd/system/actions.runner.MobileGL-Dev-MobileGL.minipc-8845-arch-wsl-gpu.service.d/gpu.conf` |
|
||||
| Service startup | Enabled at WSL systemd boot |
|
||||
| Restart policy | `Restart=always`, `RestartSec=15` |
|
||||
| Startup checks | GPU device access and WSLg X11/Wayland sockets |
|
||||
| Windows scheduled task | `MobileGL Arch WSL Runner` |
|
||||
| Task trigger | Windows login by `Swung0x48` |
|
||||
| Task behavior | Starts WSL in a hidden window and keeps it running |
|
||||
| Task execution limit | Unlimited |
|
||||
| Task retry policy | Every minute, up to 999 retries |
|
||||
|
||||
Automatic startup requires the Windows user to log in. The runner cannot execute
|
||||
jobs while the host is asleep.
|
||||
|
||||
## Network
|
||||
|
||||
The runner uses the Windows Clash proxy through WSL mirrored networking:
|
||||
|
||||
```sh
|
||||
http_proxy=http://127.0.0.1:7897
|
||||
https_proxy=http://127.0.0.1:7897
|
||||
no_proxy=localhost,127.0.0.1,::1
|
||||
```
|
||||
|
||||
Clash must be running for the runner's configured GitHub connection to work.
|
||||
@@ -209,6 +209,10 @@ LOCAL_REFUSAL_WORDS = {
|
||||
"ServerSession.cpp / ClientSession.cpp (P11 B2) - one T0 map_persistent answered DECLINED "
|
||||
"because its store never reached the server (the Offer's bounded wait, or no hop socket on "
|
||||
"the client); that store runs T2 and the session goes on",
|
||||
"Recover":
|
||||
"ClientSession.cpp RecoverAfterDeviceLoss - the CLIENT declining to dial a fresh session after "
|
||||
"a device loss (MOBILEGL_IPC_RECOVER=0, or a transport it cannot redial); the lost session is "
|
||||
"already gone, so there is no peer to send a Refuse frame to",
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Turn the failed entries of ctest --output-junit files into GitHub error annotations.
|
||||
|
||||
A red lane's log needs a signed-in reader, but its annotations do not, so the names of the
|
||||
failed entries - and the lines of their output that say why - are what a reader of the run
|
||||
page (or of the check-runs API) can see without downloading anything. GitHub keeps at most
|
||||
ten error annotations per step, so this prints one summary naming every failed entry and then
|
||||
one excerpt for each of the first few.
|
||||
|
||||
Usage: junit_annotate.py [--excerpts N] FILE_OR_DIR... (a directory means every *.xml in it)
|
||||
Exit status is always 0: this reports a failure, it is never one.
|
||||
"""
|
||||
import argparse
|
||||
import re
|
||||
import sys
|
||||
import xml.etree.ElementTree as ET
|
||||
from pathlib import Path
|
||||
|
||||
INTERESTING = re.compile(
|
||||
r"Failure|FAILED|Failed|error|Error|Fatal|Refuse|Expected|Which is|Value of|Actual|"
|
||||
r"Abort|abort|Segmentation|SIGSEGV|signal|timed out|Timeout|assert", re.ASCII)
|
||||
|
||||
|
||||
def escape(text):
|
||||
return text.replace("%", "%25").replace("\r", "").replace("\n", "%0A")
|
||||
|
||||
|
||||
def failed_cases(path):
|
||||
try:
|
||||
root = ET.parse(path).getroot()
|
||||
except (ET.ParseError, OSError) as error:
|
||||
print(f"junit_annotate: {path}: {error}", file=sys.stderr)
|
||||
return []
|
||||
out = []
|
||||
for case in root.iter("testcase"):
|
||||
status = case.get("status", "")
|
||||
failure = case.find("failure")
|
||||
error = case.find("error")
|
||||
if status not in ("fail", "failed") and failure is None and error is None:
|
||||
continue
|
||||
text = case.findtext("system-out") or ""
|
||||
if failure is not None:
|
||||
text = (failure.get("message") or "") + "\n" + (failure.text or "") + "\n" + text
|
||||
out.append((case.get("name", "?"), text))
|
||||
return out
|
||||
|
||||
|
||||
def excerpt(text, limit=40):
|
||||
lines = [line.rstrip() for line in text.splitlines() if line.strip()]
|
||||
keep = set()
|
||||
for index, line in enumerate(lines):
|
||||
if INTERESTING.search(line):
|
||||
keep.update(range(index, min(index + 4, len(lines))))
|
||||
picked = [lines[index] for index in sorted(keep)] or lines[-limit:]
|
||||
return "\n".join(line[:400] for line in picked[:limit])
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--excerpts", type=int, default=8)
|
||||
parser.add_argument("paths", nargs="+")
|
||||
args = parser.parse_args()
|
||||
files = []
|
||||
for name in args.paths:
|
||||
path = Path(name)
|
||||
files.extend(sorted(path.glob("*.xml")) if path.is_dir() else [path])
|
||||
failed = []
|
||||
for path in files:
|
||||
if path.is_file():
|
||||
failed.extend((path.name, name, text) for name, text in failed_cases(path))
|
||||
if not failed:
|
||||
print("junit_annotate: no failed entries in " + ", ".join(str(f) for f in files))
|
||||
return 0
|
||||
names = "\n".join(f"{name} ({source})" for source, name, _ in failed)
|
||||
print(f"::error title={len(failed)} failed ctest entr(y/ies)::{escape(names[:60000])}")
|
||||
for source, name, text in failed[:max(args.excerpts, 0)]:
|
||||
print(f"::error title={name[:200]}::{escape(excerpt(text))}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,6 @@
|
||||
# ab.sh <ct> <tag> <cmd...> - one quick run (phone, root), prints FPS lines
|
||||
ct=$1; tag=$2; shift 2; CR=/mnt/Droidspaces/$ct/root; st=mgl; [ $ct = arch-kde ] && st=stock
|
||||
sh /data/local/tmp/anl/pbcool.sh 46000 20 300 >/dev/null
|
||||
mkdir -p $CR/pb; echo "$*" > $CR/pb/$tag.cmd
|
||||
/data/local/Droidspaces/bin/droidspaces --name=$ct run bash /root/pbrun.sh $st $tag >/dev/null 2>&1
|
||||
grep -h FPS $CR/pb/$tag.out | sed -e 's/FrameTime.*//' -e "s/^/$tag /"
|
||||
@@ -0,0 +1,30 @@
|
||||
import sys, re, subprocess, collections, os
|
||||
f, tid, so, base, sub, target = sys.argv[1], sys.argv[2], sys.argv[3], int(sys.argv[4],16), sys.argv[5], sys.argv[6]
|
||||
SYM = os.path.expandvars(r'$LOCALAPPDATA/Android/Sdk/ndk/27.2.12479018/toolchains/llvm/prebuilt/windows-x86_64/bin/llvm-symbolizer.exe')
|
||||
S=[]; cur=None
|
||||
for line in open(f, encoding='utf-8', errors='replace'):
|
||||
s=line.strip()
|
||||
if s=='sample:':
|
||||
if cur: S.append(cur)
|
||||
cur={'ev':'','tid':'','fr':[]}; continue
|
||||
if cur is None: continue
|
||||
if s.startswith('event_type:'): cur['ev']=s.split()[1]
|
||||
elif s.startswith('thread_id:'): cur['tid']=s.split()[1]
|
||||
elif s.startswith('vaddr_in_file:'): cur['fr'].append([s.split()[1],''])
|
||||
elif s.startswith('file:') and cur['fr']: cur['fr'][-1][1]=s.split(None,1)[1]
|
||||
if cur: S.append(cur)
|
||||
S=[x for x in S if x['tid']==tid and not x['ev'].startswith('sched')]
|
||||
addrs=sorted({int(a,16)+base for x in S for a,d in x['fr'] if sub in d})
|
||||
names={}
|
||||
for i in range(0,len(addrs),3000):
|
||||
part=addrs[i:i+3000]
|
||||
out=subprocess.run([SYM,'--obj='+so,'-C','-f','--inlining=false']+['0x%x'%a for a in part],capture_output=True,text=True).stdout
|
||||
for a,b in zip(part,out.strip().split('\n\n')): names[a]=re.sub(r'\(.*','',b.split('\n')[0]).split('::')[-1]
|
||||
agg=collections.Counter(); tot=0
|
||||
for x in S:
|
||||
ch=[names.get(int(a,16)+base,'?') for a,d in x['fr'] if sub in d]
|
||||
if target in ch:
|
||||
k=ch.index(target); tot+=1
|
||||
agg[' <- '.join(ch[k:k+4])]+=1
|
||||
print('samples with', target, tot, 'of', len(S))
|
||||
for k,v in agg.most_common(12): print(v, k)
|
||||
@@ -0,0 +1,11 @@
|
||||
#!/usr/bin/env bash
|
||||
# dep.sh <DirectGLES|DirectVulkan> - (host) deploy a server (SERVER_LIB) + client (MGL_XBUILD_DIR) build and restart the desktop on that backend
|
||||
S=${SKILL_SCRIPTS:-$(cd "$(dirname "$0")/../../../.claude/skills/anland-mobilegl-plasma/scripts" && pwd)}
|
||||
# SERVER_LIB: the NDK-built server lib (Windows form path); MGL_XBUILD_DIR: the WSL client build dir.
|
||||
export MSYS_NO_PATHCONV=1
|
||||
adb push "${SERVER_LIB:?set SERVER_LIB}" /data/local/tmp/anland-mobilegl/libMobileGL.new.so >/dev/null
|
||||
CHANNEL=pbxd bash $S/xdeploy.sh 2>&1 | grep -E "DEPLOYED|rror"
|
||||
adb shell "su -c 'sh /data/local/tmp/anl/swap.sh >/dev/null; am startservice -n com.anland.consumer.mobilegl/com.anland.consumer.MobileGLWorker -a com.anland.consumer.mobilegl.STOP >/dev/null; sleep 6; am force-stop com.anland.consumer.mobilegl; sleep 1; am start -n com.anland.consumer.mobilegl/com.anland.consumer.MainActivity --es mobilegl_backend $1 >/dev/null'"
|
||||
sleep 40
|
||||
printf '%s\n' 'sleep 2; pkill -x systemsettings; true' | bash $S/ct.sh pb >/dev/null 2>&1
|
||||
adb shell 'su -c "sh /data/local/tmp/anl/status.sh 2>&1 | grep -E \"backend:|server|desktop-session\""'
|
||||
@@ -0,0 +1,12 @@
|
||||
# gprof.sh <ct> <tag> <rec_s> <cmd...> - offcpu+callgraph record of the busiest server apply thread + client
|
||||
ct=$1; tag=$2; rec=$3; shift 3; D=/data/local/tmp/anl/prof; CR=/mnt/Droidspaces/$ct/root
|
||||
echo "$*" > $CR/pb/$tag.cmd
|
||||
/data/local/Droidspaces/bin/droidspaces --name=$ct run bash /root/pbrun.sh mgl $tag > $D/$tag.run 2>&1 &
|
||||
sleep 9
|
||||
s=$(pidof com.anland.consumer.mobilegl:mobilegl); c=$(pidof glmark2-es2-wayland glmark2-wayland | awk '{print $1}')
|
||||
t=$(top -H -b -n1 -p $s -o TID,CMD,%CPU | grep mgl-srv-apply | sort -k3 -rn | head -1 | awk '{print $1}')
|
||||
echo "server_tid=$t client=$c" > $D/$tag.pids
|
||||
simpleperf record --trace-offcpu -e cpu-clock -f 2000 -g -t $t,$c --duration $rec -o $D/$tag.perf.data > $D/$tag.perf.log 2>&1
|
||||
simpleperf report-sample -i $D/$tag.perf.data --show-callchain > $D/$tag.samples 2>/dev/null
|
||||
chmod 644 $D/$tag.*
|
||||
wait
|
||||
@@ -0,0 +1,46 @@
|
||||
# incl.py <samples> <tid> <so> <base> <dsosub> [top] - inclusive on-CPU %, and leaf-dso -> first own frame
|
||||
import sys, re, subprocess, collections, os
|
||||
f, tid, so, base, sub = sys.argv[1], sys.argv[2], sys.argv[3], int(sys.argv[4], 16), sys.argv[5]
|
||||
top = int(sys.argv[6]) if len(sys.argv) > 6 else 40
|
||||
SYM = os.path.expandvars(r'$LOCALAPPDATA/Android/Sdk/ndk/27.2.12479018/toolchains/llvm/prebuilt/windows-x86_64/bin/llvm-symbolizer.exe')
|
||||
S = []; cur = None
|
||||
for line in open(f, encoding='utf-8', errors='replace'):
|
||||
s = line.strip()
|
||||
if s == 'sample:':
|
||||
if cur: S.append(cur)
|
||||
cur = {'ev': '', 'tid': '', 'fr': []}; continue
|
||||
if cur is None: continue
|
||||
if s.startswith('event_type:'): cur['ev'] = s.split()[1]
|
||||
elif s.startswith('thread_id:'): cur['tid'] = s.split()[1]
|
||||
elif s.startswith('vaddr_in_file:'): cur['fr'].append([s.split()[1], '', ''])
|
||||
elif s.startswith('file:') and cur['fr']: cur['fr'][-1][1] = s.split(None, 1)[1]
|
||||
elif s.startswith('symbol:') and cur['fr']: cur['fr'][-1][2] = s.split(None, 1)[1]
|
||||
if cur: S.append(cur)
|
||||
S = [x for x in S if x['tid'] == tid and not x['ev'].startswith('sched')]
|
||||
addrs = sorted({int(a, 16) + base for x in S for a, d, _ in x['fr'] if sub in d})
|
||||
names = {}
|
||||
for i in range(0, len(addrs), 3000):
|
||||
part = addrs[i:i+3000]
|
||||
out = subprocess.run([SYM, '--obj=' + so, '-C', '-f', '--inlining=false'] + ['0x%x' % a for a in part], capture_output=True, text=True).stdout
|
||||
for a, b in zip(part, out.strip().split('\n\n')):
|
||||
n = re.sub(r'\(.*', '', b.split('\n')[0]).replace('MobileGL::', '').replace('MG_Backend::DirectVulkan::', 'DV::').replace('MG_Backend::DirectGLES::', 'DG::')
|
||||
names[a] = n[:110]
|
||||
def nm(fr):
|
||||
a, d, sy = fr
|
||||
if sub in d: return names.get(int(a, 16) + base, a)
|
||||
return (sy if sy and not sy.startswith('*') and not sy.startswith('!!!') else os.path.basename(d))[:60]
|
||||
N = len(S)
|
||||
inc = collections.Counter(); leafmap = collections.Counter()
|
||||
for x in S:
|
||||
seen = set()
|
||||
for fr in x['fr']:
|
||||
if sub in fr[1]:
|
||||
n = nm(fr)
|
||||
if n not in seen: seen.add(n); inc[n] += 1
|
||||
if x['fr'] and sub not in x['fr'][0][1]:
|
||||
own = next((nm(fr) for fr in x['fr'] if sub in fr[1]), '?')
|
||||
leafmap[(os.path.basename(x['fr'][0][1]) or '?', own)] += 1
|
||||
print('on-CPU samples', N)
|
||||
for k, v in inc.most_common(top): print('%5.1f%% %s' % (100.0*v/N, k))
|
||||
print('-- foreign leaf -> first own frame')
|
||||
for (d, o), v in leafmap.most_common(25): print('%5.1f%% %-22s %s' % (100.0*v/N, d[:22], o))
|
||||
@@ -0,0 +1,4 @@
|
||||
# lm.sh <tag> - per-frame link-metric averages of the last run's client log
|
||||
L=/mnt/Droidspaces/arch-kde-mgl/root/pb/pb-$1.client.log
|
||||
grep -a "kind=frame-op" $L | tail -1 | cut -c40-200
|
||||
grep -a "P65LinkMetrics kind=frame " $L | tail -300 | awk '{for(i=1;i<=NF;i++){split($i,a,"="); v[a[1]]=a[2]} w+=v["wall_ns"]; c+=v["client_thread_cpu_ns"]; t+=v["transport_wait_ns"]; r+=v["rtt_mean_us"]; n++} END{printf "wall %.2fms cpu %.2fms twait %.2fms rtt %.0fus\n", w/n/1e6, c/n/1e6, t/n/1e6, r/n}'
|
||||
@@ -0,0 +1,66 @@
|
||||
import json, sys, statistics as st
|
||||
d = json.load(open(sys.argv[1]))
|
||||
stacks = ['stock', 'espryt', 'magma']
|
||||
cfgs = [('es2w', 'glmark2-es2-wayland, 800x600 window'), ('es2f', 'glmark2-es2-wayland, fullscreen'),
|
||||
('glw', 'glmark2-wayland (desktop GL), 800x600 window'), ('glf', 'glmark2-wayland (desktop GL), fullscreen')]
|
||||
def med(v):
|
||||
v = [x for x in v if x is not None]
|
||||
return st.median(v) if v else None
|
||||
def spread(v):
|
||||
v = [x for x in v if x is not None]
|
||||
return (min(v), max(v)) if v else (None, None)
|
||||
out = []
|
||||
out.append('### Overall scores (median of runs; min-max in brackets; n = runs)\n')
|
||||
out.append('| Configuration | stock | Espryt | Magma | Espryt/stock | Magma/stock | Espryt/stock (common scenes) | Magma/stock (common scenes) |')
|
||||
out.append('|---|---|---|---|---|---|---|---|')
|
||||
for c, label in cfgs:
|
||||
row = [label]
|
||||
meds = {}
|
||||
common = {}
|
||||
for s in stacks:
|
||||
k = '%s/%s' % (s, c)
|
||||
if k not in d: row.append('-'); continue
|
||||
sc = d[k]['scenes'].get('__score', [])
|
||||
m = med(sc); lo, hi = spread(sc); meds[s] = m
|
||||
row.append('%d [%d-%d] n=%d' % (m, lo, hi, len(sc)) if m else '-')
|
||||
# common-scene mean of medians
|
||||
keys = None
|
||||
for s in stacks:
|
||||
k = '%s/%s' % (s, c)
|
||||
if k not in d: continue
|
||||
ks = {n for n, v in d[k]['scenes'].items() if n != '__score' and med(v) is not None}
|
||||
keys = ks if keys is None else keys & ks
|
||||
for s in stacks:
|
||||
k = '%s/%s' % (s, c)
|
||||
if k in d and keys:
|
||||
common[s] = st.mean(med(d[k]['scenes'][n]) for n in keys)
|
||||
for s in ['espryt', 'magma']:
|
||||
row.append('%.2f' % (meds[s] / meds['stock']) if meds.get(s) and meds.get('stock') else '-')
|
||||
for s in ['espryt', 'magma']:
|
||||
row.append('%.2f' % (common[s] / common['stock']) if common.get(s) and common.get('stock') else '-')
|
||||
out.append('| ' + ' | '.join(row) + ' |')
|
||||
out.append('')
|
||||
for c, label in cfgs:
|
||||
out.append('### Per-scene FPS: %s (median of runs)\n' % label)
|
||||
out.append('| Scene | stock | Espryt | Magma | Espryt/stock | Magma/stock |')
|
||||
out.append('|---|---|---|---|---|---|')
|
||||
names = []
|
||||
for s in stacks:
|
||||
k = '%s/%s' % (s, c)
|
||||
if k in d:
|
||||
for n in d[k]['scenes']:
|
||||
if n != '__score' and n not in names: names.append(n)
|
||||
for n in names:
|
||||
vals = {}
|
||||
for s in stacks:
|
||||
k = '%s/%s' % (s, c)
|
||||
v = d.get(k, {}).get('scenes', {}).get(n)
|
||||
vals[s] = med(v) if v else None
|
||||
if v is not None and all(x is None for x in v): vals[s] = 'unsupported'
|
||||
def f(x): return x if isinstance(x, str) else ('-' if x is None else '%d' % x)
|
||||
def r(a, b):
|
||||
return '%.2f' % (a / b) if isinstance(a, (int, float)) and isinstance(b, (int, float)) and b else '-'
|
||||
out.append('| %s | %s | %s | %s | %s | %s |' % (n.replace('|', '/'), f(vals['stock']), f(vals['espryt']), f(vals['magma']),
|
||||
r(vals['espryt'], vals['stock']), r(vals['magma'], vals['stock'])))
|
||||
out.append('')
|
||||
print('\n'.join(out))
|
||||
@@ -0,0 +1,71 @@
|
||||
# offcpu.py <samples.txt> <tid> <so> <base-hex> <dso-substr> [depth]
|
||||
# Aggregates report-sample output (trace-offcpu) for one thread: on/off CPU split, and the
|
||||
# off-CPU (leaf __schedule) time by kernel wait path + first N libMobileGL frames.
|
||||
import sys, re, subprocess, collections, os
|
||||
f, tid, so, base, sub = sys.argv[1], sys.argv[2], sys.argv[3], int(sys.argv[4], 16), sys.argv[5]
|
||||
depth = int(sys.argv[6]) if len(sys.argv) > 6 else 3
|
||||
SYM = os.path.expandvars(r'$LOCALAPPDATA/Android/Sdk/ndk/27.2.12479018/toolchains/llvm/prebuilt/windows-x86_64/bin/llvm-symbolizer.exe')
|
||||
samples = []
|
||||
cur = None
|
||||
mode = None
|
||||
for line in open(f, encoding='utf-8', errors='replace'):
|
||||
s = line.strip()
|
||||
if s == 'sample:':
|
||||
if cur: samples.append(cur)
|
||||
cur = {'frames': [], 'count': 0, 'tid': None, 'time': 0, 'ev': ''}; mode = 'top'; continue
|
||||
if cur is None: continue
|
||||
if s.startswith('event_count:'): cur['count'] = int(s.split()[1])
|
||||
elif s.startswith('time:'): cur['time'] = int(s.split()[1])
|
||||
elif s.startswith('event_type:'): cur['ev'] = s.split()[1]
|
||||
elif s.startswith('thread_id:'): cur['tid'] = s.split()[1]
|
||||
elif s.startswith('vaddr_in_file:'): cur['frames'].append([s.split()[1], None, None])
|
||||
elif s.startswith('file:') and cur['frames']: cur['frames'][-1][1] = s.split(None, 1)[1]
|
||||
elif s.startswith('symbol:') and cur['frames']: cur['frames'][-1][2] = s.split(None, 1)[1]
|
||||
if cur: samples.append(cur)
|
||||
samples = sorted([x for x in samples if x['tid'] == tid], key=lambda x: x['time'])
|
||||
for i, x in enumerate(samples):
|
||||
if x['ev'].startswith('sched'):
|
||||
x['count'] = (samples[i+1]['time'] - x['time']) if i + 1 < len(samples) else 0
|
||||
x['off'] = True
|
||||
else:
|
||||
x['off'] = False
|
||||
addrs = set()
|
||||
for x in samples:
|
||||
for a, d, sym in x['frames']:
|
||||
if d and sub in d: addrs.add(int(a, 16) + base)
|
||||
addrs = sorted(addrs)
|
||||
names = {}
|
||||
CH = 4000
|
||||
for i in range(0, len(addrs), CH):
|
||||
part = addrs[i:i+CH]
|
||||
out = subprocess.run([SYM, '--obj=' + so, '-C', '-f', '--inlining=false'] + ['0x%x' % a for a in part], capture_output=True, text=True).stdout
|
||||
for a, b in zip(part, out.strip().split('\n\n')):
|
||||
n = b.split('\n')[0]
|
||||
n = re.sub(r'\(.*', '', n) # drop args
|
||||
n = n.replace('MobileGL::', '')
|
||||
names[a] = n[:90]
|
||||
def short(fr):
|
||||
a, d, sym = fr
|
||||
if d and sub in d: return names.get(int(a, 16) + base, a)
|
||||
if sym and not sym.startswith('*'): return sym
|
||||
return os.path.basename(d or '?')
|
||||
tot = sum(x['count'] for x in samples)
|
||||
off = [x for x in samples if x['off']]
|
||||
offt = sum(x['count'] for x in off)
|
||||
print('tid %s: total %.3fs, off-CPU %.3fs (%.0f%%)' % (tid, tot/1e9, offt/1e9, 100*offt/max(tot,1)))
|
||||
agg = collections.Counter()
|
||||
for x in off:
|
||||
kern = [fr[2] for fr in x['frames'] if fr[1] and 'kernel' in fr[1]]
|
||||
kpath = next((k for k in kern if any(w in k for w in ('futex','ep_poll','do_sys_poll','kgsl','unix_stream','sock','sync','fence','wait','nanosleep','read','sendmsg','recv'))), kern[1] if len(kern)>1 else '?')
|
||||
user = [short(fr) for fr in x['frames'] if fr[1] and sub in fr[1]][:depth]
|
||||
agg[(kpath, ' <- '.join(user))] += x['count']
|
||||
for (k, u), v in agg.most_common(18):
|
||||
print('%5.1f%% %-28s %s' % (100*v/max(tot,1), k[:28], u[:230]))
|
||||
on = collections.Counter()
|
||||
for x in samples:
|
||||
if x['off']: continue
|
||||
fr = x['frames'][0] if x['frames'] else ['?', '?', '?']
|
||||
on[short(fr)] += x['count']
|
||||
print('-- on-CPU top')
|
||||
for k, v in on.most_common(15):
|
||||
print('%5.1f%% %s' % (100*v/max(tot,1), k[:150]))
|
||||
@@ -0,0 +1,28 @@
|
||||
# pbbatch.sh <container> <stack stock|mgl> <label> <cfg...> (phone, root; run detached)
|
||||
# cfg: es2w es2f glw glf ; results -> /data/local/tmp/anl/pb/<label>-<cfg>.*
|
||||
ct=$1; st=$2; lab=$3; shift 3
|
||||
D=/data/local/tmp/anl/pb; mkdir -p $D; DS=/data/local/Droidspaces/bin/droidspaces
|
||||
CR=/mnt/Droidspaces/$ct/root
|
||||
for cfg in "$@"; do
|
||||
case $cfg in
|
||||
es2w) cmd="glmark2-es2-wayland -b :duration=5";;
|
||||
es2f) cmd="glmark2-es2-wayland --fullscreen -b :duration=5";;
|
||||
glw) cmd="glmark2-wayland -b :duration=5";;
|
||||
glf) cmd="glmark2-wayland --fullscreen -b :duration=5";;
|
||||
es2o) cmd="glmark2-es2-wayland --off-screen -b :duration=5";;
|
||||
glo) cmd="glmark2-wayland --off-screen -b :duration=5";;
|
||||
*) cmd="$cfg";;
|
||||
esac
|
||||
tag=$lab-$cfg
|
||||
[ $ct = arch-kde ] && sh $D/../stfix.sh > $D/$tag.fix 2>&1
|
||||
sh $D/../pbcool.sh 46000 45 300 > $D/$tag.meta
|
||||
echo "cmd: $cmd" >> $D/$tag.meta; echo "start $(date +%s)" >> $D/$tag.meta
|
||||
sh $D/../pbsamp.sh $D/$tag.samp & sp=$!
|
||||
rm -f $D/$tag.ended; sh $D/../pbprobe.sh $tag &
|
||||
( sleep 25; screencap -p /data/local/tmp/anl/pb/$tag-s1.png; sleep 1; screencap -p /data/local/tmp/anl/pb/$tag-s2.png; md5sum $D/$tag-s1.png $D/$tag-s2.png >> $D/$tag.meta; stat -c "s1_bytes=%s" $D/$tag-s1.png >> $D/$tag.meta; sh $D/../pbshown.sh >> $D/$tag.meta ) &
|
||||
mkdir -p $CR/pb; echo "$cmd" > $CR/pb/$tag.cmd
|
||||
$DS --name=$ct run bash /root/pbrun.sh $st $tag >> $D/$tag.meta 2>&1
|
||||
kill $sp; touch $D/$tag.ended; echo "end $(date +%s)" >> $D/$tag.meta; sleep 2
|
||||
cp $CR/pb/$tag.out $D/ 2>/dev/null; cp $CR/pb/pb-$tag.client.log $D/ 2>/dev/null
|
||||
done
|
||||
echo DONE > $D/$lab.done
|
||||
@@ -0,0 +1,26 @@
|
||||
# pbclk.sh save|pin|restore|show (phone, root) - CPU/GPU clock pinning for the glmark2 baseline
|
||||
O=/data/local/tmp/anl/pb-clocks.orig
|
||||
C=/sys/devices/system/cpu/cpufreq; G=/sys/class/kgsl/kgsl-3d0
|
||||
CPU_PIN="policy0:1804800 policy2:2246400 policy5:2246400 policy7:2246400"
|
||||
GPU_PIN=680000000
|
||||
case $1 in
|
||||
save)
|
||||
[ -f $O ] && { echo "already saved: $O"; cat $O; exit 0; }
|
||||
for p in policy0 policy2 policy5 policy7; do echo "$p $(cat $C/$p/scaling_governor) $(cat $C/$p/scaling_min_freq) $(cat $C/$p/scaling_max_freq)"; done > $O
|
||||
echo "gpu $(cat $G/devfreq/governor) $(cat $G/devfreq/min_freq) $(cat $G/devfreq/max_freq) $(cat $G/max_pwrlevel) $(cat $G/min_pwrlevel)" >> $O
|
||||
cat $O;;
|
||||
pin)
|
||||
for e in $CPU_PIN; do p=${e%%:*}; f=${e##*:}; echo $f > $C/$p/scaling_max_freq; echo $f > $C/$p/scaling_min_freq; echo $f > $C/$p/scaling_max_freq; done
|
||||
echo $GPU_PIN > $G/devfreq/max_freq; echo $GPU_PIN > $G/devfreq/min_freq; echo $GPU_PIN > $G/devfreq/max_freq
|
||||
sh $0 show;;
|
||||
restore)
|
||||
[ -f $O ] || { echo "no saved state"; exit 1; }
|
||||
while read p gov mn mx a b; do
|
||||
if [ $p = gpu ]; then echo $mx > $G/devfreq/max_freq; echo $mn > $G/devfreq/min_freq; echo $mx > $G/devfreq/max_freq
|
||||
else echo $gov > $C/$p/scaling_governor; echo $mx > $C/$p/scaling_max_freq; echo $mn > $C/$p/scaling_min_freq; echo $mx > $C/$p/scaling_max_freq; fi
|
||||
done < $O
|
||||
sh $0 show;;
|
||||
show)
|
||||
for p in policy0 policy2 policy5 policy7; do echo "$p gov=$(cat $C/$p/scaling_governor) min=$(cat $C/$p/scaling_min_freq) max=$(cat $C/$p/scaling_max_freq) cur=$(cat $C/$p/scaling_cur_freq)"; done
|
||||
echo "gpu gov=$(cat $G/devfreq/governor) min=$(cat $G/devfreq/min_freq) max=$(cat $G/devfreq/max_freq) cur=$(cat $G/devfreq/cur_freq)";;
|
||||
esac
|
||||
@@ -0,0 +1,5 @@
|
||||
# pbcool.sh [limit_mC=40000] [min_s=20] [max_s=600] - wait until CPU/GPU zones are below the limit
|
||||
lim=${1:-40000}; mn=${2:-20}; mx=${3:-600}; t=0
|
||||
hot() { m=0; for z in /sys/class/thermal/thermal_zone*; do case $(cat $z/type) in cpu-*|cpuss-*|gpuss-*) v=$(cat $z/temp); [ $v -gt $m ] && m=$v;; esac; done; echo $m; }
|
||||
while :; do h=$(hot); if [ $t -ge $mn ] && [ $h -lt $lim ]; then break; fi; [ $t -ge $mx ] && break; sleep 5; t=$((t+5)); done
|
||||
echo "cool: waited ${t}s maxtemp=$h batt=$(dumpsys battery | grep level | tr -d ' ')"
|
||||
@@ -0,0 +1,4 @@
|
||||
# pbkill.sh - stop every benchmark helper and glmark2 (phone, root)
|
||||
for p in $(ps -A -o pid,args | grep -E "pbbatch|pbcool|pbsamp|stfix|profrun|pbprof" | grep -v grep | grep -v pbkill | awk '{print $1}'); do kill $p 2>/dev/null; done
|
||||
pkill -x glmark2-es2-wayland; pkill -x glmark2-wayland; pkill -x glmark2-es2-way; pkill -x glmark2-wayland
|
||||
sleep 1; ps -A -o pid,args | grep -E "pbbatch|glmark2" | grep -v grep
|
||||
@@ -0,0 +1,33 @@
|
||||
import re, sys, glob, os, statistics as st
|
||||
# usage: pbparse.py <dir> ; files <round>-<stack>-<cfg>.out
|
||||
d = sys.argv[1]
|
||||
data = {} # (stack,cfg) -> list of dict scene->fps ; plus score
|
||||
sizes = {}
|
||||
for f in sorted(glob.glob(os.path.join(d, '*.out'))):
|
||||
b = os.path.basename(f)[:-4]
|
||||
m = re.match(r'(r\d+)-(\w+)-(\w+)$', b)
|
||||
if not m: continue
|
||||
rnd, stack, cfg = m.groups()
|
||||
txt = open(f, encoding='utf-8', errors='replace').read()
|
||||
sc = {}
|
||||
for line in txt.splitlines():
|
||||
mm = re.match(r'\[(\w+)\] (.*): FPS: (\d+)', line)
|
||||
if mm: sc[mm.group(1) + ' ' + mm.group(2)] = int(mm.group(3))
|
||||
mm = re.match(r'\[(\w+)\] (.*): Unsupported', line)
|
||||
if mm: sc[mm.group(1) + ' ' + mm.group(2)] = None
|
||||
mm = re.search(r'glmark2 Score: (\d+)', line)
|
||||
if mm: sc['__score'] = int(mm.group(1))
|
||||
mm = re.search(r'Surface Size:\s+(\S+ \S+)', line)
|
||||
if mm: sizes[(stack, cfg)] = mm.group(1)
|
||||
data.setdefault((stack, cfg), []).append((rnd, sc))
|
||||
import json
|
||||
out = {}
|
||||
for k, runs in data.items():
|
||||
scenes = {}
|
||||
for rnd, sc in runs:
|
||||
for s, v in sc.items(): scenes.setdefault(s, []).append(v)
|
||||
out['%s/%s' % k] = {'size': sizes.get(k), 'runs': [r for r, _ in runs], 'scenes': scenes}
|
||||
json.dump(out, open(os.path.join(d, 'all.json'), 'w'), indent=1)
|
||||
for k in sorted(out):
|
||||
s = out[k]['scenes'].get('__score', [])
|
||||
print(k, out[k]['size'], 'scores', s, 'median', st.median(s) if s else None)
|
||||
@@ -0,0 +1,10 @@
|
||||
# pbprobe.sh <tag> - every 15 s while the run lasts: two screenshots 1 s apart; logs size and whether they differ
|
||||
D=/data/local/tmp/anl/pb; tag=$1; n=0
|
||||
sleep 10
|
||||
while [ ! -f $D/$tag.ended ]; do
|
||||
screencap -p $D/pr-a.png; sleep 1; screencap -p $D/pr-b.png
|
||||
a=$(md5sum $D/pr-a.png | cut -c1-8); b=$(md5sum $D/pr-b.png | cut -c1-8); s=$(stat -c %s $D/pr-a.png)
|
||||
st=ok; [ "$a" = "$b" ] && st=STATIC; [ $s -lt 200000 ] && st=BLACK
|
||||
echo "probe t=$n size=$s $st" >> $D/$tag.meta
|
||||
n=$((n+15)); sleep 13
|
||||
done
|
||||
@@ -0,0 +1,20 @@
|
||||
# pbprof.sh <container> <tag> <warm_s> <rec_s> <cmd...> (phone, root)
|
||||
# Runs <cmd> in the container (mgl stack via pbrun), then after warm_s records: per-thread CPU (top -H),
|
||||
# simpleperf on the server (:mobilegl) and on the client, GPU busy samples. Results: /data/local/tmp/anl/prof/<tag>.*
|
||||
ct=$1; tag=$2; warm=$3; rec=$4; shift 4
|
||||
D=/data/local/tmp/anl/prof; mkdir -p $D; DS=/data/local/Droidspaces/bin/droidspaces; CR=/mnt/Droidspaces/$ct/root
|
||||
st=mgl; [ $ct = arch-kde ] && st=stock
|
||||
mkdir -p $CR/pb; echo "$*" > $CR/pb/$tag.cmd
|
||||
$DS --name=$ct run bash /root/pbrun.sh $st $tag > $D/$tag.run 2>&1 &
|
||||
sleep $warm
|
||||
cli=$(pidof glmark2-es2-wayland glmark2-wayland | awk '{print $1}')
|
||||
srv=$(pidof com.anland.consumer.mobilegl:mobilegl)
|
||||
kw=$(pidof kwin_wayland | awk '{print $1}')
|
||||
echo "client=$cli server=$srv kwin=$kw" > $D/$tag.pids
|
||||
sh /data/local/tmp/anl/pbsamp.sh $D/$tag.samp & sp=$!
|
||||
P=$cli; [ -n "$srv" ] && P=$P,$srv; [ -n "$kw" ] && P=$P,$kw
|
||||
top -H -b -d $rec -n 2 -p $(echo $P | tr , ' ' | sed 's/ /,/g') -m 40 -o TID,PID,CMD,%CPU > $D/$tag.top 2>&1 &
|
||||
simpleperf record -e cpu-clock -f 4000 -p $P --duration $rec -o $D/$tag.perf.data > $D/$tag.perf.log 2>&1
|
||||
kill $sp
|
||||
sh /data/local/tmp/anl/pbshown.sh >> $D/$tag.pids
|
||||
wait
|
||||
@@ -0,0 +1,13 @@
|
||||
#!/bin/bash
|
||||
# pbrun.sh <stack: stock|mgl> <tag> (container, root) - runs the command in /root/pb/<tag>.cmd
|
||||
st=$1; tag=$2
|
||||
mkdir -p /root/pb; out=/root/pb/$tag.out; cmd=$(cat /root/pb/$tag.cmd)
|
||||
if [ "$st" = stock ]; then
|
||||
sudo -u swung0x48 bash -c 'set -a; . /etc/environment; set +a; export XDG_RUNTIME_DIR=/run/user/1000 WAYLAND_DISPLAY=wayland-0 DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/1000/bus; cd /tmp; kscreen-doctor --dpms on >/dev/null 2>&1; eval "exec kde-inhibit --power --screenSaver $1"' x "$cmd" > $out 2>&1
|
||||
else
|
||||
rm -f /tmp/pb-$tag.client.log
|
||||
MGLOG=/tmp/pb-$tag.log mgrun offscreen bash -c "$cmd" > $out 2>&1
|
||||
grep -a -m1 "presented through" /tmp/pb-$tag.client.log >> $out
|
||||
cp /tmp/pb-$tag.client.log /root/pb/ 2>/dev/null
|
||||
fi
|
||||
grep -a "Score" $out
|
||||
@@ -0,0 +1,8 @@
|
||||
# pbsamp.sh <outfile> - sample GPU freq/busy, temps, cpu7 freq every 2 s until killed
|
||||
o=$1; : > $o
|
||||
while :; do
|
||||
g=$(cat /sys/class/kgsl/kgsl-3d0/devfreq/cur_freq); b=$(cat /sys/class/kgsl/kgsl-3d0/gpubusy)
|
||||
m=0; gt=0; for z in /sys/class/thermal/thermal_zone*; do case $(cat $z/type) in cpu-*|cpuss-*) v=$(cat $z/temp); [ $v -gt $m ] && m=$v;; gpuss-*) v=$(cat $z/temp); [ $v -gt $gt ] && gt=$v;; esac; done
|
||||
echo "$(date +%s) gpuf=$g busy=$b cpuT=$m gpuT=$gt c7=$(cat /sys/devices/system/cpu/cpu7/cpufreq/scaling_cur_freq) c5=$(cat /sys/devices/system/cpu/cpu5/cpufreq/scaling_cur_freq)" >> $o
|
||||
sleep 2
|
||||
done
|
||||
@@ -0,0 +1,5 @@
|
||||
# pbset.sh <tag> [extra env] - (phone) the affected-scene set, once, es2 window + texture fullscreen
|
||||
t=$1; shift; E="$*"
|
||||
cd /data/local/tmp/anl
|
||||
sh ab.sh arch-kde-mgl $t-w $E glmark2-es2-wayland -b texture:duration=5 -b build:use-vbo=false:duration=5 -b build:use-vbo=true:duration=5 -b desktop:blur-radius=5:effect=blur:passes=1:separable=true:windows=4:duration=5 -b desktop:effect=shadow:windows=4:duration=5 -b ideas:speed=duration:duration=5 -b terrain:duration=5 -b refract:duration=5 -b jellyfish:duration=5 -b shadow:duration=5
|
||||
sh ab.sh arch-kde-mgl $t-f $E glmark2-es2-wayland --fullscreen -b texture:duration=5 -b terrain:duration=5
|
||||
@@ -0,0 +1,4 @@
|
||||
# pbshown.sh - frames SurfaceFlinger latched for the anland SurfaceView in the last second (BLAST layer)
|
||||
L=$(dumpsys SurfaceFlinger --list | grep -E "^SurfaceView\[com\.anland\.consumer.*\(BLAST\)#" | head -1)
|
||||
[ -z "$L" ] && L=$(dumpsys SurfaceFlinger --list | grep -oE "SurfaceView\[com\.anland\.consumer[^]]*\]\(BLAST\)#[0-9]+" | head -1)
|
||||
dumpsys SurfaceFlinger --latency "$L" | awk -v l="$L" 'NR>1 && $2>0 && $2<9e18 {t[n++]=$2; if($2>m)m=$2} END{c=0; for(i=0;i<n;i++) if(t[i]>m-1e9) c++; print "shown_last_1s=" c " layer=" l}'
|
||||
@@ -0,0 +1,12 @@
|
||||
# profrun.sh <container> <prefix> - profile the scene list (phone, root)
|
||||
ct=$1; pre=$2; E="MOBILEGL_PIPE_STATS=1"; [ $ct = arch-kde ] && E=""
|
||||
run() { t=$1; shift; sh /data/local/tmp/anl/pbcool.sh 46000 30 300 > /data/local/tmp/anl/prof/$pre-$t.cool; sh /data/local/tmp/anl/pbprof.sh $ct $pre-$t 7 8 "$@"; }
|
||||
mkdir -p /data/local/tmp/anl/prof
|
||||
run tex $E glmark2-es2-wayland -b texture:texture-filter=linear:duration=18
|
||||
run texF $E glmark2-es2-wayland --fullscreen -b texture:texture-filter=linear:duration=18
|
||||
run blur $E glmark2-es2-wayland -b desktop:blur-radius=5:effect=blur:passes=1:separable=true:windows=4:duration=18
|
||||
run shad $E glmark2-es2-wayland -b desktop:effect=shadow:windows=4:duration=18
|
||||
run ideas $E glmark2-es2-wayland -b ideas:speed=duration:duration=18
|
||||
run terr $E glmark2-es2-wayland -b terrain:duration=18
|
||||
run bvbo $E glmark2-es2-wayland -b build:use-vbo=false:duration=18
|
||||
echo DONE > /data/local/tmp/anl/prof/$pre.done
|
||||
@@ -0,0 +1,14 @@
|
||||
#!/usr/bin/env bash
|
||||
# smoke.sh <tag> - (host) Chrome scrolling + lock screen greeter + Plasma screenshot on the running MobileGL desktop
|
||||
S=${SKILL_SCRIPTS:-$(cd "$(dirname "$0")/../../../.claude/skills/anland-mobilegl-plasma/scripts" && pwd)}
|
||||
O=${OUT_DIR:-${TEMP:-/tmp}}
|
||||
export MSYS_NO_PATHCONV=1
|
||||
T=${1:-smk}
|
||||
printf '%s\n' 'python3 -c "print(\"<html><body style=font-size:40px>\" + \"\".join(\"<p>line %d lorem ipsum dolor sit amet</p>\" % i for i in range(400)) + \"</body></html>\")" > /tmp/long.html; chmod 644 /tmp/long.html' | bash $S/ct.sh pb >/dev/null 2>&1
|
||||
WAIT=15 bash $S/chrome-launch.sh $T file:///tmp/long.html 2>&1 | grep -E "presented|screenshot"
|
||||
adb shell 'su -c "screencap -p /data/local/tmp/anl/sa.png; input mouse scroll 800 1200 --axis VSCROLL,-15; sleep 1; input mouse scroll 800 1200 --axis VSCROLL,-15; sleep 2; screencap -p /data/local/tmp/anl/sb.png; md5sum /data/local/tmp/anl/sa.png /data/local/tmp/anl/sb.png | cut -c1-12"'
|
||||
printf '%s\n' 'U=$(id -u swung0x48); sudo -u swung0x48 env XDG_RUNTIME_DIR=/run/user/$U WAYLAND_DISPLAY=wayland-0 DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/$U/bus nohup /usr/lib/kscreenlocker_greet --testing > /tmp/greet.log 2>&1 & sleep 6; true' | bash $S/ct.sh pb >/dev/null 2>&1
|
||||
adb shell 'su -c "screencap -p /data/local/tmp/anland-mobilegl/lock-'$T'.png"'; adb pull /data/local/tmp/anland-mobilegl/lock-$T.png $O/lock-$T.png >/dev/null
|
||||
printf '%s\n' 'pkill -x kscreenlocker_greet; pkill -x chrome; true' | bash $S/ct.sh pb >/dev/null 2>&1
|
||||
adb shell 'su -c "logcat -b crash -d -T 1 2>/dev/null | grep -c Abort; pidof com.anland.consumer.mobilegl:mobilegl"'
|
||||
echo "lock screenshot: $O/lock-$T.png ; chrome: see the chrome-launch.sh line above"
|
||||
@@ -0,0 +1,10 @@
|
||||
# stfix.sh - (phone, root) if the stock desktop shows black, restart the stock stack; prints what it did
|
||||
D=/data/local/tmp/anl/pb; DS=/data/local/Droidspaces/bin/droidspaces; C=/data/local/Droidspaces/Containers/arch-kde/container.config
|
||||
screencap -p $D/pre.png; s=$(stat -c %s $D/pre.png)
|
||||
if [ "$s" -lt 200000 ]; then
|
||||
echo "stfix: black screen ($s bytes) - restarting the stock stack"
|
||||
am force-stop com.anland.consumer; $DS -C $C stop >/dev/null 2>&1; sleep 2; $DS -C $C start >/dev/null 2>&1; sleep 3
|
||||
monkey -p com.anland.consumer -c android.intent.category.LAUNCHER 1 >/dev/null 2>&1; sleep 25
|
||||
cp $D/../pbrun.sh /mnt/Droidspaces/arch-kde/root/pbrun.sh
|
||||
screencap -p $D/pre.png; echo "stfix: now $(stat -c %s $D/pre.png) bytes"
|
||||
else echo "stfix: screen ok ($s bytes)"; fi
|
||||
@@ -0,0 +1,27 @@
|
||||
# symagg.py <report.txt> <libname-substring> <so-path> <base-hex> [top]
|
||||
# report.txt = simpleperf report --sort dso,vaddr_in_file output; aggregates samples per function.
|
||||
import sys, re, subprocess, collections, os
|
||||
rep, sub, so, base = sys.argv[1], sys.argv[2], sys.argv[3], int(sys.argv[4], 16)
|
||||
top = int(sys.argv[5]) if len(sys.argv) > 5 else 30
|
||||
SYM = os.path.expandvars(r'$LOCALAPPDATA/Android/Sdk/ndk/27.2.12479018/toolchains/llvm/prebuilt/windows-x86_64/bin/llvm-symbolizer.exe')
|
||||
rows = []
|
||||
for line in open(rep, encoding='utf-8', errors='replace'):
|
||||
m = re.match(r'\s*([\d.]+)%\s+(\S+)\s+(0x[0-9a-f]+|\S+)', line)
|
||||
if not m: continue
|
||||
rows.append((float(m.group(1)), m.group(2), m.group(3)))
|
||||
addrs = [int(a, 16) + base for p, d, a in rows if sub in d and a.startswith('0x')]
|
||||
names = {}
|
||||
if addrs:
|
||||
out = subprocess.run([SYM, '--obj=' + so, '-C', '-f', '--inlining=false'] + ['0x%x' % a for a in addrs], capture_output=True, text=True).stdout
|
||||
blocks = [b for b in out.strip().split('\n\n')]
|
||||
for a, b in zip(addrs, blocks):
|
||||
names[a] = b.split('\n')[0][:140]
|
||||
agg = collections.Counter()
|
||||
for p, d, a in rows:
|
||||
if sub in d and a.startswith('0x'):
|
||||
agg[names.get(int(a, 16) + base, a)] += p
|
||||
else:
|
||||
key = os.path.basename(d) + (' ' + a if d.startswith('[kernel') or 'vdso' in d else '')
|
||||
agg[key if not d.startswith('[kernel') else '[kernel]'] += p
|
||||
for k, v in agg.most_common(top):
|
||||
print('%6.2f%% %s' % (v, k))
|
||||
@@ -0,0 +1,27 @@
|
||||
import sys, collections
|
||||
f = sys.argv[1]; tids = sys.argv[2].split(','); t0off = float(sys.argv[3]); span = float(sys.argv[4])
|
||||
samples = []; cur = None
|
||||
for line in open(f, encoding='utf-8', errors='replace'):
|
||||
s = line.strip()
|
||||
if s == 'sample:':
|
||||
if cur: samples.append(cur)
|
||||
cur = {'ev': '', 'tid': '', 'time': 0, 'syms': []}; continue
|
||||
if cur is None: continue
|
||||
if s.startswith('event_type:'): cur['ev'] = s.split()[1]
|
||||
elif s.startswith('thread_id:'): cur['tid'] = s.split()[1]
|
||||
elif s.startswith('time:'): cur['time'] = int(s.split()[1])
|
||||
elif s.startswith('symbol:'): cur['syms'].append(s.split(None, 1)[1])
|
||||
if cur: samples.append(cur)
|
||||
samples = [x for x in samples if x['tid'] in tids]
|
||||
samples.sort(key=lambda x: x['time'])
|
||||
T0 = samples[0]['time'] + int(t0off * 1e6)
|
||||
# collapse into intervals per tid: state on/off; print transitions
|
||||
last = {}
|
||||
for x in samples:
|
||||
if x['time'] < T0 or x['time'] > T0 + span * 1e6: continue
|
||||
st = 'OFF' if x['ev'].startswith('sched') else 'on '
|
||||
k = [s for s in x['syms'] if 'kallsyms' not in s][:1]
|
||||
key = (st, x['syms'][0] if st=='on ' else ','.join(s for s in x['syms'][1:12] if s in ('do_sys_poll','futex_wait_queue','unix_stream_read_generic','binder_thread_read','do_nanosleep','__wake_up_sync_key')))
|
||||
if last.get(x['tid']) != key:
|
||||
print('%9.3f ms %-6s %s %s' % ((x['time'] - T0) / 1e6, x['tid'], st, key[1][:60]))
|
||||
last[x['tid']] = key
|
||||
@@ -0,0 +1,9 @@
|
||||
# visset.sh <tag> - screenshot several scenes mid-run (phone, root)
|
||||
CR=/mnt/Droidspaces/arch-kde-mgl/root; D=/data/local/tmp/anland-mobilegl
|
||||
for sc in ideas:duration=6 terrain:duration=6 shadow:duration=6 refract:duration=6 jellyfish:duration=6 desktop:effect=shadow:windows=4:duration=6 desktop:blur-radius=5:effect=blur:passes=1:separable=true:windows=4:duration=6 bump:bump-render=high-poly:duration=6 conditionals:duration=6 effect2d:duration=6; do
|
||||
n=$(echo $sc | cut -d: -f1)
|
||||
echo "glmark2-es2-wayland -b $sc" > $CR/pb/vis.cmd
|
||||
/data/local/Droidspaces/bin/droidspaces --name=arch-kde-mgl run bash /root/pbrun.sh mgl vis >/dev/null 2>&1 &
|
||||
sleep 4; screencap -p $D/$1-$n.png; wait
|
||||
done
|
||||
ls $D/$1-*.png | wc -l
|
||||
@@ -0,0 +1,17 @@
|
||||
#!/bin/bash
|
||||
# wtest.sh build|run [ctest -R regex] - host unit tests for worktree $W in $B
|
||||
W=${W:?set W to the MobileGL worktree as a WSL path}
|
||||
B=${B:-$HOME/mgl-test-perf}
|
||||
if [ "$1" = build ]; then
|
||||
if [ ! -f $B/build.ninja ]; then
|
||||
cmake -S $W -B $B -G Ninja -DCMAKE_BUILD_TYPE=Release -DCMAKE_C_COMPILER=clang -DCMAKE_CXX_COMPILER=clang++ \
|
||||
-DMOBILEGL_BUILD_TEST=ON -DMOBILEGL_BUILD_DISAGGREGATED=ON -DMOBILEGL_BUILD_DISAGGREGATED_INPROC=ON -DMOBILEGL_BUILD_STAMP=wsl > $B.cfg.log 2>&1 || { tail -20 $B.cfg.log; exit 1; }
|
||||
fi
|
||||
cd $B
|
||||
T=$(ninja -t targets all 2>/dev/null | grep -oE "^[A-Za-z]+Test:" | tr -d : | sort -u | grep -v -E "^(DirectVulkan|Benchmark)" | tr "\n" " ")
|
||||
ninja -j12 MobileGLServer $T > $B.build.log 2>&1; rc=$?
|
||||
echo "build rc=$rc"; grep -E "error:|FAILED" $B.build.log | head -20
|
||||
elif [ "$1" = run ]; then
|
||||
cd $B; shift
|
||||
ctest -L unit -j10 --timeout 300 -E "DirectVulkan" "$@" 2>&1 | tail -30
|
||||
fi
|
||||
Reference in new issue
Block a user