mirror of
https://github.com/MobileGL-Dev/MobileGL
synced 2026-11-20 08:21:56 +09:00
Compare commits
124
Commits
ff2994d9a8
...
f567610339
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f567610339 | ||
|
|
538c3c19ee | ||
|
|
02972f70b6 | ||
|
|
a164113029 | ||
|
|
4dd4027e80 | ||
|
|
f561499519 | ||
|
|
b13f2b0283 | ||
|
|
c9878d69f3 | ||
|
|
74060e8b5d | ||
|
|
edcdf771db | ||
|
|
a48bc46ec1 | ||
|
|
fbeea876b3 | ||
|
|
1646049ac9 | ||
|
|
13043e3ff4 | ||
|
|
49fecc1686 | ||
|
|
a838c7879d | ||
|
|
6d86f9d9be | ||
|
|
eec0e836c6 | ||
|
|
fa924d34fb | ||
|
|
cc20de37da | ||
|
|
ca92308bc0 | ||
|
|
68d8ef9f34 | ||
|
|
e61d00123c | ||
|
|
65a403284c | ||
|
|
2536ffb920 | ||
|
|
5682f429d0 | ||
|
|
b2dcae713f | ||
|
|
c9d84e33c5 | ||
|
|
f280baf2b3 | ||
|
|
455b475c5d | ||
|
|
a85aa95401 | ||
|
|
05bcb73477 | ||
|
|
61d6cd8e30 | ||
|
|
7a925b3259 | ||
|
|
0fde95357c | ||
|
|
0244fc4a50 | ||
|
|
e7fe3b9770 | ||
|
|
41992649c9 | ||
|
|
c3e736a343 | ||
|
|
02f15bb675 | ||
|
|
39292958e0 | ||
|
|
949ba509f3 | ||
|
|
129969c327 | ||
|
|
0a22f363ff | ||
|
|
2e2b41ab49 | ||
|
|
cd2079ec8f | ||
|
|
aa7ad670c4 | ||
|
|
3fb97cc536 | ||
|
|
bb6ba28241 | ||
|
|
ba6dc4f7f1 | ||
|
|
1a06b40a58 | ||
|
|
7110cdb61a | ||
|
|
ce53553c79 | ||
|
|
6cabc6b070 | ||
|
|
f63c9483de | ||
|
|
571cbabb53 | ||
|
|
7ea3b1d1f1 | ||
|
|
d623118485 | ||
|
|
23c0468775 | ||
|
|
8dbe230ae3 | ||
|
|
377356f8ca | ||
|
|
4ba14fa4ed | ||
|
|
87c1e1bebd | ||
|
|
5e5bf7b9d6 | ||
|
|
fff9d639f0 | ||
|
|
d628d906d1 | ||
|
|
bfaf5f9d0e | ||
|
|
3089ce8c1a | ||
|
|
a6bcf28da0 | ||
|
|
2de7d40555 | ||
|
|
511e902f27 | ||
|
|
505b5084cf | ||
|
|
6afa044701 | ||
|
|
f858841c5f | ||
|
|
3dadd4c1e0 | ||
|
|
0598cfffe0 | ||
|
|
950968044c | ||
|
|
3a5e26215d | ||
|
|
6e858fa3f6 | ||
|
|
ab112eb0ed | ||
|
|
d55e37337b | ||
|
|
f33e5d6090 | ||
|
|
949ed1f037 | ||
|
|
8b425a9718 | ||
|
|
79b7866511 | ||
|
|
3f1eaee787 | ||
|
|
8024dab9f4 | ||
|
|
da8f030459 | ||
|
|
ed60c06b98 | ||
|
|
c5c12b489a | ||
|
|
3aa48bccdc | ||
|
|
126bd9aa62 | ||
|
|
3cb2c4aa9a | ||
|
|
c16411aa33 | ||
|
|
fb70704e74 | ||
|
|
7ad0ff3c33 | ||
|
|
31de23142f | ||
|
|
db1a5dbc27 | ||
|
|
0b847d462a | ||
|
|
d9ade1e7cd | ||
|
|
142bf921d4 | ||
|
|
13827e376f | ||
|
|
feca3994d1 | ||
|
|
851a0b6f76 | ||
|
|
eaf2b28b8c | ||
|
|
76140c33eb | ||
|
|
75c0bcae80 | ||
|
|
1f953c09ea | ||
|
|
558fb210dc | ||
|
|
7c25130d5a | ||
|
|
817e1c40cf | ||
|
|
97df377381 | ||
|
|
96cc6a14af | ||
|
|
bc55da75fb | ||
|
|
d709ef3ee9 | ||
|
|
bb6848c8d1 | ||
|
|
f265f0a8e1 | ||
|
|
55ed1c8784 | ||
|
|
eafa47ea46 | ||
|
|
91d0c6b06f | ||
|
|
1af5e31f3b | ||
|
|
d17c6c225c | ||
|
|
713d1b51ac | ||
|
|
aa263d2169 |
+641
-8
@@ -736,6 +736,389 @@ jobs:
|
||||
path: /tmp/core.*
|
||||
if-no-files-found: ignore
|
||||
|
||||
# P5's split build. The verify pair cloned, because the problem is the same one: a third
|
||||
# configuration of the same sources whose whole value depends on the option having taken.
|
||||
#
|
||||
# IT CANNOT RIDE ON build-linux'S ARTIFACT. build-linux passes no -DMOBILEGL_PIPE_PUSH, so it is
|
||||
# a PULL build; MOBILEGL_BUILD_DISAGGREGATED implies MOBILEGL_PIPE_PUSH (the split path decodes
|
||||
# into the MGPipe applier and PIPE_PUSH is what compiles the applier), so the split arm needs a
|
||||
# build of its own exactly as the verify arm does.
|
||||
#
|
||||
# THE `nm` STEP IS THE POINT OF THIS JOB. In a build without the option, MG_Remote is not
|
||||
# compiled at all and MOBILEGL_TRANSPORT's parser does not exist - so the variable is accepted by
|
||||
# the environment and silently ignored (CONTRACT-P5 5). Every downstream lane would then run
|
||||
# monolith and go green under a name that says split. CMake will not complain about a typo'd -D,
|
||||
# so the build-level assertion is the only guard, and its absence is precisely what would make
|
||||
# the whole split arm meaningless.
|
||||
build-linux-split:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 120
|
||||
permissions:
|
||||
actions: write
|
||||
contents: read
|
||||
env:
|
||||
BUILD_DIR: build-split
|
||||
CCACHE_BASEDIR: ${{ github.workspace }}
|
||||
CCACHE_COMPRESS: "true"
|
||||
CCACHE_DIR: ${{ github.workspace }}/.ccache
|
||||
CCACHE_MAXSIZE: 4G
|
||||
CCACHE_NOHASHDIR: "true"
|
||||
|
||||
steps:
|
||||
- name: Set Swap Space
|
||||
uses: pierotofy/set-swap-space@v1.0
|
||||
with:
|
||||
swap-size-gb: 32
|
||||
|
||||
- name: Checkout repo
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
# recursive, and load-bearing here beyond the usual: MOBILEGL_BUILD_DISAGGREGATED
|
||||
# SHADOWS ITSELF BACK TO OFF when 3rdparty/flatbuffers/include is missing
|
||||
# (CMakeLists.txt:471-486, a normal variable rather than a cache force, deliberately).
|
||||
# A shallow checkout would therefore configure cleanly, build a monolith library, and
|
||||
# be caught only by the nm step below.
|
||||
submodules: recursive
|
||||
|
||||
- name: Get CMake
|
||||
uses: lukka/get-cmake@v4.3.3
|
||||
|
||||
- name: Restore ccache
|
||||
uses: actions/cache/restore@v5
|
||||
with:
|
||||
path: .ccache
|
||||
key: ${{ runner.os }}-test-${{ github.job }}-ccache-v1
|
||||
restore-keys: |
|
||||
${{ runner.os }}-test-${{ github.job }}-ccache-
|
||||
|
||||
- name: Prepare Vulkan SDK
|
||||
uses: humbletim/setup-vulkan-sdk@v1.2.1
|
||||
with:
|
||||
vulkan-query-version: 1.4.304.1
|
||||
vulkan-components: Vulkan-Headers, Vulkan-Loader
|
||||
vulkan-use-cache: true
|
||||
|
||||
- name: Update glslang external sources
|
||||
working-directory: 3rdparty/glslang
|
||||
run: python update_glslang_sources.py
|
||||
|
||||
- name: Install build dependencies
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y ccache clang-20 clang++-20 lld-20 libc++-20-dev libc++abi-20-dev libvulkan-dev libegl1-mesa-dev libgles2-mesa-dev libgl1-mesa-dri mesa-vulkan-drivers ninja-build
|
||||
|
||||
- name: Show installed toolchain
|
||||
run: |
|
||||
ccache --version
|
||||
clang-20 --version
|
||||
clang++-20 --version
|
||||
dpkg -l 'libc++*' 'libegl*' 'libgles*' 'mesa*' 'vulkan*' || true
|
||||
|
||||
- name: Configure CMake
|
||||
# Release/INFO like the shipped build, for the same reason build-linux-verify gives.
|
||||
# INFO specifically matters here: ConfigLoader logs the resolved transport at INFO and
|
||||
# that line is what run_trace_case.cmake and the integration-split lane read back as
|
||||
# proof the transport resolved in THIS process.
|
||||
#
|
||||
# _INPROC implies _DISAGGREGATED implies _PIPE_PUSH; all three are passed anyway, because
|
||||
# an implication that is asserted in two places is an implication nobody has to remember.
|
||||
run: |
|
||||
cmake -S . -B "${BUILD_DIR}" -G Ninja \
|
||||
-DCMAKE_C_COMPILER=clang-20 \
|
||||
-DCMAKE_CXX_COMPILER=clang++-20 \
|
||||
-DCMAKE_C_COMPILER_LAUNCHER=ccache \
|
||||
-DCMAKE_CXX_COMPILER_LAUNCHER=ccache \
|
||||
-DCMAKE_BUILD_TYPE=Release \
|
||||
-DMOBILEGL_LOG_ACTIVE_LEVEL=MOBILEGL_LOG_LEVEL_INFO \
|
||||
-DMOBILEGL_BUILD_TEST=ON \
|
||||
-DMOBILEGL_BUILD_BENCHMARK=OFF \
|
||||
-DMOBILEGL_BUILD_INTEGRATION_TEST=ON \
|
||||
-DMOBILEGL_ITEST_VK_ICD=/usr/share/vulkan/icd.d/lvp_icd.json \
|
||||
-DMOBILEGL_BUILD_TRACE_REPLAY=OFF \
|
||||
-DMOBILEGL_PIPE_PUSH=ON \
|
||||
-DMOBILEGL_BUILD_DISAGGREGATED=ON \
|
||||
-DMOBILEGL_BUILD_DISAGGREGATED_INPROC=ON \
|
||||
-DCMAKE_POLICY_VERSION_MINIMUM=3.5
|
||||
|
||||
- name: Build
|
||||
run: cmake --build "${BUILD_DIR}" --parallel "$(nproc)"
|
||||
|
||||
# `nm` and NOT `nm -D`, for the reason build-linux-verify spells out: everything under
|
||||
# MG_Remote is a plain namespace symbol in a CXX_VISIBILITY_PRESET=hidden Release build and
|
||||
# none of it reaches the dynamic table. The symbol count guards the remaining hole - a
|
||||
# stripped library would make the grep fail for a third, silent reason.
|
||||
#
|
||||
# The mirror of this assertion already exists and is the G1 control: monolith-symbol-report
|
||||
# asserts that a -DMOBILEGL_BUILD_DISAGGREGATED=OFF library defines NO MG_Remote symbol. The
|
||||
# two together are ARCHITECTURE.md:524's surviving byte-level equality, in both directions.
|
||||
- name: The split library really carries MG_Remote
|
||||
run: |
|
||||
test -f "${BUILD_DIR}/libMobileGL.so"
|
||||
defined=$(nm --defined-only "${BUILD_DIR}/libMobileGL.so" | wc -l)
|
||||
if [ "${defined}" -lt 1000 ]; then
|
||||
echo "::error::nm --defined-only sees only ${defined} symbols in ${BUILD_DIR}/libMobileGL.so - it looks stripped, so the checks below could not have failed honestly"
|
||||
exit 1
|
||||
fi
|
||||
remote=$(nm --defined-only "${BUILD_DIR}/libMobileGL.so" | grep -c -i "MG_Remote" || true)
|
||||
if [ "${remote}" -lt 1 ]; then
|
||||
echo "::error::libMobileGL.so defines no MG_Remote symbol: -DMOBILEGL_BUILD_DISAGGREGATED=ON did not take (a typo'd -D is not a CMake error, and the option shadows itself OFF when 3rdparty/flatbuffers/include is missing). Every lane that consumes this artifact would run MONOLITH while claiming to run split, because the MOBILEGL_TRANSPORT parser does not exist in such a build and the variable is accepted and ignored."
|
||||
exit 1
|
||||
fi
|
||||
# The transport parser itself, which is the symbol the runtime evidence depends on.
|
||||
if ! nm --defined-only "${BUILD_DIR}/libMobileGL.so" | grep -q "MGPipeApply"; then
|
||||
echo "::error::libMobileGL.so defines no MGPipeApply* entry point, so MOBILEGL_PIPE_PUSH did not take either and there is no applier for the split path to decode into"
|
||||
exit 1
|
||||
fi
|
||||
echo "libMobileGL.so defines ${remote} MG_Remote symbol(s) and the MGPipe applier (${defined} defined symbols)"
|
||||
|
||||
- name: Show ccache stats
|
||||
if: always()
|
||||
run: ccache --show-stats
|
||||
|
||||
- name: Release superseded ccache entry
|
||||
if: github.ref_name == github.event.repository.default_branch
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
CACHE_KEY: ${{ runner.os }}-test-${{ github.job }}-ccache-v1
|
||||
run: gh cache delete "${CACHE_KEY}" || true
|
||||
|
||||
- name: Save ccache
|
||||
if: github.ref_name == github.event.repository.default_branch
|
||||
continue-on-error: true
|
||||
uses: actions/cache/save@v5
|
||||
with:
|
||||
path: .ccache
|
||||
key: ${{ runner.os }}-test-${{ github.job }}-ccache-v1
|
||||
|
||||
- name: Package Linux split runtime
|
||||
run: |
|
||||
mkdir -p ci-artifacts
|
||||
mapfile -t SHARED_LIBS < <(find "${BUILD_DIR}" -type f \( -name '*.so' -o -name '*.so.*' \) -print | sort)
|
||||
tar \
|
||||
--exclude='*/CMakeFiles' \
|
||||
--exclude='*.o' \
|
||||
--exclude='*.a' \
|
||||
--exclude='*.ninja*' \
|
||||
--exclude='build.ninja' \
|
||||
--exclude='cmake_install.cmake' \
|
||||
-czf ci-artifacts/mobilegl-linux-runtime-split.tgz \
|
||||
"${BUILD_DIR}/CTestTestfile.cmake" \
|
||||
"${BUILD_DIR}/MobileGL/MG_Test" \
|
||||
"${BUILD_DIR}/MobileGL/MG_IntegrationTest" \
|
||||
"${SHARED_LIBS[@]}"
|
||||
|
||||
- name: Upload Linux split runtime
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: mobilegl-linux-runtime-split
|
||||
path: ci-artifacts/mobilegl-linux-runtime-split.tgz
|
||||
if-no-files-found: error
|
||||
|
||||
# The split lane itself: the three-arm shape ARCHITECTURE.md:521 asks for verbatim, plus the
|
||||
# first real run of the five MG_Test/Wire suites, plus P5's two exit-gate negative controls.
|
||||
integration-split:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 120
|
||||
needs: build-linux-split
|
||||
|
||||
steps:
|
||||
- name: Checkout repo
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Get CMake
|
||||
uses: lukka/get-cmake@v4.3.3
|
||||
|
||||
- name: Install runtime dependencies
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y libvulkan1 libegl1 libegl-mesa0 libgles2 libgl1-mesa-dri mesa-vulkan-drivers
|
||||
|
||||
- name: Download Linux split runtime
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
name: mobilegl-linux-runtime-split
|
||||
path: .
|
||||
|
||||
- name: Unpack Linux split runtime
|
||||
run: |
|
||||
tar -xzf mobilegl-linux-runtime-split.tgz
|
||||
test -f build-split/libMobileGL.so
|
||||
|
||||
- name: Normalize CTest command paths
|
||||
run: |
|
||||
python - <<'PY'
|
||||
from pathlib import Path
|
||||
import re
|
||||
|
||||
for path in Path('build-split').rglob('CTestTestfile.cmake'):
|
||||
text = path.read_text()
|
||||
text = re.sub(r'"[^"]*/cmake-[^"]*/bin/cmake"', '"cmake"', text)
|
||||
path.write_text(text)
|
||||
PY
|
||||
|
||||
# THE FIRST REAL RUN OF MG_Test/Wire. Those five suites - Framing, Ring, InProcessTransport,
|
||||
# ProtocolSmoke and FdPassing - are registered only under MOBILEGL_BUILD_DISAGGREGATED
|
||||
# (MG_Test/CMakeLists.txt), and before this job existed NO cmake invocation anywhere in this
|
||||
# workflow passed that option. They had never been compiled by CI, let alone run.
|
||||
- name: Unit tests on the split runtime
|
||||
working-directory: build-split
|
||||
run: ctest --output-on-failure -L unit --no-tests=error -j "$(nproc)"
|
||||
|
||||
# --no-tests=error is half the gate, exactly as in integration-verify: the integration-split
|
||||
# entries exist only when the library was configured with -DMOBILEGL_BUILD_DISAGGREGATED=ON,
|
||||
# so a build that lost the option matches nothing and reds here instead of reporting a green
|
||||
# run of nothing. The other half is the transport-resolution check below.
|
||||
#
|
||||
# An entry whose owning package (c1 client, s1 session, v1 server) has not landed SKIPS with
|
||||
# the reason and never goes green - MG_IntegrationTest/CMakeLists.txt probes MG_Remote for
|
||||
# c0's signature stubs and disarms the lane while any remain.
|
||||
- name: Split scenarios under MOBILEGL_TRANSPORT=inproc
|
||||
working-directory: build-split
|
||||
env:
|
||||
MOBILEGL_ITEST_REQUIRE_GPU: "1"
|
||||
run: |
|
||||
ulimit -c unlimited
|
||||
sudo sysctl -w kernel.core_pattern='/tmp/core.%e.%p'
|
||||
ctest --output-on-failure -L integration-split --no-tests=error -j 4
|
||||
|
||||
# ARCHITECTURE.md:521 asks for `ctest -L integration-gpu` to be name-for-name identical
|
||||
# between the monolith and the split arm of the SAME build - the G2 shape extended to a
|
||||
# third arm. The knob goes in the JOB environment rather than in a ctest property, for the
|
||||
# reason the MOBILEGL_ESPRYT_DISABLE_INVALIDATE_FLUSH precedent in `integration` gives: a
|
||||
# property would override it and the arm would not be an arm.
|
||||
#
|
||||
# The entries that name MOBILEGL_TRANSPORT in their OWN property (the Split. lanes) keep
|
||||
# their value in both passes, which is correct: they are the split family in both arms and
|
||||
# the comparison is about the other 1100.
|
||||
- name: The same integration entries under monolith and under inproc
|
||||
working-directory: build-split
|
||||
env:
|
||||
MOBILEGL_ITEST_REQUIRE_GPU: "1"
|
||||
MOBILEGL_MAGMA_FIX_ITERATIONRP_SUBGROUP_SCRATCH: "1"
|
||||
MOBILEGL_MAGMA_DERIVE_NUM_SUBGROUPS: "1"
|
||||
MOBILEGL_MAGMA_ITERATIONRP_FIX_BARRIER: "1"
|
||||
run: |
|
||||
ulimit -c unlimited
|
||||
sudo sysctl -w kernel.core_pattern='/tmp/core.%e.%p'
|
||||
count=$(ctest -N -L integration-gpu | grep -cE '^ *Test *#[0-9]+:')
|
||||
if [ "${count}" -lt 1 ]; then
|
||||
echo "::error::the split runtime registers ${count} integration-gpu entries"
|
||||
exit 1
|
||||
fi
|
||||
echo "integration-gpu entries in the split build: ${count}"
|
||||
MOBILEGL_TRANSPORT=monolith ctest --output-on-failure -L integration-gpu --no-tests=error -j 4 --output-junit "${RUNNER_TEMP}/arm-monolith.xml"
|
||||
MOBILEGL_TRANSPORT=inproc ctest --output-on-failure -L integration-gpu --no-tests=error -j 4 --output-junit "${RUNNER_TEMP}/arm-inproc.xml"
|
||||
# NAME **AND STATUS**, and it is the comparison this step claimed to make and did not
|
||||
# (review finding N-3): the first version wrote a names file and never read it, and
|
||||
# `--output-on-failure` treats a SKIPPED test as not-a-failure - so the very failure
|
||||
# ARCHITECTURE.md:521 is about, "an inproc arm that skipped forty entries the monolith arm
|
||||
# ran", was invisible here and caught only by the local gate. `ctest -N` cannot see it
|
||||
# either: this is one build directory, so the two arms have identical name lists by
|
||||
# construction and the difference is entirely in what each entry DID.
|
||||
python3 - "${RUNNER_TEMP}/arm-monolith.xml" "${RUNNER_TEMP}/arm-inproc.xml" <<'PY'
|
||||
import sys, xml.etree.ElementTree as ET
|
||||
def rows(path):
|
||||
out = {}
|
||||
for case in ET.parse(path).getroot().iter('testcase'):
|
||||
status = 'passed'
|
||||
if case.find('failure') is not None or case.find('error') is not None:
|
||||
status = 'failed'
|
||||
elif case.find('skipped') is not None or case.get('status') in ('notrun', 'disabled'):
|
||||
status = 'skipped'
|
||||
out[case.get('name')] = status
|
||||
return out
|
||||
a, b = rows(sys.argv[1]), rows(sys.argv[2])
|
||||
diff = sorted(set(a) ^ set(b)) + sorted(n for n in set(a) & set(b) if a[n] != b[n])
|
||||
if diff:
|
||||
for name in diff[:40]:
|
||||
print(f"::error::{name}: monolith={a.get(name, '<absent>')} inproc={b.get(name, '<absent>')}")
|
||||
print(f"::error::the monolith and inproc arms of ctest -L integration-gpu differ on "
|
||||
f"{len(diff)} entries. ARCHITECTURE.md:521 requires them identical name for name "
|
||||
f"AND status; an entry that SKIPPED on one arm and ran on the other is the "
|
||||
f"failure this compares for, and it is not a failure to --output-on-failure.")
|
||||
raise SystemExit(1)
|
||||
print(f"the two arms agree on all {len(a)} entries, name and status")
|
||||
PY
|
||||
|
||||
# THE RUNTIME HALF OF "THIS IS REALLY A SPLIT BUILD". The build-level nm check in
|
||||
# build-linux-split proves the library CARRIES MG_Remote; this proves the transport
|
||||
# RESOLVED in a process of this lane. ConfigLoader::InitTransport logs one INFO line when it
|
||||
# selects InProcess, and the DirectGLES.Split.PersistentMapArm. entry retains its private
|
||||
# counting log (all Split entries now have private paths; nothing else writes this file).
|
||||
# The line is written during bring-up, before any scenario decides to skip, so this
|
||||
# check is live from the day the lanes land rather than from the day they stop skipping.
|
||||
- name: The split lane really resolved the transport
|
||||
working-directory: build-split
|
||||
run: |
|
||||
log=MobileGL/MG_IntegrationTest/persistent-map-arm-split-DirectGLES.log
|
||||
if [ ! -f "${log}" ]; then
|
||||
echo "::error::${log} does not exist: the DirectGLES.Split.PersistentMapArm. entry never ran, so nothing in this job establishes that MOBILEGL_TRANSPORT ever resolved to inproc in a live process"
|
||||
exit 1
|
||||
fi
|
||||
# THE DISTINCTIVE PART OF THE INFO LINE, not the bare KEY=VALUE (review finding M-5):
|
||||
# ConfigLoader logs `Config: Accepted env variable: MOBILEGL_TRANSPORT=inproc` for the
|
||||
# env dump too, unconditionally and in a PULL build, and at DEBUG that line is live.
|
||||
if ! grep -q "MOBILEGL_TRANSPORT=inproc - the MGPipe record stream" "${log}"; then
|
||||
echo "::error::${log} carries no transport-resolution line. ConfigLoader::InitTransport logs it at INFO when it selects InProcess, and that code exists only in a MOBILEGL_BUILD_DISAGGREGATED build - so this lane ran a monolith library while claiming to be the split lane. (A bare MOBILEGL_TRANSPORT=inproc substring is NOT accepted: the env dump prints one in every build.)"
|
||||
exit 1
|
||||
fi
|
||||
echo "the split lane resolved MOBILEGL_TRANSPORT=inproc"
|
||||
|
||||
# EXIT GATE E1's NEGATIVE CONTROL and EXIT GATE E3(a)'s, in one step because they have the
|
||||
# same two-state shape and the same reason for it.
|
||||
#
|
||||
# Both controls turn a knob that MUST make a split scenario red: MOBILEGL_IPC_VERB_BARRIER=0
|
||||
# removes the lockstep fence R-1 rests on, and MOBILEGL_IPC_PERSISTENT_BLOCK_KB=0 turns the
|
||||
# persistent-map push off. A control of the verify lane's shape - "this step passes when
|
||||
# ctest FAILS" - cannot be written yet, because while packages c1/s1/v1 are landing the
|
||||
# Split entries SKIP and ctest reports green whatever the knob says, so an unconditional
|
||||
# control would be red for the whole of P5 for a reason that is not a defect.
|
||||
#
|
||||
# So the expected state is DERIVED FROM BEHAVIOUR rather than assumed. The first version read
|
||||
# MGITEST_REMOTE_CLIENT_PRESENT out of the generated *_tests.cmake, which was a restatement of
|
||||
# the CMake source probe review finding M-1 falsified; the arming condition is a runtime fact
|
||||
# inside each test process (MG_Config::Transport, ClientSession::Active() and
|
||||
# ImplementedVerbCount(), read by Harness/SplitRuntimePeek), so the only honest way to ask it
|
||||
# from a shell is to look at what the entries DID. When entries passed, the controls MUST
|
||||
# fire; when every one of them skipped, the step says so loudly and does not pretend.
|
||||
#
|
||||
# THE BODY OF THIS STEP IS scripts/ci/split_negative_controls.sh, and the move is the point
|
||||
# rather than tidiness. A `run:` block executes nowhere but on a runner, so these lines were
|
||||
# unreviewable and untestable: when the wave-1 cross-family review said they were broken,
|
||||
# CONFIRMING it needed a hand-made copy of them (wave1-codex-verify.md 8), and a copy is not
|
||||
# the thing. scripts/ci/control_smoke_test.sh now drives the very file this step runs.
|
||||
#
|
||||
# What that smoke test pins, and what ID-46 finding 8 found missing: each control asserts its
|
||||
# OWN failure reason. A non-zero ctest exit used to be enough, so a timeout, a setup abort or
|
||||
# any unrelated assertion printed "turned N selected entries red, as it must" and this step
|
||||
# went green. The arming run's `|| true` had the matching defect - it counted a case that ran
|
||||
# and FAILED as evidence the lane was live, so the controls could be measured against a
|
||||
# baseline that was already red.
|
||||
- name: Negative controls - the verb barrier and the persistent-map push must be load-bearing
|
||||
working-directory: build-split
|
||||
env:
|
||||
MOBILEGL_ITEST_REQUIRE_GPU: "1"
|
||||
CONTROL_TMPDIR: ${{ runner.temp }}
|
||||
run: bash "${GITHUB_WORKSPACE}/scripts/ci/split_negative_controls.sh"
|
||||
|
||||
- name: Upload split lane logs
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: integration-split-logs
|
||||
path: |
|
||||
build-split/MobileGL/MG_IntegrationTest/*.log*
|
||||
build-split/MobileGL/MG_IntegrationTest/split-logs/*.log
|
||||
if-no-files-found: warn
|
||||
|
||||
- name: Upload core dumps
|
||||
if: failure()
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: integration-split-core-dumps
|
||||
path: /tmp/core.*
|
||||
if-no-files-found: ignore
|
||||
|
||||
# MobileGL/MG_Remote/Protocol/generated/protocol_generated.h is COMMITTED, and
|
||||
# flatc is deliberately absent from the default build graph (a codegen step in
|
||||
# the graph is how the earlier branch ended up cross-compiling an arm64 flatc
|
||||
@@ -1013,6 +1396,7 @@ jobs:
|
||||
matrix: ${{ steps.trace-cases.outputs.matrix }}
|
||||
names: ${{ steps.trace-cases.outputs.names }}
|
||||
verify-matrix: ${{ steps.trace-cases.outputs.verify-matrix }}
|
||||
split-matrix: ${{ steps.trace-cases.outputs.split-matrix }}
|
||||
steps:
|
||||
- name: Checkout repo
|
||||
uses: actions/checkout@v6
|
||||
@@ -1025,6 +1409,20 @@ jobs:
|
||||
# The subset the verify build retraces ("verify": true in trace_cases.json). It is a
|
||||
# SUBSET of the matrix above, so retrace-verify needs no fixtures of its own.
|
||||
echo "verify-matrix=$(python3 tools/trace_replay/trace_cases.py --ci --format github-verify-matrix)" >> "$GITHUB_OUTPUT"
|
||||
# P5's split subset ("split": true, DirectGLES only). Also a SUBSET of the matrix above,
|
||||
# so retrace-split needs no fixtures of its own either. It is one case today - OpenRA,
|
||||
# which is what the phase gate names - and trace_cases.py refuses a `split` case that is
|
||||
# not in CI or does not run DirectGLES, so the subset cannot silently become empty.
|
||||
SPLIT_MATRIX=$(python3 tools/trace_replay/trace_cases.py --ci --format github-split-matrix)
|
||||
# AND IT MUST NOT BE EMPTY. An empty `include` is not an error to GitHub - it skips the
|
||||
# whole retrace-split job with no red anywhere - so the one way this subset can vanish
|
||||
# silently is guarded here. trace_cases.py now also rejects an unknown manifest key, which
|
||||
# was the hole: `"splitt": true` loaded clean and emptied the subset (review N-4).
|
||||
if [ "$(printf '%s' "${SPLIT_MATRIX}" | python3 -c 'import json,sys; print(len(json.load(sys.stdin)["include"]))')" -lt 1 ]; then
|
||||
echo "::error::the split retrace subset is EMPTY. No case in trace_cases.json carries \"split\": true, so retrace-split would be skipped with no red. Exit gate E2 names OpenRA."
|
||||
exit 1
|
||||
fi
|
||||
echo "split-matrix=${SPLIT_MATRIX}" >> "$GITHUB_OUTPUT"
|
||||
|
||||
trace-fixtures:
|
||||
name: trace fixture (${{ matrix.case }})
|
||||
@@ -1397,6 +1795,202 @@ jobs:
|
||||
build-retrace/tools/trace_replay/${{ matrix.case }}/${{ matrix.backend }}/output/**
|
||||
if-no-files-found: warn
|
||||
|
||||
# P5's retrace arm: retrace-verify with MOBILEGL_PIPE_VERIFY=1 swapped for
|
||||
# MOBILEGL_TRANSPORT=inproc and the comparator's symbol swapped for an MG_Remote one. Exit gate
|
||||
# E2 is one row - OpenRA at SSIM >= 0.99 - and trace_cases.json's `split: true` is where that
|
||||
# subset lives.
|
||||
#
|
||||
# IT RUNS THE UNCHANGED CTEST NAMES with the transport exported in the JOB environment, rather
|
||||
# than the SPLIT-suffixed variant entries. build-retrace configures without
|
||||
# -DMOBILEGL_BUILD_DISAGGREGATED, so the variant entries are deliberately not registered there
|
||||
# (a name that says SPLIT in a build that cannot be one is worse than no name), and the
|
||||
# unchanged names are what retrace-verify already proves this shape works with. The variant
|
||||
# entries exist for a build that DOES configure the option - a local build-split with trace
|
||||
# replay on - where `ctest -L retrace-split` is self-describing and needs no environment ritual.
|
||||
#
|
||||
# WHAT MAKES IT FALSIFIABLE is not the SSIM. A monolith run of OpenRA also scores 1.000: measured
|
||||
# on this branch, a pull library under MOBILEGL_TRANSPORT=inproc produced ssim=1.0 and was caught
|
||||
# only by run_trace_case.cmake's transport-resolution assertion. So there are two guards, and the
|
||||
# SSIM is neither of them: the nm check below (this library carries MG_Remote) and the
|
||||
# transport-resolution line in the library's own log (this PROCESS resolved inproc).
|
||||
retrace-split:
|
||||
name: retrace split (${{ matrix.backend }}, ${{ matrix.case }})
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 240
|
||||
needs:
|
||||
- build-linux
|
||||
- build-linux-split
|
||||
- build-retrace
|
||||
- trace-cases
|
||||
- trace-fixtures
|
||||
# build-linux is needed for the negative control ONLY: its pull library is what the control
|
||||
# swaps in to prove the transport-resolution assertion is load-bearing.
|
||||
if: ${{ always() && needs.build-linux.result == 'success' && needs.build-linux-split.result == 'success' && needs.build-retrace.result == 'success' && needs.trace-cases.result == 'success' }}
|
||||
strategy:
|
||||
fail-fast: false
|
||||
max-parallel: 4
|
||||
matrix: ${{ fromJSON(needs.trace-cases.outputs.split-matrix) }}
|
||||
|
||||
steps:
|
||||
- name: Set Swap Space
|
||||
uses: pierotofy/set-swap-space@v1.0
|
||||
with:
|
||||
swap-size-gb: 16
|
||||
|
||||
- name: Checkout repo
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Download trace fixture
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
name: trace-fixture-${{ matrix.case }}
|
||||
path: trace-fixture-download
|
||||
|
||||
- name: Install trace fixture
|
||||
run: |
|
||||
mkdir -p tools/trace_replay/fixtures
|
||||
find trace-fixture-download -type f -exec cp {} tools/trace_replay/fixtures/ \;
|
||||
|
||||
- name: Get CMake
|
||||
uses: lukka/get-cmake@v4.3.3
|
||||
|
||||
- name: Install runtime dependencies
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y libvulkan1 libegl1-mesa-dev libgles2-mesa-dev libgl1-mesa-dri mesa-vulkan-drivers
|
||||
test -e /usr/lib/x86_64-linux-gnu/libEGL.so
|
||||
test -e /usr/lib/x86_64-linux-gnu/libGLESv2.so
|
||||
|
||||
- name: Download Linux split runtime
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
name: mobilegl-linux-runtime-split
|
||||
path: .
|
||||
|
||||
- name: Download trace replay
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
name: mobilegl-trace-replay
|
||||
path: .
|
||||
|
||||
# The PULL runtime, for the negative control at the end of this job and for nothing else.
|
||||
- name: Download Linux pull runtime (negative control)
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
name: mobilegl-linux-runtime
|
||||
path: pull-runtime
|
||||
|
||||
- name: Unpack the pull runtime (negative control)
|
||||
run: |
|
||||
tar -xzf pull-runtime/mobilegl-linux-runtime.tgz -C pull-runtime
|
||||
test -f pull-runtime/build-linux/libMobileGL.so
|
||||
|
||||
- name: Unpack the SPLIT runtime as the library under test
|
||||
# build-retrace's CTestTestfile.cmake has the absolute path
|
||||
# <workspace>/build-linux/libMobileGL.so frozen into every case, so the swap happens here
|
||||
# rather than through a variable, exactly as in retrace-verify. `nm`, not `nm -D`.
|
||||
run: |
|
||||
tar -xzf mobilegl-linux-runtime-split.tgz
|
||||
tar -xzf mobilegl-trace-replay.tgz
|
||||
test -f build-split/libMobileGL.so
|
||||
test -f build-retrace/tools/trace_replay/mobilegl_trace_replay
|
||||
mkdir -p build-linux
|
||||
cp build-split/libMobileGL.so build-linux/libMobileGL.so
|
||||
if ! nm --defined-only build-linux/libMobileGL.so | grep -q -i MG_Remote; then
|
||||
echo "::error::the library unpacked at build-linux/libMobileGL.so defines no MG_Remote symbol, so this retrace would replay against a monolith build, ignore MOBILEGL_TRANSPORT entirely and match its golden having split nothing"
|
||||
exit 1
|
||||
fi
|
||||
echo "the library at build-linux/libMobileGL.so is the split build"
|
||||
|
||||
- name: Retrace and validate under MOBILEGL_TRANSPORT=inproc
|
||||
working-directory: build-retrace/tools/trace_replay
|
||||
# run_trace_case.cmake turns MOBILEGL_TRANSPORT into assertions of its own - the library
|
||||
# must have RESOLVED the transport in this process, and its log must carry no Fatal{ - so a
|
||||
# case that somehow ran the wrong library reds here instead of passing on its golden. That
|
||||
# log is also the only valid refusal census: the console sink is compiled out of this
|
||||
# configuration, so a `ctest -V` transcript reports a false zero for Fatal{ lines.
|
||||
run: |
|
||||
ulimit -c unlimited
|
||||
sudo sysctl -w kernel.core_pattern='/tmp/core.%e.%p'
|
||||
export MOBILEGL_TRANSPORT=inproc
|
||||
ctest -V --no-tests=error --timeout 10800 \
|
||||
-R '^MobileGLTraceReplay\.${{ matrix.case }}\.${{ matrix.backend }}$'
|
||||
|
||||
# THE RETRACE LANE'S OWN ALWAYS-ON NEGATIVE CONTROL, and its absence was review finding M-6:
|
||||
# this job was a clone of retrace-verify with the one step removed that makes the lane mean
|
||||
# anything. retrace-verify carries "a corrupted snapshot field must red this retrace" so that
|
||||
# "79 traces, zero divergences" is not a statement about a comparator nobody watched; the
|
||||
# same sentence applies here word for word.
|
||||
#
|
||||
# The control swaps the PULL library into the frozen path and requires the SAME replay to
|
||||
# fail. It is the sharpest one available, because OpenRA scores ssim 1.000000 either way -
|
||||
# measured - so this step fails if and only if run_trace_case.cmake's transport-resolution
|
||||
# assertion has stopped working, which is the single thing standing between this job and a
|
||||
# green that ran monolith end to end.
|
||||
#
|
||||
# NOT the control BRIEF 7 E2 names ("patch the Clear emitter to drop one emission; SSIM must
|
||||
# fall below threshold"). That one needs an emitter, i.e. package c1, and it is carried as an
|
||||
# explicit debt in t1-v1.md rather than silently substituted - which is what the first
|
||||
# version of this package did.
|
||||
#
|
||||
# The rerun replays into the same case directory, so the good run's images are put aside and
|
||||
# restored whichever way the control goes; "Upload actual image" below runs `if: always()`
|
||||
# and would otherwise ship the deliberately-wrong run's output under the good run's name.
|
||||
# THE BODY OF THIS STEP IS scripts/ci/retrace_pull_library_control.sh, for the reason the
|
||||
# split lane's control gives: a `run:` block cannot be executed off a runner, so these lines
|
||||
# could not be tested until they ran in CI. scripts/ci/control_smoke_test.sh drives that file.
|
||||
#
|
||||
# Two holes ID-46 finding 8(b) found in this block, both CONFIRMED against the REAL ctest in a
|
||||
# REAL build tree, both closed in the script: it had NO selection guard at all - unlike the
|
||||
# split lane's run_control - so a case/backend regex matching nothing exited 8 through
|
||||
# `--no-tests=error` and was read as "the pull library turned it red"; and only "non-zero
|
||||
# ctest" was checked after the nm identity check, so a loader failure, a missing fixture or a
|
||||
# timeout passed it. The red must now carry run_trace_case.cmake's own sentence.
|
||||
- name: Negative control - the PULL library must red this split retrace
|
||||
working-directory: build-retrace/tools/trace_replay
|
||||
env:
|
||||
CONTROL_TMPDIR: ${{ runner.temp }}
|
||||
PULL_LIBRARY: ${{ github.workspace }}/pull-runtime/build-linux/libMobileGL.so
|
||||
FROZEN_LIBRARY: ${{ github.workspace }}/build-linux/libMobileGL.so
|
||||
run: >-
|
||||
bash "${GITHUB_WORKSPACE}/scripts/ci/retrace_pull_library_control.sh"
|
||||
'${{ matrix.case }}' '${{ matrix.backend }}'
|
||||
|
||||
# The refusal census, recorded rather than gated. run_trace_case.cmake already REDS the case
|
||||
# on any Fatal{, so reaching here means the count is zero - but the number and the distinct
|
||||
# slot names are what MEASUREMENTS wants from every split run, and reading them out of the
|
||||
# library's own log is the only way to get them (ctest -V's transcript is a false zero).
|
||||
- name: Refusal census from the library log
|
||||
if: always()
|
||||
working-directory: build-retrace/tools/trace_replay
|
||||
run: |
|
||||
log="${{ matrix.case }}/${{ matrix.backend }}/output/mobilegl.log"
|
||||
if [ ! -f "${log}" ]; then
|
||||
echo "no ${log} - the replay wrote no library log"
|
||||
exit 0
|
||||
fi
|
||||
echo "Fatal{ lines: $(grep -c 'Fatal{' "${log}" || true)"
|
||||
grep -o 'Fatal{[A-Za-z]*, "[^"]*"' "${log}" | sort | uniq -c | sort -rn | head -20 || true
|
||||
grep -m1 "MOBILEGL_TRANSPORT=" "${log}" || echo "no transport line in ${log}"
|
||||
|
||||
- name: Upload core dumps
|
||||
if: failure()
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: retrace-split-core-dumps-${{ matrix.backend }}-${{ matrix.case }}
|
||||
path: /tmp/core.*
|
||||
if-no-files-found: ignore
|
||||
|
||||
- name: Upload actual image
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: retrace-split-result-${{ matrix.backend }}-${{ matrix.case }}
|
||||
path: |
|
||||
build-retrace/tools/trace_replay/${{ matrix.case }}/actual-images/**
|
||||
build-retrace/tools/trace_replay/${{ matrix.case }}/${{ matrix.backend }}/output/**
|
||||
if-no-files-found: warn
|
||||
|
||||
# G1's own job: the pull build must be the tree before P1, symbol for symbol and byte for byte.
|
||||
# workflow_dispatch only - it builds the library twice from scratch, and its answer is about a
|
||||
# BASELINE rather than about this push, so a per-push run would be measuring the wrong pair.
|
||||
@@ -1664,6 +2258,42 @@ jobs:
|
||||
python3 scripts/gen_pipe_dirty_surface.py --check
|
||||
python3 scripts/gen_pipe_dirty_surface.py --self-test
|
||||
|
||||
# A GATE as of P5 (R-7.1, CONTRACT-P5.md table 2). The eighth generator, and the only one
|
||||
# whose output the step above cannot cover: `gen_pipe.py` does not write
|
||||
# PipeFieldOwnership.inc, so regenerating the seven and diffing MG_Pipe/generated leaves a
|
||||
# drifted ownership table green. The build-level static_assert only catches an
|
||||
# UNCLASSIFIED row; a hand edit that CHANGES a class compiles clean, and --check is the
|
||||
# only thing in the tree that catches it.
|
||||
#
|
||||
# NO BRANCH GUARD, deliberately, unlike the two G5 steps below: this asks "does the
|
||||
# committed table still follow from the .def files", which is a question every branch can
|
||||
# answer and every branch wants answered. The table outlives feat/disaggregated.
|
||||
#
|
||||
# --self-test is not optional, for the reason the two gates above give and for one this
|
||||
# generator learned the hard way: its first version counted eleven trips when one control
|
||||
# was a silent duplicate of another, because the harness asked "did something exit" rather
|
||||
# than "did THIS exit". Every control now asserts its own message, and a harness control
|
||||
# asserts that the harness still rejects someone else's exit.
|
||||
- name: MGPipe PipeInputs field-ownership table is complete (R-7.1, table 2)
|
||||
run: |
|
||||
python3 scripts/gen_pipe_field_ownership.py --check
|
||||
python3 scripts/gen_pipe_field_ownership.py --self-test
|
||||
|
||||
# R-16 APPLIED TO THE NEGATIVE CONTROLS THEMSELVES. The split lane's E1/E3(a) controls and the
|
||||
# retrace lane's pull-library control are gates, and until ID-46 finding 8 neither could be
|
||||
# made red by anyone: their bodies were `run:` blocks, which execute only on a runner. Both
|
||||
# bodies now live in scripts/ci/, and this step runs them against a stubbed ctest that
|
||||
# reproduces the finding - a NON-EMPTY selection failing with UNRELATED_CONTROL_FAILURE, and a
|
||||
# case/backend regex matching no tests - and requires each control to report FAILED. The same
|
||||
# stub, failing with the diagnostics the scenarios really emit, must make them report PASSED.
|
||||
#
|
||||
# NO BRANCH GUARD: this asks "do the negative controls still reject a red that is not theirs",
|
||||
# which is a question every branch can answer and none of which depends on the TEMPORARY
|
||||
# feat/disaggregated trigger at the top of this file. It costs a couple of seconds and needs
|
||||
# no build.
|
||||
- name: The split and retrace negative controls still reject a red that is not theirs (R-16)
|
||||
run: bash scripts/ci/control_smoke_test.sh
|
||||
|
||||
# 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
|
||||
@@ -1675,8 +2305,9 @@ jobs:
|
||||
# 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 3e298c9a, because that
|
||||
# one was born in P3a and has no body at the base ref to compare with.
|
||||
# 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,
|
||||
@@ -1686,9 +2317,10 @@ jobs:
|
||||
#
|
||||
# --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 six canned controls - eleven bodies extracted, an untouched copy compared equal, an
|
||||
# edit OUTSIDE them ignored, and each of the three perturbation targets (ClearBufferPool
|
||||
# and BOTH flush ladders) reported BY NAME - and fails if any of them does not answer.
|
||||
# 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: The buffer pool, the deferred-release drain and the rings did not move (G5)
|
||||
if: ${{ github.ref == 'refs/heads/feat/disaggregated' || github.event_name == 'workflow_dispatch' }}
|
||||
@@ -1719,10 +2351,11 @@ jobs:
|
||||
# --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 FOUR negative ones - ClearBufferPool,
|
||||
# edit OUTSIDE them invisible in all three files) and NINE negative ones - ClearBufferPool,
|
||||
# FlushPendingRangesNow, RecomputeBackendColorSlots and StageBlocksIntoUnpackRing, each
|
||||
# perturbed on its own and each required to be named BY NAME - and fails if any of them does
|
||||
# not answer.
|
||||
# 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: The unpack ring, the attachment permutation, the D24S8 core and the format caveat did not move (G5)
|
||||
if: ${{ github.ref == 'refs/heads/feat/disaggregated' || github.event_name == 'workflow_dispatch' }}
|
||||
run: bash scripts/p4a_untouched_regions.sh "${BASELINE}" HEAD
|
||||
|
||||
@@ -533,6 +533,13 @@ if (MOBILEGL_PIPE_PUSH)
|
||||
# by pointer beside the record), so the codec is live code only in the VERIFY lane,
|
||||
# where the applier serialises, deserialises and field-compares before storing.
|
||||
MobileGL/MG_State/GLState/ProgramState/ProgramArtifactsCodec.cpp
|
||||
# P5's contract (integrator ruling R-17, package c1): the MONOLITH arm of the
|
||||
# client->wire routing - the thirty-seven adapters that install gMGPipeScreen /
|
||||
# gMGPipeContext over the MGPipeApply* entry points, and the reply mailbox the four
|
||||
# acceptance rows answer through. Push-only for the same G1 reason as the five above:
|
||||
# the two tables are inline variables that are zero in a pull build and nothing there
|
||||
# can reach a thunk.
|
||||
MobileGL/MG_Pipe/PipeRoute.cpp
|
||||
)
|
||||
endif()
|
||||
|
||||
@@ -571,6 +578,20 @@ if (MOBILEGL_BUILD_DISAGGREGATED)
|
||||
MobileGL/MG_Remote/Client/ClientSession.cpp
|
||||
MobileGL/MG_Remote/Client/EmitTables.cpp
|
||||
MobileGL/MG_Remote/Client/CapsMirror.cpp
|
||||
# P5 c1: the client role's BackendObject. pActiveBackendObject holds one of these
|
||||
# under split (table 3); the hook that installs it is v1's, in MG_Backend/Init.cpp.
|
||||
MobileGL/MG_Remote/Client/BackendObject_Remote.cpp
|
||||
# P5 c1, ruling R-17: the ENCODE TWIN of gMGPipeWireRecordApply - the thirty-seven
|
||||
# emitters installed over the two generated tables, which is what stops every
|
||||
# resource/CSO/texture/program record executing synchronously on the GL thread under
|
||||
# inproc. The monolith arm of the same routing is MG_Pipe/PipeRoute.cpp, in the
|
||||
# PIPE_PUSH list above, because it must exist in a push build that has no MG_Remote.
|
||||
MobileGL/MG_Remote/Client/WireTables.cpp
|
||||
# P5 b1's two: the conservative GPU-write set the client must build because all six
|
||||
# MarkGpuWritten producers are on the server's side of the line, and the
|
||||
# block-granularity persistent-map push that tier T2 makes mandatory.
|
||||
MobileGL/MG_Remote/Client/GpuWritePending.cpp
|
||||
MobileGL/MG_Remote/Client/PersistentMapTracker.cpp
|
||||
MobileGL/MG_Remote/Server/ServerSession.cpp
|
||||
MobileGL/MG_Remote/Server/PipeApplier.cpp
|
||||
MobileGL/MG_Remote/Server/ServerLoop.cpp
|
||||
|
||||
@@ -43,6 +43,15 @@ namespace MobileGL {
|
||||
if (logLifecycle) {
|
||||
MGLOG_I("MobileGL closing...");
|
||||
}
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
// P5: the split roles come down FIRST - ARCHITECTURE.md:537's order puts the whole
|
||||
// of it before MobileGL::Destroy(), and this function IS MobileGL::Destroy. A no-op
|
||||
// in a monolith RUN; absent from a monolith BUILD, because G1 admits no new pull
|
||||
// symbol and no resized one (the first version called it unconditionally and moved
|
||||
// DestroyImpl by 32 bytes). See BackendObjects.h for why the position rather than
|
||||
// the call is the load-bearing part.
|
||||
MG_Backend::ShutdownSplitRoles();
|
||||
#endif
|
||||
// Before any subsystem the counters name goes away, and before the last frame's
|
||||
// numbers can be lost: emits the final summary line and, when
|
||||
// MOBILEGL_PIPE_STATS_FILE is set, the JSON dump. A no-op when the counters are
|
||||
|
||||
@@ -15,4 +15,29 @@
|
||||
namespace MobileGL::MG_Backend {
|
||||
extern UniquePtr<BackendObject>& pActiveBackendObject;
|
||||
extern GlobalBackendFunctionsTable gBackendFunctionsTable;
|
||||
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
// P5 v1. The counterpart of Init()'s single split hook, and a NO-OP in every run that is
|
||||
// not split. It exists ONLY in a split build: G1 admits no new symbol in the pull build,
|
||||
// so MobileGL/Init.cpp's call sits under the same #if rather than calling a no-op.
|
||||
//
|
||||
// IT MUST RUN FIRST, BEFORE ANYTHING ELSE IN DestroyImpl. ARCHITECTURE.md:537's order is
|
||||
// publish -> the server drains and acks -> stop the apply thread (Kill, then join) -> close
|
||||
// the transport -> the client drains the compile pool -> MobileGL::Destroy() -> release the
|
||||
// sync/query handles; DestroyImpl IS MobileGL::Destroy, so everything before that arrow has
|
||||
// to happen at its top. Two consequences are load-bearing rather than tidy:
|
||||
//
|
||||
// * the apply thread is JOINED before PipeStats::Shutdown() dumps, so nothing is writing
|
||||
// a counter while the final line is produced;
|
||||
// * the apply thread is joined before pActiveBackendObject.reset(), so the server's own
|
||||
// BackendObject - which is NOT that global (table 3) - is destroyed on the thread that
|
||||
// owns the context, by ServerLoop::Stop, rather than on the app thread.
|
||||
//
|
||||
// The sync/query registries stay where they are, drained at MobileGL/Init.cpp:62 and :67
|
||||
// BEFORE pActiveBackendObject.reset(). ARCHITECTURE.md:537 puts them after
|
||||
// MobileGL::Destroy(); the two are only reconcilable if a split sync handle is
|
||||
// client-minted and needs no backend call, which is P10's. CONTRACT-P5 4 flags this as a
|
||||
// KNOWN OPEN ITEM and asks v1 to record which way it went: P5 keeps today's order.
|
||||
void ShutdownSplitRoles();
|
||||
#endif
|
||||
} // namespace MobileGL::MG_Backend
|
||||
|
||||
@@ -32,6 +32,54 @@ namespace MobileGL::MG_Backend::DirectGLES {
|
||||
return draw == EGL_NO_SURFACE && read == EGL_NO_SURFACE && ctx == EGL_NO_CONTEXT;
|
||||
}
|
||||
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
// ID-54 / ID-67 (v1, under ID-52/ID-59's grant for this file). Which VIRTUAL (dpy, draw,
|
||||
// read, ctx) the process's one native ES context is currently bound FOR, on the apply
|
||||
// thread. DirectGLES has one native context and one native surface (g_Context, g_Surface)
|
||||
// whatever virtual handles the client uses, so "is a native eglMakeCurrent needed" is never
|
||||
// "is the native triple different" - it is "did the VIRTUAL context change":
|
||||
// DirectGLES::MakeCurrent is also where the seven caches that describe the frontend context
|
||||
// are invalidated, and a different virtual context needs them invalidated even though the
|
||||
// driver binds the same triple. ID-67: a make-current with a DIFFERENT tuple is a real
|
||||
// native bind (and a caps republish, ServerLoop's half); an IDENTICAL one is neither.
|
||||
//
|
||||
// Three states. NotBound: the next bind is native. FreshFromSurfaceCreation: the surface's
|
||||
// own creation (InitPbufferSurface / InitWindowSurface) bound natively and invalidated, and
|
||||
// no virtual tuple has claimed that bind yet - the first tuple adopts it, which is the
|
||||
// "2 -> 1 native binds per process" of round 3. BoundForTuple: bound and invalidated for
|
||||
// the recorded tuple; only that exact tuple may skip. Process-wide like the native state it
|
||||
// mirrors; under split exactly one DirectGLES object exists (the server's), and only the
|
||||
// apply thread reaches these.
|
||||
enum class NativeBindState : Uint8 { NotBound, FreshFromSurfaceCreation, BoundForTuple };
|
||||
NativeBindState g_nativeBindState = NativeBindState::NotBound;
|
||||
EGLDisplay g_nativeBoundDpy = EGL_NO_DISPLAY;
|
||||
EGLSurface g_nativeBoundDraw = EGL_NO_SURFACE;
|
||||
EGLSurface g_nativeBoundRead = EGL_NO_SURFACE;
|
||||
EGLContext g_nativeBoundCtx = EGL_NO_CONTEXT;
|
||||
|
||||
void NoteNativeContextGone() { g_nativeBindState = NativeBindState::NotBound; }
|
||||
void NoteNativeContextFreshFromSurfaceCreation() {
|
||||
g_nativeBindState = NativeBindState::FreshFromSurfaceCreation;
|
||||
}
|
||||
void NoteNativeBoundFor(EGLDisplay dpy, EGLSurface draw, EGLSurface read, EGLContext ctx) {
|
||||
g_nativeBindState = NativeBindState::BoundForTuple;
|
||||
g_nativeBoundDpy = dpy;
|
||||
g_nativeBoundDraw = draw;
|
||||
g_nativeBoundRead = read;
|
||||
g_nativeBoundCtx = ctx;
|
||||
}
|
||||
Bool NativeBindCanBeSkippedFor(EGLDisplay dpy, EGLSurface draw, EGLSurface read, EGLContext ctx) {
|
||||
switch (g_nativeBindState) {
|
||||
case NativeBindState::NotBound: return false;
|
||||
case NativeBindState::FreshFromSurfaceCreation: return true;
|
||||
case NativeBindState::BoundForTuple:
|
||||
return g_nativeBoundDpy == dpy && g_nativeBoundDraw == draw && g_nativeBoundRead == read &&
|
||||
g_nativeBoundCtx == ctx;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
#endif
|
||||
|
||||
void ClearGLErrors(const MG_External::GLESFunctionsTable& gl) {
|
||||
if (!gl.glGetError) return;
|
||||
while (gl.glGetError() != GL_NO_ERROR) {}
|
||||
@@ -812,6 +860,19 @@ namespace MobileGL::MG_Backend::DirectGLES {
|
||||
|
||||
Int maxSamples = 0;
|
||||
const SizeT formatIndex = static_cast<SizeT>(logicalFormat);
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
// C6 / ID-52: read the ROLE's own cache. Under split that is the server's private backend
|
||||
// (ActiveBackendFormatCaps), not pActiveBackendObject, which holds the client's mirror.
|
||||
const FormatCapabilityCache* activeCaps = ActiveBackendFormatCaps();
|
||||
if (activeCaps != nullptr && targetIndex < kFormatCapabilityTargetCount &&
|
||||
formatIndex < kFormatCapabilityFormatCount) {
|
||||
// Descending, so the head is the largest count this device actually allocated.
|
||||
const Vector<Int>& probedCounts = activeCaps->SampleCounts[targetIndex][formatIndex];
|
||||
if (!probedCounts.empty()) {
|
||||
maxSamples = probedCounts.front();
|
||||
}
|
||||
}
|
||||
#else
|
||||
if (pActiveBackendObject && targetIndex < kFormatCapabilityTargetCount &&
|
||||
formatIndex < kFormatCapabilityFormatCount) {
|
||||
// Descending, so the head is the largest count this device actually allocated.
|
||||
@@ -821,6 +882,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
|
||||
maxSamples = probedCounts.front();
|
||||
}
|
||||
}
|
||||
#endif
|
||||
if (maxSamples <= 0) {
|
||||
maxSamples = GetGLESFormatMaxSamples(g_GLESCapabilities, logicalFormat, imageFormat);
|
||||
}
|
||||
@@ -829,6 +891,9 @@ namespace MobileGL::MG_Backend::DirectGLES {
|
||||
|
||||
BackendObject_DirectGLES::~BackendObject_DirectGLES() {
|
||||
DestroyEGLContext();
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
NoteNativeContextGone();
|
||||
#endif
|
||||
}
|
||||
|
||||
Bool BackendObject_DirectGLES::InitWindowSurface() {
|
||||
@@ -906,7 +971,20 @@ namespace MobileGL::MG_Backend::DirectGLES {
|
||||
ResetEGLRuntimeState();
|
||||
}
|
||||
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
// ID-54 / ID-67: the surface's creation bound natively (InitWindowSurface -> MakeCurrent);
|
||||
// the first virtual tuple adopts that bind. On failure nothing is known to be bound. The
|
||||
// pull arm below is the original statement, byte for byte (G1).
|
||||
const Bool created = BackendObject::CreateEGLWindowSurface(surface, handle);
|
||||
if (created) {
|
||||
NoteNativeContextFreshFromSurfaceCreation();
|
||||
} else {
|
||||
NoteNativeContextGone();
|
||||
}
|
||||
return created;
|
||||
#else
|
||||
return BackendObject::CreateEGLWindowSurface(surface, handle);
|
||||
#endif
|
||||
}
|
||||
|
||||
Bool BackendObject_DirectGLES::CreateEGLPbufferSurface(EGLSurface surface, EGLint width, EGLint height) {
|
||||
@@ -925,7 +1003,19 @@ namespace MobileGL::MG_Backend::DirectGLES {
|
||||
ResetEGLRuntimeState();
|
||||
}
|
||||
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
// ID-54 / ID-67: as for the window surface - InitPbufferSurface bound natively. The pull
|
||||
// arm below is the original statement, byte for byte (G1).
|
||||
const Bool created = BackendObject::CreateEGLPbufferSurface(surface, width, height);
|
||||
if (created) {
|
||||
NoteNativeContextFreshFromSurfaceCreation();
|
||||
} else {
|
||||
NoteNativeContextGone();
|
||||
}
|
||||
return created;
|
||||
#else
|
||||
return BackendObject::CreateEGLPbufferSurface(surface, width, height);
|
||||
#endif
|
||||
}
|
||||
|
||||
Bool BackendObject_DirectGLES::InitPbufferSurface(EGLint width, EGLint height) {
|
||||
@@ -938,6 +1028,9 @@ namespace MobileGL::MG_Backend::DirectGLES {
|
||||
if (!DirectGLES::ReleaseCurrent()) {
|
||||
return false;
|
||||
}
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
NoteNativeContextGone();
|
||||
#endif
|
||||
return BackendObject::MakeEGLCurrent(dpy, draw, read, ctx);
|
||||
}
|
||||
|
||||
@@ -958,12 +1051,50 @@ namespace MobileGL::MG_Backend::DirectGLES {
|
||||
return false;
|
||||
}
|
||||
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
// ID-54 / C7, the native half of "bind once per tuple" (v1, under ID-52/ID-59's grant for
|
||||
// this file; #if-guarded so the pull build is byte-identical). Under an active transport
|
||||
// this runs on the apply thread, which is the ONLY thread that ever binds the server's
|
||||
// context, and the surface it is asked for was made natively current on this very thread
|
||||
// by its own creation (InitPbufferSurface / InitWindowSurface -> DirectGLES::MakeCurrent).
|
||||
// A second native eglMakeCurrent for the same surface is then a repeat: it rewrites the
|
||||
// owner with the same thread, re-registers the same op table and invalidates seven caches
|
||||
// that describe a context that did not change - the per-client-make-current storm the
|
||||
// v2 review measured as "2 native binds per process, unchanged". So when the requested
|
||||
// draw surface IS the active one and EGL itself says this thread holds the context
|
||||
// (IsBackendContextCurrentOnThisThread re-verifies against eglGetCurrentContext), the
|
||||
// native call is skipped and only the base class's bookkeeping below runs - which is
|
||||
// still required: it is what InitCapabilities and SwapEGLBuffers' current-thread record
|
||||
// hang off. Monolith transport in this build, and the pull build, bind exactly as before.
|
||||
//
|
||||
// AND ONLY FOR THE SAME VIRTUAL TUPLE (ID-67). The skip is keyed on NativeBindCanBeSkippedFor:
|
||||
// the surface's own creation bind is adopted by the FIRST tuple, an identical tuple skips,
|
||||
// and a DIFFERENT tuple - a second MobileGL context onto the same surface - runs the native
|
||||
// call again even though the driver's triple is the same, because MakeCurrent's seven
|
||||
// invalidations describe the frontend context that is changing. Red once, two ways:
|
||||
// make this arm unconditional (ServerLoopTest's C7 control reads 2 native binds at the EGL
|
||||
// function table instead of 1), or make NativeBindCanBeSkippedFor answer true for any tuple
|
||||
// (the ID-67 control's different tuple stays at 1 native bind where 2 are required).
|
||||
const Bool nativelyCurrentAlready = MG_Config::Transport != MG_Config::TransportMode::Monolith &&
|
||||
m_eglSurfaceInitialized && m_eglSurface == draw &&
|
||||
DirectGLES::IsBackendContextCurrentOnThisThread() &&
|
||||
NativeBindCanBeSkippedFor(dpy, draw, read, ctx);
|
||||
if (!nativelyCurrentAlready && !DirectGLES::MakeCurrent()) {
|
||||
NoteNativeContextGone();
|
||||
return false;
|
||||
}
|
||||
NoteNativeBoundFor(dpy, draw, read, ctx);
|
||||
#else
|
||||
if (!DirectGLES::MakeCurrent()) {
|
||||
return false;
|
||||
}
|
||||
#endif
|
||||
|
||||
if (!BackendObject::MakeEGLCurrent(dpy, draw, read, ctx)) {
|
||||
(void)DirectGLES::ReleaseCurrent();
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
NoteNativeContextGone();
|
||||
#endif
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
@@ -981,12 +1112,18 @@ namespace MobileGL::MG_Backend::DirectGLES {
|
||||
void BackendObject_DirectGLES::ReleaseEGLResources() {
|
||||
const std::lock_guard<std::recursive_mutex> lock(m_eglStateMutex);
|
||||
DestroyEGLContext();
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
NoteNativeContextGone();
|
||||
#endif
|
||||
BackendObject::ReleaseEGLResources();
|
||||
}
|
||||
|
||||
void BackendObject_DirectGLES::OnEGLSurfaceReleased(EGLSurface surface) {
|
||||
(void)surface;
|
||||
DestroyEGLContext();
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
NoteNativeContextGone();
|
||||
#endif
|
||||
}
|
||||
|
||||
const RendererInfo& BackendObject_DirectGLES::GetRendererInfo() const {
|
||||
|
||||
@@ -16,6 +16,12 @@
|
||||
#include <MG_Pipe/MGPipeHostSpan.h>
|
||||
#include <MG_Pipe/PipeApply.h>
|
||||
#endif
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
// R-11's server-owned staging copy. Header-only and package v1's; see its own header block for
|
||||
// why GLESBufferResource does not simply gain a member.
|
||||
#include <MG_Remote/Server/StagedShadow.h>
|
||||
#endif
|
||||
|
||||
#include "Utils.h"
|
||||
#include "DirectGLES.h"
|
||||
#include "BackendObject_DirectGLES.h"
|
||||
@@ -1008,6 +1014,77 @@ namespace MobileGL::MG_Backend::DirectGLES {
|
||||
return StorageMatchesSize(resource, bufferObject.GetSize());
|
||||
}
|
||||
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
// -------------------------------------------------------------------------------
|
||||
// R-11 - THE SERVER'S OWN COPY OF THE STAGED BYTES. Package v1.
|
||||
//
|
||||
// The rule, the evidence and the reason the storage is a side table rather than a
|
||||
// member of GLESBufferResource are all in MG_Remote/Server/StagedShadow.h. This is
|
||||
// only the instance and the four call sites.
|
||||
//
|
||||
// ONE PER PROCESS, and its copying arm is decided ONCE at first use: the two arms
|
||||
// hold the authoritative bytes in DIFFERENT places, so an answer that changed
|
||||
// mid-run would strand every resource already staged - the same reason
|
||||
// ResolveResourceSubsystemArm latches (Managers.h). Leaked at exit like every other
|
||||
// MG_Remote singleton (ID-8): ~BufferObject reaches the destroy path from exit
|
||||
// handlers, after this TU's globals would already be gone.
|
||||
// -------------------------------------------------------------------------------
|
||||
MG_Remote::Server::StagedShadowStore& ServerStaged() {
|
||||
static MG_Remote::Server::StagedShadowStore& store =
|
||||
*new MG_Remote::Server::StagedShadowStore(
|
||||
MG_Config::Transport != MG_Config::TransportMode::Monolith);
|
||||
return store;
|
||||
}
|
||||
|
||||
// THE COVERAGE RULE FOR THE THREE-TIER FLUSH DRAIN, ASSERTED BEFORE THE CALL AND NOT
|
||||
// INSIDE IT. FlushPendingRangesFrom is a G5-pinned body (p3a_untouched_regions.sh's
|
||||
// PINNED_FUNCTIONS, ID-41): the split arm CALLS it, it does not re-spell it, and it
|
||||
// does not add a line to it either. Its tier-1 arm - the range-invalidating map -
|
||||
// copies with its own Memcpy and never reaches UploadRangeFrom, so the one tier that
|
||||
// DECLARES THE OLD BYTES DEAD is the one tier no later check can see; the only place
|
||||
// left to say "every queued range is inside the staged coverage" is the instant before
|
||||
// the drain takes the queue. The clamp is the drain's own (limit = the smaller of the
|
||||
// frontend size and the backend store; bytes past either end have nowhere to land and
|
||||
// are not this rule's subject), so the two agree about which bytes are meant.
|
||||
//
|
||||
// Fires only for a base that IS this resource's server shadow: RequireCoverage
|
||||
// answers nothing for the legacy arm's MappedData(), which is valid for the whole
|
||||
// store. `pendingMutex` is taken here and released before the drain takes it again.
|
||||
void RequireStagedCoverageForPendingRanges(GLESBufferResource& resource, const Uint8* hostBase,
|
||||
SizeT frontendSize, const char* site) {
|
||||
if (hostBase == nullptr) return;
|
||||
const SizeT limit = std::min(frontendSize, resource.storageSize);
|
||||
const std::lock_guard<std::mutex> lock(resource.pendingMutex);
|
||||
for (const auto& range : resource.pendingRanges) {
|
||||
const SizeT end = std::min(range.end, limit);
|
||||
const SizeT start = std::min(range.start, end);
|
||||
if (start == end) continue;
|
||||
ServerStaged().RequireCoverage(&resource, hostBase, start, end, site);
|
||||
}
|
||||
}
|
||||
#endif // MOBILEGL_BUILD_DISAGGREGATED
|
||||
|
||||
// The four hostBytes sites read the same in both builds. The non-split expansion is the
|
||||
// ORIGINAL EXPRESSION, character for character - `raw - offset` - so a push or verify build
|
||||
// compiles exactly what it compiled before R-11 and the split arm is the only new behaviour.
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
#define MGL_SERVER_STAGED_ADOPT(res, width, bytes, offset, size) \
|
||||
ServerStaged().Adopt(&(res), (width), (bytes), (offset), (size))
|
||||
#define MGL_SERVER_STAGED_DROP(res) ServerStaged().Drop(&(res))
|
||||
#define MGL_SERVER_STAGED_DROP_ALL() ServerStaged().DropAll()
|
||||
#define MGL_SERVER_STAGED_REQUIRE(res, base, start, end, site) \
|
||||
ServerStaged().RequireCoverage(&(res), (base), (start), (end), (site))
|
||||
#define MGL_SERVER_STAGED_REQUIRE_PENDING(res, base, frontendSize, site) \
|
||||
RequireStagedCoverageForPendingRanges((res), (base), (frontendSize), (site))
|
||||
#else
|
||||
#define MGL_SERVER_STAGED_ADOPT(res, width, bytes, offset, size) \
|
||||
(static_cast<const Uint8*>(bytes) - (offset))
|
||||
#define MGL_SERVER_STAGED_DROP(res) ((void)0)
|
||||
#define MGL_SERVER_STAGED_DROP_ALL() ((void)0)
|
||||
#define MGL_SERVER_STAGED_REQUIRE(res, base, start, end, site) ((void)0)
|
||||
#define MGL_SERVER_STAGED_REQUIRE_PENDING(res, base, frontendSize, site) ((void)0)
|
||||
#endif
|
||||
|
||||
// The host bytes a range upload/flush reads. On the legacy arm the frontend object's
|
||||
// shadow; on the handle arm the base the last content-carrying call handed over.
|
||||
void UploadRangeFrom(GLESBufferResource& resource, const Uint8* hostBase, SizeT start, SizeT end) {
|
||||
@@ -1015,6 +1092,9 @@ namespace MobileGL::MG_Backend::DirectGLES {
|
||||
ZoneScopedC(TRACY_ZONECOLOR_BACKEND);
|
||||
#endif
|
||||
if (start >= end || hostBase == nullptr) return;
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
MGL_SERVER_STAGED_REQUIRE(resource, hostBase, start, end, "upload_range");
|
||||
#endif
|
||||
BindBufferId(TempBufferTarget, resource.id);
|
||||
g_GLESFuncs.glBufferSubData(TempBufferTarget, (GLintptr)start, (GLsizeiptr)(end - start),
|
||||
hostBase + start);
|
||||
@@ -1043,6 +1123,14 @@ namespace MobileGL::MG_Backend::DirectGLES {
|
||||
// sizeable (page-coverable) range to engage, and below it the driver
|
||||
// falls back to waiting out the WAR hazard on the CPU.
|
||||
constexpr SizeT kInvalidateRangeMinBytes = 128u * 1024u;
|
||||
#if MOBILEGL_PIPE_PUSH
|
||||
// The push arm's copy of this threshold lives in Managers.h, where a unit case can
|
||||
// reach it (InvalidateFlushAccessFor). Two constants, one value, and the compiler
|
||||
// is what keeps them one: the pull arm's FlushPendingRangesNow is byte-frozen
|
||||
// against 5cb826b0 (ID-15), so the constant it reads may not move to a header.
|
||||
static_assert(kInvalidateRangeMinBytes == kEsprytInvalidateRangeMinBytes,
|
||||
"the two arms of the three-tier ladder must use the same tier-1 threshold");
|
||||
#endif
|
||||
|
||||
// Push every queued range of `resource` from the shadow into the backend
|
||||
// store, without ever letting a driver resolve the WAR hazard against
|
||||
@@ -1078,7 +1166,21 @@ namespace MobileGL::MG_Backend::DirectGLES {
|
||||
// 26.3 p99 depends on, and a second copy of it for the handle arm is exactly how a
|
||||
// tier silently changes. The arms differ only in where `hostBase` and `frontendSize`
|
||||
// come from.
|
||||
void FlushPendingRangesFrom(GLESBufferResource& resource, const Uint8* hostBase, SizeT frontendSize) {
|
||||
//
|
||||
// R-11'S PARAMETER, AND IT IS A PARAMETER RATHER THAN AN ASSUMPTION (P5 b1).
|
||||
// `hostBase` is re-read at every use today precisely because a shadow resize or an
|
||||
// adoption moves what an earlier base pointed at. Under split the server may hold
|
||||
// no pointer into the client's shadow at all, so the base becomes a SNAPSHOT taken
|
||||
// into SEG_STAGE at emission - and a snapshot covers a RANGE, not the store. The
|
||||
// two extra arguments say which range `hostBase` is good for; the default is the
|
||||
// whole store, which is exactly what a live shadow is, so every caller today is
|
||||
// byte-identical. The moment w1 passes a real snapshot extent, tier 1's widening
|
||||
// refusal below stops being unreachable and a too-narrow snapshot is named instead
|
||||
// of silently clobbering GPU-written bytes with stale ones.
|
||||
constexpr SizeT kHostBaseCoversWholeStore = ~static_cast<SizeT>(0);
|
||||
void FlushPendingRangesFrom(GLESBufferResource& resource, const Uint8* hostBase, SizeT frontendSize,
|
||||
SizeT hostBaseFrom = 0,
|
||||
SizeT hostBaseTo = kHostBaseCoversWholeStore) {
|
||||
#ifdef TRACY_ENABLE
|
||||
ZoneScopedC(TRACY_ZONECOLOR_BACKEND);
|
||||
#endif
|
||||
@@ -1126,12 +1228,28 @@ namespace MobileGL::MG_Backend::DirectGLES {
|
||||
// shadow's to rewrite. Widening to page bounds looked free and was
|
||||
// not - the widened bytes clobbered GPU-written data (an SSBO
|
||||
// counter beside the app's SubData) with the stale shadow.
|
||||
const Bool wholeBuffer = start == 0 && end == limit && limit == resource.storageSize;
|
||||
if (mapUsable && (wholeBuffer || size >= kInvalidateRangeMinBytes)) {
|
||||
// The extent the bytes behind `hostBase` are actually good for, clamped
|
||||
// to the store. With the default it IS [start, end), so the refusal below
|
||||
// cannot fire and the ladder is unchanged; with a real SEG_STAGE snapshot
|
||||
// it is the snapshot's window and a disagreement drops this range to the
|
||||
// staging ring instead of letting a widened INVALIDATE_RANGE declare bytes
|
||||
// dead that nothing is about to rewrite.
|
||||
const SizeT coveredFrom = hostBaseFrom > start ? hostBaseFrom : start;
|
||||
const SizeT coveredTo = hostBaseTo < end ? hostBaseTo : end;
|
||||
#if MOBILEGL_PIPE_VERIFY
|
||||
if (coveredFrom != start || coveredTo != end) {
|
||||
MGLOG_E_ONCE("MGPipe: Fatal{StageSnapshotTooNarrow} flush_pending_ranges: the "
|
||||
"staged bytes cover [%zu, %zu) and the queued range is [%zu, %zu) "
|
||||
"- tiers 2 and 3 would copy from outside the snapshot",
|
||||
hostBaseFrom, hostBaseTo, start, end);
|
||||
}
|
||||
#endif
|
||||
const GLbitfield access =
|
||||
mapUsable ? InvalidateFlushAccessFor(start, end, coveredFrom, coveredTo, limit,
|
||||
resource.storageSize)
|
||||
: 0u;
|
||||
if (access != 0) {
|
||||
BindBufferId(TempBufferTarget, resource.id);
|
||||
const GLbitfield access =
|
||||
GL_MAP_WRITE_BIT |
|
||||
(wholeBuffer ? GL_MAP_INVALIDATE_BUFFER_BIT : GL_MAP_INVALIDATE_RANGE_BIT);
|
||||
void* dst = g_GLESFuncs.glMapBufferRange(TempBufferTarget, (GLintptr)start,
|
||||
(GLsizeiptr)size, access);
|
||||
if (dst) {
|
||||
@@ -1885,6 +2003,23 @@ namespace MobileGL::MG_Backend::DirectGLES {
|
||||
const auto* record = ResourceRecordOf(res);
|
||||
return record != nullptr ? static_cast<SizeT>(record->Desc.Width) : 0;
|
||||
}
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
// M-3's rule for the two WHOLE-STORE readers (v1 round 3). The descriptor is the
|
||||
// application's own statement about the store: HasDefinedContent set means it SUPPLIED
|
||||
// the content (glBufferData(size, data)), which under split arrives as resource_subdata
|
||||
// records behind the respecify (table 1 row 19) - so a coverage gap at the draw is a
|
||||
// MISSING RECORD and the zero-fill past the coverage is not the application's bytes.
|
||||
// Clear means it ORPHANED the store (glBufferData(size, NULL), glBufferStorage(NULL)):
|
||||
// every byte it has not staged since is UNDEFINED by its own declaration, the streaming
|
||||
// idiom (orphan, partial glBufferSubData, draw) is the ordinary case, and uploading the
|
||||
// shadow's zero-fill for the rest is exactly what the monolith arm uploads from
|
||||
// MappedData(). Round 2 refused both shapes and aborted six LargeArenaAdoption /
|
||||
// ResourceSubsystemControl entries on the joint by name (v1-v3.md 6).
|
||||
Bool ResourceContentIsDeclared(MG_Pipe::MGPipeHandle res) {
|
||||
const auto* record = ResourceRecordOf(res);
|
||||
return record != nullptr && record->Desc.HasDefinedContent != 0;
|
||||
}
|
||||
#endif
|
||||
|
||||
void Ops_H_Create(MG_Pipe::MGPipeHandle res, const MG_Pipe::MGPResourceDesc& desc) {
|
||||
(void)res;
|
||||
@@ -1908,9 +2043,21 @@ namespace MobileGL::MG_Backend::DirectGLES {
|
||||
// every reader below treats a null base as "no bytes to move", which is the
|
||||
// honest answer, and the ensure path re-reads the live base from the
|
||||
// frontend object it still holds.
|
||||
resource->hostBytes = (desc.HasDefinedContent != 0 && initialBytes != nullptr)
|
||||
? static_cast<const Uint8*>(initialBytes)
|
||||
: nullptr;
|
||||
if (desc.HasDefinedContent != 0 && initialBytes != nullptr) {
|
||||
// R-11: in monolith this is the client's shadow base, unchanged; under
|
||||
// split it is copied into server-owned storage first. A respecify's
|
||||
// companion pointer is the base at offset 0 and covers the whole store.
|
||||
// Under split it is ALWAYS null (contract table 1 row 19 -
|
||||
// initialBytes does not cross, and the content arrives as
|
||||
// resource_subdata records right behind this record), so in practice
|
||||
// this arm is the monolith one and the else arm is the split one.
|
||||
resource->hostBytes = MGL_SERVER_STAGED_ADOPT(*resource, static_cast<SizeT>(desc.Width),
|
||||
initialBytes, 0,
|
||||
static_cast<SizeT>(desc.Width));
|
||||
} else {
|
||||
MGL_SERVER_STAGED_DROP(*resource);
|
||||
resource->hostBytes = nullptr;
|
||||
}
|
||||
}
|
||||
if (!resource) return; // lazy: the ensure path full-uploads on creation
|
||||
if (resource->immutableStorage) {
|
||||
@@ -1963,6 +2110,21 @@ namespace MobileGL::MG_Backend::DirectGLES {
|
||||
const SizeT offset = static_cast<SizeT>(MG_Pipe::MGPipeSubDataBufferOffset(record));
|
||||
const SizeT size = static_cast<SizeT>(MG_Pipe::MGPipeSubDataBufferSize(record));
|
||||
auto* resource = FindBufferResourceForHandle(res);
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
// R-11 / ID-52 item 3: under an ACTIVE TRANSPORT this record's bytes are the ONLY
|
||||
// delivery of the buffer's content - the client sends no companion pointer and the
|
||||
// server has no MappedData to fall back on. But the twin is created LAZILY at the
|
||||
// first draw (Ops_H_Create is a no-op by D-A2), which is AFTER this record, so a
|
||||
// subdata that finds no twin would return here and the bytes would be lost - the
|
||||
// draw then uploads an empty/shifted store (TriangleScenario read a blue triangle
|
||||
// before this). So under split the subdata MINTS the twin it needs to stage into.
|
||||
// Monolith is untouched: the twin stays lazy there because the frontend object's
|
||||
// MappedData is the source and nothing is lost by deferring the allocation (D-A2).
|
||||
if (resource == nullptr && bytes != nullptr &&
|
||||
MG_Config::Transport != MG_Config::TransportMode::Monolith) {
|
||||
resource = GetOrCreateBufferResourceForHandle(res);
|
||||
}
|
||||
#endif
|
||||
if (!resource) return;
|
||||
// M-2: UNDER pendingMutex, because this line runs BEFORE the CanTouchGLNow()
|
||||
// test below - i.e. on the arm D-A2 deliberately keeps reachable off the render
|
||||
@@ -1980,7 +2142,12 @@ namespace MobileGL::MG_Backend::DirectGLES {
|
||||
// and the ensure path's republication (the 3c55e027 fix) is what runs at a draw.
|
||||
if (bytes != nullptr) {
|
||||
const std::lock_guard<std::mutex> lock(resource->pendingMutex);
|
||||
resource->hostBytes = static_cast<const Uint8*>(bytes) - offset;
|
||||
// R-11: MONOLITH keeps the client's base; SPLIT copies [offset, offset+size)
|
||||
// into server-owned storage and points hostBytes at that. Inside the SAME
|
||||
// lock as the queued range, because the base and the range are one fact
|
||||
// ("these bytes, at this base") and the drain takes this mutex to lift them.
|
||||
resource->hostBytes =
|
||||
MGL_SERVER_STAGED_ADOPT(*resource, ResourceWidthOf(res), bytes, offset, size);
|
||||
}
|
||||
if (resource->pendingRespecify) return; // full re-upload pending anyway
|
||||
if (!CanTouchGLNow() || resource->id == 0 ||
|
||||
@@ -2029,10 +2196,18 @@ namespace MobileGL::MG_Backend::DirectGLES {
|
||||
if (!resource) return;
|
||||
const SizeT start = static_cast<SizeT>(record.Offset);
|
||||
const SizeT end = start + static_cast<SizeT>(record.Size);
|
||||
// M-2, the second store site - same lock, same reason as Ops_H_SubData's.
|
||||
// M-2, the second store site - same lock, same reason as Ops_H_SubData's, and
|
||||
// the same R-11 copy. UNDER SPLIT `bytes` IS ALWAYS NULL HERE by ruling (C-6 /
|
||||
// contract table 1 row 20: resource_flush_range carries no bytes at all - the
|
||||
// ladder it drives rewrites its range from the authoritative shadow, which rule
|
||||
// C makes server-owned, so resource_subdata is already the only way bytes reach
|
||||
// it and a second carrier would be a forgeable way to say the same thing). So
|
||||
// this arm keeps whatever the preceding subdata records staged, which is
|
||||
// exactly what the ladder must read.
|
||||
if (bytes != nullptr) {
|
||||
const std::lock_guard<std::mutex> lock(resource->pendingMutex);
|
||||
resource->hostBytes = static_cast<const Uint8*>(bytes) - start;
|
||||
resource->hostBytes = MGL_SERVER_STAGED_ADOPT(*resource, ResourceWidthOf(res), bytes,
|
||||
start, end - start);
|
||||
}
|
||||
if (resource->pendingRespecify) return;
|
||||
if (!CanTouchGLNow() || resource->id == 0 ||
|
||||
@@ -2062,6 +2237,14 @@ namespace MobileGL::MG_Backend::DirectGLES {
|
||||
resource->hostBytes != nullptr) {
|
||||
#ifdef TRACY_ENABLE
|
||||
ZoneScopedC(TRACY_ZONECOLOR_BACKEND);
|
||||
#endif
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
// The kill-switch arm's own Memcpy, and the one that passes
|
||||
// GL_MAP_INVALIDATE_RANGE_BIT - i.e. the one that tells the driver the old
|
||||
// bytes are dead. Bytes outside the staged coverage are exactly the ones
|
||||
// that claim is false for.
|
||||
MGL_SERVER_STAGED_REQUIRE(*resource, resource->hostBytes, start, end,
|
||||
"flush_range_invalidate_map");
|
||||
#endif
|
||||
BindBufferId(TempBufferTarget, resource->id);
|
||||
void* mappedData = g_GLESFuncs.glMapBufferRange(
|
||||
@@ -2107,7 +2290,12 @@ namespace MobileGL::MG_Backend::DirectGLES {
|
||||
if (size == 0) return;
|
||||
|
||||
// Queued app writes must land in the backend store before it is read back, or
|
||||
// the writeback below would revert them in the shadow.
|
||||
// the writeback below would revert them in the shadow. Under split every queued
|
||||
// range must lie inside the server shadow's staged coverage first (R-11 / the
|
||||
// M-6 ruling): the drain's tier-1 map would otherwise declare live GPU bytes
|
||||
// dead over a range nothing staged.
|
||||
MGL_SERVER_STAGED_REQUIRE_PENDING(*resource, resource->hostBytes, ResourceWidthOf(res),
|
||||
"readback_flush_pending");
|
||||
FlushPendingRangesFrom(*resource, resource->hostBytes, ResourceWidthOf(res));
|
||||
|
||||
BindBufferId(TempBufferTarget, resource->id);
|
||||
@@ -2149,6 +2337,12 @@ namespace MobileGL::MG_Backend::DirectGLES {
|
||||
}
|
||||
|
||||
void Ops_H_Destroy(MG_Pipe::MGPipeHandle res) {
|
||||
// R-11's server copy dies with the resource, and BEFORE the twin leaves the
|
||||
// table - the side map is keyed by the twin's address, so this is the last
|
||||
// moment that address can be looked up.
|
||||
if (GLESBufferResource* dying = FindBufferResourceForHandle(res); dying != nullptr) {
|
||||
MGL_SERVER_STAGED_DROP(*dying);
|
||||
}
|
||||
// The twin comes OUT of the table first, so the three outcomes below are
|
||||
// reached with the entry already retired. The SLOT is the client's to free,
|
||||
// after this returns (D-L).
|
||||
@@ -2234,6 +2428,9 @@ namespace MobileGL::MG_Backend::DirectGLES {
|
||||
// PipeResource::AdoptPersistentMap then does m_shadow->clear() +
|
||||
// shrink_to_fit(), so the shadow base any earlier content-carrying call
|
||||
// recorded is a FREED allocation from here on. The live bytes are persistentPtr.
|
||||
// R-11's server copy goes with it: the bytes are the coherent map's now, and a
|
||||
// stale server shadow would answer a later drain with pre-map content.
|
||||
MGL_SERVER_STAGED_DROP(*resource);
|
||||
resource->hostBytes = nullptr;
|
||||
resource->storageSize = static_cast<SizeT>(size);
|
||||
resource->storageInitialized = true;
|
||||
@@ -2593,6 +2790,13 @@ namespace MobileGL::MG_Backend::DirectGLES {
|
||||
// handles (no GL) and let the next draw / texture upload recreate them.
|
||||
ResetRingForNewContext(g_uboRing);
|
||||
ResetRingForNewContext(g_unpackRing);
|
||||
#if MOBILEGL_PIPE_PUSH
|
||||
// R-11's server copies die with the context for the same reason the rings' ids do:
|
||||
// the resource twins they are keyed by are about to be rebuilt against a new
|
||||
// generation, and a shadow that outlived its twin would be looked up by a RECYCLED
|
||||
// address on the next allocation - which is the quietest possible wrong answer.
|
||||
MGL_SERVER_STAGED_DROP_ALL();
|
||||
#endif
|
||||
}
|
||||
|
||||
void ProcessDeferredBufferReleases() {
|
||||
@@ -2667,16 +2871,33 @@ namespace MobileGL::MG_Backend::DirectGLES {
|
||||
}
|
||||
const auto* record = ResourceRecordOf(res);
|
||||
if (record == nullptr) return false;
|
||||
#if MOBILEGL_PIPE_VERIFY
|
||||
#if MOBILEGL_PIPE_VERIFY && !MOBILEGL_BUILD_DISAGGREGATED
|
||||
MOBILEGL_ASSERT(!record->HasLiveHostWrites,
|
||||
"MGPipeResourceRecord::HasLiveHostWrites is set, but P3a has no producer for it");
|
||||
"MGPipeResourceRecord::HasLiveHostWrites is set, but this build has no producer "
|
||||
"for it - P5 b1's producer is MGPSubData::HasLiveHostWrites and is split-only");
|
||||
#endif
|
||||
if (record->HasLiveHostWrites) return false;
|
||||
// The same question the legacy arm asks at this exact point in the order, for the
|
||||
// reason written at the top of this function. A null object is the "no frontend to
|
||||
// ask" case (nothing reaches this probe without one today) and is treated as "not
|
||||
// mapped", which is what the record already says.
|
||||
if (frontend != nullptr && frontend->IsMapped()) return false;
|
||||
// THE LAST FRONTEND READ IN THIS FUNCTION, AND P5 b1 RETIRES IT - under split
|
||||
// only, because that is the only build where it is both wrong and replaceable.
|
||||
//
|
||||
// It asked the object whether it was mapped because HasLiveHostWrites was pinned
|
||||
// false and an emulated persistent map mutates the shadow with no call, no serial
|
||||
// and no epoch; answering from the record alone made such a buffer read
|
||||
// draw-CLEAN forever, SyncPersistentMappedRange was never reached again, and the
|
||||
// frame drew the last uploaded bytes with no diagnostic
|
||||
// (MG_Test/SanityTest.cpp's DirectGLESBufferDrawProbe is exactly that case).
|
||||
//
|
||||
// TWO THINGS REPLACE IT AND BOTH HAD TO LAND FIRST: the record now carries the map
|
||||
// state (the line above, from MGPSubData::HasLiveHostWrites), and the client
|
||||
// pushes the mapped span by block at every validate point, so the serial moves for
|
||||
// a write the application made with no API call. Under a spawn there is no object
|
||||
// on this side to ask, which is why this was never going to stay a choice.
|
||||
//
|
||||
// A null object is the "no frontend to ask" case and is treated as "not mapped",
|
||||
// which is what the record already says.
|
||||
const Bool askTheObjectWhetherItIsMapped =
|
||||
MG_Config::Transport == MG_Config::TransportMode::Monolith;
|
||||
if (askTheObjectWhetherItIsMapped && frontend != nullptr && frontend->IsMapped()) return false;
|
||||
if (resource->pendingRespecify || !resource->storageInitialized) return false;
|
||||
if (!resource->pendingRanges.empty()) return false;
|
||||
if (resource->storageSize != static_cast<SizeT>(record->Desc.Width)) return false;
|
||||
@@ -2737,6 +2958,19 @@ namespace MobileGL::MG_Backend::DirectGLES {
|
||||
// fallback for the drains that have NO object (the readback flush), and it is
|
||||
// nulled at both of those events.
|
||||
const auto liveHostBase = [&resource, &bufferObject]() -> const Uint8* {
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
// M-2 / codex 3 / ID-52 item 3: under an ACTIVE TRANSPORT the server's staged
|
||||
// copy (resource->hostBytes, filled by MGL_SERVER_STAGED_ADOPT in Ops_H_SubData /
|
||||
// Ops_H_FlushRange) is the ONLY authoritative base. Preferring the frontend
|
||||
// object's MappedData() here - which under inproc is always non-null, same process
|
||||
// - meant every reduced-path drain read the CLIENT's shadow and NEVER the server's,
|
||||
// so a corrupt staged upload rendered the frontend's correct bytes and the R-2.5
|
||||
// 0xDD audit could not reach a draw. R-2 / table 3: honest inproc is inproc that
|
||||
// does not read the client object's memory. Under monolith nothing changes.
|
||||
if (MG_Config::Transport != MG_Config::TransportMode::Monolith) {
|
||||
return resource->hostBytes;
|
||||
}
|
||||
#endif
|
||||
if (bufferObject) return bufferObject->MappedData();
|
||||
return resource->hostBytes;
|
||||
};
|
||||
@@ -2753,6 +2987,28 @@ namespace MobileGL::MG_Backend::DirectGLES {
|
||||
resource->persistentMapped = false;
|
||||
resource->persistentPtr = nullptr;
|
||||
resource->immutableStorage = false;
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
// m-5 / codex 5: OnBackendContextDestroyed ran MGL_SERVER_STAGED_DROP_ALL(), which
|
||||
// frees every server shadow but does NOT null the hostBytes that name them - so a
|
||||
// twin that SURVIVES a context loss still carries a base into the freed allocation.
|
||||
// Null it here, where a surviving twin is re-armed - but ONLY when the shadow is
|
||||
// really gone. This block also runs on a twin's FIRST ensure (contextGeneration
|
||||
// starts mismatched), and there the shadow a preceding resource_subdata just staged
|
||||
// is still live; nulling it then would drop the reduced path's own bytes (it did,
|
||||
// and TriangleScenario read the wrong VBO). HasShadow is the discriminator: false
|
||||
// after DropAll, true after an ordinary Adopt.
|
||||
//
|
||||
// TRANSPORT-GUARDED like the other two split hunks in this file (review v2 N-7):
|
||||
// under MONOLITH transport in a disaggregated build the store never copies, Adopt
|
||||
// never sets m_any, HasShadow answers false for everything, and this null would
|
||||
// run on every twin's first ensure - harmless there only because liveHostBase()
|
||||
// prefers MappedData() under monolith, and "under monolith nothing changes" should
|
||||
// be true by construction rather than by luck.
|
||||
if (MG_Config::Transport != MG_Config::TransportMode::Monolith &&
|
||||
!ServerStaged().HasShadow(resource)) {
|
||||
resource->hostBytes = nullptr;
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
// An immutable store nothing maps any more, retired here on the thread that can.
|
||||
@@ -2788,6 +3044,20 @@ namespace MobileGL::MG_Backend::DirectGLES {
|
||||
resource->storageInitialized = true;
|
||||
resource->pendingRespecify = false;
|
||||
BindBufferId(TempBufferTarget, reused);
|
||||
// M-3 / codex 4: this is a WHOLE-STORE upload from the base, and under split
|
||||
// the base is the server shadow (M-2). For a store whose content the
|
||||
// application SUPPLIED, zero-filled bytes past the staged coverage are not the
|
||||
// application's - uploading them is the silent data loss the M-6 ruling
|
||||
// forbids, and a gap is a missing record: Fatal by name. For a store the
|
||||
// application ORPHANED the gap is its own undefined content and the upload is
|
||||
// legal (ResourceContentIsDeclared, above). RequireCoverage is a no-op for the
|
||||
// legacy arm's MappedData() and for a non-copying store.
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
if (ResourceContentIsDeclared(res)) {
|
||||
MGL_SERVER_STAGED_REQUIRE(*resource, liveHostBase(), 0, poolSize,
|
||||
"pool_reuse_whole_store");
|
||||
}
|
||||
#endif
|
||||
g_GLESFuncs.glBufferSubData(TempBufferTarget, 0, (GLsizeiptr)poolSize, liveHostBase());
|
||||
if (MG_Util::PipeStats::Enabled()) {
|
||||
MG_Util::PipeStats::AddBytes(MG_Util::PipeStats::ByteClass::StageBuffer,
|
||||
@@ -2861,15 +3131,41 @@ namespace MobileGL::MG_Backend::DirectGLES {
|
||||
const Bool shadowHasContent =
|
||||
bufferObject ? bufferObject->HasDefinedContent() : (record->Desc.HasDefinedContent != 0);
|
||||
const void* initialData = shadowHasContent ? hostBase : nullptr;
|
||||
// M-3 / codex 4: a RespecifyStorageWith(..., initialData != nullptr) is a WHOLE-STORE
|
||||
// [0, size) upload from the base, so it owes the same coverage the pending-range drain
|
||||
// below owes - the two respecify arms were the readers M-6's "never widened" rule did
|
||||
// not reach. No-op for the legacy arm's MappedData() and for a non-copying store; a
|
||||
// Fatal{StageSnapshotTooNarrow, "respecify_whole_store"} under split when the
|
||||
// DESCRIPTOR says the application supplied the content and the shadow's coverage does
|
||||
// not span the store (a missing record), instead of uploading its zero-fill as content.
|
||||
// NOT for a store the application orphaned: there `shadowHasContent` is the frontend
|
||||
// object's flag, which the streaming idiom's partial glBufferSubData flips to true, and
|
||||
// the bytes it did not write are undefined by its own glBufferData(NULL) - the rule at
|
||||
// ResourceContentIsDeclared. Round 2 refused that idiom and aborted six joint entries.
|
||||
const auto requireWholeStoreCoverage = [&]() {
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
if (initialData != nullptr && record->Desc.HasDefinedContent != 0) {
|
||||
MGL_SERVER_STAGED_REQUIRE(*resource, static_cast<const Uint8*>(initialData), 0,
|
||||
size, "respecify_whole_store");
|
||||
}
|
||||
#else
|
||||
(void)initialData;
|
||||
#endif
|
||||
};
|
||||
|
||||
if (resource->pendingRespecify || !resource->storageInitialized || resource->storageSize != size) {
|
||||
requireWholeStoreCoverage();
|
||||
RespecifyStorageWith(*resource, size, usage, initialData, serial);
|
||||
} else if (!resource->pendingRanges.empty()) {
|
||||
// Same rule as Ops_H_Readback's, at the draw-time drain: with no frontend object
|
||||
// `hostBase` is the server shadow and every queued range must be staged.
|
||||
MGL_SERVER_STAGED_REQUIRE_PENDING(*resource, hostBase, size, "ensure_flush_pending");
|
||||
FlushPendingRangesFrom(*resource, hostBase, size);
|
||||
resource->syncedChangeSerial = serial;
|
||||
} else if (resource->syncedChangeSerial != serial) {
|
||||
// Mutations this backend could not track (the table was unregistered between
|
||||
// contexts); re-upload everything.
|
||||
requireWholeStoreCoverage();
|
||||
RespecifyStorageWith(*resource, size, usage, initialData, serial);
|
||||
}
|
||||
return resource;
|
||||
@@ -2922,6 +3218,10 @@ namespace MobileGL::MG_Backend::DirectGLES {
|
||||
resource->persistentPtr = nullptr;
|
||||
resource->immutableStorage = false;
|
||||
}
|
||||
// m-5: the LEGACY arm (EnsureBufferResource) is reached only under monolith/push, where
|
||||
// liveHostBase reads the frontend object's MappedData rather than a server shadow, so
|
||||
// there is no freed server base to null here - the split freed-base hazard lives in
|
||||
// EnsureBufferResourceForHandle above, guarded by HasShadow.
|
||||
|
||||
// An immutable store nothing maps any more: a respecification of a buffer that
|
||||
// had been persistently mapped, which Ops_Respecify could not retire because it
|
||||
|
||||
@@ -901,6 +901,44 @@ namespace MobileGL::MG_Backend::DirectGLES {
|
||||
// has to receive the handle in a payload instead.
|
||||
MG_Pipe::MGPipeHandle HandleOfBuffer(const MG_State::GLState::BufferObject* bufferObject);
|
||||
|
||||
// TIER 1 OF THE THREE-TIER FLUSH LADDER, AS A PURE FUNCTION (P5 b1).
|
||||
//
|
||||
// `GL_MAP_INVALIDATE_RANGE_BIT` is not a hint, it is an ASSERTION THAT THE OLD BYTES
|
||||
// ARE DEAD - and it is only true of the bytes this call is about to rewrite from the
|
||||
// authoritative shadow. Managers.cpp:1125-1128 records what happens when it is not:
|
||||
// widening the map to page bounds "looked free and was not - the widened bytes
|
||||
// clobbered GPU-written data (an SSBO counter beside the app's SubData) with the stale
|
||||
// shadow". It fails SILENTLY, unlike tier 3, which only stalls.
|
||||
//
|
||||
// WHY IT IS A FUNCTION NOW, AND WHY IT TAKES THE MAP RANGE SEPARATELY FROM THE QUEUED
|
||||
// ONE. Under split the bytes are not re-read at every use any more: the server may not
|
||||
// hold a pointer into the client's shadow at all (R-11), so `hostBase` becomes a
|
||||
// SNAPSHOT taken into SEG_STAGE at emission, and the window between the snapshot and
|
||||
// the apply is new. A snapshot that covers less than the map does is exactly the
|
||||
// widening that drew blood, with a thread boundary instead of a page alignment as the
|
||||
// cause - so the two extents are separate parameters and a disagreement returns 0
|
||||
// ("do not take tier 1"), which drops the range onto the staging ring and costs a copy
|
||||
// rather than a corruption.
|
||||
//
|
||||
// Returns the glMapBufferRange access bits, or 0 when tier 1 must not be taken.
|
||||
inline constexpr SizeT kEsprytInvalidateRangeMinBytes = 128u * 1024u;
|
||||
constexpr GLbitfield InvalidateFlushAccessFor(SizeT queuedStart, SizeT queuedEnd, SizeT mapStart,
|
||||
SizeT mapEnd, SizeT limit, SizeT storageSize) {
|
||||
if (mapEnd <= mapStart) return 0u;
|
||||
// THE WIDENING REFUSAL. Not >=, not "covers": exactly, in both directions. A map
|
||||
// narrower than the queued range leaves bytes unwritten inside a range it has just
|
||||
// declared dead, which is the same corruption read the other way round.
|
||||
if (mapStart != queuedStart || mapEnd != queuedEnd) return 0u;
|
||||
const SizeT size = mapEnd - mapStart;
|
||||
const Bool wholeBuffer = mapStart == 0 && mapEnd == limit && limit == storageSize;
|
||||
// A partial range below the threshold goes to the ring instead: the map's
|
||||
// page-substitution fast path needs a page-coverable range to engage, and below it
|
||||
// the driver falls back to waiting out the WAR hazard on the CPU.
|
||||
if (!wholeBuffer && size < kEsprytInvalidateRangeMinBytes) return 0u;
|
||||
return GL_MAP_WRITE_BIT |
|
||||
(wholeBuffer ? GL_MAP_INVALIDATE_BUFFER_BIT : GL_MAP_INVALIDATE_RANGE_BIT);
|
||||
}
|
||||
|
||||
// The handle arms of the two draw-path entry points below. IsBufferDrawCleanByHandle
|
||||
// asks the applier the same five questions IsBufferDrawClean asks the frontend object,
|
||||
// with identical semantics (D-A4); EnsureBufferResourceForHandle is the ensure path
|
||||
|
||||
@@ -10,6 +10,9 @@
|
||||
#include "Utils.h"
|
||||
#include "Managers.h"
|
||||
#include "MG_Backend/BackendObjects.h"
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
#include <MG_Remote/Server/ServerLoop.h>
|
||||
#endif
|
||||
#include "MG_Util/Converters/GLToMG/FramebufferEnumConverter.h"
|
||||
#include "MG_Util/SelfTest/DriverBugProbes.h"
|
||||
#include "MG_Util/Texture/TextureFormatProcessor.h"
|
||||
@@ -33,6 +36,21 @@
|
||||
#include <regex>
|
||||
|
||||
namespace MobileGL::MG_Backend::DirectGLES {
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
const FormatCapabilityCache* ActiveBackendFormatCaps() {
|
||||
// Under a live split session the SERVER's private backend is what owns the context on the
|
||||
// apply thread (and these reads all run there), so its cache is the authoritative one.
|
||||
// Before the session lands, or under monolith transport in a disaggregated build, fall
|
||||
// back to the process global exactly as the monolith path always has.
|
||||
if (MG_Config::Transport != MG_Config::TransportMode::Monolith) {
|
||||
if (MG_Backend::BackendObject* server = MG_Remote::Server::ServerLoopInstance().Backend()) {
|
||||
return &server->GetFormatCapabilities();
|
||||
}
|
||||
}
|
||||
return pActiveBackendObject ? &pActiveBackendObject->GetFormatCapabilities() : nullptr;
|
||||
}
|
||||
#endif
|
||||
|
||||
namespace {
|
||||
Flags<PixelFormatNormalizeOptionBit> GetForcedPixelFormatNormalizeOptions() {
|
||||
Flags<PixelFormatNormalizeOptionBit> options;
|
||||
@@ -71,15 +89,26 @@ namespace MobileGL::MG_Backend::DirectGLES {
|
||||
SizeT targetIndex,
|
||||
Bool caveat,
|
||||
FormatCapability capability) {
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
const FormatCapabilityCache* activeCaps = ActiveBackendFormatCaps();
|
||||
if (activeCaps == nullptr || targetIndex >= kFormatCapabilityTargetCount) {
|
||||
return false;
|
||||
}
|
||||
#else
|
||||
if (!pActiveBackendObject || targetIndex >= kFormatCapabilityTargetCount) {
|
||||
return false;
|
||||
}
|
||||
#endif
|
||||
const SizeT formatIndex = static_cast<SizeT>(internalFormat);
|
||||
if (formatIndex >= kFormatCapabilityFormatCount) {
|
||||
return false;
|
||||
}
|
||||
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
const FormatCapabilityCache& cache = *activeCaps;
|
||||
#else
|
||||
const FormatCapabilityCache& cache = pActiveBackendObject->GetFormatCapabilities();
|
||||
#endif
|
||||
const FormatCapabilityFlags caps =
|
||||
caveat ? cache.CaveatCaps[targetIndex][formatIndex] : cache.FullCaps[targetIndex][formatIndex];
|
||||
return HasFormatCapability(caps, capability);
|
||||
@@ -123,7 +152,11 @@ namespace MobileGL::MG_Backend::DirectGLES {
|
||||
using namespace MobileGL::MG_Util::TextureFormatProcessor;
|
||||
const GLenum requestedInternalFormat = MG_Util::ConvertTextureInternalFormatToGLEnum(internalFormat);
|
||||
Flags<PixelFormatNormalizeOptionBit> options;
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
if (ActiveBackendFormatCaps() == nullptr || ShouldUseCaveatFormat(internalFormat, targetIndex)) {
|
||||
#else
|
||||
if (!pActiveBackendObject || ShouldUseCaveatFormat(internalFormat, targetIndex)) {
|
||||
#endif
|
||||
options = GetRuntimeFallbackNormalizeOptions(
|
||||
requestedInternalFormat,
|
||||
TextureImpl::GetRenderTargetNormalizeOptions(g_GLESCapabilities, targetIndex));
|
||||
@@ -217,9 +250,15 @@ namespace MobileGL::MG_Backend::DirectGLES {
|
||||
// not be resolved yet - a probe run then would latch "cannot tell" as "clean"
|
||||
// forever. Once the backend exists, the first narrow-format image this process
|
||||
// creates runs the probe on a live context.
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
if (ActiveBackendFormatCaps() == nullptr) {
|
||||
return false;
|
||||
}
|
||||
#else
|
||||
if (pActiveBackendObject == nullptr) {
|
||||
return false;
|
||||
}
|
||||
#endif
|
||||
return MG_Util::SelfTest::CopyImageMirrorsPacked16FieldOrder(g_GLESFuncs);
|
||||
}
|
||||
|
||||
@@ -257,9 +296,15 @@ namespace MobileGL::MG_Backend::DirectGLES {
|
||||
if (!TargetRequiresRenderableFormat(targetIndex)) {
|
||||
return false;
|
||||
}
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
if (ActiveBackendFormatCaps() != nullptr && !ShouldUseCaveatFormat(internalFormat, targetIndex)) {
|
||||
return false;
|
||||
}
|
||||
#else
|
||||
if (pActiveBackendObject && !ShouldUseCaveatFormat(internalFormat, targetIndex)) {
|
||||
return false;
|
||||
}
|
||||
#endif
|
||||
const GLenum requestedInternalFormat = MG_Util::ConvertTextureInternalFormatToGLEnum(internalFormat);
|
||||
const Flags<PixelFormatNormalizeOptionBit> options = GetRuntimeFallbackNormalizeOptions(
|
||||
requestedInternalFormat, GetRenderTargetNormalizeOptions(g_GLESCapabilities, targetIndex));
|
||||
|
||||
@@ -13,6 +13,19 @@
|
||||
#include <MG_Util/Texture/TextureFormatProcessor.h>
|
||||
|
||||
namespace MobileGL::MG_Backend::DirectGLES {
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
// C6 / ID-52 / CONTRACT-P5 table 3's pActiveBackendObject row. The format-capability cache of
|
||||
// THIS ROLE's backend. Under an active transport the server's own private
|
||||
// BackendObject_DirectGLES owns the context on the apply thread, so a backend-internal format
|
||||
// lookup must read ITS probed cache - not pActiveBackendObject's, which under split is the
|
||||
// CLIENT's BackendObject_Remote mirror (a caps snapshot, generation-lagged, and on an
|
||||
// independent server not usable at all). Monolith build/transport: pActiveBackendObject, so a
|
||||
// pull build never sees this symbol. Null when no backend is up. The seven table-3 reads
|
||||
// (five in Utils.cpp, ClampSamplesToBackendSupport in BackendObject_DirectGLES.cpp) go through
|
||||
// this instead of dereferencing pActiveBackendObject directly.
|
||||
const FormatCapabilityCache* ActiveBackendFormatCaps();
|
||||
#endif
|
||||
|
||||
namespace DebugImpl {
|
||||
class ErrorLopper {
|
||||
public:
|
||||
|
||||
@@ -67,6 +67,12 @@ namespace MobileGL::MG_Backend::DirectVulkan {
|
||||
}
|
||||
}
|
||||
|
||||
void Ops_ResidentSubData(BufferObject& bufferObject, SizeT offset, DataPtr data) {
|
||||
if (g_activeBufferManager) {
|
||||
g_activeBufferManager->OnResidentSubData(bufferObject, offset, data);
|
||||
}
|
||||
}
|
||||
|
||||
void Ops_FlushMappedRange(BufferObject& bufferObject, Range1D range,
|
||||
Flags<BufferMappingAccessBit> appAccess) {
|
||||
if (g_activeBufferManager) {
|
||||
@@ -78,11 +84,12 @@ namespace MobileGL::MG_Backend::DirectVulkan {
|
||||
// host-visible GPU storage (EnsureGpuResidentStorage adopts it when the buffer is
|
||||
// bound as a shader storage buffer), so nothing needs copying - but coherence only
|
||||
// says the writes are visible once they have happened, so the work has to retire
|
||||
// first.
|
||||
// first, including copies already submitted by a sync-point flush.
|
||||
void Ops_ReadbackFromGpu(BufferObject& bufferObject) {
|
||||
(void)bufferObject;
|
||||
if (pVulkanRenderer) {
|
||||
pVulkanRenderer->FinishPendingGpuWork();
|
||||
pVulkanRenderer->WaitForSubmitIndex(
|
||||
pVulkanRenderer->GetSyncPointSubmitIndex(), UINT64_MAX, true);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -106,6 +113,7 @@ namespace MobileGL::MG_Backend::DirectVulkan {
|
||||
const BufferBackendOps g_vulkanBufferBackendOps = {
|
||||
.Respecify = Ops_Respecify,
|
||||
.SubData = Ops_SubData,
|
||||
.ResidentSubData = Ops_ResidentSubData,
|
||||
.FlushMappedRange = Ops_FlushMappedRange,
|
||||
.OnDestroy = Ops_OnDestroy,
|
||||
.AcquirePersistentMap = Ops_AcquirePersistentMap,
|
||||
@@ -378,13 +386,13 @@ namespace MobileGL::MG_Backend::DirectVulkan {
|
||||
return true;
|
||||
}
|
||||
|
||||
Bool VkBufferManager::StagedRangeCopy(VkBufferResource& resource, MG_State::GLState::BufferObject& bufferObject,
|
||||
Bool VkBufferManager::StagedRangeCopy(VkBufferResource& resource, const void* data,
|
||||
SizeT offset, SizeT size) {
|
||||
if (!m_copyProvider) {
|
||||
return false;
|
||||
}
|
||||
BufferSlice staging{};
|
||||
if (!m_transientUploadArena.Upload(m_currentFrameIndex, bufferObject.MappedData() + offset,
|
||||
if (!m_transientUploadArena.Upload(m_currentFrameIndex, data,
|
||||
static_cast<VkDeviceSize>(size), 16, staging)) {
|
||||
return false;
|
||||
}
|
||||
@@ -499,11 +507,32 @@ namespace MobileGL::MG_Backend::DirectVulkan {
|
||||
// Busy partial write: stage + GPU copy preserves GL ordering within the
|
||||
// frame and leaves bytes outside the range (possibly GPU-written, e.g.
|
||||
// SSBO) intact. Fall back to a storage swap if staging is unavailable.
|
||||
if (!StagedRangeCopy(*resource, bufferObject, offset, size)) {
|
||||
if (!StagedRangeCopy(*resource, bufferObject.MappedData() + offset, offset, size)) {
|
||||
SwapStorageAndUploadAll(*resource, bufferObject);
|
||||
}
|
||||
}
|
||||
|
||||
void VkBufferManager::OnResidentSubData(MG_State::GLState::BufferObject& bufferObject,
|
||||
SizeT offset, DataPtr data) {
|
||||
auto* resource = ResourceOf(bufferObject);
|
||||
MOBILEGL_ASSERT(resource && resource->persistentMapped && resource->buffer.IsValid(),
|
||||
"OnResidentSubData requires adopted Vulkan storage");
|
||||
// The mapping is also the GPU's storage. Copy the supplied bytes onto the
|
||||
// command timeline before touching it: earlier draws must keep seeing the
|
||||
// old contents, including draws recorded but not yet submitted. The buffer
|
||||
// cannot be orphaned because the application may hold its mapped pointer.
|
||||
if (StagedRangeCopy(*resource, data.data, offset, data.size)) {
|
||||
return;
|
||||
}
|
||||
// Allocation failure: a host write is safe only after all prior work retires.
|
||||
if (pVulkanRenderer && pVulkanRenderer->WaitForSubmitIndex(
|
||||
pVulkanRenderer->GetSyncPointSubmitIndex(), UINT64_MAX, true)) {
|
||||
resource->buffer.Upload(data.data, data.size, offset);
|
||||
} else {
|
||||
MGLOG_E_ONCE("VkBufferManager::OnResidentSubData: ordered upload failed");
|
||||
}
|
||||
}
|
||||
|
||||
void VkBufferManager::OnFlushMappedRange(MG_State::GLState::BufferObject& bufferObject, Range1D range,
|
||||
Flags<BufferMappingAccessBit> appAccess) {
|
||||
auto* resource = ResourceOf(bufferObject);
|
||||
@@ -536,7 +565,7 @@ namespace MobileGL::MG_Backend::DirectVulkan {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!StagedRangeCopy(*resource, bufferObject, offset, size)) {
|
||||
if (!StagedRangeCopy(*resource, bufferObject.MappedData() + offset, offset, size)) {
|
||||
SwapStorageAndUploadAll(*resource, bufferObject);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -160,6 +160,7 @@ namespace MobileGL::MG_Backend::DirectVulkan {
|
||||
// Immediate ops, dispatched from the frontend BufferBackendOps table.
|
||||
void OnRespecify(MG_State::GLState::BufferObject& bufferObject);
|
||||
void OnSubData(MG_State::GLState::BufferObject& bufferObject, SizeT offset, SizeT size);
|
||||
void OnResidentSubData(MG_State::GLState::BufferObject& bufferObject, SizeT offset, DataPtr data);
|
||||
void OnFlushMappedRange(MG_State::GLState::BufferObject& bufferObject, Range1D range,
|
||||
Flags<BufferMappingAccessBit> appAccess);
|
||||
void OnResourceDestroyed(SharedPtr<MG_State::GLState::BackendBufferResource>&& resource);
|
||||
@@ -189,7 +190,7 @@ namespace MobileGL::MG_Backend::DirectVulkan {
|
||||
Bool SwapStorageAndUploadAll(VkBufferResource& resource, MG_State::GLState::BufferObject& bufferObject);
|
||||
// Record a staging-slice copy into the resident storage, ordered against
|
||||
// in-flight and already-recorded GPU work.
|
||||
Bool StagedRangeCopy(VkBufferResource& resource, MG_State::GLState::BufferObject& bufferObject,
|
||||
Bool StagedRangeCopy(VkBufferResource& resource, const void* data,
|
||||
SizeT offset, SizeT size);
|
||||
void DeferRelease(VkBufferObject&& buffer);
|
||||
void CollectDeferredReleases(Uint32 frameIndex);
|
||||
|
||||
@@ -11,6 +11,25 @@
|
||||
#include <MG_Util/BackendLoaders/OpenGL/Loader.h>
|
||||
#include <MG_Util/Converters/MGToStr/GLExtensionConverter.h>
|
||||
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
#include <MG_Pipe/MGPipe.h>
|
||||
#include <MG_Pipe/PipeApply.h>
|
||||
#include <MG_Remote/Client/ClientSession.h>
|
||||
#include <MG_Remote/Server/ServerLoop.h>
|
||||
#include <MG_Remote/Server/ServerSession.h>
|
||||
#endif
|
||||
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
// [p5/v1-joint PREVIEW EDIT - the merge-time form of v1's hook, c1-v1 8.2's exact order.] The
|
||||
// weak CreateRemoteBackendObject placeholder v1 shipped for a c1-less tree is DELETED at the
|
||||
// merge: the integration test links the STATIC MobileGL_s archive, and an archive member is
|
||||
// only pulled to satisfy an UNDEFINED reference - the weak definition in ServerLoop.cpp.o
|
||||
// already satisfied it, so BackendObject_Remote.cpp.o was never linked at all and the joint
|
||||
// build aborted in the placeholder (~/w7/p5-v1-joint-preflight.log). Direct construction
|
||||
// needs no factory and no weak symbol.
|
||||
#include <MG_Remote/Client/BackendObject_Remote.h>
|
||||
#endif
|
||||
|
||||
namespace MobileGL::MG_Backend {
|
||||
void LogBackendInfo() {
|
||||
if (!pActiveBackendObject) {
|
||||
@@ -45,9 +64,186 @@ namespace MobileGL::MG_Backend {
|
||||
return true;
|
||||
}
|
||||
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
namespace {
|
||||
// WHICH MGPipe SUBSYSTEMS THIS SERVER HAS A CONSUMER FOR - CallMask bits 32..47 (R-8 /
|
||||
// C-4). It is stated from what the server's own backend IS, and NOT derived from
|
||||
// MGPipeGetResourceOps(): that is a PROCESS-WIDE global, so under inproc a derivation
|
||||
// would answer with whatever the client half of the same process registered and under
|
||||
// spawn it would collapse to P2's 0x7f. Either way CapsMirror::ServerConsumes would
|
||||
// then answer a client-side liveness gate with a guess, the client would stop emitting
|
||||
// whole record families, clear its dirty flags on acceptance anyway, and the lane would
|
||||
// go green with the uploads lost - ID-39's 66 lost uploads, reflected (ServerSession.h).
|
||||
//
|
||||
// DirectGLES consumes all thirteen migrated families (P2's 0..6, P3a's 7..8, P4a's
|
||||
// 9..12): it registers the resource op table in Initialize()
|
||||
// (BackendObject_DirectGLES.cpp:849) and reads every other family out of gPipeInputs.
|
||||
// DirectVulkan registers NO resource ops - MGPipeSetResourceOps has exactly one caller
|
||||
// in the whole tree and it is Managers.cpp:2594 - so bit 7 is CLEAR for it, which is
|
||||
// the same fact ObjectSubsystemControlScenario already pins from the client side.
|
||||
Uint64 ConsumedSubsystemsFor(BackendType type) {
|
||||
switch (type) {
|
||||
case BackendType::DirectGLES: return MG_Pipe::kMGPipeSubsystemsMigratedAtP4a;
|
||||
case BackendType::DirectVulkan:
|
||||
return MG_Pipe::kMGPipeSubsystemsMigratedAtP4a & ~MG_Pipe::kMGPipeSubsystemResources;
|
||||
default: return 0;
|
||||
}
|
||||
}
|
||||
|
||||
// THE CROSS-CHECK THAT MAKES A WRONG ANSWER LOUD. Claiming bit 7 while no resource op
|
||||
// table is registered is the exact failure the mask exists to prevent, one level down:
|
||||
// the client would keep emitting the resource family and the server would drop every
|
||||
// record of it. The check runs AFTER Initialize(), which is where DirectGLES registers
|
||||
// the table, so it can see the real answer rather than a promise.
|
||||
void AssertConsumerMaskIsHonest(Uint64 mask) {
|
||||
const Bool claimsResources = (mask & MG_Pipe::kMGPipeSubsystemResources) != 0;
|
||||
const Bool hasResourceOps = MG_Pipe::MGPipeGetResourceOps() != nullptr;
|
||||
if (claimsResources && !hasResourceOps) {
|
||||
MGLOG_F("MGPipe: Fatal{ConsumerMaskLie, \"kMGPipeSubsystemResources\"} - the "
|
||||
"server published a consumer bit for the resource family while "
|
||||
"MGPipeGetResourceOps() is null. The client's R-8 liveness gate would "
|
||||
"keep emitting resource_create / resource_subdata records that this "
|
||||
"server drops on the floor, and the client clears its dirty flags on "
|
||||
"acceptance anyway (ID-39). A mask is a statement about this backend, "
|
||||
"not a hope");
|
||||
std::abort();
|
||||
}
|
||||
if (!claimsResources && hasResourceOps) {
|
||||
// The safe direction: the legacy pull path keeps running. Said out loud anyway,
|
||||
// because it silently costs the whole P3a family its migration.
|
||||
MGLOG_W("MG_Remote server: a resource op table is registered but the consumer "
|
||||
"mask withholds kMGPipeSubsystemResources; the buffer family will fall "
|
||||
"back to the legacy path for this session");
|
||||
}
|
||||
}
|
||||
|
||||
// The resource op table the SERVER's backend registered at step 1 (BackendObject_DirectGLES::
|
||||
// Initialize -> RegisterBufferBackendOps), as step 2 saw it. Step 5 compares against it
|
||||
// (review v2 N-8): a client object that registered a table of its own would have made
|
||||
// AssertConsumerMaskIsHonest's "is a table registered" answer TRUE, so re-asking that
|
||||
// question could never notice the swap - only the pointer can.
|
||||
const MG_Pipe::MGPipeResourceOps* g_resourceOpsAtStep2 = nullptr;
|
||||
|
||||
// The single hook (ARCHITECTURE.md:29). Returns false when the split could not be
|
||||
// brought up, and the caller then REFUSES TO CONTINUE rather than falling back to the
|
||||
// switch below - a fallback here is "the split lane ran monolith and went green".
|
||||
Bool InitSplitRoles() {
|
||||
using namespace MobileGL::MG_Remote;
|
||||
|
||||
// 1. the SERVER role's private backend object, on the app thread, with no GL and no
|
||||
// EGL. The context is created and made current later, on mgl-srv-apply, when the
|
||||
// client's first eglMakeCurrent crosses as a blocking control request.
|
||||
Server::ServerLoop& loop = Server::ServerLoopInstance();
|
||||
const MobileGLResult created = loop.CreateBackend(MG_Config::ActiveBackendType);
|
||||
if (created != MOBILEGL_OK) return false;
|
||||
|
||||
// 2. the two CallMask halves. NEITHER HAS A DEFAULT and CallMask() is a named Fatal
|
||||
// on an unset one (s1's BLOCKER fix), so this is the "somebody" that block names.
|
||||
Server::ServerSession& session = Server::ServerSessionInstance();
|
||||
const Uint64 consumed = ConsumedSubsystemsFor(MG_Config::ActiveBackendType);
|
||||
AssertConsumerMaskIsHonest(consumed);
|
||||
g_resourceOpsAtStep2 = MG_Pipe::MGPipeGetResourceOps();
|
||||
session.SetConsumedSubsystems(consumed);
|
||||
// ZERO IS THE EXPLICIT ANSWER FOR P5, not an omission (ServerSession.h's block):
|
||||
// every optional capability bit belongs to the package that owns its question, and
|
||||
// withholding one leaves the legacy path running, which is the safe direction.
|
||||
// kCapNeedsHostIndexBytes and kCapNeedsHostUboBytes must be 0 for the whole of P5
|
||||
// by ruling - they are the only two things that ask for an MGHostSpan, and 0 is
|
||||
// what keeps every one of them out of the first IPC frame (contract table 0).
|
||||
session.SetCapabilityBits(0);
|
||||
session.SetBackend(loop.Backend());
|
||||
|
||||
// 3. the handshake, the four segments, and - at its end - the apply thread.
|
||||
const MobileGLResult started =
|
||||
Client::ClientSessionInstance().Start(MG_Config::Transport, MG_Config::TransportEndpoint);
|
||||
if (started != MOBILEGL_OK) {
|
||||
MGLOG_E("MG_Remote: the split session failed to start (rc=%d); MobileGL will not "
|
||||
"fall back to monolith - a lane named split that ran monolith is the one "
|
||||
"failure this phase is built to make impossible",
|
||||
static_cast<int>(started));
|
||||
return false;
|
||||
}
|
||||
|
||||
// 4. and only now the CLIENT's backend object in the one global that holds it.
|
||||
// Table 3: pActiveBackendObject holds BackendObject_Remote and the server's
|
||||
// BackendObject_DirectGLES stays private to ServerLoop.
|
||||
pActiveBackendObject = MakeUnique<MG_Remote::Client::BackendObject_Remote>();
|
||||
return true;
|
||||
}
|
||||
} // namespace
|
||||
#endif
|
||||
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
void ShutdownSplitRoles() {
|
||||
if (MG_Config::Transport == MG_Config::TransportMode::Monolith) return;
|
||||
// ClientSession::Stop IS table 3's whole order and it is idempotent: publish and wait
|
||||
// for the server to drain (bounded - a lost record must be a red lane, not a hung
|
||||
// exit), Doorbell::Kill through the transport's Shutdown, ServerLoop::Stop's bounded
|
||||
// join - which also destroys the server's private BackendObject ON the apply thread
|
||||
// while it still owns the context - the transport, and only THEN anything an emitter
|
||||
// owns. A var-tail still named by an unapplied record is a use-after-free the join is
|
||||
// what prevents, which is why the order is not a preference.
|
||||
MG_Remote::Client::ClientSessionInstance().Stop();
|
||||
// M-6: ClientSession::Stop's !m_started arm (a Start that FAILED after
|
||||
// ServerSession::Accept - a refused Accept, an invalid cmd/reply ring) tears down only
|
||||
// the client half and never stops the apply thread or drops the server's private backend,
|
||||
// which ServerLoop::CreateBackend already built and which holds the process-wide
|
||||
// g_resourceOps. So call ServerLoop::Stop() here unconditionally. It is idempotent: on the
|
||||
// started path ClientSession::Stop already joined the thread, so this hits Stop's
|
||||
// !joinable arm, which resets a backend that never ran a thread and is otherwise a no-op.
|
||||
// Without this an early Start failure leaves BackendObject_DirectGLES permanently alive
|
||||
// and every later split bring-up in the process fails at CreateBackend's m_backend!=null
|
||||
// guard.
|
||||
MG_Remote::Server::ServerLoopInstance().Stop();
|
||||
}
|
||||
#endif
|
||||
|
||||
void Init() {
|
||||
MGLOG_D("Initializing MobileGL Backend...");
|
||||
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
// THE SINGLE HOOK. In a build without MOBILEGL_BUILD_DISAGGREGATED, MG_Config::Transport
|
||||
// is a `constexpr Monolith` (Config.h) and this whole statement is discarded, so the
|
||||
// pull build gains no symbol, no branch and no byte - which is what G1 measures.
|
||||
if (MG_Config::Transport != MG_Config::TransportMode::Monolith) {
|
||||
if (!InitSplitRoles()) {
|
||||
// NOT a fallback to the switch. pActiveBackendObject stays null and the next GL
|
||||
// call fails loudly, which is the only honest outcome: the operator asked for a
|
||||
// transport this process could not bring up.
|
||||
pActiveBackendObject = nullptr;
|
||||
return;
|
||||
}
|
||||
Bool remoteResult = InitSpecificBackendLibs();
|
||||
if (!remoteResult) {
|
||||
MGLOG_W("Failed to initialize MobileGL backend libraries for the remote object");
|
||||
return;
|
||||
}
|
||||
// m-6, re-worded per review v2 N-8. The honesty cross-check runs a SECOND time, now
|
||||
// that step 4's pActiveBackendObject (the client's BackendObject_Remote) exists and
|
||||
// its Initialize() has run inside InitSpecificBackendLibs. What the re-run CAN catch
|
||||
// is a table that was REMOVED between step 2 and here (the claim would then be a lie
|
||||
// again). What it cannot catch - and its first comment claimed it could - is a client
|
||||
// object that REGISTERED a table of its own: that leaves "is a table registered"
|
||||
// true. Only the pointer tells those apart, so the table is compared against the one
|
||||
// step 2 saw and a swap is refused by name: the applier would otherwise dispatch the
|
||||
// server's resource records into the CLIENT object's table under its feet.
|
||||
AssertConsumerMaskIsHonest(ConsumedSubsystemsFor(MG_Config::ActiveBackendType));
|
||||
if (MG_Pipe::MGPipeGetResourceOps() != g_resourceOpsAtStep2) {
|
||||
MGLOG_F("MGPipe: Fatal{ConsumerMaskLie, \"resource ops table replaced\"} - the "
|
||||
"resource op table MGPipeGetResourceOps() answers with is not the one the "
|
||||
"server's backend registered at step 1 (%p now, %p then). Something between "
|
||||
"ServerSession::Accept and the client object's Initialize() registered its "
|
||||
"own table, and the applier would dispatch every resource record into it. A "
|
||||
"mask is a statement about the server's backend, and so is the table",
|
||||
static_cast<const void*>(MG_Pipe::MGPipeGetResourceOps()),
|
||||
static_cast<const void*>(g_resourceOpsAtStep2));
|
||||
std::abort();
|
||||
}
|
||||
LogBackendInfo();
|
||||
return;
|
||||
}
|
||||
#endif
|
||||
|
||||
switch (MG_Config::ActiveBackendType) {
|
||||
case BackendType::DirectGLES:
|
||||
pActiveBackendObject = MakeUnique<DirectGLES::BackendObject_DirectGLES>();
|
||||
|
||||
@@ -16,6 +16,11 @@
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
#include <Config.h>
|
||||
#include <MG_Util/Metrics/PipeStats.h>
|
||||
#endif
|
||||
|
||||
namespace MobileGL::MG_Pipe {
|
||||
const char* MGPipeVerbName(MGPipeVerb verb) {
|
||||
const auto index = static_cast<SizeT>(verb);
|
||||
@@ -42,6 +47,145 @@ namespace MobileGL::MG_Pipe {
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
// ================================================================================
|
||||
// P5: the server's verb stamp, the residual-pull counter, and the four-way read verdict
|
||||
// ================================================================================
|
||||
namespace {
|
||||
Uint64 g_residualPulls = 0;
|
||||
|
||||
// The strict arm of R-7.3. Same first line as the ordinary poison Fatal, so every
|
||||
// existing filter on Fatal{UnmigratedPipeInput still matches, plus the class and the
|
||||
// phase that retires it - a strict abort that did not say which phase owes the answer
|
||||
// would leave the reader exactly where the gate found them.
|
||||
[[noreturn]] void StrictBarrierPullFatal(MGPipeInputField field, MGPipeVerb verb) {
|
||||
const SizeT index = static_cast<SizeT>(field);
|
||||
MGLOG_F("MGPipe: Fatal{UnmigratedPipeInput, \"%s@%s\"} [BARRIER-PULLED, "
|
||||
"MOBILEGL_IPC_STRICT_ERRORS=1, retires in %s]",
|
||||
kMGPipeInputFieldNames[index], MGPipeVerbName(verb), kMGPipeFieldRetiringPhase[index]);
|
||||
std::abort();
|
||||
}
|
||||
|
||||
// One place decides what a BARRIER-PULLED read does, so the field accessors and the
|
||||
// seven sticky forwards cannot drift apart on it.
|
||||
void CountBarrierPull(MGPipeInputField field, MGPipeVerb verb) {
|
||||
++g_residualPulls;
|
||||
if (MG_Util::PipeStats::Enabled()) {
|
||||
MG_Util::PipeStats::AddCalls(MG_Util::PipeStats::CallClass::ResidualPulls, 1);
|
||||
}
|
||||
if (MG_Config::Ipc.StrictErrors) StrictBarrierPullFatal(field, verb);
|
||||
}
|
||||
|
||||
// The verb's OWN may-read table (FillPoints.def, kMGPipeClassFieldMask). The stamp
|
||||
// respects it for the same reason the client's residual fill does: a field outside the
|
||||
// verb's class is one the fill never copied, so answering it out of gPipeInputs would
|
||||
// hand the server the PREVIOUS verb's value - the exact staleness the generation poison
|
||||
// exists to catch, re-introduced by the very mechanism meant to instrument it.
|
||||
Bool FieldIsInVerbClass(MGPipeInputField field, MGPipeVerb verb) {
|
||||
const SizeT verbIndex = static_cast<SizeT>(verb);
|
||||
if (verbIndex >= kMGPipeVerbCount) return false;
|
||||
const MGPipeVerbClass verbClass = kMGPipeVerbClass[verbIndex];
|
||||
return MGPipeFieldMaskHas(kMGPipeClassFieldMask[static_cast<SizeT>(verbClass)], field);
|
||||
}
|
||||
} // namespace
|
||||
|
||||
// The third door into the storage (see PipeInputs.h). It exists because neither of the
|
||||
// other two can be the one that stamps: MGPipeApplyAccess deliberately does not, and
|
||||
// MGPipeFillAccess lives in MG_Impl, the role a server does not have.
|
||||
struct MGPipeStampAccess {
|
||||
static MGPipeFilledState& Filled(PipeInputs& inputs) { return inputs.m_filled; }
|
||||
static void SetVerb(PipeInputs& inputs, MGPipeVerb verb) { inputs.m_currentVerb = verb; }
|
||||
static void SetServerStamped(PipeInputs& inputs, Bool stamped) {
|
||||
inputs.m_serverStampedVerb = stamped;
|
||||
}
|
||||
};
|
||||
|
||||
void MGPipeServerStampVerbBoundary(MGPipeVerb verb) {
|
||||
PipeInputs& inputs = gPipeInputs;
|
||||
MGPipeFilledState& filled = MGPipeStampAccess::Filled(inputs);
|
||||
MGPipeStampAccess::SetVerb(inputs, verb);
|
||||
// Starts at 1 for MGPipeValidateForVerb's reason: FilledGen == 0 is "never filled" on
|
||||
// BOTH branches of MGPipeInputFieldIsFresh, so the zeroing below is a real withdrawal
|
||||
// rather than a stamp that happens to be old.
|
||||
++filled.CurrentVerbSerial;
|
||||
for (SizeT i = 0; i < kMGPipeInputFieldCount; ++i) {
|
||||
const auto field = static_cast<MGPipeInputField>(i);
|
||||
const MGPipeFieldOwnership ownership = kMGPipeFieldOwnership[i];
|
||||
// STAMPED: in this verb's class AND answerable out of the records the applier has
|
||||
// already applied. WITHDRAWN (0): everything else - which is BARRIER-PULLED, FATAL,
|
||||
// and anything the verb's own may-read table says this verb does not read.
|
||||
//
|
||||
// The withdrawal is the load-bearing half of the rule: the client's residual fill
|
||||
// stamped all 63 fields at its own verb boundary, so without it every field would
|
||||
// read fresh on the server, `rsp` would be identically 0 and the exit gate would be
|
||||
// decoration. It also cancels the sticky exemption for free - generated/
|
||||
// PipeFilled.inc tests "never filled" BEFORE it tests sticky, so 0 wins over
|
||||
// kMGPipeInputFieldSticky without a line of the generated file changing.
|
||||
const Bool answerable = (ownership == MGPipeFieldOwnership::kRecordSupplied ||
|
||||
ownership == MGPipeFieldOwnership::kApplierDerived) &&
|
||||
FieldIsInVerbClass(field, verb);
|
||||
filled.FilledGen[i] = answerable ? filled.CurrentVerbSerial : 0;
|
||||
}
|
||||
MGPipeStampAccess::SetServerStamped(inputs, true);
|
||||
}
|
||||
|
||||
void MGPipeServerClearVerbBoundary() { MGPipeStampAccess::SetServerStamped(gPipeInputs, false); }
|
||||
|
||||
Uint64 MGPipeResidualPullCount() { return g_residualPulls; }
|
||||
void MGPipeResetResidualPullCountForTesting() { g_residualPulls = 0; }
|
||||
|
||||
void MGPipeInputUnfreshRead(MGPipeInputField field, MGPipeVerb verb, Bool serverStamped) {
|
||||
// OUTSIDE A SERVER-STAMPED VERB THIS IS THE MONOLITH ANSWER, UNCHANGED. A split BUILD
|
||||
// running MOBILEGL_TRANSPORT=monolith - every unit and integration-gpu lane of
|
||||
// build-split - has a client that stamped all 63 fields, so a stale read there is the
|
||||
// same defect it is in a verify build. Softening it on the build rather than on the
|
||||
// stamp would take 1842 unit cases' ability to go red away with it.
|
||||
//
|
||||
// AND A READ OUTSIDE THE VERB'S OWN CLASS IS STILL FATAL even for a BARRIER-PULLED
|
||||
// field: the value it would be answered with was never copied for this verb, so
|
||||
// counting it would trade a loud staleness for a quiet one.
|
||||
if (!serverStamped ||
|
||||
kMGPipeFieldOwnership[static_cast<SizeT>(field)] != MGPipeFieldOwnership::kBarrierPulled ||
|
||||
!FieldIsInVerbClass(field, verb)) {
|
||||
MGPipeInputPoisonFatalForVerb(field, verb);
|
||||
}
|
||||
CountBarrierPull(field, verb);
|
||||
}
|
||||
|
||||
Bool MGPipeInputArgumentRead(MGPipeInputField field, Uint32 arg0, MGPipeVerb verb, Bool serverStamped) {
|
||||
if (!serverStamped) return false;
|
||||
const MGPipeFieldOwnership narrowed = MGPipeFieldOwnershipOf(field, arg0);
|
||||
if (narrowed == MGPipeFieldOwnershipOf(field)) return false; // the argument narrows nothing
|
||||
if (narrowed == MGPipeFieldOwnership::kFatal) {
|
||||
// The field's own stamp says fresh - the applier really did write the half that has
|
||||
// a carrier - so only the argument can say that THIS read is unserved. THE MESSAGE
|
||||
// NAMES THE ARGUMENT, because without it this line is byte-identical to what a
|
||||
// genuinely stale read of the OTHER half would print, and the whole case for
|
||||
// narrowing by argument rather than by a second field id is that the reader is told
|
||||
// which half they asked for.
|
||||
MGLOG_F("MGPipe: Fatal{UnmigratedPipeInput, \"%s@%s\"} [argument 0 = %u is %s while the "
|
||||
"field is %s]",
|
||||
kMGPipeInputFieldNames[static_cast<SizeT>(field)], MGPipeVerbName(verb), arg0,
|
||||
MGPipeFieldOwnershipName(narrowed),
|
||||
MGPipeFieldOwnershipName(MGPipeFieldOwnershipOf(field)));
|
||||
std::abort();
|
||||
}
|
||||
if (narrowed == MGPipeFieldOwnership::kBarrierPulled) {
|
||||
CountBarrierPull(field, verb);
|
||||
return true; // decided here; the field-level check must not count it again
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void MGPipeStickyForwardPull(MGPipeInputField field) {
|
||||
// The seven carry no MGP_INPUT_CHECK at all (the declared exception argued at
|
||||
// PipeInputs.h's F-class block), so freshness can never reach them and neither can the
|
||||
// stamp's withdrawal. This is the only thing that puts them in `rsp`.
|
||||
if (!gPipeInputs.ServerStampedVerb()) return;
|
||||
CountBarrierPull(field, gPipeInputs.CurrentVerb());
|
||||
}
|
||||
#endif // MOBILEGL_BUILD_DISAGGREGATED
|
||||
|
||||
#if MOBILEGL_PIPE_VERIFY
|
||||
namespace {
|
||||
using CurrentVertexAttributeValue = PipeInputs::CurrentVertexAttributeValue;
|
||||
|
||||
@@ -26,6 +26,14 @@
|
||||
#endif
|
||||
|
||||
namespace MobileGL::MG_Pipe {
|
||||
// TABLE 2 (CONTRACT-P5.md section 3, R-7): the four ownership classes, one per field, plus
|
||||
// the seven sticky forwards' own rows. Included HERE rather than from MG_Pipe/MGPipe.h with
|
||||
// gen_pipe.py's seven outputs, deliberately: MGPipe.h is in the PULL build's include closure
|
||||
// and G1 admits no symbol motion there, while this header is reached only through
|
||||
// PipeInputsSwitch.h's MOBILEGL_PIPE_PUSH arm. It is also exactly the header the poison check
|
||||
// below and the server's verb stamp both already see.
|
||||
#include <MG_Pipe/generated/PipeFieldOwnership.inc>
|
||||
|
||||
// PipeInputs.cpp. The poison Fatal with the verb's name ("<none>" before the first
|
||||
// verb): MGLOG_F + std::abort(), live at every log level on purpose - this is not
|
||||
// MOBILEGL_ASSERT, which is inert in INFO builds.
|
||||
@@ -37,18 +45,72 @@ namespace MobileGL::MG_Pipe {
|
||||
Optional<MGPipeInputField> MGPipeFindInputField(const char* name);
|
||||
Optional<MGPipeVerb> MGPipeFindVerb(const char* name);
|
||||
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
// ---- P5: the split arm of the read check (R-7.2, R-7.3) ------------------------------
|
||||
//
|
||||
// A stale read stops being one answer and becomes FOUR, keyed on the field's table-2 class
|
||||
// - which is what turns the generated table from a document into a runtime mechanism:
|
||||
//
|
||||
// RECORD-SUPPLIED / APPLIER-DERIVED the server could answer it and did not: a real
|
||||
// defect. Fatal, exactly as today.
|
||||
// BARRIER-PULLED the server is reading the value the client's
|
||||
// residual fill left in gPipeInputs while the verb
|
||||
// barrier holds both threads apart (R-1). LEGAL, and
|
||||
// COUNTED: PipeStats::CallClass::ResidualPulls. Under
|
||||
// MOBILEGL_IPC_STRICT_ERRORS=1 it is Fatal instead.
|
||||
// FATAL no carrier and the reduced path never reads it.
|
||||
//
|
||||
// AND IT IS ARMED ONLY INSIDE A SERVER-STAMPED VERB (PipeInputs::ServerStampedVerb).
|
||||
// A split BUILD running monolith transport - which is every unit and integration-gpu lane
|
||||
// of build-split - has a client that fills and stamps all 63 fields at every verb, so a
|
||||
// stale read there is the same defect it is in a verify build and gets the same Fatal.
|
||||
// Without that condition the leniency would apply to lanes whose stamps are the client's,
|
||||
// and 1842 unit cases would quietly stop being able to go red.
|
||||
void MGPipeInputUnfreshRead(MGPipeInputField field, MGPipeVerb verb, Bool serverStamped);
|
||||
// The same decision for an accessor that takes an argument the table narrows on
|
||||
// (kMGPipeFieldArgumentOwnership). Called BEFORE the freshness test, because the narrowed
|
||||
// class is a statement about the argument rather than about the stamp: the pack half of
|
||||
// GetPixelStoreParameters is stamped and fresh while the unpack half has no carrier and no
|
||||
// backend reader at all.
|
||||
//
|
||||
// RETURNS TRUE WHEN THE ARGUMENT ROW DECIDED, and the caller then skips the field-level
|
||||
// check. Today the only row narrows to FATAL, which aborts, so the return value changes
|
||||
// nothing; the day a row narrows to BARRIER-PULLED it is what stops the field-level check
|
||||
// from either counting the same read twice or - worse, because the field's own class would
|
||||
// not be BARRIER-PULLED - aborting a read the argument row had just declared legal.
|
||||
Bool MGPipeInputArgumentRead(MGPipeInputField field, Uint32 arg0, MGPipeVerb verb, Bool serverStamped);
|
||||
#endif
|
||||
|
||||
// The read-side poison check, on every non-forwarded accessor. Under MOBILEGL_PIPE_POISON
|
||||
// a read of a field whose stamp is older than the current verb serial is
|
||||
// Fatal{UnmigratedPipeInput, "Field@Verb"}; otherwise the accessor is a plain load.
|
||||
#if MOBILEGL_PIPE_POISON
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
#define MGP_INPUT_CHECK(Field) \
|
||||
do { \
|
||||
if (!::MobileGL::MG_Pipe::MGPipeInputFieldIsFresh(m_filled, (Field))) { \
|
||||
::MobileGL::MG_Pipe::MGPipeInputUnfreshRead((Field), m_currentVerb, m_serverStampedVerb); \
|
||||
} \
|
||||
} while (0)
|
||||
#define MGP_INPUT_CHECK_ARG(Field, Arg0) \
|
||||
do { \
|
||||
if (!::MobileGL::MG_Pipe::MGPipeInputArgumentRead((Field), static_cast<Uint32>(Arg0), m_currentVerb, \
|
||||
m_serverStampedVerb)) { \
|
||||
MGP_INPUT_CHECK(Field); \
|
||||
} \
|
||||
} while (0)
|
||||
#else
|
||||
#define MGP_INPUT_CHECK(Field) \
|
||||
do { \
|
||||
if (!::MobileGL::MG_Pipe::MGPipeInputFieldIsFresh(m_filled, (Field))) { \
|
||||
::MobileGL::MG_Pipe::MGPipeInputPoisonFatalForVerb((Field), m_currentVerb); \
|
||||
} \
|
||||
} while (0)
|
||||
#define MGP_INPUT_CHECK_ARG(Field, Arg0) MGP_INPUT_CHECK(Field)
|
||||
#endif
|
||||
#else
|
||||
#define MGP_INPUT_CHECK(Field) ((void)0)
|
||||
#define MGP_INPUT_CHECK_ARG(Field, Arg0) ((void)0)
|
||||
#endif
|
||||
// The compare-at-read hook of the MOBILEGL_PIPE_VERIFY comparator (P1 brief D8), defined
|
||||
// in MG_Impl/Pipe/PipeFill.cpp: re-reads the field from the live context and compares it
|
||||
@@ -194,6 +256,26 @@ namespace MobileGL::MG_Pipe {
|
||||
#if MOBILEGL_PIPE_POISON
|
||||
const MGPipeFilledState& FilledState() const { return m_filled; }
|
||||
#endif
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
// TRUE between the server's verb-boundary stamp and whoever clears it. It is the
|
||||
// arming condition of the whole split read path: only inside a server-stamped verb is
|
||||
// a BARRIER-PULLED read counted rather than Fatal, and only there is a sticky forward
|
||||
// a residual pull rather than an ordinary monolith call. A split build running
|
||||
// monolith transport never sets it, which is why build-split's unit and integration
|
||||
// cases behave exactly as a verify build's do.
|
||||
//
|
||||
// CLEARING IT IS THE APPLIER'S JOB AND NOT THE CLIENT'S, even though the client also
|
||||
// does it. MGPipeValidateForVerb and MGPipeLeaveVerb both call
|
||||
// MGPipeServerClearVerbBoundary, which is sufficient for inproc, where both roles share
|
||||
// one process and one gPipeInputs - and misleading for P6, where MG_Impl is not in the
|
||||
// server at all. There this flag would latch TRUE for the life of the server after the
|
||||
// first stamp, every later read anywhere would be judged against the last verb's mask,
|
||||
// and MGPipeStickyForwardPull would stop being a no-op outside a verb - so
|
||||
// InvalidateCompileEnv reached from a later context's backend initialisation, the exact
|
||||
// case the sticky exemption was written for, would be counted and, under strict, would
|
||||
// abort. So: PipeApplier clears on leaving the applier. Not optional.
|
||||
Bool ServerStampedVerb() const { return m_serverStampedVerb; }
|
||||
#endif
|
||||
|
||||
// ---- V: values ----
|
||||
Int GetActiveTextureUnit() const {
|
||||
@@ -345,8 +427,17 @@ namespace MobileGL::MG_Pipe {
|
||||
MGP_INPUT_VERIFY_READ(MGPipeInputField::GetRenderStateParametersVersion, 0, 0);
|
||||
return m_renderStateParametersVersion;
|
||||
}
|
||||
// THE ONE FIELD TABLE 2 NARROWS BY ARGUMENT. m_pixelStore[2] is one array indexed by
|
||||
// this accessor's own argument, exactly as m_bufferBindingSlot[15] is indexed by a
|
||||
// BufferTarget, and Coverage.def:62-69 already rules that such a field stays ONE row.
|
||||
// Only [0] (pack) has a carrier - set_pixel_pack_state, which the applier writes
|
||||
// (PipeApply.cpp:1373) - so the field is APPLIER-DERIVED and the UNPACK half is FATAL:
|
||||
// every MGB_CTX->GetPixelStoreParameters site in the tree passes false
|
||||
// (DirectGLES.cpp:7924, :9399, :10893, :11272, Utils.cpp:2302,
|
||||
// VulkanRenderer.cpp:10980), and PipeFill.cpp's EmitPixelPackState says the same from
|
||||
// the other side: "nothing on the far side of the boundary reads unpack state".
|
||||
PixelStoreParameters GetPixelStoreParameters(Bool isUnpack) const {
|
||||
MGP_INPUT_CHECK(MGPipeInputField::GetPixelStoreParameters);
|
||||
MGP_INPUT_CHECK_ARG(MGPipeInputField::GetPixelStoreParameters, isUnpack ? 1u : 0u);
|
||||
MGP_INPUT_VERIFY_READ(MGPipeInputField::GetPixelStoreParameters, isUnpack ? 1u : 0u, 0);
|
||||
return m_pixelStore[isUnpack ? 1 : 0];
|
||||
}
|
||||
@@ -616,6 +707,12 @@ namespace MobileGL::MG_Pipe {
|
||||
// does NOT stamp the poison generations - a stamp says "the filler published this
|
||||
// for THIS verb", which is the walk's statement, not the applier's.
|
||||
friend struct MGPipeApplyAccess;
|
||||
// THE THIRD DOOR, and the one the split phase needed that neither of the two above
|
||||
// could be: the SERVER's verb-boundary stamp (PipeInputs.cpp). MGPipeApplyAccess
|
||||
// deliberately does not stamp - see its comment above - and MGPipeFillAccess lives in
|
||||
// MG_Impl, which is the role the server does not have. So the stamp gets a door of its
|
||||
// own rather than a relaxation of either existing one.
|
||||
friend struct MGPipeStampAccess;
|
||||
|
||||
// ---- identity ----
|
||||
const void* m_contextIdentity = nullptr;
|
||||
@@ -624,6 +721,9 @@ namespace MobileGL::MG_Pipe {
|
||||
#if MOBILEGL_PIPE_POISON
|
||||
MGPipeFilledState m_filled{};
|
||||
#endif
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
Bool m_serverStampedVerb = false;
|
||||
#endif
|
||||
|
||||
// ---- V ----
|
||||
Int m_activeTextureUnit = 0;
|
||||
@@ -713,6 +813,83 @@ namespace MobileGL::MG_Pipe {
|
||||
// The docs budget ~20 KB; the block is a few KB.
|
||||
static_assert(sizeof(PipeInputs) < 20 * 1024, "PipeInputs outgrew its budget");
|
||||
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
// ============================================================================
|
||||
// P5: the server-side verb stamp, and the counter that sizes what it leaves behind
|
||||
// ============================================================================
|
||||
//
|
||||
// THE PREREQUISITE NOBODY ELSE OWNS (CONTRACT-P5.md section 3). Nothing stamps the poison
|
||||
// generations on the applier side today and that is deliberate (see MGPipeApplyAccess'
|
||||
// comment above: a stamp is the filler's statement, not the applier's). Under split the
|
||||
// filler is in the other role, so without this every FilledGen[] would stay 0,
|
||||
// MGPipeInputFieldIsFresh would answer false for EVERYTHING, and a purely server-side read
|
||||
// would abort on the first field inside SyncRenderState - before any interesting case.
|
||||
//
|
||||
// THE RULE, in three lines, and the third one is the load-bearing one:
|
||||
//
|
||||
// 1. bump CurrentVerbSerial and set the verb, so a Fatal names it instead of "<none>";
|
||||
// 2. stamp every RECORD-SUPPLIED and APPLIER-DERIVED field with the new serial - those
|
||||
// are exactly the fields the records this verb carried can answer;
|
||||
// 3. ZERO every BARRIER-PULLED and FATAL field's stamp.
|
||||
//
|
||||
// (3) is what makes the instrumentation real. The client's residual fill stamps ALL 63
|
||||
// fields at its own verb boundary (PipeFill.cpp step 4), so without the zeroing every
|
||||
// field would read fresh on the server, `rsp` would be identically 0, and the gate would
|
||||
// be decoration - the precise "an inproc implementation proves nothing" failure R-2
|
||||
// exists to prevent. Zeroing also cancels the sticky exemption for free: generated/
|
||||
// PipeFilled.inc tests "never filled" BEFORE it tests sticky, so gen == 0 wins.
|
||||
//
|
||||
// The value a BARRIER-PULLED read then gets is still the client's residual fill's, and it
|
||||
// is still CORRECT - because the verb barrier (R-1) leaves exactly one of the two threads
|
||||
// runnable. That is the debt, not a bug; `rsp` is its size.
|
||||
//
|
||||
// v1 calls this from Server/PipeApplier::StampVerbBoundary. MGPipeVerbForWireOp maps the
|
||||
// record's op onto a verb and answers kVerbCount for an op that is not verb-shaped, which
|
||||
// is the case the applier must NOT stamp on: a set_dynamic_state between two draws is not
|
||||
// a new verb, and stamping there would retire the previous verb's answers early.
|
||||
//
|
||||
// TWO THINGS THE CALLER INHERITS AND SHOULD NOT REDISCOVER:
|
||||
//
|
||||
// (a) The records BETWEEN two boundaries apply under the earlier boundary's stamp - its
|
||||
// serial, its class mask and its verb NAME. That is correct today because every
|
||||
// MGPipeApply* entry point touches gPipeInputs through MGPipeApplyAccess, which
|
||||
// carries no MGP_INPUT_CHECK; the day one of them calls back into the backend, its
|
||||
// reads will be judged against a verb they do not belong to.
|
||||
// (b) The verb a draw record stamps is MGPipeVerb::DrawArrays for ALL TWENTY draw verbs.
|
||||
// The class mask is right (FillPoints.def puts all twenty in kDraw) and the NAME in a
|
||||
// Fatal is not: a glDrawElements that aborts will say "@DrawArrays". draw_vbo carries
|
||||
// no verb id, so fixing it means either a field on the record or a second argument
|
||||
// here; it is cosmetic for the verdict and misleading for the reader, and it belongs
|
||||
// with whatever phase widens draw_vbo to the multi-draw family (P8).
|
||||
void MGPipeServerStampVerbBoundary(MGPipeVerb verb);
|
||||
// MANDATORY for the applier when it leaves the verb. The client's own MGPipeValidateForVerb
|
||||
// and MGPipeLeaveVerb call it too, which is enough for inproc and NOT enough for a spawned
|
||||
// server, where MG_Impl is not in the process - see ServerStampedVerb() above for what
|
||||
// latching TRUE would do to the sticky forwards.
|
||||
void MGPipeServerClearVerbBoundary();
|
||||
|
||||
// `rsp`. Also published per frame through PipeStats::CallClass::ResidualPulls; this is the
|
||||
// raw count, which exists because PipeStats can be switched off and the exit gate may not
|
||||
// be. Its value at the end of P5 IS the size of the P6/P7/P8 debt.
|
||||
//
|
||||
// PLAIN, NOT ATOMIC, AND THAT IS THE SAME RULING TABLE 3 MAKES FOR gPipeInputS ITSELF
|
||||
// (CONTRACT-P5.md section 4): the verb barrier leaves at most one of {GL thread, apply
|
||||
// thread} runnable, so there is one writer at any instant. This counter, m_serverStampedVerb
|
||||
// and FilledGen[] all rest on that and on nothing else - so MOBILEGL_IPC_VERB_BARRIER=0,
|
||||
// R-1's negative control, is a data race on all three as well as the correctness failure it
|
||||
// is there to show. It is expected to be red; it is not expected to be meaningful.
|
||||
Uint64 MGPipeResidualPullCount();
|
||||
void MGPipeResetResidualPullCountForTesting();
|
||||
|
||||
// The sticky forwards' hook, called from each of the seven bodies in
|
||||
// MG_Impl/Pipe/PipeFill.cpp. They carry no MGP_INPUT_CHECK at all - the declared exception
|
||||
// argued at the F-class block above - so freshness can never reach them and the exit gate
|
||||
// would be structurally blind on the seven fields that hand the server a raw frontend
|
||||
// object or write into the frontend. This is what puts them in `rsp` and, under
|
||||
// MOBILEGL_IPC_STRICT_ERRORS=1, makes them Fatal like any other BARRIER-PULLED row.
|
||||
void MGPipeStickyForwardPull(MGPipeInputField field);
|
||||
#endif
|
||||
|
||||
#if MOBILEGL_PIPE_VERIFY
|
||||
// PipeInputs.cpp. Per-field equality for the entry compare (P1 brief D8): V by value
|
||||
// through G4's MGPipeFieldEqual (bitwise floats, field-wise structs), O by identity, F
|
||||
|
||||
@@ -12,6 +12,9 @@
|
||||
#include <MG_State/EGLState/Core.h>
|
||||
#include <MG_Backend/BackendObjects.h>
|
||||
#include <MG_Impl/Pipe/PipeFill.h>
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
#include <MG_Remote/Client/GpuWritePending.h>
|
||||
#endif
|
||||
#include "../Getter/GL_Getter.h"
|
||||
|
||||
namespace MobileGL::MG_Impl::GLImpl {
|
||||
@@ -1315,6 +1318,20 @@ namespace MobileGL::MG_Impl::GLImpl {
|
||||
static_cast<Uint>(bufferIndex));
|
||||
const auto& buffer = bindingPoint.GetBoundObject();
|
||||
if (buffer == nullptr) continue;
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
// This fixup READS the captured bytes back through the shadow, so it is the one
|
||||
// consumer that cannot simply inherit the deferral EndTransformFeedback's dropped
|
||||
// fence introduces. Under split it pays the reconciliation itself, which is the
|
||||
// same cost the fence used to charge every caller - here charged only to the
|
||||
// capture shapes that actually need reordering.
|
||||
//
|
||||
// TRANSPORT-GATED LIKE EVERY OTHER NEW SITE (D-J). Without the test this fires in
|
||||
// a build-split lane running MOBILEGL_TRANSPORT=monolith on Magma - whose
|
||||
// BeginXfbCaptureForDraw does mark the capture targets - where the fence at the
|
||||
// caller still runs, so the readback it emits is pure new work on the monolith
|
||||
// path and integration-gpu cannot see it.
|
||||
if (MG_Config::Transport != MG_Config::TransportMode::Monolith) buffer->SyncGpuWrites();
|
||||
#endif
|
||||
const Range1D range = bindingPoint.GetRange();
|
||||
const Uint8* mapped = buffer->MappedData();
|
||||
if (mapped == nullptr) continue;
|
||||
@@ -1355,12 +1372,28 @@ namespace MobileGL::MG_Impl::GLImpl {
|
||||
MGP_FILL(EndTransformFeedback);
|
||||
endXfb();
|
||||
}
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
// P5 (b1), the second producer the client-side GPU-write set ADDS, and it has to be
|
||||
// taken HERE - before GLContext::EndTransformFeedback clears the live bindings, since
|
||||
// a mark taken after it marks nothing.
|
||||
MG_Remote::Client::MarkEndTransformFeedbackCaptureTargets();
|
||||
#endif
|
||||
MG_State::pGLContext->EndTransformFeedback();
|
||||
// Captured results must be visible to MapBuffer/GetBufferSubData after
|
||||
// End; the capture targets are host-coherent GPU memory, so completing
|
||||
// the GPU work is all that is required.
|
||||
//
|
||||
// P5 (b1): UNDER SPLIT THE UNBOUNDED WAIT GOES AND THE MARK ABOVE REPLACES IT. The
|
||||
// wait exists for one reason - so that a later MapBuffer sees real captured results -
|
||||
// and that is precisely what m_gpuWritePending says; SyncGpuWrites then pays for it
|
||||
// once, on the first read that actually wants the bytes, instead of on every
|
||||
// glEndTransformFeedback. A ~0ull ClientWaitSync on the GL thread is also the one
|
||||
// shape a verb barrier cannot make cheap, because it is the driver's wait and not the
|
||||
// barrier's.
|
||||
auto& backendGL = MG_Backend::gBackendFunctionsTable.GL;
|
||||
if (backendGL.FenceSync && backendGL.ClientWaitSync) {
|
||||
const Bool waitForTheCapture =
|
||||
MG_Config::Transport == MG_Config::TransportMode::Monolith;
|
||||
if (waitForTheCapture && backendGL.FenceSync && backendGL.ClientWaitSync) {
|
||||
MGP_FILL(FenceSync);
|
||||
if (auto sync = backendGL.FenceSync()) {
|
||||
MGP_FILL(ClientWaitSync);
|
||||
|
||||
@@ -16,6 +16,9 @@
|
||||
#include <MG_Impl/GLImpl/Getter/GL_Getter.h>
|
||||
#include <MG_State/GLState/ErrorState/Error.h>
|
||||
#include <MG_Impl/Pipe/PipeFill.h>
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
#include <MG_Remote/Client/GpuWritePending.h>
|
||||
#endif
|
||||
#if MOBILEGL_PIPE_PUSH
|
||||
// P4a, ID-19(c). This file is the ONLY place every DSA framebuffer entry point lives, and the
|
||||
// emitter it reaches is this package's own header rather than a declaration in one of the
|
||||
@@ -3093,6 +3096,18 @@ namespace MobileGL::MG_Impl::GLImpl {
|
||||
void ReadPixels_Backend(GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, void* pixels) {
|
||||
MGP_FILL(ReadPixels);
|
||||
MG_Backend::gBackendFunctionsTable.GL.ReadPixels(x, y, width, height, format, type, pixels);
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
// P5 (b1), one of the two producers the client-side GPU-write set ADDS. A read into a
|
||||
// bound GL_PIXEL_PACK_BUFFER is a GPU write to that buffer exactly as a shader's store
|
||||
// is, and marking it is what makes the next glMapBuffer / glGetBufferSubData of the
|
||||
// PBO reconcile. It is a no-op on the monolith path, where the backend still maps the
|
||||
// PBO and copies it into the shadow inside the call
|
||||
// (DirectGLES.cpp:10983-10993) - an unconditional stall on every glReadPixels whether
|
||||
// or not anything ever reads the shadow. Deferring that to the first read that wants
|
||||
// it is STRICTLY BETTER, which is the only reason a split build is allowed to differ
|
||||
// here at all.
|
||||
MG_Remote::Client::MarkReadPixelsPackBuffer();
|
||||
#endif
|
||||
}
|
||||
|
||||
/* @INSERTION_POINT:FUNCTION_IMPLEMENTATION@ */
|
||||
|
||||
@@ -31,6 +31,11 @@
|
||||
#include <MG_Util/ShaderTranspiler/Types.h>
|
||||
#include <MG_Backend/BackendObjects.h>
|
||||
#include <MG_Impl/Pipe/PipeFill.h>
|
||||
// CONTRACT-P5.md §7 / ID-14: a null check on a GLFunctionsTable slot may not survive into the
|
||||
// client under split - it becomes a caps-mirror read. SlotCaps.h carries the rule and the test
|
||||
// that decides which of its two spellings a site takes; in a pull build both expand to exactly
|
||||
// the check they replaced.
|
||||
#include <MG_Remote/Client/SlotCaps.h>
|
||||
|
||||
namespace MobileGL::MG_Impl::GLImpl {
|
||||
// Declared rather than #included from GL_RenderState.h on purpose: that header also declares
|
||||
@@ -1354,7 +1359,16 @@ namespace MobileGL::MG_Impl::GLImpl {
|
||||
// full 64-bit GPU timestamp survives; LWJGL reads it this way.
|
||||
Int64 timestamp = 0;
|
||||
if (!MG_Config::Features.DisableTimerQuery) {
|
||||
if (const auto getGpuTimestampNs = MG_Backend::gBackendFunctionsTable.GL.GetGpuTimestampNs) {
|
||||
// glGetInteger64v(GL_TIMESTAMP). GetGpuTimestampNs is class C - a LIVE GPU
|
||||
// timestamp is not a static property, so R-15 does not reach it - and the
|
||||
// documented answer when it is unavailable is 0 (BackendObject.h:192), which
|
||||
// is correct rather than merely quiet. kCapTimerQuery is the published bit.
|
||||
//
|
||||
// The POINTER-valued macro, so the init-statement below is unchanged in a pull
|
||||
// build and G1 cannot see this edit: the Bool-valued spelling moved this
|
||||
// function by -150 bytes for no behavioural reason at all.
|
||||
if (const auto getGpuTimestampNs =
|
||||
MGL_BACKEND_SLOT_PTR_CAP(GetGpuTimestampNs, MG_Pipe::kCapTimerQuery)) {
|
||||
MGP_FILL(GetGpuTimestampNs);
|
||||
timestamp = getGpuTimestampNs();
|
||||
}
|
||||
@@ -2265,7 +2279,16 @@ namespace MobileGL::MG_Impl::GLImpl {
|
||||
case GL_TIMESTAMP: {
|
||||
Int64 timestamp = 0;
|
||||
if (!MG_Config::Features.DisableTimerQuery) {
|
||||
if (const auto getGpuTimestampNs = MG_Backend::gBackendFunctionsTable.GL.GetGpuTimestampNs) {
|
||||
// glGetInteger64v(GL_TIMESTAMP). GetGpuTimestampNs is class C - a LIVE GPU
|
||||
// timestamp is not a static property, so R-15 does not reach it - and the
|
||||
// documented answer when it is unavailable is 0 (BackendObject.h:192), which
|
||||
// is correct rather than merely quiet. kCapTimerQuery is the published bit.
|
||||
//
|
||||
// The POINTER-valued macro, so the init-statement below is unchanged in a pull
|
||||
// build and G1 cannot see this edit: the Bool-valued spelling moved this
|
||||
// function by -150 bytes for no behavioural reason at all.
|
||||
if (const auto getGpuTimestampNs =
|
||||
MGL_BACKEND_SLOT_PTR_CAP(GetGpuTimestampNs, MG_Pipe::kCapTimerQuery)) {
|
||||
MGP_FILL(GetGpuTimestampNs);
|
||||
timestamp = getGpuTimestampNs();
|
||||
}
|
||||
|
||||
@@ -13,6 +13,10 @@
|
||||
#include <MG_State/GLState/Core.h>
|
||||
#include <MG_State/GLState/ErrorState/ErrorInfo.h>
|
||||
#include <MG_Impl/Pipe/PipeFill.h>
|
||||
// CONTRACT-P5.md §7 / ID-14: a null check on a GLFunctionsTable slot may not survive into the
|
||||
// client under split - it becomes a caps-mirror read, whatever class the slot itself is in.
|
||||
// The two macros carry that rule; in a pull build each expands to exactly the check it replaced.
|
||||
#include <MG_Remote/Client/SlotCaps.h>
|
||||
|
||||
namespace MobileGL::MG_Impl::GLImpl {
|
||||
namespace {
|
||||
@@ -478,7 +482,7 @@ namespace MobileGL::MG_Impl::GLImpl {
|
||||
const Bool isOcclusionQuery =
|
||||
(target == GL_SAMPLES_PASSED || target == GL_ANY_SAMPLES_PASSED ||
|
||||
target == GL_ANY_SAMPLES_PASSED_CONSERVATIVE) &&
|
||||
MG_Backend::gBackendFunctionsTable.GL.BeginOcclusionQuery != nullptr;
|
||||
MGL_BACKEND_SLOT_CAP(BeginOcclusionQuery, MG_Pipe::kCapOcclusionQuery);
|
||||
const Bool isPipelineStatisticsQuery = IsPipelineStatisticsQueryTarget(target);
|
||||
if (target != GL_TIME_ELAPSED && !isTransformFeedbackQuery && !isOcclusionQuery &&
|
||||
!isPipelineStatisticsQuery) {
|
||||
@@ -528,10 +532,12 @@ namespace MobileGL::MG_Impl::GLImpl {
|
||||
} else if (isTransformFeedbackQuery) {
|
||||
// Prefer real GPU transform-feedback queries (exact with geometry shaders);
|
||||
// the CPU accounting delta stays as the fallback when the backend lacks them.
|
||||
const Bool xfbQuerySupported =
|
||||
MGL_BACKEND_SLOT_CAP(BeginXfbPrimitivesQuery, MG_Pipe::kCapXfbPrimitivesQuery);
|
||||
const auto beginXfbPrimitivesQuery = MG_Backend::gBackendFunctionsTable.GL.BeginXfbPrimitivesQuery;
|
||||
MGP_FILL(BeginXfbPrimitivesQuery);
|
||||
queryObject->backendHandle =
|
||||
beginXfbPrimitivesQuery ? beginXfbPrimitivesQuery(target == GL_PRIMITIVES_GENERATED) : nullptr;
|
||||
xfbQuerySupported ? beginXfbPrimitivesQuery(target == GL_PRIMITIVES_GENERATED) : nullptr;
|
||||
queryObject->counterSnapshot = TransformFeedbackCounterForTarget(target);
|
||||
queryObject->accountedCaptureDrawSnapshot =
|
||||
MG_State::pGLContext->GetTransformFeedbackAccountedCaptureDraws();
|
||||
@@ -541,10 +547,12 @@ namespace MobileGL::MG_Impl::GLImpl {
|
||||
MGP_FILL(BeginOcclusionQuery);
|
||||
queryObject->backendHandle = MG_Backend::gBackendFunctionsTable.GL.BeginOcclusionQuery();
|
||||
} else {
|
||||
const Bool timerQuerySupported =
|
||||
MGL_BACKEND_SLOT_CAP(BeginTimeElapsedQuery, MG_Pipe::kCapTimerQuery);
|
||||
const auto beginTimeElapsedQuery = MG_Backend::gBackendFunctionsTable.GL.BeginTimeElapsedQuery;
|
||||
MGP_FILL(BeginTimeElapsedQuery);
|
||||
queryObject->backendHandle =
|
||||
(!TimerQueryDisabled() && beginTimeElapsedQuery) ? beginTimeElapsedQuery() : nullptr;
|
||||
(!TimerQueryDisabled() && timerQuerySupported) ? beginTimeElapsedQuery() : nullptr;
|
||||
}
|
||||
activeQueryId = id;
|
||||
}
|
||||
@@ -555,7 +563,7 @@ namespace MobileGL::MG_Impl::GLImpl {
|
||||
const Bool isOcclusionQuery =
|
||||
(target == GL_SAMPLES_PASSED || target == GL_ANY_SAMPLES_PASSED ||
|
||||
target == GL_ANY_SAMPLES_PASSED_CONSERVATIVE) &&
|
||||
MG_Backend::gBackendFunctionsTable.GL.BeginOcclusionQuery != nullptr;
|
||||
MGL_BACKEND_SLOT_CAP(BeginOcclusionQuery, MG_Pipe::kCapOcclusionQuery);
|
||||
const Bool isPipelineStatisticsQuery = IsPipelineStatisticsQueryTarget(target);
|
||||
if (target != GL_TIME_ELAPSED && !isTransformFeedbackQuery && !isOcclusionQuery &&
|
||||
!isPipelineStatisticsQuery) {
|
||||
@@ -657,7 +665,10 @@ namespace MobileGL::MG_Impl::GLImpl {
|
||||
|
||||
ResetQueryObjectLocked(queryObject); // discard any previous result
|
||||
queryObject->target = target;
|
||||
const auto queryCounterTimestamp = MG_Backend::gBackendFunctionsTable.GL.QueryCounterTimestamp;
|
||||
const Bool timerQuerySupported =
|
||||
MGL_BACKEND_SLOT_CAP(QueryCounterTimestamp, MG_Pipe::kCapTimerQuery);
|
||||
const auto queryCounterTimestamp =
|
||||
timerQuerySupported ? MG_Backend::gBackendFunctionsTable.GL.QueryCounterTimestamp : nullptr;
|
||||
MGP_FILL(QueryCounterTimestamp);
|
||||
queryObject->backendHandle =
|
||||
(!TimerQueryDisabled() && queryCounterTimestamp) ? queryCounterTimestamp() : nullptr;
|
||||
@@ -782,7 +793,7 @@ namespace MobileGL::MG_Impl::GLImpl {
|
||||
}
|
||||
if (target == GL_SAMPLES_PASSED || target == GL_ANY_SAMPLES_PASSED ||
|
||||
target == GL_ANY_SAMPLES_PASSED_CONSERVATIVE) {
|
||||
const Bool occlusionSupported = MG_Backend::gBackendFunctionsTable.GL.BeginOcclusionQuery != nullptr;
|
||||
const Bool occlusionSupported = MGL_BACKEND_SLOT_CAP(BeginOcclusionQuery, MG_Pipe::kCapOcclusionQuery);
|
||||
*params = occlusionSupported ? (target == GL_SAMPLES_PASSED ? 32 : 1) : 0;
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -10,6 +10,11 @@
|
||||
#include <MG_Backend/BackendObjects.h>
|
||||
#include <MG_State/GLState/Core.h>
|
||||
#include <MG_Impl/Pipe/PipeFill.h>
|
||||
// CONTRACT-P5.md §7 / ID-14: a null check on a GLFunctionsTable slot may not survive into the
|
||||
// client under split - it becomes a caps-mirror read. SlotCaps.h carries the rule and the test
|
||||
// that decides which of its two spellings a site takes; in a pull build both expand to exactly
|
||||
// the check they replaced.
|
||||
#include <MG_Remote/Client/SlotCaps.h>
|
||||
|
||||
namespace MobileGL::MG_Impl::GLImpl {
|
||||
namespace {
|
||||
@@ -56,7 +61,11 @@ namespace MobileGL::MG_Impl::GLImpl {
|
||||
auto* syncObject = new SyncObject;
|
||||
syncObject->condition = condition;
|
||||
syncObject->flags = flags;
|
||||
if (const auto backendFenceSync = MG_Backend::gBackendFunctionsTable.GL.FenceSync) {
|
||||
// The family's ONE gate. FenceSync is class C under split, and "absent" is the
|
||||
// answer the whole fallback chain below is written against: every later site already
|
||||
// checks syncObject->backendHandle, which stays null from here. The POINTER-valued
|
||||
// macro keeps the init-statement byte-identical in a pull build (G1).
|
||||
if (const auto backendFenceSync = MGL_BACKEND_SLOT_PTR_LOCAL(FenceSync)) {
|
||||
MGP_FILL(FenceSync);
|
||||
syncObject->backendHandle = backendFenceSync();
|
||||
}
|
||||
|
||||
@@ -31,6 +31,11 @@
|
||||
#include <MG_Util/Math/FixedPointConversion.h>
|
||||
#include <MG_State/GLState/TextureState/TextureObjectBuffer.h>
|
||||
#include <MG_Impl/Pipe/PipeFill.h>
|
||||
// CONTRACT-P5.md §7 / ID-14: a null check on a GLFunctionsTable slot may not survive into the
|
||||
// client under split - it becomes a caps-mirror read. SlotCaps.h carries the rule and the test
|
||||
// that decides which of its two spellings a site takes; in a pull build both expand to exactly
|
||||
// the check they replaced.
|
||||
#include <MG_Remote/Client/SlotCaps.h>
|
||||
// P4a, ID-18 M2. The ONE door MG_State and MG_Impl have into the client's emitters; the three
|
||||
// call sites below are declarations only, exactly as the frontend's mutators are.
|
||||
#include <MG_Pipe/PipeMutation.h>
|
||||
@@ -6534,7 +6539,7 @@ namespace MobileGL::MG_Impl::GLImpl {
|
||||
GLenum type, GLsizei bufSize, void* pixels, const char* caller) {
|
||||
if (MG_Backend::pActiveBackendObject != nullptr &&
|
||||
MG_Backend::pActiveBackendObject->GetBackendType() == BackendType::DirectVulkan &&
|
||||
MG_Backend::gBackendFunctionsTable.GL.GetTextureImage != nullptr) {
|
||||
MGL_BACKEND_SLOT_LOCAL(GetTextureImage)) {
|
||||
MGP_FILL(GetTextureImage);
|
||||
MG_Backend::gBackendFunctionsTable.GL.GetTextureImage(textureObject, uploadTarget, level, format, type,
|
||||
bufSize, pixels);
|
||||
@@ -6796,7 +6801,7 @@ namespace MobileGL::MG_Impl::GLImpl {
|
||||
|
||||
void GetTexImage(GLenum target, GLint level, GLenum format, GLenum type, GLvoid* pixels) {
|
||||
if (!GetTexImage_State(target, level, format, type, pixels)) return;
|
||||
if (MG_Backend::gBackendFunctionsTable.GL.GetTexImage != nullptr) {
|
||||
if (MGL_BACKEND_SLOT_LOCAL(GetTexImage)) {
|
||||
GetTexImage_Backend(target, level, format, type, pixels);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -44,6 +44,7 @@
|
||||
#include <MG_Pipe/MGPipe.h>
|
||||
#include <MG_Pipe/MGPipeRenderStateSpans.h>
|
||||
#include <MG_Pipe/PipeApply.h>
|
||||
#include <MG_Pipe/PipeRoute.h>
|
||||
#include <MG_Util/Metrics/PipeStats.h>
|
||||
|
||||
#include <cstring>
|
||||
@@ -154,7 +155,7 @@ namespace MobileGL::MG_Pipe {
|
||||
// minted from a neighbour rather than from nothing.
|
||||
desc.ChunkMask = kAllPipelineChunks;
|
||||
desc.Blob.Size = kMGPipePipelineChunkBytes;
|
||||
MGPipeApplyCreateRenderState(desc, bytes.data());
|
||||
MGPipeRouteCreateRenderState(desc, bytes.data());
|
||||
payloadBytes += sizeof(MGPRenderStateDesc) + kMGPipePipelineChunkBytes;
|
||||
|
||||
Entry entry;
|
||||
@@ -175,7 +176,7 @@ namespace MobileGL::MG_Pipe {
|
||||
MGPHandleOnly handle{};
|
||||
handle.Handle = m_entries[index].Cso;
|
||||
handle.Kind = static_cast<Uint32>(MGPipeKind::RenderStateCso);
|
||||
MGPipeApplyDeleteRenderState(handle);
|
||||
MGPipeRouteDeleteRenderState(handle);
|
||||
MGPipeSlots().Free(MGPipeKind::RenderStateCso, m_entries[index].Cso);
|
||||
m_entries[index] = m_entries.back();
|
||||
m_entries.pop_back();
|
||||
|
||||
@@ -32,6 +32,7 @@
|
||||
#include <MG_Impl/Pipe/Tracker.h>
|
||||
#include <MG_Pipe/MGPipe.h>
|
||||
#include <MG_Pipe/PipeApply.h>
|
||||
#include <MG_Pipe/PipeRoute.h>
|
||||
#include <MG_State/GLState/Core.h>
|
||||
#include <MG_Util/Metrics/PipeStats.h>
|
||||
|
||||
@@ -456,7 +457,7 @@ namespace MobileGL::MG_Pipe {
|
||||
m_lastDraw = state;
|
||||
if (state.Target == static_cast<Uint8>(MGPipeFramebufferTarget::Both)) m_lastRead = state;
|
||||
}
|
||||
MGPipeApplySetFramebufferState(state);
|
||||
MGPipeRouteSetFramebufferState(state);
|
||||
++m_emissions;
|
||||
if (MG_Util::PipeStats::Enabled()) {
|
||||
MG_Util::PipeStats::AddCalls(MG_Util::PipeStats::CallClass::FramebufferEmissions, 1);
|
||||
|
||||
@@ -38,6 +38,7 @@
|
||||
#include <MG_Impl/Pipe/SlotAllocator.h>
|
||||
#include <MG_Pipe/MGPipe.h>
|
||||
#include <MG_Pipe/PipeApply.h>
|
||||
#include <MG_Pipe/PipeRoute.h>
|
||||
#include <MG_Pipe/PipeMutation.h>
|
||||
#include <MG_State/GLState/Core.h>
|
||||
#include <MG_State/GLState/TextureState/TextureState.h>
|
||||
@@ -126,7 +127,7 @@ namespace MobileGL::MG_Pipe {
|
||||
m_lastImages.Start = 0;
|
||||
m_lastImages.Count = count;
|
||||
m_lastImages.ContentHash = hash;
|
||||
MGPipeApplySetShaderImages(m_lastImages, m_entries.data());
|
||||
MGPipeRouteSetShaderImages(m_lastImages, m_entries.data());
|
||||
++m_imageSets;
|
||||
if (MG_Util::PipeStats::Enabled()) {
|
||||
MG_Util::PipeStats::AddCalls(MG_Util::PipeStats::CallClass::ShaderImageEmissions, 1);
|
||||
|
||||
@@ -36,9 +36,20 @@
|
||||
#include <MG_Impl/Pipe/VertexInputEmit.h>
|
||||
#include <MG_Pipe/MGPipeRenderStateSpans.h>
|
||||
#include <MG_Pipe/PipeApply.h>
|
||||
#include <MG_Pipe/PipeRoute.h>
|
||||
#include <MG_Pipe/PipeMutation.h>
|
||||
#include <Config.h>
|
||||
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
// R-8 (c1): the client's liveness gates read the caps mirror, never MGPipeGetResourceOps().
|
||||
// Behind the build option for G1's reason - nothing under MG_Remote may be reachable from a
|
||||
// pull build - and every use below is additionally gated on the resolved TRANSPORT, because
|
||||
// build-split runs MOBILEGL_TRANSPORT=monolith in every unit and integration-gpu lane and those
|
||||
// lanes must keep answering exactly what they answered before.
|
||||
#include <MG_Remote/Client/CapsMirror.h>
|
||||
#include <MG_Remote/Client/WireTables.h>
|
||||
#endif
|
||||
|
||||
#include <atomic>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
@@ -609,12 +620,38 @@ namespace MobileGL::MG_Pipe {
|
||||
}
|
||||
} // namespace
|
||||
|
||||
// R-8 (c1). THE SECOND CONJUNCT MOVES UNDER SPLIT, AND ONLY UNDER SPLIT.
|
||||
//
|
||||
// `MGPipeGetResourceOps() != nullptr` asks "has a backend registered the consumer". That
|
||||
// table is the SERVER's registration and it is a PROCESS-WIDE global (PipeApply.cpp:402):
|
||||
// under inproc a client reading it answers correctly BY ACCIDENT, and under spawn the
|
||||
// client process has no backend at all, so the read answers null and five record families
|
||||
// stop emitting - silently, while the emitters go on clearing their per-level dirty flags
|
||||
// on the acceptance they never asked for. That is ID-39's 66 lost DirectVulkan uploads with
|
||||
// a wire in between. The client asks the caps mirror instead, which carries the answer the
|
||||
// SERVER gave at the handshake (CallMask bits 32..47).
|
||||
//
|
||||
// s1 made the server end Fatal when nobody sets the mask; this is the client end.
|
||||
Bool MGPipeResourceSubsystemEnabled() {
|
||||
return (MG_Config::Features.PipePush & kMGPipeSubsystemResources) != 0 &&
|
||||
MGPipeGetResourceOps() != nullptr;
|
||||
if ((MG_Config::Features.PipePush & kMGPipeSubsystemResources) == 0) return false;
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
if (MG_Config::Transport != MG_Config::TransportMode::Monolith) {
|
||||
return MG_Remote::Client::CapsMirrorInstance().ServerConsumes(kMGPipeSubsystemResources);
|
||||
}
|
||||
#endif
|
||||
return MGPipeGetResourceOps() != nullptr;
|
||||
}
|
||||
|
||||
Bool MGPipeResourceOpsHaveSubDataResident() {
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
if (MG_Config::Transport != MG_Config::TransportMode::Monolith) {
|
||||
// CONTRACT-P5.md §7's THIRD NAMED CAPABILITY PROBE. `ops->SubDataResident != nullptr`
|
||||
// is not a safety check - it decides whether the resident-upload path EXISTS - and
|
||||
// under split there is no op table here to probe. kCapResidentSubData is the bit the
|
||||
// server publishes for exactly this question.
|
||||
return MG_Remote::Client::CapsMirrorInstance().HasCap(kCapResidentSubData);
|
||||
}
|
||||
#endif
|
||||
const MGPipeResourceOps* ops = MGPipeGetResourceOps();
|
||||
return ops != nullptr && ops->SubDataResident != nullptr;
|
||||
}
|
||||
@@ -642,7 +679,7 @@ namespace MobileGL::MG_Pipe {
|
||||
// LATCHED, so the destroy is gated on whether this create actually went out rather
|
||||
// than on whether a table is still registered when the object dies (D-L, m12).
|
||||
tracker.NotePublished(handle);
|
||||
MGPipeApplyResourceCreate(desc);
|
||||
MGPipeRouteResourceCreate(desc);
|
||||
}
|
||||
|
||||
void MGPipeEmitResourceRespecify(BufferObject& buffer) {
|
||||
@@ -675,7 +712,7 @@ namespace MobileGL::MG_Pipe {
|
||||
MGPipeBuildResourceDesc(buffer, handle, bindMask, /*storageDefined=*/false);
|
||||
tracker.NoteDesc(createDesc, true);
|
||||
tracker.NotePublished(handle);
|
||||
MGPipeApplyResourceCreate(createDesc);
|
||||
MGPipeRouteResourceCreate(createDesc);
|
||||
}
|
||||
const MGPResourceDesc desc = MGPipeBuildResourceDesc(buffer, handle, bindMask, true);
|
||||
tracker.NoteDesc(desc, false);
|
||||
@@ -688,7 +725,58 @@ namespace MobileGL::MG_Pipe {
|
||||
// allocation and only it is allowed one. In monolith the acknowledgement is
|
||||
// ((void)0), because the applier is one function call away and has already run by
|
||||
// the time this returns; the transport wires the doorbell to that same predicate.
|
||||
MGPipeApplyResourceRespecify(desc, initialBytes);
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
// R-13.3's MISSING PRODUCER, and it is the reason the first joint inproc run died.
|
||||
// CONTRACT-P5 §2 row 19 rules that `initialBytes` is ALWAYS nullptr under split and
|
||||
// that "initial content arrives as ResourceSubData records immediately after this
|
||||
// one" - but nothing emitted those records, so the split arm's refusal
|
||||
// (Fatal{UncarriedInitialBytes}) fired on the first glBufferData with data, which is
|
||||
// the first thing every scenario does.
|
||||
//
|
||||
// IT IS THE CONTRACT'S OWN PRESCRIBED ROUTE, not a new one: "the chosen route reuses a
|
||||
// path that is already chunked (MGPipeForEachSubDataRecordRange) and already
|
||||
// acceptance-gated; it costs one extra record". So the respecify defines the storage
|
||||
// and the walk below ships the bytes, through the same emitter every later
|
||||
// glBufferSubData uses - which also means the HasLiveHostWrites bit and the
|
||||
// acceptance latch are computed in exactly one place instead of two.
|
||||
//
|
||||
// SPLIT-ONLY, and that is load-bearing for G2: under monolith the applier reads
|
||||
// `initialBytes` directly and a second upload would be a real behaviour change in the
|
||||
// arm the split arm is measured against.
|
||||
//
|
||||
// ROLE-AWARE (M5). Under inproc the apply thread reaches this very emitter when the
|
||||
// server's own backend respecifies a buffer (c1-v2 §4 R-17.3: that is where
|
||||
// Fatal{BarrierTimeout, "ResourceRespecify"} from mgl-srv-apply came from). On that
|
||||
// thread this branch would emit CLIENT wire records - which the server role does not
|
||||
// produce, so ClientWireRecordsEmitted() would not move and the self-check below would
|
||||
// abort the SERVER by name; it would also run the respecify(nullptr)+follow-up shape,
|
||||
// giving the server role a path monolith does not have. So the server role takes the
|
||||
// ELSE below, exactly as monolith does. RunsAsTheServerRole() is v1's
|
||||
// ServerLoop::OnApplyThread(), false on the GL thread that owns this fill.
|
||||
if (MG_Config::Transport != MG_Config::TransportMode::Monolith &&
|
||||
!MG_Remote::Client::RunsAsTheServerRole() && initialBytes != nullptr) {
|
||||
MGPipeRouteResourceRespecify(desc, nullptr);
|
||||
// COUNTED, NOT ASSUMED, and this is the only thing that can gate the follow-up at
|
||||
// all. Dropping the walk below leaves a respecify that went out with nullptr and
|
||||
// bytes that nothing carried - and no P5 scenario's PICTURE changes, because every
|
||||
// one of them re-uploads its vertices through the ordinary dirty path afterwards.
|
||||
// So the statement "the content followed" is made HERE, against the client's own
|
||||
// record ordinal, rather than left to a lane that cannot see it. Remove the call
|
||||
// below and this aborts by name on the first glBufferData that carries data.
|
||||
const Uint64 before = MG_Remote::Client::ClientWireRecordsEmitted();
|
||||
MGPipeEmitResourceSubData(buffer, 0, static_cast<SizeT>(buffer.GetSize()));
|
||||
if (MG_Remote::Client::ClientWireRecordsEmitted() == before) {
|
||||
MGLOG_F("MGPipe: Fatal{InitialBytesNotCarried, \"resource_respecify\"} - the "
|
||||
"respecify crossed with initialBytes = nullptr (R-13.3) and the "
|
||||
"resource_subdata records that were supposed to follow it emitted "
|
||||
"NOTHING, so %llu bytes of initial content exist on no side of the wire",
|
||||
static_cast<unsigned long long>(buffer.GetSize()));
|
||||
std::abort();
|
||||
}
|
||||
return;
|
||||
}
|
||||
#endif
|
||||
MGPipeRouteResourceRespecify(desc, initialBytes);
|
||||
}
|
||||
|
||||
void MGPipeEmitResourceSubData(BufferObject& buffer, SizeT offset, SizeT size) {
|
||||
@@ -702,7 +790,20 @@ namespace MobileGL::MG_Pipe {
|
||||
// one was emitted, so this cannot be false - but a zeroed record (null
|
||||
// handle, size 0) is not the answer if that pre-pass is ever relaxed.
|
||||
if (!MGPipeBuildSubDataRecord(handle, at, length, record, /*verbatimShadow=*/true)) return;
|
||||
MGPipeApplyResourceSubData(record, base + at);
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
// P5 (b1): the live-host-writes bit rides the content record, because
|
||||
// "someone may be writing these bytes without telling you" is a fact about the
|
||||
// CONTENT and not about the storage. It is set from the object's PUBLISHED
|
||||
// value rather than from a live IsMapped() read so that the record and the
|
||||
// edge that announced it can never disagree. MGPipeBuildSubDataRecord does not
|
||||
// take the object, which is why it is set here and not in the builder.
|
||||
record.HasLiveHostWrites = buffer.HasLiveHostWritesForWire() ? 1 : 0;
|
||||
#endif
|
||||
// `length` is this chunk's byte count, which the record also declares
|
||||
// (MGPipeBuildSubDataRecord writes it into the destination range) - passed
|
||||
// rather than re-read so the staged run and the record's own claim come from
|
||||
// one number.
|
||||
MGPipeRouteResourceSubData(record, base + at, length);
|
||||
});
|
||||
if (!encodable) {
|
||||
MGLOG_E_ONCE("MGPipe: resource_subdata range [%llu, +%llu) on buffer %u cannot be encoded - "
|
||||
@@ -723,8 +824,17 @@ namespace MobileGL::MG_Pipe {
|
||||
// store, or the pattern FillSubData expanded locally, and neither is this
|
||||
// client's untransformed shadow of the level.
|
||||
if (!MGPipeBuildSubDataRecord(handle, at, length, record, /*verbatimShadow=*/false)) return;
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
// P5 (b1): THE SECOND CONTENT EMITTER, and it has to speak for the same reason
|
||||
// the first does. ApplyBufferWrite ASSIGNS the bit - a content record emitted
|
||||
// while nothing maps the buffer is how the state goes back to false - so a
|
||||
// resident sub-data that stayed silent would write false over a live write
|
||||
// map. `glBufferSubData` against a persistently mapped arena is legal and is
|
||||
// the ordinary Flywheel/Create shape, so that is not a corner.
|
||||
record.HasLiveHostWrites = buffer.HasLiveHostWritesForWire() ? 1 : 0;
|
||||
#endif
|
||||
// The application's STAGING store, valid for the duration of the call only.
|
||||
MGPipeApplyBufferSubDataResident(record, base + (at - offset));
|
||||
MGPipeRouteBufferSubDataResident(record, base + (at - offset), length);
|
||||
});
|
||||
if (!encodable) {
|
||||
MGLOG_E_ONCE("MGPipe: buffer_subdata_resident range [%llu, +%llu) on buffer %u cannot be encoded",
|
||||
@@ -744,7 +854,31 @@ namespace MobileGL::MG_Pipe {
|
||||
// arm reads INVALIDATE_RANGE / INVALIDATE_BUFFER / UNSYNCHRONIZED per call to choose
|
||||
// between a map+memcpy+unmap and an upload, so merging them here would change which.
|
||||
record.AccessFlags = accessFlags;
|
||||
MGPipeApplyResourceFlushRange(record, buffer.MappedData() + offset);
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
// R-13.2's MISSING PRODUCER, the twin of the respecify one above, and the cause of the
|
||||
// seven PersistentCoherentMapScenario aborts on the first joint inproc run:
|
||||
// Fatal{ProtocolCorruption} resource_flush_range {slot=1, gen=0, glName=1}:
|
||||
// a non-empty flush carries no bytes (offset=0, size=120, storage=120 bytes)
|
||||
//
|
||||
// CONTRACT-P5 §2 row 20 rules that this record carries NO bytes under split - it is a
|
||||
// {range, AccessFlags} control record, and a blobref here "would be a second,
|
||||
// forgeable way to say the same thing" - and that "the bytes of [Offset, Offset+Size)
|
||||
// arrive AHEAD of it as ResourceSubData records covering exactly that range". Nothing
|
||||
// emitted those records, so v1's StagedShadowStore had nothing staged for the range
|
||||
// the flush names, which is precisely the refusal ID-37 asked it to make rather than
|
||||
// silently reading the bytes again.
|
||||
//
|
||||
// EXACTLY THAT RANGE, not the whole buffer: the flush's own [offset, size) is what
|
||||
// the ladder rewrites, and staging more would be the coverage WIDENING ID-37 forbids.
|
||||
// Split-only, for the respecify's G2 reason - and ROLE-AWARE for M5's reason, the twin of
|
||||
// the respecify branch above: the apply thread flushing the server's own buffer emits no
|
||||
// client wire records, so it takes the plain route below rather than this split follow-up.
|
||||
if (MG_Config::Transport != MG_Config::TransportMode::Monolith &&
|
||||
!MG_Remote::Client::RunsAsTheServerRole() && size != 0) {
|
||||
MGPipeEmitResourceSubData(buffer, offset, size);
|
||||
}
|
||||
#endif
|
||||
MGPipeRouteResourceFlushRange(record, buffer.MappedData() + offset);
|
||||
}
|
||||
|
||||
void MGPipeEmitResourceReadback(BufferObject& buffer) {
|
||||
@@ -758,7 +892,7 @@ namespace MobileGL::MG_Pipe {
|
||||
record.Size = buffer.GetSize();
|
||||
// The answer travels back through MGPipeClientOnBufferWriteback, and the server's
|
||||
// epoch bump happens AFTER that writeback, never before.
|
||||
MGPipeApplyResourceReadback(record);
|
||||
MGPipeRouteResourceReadback(record);
|
||||
}
|
||||
|
||||
// NO UnmapPersistent PRODUCER IN P3a, AND THAT IS DELIBERATE. The catalogue has the call
|
||||
@@ -781,7 +915,7 @@ namespace MobileGL::MG_Pipe {
|
||||
if (MG_Util::PipeStats::Enabled()) {
|
||||
MG_Util::PipeStats::AddCalls(MG_Util::PipeStats::CallClass::MapPersistentRoundtrips, 1);
|
||||
}
|
||||
return MGPipeApplyMapPersistent(BufferHandleOnly(handle), buffer.GetSize(), buffer.MappedData());
|
||||
return MGPipeRouteMapPersistent(BufferHandleOnly(handle), buffer.GetSize(), buffer.MappedData());
|
||||
}
|
||||
|
||||
Bool MGPipeEmitResourceDestroyAndFree(BufferObject& buffer) {
|
||||
@@ -796,7 +930,7 @@ namespace MobileGL::MG_Pipe {
|
||||
const Bool published = tracker.WasPublished(handle);
|
||||
if (published) {
|
||||
tracker.NoteDestroy();
|
||||
MGPipeApplyResourceDestroy(BufferHandleOnly(handle));
|
||||
MGPipeRouteResourceDestroy(BufferHandleOnly(handle));
|
||||
}
|
||||
// THE ORDER IS FIXED (D-L): the applier clears the record and the backend drops its
|
||||
// twin while the handle still resolves, and only then does the slot go back. Free
|
||||
@@ -836,7 +970,7 @@ namespace MobileGL::MG_Pipe {
|
||||
MGPHandleOnly only{};
|
||||
only.Handle = handle;
|
||||
only.Kind = static_cast<Uint32>(MGPipeKind::VertexElementsCso);
|
||||
MGPipeApplyDeleteVertexElements(only);
|
||||
MGPipeRouteDeleteVertexElements(only);
|
||||
emitter.NoteRecordDestroyed(handle);
|
||||
}
|
||||
|
||||
@@ -918,8 +1052,21 @@ namespace MobileGL::MG_Pipe {
|
||||
// MGPipeEmitResourceRespecify above uses for buffers) publishes it. Nothing here needs
|
||||
// to remember the window.
|
||||
Bool P4aFamilyHasItsConsumer(Uint64 subsystem) {
|
||||
return (subsystem & kMGPipeP4aFamilySubsystems) == 0 ||
|
||||
MGPipeGetResourceOps() != nullptr;
|
||||
if ((subsystem & kMGPipeP4aFamilySubsystems) == 0) return true;
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
// R-8 (c1), the same move as MGPipeResourceSubsystemEnabled's and for the same
|
||||
// reason. ALL FOUR FAMILIES RIDE THE ONE SIGNAL, exactly as they do in monolith:
|
||||
// the paragraph above explains why the resource consumer IS the texture family's
|
||||
// consumer, and the split spelling of "a backend registered the resource op table"
|
||||
// is "the server published the resource subsystem's consumer bit". Asking per
|
||||
// family here would be a NEW rule, and a client that withheld more than the server
|
||||
// refuses leaves the server's handle arm live with no records to read.
|
||||
if (MG_Config::Transport != MG_Config::TransportMode::Monolith) {
|
||||
return MG_Remote::Client::CapsMirrorInstance().ServerConsumes(
|
||||
kMGPipeSubsystemResources);
|
||||
}
|
||||
#endif
|
||||
return MGPipeGetResourceOps() != nullptr;
|
||||
}
|
||||
|
||||
// ================================================================================
|
||||
@@ -1377,9 +1524,21 @@ namespace MobileGL::MG_Pipe {
|
||||
// Step 1, shared: the wire delete goes out FIRST and only for a PUBLISHED handle, and
|
||||
// the latch is cleared with it so a second death path - a composite's two, a backend's
|
||||
// redundant notice - cannot emit a second delete for a record that is already gone.
|
||||
Bool EmitDeleteIfPublished(MGPipeKind kind, MGPipeHandle handle, void (*apply)(const MGPHandleOnly&)) {
|
||||
//
|
||||
// `route` IS A MGPipeRoute<Name> AND NEVER A MGPipeApply<Name> (B1). R-17 converted the
|
||||
// 40 direct applier CALLS to route calls by renaming `MGPipeApply<Name>(` -> but these
|
||||
// five sites take the entry point BY ADDRESS, `&MGPipeApply<Name>`, so the call-expression
|
||||
// rename missed them and four routed rows (DeleteSamplerView, DeleteShaderState,
|
||||
// DeleteSamplerState, ResourceDestroy for textures/renderbuffers) still ran the applier
|
||||
// synchronously on the GL thread under split - two writers on g_applier with the barrier
|
||||
// not consulted, and under spawn a silent no-op that leaks every one of those objects.
|
||||
// The parameter type is the route's, which is byte-identical to the applier's
|
||||
// (const MGPHandleOnly&, void return), so the fix is `&MGPipeRoute<Name>` at the five call
|
||||
// sites; PipeCatalogue.FrontendNeverTakesAnApplierAddress checks MG_Impl in every unit lane.
|
||||
Bool EmitDeleteIfPublished(MGPipeKind kind, MGPipeHandle handle,
|
||||
void (*route)(const MGPHandleOnly&)) {
|
||||
if (!MGPipeHandleIsPublished(kind, handle)) return false;
|
||||
apply(HandleOnly(kind, handle));
|
||||
route(HandleOnly(kind, handle));
|
||||
MGPipeNoteHandleUnpublished(kind, handle);
|
||||
return true;
|
||||
}
|
||||
@@ -1400,7 +1559,7 @@ namespace MobileGL::MG_Pipe {
|
||||
const MGPipeHandle handle =
|
||||
MGPipeSlots().FindByLifetimeId(MGPipeKind::SamplerViewCso, lifetimeId);
|
||||
const Bool published =
|
||||
EmitDeleteIfPublished(MGPipeKind::SamplerViewCso, handle, &MGPipeApplyDeleteSamplerView);
|
||||
EmitDeleteIfPublished(MGPipeKind::SamplerViewCso, handle, &MGPipeRouteDeleteSamplerView);
|
||||
ForwardWhenWired<kMGPipeWiredSamplerSubsystem>(
|
||||
MGPipeSamplerEmitterInstance(), [&](auto& emitter) { emitter.NoteRecordDestroyed(handle); });
|
||||
// THE NOTICE IS RAISED FOR THIS KIND TOO, and the reason it once was not is wrong:
|
||||
@@ -1421,7 +1580,7 @@ namespace MobileGL::MG_Pipe {
|
||||
Bool MGPipeEmitTextureDestroyAndFree(Uint64 lifetimeId) {
|
||||
const MGPipeHandle handle = MGPipeSlots().FindByLifetimeId(MGPipeKind::Texture, lifetimeId);
|
||||
const Bool published =
|
||||
EmitDeleteIfPublished(MGPipeKind::Texture, handle, &MGPipeApplyResourceDestroy);
|
||||
EmitDeleteIfPublished(MGPipeKind::Texture, handle, &MGPipeRouteResourceDestroy);
|
||||
// The emitter retires its entry while the handle still resolves (C-2): the drain list
|
||||
// drops the dead texture's levels, the raw pointer goes, the built-in sampler's cache
|
||||
// reference is given back, the latches and the sticky mask are cleared.
|
||||
@@ -1462,7 +1621,7 @@ namespace MobileGL::MG_Pipe {
|
||||
const MGPipeHandle handle =
|
||||
MGPipeSlots().FindByLifetimeId(MGPipeKind::Renderbuffer, lifetimeId);
|
||||
const Bool published =
|
||||
EmitDeleteIfPublished(MGPipeKind::Renderbuffer, handle, &MGPipeApplyResourceDestroy);
|
||||
EmitDeleteIfPublished(MGPipeKind::Renderbuffer, handle, &MGPipeRouteResourceDestroy);
|
||||
ForwardWhenWired<kMGPipeWiredTextureSubsystem>(
|
||||
MGPipeTextureEmitterInstance(), [&](auto& emitter) { emitter.NoteRenderbufferDied(handle); });
|
||||
NotifyAndFree(MGPipeKind::Renderbuffer, lifetimeId, handle);
|
||||
@@ -1499,7 +1658,7 @@ namespace MobileGL::MG_Pipe {
|
||||
const MGPipeHandle handle =
|
||||
MGPipeSlots().FindByLifetimeId(MGPipeKind::SamplerCso, lifetimeId);
|
||||
const Bool published =
|
||||
EmitDeleteIfPublished(MGPipeKind::SamplerCso, handle, &MGPipeApplyDeleteSamplerState);
|
||||
EmitDeleteIfPublished(MGPipeKind::SamplerCso, handle, &MGPipeRouteDeleteSamplerState);
|
||||
// NOTHING TO RETIRE IN AN EMITTER FOR THIS KIND, stated rather than implied: a sampler
|
||||
// CSO is content-addressed and belongs to a value, so no emitter keeps an entry under
|
||||
// a SamplerObject's handle - the cache's entries are keyed by value and reference
|
||||
@@ -1520,7 +1679,7 @@ namespace MobileGL::MG_Pipe {
|
||||
const MGPipeHandle handle =
|
||||
MGPipeSlots().FindByLifetimeId(MGPipeKind::ShaderCso, lifetimeId);
|
||||
const Bool published =
|
||||
EmitDeleteIfPublished(MGPipeKind::ShaderCso, handle, &MGPipeApplyDeleteShaderState);
|
||||
EmitDeleteIfPublished(MGPipeKind::ShaderCso, handle, &MGPipeRouteDeleteShaderState);
|
||||
ForwardWhenWired<kMGPipeWiredProgramSubsystem>(
|
||||
MGPipeProgramEmitterInstance(), [&](auto& emitter) { emitter.NoteRecordDestroyed(handle); });
|
||||
NotifyAndFree(MGPipeKind::ShaderCso, lifetimeId, handle);
|
||||
@@ -1551,36 +1710,59 @@ namespace MobileGL::MG_Pipe {
|
||||
Bool PipeInputs::IsLive() const { return LiveContext() != nullptr; }
|
||||
|
||||
// ---- the seven F-class forwarders ----
|
||||
//
|
||||
// P5 (R-7.3, CONTRACT-P5.md table 2's "the seven sticky forwards"): each of them now opens
|
||||
// with MGP_STICKY_FORWARD_PULL. They are THE SEVEN THAT HAND THE SERVER A RAW FRONTEND
|
||||
// OBJECT OR WRITE INTO THE FRONTEND, and they are also the only fields the poison cannot
|
||||
// see - they carry no MGP_INPUT_CHECK at all, by the declared exception argued at
|
||||
// PipeInputs.h's F-class block, so freshness never reaches them and the exit gate was
|
||||
// structurally blind on exactly the seven most dangerous rows. The hook is a no-op outside
|
||||
// a server-stamped verb, so InvalidateCompileEnv keeps being reachable from backend
|
||||
// initialisation - the case the exemption was written for - and every monolith lane, split
|
||||
// build included, behaves as it does today.
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
#define MGP_STICKY_FORWARD_PULL(Field) MGPipeStickyForwardPull(MGPipeInputField::Field)
|
||||
#else
|
||||
#define MGP_STICKY_FORWARD_PULL(Field) ((void)0)
|
||||
#endif
|
||||
|
||||
SizeT PipeInputs::GetBufferBindingPointCount(BufferTarget target) const {
|
||||
MGP_STICKY_FORWARD_PULL(GetBufferBindingPointCount);
|
||||
const auto* ctx = LiveContext();
|
||||
return ctx != nullptr ? ctx->GetBufferBindingPointCount(target) : 0;
|
||||
}
|
||||
|
||||
const SharedPtr<PipeInputs::ProgramObject>& PipeInputs::GetProgramObject(Uint index) {
|
||||
MGP_STICKY_FORWARD_PULL(GetProgramObject);
|
||||
auto* ctx = LiveContext();
|
||||
return ctx != nullptr ? ctx->GetProgramObject(index) : NullShared<ProgramObject>();
|
||||
}
|
||||
|
||||
const SharedPtr<PipeInputs::ITextureObject>& PipeInputs::GetTextureObject(Uint index) {
|
||||
MGP_STICKY_FORWARD_PULL(GetTextureObject);
|
||||
auto* ctx = LiveContext();
|
||||
return ctx != nullptr ? ctx->GetTextureObject(index) : NullShared<ITextureObject>();
|
||||
}
|
||||
|
||||
Bool PipeInputs::HasOpenTransformFeedbackSpan(Uint64 lifetimeId) const {
|
||||
MGP_STICKY_FORWARD_PULL(HasOpenTransformFeedbackSpan);
|
||||
const auto* ctx = LiveContext();
|
||||
return ctx != nullptr && ctx->HasOpenTransformFeedbackSpan(lifetimeId);
|
||||
}
|
||||
|
||||
void PipeInputs::InvalidateCompileEnv() {
|
||||
MGP_STICKY_FORWARD_PULL(InvalidateCompileEnv);
|
||||
if (auto* ctx = LiveContext()) ctx->InvalidateCompileEnv();
|
||||
}
|
||||
|
||||
Bool PipeInputs::ValidateProgramName(Uint index) const {
|
||||
MGP_STICKY_FORWARD_PULL(ValidateProgramName);
|
||||
const auto* ctx = LiveContext();
|
||||
return ctx != nullptr && ctx->ValidateProgramName(index);
|
||||
}
|
||||
|
||||
void PipeInputs::RecordError(ErrorCode code, UniquePtr<ErrorInfo> info) {
|
||||
MGP_STICKY_FORWARD_PULL(RecordError);
|
||||
auto* ctx = LiveContext();
|
||||
if (ctx == nullptr) {
|
||||
MGLOG_E_ONCE("PipeInputs::RecordError: no live context, dropping error %d", static_cast<int>(code));
|
||||
@@ -1588,6 +1770,7 @@ namespace MobileGL::MG_Pipe {
|
||||
}
|
||||
ctx->RecordError(code, Move(info));
|
||||
}
|
||||
#undef MGP_STICKY_FORWARD_PULL
|
||||
|
||||
// P3a D-H2.1. The draw's RAW vertex-fetch base instance, set immediately before the fill
|
||||
// at the three *BaseInstance draw entry points. It replaces the ambient process global
|
||||
@@ -1610,6 +1793,9 @@ namespace MobileGL::MG_Pipe {
|
||||
// Same bump the next fill would make, without a verb to fill from: no field is
|
||||
// stamped, so every stamp this verb made falls behind the serial.
|
||||
++MGPipeFillAccess::Filled(inputs).CurrentVerbSerial;
|
||||
#endif
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
MGPipeServerClearVerbBoundary();
|
||||
#endif
|
||||
MGPipeFillAccess::SetVerb(inputs, MGPipeVerb::kVerbCount);
|
||||
// The pending base instance belongs to the verb that was about to run, so leaving
|
||||
@@ -2010,7 +2196,7 @@ namespace MobileGL::MG_Pipe {
|
||||
Uint64 EmitPixelPackState(GLContext& ctx) {
|
||||
MGPPixelPackState pack{};
|
||||
pack.Pack = ctx.GetPixelStoreParameters(false);
|
||||
MGPipeApplySetPixelPackState(pack);
|
||||
MGPipeRouteSetPixelPackState(pack);
|
||||
return sizeof(MGPPixelPackState);
|
||||
}
|
||||
|
||||
@@ -2023,7 +2209,7 @@ namespace MobileGL::MG_Pipe {
|
||||
patch.Vertices = live.PatchVertices;
|
||||
for (SizeT i = 0; i < 4; ++i) patch.Outer[i] = live.PatchDefaultOuterLevel[i];
|
||||
for (SizeT i = 0; i < 2; ++i) patch.Inner[i] = live.PatchDefaultInnerLevel[i];
|
||||
MGPipeApplySetPatchState(patch);
|
||||
MGPipeRouteSetPatchState(patch);
|
||||
return sizeof(MGPPatchState);
|
||||
}
|
||||
|
||||
@@ -2112,7 +2298,7 @@ namespace MobileGL::MG_Pipe {
|
||||
}
|
||||
if (header.Count == 0) return 0;
|
||||
g_attribDefaultLastHeader = header;
|
||||
MGPipeApplySetVertexAttribDefaults(header, tail.data());
|
||||
MGPipeRouteSetVertexAttribDefaults(header, tail.data());
|
||||
|
||||
// Did the applier reproduce it? Byte for byte, over the attributes this call
|
||||
// named - anything less would be a mirror that disagrees with the frontend in a
|
||||
@@ -2181,7 +2367,7 @@ namespace MobileGL::MG_Pipe {
|
||||
block.CapabilityBits |= Uint64{1} << i;
|
||||
}
|
||||
}
|
||||
MGPipeApplySetResidualValueState(block);
|
||||
MGPipeRouteSetResidualValueState(block);
|
||||
if (MG_Util::PipeStats::Enabled()) {
|
||||
// ByteClass::ResidualValueBlock has been a placeholder that "stays at 0
|
||||
// until P2" since P0. This is what makes it non-zero.
|
||||
@@ -2235,7 +2421,7 @@ namespace MobileGL::MG_Pipe {
|
||||
bind.Cso = cso;
|
||||
bind.Version = version;
|
||||
bind.PipelineVersion = pipelineVersion;
|
||||
MGPipeApplyBindRenderState(bind);
|
||||
MGPipeRouteBindRenderState(bind);
|
||||
payloadBytes += sizeof(MGPBindRenderState);
|
||||
if (MG_Util::PipeStats::Enabled()) {
|
||||
MG_Util::PipeStats::AddCalls(MG_Util::PipeStats::CallClass::RenderStateCsoBinds, 1);
|
||||
@@ -2257,7 +2443,7 @@ namespace MobileGL::MG_Pipe {
|
||||
dyn.ChunkMask = chunkMask;
|
||||
dyn.Version = version;
|
||||
dyn.Blob.Size = blobBytes;
|
||||
MGPipeApplySetDynamicState(dyn, blob.data());
|
||||
MGPipeRouteSetDynamicState(dyn, blob.data());
|
||||
payloadBytes += sizeof(MGPDynamicState) + blobBytes;
|
||||
}
|
||||
|
||||
@@ -2382,6 +2568,14 @@ namespace MobileGL::MG_Pipe {
|
||||
// it on both branches, so a read before this first bump is
|
||||
// Fatal{UnmigratedPipeInput, "<Field>@<none>"} rather than default storage.
|
||||
++filled.CurrentVerbSerial;
|
||||
#endif
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
// The client is filling, so whatever the server stamped at its last verb boundary is
|
||||
// withdrawn: the stamps below are the CLIENT's again and a stale read is a defect, not
|
||||
// a residual pull. Disarming here rather than at the end of the applier's work is what
|
||||
// makes the arming flag say "the current stamps are the server's" no matter which of
|
||||
// the two roles ran last.
|
||||
MGPipeServerClearVerbBoundary();
|
||||
#endif
|
||||
MGPipeFillAccess::SetVerb(inputs, verb);
|
||||
auto* ctx = LiveContext();
|
||||
|
||||
@@ -41,6 +41,7 @@
|
||||
#include <MG_Pipe/MGPipe.h>
|
||||
#include <MG_Pipe/MGPipeHostSpan.h>
|
||||
#include <MG_Pipe/PipeApply.h>
|
||||
#include <MG_Pipe/PipeRoute.h>
|
||||
#include <MG_Pipe/PipeMutation.h>
|
||||
#include <MG_State/GLState/Core.h>
|
||||
#include <MG_State/GLState/ProgramState/ProgramObject.h>
|
||||
@@ -137,19 +138,19 @@ namespace MobileGL::MG_Pipe {
|
||||
// exactly "nothing bound".
|
||||
const MGPipeHandle boundCso = !MGPipeHandleIsNull(drawCso) ? drawCso : dispatchCso;
|
||||
if (boundCso != m_boundCso) {
|
||||
MGPipeApplyBindShaderState(HandleOnly(boundCso));
|
||||
MGPipeRouteBindShaderState(HandleOnly(boundCso));
|
||||
m_boundCso = boundCso;
|
||||
++m_binds;
|
||||
bytes += sizeof(MGPHandleOnly);
|
||||
}
|
||||
if (drawCso != m_drawCso) {
|
||||
MGPipeApplySetDrawProgram(HandleOnly(drawCso));
|
||||
MGPipeRouteSetDrawProgram(HandleOnly(drawCso));
|
||||
m_drawCso = drawCso;
|
||||
++m_drawSets;
|
||||
bytes += sizeof(MGPHandleOnly);
|
||||
}
|
||||
if (dispatchCso != m_dispatchCso) {
|
||||
MGPipeApplySetDispatchProgram(HandleOnly(dispatchCso));
|
||||
MGPipeRouteSetDispatchProgram(HandleOnly(dispatchCso));
|
||||
m_dispatchCso = dispatchCso;
|
||||
++m_dispatchSets;
|
||||
bytes += sizeof(MGPHandleOnly);
|
||||
@@ -192,7 +193,12 @@ namespace MobileGL::MG_Pipe {
|
||||
m_lastConstants.Blob.Seg = kMGHostSpanSegNone;
|
||||
m_lastConstants.Blob.Offset = reinterpret_cast<Uint64>(program->GetUBOData());
|
||||
m_lastConstants.Blob.Size = 0;
|
||||
MGPipeApplySetGlobalConstants(m_lastConstants, program->GetUBOData());
|
||||
// `size` is GetUBOSize(), and it is passed because the record declares 0 - the
|
||||
// monolith convention (the bytes ride beside the record) that CONTRACT-P5 table 1
|
||||
// rule A cannot keep under split. It is the row's largest and least bounded blob,
|
||||
// per program per frame, so it is also the one R-10's max-record counter watches.
|
||||
MGPipeRouteSetGlobalConstants(m_lastConstants, program->GetUBOData(),
|
||||
static_cast<Uint64>(size));
|
||||
m_constantsCso = cso;
|
||||
m_constantsVersion = version;
|
||||
++m_constantSets;
|
||||
@@ -254,7 +260,7 @@ namespace MobileGL::MG_Pipe {
|
||||
m_lastDesc.Reflection.Offset = reinterpret_cast<Uint64>(&link);
|
||||
m_lastDesc.Reflection.Size = 0;
|
||||
|
||||
MGPipeApplyCreateShaderState(m_lastDesc, &link, &spirv);
|
||||
MGPipeRouteCreateShaderState(m_lastDesc, &link, &spirv);
|
||||
// THE CREATE WENT OUT, so the publication latch is taken here and nowhere else
|
||||
// (contract-v2 §3.1). MGPipeEmitShaderCsoDestroyAndFree reads it, and without it
|
||||
// delete_shader_state can never go out - for an ordinary program or for a
|
||||
|
||||
@@ -44,6 +44,7 @@
|
||||
#include <MG_Pipe/MGPipe.h>
|
||||
#include <MG_Pipe/MGPipeHostSpan.h>
|
||||
#include <MG_Pipe/PipeApply.h>
|
||||
#include <MG_Pipe/PipeRoute.h>
|
||||
#include <MG_Pipe/PipeMutation.h>
|
||||
#include <MG_State/GLState/Core.h>
|
||||
#include <MG_State/GLState/ProgramState/ProgramObject.h>
|
||||
@@ -455,7 +456,7 @@ namespace MobileGL::MG_Pipe {
|
||||
// The applier is handed the CACHE's copy, so the pointer stays valid for the whole
|
||||
// call and the bytes it stores are provably the bytes the memcmp will confirm
|
||||
// against later.
|
||||
MGPipeApplyCreateSamplerState(desc, &m_entries.back().Params);
|
||||
MGPipeRouteCreateSamplerState(desc, &m_entries.back().Params);
|
||||
// THE CREATE ACTUALLY WENT OUT, so the publication latch is taken here and nowhere
|
||||
// else (contract-v2 §3.1). It is what the six death helpers read, and without it a
|
||||
// delete_sampler_state can never go out for this kind.
|
||||
@@ -490,7 +491,7 @@ namespace MobileGL::MG_Pipe {
|
||||
// only then does the slot go back. There is no NotifyStateObjectDestroyed step
|
||||
// here - a content-addressed CSO has no frontend object whose death is being
|
||||
// announced, which is precisely why this eviction is the only death path it has.
|
||||
MGPipeApplyDeleteSamplerState(handle);
|
||||
MGPipeRouteDeleteSamplerState(handle);
|
||||
// AND THE LATCH GOES WITH THE DELETE. This is the "an emitter that drops a record
|
||||
// for its own reasons calls MGPipeNoteHandleUnpublished" half of the publication
|
||||
// protocol (contract-v2 §3.1): the record is gone, so a death helper reaching this
|
||||
@@ -783,7 +784,7 @@ namespace MobileGL::MG_Pipe {
|
||||
m_lastViews.Start = 0;
|
||||
m_lastViews.Count = count;
|
||||
m_lastViews.ContentHash = hash;
|
||||
MGPipeApplySetSamplerViews(m_lastViews, m_views.data());
|
||||
MGPipeRouteSetSamplerViews(m_lastViews, m_views.data());
|
||||
++m_viewSets;
|
||||
if (MG_Util::PipeStats::Enabled()) {
|
||||
MG_Util::PipeStats::AddCalls(MG_Util::PipeStats::CallClass::SamplerViewEmissions, 1);
|
||||
@@ -857,7 +858,7 @@ namespace MobileGL::MG_Pipe {
|
||||
m_lastStates.Start = 0;
|
||||
m_lastStates.Count = count;
|
||||
m_lastStates.ContentHash = hash;
|
||||
MGPipeApplyBindSamplerStates(m_lastStates, m_states.data());
|
||||
MGPipeRouteBindSamplerStates(m_lastStates, m_states.data());
|
||||
++m_stateSets;
|
||||
if (MG_Util::PipeStats::Enabled()) {
|
||||
MG_Util::PipeStats::AddCalls(MG_Util::PipeStats::CallClass::SamplerStateEmissions, 1);
|
||||
@@ -914,7 +915,7 @@ namespace MobileGL::MG_Pipe {
|
||||
m_lastView.NumLayers = static_cast<Uint16>(texture.GetViewNumLayers());
|
||||
m_lastView.Samples = static_cast<Uint16>(texture.GetSamples() < 0 ? 0 : texture.GetSamples());
|
||||
m_lastView.FixedSampleLocations = texture.HasFixedSampleLocations() ? 1 : 0;
|
||||
MGPipeApplyCreateSamplerView(m_lastView);
|
||||
MGPipeRouteCreateSamplerView(m_lastView);
|
||||
// THE CREATE WENT OUT, so the publication latch is taken (contract-v2 §3.1). The
|
||||
// texture's death helper reads it, and without it delete_sampler_view can never go
|
||||
// out - the C-1 leak, one kind later. Re-taking it on a re-issue is right and
|
||||
|
||||
@@ -57,6 +57,7 @@
|
||||
#include <MG_Impl/Pipe/SlotAllocator.h>
|
||||
#include <MG_Pipe/MGPipe.h>
|
||||
#include <MG_Pipe/PipeApply.h>
|
||||
#include <MG_Pipe/PipeRoute.h>
|
||||
#include <MG_Pipe/PipeMutation.h>
|
||||
#include <MG_State/GLState/Core.h>
|
||||
#include <MG_State/GLState/RenderbufferState/RenderbufferObject.h>
|
||||
@@ -802,7 +803,7 @@ namespace MobileGL::MG_Pipe {
|
||||
++m_paramSets;
|
||||
// Not behind MGPipeTextureRecordsReachTheApplier() (see its comment): the call is
|
||||
// dispatched whenever this emitter runs, so the answer is always a real one.
|
||||
Bool accepted = MGPipeApplySetTextureParams(params);
|
||||
Bool accepted = MGPipeRouteSetTextureParams(params);
|
||||
if (!accepted) {
|
||||
// THE SELF-HEAL, the respecify path's shape, and the parameters are the one
|
||||
// publication that may be a texture's FIRST: the context's default textures are
|
||||
@@ -828,7 +829,7 @@ namespace MobileGL::MG_Pipe {
|
||||
// across it - `entry` is re-fetched below.
|
||||
EmitResourceRespecify(texture, MGPipeTextureRespecifyScope::WholeResource, 0, 0);
|
||||
}
|
||||
accepted = MGPipeApplySetTextureParams(params);
|
||||
accepted = MGPipeRouteSetTextureParams(params);
|
||||
}
|
||||
Entry& latched = EntryFor(m_textures, handle);
|
||||
if (!accepted) {
|
||||
@@ -1121,7 +1122,7 @@ namespace MobileGL::MG_Pipe {
|
||||
Bool dispatched = false;
|
||||
if constexpr (MGPipeTextureRecordsReachTheApplier()) {
|
||||
dispatched = true;
|
||||
accepted = MGPipeApplyResourceCreate(desc);
|
||||
accepted = MGPipeRouteResourceCreate(desc);
|
||||
}
|
||||
if (dispatched && !accepted) return;
|
||||
MGPipeNoteHandlePublished(kind, handle);
|
||||
@@ -1134,7 +1135,7 @@ namespace MobileGL::MG_Pipe {
|
||||
// replaces no storage at all.
|
||||
static Bool ApplyRespecify(const MGPResourceDesc& desc, const MGPRespecifiedLevel* level) {
|
||||
if constexpr (MGPipeTextureRecordsReachTheApplier()) {
|
||||
return MGPipeApplyResourceRespecify(desc, nullptr, level);
|
||||
return MGPipeRouteResourceRespecify(desc, nullptr, level);
|
||||
}
|
||||
(void)level;
|
||||
return false;
|
||||
@@ -1275,7 +1276,14 @@ namespace MobileGL::MG_Pipe {
|
||||
Bool dispatched = false;
|
||||
if constexpr (MGPipeTextureRecordsReachTheApplier()) {
|
||||
dispatched = true;
|
||||
accepted = MGPipeApplyResourceSubData(m_lastSubData, shadow,
|
||||
// `levelBytes` closes CONTRACT-P5 table 1 row 7's open half. The record still
|
||||
// declares Blob.Size 0 on the monolith arm - where the applier reads the
|
||||
// companion pointer and the destination box bounds the write - but under split
|
||||
// the staged run needs a length, and the comment above already says what it
|
||||
// is: "the bytes this record declares ARE the level shadow". The regions' own
|
||||
// SrcOffsets index into exactly that run.
|
||||
accepted = MGPipeRouteResourceSubData(m_lastSubData, shadow,
|
||||
static_cast<Uint64>(levelBytes),
|
||||
m_regions.empty() ? nullptr : m_regions.data());
|
||||
}
|
||||
++m_subDatas;
|
||||
|
||||
@@ -43,6 +43,7 @@
|
||||
#include <MG_Impl/Pipe/Tracker.h>
|
||||
#include <MG_Pipe/MGPipe.h>
|
||||
#include <MG_Pipe/PipeApply.h>
|
||||
#include <MG_Pipe/PipeRoute.h>
|
||||
#include <MG_State/GLState/Core.h>
|
||||
#include <MG_Util/Metrics/PipeStats.h>
|
||||
|
||||
@@ -158,7 +159,7 @@ namespace MobileGL::MG_Pipe {
|
||||
const auto& vao = ctx.GetBoundVertexArray();
|
||||
if (!vao) {
|
||||
if (!MGPipeHandleIsNull(m_boundHandle)) {
|
||||
MGPipeApplyBindVertexElements(HandleOnly(kMGPipeNullHandle));
|
||||
MGPipeRouteBindVertexElements(HandleOnly(kMGPipeNullHandle));
|
||||
++m_binds;
|
||||
m_boundHandle = kMGPipeNullHandle;
|
||||
m_boundLifetimeId = 0;
|
||||
@@ -178,7 +179,7 @@ namespace MobileGL::MG_Pipe {
|
||||
latch.Gen != handle.Gen;
|
||||
if (configMoved) bytes += EmitCreate(*vao, handle, latch, configVersion);
|
||||
if (lifetimeId != m_boundLifetimeId || m_boundHandle != handle) {
|
||||
MGPipeApplyBindVertexElements(HandleOnly(handle));
|
||||
MGPipeRouteBindVertexElements(HandleOnly(handle));
|
||||
++m_binds;
|
||||
bytes += sizeof(MGPHandleOnly);
|
||||
m_boundHandle = handle;
|
||||
@@ -242,7 +243,7 @@ namespace MobileGL::MG_Pipe {
|
||||
// emulation is server-owned.
|
||||
m_lastBuffers.BaseInstance = baseInstance;
|
||||
m_lastBuffers.ContentHash = hash;
|
||||
MGPipeApplySetVertexBuffers(m_lastBuffers, m_entries.data());
|
||||
MGPipeRouteSetVertexBuffers(m_lastBuffers, m_entries.data());
|
||||
++m_bufferSets;
|
||||
return sizeof(MGPVertexBuffers) + static_cast<Uint64>(count) * sizeof(MGPVertexBuffer);
|
||||
}
|
||||
@@ -267,7 +268,7 @@ namespace MobileGL::MG_Pipe {
|
||||
MGPipeResourceTrackerInstance().NoteBoundAs(m_lastIndex.Res, BufferTarget::Index);
|
||||
}
|
||||
}
|
||||
MGPipeApplySetIndexBuffer(m_lastIndex);
|
||||
MGPipeRouteSetIndexBuffer(m_lastIndex);
|
||||
++m_indexSets;
|
||||
return sizeof(MGPIndexBuffer);
|
||||
}
|
||||
@@ -396,7 +397,7 @@ namespace MobileGL::MG_Pipe {
|
||||
m_lastElements.Blob.Seg = kMGHostSpanSegNone;
|
||||
m_lastElements.Blob.Offset = 0;
|
||||
m_lastElements.Blob.Size = kAttribBytes + kBindingBytes;
|
||||
MGPipeApplyCreateVertexElements(m_lastElements, m_blob.data());
|
||||
MGPipeRouteCreateVertexElements(m_lastElements, m_blob.data());
|
||||
++m_creates;
|
||||
latch.Published = true;
|
||||
latch.Gen = handle.Gen;
|
||||
|
||||
@@ -56,6 +56,8 @@ add_executable(MobileGLIntegrationTest
|
||||
Harness/PipeApplyPeek.cpp
|
||||
Harness/P4aSeamPeek.cpp
|
||||
Harness/P4aFinalFixPeek.cpp
|
||||
Harness/PersistentMapPeek.cpp
|
||||
Harness/SplitRuntimePeek.cpp
|
||||
Scenarios/OrientationScenario.cpp
|
||||
Scenarios/CrossFrameBufferScenario.cpp
|
||||
Scenarios/ResidentIndexScenario.cpp
|
||||
@@ -141,6 +143,11 @@ add_executable(MobileGLIntegrationTest
|
||||
Scenarios/ObjectSubsystemControlScenario.cpp
|
||||
Scenarios/P4aSeamAuditScenario.cpp
|
||||
Scenarios/P4aFinalFixScenario.cpp
|
||||
# P5's two new scenarios, targets B and C of the reduced path (BRIEF-P5 4). Both are
|
||||
# ORDINARY GL scenarios that run in every lane; the DirectGLES.Split. entries further down
|
||||
# run the same cases with MOBILEGL_TRANSPORT=inproc.
|
||||
Scenarios/TriangleScenario.cpp
|
||||
Scenarios/PersistentCoherentMapScenario.cpp
|
||||
)
|
||||
|
||||
target_include_directories(MobileGLIntegrationTest PRIVATE
|
||||
@@ -1757,3 +1764,249 @@ if (MOBILEGL_PIPE_VERIFY)
|
||||
ENVIRONMENT "${MGL_ITEST_VULKAN_POISON_OMIT_ENVIRONMENT}"
|
||||
)
|
||||
endif()
|
||||
|
||||
# --- P5: the DirectGLES.Split. lanes and the persistent-map ARM lanes ------------------------
|
||||
#
|
||||
# THE PRIVATE SECOND LABEL IS WHAT MAKES THE LANE FALSIFIABLE, and it is the verify block above
|
||||
# copied verbatim for the same argument: `ctest -L integration-split --no-tests=error` in a build
|
||||
# that forgot -DMOBILEGL_BUILD_DISAGGREGATED=ON matches NOTHING and FAILS, instead of reporting a
|
||||
# green run of zero entries. Keeping `integration-gpu` as well is why "a split build's
|
||||
# `ctest -L integration-gpu` still describes the whole registration set" stays true.
|
||||
#
|
||||
# REGISTERED INSIDE `if (MOBILEGL_BUILD_DISAGGREGATED)`, and that is what keeps gate G2 (pull and
|
||||
# push name-for-name identical) untouched: neither of those two builds sets the option, so the
|
||||
# Split family is absent from BOTH of them rather than present in one. The two SCENARIO FILES the
|
||||
# lanes point at are added to the source list unconditionally, so their cases DO appear in the
|
||||
# ambient DirectGLES./DirectVulkan. registrations of every build - they are ordinary GL scenarios
|
||||
# and their monolith behaviour is the baseline the split arm is compared against.
|
||||
#
|
||||
# WHAT ARMS THE SPLIT LANES, AND WHY IT IS NOT A PROBE OVER SOURCE TEXT.
|
||||
#
|
||||
# Until a real client session exists, MOBILEGL_TRANSPORT=inproc is parsed (CONTRACT-P5 5) and then
|
||||
# nothing consumes it, so a Split entry would go green having run monolith end to end - the exact
|
||||
# failure the lane exists to prevent. The first version of this file answered "has the client
|
||||
# landed" with a CMake conjunction over c0's stub files: the c1 symbols present AND no
|
||||
# `Fatal.Unimplemented` surviving. REVIEW FINDING M-1 FALSIFIED IT BY PERFORMING IT - a
|
||||
# `sed -i 's/Fatal{Unimplemented/Fatal{NotYetImplemented/'` over c0's six stubs, with every entry
|
||||
# point still aborting and ImplementedVerbCount() still 0, armed all eleven lanes and EIGHT WENT
|
||||
# GREEN. A single comment line carrying the marker did the opposite and would keep them dark
|
||||
# forever (M-2), and two stub files outside the two probed directories allowed a partial arm (M-3).
|
||||
#
|
||||
# A statement about source text can always be falsified by editing source text, and the people
|
||||
# most likely to edit it are the ones landing the packages the probe watches for. So the arming
|
||||
# condition moved into the PROCESS: Harness/SplitRuntimePeek.cpp reads MG_Config::Transport,
|
||||
# ClientSession::Active() and ImplementedVerbCount() - three values c0 shipped and documented,
|
||||
# none of which a message edit can move - and every Split case skips, naming the first one that is
|
||||
# not true. All this file has to decide now is whether that peek can be COMPILED, which is exactly
|
||||
# "did this build compile MG_Remote", which is exactly the build option.
|
||||
if (MOBILEGL_BUILD_DISAGGREGATED)
|
||||
target_compile_definitions(MobileGLIntegrationTest PRIVATE -DMGITEST_SPLIT_RUNTIME_PEEK=1)
|
||||
message(STATUS "Integration tests: the DirectGLES.Split. lanes arm from the RUNNING PROCESS - "
|
||||
"MG_Config::Transport, ClientSession::Active() and ImplementedVerbCount() - and "
|
||||
"skip naming the first of those that is not true")
|
||||
endif()
|
||||
|
||||
# Q-3, made a build fact rather than documentation. ConfigLoader logs the resolved transport at
|
||||
# INFO, and that line is what run_trace_case.cmake reads back as proof a retrace really went
|
||||
# split. At WARN or above it is compiled out and every split retrace reds for a reason that is not
|
||||
# a defect; at DEBUG, ConfigLoader's unconditional env dump prints a confusable KEY=VALUE line in
|
||||
# a PULL build too (review M-5, also fixed on the reading side). The integration lanes themselves
|
||||
# no longer depend on the log level at all - they read the variable - so this is a WARNING.
|
||||
if (MOBILEGL_BUILD_DISAGGREGATED AND DEFINED MOBILEGL_LOG_ACTIVE_LEVEL
|
||||
AND NOT MOBILEGL_LOG_ACTIVE_LEVEL STREQUAL "MOBILEGL_LOG_LEVEL_INFO"
|
||||
AND NOT MOBILEGL_LOG_ACTIVE_LEVEL STREQUAL "MOBILEGL_LOG_LEVEL_DEBUG")
|
||||
message(WARNING "Integration tests: MOBILEGL_LOG_ACTIVE_LEVEL=${MOBILEGL_LOG_ACTIVE_LEVEL} in a "
|
||||
"disaggregated build. ConfigLoader's transport line is MGLOG_I, so the "
|
||||
"trace-replay split arm's transport-resolution assertion cannot see it and every "
|
||||
"split retrace will red. Use MOBILEGL_LOG_LEVEL_INFO.")
|
||||
endif()
|
||||
|
||||
# Package b1's client-side persistent-map tracker, which is what Harness/PersistentMapPeek.cpp
|
||||
# asks the membership question of (b1-v1.md 4.1 item 2). TWO halves, and both are needed:
|
||||
# MOBILEGL_BUILD_DISAGGREGATED because a build that never compiled MG_Remote cannot LINK the call,
|
||||
# and the content probe because b1 may not have landed it yet. __has_include in the peek would
|
||||
# answer yes in a pull build - the header is in the source tree of every build - and turn a
|
||||
# healthy pull build into a link error, which is why this decision is made here.
|
||||
if (MOBILEGL_BUILD_DISAGGREGATED)
|
||||
mgl_itest_probe_for_symbol(MGL_ITEST_PERSISTENT_MAP_TRACKER
|
||||
"${MGL_ITEST_ROOT}/MobileGL/MG_Remote/Client" "IsLivePersistentMap")
|
||||
if (MGL_ITEST_PERSISTENT_MAP_TRACKER)
|
||||
message(STATUS "Integration tests: package b1's persistent-map tracker is present "
|
||||
"(${MGL_ITEST_PERSISTENT_MAP_TRACKER}) - PersistentCoherentMapScenario's "
|
||||
"membership assertion is live")
|
||||
target_compile_definitions(MobileGLIntegrationTest PRIVATE -DMGITEST_PERSISTENT_MAP_TRACKER=1)
|
||||
else()
|
||||
message(STATUS "Integration tests: no source under MobileGL/MG_Remote/Client names "
|
||||
"IsLivePersistentMap - package b1's tracker has not landed, so "
|
||||
"PersistentCoherentMapScenario's membership assertion SKIPS")
|
||||
endif()
|
||||
endif()
|
||||
|
||||
# ARCHITECTURE.md:543 - every new ctest ENVIRONMENT and add_trace_replay_test's SPLIT branch
|
||||
# carries MOBILEGL_IPC_SERVER_PATH, because the dladdr fallback cannot find the server from a
|
||||
# binary that links MobileGL_s statically. P5 is inproc-only and nothing reads the value yet; it
|
||||
# is carried now so that an unparsed variable and a parsed-and-ignored one stop being
|
||||
# indistinguishable the day P6 consumes it. A generator expression is deliberately NOT used here:
|
||||
# a $<TARGET_FILE_DIR:...> inside a gtest_discover_tests PROPERTIES value is written into the
|
||||
# generated ctest include file verbatim and never expanded.
|
||||
set(MGL_ITEST_SPLIT_SERVER_PATH "${CMAKE_BINARY_DIR}/libMobileGLServer.so")
|
||||
|
||||
mgl_itest_join_environment(MGL_ITEST_GLES_SPLIT_ENVIRONMENT
|
||||
"MOBILEGL_BACKEND_TYPE=DirectGLES" "MOBILEGL_TRANSPORT=inproc"
|
||||
"MOBILEGL_IPC_SERVER_PATH=${MGL_ITEST_SPLIT_SERVER_PATH}" "MGITEST_SPLIT_LANE=1"
|
||||
${MGL_ITEST_CAPABILITY_ENV} ${MGL_ITEST_COMMON_ENV})
|
||||
|
||||
# The two counting lanes, one per transport, and they are a PAIR: exit gate E3(c) asks that the
|
||||
# split arm's `mpr` equal the monolith arm's, and one test process can only ever see its own. So
|
||||
# both lanes run the same workload and assert the same constant, and the equality holds by
|
||||
# construction with each half able to fail on its own.
|
||||
#
|
||||
# Each gets a LOG PATH OF ITS OWN and a TEST_FILTER that selects ONE case, for the reason
|
||||
# PipeStatsWindow.h gives: the library opens its log fopen(path, "w"), so every process in a lane
|
||||
# truncates it, and two readers in one lane race under `ctest -j`. RESOURCE_LOCK on top of that,
|
||||
# for the reason the UnlocatedIoBlocks lane gives - measured on this tree, three runs of the full
|
||||
# integration-gpu label at -j 8 produced 4, 0 and 2 spurious failures of the log-reading cases
|
||||
# without it.
|
||||
#
|
||||
# The monolith lane declares NO arm: which arm AcquireMemoryRange takes for a sub-16-MiB
|
||||
# PERSISTENT|WRITE|COHERENT map is a property of the driver and the build, so the case RECORDS it
|
||||
# there and skips the assertion. Only the split lane - where R-6 pins the adopt tier at T2 -
|
||||
# declares one.
|
||||
# MOBILEGL_TRANSPORT=monolith IS NAMED HERE ON PURPOSE, and it is review finding N-6. This entry
|
||||
# is the MONOLITH half of a pair; without the property a job-level or gate-level
|
||||
# `MOBILEGL_TRANSPORT=inproc` export reaches it (observed: its own log then carried
|
||||
# `Config: MOBILEGL_TRANSPORT=inproc`) and, in the inproc arm of the three-arm A/B, BOTH halves of
|
||||
# the pair were inproc. Nothing failed - each half asserts the same constant - but the pair was
|
||||
# not the pair its name describes. A ctest ENVIRONMENT property overrides the job environment,
|
||||
# which is the one case where that is what you want.
|
||||
mgl_itest_join_environment(MGL_ITEST_GLES_PMAP_ARM_ENVIRONMENT
|
||||
"MOBILEGL_BACKEND_TYPE=DirectGLES" "MGITEST_PMAP_LANE=1" "MOBILEGL_TRANSPORT=monolith"
|
||||
"MOBILEGL_PIPE_STATS=1" "MOBILEGL_PIPE_STATS_PERIOD=1"
|
||||
"MOBILEGL_LOG_FILE_PATH=${CMAKE_CURRENT_BINARY_DIR}/persistent-map-arm-DirectGLES.log"
|
||||
${MGL_ITEST_CAPABILITY_ENV} ${MGL_ITEST_COMMON_ENV})
|
||||
|
||||
gtest_discover_tests(MobileGLIntegrationTest
|
||||
TEST_PREFIX "DirectGLES.PersistentMapArm."
|
||||
TEST_FILTER "PersistentCoherentMapScenario.TheMapLandsInTheArmItsLaneDeclares"
|
||||
DISCOVERY_TIMEOUT 30
|
||||
PROPERTIES
|
||||
LABELS integration-gpu
|
||||
TIMEOUT ${MGL_ITEST_TIMEOUT}
|
||||
RESOURCE_LOCK persistent-map-arm-DirectGLES.log
|
||||
ENVIRONMENT "${MGL_ITEST_GLES_PMAP_ARM_ENVIRONMENT}"
|
||||
)
|
||||
|
||||
if (MOBILEGL_BUILD_DISAGGREGATED)
|
||||
# One block per scenario, following the DirectGLES.MapPersistentRoundtrips. precedent: a
|
||||
# `:`-separated multi-pattern TEST_FILTER is not used anywhere in this file, so its escaping
|
||||
# through gtest_discover_tests' flat PROPERTIES forwarding is unproven, and three blocks cost
|
||||
# nothing.
|
||||
#
|
||||
# ClearThenReadPixelsScenario is target A of the reduced path and already existed; Triangle is
|
||||
# target B and PersistentCoherentMap is target C, both new in P5.
|
||||
gtest_discover_tests(MobileGLIntegrationTest
|
||||
TEST_PREFIX "DirectGLES.Split."
|
||||
TEST_LIST MGL_SPLIT_CLEAR_TESTS
|
||||
TEST_FILTER "ClearThenReadPixelsScenario.*"
|
||||
DISCOVERY_TIMEOUT 30
|
||||
PROPERTIES
|
||||
LABELS "integration-gpu\;integration-split"
|
||||
TIMEOUT ${MGL_ITEST_TIMEOUT}
|
||||
ENVIRONMENT "${MGL_ITEST_GLES_SPLIT_ENVIRONMENT}"
|
||||
)
|
||||
gtest_discover_tests(MobileGLIntegrationTest
|
||||
TEST_PREFIX "DirectGLES.Split."
|
||||
TEST_LIST MGL_SPLIT_TRIANGLE_TESTS
|
||||
TEST_FILTER "TriangleScenario.*"
|
||||
DISCOVERY_TIMEOUT 30
|
||||
PROPERTIES
|
||||
LABELS "integration-gpu\;integration-split"
|
||||
TIMEOUT ${MGL_ITEST_TIMEOUT}
|
||||
ENVIRONMENT "${MGL_ITEST_GLES_SPLIT_ENVIRONMENT}"
|
||||
)
|
||||
gtest_discover_tests(MobileGLIntegrationTest
|
||||
TEST_PREFIX "DirectGLES.Split."
|
||||
TEST_LIST MGL_SPLIT_PMAP_TESTS
|
||||
TEST_FILTER "PersistentCoherentMapScenario.*"
|
||||
DISCOVERY_TIMEOUT 30
|
||||
PROPERTIES
|
||||
LABELS "integration-gpu\;integration-split"
|
||||
TIMEOUT ${MGL_ITEST_TIMEOUT}
|
||||
ENVIRONMENT "${MGL_ITEST_GLES_SPLIT_ENVIRONMENT}"
|
||||
)
|
||||
|
||||
# The split half of the counting pair. MGITEST_PERSISTENT_MAP_ARM=emulated is R-6: under split
|
||||
# the adopt tier is pinned at T2, the resource owner declines every acquisition and the client
|
||||
# pushes the mapping's dirty blocks - so pmap must be non-zero and mpr must be the monolith
|
||||
# lane's number. pmap == 0 here means MGPipeApplyMapPersistent handed back a pointer, which is
|
||||
# exit gate E3(d) failing, and under inproc that failure is invisible in pixels.
|
||||
mgl_itest_join_environment(MGL_ITEST_GLES_SPLIT_PMAP_ARM_ENVIRONMENT
|
||||
"MOBILEGL_BACKEND_TYPE=DirectGLES" "MOBILEGL_TRANSPORT=inproc"
|
||||
"MOBILEGL_IPC_SERVER_PATH=${MGL_ITEST_SPLIT_SERVER_PATH}" "MGITEST_SPLIT_LANE=1"
|
||||
"MGITEST_PMAP_LANE=1" "MGITEST_PERSISTENT_MAP_ARM=emulated"
|
||||
"MOBILEGL_PIPE_STATS=1" "MOBILEGL_PIPE_STATS_PERIOD=1"
|
||||
"MOBILEGL_LOG_FILE_PATH=${CMAKE_CURRENT_BINARY_DIR}/persistent-map-arm-split-DirectGLES.log"
|
||||
${MGL_ITEST_CAPABILITY_ENV} ${MGL_ITEST_COMMON_ENV})
|
||||
|
||||
gtest_discover_tests(MobileGLIntegrationTest
|
||||
TEST_PREFIX "DirectGLES.Split.PersistentMapArm."
|
||||
TEST_FILTER "PersistentCoherentMapScenario.TheMapLandsInTheArmItsLaneDeclares"
|
||||
DISCOVERY_TIMEOUT 30
|
||||
PROPERTIES
|
||||
LABELS "integration-gpu\;integration-split"
|
||||
TIMEOUT ${MGL_ITEST_TIMEOUT}
|
||||
RESOURCE_LOCK persistent-map-arm-split-DirectGLES.log
|
||||
ENVIRONMENT "${MGL_ITEST_GLES_SPLIT_PMAP_ARM_ENVIRONMENT}"
|
||||
)
|
||||
|
||||
# --- EXIT GATE E3(e): the same checks with a ring small enough to force back-pressure -----
|
||||
#
|
||||
# BRIEF 7 E3(e) - "以上五条再跑一遍 ring 小到足以至少发生一次背压等待的配置" - was missing from
|
||||
# the first cut of this package and missing from its report (review finding M-7). It is a
|
||||
# LANE, not a new scenario: the same three split scenarios with SEG_CMD and SEG_STAGE at their
|
||||
# floor, so a workload that fits comfortably in the 8 MiB / 32 MiB defaults has to wrap and
|
||||
# wait at least once.
|
||||
#
|
||||
# 1 MiB is ConfigLoader's minimum for both (Config.h / ConfigLoader.cpp:363-364, floors of 1
|
||||
# rather than 0 because a ring caps ONE record at half its size). That caps a record at 512
|
||||
# KiB, which every record on the reduced path is far under, so the ring is legal and small
|
||||
# rather than unusable.
|
||||
#
|
||||
# WHAT THIS LANE DOES NOT YET ASSERT, stated rather than implied: that a back-pressure wait
|
||||
# ACTUALLY happened. That needs a counter only package s1 can publish (a producer-parked or
|
||||
# ring-full tally on RingControl); until it exists this lane proves the five checks survive a
|
||||
# small ring, not that the small ring bit. The gap is named in t1-v1.md's debts rather than
|
||||
# left for someone to discover from a green.
|
||||
mgl_itest_join_environment(MGL_ITEST_GLES_SPLIT_SMALL_RING_ENVIRONMENT
|
||||
"MOBILEGL_BACKEND_TYPE=DirectGLES" "MOBILEGL_TRANSPORT=inproc"
|
||||
"MOBILEGL_IPC_SERVER_PATH=${MGL_ITEST_SPLIT_SERVER_PATH}" "MGITEST_SPLIT_LANE=1"
|
||||
"MGITEST_SMALL_RING_LANE=1" "MOBILEGL_IPC_RING_MB=1" "MOBILEGL_IPC_STAGE_MB=1"
|
||||
${MGL_ITEST_CAPABILITY_ENV} ${MGL_ITEST_COMMON_ENV})
|
||||
|
||||
set(MGL_SPLIT_SMALL_RING_SCENARIOS ClearThenReadPixelsScenario TriangleScenario
|
||||
PersistentCoherentMapScenario)
|
||||
foreach(mglItestSmallRingScenario IN LISTS MGL_SPLIT_SMALL_RING_SCENARIOS)
|
||||
gtest_discover_tests(MobileGLIntegrationTest
|
||||
TEST_PREFIX "DirectGLES.Split.SmallRing."
|
||||
TEST_LIST "MGL_SPLIT_SMALL_${mglItestSmallRingScenario}_TESTS"
|
||||
TEST_FILTER "${mglItestSmallRingScenario}.*"
|
||||
DISCOVERY_TIMEOUT 30
|
||||
PROPERTIES
|
||||
LABELS "integration-gpu\;integration-split"
|
||||
TIMEOUT ${MGL_ITEST_TIMEOUT}
|
||||
ENVIRONMENT "${MGL_ITEST_GLES_SPLIT_SMALL_RING_ENVIRONMENT}"
|
||||
)
|
||||
endforeach()
|
||||
# Apply per-entry paths after GoogleTest discovery has populated the TEST_LISTs.
|
||||
configure_file(Harness/SplitLogPaths.cmake.in SplitLogPaths.cmake @ONLY)
|
||||
set_property(DIRECTORY APPEND PROPERTY TEST_INCLUDE_FILES
|
||||
"${CMAKE_CURRENT_BINARY_DIR}/SplitLogPaths.cmake")
|
||||
# Python is mandatory for this split integration gate (also used by the CI controls).
|
||||
# Do not silently omit the ownership check when the interpreter is unavailable.
|
||||
find_package(Python3 REQUIRED COMPONENTS Interpreter)
|
||||
add_test(NAME SplitLogPaths.PrivateAndDistinct
|
||||
COMMAND "${Python3_EXECUTABLE}"
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/Harness/split_log_paths.py"
|
||||
check "${CMAKE_CTEST_COMMAND}" "${CMAKE_BINARY_DIR}")
|
||||
set_tests_properties(SplitLogPaths.PrivateAndDistinct PROPERTIES LABELS "integration-split")
|
||||
endif()
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
// MobileGL - MobileGL/MG_IntegrationTest/Harness/PersistentMapPeek.cpp
|
||||
// Copyright (c) 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 "PersistentMapPeek.h"
|
||||
|
||||
#if !defined(__ANDROID__)
|
||||
#include <MG_State/GLState/BufferState/BufferObject.h>
|
||||
#include <MG_State/GLState/Core.h>
|
||||
#define MGITEST_PERSISTENT_MAP_PEEK_LIVE 1
|
||||
#endif
|
||||
|
||||
// MGITEST_PERSISTENT_MAP_TRACKER is defined by MG_IntegrationTest/CMakeLists.txt, and only when
|
||||
// BOTH halves are true: the build compiled MG_Remote (so the symbol can link) AND some source
|
||||
// under MG_Remote/Client names IsLivePersistentMap (so package b1 landed it). __has_include is
|
||||
// NOT enough on its own - the header exists in the source tree of every build, including the pull
|
||||
// build that never compiles MG_Remote, so keying on it would turn a healthy pull build into a
|
||||
// link error.
|
||||
#if defined(MGITEST_PERSISTENT_MAP_PEEK_LIVE) && defined(MGITEST_PERSISTENT_MAP_TRACKER)
|
||||
#include <MG_Remote/Client/PersistentMapTracker.h>
|
||||
#define MGITEST_PERSISTENT_MAP_TRACKER_LIVE 1
|
||||
#endif
|
||||
|
||||
namespace MGITest {
|
||||
|
||||
bool PersistentMapPeekAvailable() {
|
||||
#if defined(MGITEST_PERSISTENT_MAP_PEEK_LIVE)
|
||||
return true;
|
||||
#else
|
||||
return false;
|
||||
#endif
|
||||
}
|
||||
|
||||
bool PersistentMapTrackerAvailable() {
|
||||
#if defined(MGITEST_PERSISTENT_MAP_TRACKER_LIVE)
|
||||
return true;
|
||||
#else
|
||||
return false;
|
||||
#endif
|
||||
}
|
||||
|
||||
#if defined(MGITEST_PERSISTENT_MAP_PEEK_LIVE)
|
||||
namespace {
|
||||
// The frontend object behind a GL buffer name, or null. GetBufferObject mints on demand
|
||||
// for a name that was generated and never bound, which is harmless here: a scenario only
|
||||
// ever asks about a buffer it has already defined and mapped, and a null store answers
|
||||
// "not adopted", which is the same answer an un-mapped buffer would give.
|
||||
MobileGL::MG_State::GLState::BufferObject* FrontendBuffer(unsigned int bufferName) {
|
||||
if (bufferName == 0) return nullptr;
|
||||
auto& context = MobileGL::MG_State::pGLContext;
|
||||
if (!context) return nullptr;
|
||||
const auto& buffer = context->GetBufferObject(static_cast<MobileGL::Uint>(bufferName));
|
||||
return buffer.get();
|
||||
}
|
||||
} // namespace
|
||||
#endif
|
||||
|
||||
bool PeekBufferIsAdoptedPersistentMap(unsigned int bufferName, bool* outAdopted) {
|
||||
#if defined(MGITEST_PERSISTENT_MAP_PEEK_LIVE)
|
||||
if (outAdopted == nullptr) return false;
|
||||
MobileGL::MG_State::GLState::BufferObject* buffer = FrontendBuffer(bufferName);
|
||||
if (buffer == nullptr) return false;
|
||||
*outAdopted = static_cast<bool>(buffer->IsBackendPersistentMapped());
|
||||
return true;
|
||||
#else
|
||||
(void)bufferName;
|
||||
(void)outAdopted;
|
||||
return false;
|
||||
#endif
|
||||
}
|
||||
|
||||
bool PeekBufferIsLivePersistentMap(unsigned int bufferName, bool* outLive) {
|
||||
#if defined(MGITEST_PERSISTENT_MAP_TRACKER_LIVE)
|
||||
if (outLive == nullptr) return false;
|
||||
MobileGL::MG_State::GLState::BufferObject* buffer = FrontendBuffer(bufferName);
|
||||
if (buffer == nullptr) return false;
|
||||
*outLive = static_cast<bool>(
|
||||
MobileGL::MG_Remote::Client::PersistentMapTracker::IsLivePersistentMap(*buffer));
|
||||
return true;
|
||||
#else
|
||||
(void)bufferName;
|
||||
(void)outLive;
|
||||
return false;
|
||||
#endif
|
||||
}
|
||||
|
||||
} // namespace MGITest
|
||||
@@ -0,0 +1,61 @@
|
||||
// MobileGL - MobileGL/MG_IntegrationTest/Harness/PersistentMapPeek.h
|
||||
// Copyright (c) 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
|
||||
//
|
||||
// WHICH ARM A PERSISTENT|WRITE|COHERENT MAP LANDED IN, read from a scenario.
|
||||
//
|
||||
// It exists for exit gate E3's first assertion, and package b1 (b1-v1.md 4.1) names the
|
||||
// spelling: `IsBackendPersistentMapped()` must be FALSE, i.e. the store was NOT adopted and the
|
||||
// CPU shadow is still the source of truth, i.e. the emulated arm. The question has no answer in
|
||||
// the GL API at all - both arms map, both arms take the application's writes, both arms draw the
|
||||
// same pixels - so a scenario with no peek is a scenario that silently tests whichever arm the
|
||||
// driver and the build happened to choose. `MOBILEGL_DISABLE_LARGE_BUFFER_ADOPTION` does not
|
||||
// separate them either: it is read only inside TryAdoptLargeStorage, and a scenario-sized buffer
|
||||
// never reaches the 16 MiB threshold that calls it.
|
||||
//
|
||||
// A separate translation unit for BackendCapsPeek.h's reason, verbatim: the scenario sources
|
||||
// include the GL headers with prototypes and MobileGL's umbrella header is not meant to meet them
|
||||
// in one file.
|
||||
//
|
||||
// Every entry point returns FALSE, touching nothing, where the state is out of reach - on Android
|
||||
// this module links the shipping libMobileGL.so built -fvisibility=hidden, so no internal symbol
|
||||
// resolves, and the tracker half additionally needs a build that compiled MG_Remote/Client. A
|
||||
// caller that gets false must SKIP rather than pass: "could not look" is not "it was emulated".
|
||||
|
||||
#pragma once
|
||||
|
||||
namespace MGITest {
|
||||
|
||||
// True when the peek can answer at all in this build. A scenario asks this first so that its
|
||||
// skip message can name WHY it could not look.
|
||||
bool PersistentMapPeekAvailable();
|
||||
|
||||
// BufferObject::IsBackendPersistentMapped() for the buffer with this GL name.
|
||||
//
|
||||
// returns false -> could not look (no peek in this build, no current context, or no such
|
||||
// buffer). *outAdopted is untouched.
|
||||
// returns true -> *outAdopted is true on the ADOPTED arm (the resource owner minted
|
||||
// host-visible coherent storage and the shadow was released) and false on
|
||||
// the EMULATED arm (the owner declined; the shadow is the truth and the
|
||||
// client has to push blocks). R-6 pins the split arm at emulated.
|
||||
bool PeekBufferIsAdoptedPersistentMap(unsigned int bufferName, bool* outAdopted);
|
||||
|
||||
// True when this build compiled package b1's client-side persistent-map tracker, so the
|
||||
// membership predicate below means something. CMake answers it, by probing MG_Remote/Client
|
||||
// for the symbol: a build that never compiled MG_Remote cannot link the call, so the decision
|
||||
// has to be made before the compiler sees it rather than by __has_include.
|
||||
bool PersistentMapTrackerAvailable();
|
||||
|
||||
// MG_Remote::Client::PersistentMapTracker::IsLivePersistentMap() for this buffer - b1-v1.md
|
||||
// 4.1 item 2. The membership set is meant to be exactly the early-out chain of
|
||||
// SyncPersistentMappedRange; asking it here is what makes a drift between the two fail in a
|
||||
// named test rather than silently stop the push.
|
||||
//
|
||||
// Same contract as above: false means "could not look".
|
||||
bool PeekBufferIsLivePersistentMap(unsigned int bufferName, bool* outLive);
|
||||
|
||||
} // namespace MGITest
|
||||
@@ -91,4 +91,23 @@ namespace MGITest::PipeStatsWindow {
|
||||
return -1;
|
||||
}
|
||||
|
||||
// The same lookup for a counter that is printed as a FIXED-POINT PER-FRAME FIGURE rather
|
||||
// than as an integer, which is every member of the bytes/f[...] bracket: FormatWindowLine
|
||||
// divides each byte class by the window's frame count and prints two decimals whenever the
|
||||
// window contains a Present. `pmap` is one of those, so CounterOrAbsent's strtoll reads
|
||||
// "0.37" as 0 and an assertion that a push HAPPENED silently becomes an assertion that it
|
||||
// pushed at least one whole byte per frame - the one way this counter can be wrong without
|
||||
// ever failing. Returns -1.0 when the line does not carry the name; every real value of a
|
||||
// byte class is >= 0, so the sentinel cannot collide with one.
|
||||
inline double CounterAsDoubleOrAbsent(const Window& window, const char* shortName) {
|
||||
if (!window.found) return -1.0;
|
||||
for (const char* prefix : {" ", "["}) {
|
||||
const std::string key = std::string(prefix) + shortName + "=";
|
||||
const std::size_t at = window.line.find(key);
|
||||
if (at == std::string::npos) continue;
|
||||
return std::strtod(window.line.c_str() + at + key.size(), nullptr);
|
||||
}
|
||||
return -1.0;
|
||||
}
|
||||
|
||||
} // namespace MGITest::PipeStatsWindow
|
||||
|
||||
@@ -28,6 +28,7 @@
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include "HeadlessGL.h"
|
||||
#include "SplitLane.h"
|
||||
|
||||
namespace MGITest {
|
||||
|
||||
@@ -66,6 +67,33 @@ namespace MGITest {
|
||||
|
||||
class ScenarioTest : public ::testing::Test {
|
||||
protected:
|
||||
// THE BEHAVIOURAL HALF OF THE SPLIT LANE'S CLAIM, and it is in the DESTRUCTOR rather than
|
||||
// in TearDown() on purpose: gtest calls only the MOST DERIVED TearDown, and every scenario
|
||||
// that overrides it would have to remember to chain here. The fixture destructor always
|
||||
// runs, and it runs before the test result is finalized, so ADD_FAILURE() is recorded.
|
||||
//
|
||||
// What it asserts: a case that ran in an ARMED split lane must have moved the client
|
||||
// encoder's record ordinal. Everything else in the lane - the pixels, the readbacks, the
|
||||
// arm assertion - is equally true of a monolith run of the same workload; this is the one
|
||||
// statement that is only true if records crossed the ring. An emit table that resolves the
|
||||
// transport and then falls through to the driver passes every other assertion in the file
|
||||
// and fails exactly here.
|
||||
~ScenarioTest() override {
|
||||
if (!m_splitAssertionsArmed) return;
|
||||
if (IsSkipped() || HasFailure()) return;
|
||||
const SplitRuntimeState after = PeekSplitRuntime();
|
||||
if (after.emitSeq <= m_emitSeqAtSetUp) {
|
||||
ADD_FAILURE() << "this case ran in an armed DirectGLES.Split. lane and the client "
|
||||
"encoder's record ordinal did not move: EmitSeq was "
|
||||
<< m_emitSeqAtSetUp << " at SetUp and is " << after.emitSeq
|
||||
<< " now. The workload drew, cleared and read pixels, so records were "
|
||||
"due - a sequence that did not advance means the emit table "
|
||||
"resolved the transport and then did not put anything on the wire, "
|
||||
"which every other assertion in this lane is blind to because a "
|
||||
"monolith run of the same workload produces the same pixels.";
|
||||
}
|
||||
}
|
||||
|
||||
void SetUp() override {
|
||||
m_ready = false;
|
||||
HeadlessGL& gl = HeadlessGL::Get();
|
||||
@@ -95,6 +123,36 @@ namespace MGITest {
|
||||
FAIL() << "MOBILEGL_ITEST_REQUIRE_HARDWARE_GPU is set but the context landed on a software "
|
||||
<< "rasterizer: " << gl.RendererString();
|
||||
}
|
||||
// P5's DirectGLES.Split. lanes, in ONE place rather than in each scenario they point
|
||||
// at - the Split family also points at ClearThenReadPixelsScenario, which is target A
|
||||
// of the reduced path and predates P5, and any later Split lane gets the same
|
||||
// guarantee without anyone having to remember it.
|
||||
//
|
||||
// THE ARMING QUESTION IS ASKED OF THE PROCESS, not of the source tree. Until a real
|
||||
// client session exists, MOBILEGL_TRANSPORT=inproc is parsed and then nothing consumes
|
||||
// it, so every case in the lane would go GREEN against the monolith path under a name
|
||||
// that says it tested the split one. The first version of this guard answered the
|
||||
// question with a CMake grep over c0's stub files, and review finding M-1 falsified it
|
||||
// by renaming one string: eleven lanes armed and eight went green. Harness/
|
||||
// SplitRuntimePeek.h now answers it from MG_Config::Transport, ClientSession::Active()
|
||||
// and ImplementedVerbCount(), none of which a message edit can move. Registrations are
|
||||
// never deleted (gate G14); they skip, naming exactly which fact is not true.
|
||||
if (SplitLane::IsSplitLane()) {
|
||||
if (const std::string splitSkip = SplitLane::SkipReasonForSplitOnlyAssertions();
|
||||
!splitSkip.empty()) {
|
||||
GTEST_SKIP() << splitSkip;
|
||||
}
|
||||
// Armed. Take the wire's baseline, so the destructor can require that this case
|
||||
// actually PUT SOMETHING THROUGH IT (review finding N-5: ten of the eleven Split
|
||||
// entries had no runtime evidence of anything, and their green meant only "the
|
||||
// same GL workload passed").
|
||||
const SplitRuntimeState state = PeekSplitRuntime();
|
||||
m_splitAssertionsArmed = true;
|
||||
m_emitSeqAtSetUp = state.emitSeq;
|
||||
RecordProperty("split_transport", state.transportName);
|
||||
RecordProperty("split_implemented_verbs", static_cast<int>(state.implementedVerbs));
|
||||
RecordProperty("split_emit_seq_at_setup", static_cast<int>(state.emitSeq));
|
||||
}
|
||||
// A scenario starts from a clean slate but shares the context (and so
|
||||
// the renderer's memos) with every other scenario in this process -
|
||||
// which is exactly the situation both shipped bugs needed.
|
||||
@@ -122,6 +180,8 @@ namespace MGITest {
|
||||
}
|
||||
|
||||
bool m_ready = false;
|
||||
bool m_splitAssertionsArmed = false;
|
||||
unsigned long long m_emitSeqAtSetUp = 0;
|
||||
};
|
||||
|
||||
} // namespace MGITest
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
// MobileGL - MobileGL/MG_IntegrationTest/Harness/SplitLane.h
|
||||
// Copyright (c) 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
|
||||
//
|
||||
// The harness markers the `DirectGLES.Split.` ctest entries set.
|
||||
//
|
||||
// WHAT IS AND IS NOT DECIDED HERE. These markers say what the LANE asked for. Whether the lane
|
||||
// GOT it is a different question and it is answered by Harness/SplitRuntimePeek.h, out of the
|
||||
// running process - see the long argument in that header. The split of responsibility matters:
|
||||
// an environment variable is a request, and this package's first version treated a request (plus
|
||||
// a grep over source text) as evidence that the request had been honoured. Review finding M-1
|
||||
// falsified that by renaming one string in six files, which armed eleven lanes and turned eight
|
||||
// of them green against the monolith path.
|
||||
//
|
||||
// MGITEST_SPLIT_LANE=1
|
||||
// Set by the DirectGLES.Split.* entries and by nothing else. It is how a case in ONE binary,
|
||||
// registered many times over, knows which registration it is running under. It is NOT
|
||||
// evidence of anything about the transport.
|
||||
//
|
||||
// MGITEST_PERSISTENT_MAP_ARM=adopted|emulated
|
||||
// The arm the LANE declares. AcquireMemoryRange adopts a PERSISTENT|WRITE map that is not
|
||||
// FLUSH_EXPLICIT whenever the resource owner mints one (BufferObject.cpp:645-661), and
|
||||
// declines to the shadow otherwise - two completely different code paths, chosen by the
|
||||
// driver and the build rather than by the test, and MOBILEGL_DISABLE_LARGE_BUFFER_ADOPTION
|
||||
// does NOT separate them (it guards TryAdoptLargeStorage's 16 MiB path, which a
|
||||
// scenario-sized buffer never reaches at all). So the lane states which arm it expects and
|
||||
// PersistentCoherentMapScenario asserts it landed there, through
|
||||
// Harness/PersistentMapPeek.h's read of IsBackendPersistentMapped(). R-6 pins the split lane
|
||||
// at T2 = declined = emulated.
|
||||
//
|
||||
// MGITEST_PMAP_LANE=1
|
||||
// The one counting entry per transport that reads the library's summary line back. It has a
|
||||
// MOBILEGL_LOG_FILE_PATH of its own and a RESOURCE_LOCK on it.
|
||||
//
|
||||
// MGITEST_SMALL_RING_LANE=1
|
||||
// Exit gate E3(e)'s lane: the same split scenarios with MOBILEGL_IPC_RING_MB and
|
||||
// MOBILEGL_IPC_STAGE_MB at their floor, so that the ring is small enough to make at least one
|
||||
// back-pressure wait happen. A case uses it only to say so in its recorded properties; the
|
||||
// ring sizes themselves reach the library through MOBILEGL_IPC_*.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <cstdlib>
|
||||
#include <string>
|
||||
|
||||
#include "SplitRuntimePeek.h"
|
||||
|
||||
namespace MGITest::SplitLane {
|
||||
|
||||
inline std::string MarkerValue(const char* name) {
|
||||
const char* value = std::getenv(name);
|
||||
return (value != nullptr) ? std::string(value) : std::string();
|
||||
}
|
||||
|
||||
inline bool MarkerIsOne(const char* name) { return MarkerValue(name) == "1"; }
|
||||
|
||||
// True in the DirectGLES.Split.* entries only.
|
||||
inline bool IsSplitLane() { return MarkerIsOne("MGITEST_SPLIT_LANE"); }
|
||||
|
||||
// True in exit gate E3(e)'s small-ring lane.
|
||||
inline bool IsSmallRingLane() { return MarkerIsOne("MGITEST_SMALL_RING_LANE"); }
|
||||
|
||||
// Empty when this case may assert; otherwise the reason to GTEST_SKIP() with. The reason is
|
||||
// spelled out rather than summarised because a skip line is the only thing anyone reads when
|
||||
// they ask "did the split lane actually run" - and because the previous version of this
|
||||
// message named the wrong missing thing (review finding N-1): it said MG_Remote/Client did
|
||||
// not exist, on a tree where it existed and compiled and every entry point aborted.
|
||||
inline std::string SkipReasonForSplitOnlyAssertions() {
|
||||
if (!IsSplitLane()) {
|
||||
return "not the split lane (MGITEST_SPLIT_LANE is unset): this case's split-only "
|
||||
"assertions are about a live MG_Remote client session and say nothing in a "
|
||||
"monolith process";
|
||||
}
|
||||
return SplitRuntimeSkipReason();
|
||||
}
|
||||
|
||||
// "adopted", "emulated", or empty when the lane declared nothing.
|
||||
inline std::string DeclaredPersistentMapArm() { return MarkerValue("MGITEST_PERSISTENT_MAP_ARM"); }
|
||||
|
||||
} // namespace MGITest::SplitLane
|
||||
@@ -0,0 +1,14 @@
|
||||
# Included by CTest after all GoogleTest discovery files (ID-53).
|
||||
# CTest appends ENVIRONMENT here; keep all previously discovered lane settings.
|
||||
file(MAKE_DIRECTORY "@CMAKE_CURRENT_BINARY_DIR@/split-logs")
|
||||
foreach(entry IN LISTS MGL_SPLIT_CLEAR_TESTS MGL_SPLIT_TRIANGLE_TESTS MGL_SPLIT_PMAP_TESTS)
|
||||
set_tests_properties("${entry}" PROPERTIES ENVIRONMENT
|
||||
"MOBILEGL_LOG_FILE_PATH=@CMAKE_CURRENT_BINARY_DIR@/split-logs/${entry}.log")
|
||||
endforeach()
|
||||
foreach(scenario @MGL_SPLIT_SMALL_RING_SCENARIOS@)
|
||||
foreach(entry IN LISTS MGL_SPLIT_SMALL_${scenario}_TESTS)
|
||||
set_tests_properties("${entry}" PROPERTIES ENVIRONMENT
|
||||
"MOBILEGL_LOG_FILE_PATH=@CMAKE_CURRENT_BINARY_DIR@/split-logs/${entry}.log")
|
||||
endforeach()
|
||||
endforeach()
|
||||
# PersistentMapArm retains its existing private path and RESOURCE_LOCK: b1 reads it.
|
||||
@@ -0,0 +1,88 @@
|
||||
// MobileGL - MobileGL/MG_IntegrationTest/Harness/SplitRuntimePeek.cpp
|
||||
// Copyright (c) 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 "SplitRuntimePeek.h"
|
||||
|
||||
// MGITEST_SPLIT_RUNTIME_PEEK is defined by MG_IntegrationTest/CMakeLists.txt under
|
||||
// MOBILEGL_BUILD_DISAGGREGATED and nowhere else. NO SOURCE PROBE decides it: the three symbols
|
||||
// below are c0's, they exist in every disaggregated build from the contract commit onward, and
|
||||
// their VALUES are what answer the question. That is the whole of the fix for review findings
|
||||
// M-1, M-2 and M-3 - there is no longer a string for anyone to rename, comment out, or land
|
||||
// outside a probed directory.
|
||||
#if defined(MGITEST_SPLIT_RUNTIME_PEEK) && !defined(__ANDROID__)
|
||||
#include <Config.h>
|
||||
|
||||
#include <MG_Remote/Client/ClientSession.h>
|
||||
#include <MG_Remote/Client/EmitTables.h>
|
||||
#define MGITEST_SPLIT_RUNTIME_PEEK_LIVE 1
|
||||
#endif
|
||||
|
||||
namespace MGITest {
|
||||
|
||||
SplitRuntimeState PeekSplitRuntime() {
|
||||
SplitRuntimeState state;
|
||||
#if defined(MGITEST_SPLIT_RUNTIME_PEEK_LIVE)
|
||||
using MobileGL::MG_Config::TransportMode;
|
||||
state.peekAvailable = true;
|
||||
state.totalVerbSlots = MobileGL::MG_Remote::Client::kRemoteEmitSlotCount;
|
||||
switch (MobileGL::MG_Config::Transport) {
|
||||
case TransportMode::Monolith: state.transportName = "monolith"; break;
|
||||
case TransportMode::InProcess: state.transportName = "inproc"; break;
|
||||
default: state.transportName = "non-monolith"; break;
|
||||
}
|
||||
state.transportResolved = MobileGL::MG_Config::Transport != TransportMode::Monolith;
|
||||
|
||||
// Active() is c0's one deliberately non-aborting accessor: "does a session exist" has a
|
||||
// legitimate no. Everything below it is only reached through a live session, so nothing
|
||||
// here can trip one of c0's Fatal stubs.
|
||||
MobileGL::MG_Remote::Client::ClientSession* session =
|
||||
MobileGL::MG_Remote::Client::ClientSession::Active();
|
||||
state.sessionActive = session != nullptr;
|
||||
state.implementedVerbs = MobileGL::MG_Remote::Client::ImplementedVerbCount();
|
||||
if (session != nullptr) {
|
||||
// Encoder() returns the member; EmitSeq() returns m_emitSeq. Neither is a stub, and
|
||||
// neither emits anything - this is a read.
|
||||
state.emitSeq = session->Encoder().EmitSeq();
|
||||
}
|
||||
#endif
|
||||
return state;
|
||||
}
|
||||
|
||||
std::string SplitRuntimeSkipReason() {
|
||||
const SplitRuntimeState state = PeekSplitRuntime();
|
||||
if (!state.peekAvailable) {
|
||||
return "this build did not compile MG_Remote (no -DMOBILEGL_BUILD_DISAGGREGATED=ON), or "
|
||||
"this is the Android binary, which links the shipping libMobileGL.so built "
|
||||
"-fvisibility=hidden and can reach no internal symbol. MOBILEGL_TRANSPORT is "
|
||||
"ACCEPTED AND SILENTLY IGNORED in such a build (CONTRACT-P5 5), so a green here "
|
||||
"would be a monolith run under a name that says split";
|
||||
}
|
||||
if (!state.transportResolved) {
|
||||
return "MG_Config::Transport resolved to '" + state.transportName +
|
||||
"', not to a split transport. The variable is read from the process, not from a "
|
||||
"log line - a DEBUG-level pull build prints the same KEY=VALUE string out of "
|
||||
"ConfigLoader's env dump (review M-5). Check MOBILEGL_TRANSPORT reached this "
|
||||
"process";
|
||||
}
|
||||
if (!state.sessionActive) {
|
||||
return "MG_Remote::Client::ClientSession::Active() is null: no client session exists in "
|
||||
"this process. c0 shipped Start() as a Fatal stub and Active() as a deliberate "
|
||||
"null, so this is what 'packages s1 (construction and handshake) and c1 have not "
|
||||
"landed' looks like from inside a running test. The entry stays registered (gate "
|
||||
"G14) and skips rather than passing against the monolith path";
|
||||
}
|
||||
if (state.implementedVerbs == 0) {
|
||||
return "MG_Remote::Client::ImplementedVerbCount() is 0 of " +
|
||||
std::to_string(state.totalVerbSlots) +
|
||||
": the emit table has no real emitter, so every verb this scenario issues would "
|
||||
"take the Fatal{UnmigratedVerb} arm or fall through. Package c1 owns it";
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
} // namespace MGITest
|
||||
@@ -0,0 +1,82 @@
|
||||
// MobileGL - MobileGL/MG_IntegrationTest/Harness/SplitRuntimePeek.h
|
||||
// Copyright (c) 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
|
||||
//
|
||||
// WHETHER THIS PROCESS IS REALLY RUNNING SPLIT, asked of the process rather than of the source
|
||||
// tree. This is what arms every `DirectGLES.Split.` entry.
|
||||
//
|
||||
// WHY IT REPLACED A CONTENT PROBE, and the lesson is worth the paragraph. The first version of
|
||||
// this arming condition was a CMake `file(STRINGS ... REGEX)` conjunction: "some source under
|
||||
// MG_Remote/Client names the c1 symbols AND no source under Client or Server still matches
|
||||
// `Fatal.Unimplemented`". Review finding M-1 did not argue with it, it PERFORMED it: a
|
||||
// `sed -i 's/Fatal{Unimplemented/Fatal{NotYetImplemented/'` over c0's six stub files - every
|
||||
// entry point still ending in std::abort(), RemoteEmitTable() still aborting on sight,
|
||||
// ImplementedVerbCount() still returning 0 - armed all eleven lanes and EIGHT OF THEM WENT GREEN
|
||||
// having run monolith end to end. A comment line containing the marker did the opposite and kept
|
||||
// them dark forever (M-2), and two further stub files outside the two probed directories made a
|
||||
// partial arm possible (M-3).
|
||||
//
|
||||
// The general form of that defect: A STATEMENT ABOUT SOURCE TEXT CAN ALWAYS BE FALSIFIED BY
|
||||
// EDITING SOURCE TEXT, and the people most likely to edit it are the ones landing the packages
|
||||
// the probe is watching for. A statement about what the process actually did cannot. So the three
|
||||
// facts below are read out of the running process, and each is structurally impossible in a
|
||||
// monolith build:
|
||||
//
|
||||
// 1. `MG_Config::Transport != Monolith`. In a build without MOBILEGL_BUILD_DISAGGREGATED,
|
||||
// `Transport` is a `constexpr` Monolith (Config.h:514) and this whole translation unit is
|
||||
// compiled out. Read from the VARIABLE, never from a log line - the log-grep spelling of
|
||||
// this question is satisfied by a DEBUG-level pull build's `Config: Accepted env variable:
|
||||
// MOBILEGL_TRANSPORT=inproc` (review finding M-5).
|
||||
// 2. `ClientSession::Active() != nullptr`. c0 made this one deliberately return null rather
|
||||
// than Fatal, because "does a session exist" has a legitimate "no" - it is the monolith
|
||||
// answer (ClientSession.cpp:31). So it is exactly "a client session exists in this process",
|
||||
// and no amount of editing stub MESSAGES makes a null pointer non-null.
|
||||
// 3. `ImplementedVerbCount() > 0`. c0's stub returns 0; the contract gives this function the
|
||||
// job of making "a table that silently lost an emitter" distinguishable from "a table that
|
||||
// never had one" (EmitTables.h). Zero means there is no emitter to test.
|
||||
//
|
||||
// And one BEHAVIOURAL fact, which is the half that says the run went through the wire rather than
|
||||
// merely that it could have: `ClientSession::Active()->Encoder().EmitSeq()`, the highest record
|
||||
// ordinal this client has produced. A scenario that armed, drew, and emitted nothing has a
|
||||
// sequence that did not move, and that is the shape of an emit table that resolves the transport
|
||||
// and then falls through to the driver.
|
||||
//
|
||||
// Every entry point returns false, touching nothing, where the state is out of reach: in a build
|
||||
// that never compiled MG_Remote, and on Android where this module links the shipping
|
||||
// libMobileGL.so built -fvisibility=hidden. A caller that gets false must SKIP.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <string>
|
||||
|
||||
namespace MGITest {
|
||||
|
||||
// What this process can say about itself. Every field is false/0 where the peek cannot look.
|
||||
struct SplitRuntimeState {
|
||||
// The peek is compiled in at all (MOBILEGL_BUILD_DISAGGREGATED, not Android).
|
||||
bool peekAvailable = false;
|
||||
// MG_Config::Transport != Monolith - this process RESOLVED a split transport.
|
||||
bool transportResolved = false;
|
||||
// The resolved transport, for a message: "monolith", "inproc", "spawn", "unix", "pipe".
|
||||
std::string transportName = "monolith";
|
||||
// ClientSession::Active() != nullptr.
|
||||
bool sessionActive = false;
|
||||
// ImplementedVerbCount(), out of kRemoteEmitSlotCount (71).
|
||||
unsigned int implementedVerbs = 0;
|
||||
unsigned int totalVerbSlots = 0;
|
||||
// The encoder's highest produced record ordinal, or 0 when there is no session.
|
||||
unsigned long long emitSeq = 0;
|
||||
};
|
||||
|
||||
SplitRuntimeState PeekSplitRuntime();
|
||||
|
||||
// Empty when this process is a real split run that can be asserted about; otherwise the
|
||||
// reason to GTEST_SKIP() with, naming the first fact that is not true and the package that
|
||||
// owns it.
|
||||
std::string SplitRuntimeSkipReason();
|
||||
|
||||
} // namespace MGITest
|
||||
@@ -0,0 +1,89 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Validate discovered Split log ownership; read only freshly reset control logs."""
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import xml.etree.ElementTree as ET
|
||||
|
||||
|
||||
def paths(document):
|
||||
owners = {}
|
||||
split = {}
|
||||
for test in document["tests"]:
|
||||
props = {p["name"]: p["value"] for p in test.get("properties", [])}
|
||||
values = [v.split("=", 1)[1] for v in props.get("ENVIRONMENT", [])
|
||||
if v.startswith("MOBILEGL_LOG_FILE_PATH=")]
|
||||
is_split = test["name"].startswith("DirectGLES.Split.")
|
||||
if is_split and (len(values) != 1 or not values[0]):
|
||||
raise ValueError(f"{test['name']}: requires exactly one nonempty MOBILEGL_LOG_FILE_PATH")
|
||||
for value in values:
|
||||
path = str(Path(value).resolve())
|
||||
owners.setdefault(path, []).append(test["name"])
|
||||
if is_split:
|
||||
if not Path(value).is_absolute():
|
||||
raise ValueError(f"{test['name']}: MOBILEGL_LOG_FILE_PATH must be absolute: {value}")
|
||||
split[test["name"]] = path
|
||||
if not split:
|
||||
raise ValueError("integration-split: no entries discovered")
|
||||
for name, path in split.items():
|
||||
if len(owners[path]) != 1:
|
||||
raise ValueError(f"{name}: duplicate MOBILEGL_LOG_FILE_PATH {path}: {owners[path]}")
|
||||
return split
|
||||
|
||||
|
||||
def main():
|
||||
mode = sys.argv[1]
|
||||
if mode == "check":
|
||||
data = subprocess.check_output([sys.argv[2], "--test-dir", sys.argv[3],
|
||||
"--show-only=json-v1"], text=True)
|
||||
selected = paths(json.loads(data))
|
||||
print(f"SplitLogPaths: {len(selected)} entries, {len(set(selected.values()))} distinct private paths")
|
||||
return
|
||||
selected = paths(json.loads(Path(sys.argv[2]).read_text()))
|
||||
selected = {name: path for name, path in selected.items() if re.search(sys.argv[3], name)}
|
||||
if not selected:
|
||||
raise ValueError(f"integration-split: empty selection for {sys.argv[3]}")
|
||||
if mode == "reset":
|
||||
for path in selected.values():
|
||||
Path(path).unlink(missing_ok=True)
|
||||
elif mode == "results":
|
||||
cases = ET.parse(sys.argv[4]).getroot().findall(".//testcase")
|
||||
label = sys.argv[5]
|
||||
by_name = {}
|
||||
for case in cases:
|
||||
by_name.setdefault(case.get("name"), []).append(case)
|
||||
skipped = sum(any(c.find("skipped") is not None for c in by_name.get(n, []))
|
||||
for n in selected)
|
||||
# ID-62: pre-flight Fatal is not evidence that a selected entry ran.
|
||||
if skipped:
|
||||
raise ValueError(f"{label} control: the knob killed the pre-flight, not the entry - "
|
||||
f"{skipped} selected entries skipped")
|
||||
missing = sum(len(by_name.get(n, [])) != 1 or
|
||||
by_name[n][0].get("status") in ("notrun", "disabled") for n in selected)
|
||||
if missing:
|
||||
raise ValueError(f"{label} control: {missing} selected entries did not run")
|
||||
not_failed = sum(c.find("failure") is None or c.get("status") != "fail"
|
||||
for n in selected for c in by_name[n])
|
||||
if not_failed:
|
||||
raise ValueError(f"{label} control: {not_failed} selected entries did not fail")
|
||||
elif mode == "evidence":
|
||||
missing = []
|
||||
for name, path in selected.items():
|
||||
if Path(path).is_file() and re.search(sys.argv[4], Path(path).read_text(errors="replace")):
|
||||
print(f"private-log evidence: {name}: {path}")
|
||||
else:
|
||||
missing.append(f"{name} ({path})")
|
||||
if missing:
|
||||
raise ValueError("E1 FAILED: selected private logs lack expected Fatal{BarrierViolation, \"<slot>\"} line: "
|
||||
+ ", ".join(missing))
|
||||
else:
|
||||
raise ValueError(f"unknown mode: {mode}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
main()
|
||||
except (ValueError, OSError, ET.ParseError, subprocess.CalledProcessError) as error:
|
||||
sys.exit(f"SplitLogPaths FAILED: {error}")
|
||||
@@ -0,0 +1,558 @@
|
||||
// MobileGL - MobileGL/MG_IntegrationTest/Scenarios/PersistentCoherentMapScenario.cpp
|
||||
// Copyright (c) 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
|
||||
//
|
||||
// Scenario - A PERSISTENT|WRITE|COHERENT MAPPING, WRITTEN THROUGH WITH NO GL CALL ANNOUNCING IT.
|
||||
//
|
||||
// Target C of P5's reduced path, spelled out in full at docs/Disaggregated/ARCHITECTURE.md:500:
|
||||
// map PERSISTENT|WRITE|COHERENT, write through the pointer, MAKE NO OTHER GL CALL, draw, read
|
||||
// back and check.
|
||||
//
|
||||
// THE "NO OTHER GL CALL" IS THE ENTIRE POINT and it is exit gate E3(b). Under the split shape the
|
||||
// server has no access to the client's address space, so a coherent mapping that the application
|
||||
// writes into is bytes nobody told anyone about: the client tracker has to push the dirty blocks
|
||||
// at EVERY VALIDATE POINT, on its own initiative, because no glBufferSubData, no
|
||||
// glFlushMappedBufferRange and no unmap will ever come. A scenario that slipped in one announcing
|
||||
// call - even a glGetError between the write and the draw - would let a "push on the next explicit
|
||||
// buffer operation" implementation pass, which is the implementation this gate exists to reject.
|
||||
// So the write/draw pairs below are exactly `std::memcpy(...)` followed by `glDrawArrays(...)`
|
||||
// with nothing in between, and the sequence is map, write, draw, WRITE AGAIN, draw again, read
|
||||
// back: the second write is the one that cannot have been carried by anything the first one did.
|
||||
//
|
||||
// WHICH ARM IS THIS RUNNING ON. A scenario-sized buffer is far below the 16 MiB
|
||||
// kLargeBufferAdoptBytes, so BufferObject::TryAdoptLargeStorage never fires here - but
|
||||
// AcquireMemoryRange has an adoption of its OWN that fires for any PERSISTENT|WRITE map that is
|
||||
// not FLUSH_EXPLICIT (BufferObject.cpp:645-661). So the same test lands in the ADOPTED arm (the
|
||||
// resource owner minted host-visible coherent storage, the CPU shadow was released, the
|
||||
// application writes straight into GPU-visible memory) or in the EMULATED arm (the owner
|
||||
// declined, the shadow is the truth, and the client has to push blocks) depending on driver and
|
||||
// build - and those are completely different code paths. MOBILEGL_DISABLE_LARGE_BUFFER_ADOPTION
|
||||
// does NOT separate them: it guards the 16 MiB path this buffer never reaches.
|
||||
//
|
||||
// So the lane DECLARES the arm (MGITEST_PERSISTENT_MAP_ARM, Harness/SplitLane.h) and
|
||||
// TheMapLandsInTheArmItsLaneDeclares asserts it landed there, reading the library's own summary
|
||||
// line. R-6 pins the split arm at T2 = emulated. The observable that separates them is
|
||||
// `pmap` (persistent-map-push bytes, PipeStats ByteClass::PersistentMapPush): a push happens if
|
||||
// and only if the acquisition was DECLINED, so pmap > 0 IS the black-box spelling of exit gate
|
||||
// E3(d), "MGPipeApplyMapPersistent never returns a non-null pointer under split". It is the only
|
||||
// spelling available from here - an adopted inproc store still renders correctly, because the
|
||||
// address really is valid in this process, which is precisely why E3(d) is worth gating at all -
|
||||
// and a direct count of declines would need a counter from packages b1/v1.
|
||||
//
|
||||
// AND MEMBERSHIP FOLLOWS THE ARM (ID-42). The client's live-persistent-map set is the set of maps
|
||||
// the client still has to PUSH, so an ADOPTED store is deliberately not in it -
|
||||
// PersistentMapTracker::IsLivePersistentMap's second row is IsBackendPersistentMapped(), and an
|
||||
// adopted store's bytes are already in coherent GPU memory. AssertMembership therefore expects
|
||||
// `live == (arm == emulated)`, from the same peek AssertOrRecordArm reads. The arm-INDEPENDENT
|
||||
// claim - "the predicate reads the chain, not the adopt tier" - belongs to a unit case that can
|
||||
// drive both answers on demand (SplitBufferSet.
|
||||
// TheAdoptedArmIsNotAMemberAndItIsTheChainRowThatSaysSo) and not to an integration entry, which
|
||||
// only ever sees whichever arm its driver and transport happen to give it.
|
||||
//
|
||||
// `mpr` (map-persistent-roundtrips) is counted per ACQUISITION ATTEMPT, mint or decline
|
||||
// (ARCHITECTURE.md:492), so it is the SAME NUMBER on both arms and in both transports: that is
|
||||
// what makes exit gate E3(c)'s "mpr equal to the monolith arm's" checkable by one process. Both
|
||||
// lanes assert the same constant against the same workload, so the equality holds by
|
||||
// construction and each lane can fail on its own.
|
||||
|
||||
#include <array>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
|
||||
#include "../Harness/HeadlessGL.h"
|
||||
#include "../Harness/PersistentMapPeek.h"
|
||||
#include "../Harness/PipeStatsWindow.h"
|
||||
#include "../Harness/ScenarioFixture.h"
|
||||
#include "../Harness/SplitLane.h"
|
||||
|
||||
#ifdef GLAPI
|
||||
#undef GLAPI
|
||||
#endif
|
||||
#define GL_GLEXT_PROTOTYPES
|
||||
#include <GL/gl.h>
|
||||
#include <GL/glcorearb.h>
|
||||
#undef GL_GLEXT_PROTOTYPES
|
||||
|
||||
namespace MGITest {
|
||||
namespace {
|
||||
|
||||
constexpr const char* kVertexSource = R"(#version 330 core
|
||||
layout(location = 0) in vec2 aPos;
|
||||
layout(location = 1) in vec3 aColor;
|
||||
out vec3 vColor;
|
||||
void main() {
|
||||
vColor = aColor;
|
||||
gl_Position = vec4(aPos, 0.0, 1.0);
|
||||
}
|
||||
)";
|
||||
|
||||
constexpr const char* kFragmentSource = R"(#version 330 core
|
||||
in vec3 vColor;
|
||||
out vec4 oColor;
|
||||
void main() { oColor = vec4(vColor, 1.0); }
|
||||
)";
|
||||
|
||||
struct Vertex {
|
||||
float x, y;
|
||||
float r, g, b;
|
||||
};
|
||||
|
||||
// A full-viewport quad as two triangles, flat-coloured: one region readback then speaks
|
||||
// for the whole draw, and an offender pixel is a real disagreement rather than an
|
||||
// interpolation difference between two drivers.
|
||||
std::array<Vertex, 6> Quad(float r, float g, float b) {
|
||||
return {{
|
||||
{-1.f, -1.f, r, g, b},
|
||||
{1.f, -1.f, r, g, b},
|
||||
{1.f, 1.f, r, g, b},
|
||||
{-1.f, -1.f, r, g, b},
|
||||
{1.f, 1.f, r, g, b},
|
||||
{-1.f, 1.f, r, g, b},
|
||||
}};
|
||||
}
|
||||
|
||||
constexpr GLsizeiptr kQuadBytes = GLsizeiptr(sizeof(Vertex) * 6);
|
||||
constexpr GLbitfield kCoherentFlags = GL_MAP_WRITE_BIT | GL_MAP_PERSISTENT_BIT | GL_MAP_COHERENT_BIT;
|
||||
// b1-v1.md 4.1 item 7, asserted rather than commented. GL_MAP_FLUSH_EXPLICIT_BIT would
|
||||
// take this buffer OUT of the client's live-persistent-map set on purpose - the
|
||||
// application announces its own writes through resource_flush_range and the push ships
|
||||
// nothing - so a flag added here would turn every assertion below into a statement about
|
||||
// a different mechanism, and it would still draw the right pixels under monolith.
|
||||
static_assert((kCoherentFlags & GL_MAP_FLUSH_EXPLICIT_BIT) == 0,
|
||||
"this scenario is about the PUSH, which is defined only for a persistent "
|
||||
"write map that is NOT FLUSH_EXPLICIT (BufferObject.cpp:645-661)");
|
||||
|
||||
// The ctest entry that reads the summary line sets this and nothing else does; the case
|
||||
// skips everywhere else rather than racing for the lane's log (PipeStatsWindow.h).
|
||||
constexpr const char* kCounterLaneMarker = "MGITEST_PMAP_LANE";
|
||||
|
||||
// Draws issued against the mapping inside the counted window. One mapping, many draws:
|
||||
// "one per acquisition" (1) and "one per draw" (kDrawsInTheWindow) have to be different
|
||||
// numbers or the assertion cannot tell them apart.
|
||||
constexpr int kDrawsInTheWindow = 4;
|
||||
|
||||
// Acquisitions the counted window performs: exactly one glMapBufferRange of exactly one
|
||||
// freshly defined immutable store.
|
||||
constexpr long long kExpectedRoundtrips = 1;
|
||||
|
||||
bool BuildMarkerIsSet(const char* name) {
|
||||
const char* value = std::getenv(name);
|
||||
return value != nullptr && value[0] == '1' && value[1] == '\0';
|
||||
}
|
||||
|
||||
// A store defined with the three bits and mapped once, or a reason the driver refused.
|
||||
// Returns false WITHOUT touching gtest state, so it can be called from a helper: a
|
||||
// GTEST_SKIP() inside a value-returning function does not compile (the macro expands to
|
||||
// a bare `return`), and every earlier attempt to hide one in a factory grew a second
|
||||
// "did it skip" channel that drifted from the first.
|
||||
struct CoherentStore {
|
||||
unsigned int vbo = 0;
|
||||
void* map = nullptr;
|
||||
std::string refusal;
|
||||
};
|
||||
|
||||
CoherentStore MakeCoherentlyMappedQuadStore() {
|
||||
CoherentStore store;
|
||||
glGenBuffers(1, &store.vbo);
|
||||
glBindBuffer(GL_ARRAY_BUFFER, store.vbo);
|
||||
glBufferStorage(GL_ARRAY_BUFFER, kQuadBytes, nullptr, kCoherentFlags);
|
||||
if (FirstGLError() != 0u) {
|
||||
glDeleteBuffers(1, &store.vbo);
|
||||
store.vbo = 0;
|
||||
store.refusal =
|
||||
"this driver has no immutable storage with GL_MAP_PERSISTENT_BIT|GL_MAP_COHERENT_BIT";
|
||||
return store;
|
||||
}
|
||||
// THE ONE ACQUISITION. Everything below writes through this pointer and never maps
|
||||
// again: AcquireMemoryRange only attempts an adoption while the store is not yet
|
||||
// resident, so a second map would emit a second map_persistent and make the counted
|
||||
// window's expected mpr a function of how often the test remapped.
|
||||
store.map = glMapBufferRange(GL_ARRAY_BUFFER, 0, kQuadBytes, kCoherentFlags);
|
||||
if (store.map == nullptr || FirstGLError() != 0u) {
|
||||
glDeleteBuffers(1, &store.vbo);
|
||||
store.vbo = 0;
|
||||
store.map = nullptr;
|
||||
store.refusal = "glMapBufferRange(PERSISTENT|WRITE|COHERENT) was refused";
|
||||
}
|
||||
return store;
|
||||
}
|
||||
|
||||
void DescribeAttributes() {
|
||||
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), nullptr);
|
||||
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex),
|
||||
reinterpret_cast<void*>(2 * sizeof(float)));
|
||||
glEnableVertexAttribArray(0);
|
||||
glEnableVertexAttribArray(1);
|
||||
}
|
||||
|
||||
class PersistentCoherentMapScenario : public ScenarioTest {
|
||||
protected:
|
||||
void SetUp() override {
|
||||
ScenarioTest::SetUp();
|
||||
// Ready() is false both when there is no GPU and when the base SetUp skipped a
|
||||
// Split lane that has no client to assert against (ScenarioFixture.h).
|
||||
if (!Ready()) return;
|
||||
|
||||
std::string error;
|
||||
m_program = CompileProgram(kVertexSource, kFragmentSource, &error);
|
||||
ASSERT_NE(m_program, 0u) << error;
|
||||
|
||||
glGenVertexArrays(1, &m_vao);
|
||||
glBindVertexArray(m_vao);
|
||||
const CoherentStore store = MakeCoherentlyMappedQuadStore();
|
||||
if (!store.refusal.empty()) {
|
||||
GTEST_SKIP() << store.refusal;
|
||||
}
|
||||
m_vbo = store.vbo;
|
||||
m_map = store.map;
|
||||
// b1-v1.md 4.1 item 1, IMMEDIATELY AFTER THE MAP and before anything else can
|
||||
// change the answer. This is the assertion that decides whether the rest of the
|
||||
// scenario means anything.
|
||||
AssertOrRecordArm(m_vbo, "immediately after the map");
|
||||
if (IsSkipped() || HasFatalFailure()) return;
|
||||
AssertMembership(m_vbo, "immediately after the map");
|
||||
if (IsSkipped() || HasFatalFailure()) return;
|
||||
DescribeAttributes();
|
||||
ASSERT_EQ(FirstGLError(), 0u) << "configuring the VAO over the coherently mapped store";
|
||||
}
|
||||
|
||||
// WHICH ARM. b1-v1.md 4.1 items 1 and 5: IsBackendPersistentMapped() false is the
|
||||
// emulated arm - the resource owner DECLINED, the CPU shadow is still the truth, and
|
||||
// the client has to push the mapping's dirty blocks. True is the adopted arm, where
|
||||
// MGPipeApplyMapPersistent handed back a pointer and the shadow was released.
|
||||
//
|
||||
// Under inproc BOTH ARMS RENDER CORRECTLY, because an adopted store's address really
|
||||
// is valid in this process - which is exactly why exit gate E3(d) has to be checked
|
||||
// and cannot be inferred from pixels. Under spawn the adopted arm would be a wild
|
||||
// pointer, so this one assertion is what makes E3 mean the same thing in P5 and P6.
|
||||
//
|
||||
// The lane DECLARES the arm it expects (MGITEST_PERSISTENT_MAP_ARM); a lane that
|
||||
// declares none RECORDS it, because which arm AcquireMemoryRange takes for a
|
||||
// sub-16-MiB map is a property of the driver - llvmpipe mints, a device may decline -
|
||||
// and a monolith lane that pinned one would be red on hardware for no defect.
|
||||
void AssertOrRecordArm(unsigned int vbo, const char* when) {
|
||||
const std::string declared = SplitLane::DeclaredPersistentMapArm();
|
||||
if (!PersistentMapPeekAvailable()) {
|
||||
if (!declared.empty()) {
|
||||
GTEST_SKIP() << "this lane declares the " << declared
|
||||
<< " arm but Harness/PersistentMapPeek cannot look in this "
|
||||
"build (on Android this module links the shipping "
|
||||
"libMobileGL.so, built -fvisibility=hidden, so no internal "
|
||||
"symbol resolves). 'Could not look' is not 'it was "
|
||||
<< declared << "'.";
|
||||
}
|
||||
RecordProperty("persistent_map_arm", "unknown");
|
||||
return;
|
||||
}
|
||||
bool adopted = false;
|
||||
ASSERT_TRUE(PeekBufferIsAdoptedPersistentMap(vbo, &adopted))
|
||||
<< "no frontend BufferObject behind GL buffer " << vbo << " " << when;
|
||||
const char* arm = adopted ? "adopted" : "emulated";
|
||||
// REMEMBERED, because AssertMembership's expectation is a function of it (ID-42)
|
||||
// and the two have to be talking about ONE observation of ONE buffer. A second
|
||||
// peek would be a second question, and a scenario that asked it twice could
|
||||
// straddle a change and then compare two different moments.
|
||||
m_observedArm = adopted ? ObservedArm::Adopted : ObservedArm::Emulated;
|
||||
RecordProperty("persistent_map_arm", arm);
|
||||
if (declared.empty()) return;
|
||||
ASSERT_EQ(declared, std::string(arm))
|
||||
<< "the lane declared the " << declared << " arm and IsBackendPersistentMapped() "
|
||||
<< when << " says " << arm
|
||||
<< ". R-6 pins the split arm at adopt tier T2 = declined = emulated, and the two "
|
||||
"arms are completely different code paths: adopted means the CPU shadow was "
|
||||
"released and the application writes straight into storage the resource owner "
|
||||
"minted, emulated means the shadow is the truth and every validate point has "
|
||||
"to push blocks. Under inproc both render correctly, so pixels cannot tell "
|
||||
"them apart - this is exit gate E3(d) and it is the only thing that can.";
|
||||
}
|
||||
|
||||
// b1-v1.md 4.1 item 2: the client's live-persistent-map set is meant to be exactly
|
||||
// SyncPersistentMappedRange's early-out chain. A drift between the two stops the push
|
||||
// silently; asking here makes it a named failure instead.
|
||||
//
|
||||
// MEMBERSHIP IS A PROPERTY OF THE ARM, NOT OF THE FLAGS - INTEGRATOR DECISION ID-42,
|
||||
// and the first cut of this function got it wrong in a way no lane could see. It
|
||||
// asserted `live` UNCONDITIONALLY, on the grounds that "a PERSISTENT|WRITE|COHERENT map
|
||||
// that is not FLUSH_EXPLICIT is a member by construction". That sentence is true only
|
||||
// on the EMULATED arm. PersistentMapTracker::IsLivePersistentMap's second row is
|
||||
// `if (buffer.IsBackendPersistentMapped()) return false;` - deliberately, because the
|
||||
// predicate must read the CHAIN and not the tier: an adopted store's bytes are already
|
||||
// in coherent GPU memory and there is nothing for the push to ship, so it is not a
|
||||
// member and must not be one. On the adopted arm `live` is false BY DESIGN.
|
||||
//
|
||||
// It survived the first wave because the two builds that ran it could not contradict
|
||||
// it: the push build compiles no MG_Remote, so MGITEST_PERSISTENT_MAP_TRACKER is
|
||||
// undefined and this function returned at the line above before asserting anything;
|
||||
// the split build's monolith lane, where the tracker IS compiled, adopts
|
||||
// (MGPipeApplyMapPersistent's R-6 decline is ANDed with `Transport != Monolith`,
|
||||
// PipeApply.cpp:2005), and seven entries went red the first time the assertion ran at
|
||||
// all.
|
||||
//
|
||||
// So the expectation is `live == (arm == emulated)`, taken from the SAME peek
|
||||
// AssertOrRecordArm read. The arm-independent half - "the predicate reads the chain,
|
||||
// not the tier" - is not an integration claim and is pinned where it can be driven
|
||||
// directly, by MG_Test/Buffer/SplitBufferTest.cpp's
|
||||
// SplitBufferSet.TheAdoptedArmIsNotAMemberAndItIsTheChainRowThatSaysSo.
|
||||
void AssertMembership(unsigned int vbo, const char* when) {
|
||||
if (!PersistentMapTrackerAvailable()) {
|
||||
RecordProperty("persistent_map_membership", "unavailable");
|
||||
return;
|
||||
}
|
||||
if (m_observedArm == ObservedArm::NotLookedAt) {
|
||||
// AssertOrRecordArm could not look, so there is no arm to condition on and
|
||||
// "could not look" is not "it was emulated" (PersistentMapPeek.h). A lane that
|
||||
// DECLARES an arm has already been skipped by AssertOrRecordArm in this case.
|
||||
RecordProperty("persistent_map_membership", "arm unknown");
|
||||
return;
|
||||
}
|
||||
const bool emulated = (m_observedArm == ObservedArm::Emulated);
|
||||
bool live = false;
|
||||
ASSERT_TRUE(PeekBufferIsLivePersistentMap(vbo, &live))
|
||||
<< "the tracker is compiled in but could not answer for GL buffer " << vbo << " " << when;
|
||||
RecordProperty("persistent_map_membership", live ? "member" : "not a member");
|
||||
EXPECT_EQ(live, emulated)
|
||||
<< "the client's live-persistent-map set is the set of maps the client still has "
|
||||
"to PUSH, so membership follows the arm: on the emulated arm this "
|
||||
"PERSISTENT|WRITE|COHERENT non-FLUSH_EXPLICIT map must be a member, and on "
|
||||
"the adopted arm it must not be - IsLivePersistentMap's "
|
||||
"IsBackendPersistentMapped() row takes it out, because an adopted store's "
|
||||
"bytes are already in coherent GPU memory and there is nothing to ship. This "
|
||||
"map landed in the "
|
||||
<< (emulated ? "emulated" : "adopted") << " arm " << when << " and the predicate "
|
||||
<< (live ? "made it a member" : "did not make it a member")
|
||||
<< ". The set is supposed to BE SyncPersistentMappedRange's early-out chain; if "
|
||||
"they have drifted, the push either stops shipping this buffer's blocks or "
|
||||
"starts shipping an adopted store's, and nothing else says so. (ID-42. The "
|
||||
"arm-independent statement - that the predicate reads the chain and not the "
|
||||
"adopt tier - is pinned by SplitBufferSet."
|
||||
"TheAdoptedArmIsNotAMemberAndItIsTheChainRowThatSaysSo, not here.)";
|
||||
}
|
||||
|
||||
void TearDown() override {
|
||||
if (!Ready()) return;
|
||||
glBindVertexArray(0);
|
||||
if (m_vbo != 0) {
|
||||
glBindBuffer(GL_ARRAY_BUFFER, m_vbo);
|
||||
if (m_map != nullptr) glUnmapBuffer(GL_ARRAY_BUFFER);
|
||||
glBindBuffer(GL_ARRAY_BUFFER, 0);
|
||||
glDeleteBuffers(1, &m_vbo);
|
||||
}
|
||||
if (m_vao != 0) glDeleteVertexArrays(1, &m_vao);
|
||||
if (m_program != 0) glDeleteProgram(m_program);
|
||||
m_vbo = m_vao = m_program = 0;
|
||||
m_map = nullptr;
|
||||
}
|
||||
|
||||
// Everything the draw needs, set once, so that the write/draw pairs below are
|
||||
// memcpy + glDrawArrays and nothing else.
|
||||
void ArmTheDrawState() {
|
||||
HeadlessGL& gl = Gl();
|
||||
BindDefaultFramebuffer();
|
||||
glViewport(0, 0, gl.Width(), gl.Height());
|
||||
glDisable(GL_SCISSOR_TEST);
|
||||
glDisable(GL_DEPTH_TEST);
|
||||
ClearTo(0.0f, 0.0f, 0.0f, 1.0f);
|
||||
glUseProgram(m_program);
|
||||
glBindVertexArray(m_vao);
|
||||
EXPECT_EQ(FirstGLError(), 0u) << "arming the draw state";
|
||||
}
|
||||
|
||||
// THE WHOLE CONTRACT, IN TWO STATEMENTS. Nothing may be inserted between them - no
|
||||
// glGetError, no glBindBuffer, no assertion that calls into GL. See the file header.
|
||||
static void WriteThroughTheMapThenDraw(void* map, float r, float g, float b) {
|
||||
const std::array<Vertex, 6> quad = Quad(r, g, b);
|
||||
std::memcpy(map, quad.data(), sizeof(Vertex) * quad.size());
|
||||
glDrawArrays(GL_TRIANGLES, 0, 6);
|
||||
}
|
||||
|
||||
// The whole surface minus an 8-pixel inset, so a primitive edge cannot contribute an
|
||||
// offender.
|
||||
::testing::AssertionResult WholeSurfaceIs(const Image& image, const char* color,
|
||||
const std::string& when) {
|
||||
return RegionIsMostly(image, 8, image.Width() - 9, 8, image.Height() - 9, color, 0.0, when);
|
||||
}
|
||||
|
||||
// The arm this scenario OBSERVED, as opposed to the one its lane declared. A lane may
|
||||
// declare none (the monolith counting lane does not), and the peek may be unable to
|
||||
// look at all, so the third state is not "assume emulated" - it is "there is no arm to
|
||||
// condition on", and AssertMembership records rather than asserts under it.
|
||||
enum class ObservedArm { NotLookedAt, Adopted, Emulated };
|
||||
ObservedArm m_observedArm = ObservedArm::NotLookedAt;
|
||||
|
||||
unsigned int m_program = 0;
|
||||
unsigned int m_vao = 0;
|
||||
unsigned int m_vbo = 0;
|
||||
void* m_map = nullptr;
|
||||
};
|
||||
|
||||
} // namespace
|
||||
|
||||
// E3(b): map, write, draw, WRITE AGAIN, draw again, read back. The second write is announced
|
||||
// by nothing at all, so an implementation that pushed on an explicit buffer operation fails
|
||||
// here and only here.
|
||||
TEST_F(PersistentCoherentMapScenario, TwoWritesThroughTheCoherentPointerEachReachTheirOwnDraw) {
|
||||
if (!Ready() || IsSkipped()) return;
|
||||
ArmTheDrawState();
|
||||
|
||||
WriteThroughTheMapThenDraw(m_map, 0.0f, 1.0f, 0.0f);
|
||||
const Image afterFirst = ReadPixels(Gl().Width(), Gl().Height());
|
||||
EXPECT_EQ(FirstGLError(), 0u);
|
||||
EXPECT_TRUE(WholeSurfaceIs(afterFirst, "green",
|
||||
"the first write through a PERSISTENT|WRITE|COHERENT mapping, with "
|
||||
"no GL call announcing it"));
|
||||
|
||||
// The second write. Whatever carried the first one - an unmap, a flush, the definition
|
||||
// itself - is in the past; only a push taken at this draw's validate point can carry it.
|
||||
WriteThroughTheMapThenDraw(m_map, 1.0f, 0.0f, 0.0f);
|
||||
const Image afterSecond = ReadPixels(Gl().Width(), Gl().Height());
|
||||
EXPECT_EQ(FirstGLError(), 0u);
|
||||
EXPECT_TRUE(WholeSurfaceIs(afterSecond, "red",
|
||||
"the SECOND write through the same mapping, announced by nothing: "
|
||||
"this is exit gate E3(b), and a 'push on the next explicit buffer "
|
||||
"operation' implementation reads back the FIRST write's colour here"));
|
||||
// E3(d) again, AFTER the draws: b1-v1.md 4.1 item 5 asks that the arm hold across the
|
||||
// whole scenario, not only at the map. A late adoption - the owner declining once and
|
||||
// minting on a later validate point - would leave the first assertion true and this one
|
||||
// false, and would be invisible in every pixel this case reads.
|
||||
AssertOrRecordArm(m_vbo, "after both writes and both draws");
|
||||
Gl().EndFrame();
|
||||
}
|
||||
|
||||
// The same claim across a frame boundary, because the dirty-block set is per-frame state on
|
||||
// the client and a tracker that cleared it at Present without pushing would pass the case
|
||||
// above and fail this one.
|
||||
TEST_F(PersistentCoherentMapScenario, AWriteAfterAFrameBoundaryReachesTheNextFramesDraw) {
|
||||
if (!Ready() || IsSkipped()) return;
|
||||
ArmTheDrawState();
|
||||
|
||||
WriteThroughTheMapThenDraw(m_map, 0.0f, 1.0f, 0.0f);
|
||||
const Image first = ReadPixels(Gl().Width(), Gl().Height());
|
||||
EXPECT_TRUE(WholeSurfaceIs(first, "green", "frame 0's write through the mapping"));
|
||||
Gl().EndFrame();
|
||||
|
||||
ArmTheDrawState();
|
||||
WriteThroughTheMapThenDraw(m_map, 1.0f, 0.0f, 0.0f);
|
||||
const Image second = ReadPixels(Gl().Width(), Gl().Height());
|
||||
EXPECT_EQ(FirstGLError(), 0u);
|
||||
EXPECT_TRUE(WholeSurfaceIs(second, "red",
|
||||
"frame 1's write through the SAME mapping, after a Present"));
|
||||
AssertOrRecordArm(m_vbo, "after a frame boundary and two draws");
|
||||
Gl().EndFrame();
|
||||
}
|
||||
|
||||
// E3(c) and the black-box half of E3(d). ONE reading case, in a lane of its own, for the
|
||||
// reason PipeStatsWindow.h gives: the library truncates its log per process, so two readers
|
||||
// in one lane race under `ctest -j`.
|
||||
TEST_F(PersistentCoherentMapScenario, TheMapLandsInTheArmItsLaneDeclares) {
|
||||
if (!Ready() || IsSkipped()) return;
|
||||
if (!BuildMarkerIsSet(kCounterLaneMarker)) {
|
||||
GTEST_SKIP() << "not the counting lane: " << kCounterLaneMarker
|
||||
<< " is set only by the *.PersistentMapArm.* entries, which give this case "
|
||||
"a private MOBILEGL_LOG_FILE_PATH and a RESOURCE_LOCK on it";
|
||||
}
|
||||
if (!BuildMarkerIsSet("MGITEST_PIPE_PUSH_BUILD")) {
|
||||
GTEST_SKIP() << "pull build: mpr= lives in the cso[ bracket, which is compiled only "
|
||||
"under MOBILEGL_PIPE_PUSH, so the summary line does not carry it";
|
||||
}
|
||||
if (!BuildMarkerIsSet("MGITEST_PIPE_RESOURCE_EMITTER_PRESENT")) {
|
||||
GTEST_SKIP() << "no MG_Impl/Pipe source emits MapPersistentRoundtrips on this tree, so "
|
||||
"mpr= is structurally zero and an assertion about it would be a "
|
||||
"statement about nothing";
|
||||
}
|
||||
|
||||
Gl().EndFrame(); // close the setup window; SetUp's own store and map go in it
|
||||
|
||||
// One acquisition inside the counted window: one fresh immutable store, mapped once.
|
||||
const CoherentStore store = MakeCoherentlyMappedQuadStore();
|
||||
if (!store.refusal.empty()) {
|
||||
GTEST_SKIP() << store.refusal;
|
||||
}
|
||||
AssertOrRecordArm(store.vbo, "immediately after the counted window's map");
|
||||
if (IsSkipped() || HasFatalFailure()) return;
|
||||
AssertMembership(store.vbo, "immediately after the counted window's map");
|
||||
if (IsSkipped() || HasFatalFailure()) return;
|
||||
glBindVertexArray(m_vao);
|
||||
glBindBuffer(GL_ARRAY_BUFFER, store.vbo);
|
||||
DescribeAttributes();
|
||||
ArmTheDrawState();
|
||||
|
||||
// ... and then a frame's worth of traffic through it. Four writes and four draws must
|
||||
// still cost ONE acquisition.
|
||||
for (int draw = 0; draw < kDrawsInTheWindow; ++draw) {
|
||||
WriteThroughTheMapThenDraw(store.map, 0.0f, 1.0f, 0.0f);
|
||||
}
|
||||
const Image image = ReadPixels(Gl().Width(), Gl().Height());
|
||||
EXPECT_EQ(FirstGLError(), 0u);
|
||||
EXPECT_TRUE(WholeSurfaceIs(image, "green",
|
||||
"the draws inside the counted window; if they never landed, every "
|
||||
"number below is a number about nothing"));
|
||||
|
||||
Gl().EndFrame(); // the swap that emits the window covering exactly the work above
|
||||
|
||||
const PipeStatsWindow::Window window = PipeStatsWindow::LastFromLaneLog();
|
||||
ASSERT_TRUE(window.found) << "no 'MGPipe stats:' line in " << PipeStatsWindow::LibraryLogPath()
|
||||
<< ": either MOBILEGL_PIPE_STATS / MOBILEGL_PIPE_STATS_PERIOD did "
|
||||
"not reach the process, or nothing reached PipeStats::OnPresent.";
|
||||
RecordProperty("stats_line", window.line.c_str());
|
||||
|
||||
const long long roundtrips = PipeStatsWindow::CounterOrAbsent(window, "mpr");
|
||||
ASSERT_GE(roundtrips, 0) << "the summary line carries no mpr= field: " << window.line;
|
||||
EXPECT_EQ(roundtrips, kExpectedRoundtrips)
|
||||
<< "one PERSISTENT|WRITE|COHERENT map of one freshly defined store is ONE acquisition "
|
||||
"attempt, mint or decline (ARCHITECTURE.md:492). This window mapped once and drew "
|
||||
<< kDrawsInTheWindow << " times, so " << kExpectedRoundtrips << " is the whole cost; "
|
||||
<< kDrawsInTheWindow
|
||||
<< " would mean the acquisition moved onto the draw path. The number is counted as "
|
||||
"ATTEMPTS precisely so that it is the SAME on the adopted and the emulated arm and "
|
||||
"under both transports - which is what makes exit gate E3(c)'s 'mpr equal to the "
|
||||
"monolith arm's' checkable by one process. It reported: "
|
||||
<< window.line;
|
||||
|
||||
// E3(c)'s second half: the bytes the push actually shipped. `pmap` is bytes PUSHED because
|
||||
// a persistently mapped range had to be published, so on the emulated arm a window with
|
||||
// four writes and four draws through a live coherent mapping cannot be zero.
|
||||
//
|
||||
// THE ARM ITSELF IS NOT DERIVED FROM THIS NUMBER. It is asserted from
|
||||
// IsBackendPersistentMapped() at the map and again after the draws (b1-v1.md 4.1 items 1
|
||||
// and 5), which is the direct observable; pmap is the CONSEQUENCE and is checked as a
|
||||
// cross-check. Deriving the arm from pmap would have made "the push was never wired" and
|
||||
// "the store was adopted" the same reading, and they are different defects with different
|
||||
// owners.
|
||||
const double pushedBytes = PipeStatsWindow::CounterAsDoubleOrAbsent(window, "pmap");
|
||||
ASSERT_GE(pushedBytes, 0.0) << "the summary line carries no pmap= field: " << window.line;
|
||||
RecordProperty("persistent_map_push_bytes_per_frame", std::to_string(pushedBytes).c_str());
|
||||
RecordProperty("map_persistent_roundtrips", std::to_string(roundtrips).c_str());
|
||||
|
||||
if (SplitLane::DeclaredPersistentMapArm() == "emulated") {
|
||||
EXPECT_GT(pushedBytes, 0.0)
|
||||
<< "the emulated arm pushes the mapping's dirty blocks at every validate point, so "
|
||||
"a window with "
|
||||
<< kDrawsInTheWindow
|
||||
<< " writes and as many draws through a live coherent mapping cannot have pushed "
|
||||
"zero bytes. Zero here with MOBILEGL_IPC_PERSISTENT_BLOCK_KB at its default "
|
||||
"means the push is not reaching this buffer - which is a DIFFERENT defect from "
|
||||
"the store having been adopted, and the arm assertion above has already ruled "
|
||||
"that one out. Zero with the knob set to 0 is exit gate E3(a)'s negative control "
|
||||
"working as intended. Line: "
|
||||
<< window.line;
|
||||
} else {
|
||||
// Recorded, not asserted: on this arm the number is whatever the driver's adoption
|
||||
// decision makes it, and it is the figure MEASUREMENTS wants beside the split one.
|
||||
RecordProperty("persistent_map_push_note",
|
||||
"recorded only - this lane declares no emulated arm");
|
||||
}
|
||||
|
||||
unsigned int vbo = store.vbo;
|
||||
glBindVertexArray(0);
|
||||
glBindBuffer(GL_ARRAY_BUFFER, vbo);
|
||||
glUnmapBuffer(GL_ARRAY_BUFFER);
|
||||
glBindBuffer(GL_ARRAY_BUFFER, 0);
|
||||
glDeleteBuffers(1, &vbo);
|
||||
}
|
||||
|
||||
} // namespace MGITest
|
||||
@@ -0,0 +1,210 @@
|
||||
// MobileGL - MobileGL/MG_IntegrationTest/Scenarios/TriangleScenario.cpp
|
||||
// Copyright (c) 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
|
||||
//
|
||||
// Scenario - THE SMALLEST THING THAT DRAWS: one VBO, one program, one VAO, a clear, a
|
||||
// VBO-backed glDrawArrays and a glReadPixels.
|
||||
//
|
||||
// This is target B of P5's reduced path (BRIEF-P5 4). It is an ORDINARY GL scenario and runs
|
||||
// in every lane; the DirectGLES.Split. entries run the same two cases with
|
||||
// MOBILEGL_TRANSPORT=inproc, where the same body is the smallest workload that crosses a real
|
||||
// ring. Four things about its shape are decisions rather than defaults, and all four come from
|
||||
// the measured verb census (~/w7/notes/p5/verb-census.md):
|
||||
//
|
||||
// 1. THE DRAW IS VBO-BACKED AND HAS NO CLIENT-ARRAY INDICES. glDrawArrays against a buffer
|
||||
// bound to GL_ARRAY_BUFFER, never glDrawElements with a client pointer. That keeps
|
||||
// kDrawHasUserIndices' MGHostSpan out of the first IPC frame entirely - the split filling of
|
||||
// a host span is P8 - and it is why table 0 can pin kCapNeedsHostIndexBytes and
|
||||
// kCapNeedsHostUboBytes at 0 for the whole of P5.
|
||||
//
|
||||
// 2. THERE IS NO glFlush, AND ITS ABSENCE IS THE POINT. `Flush` is not a GLFunctionsTable slot
|
||||
// at all, and MG_Impl/GLImpl/Exporting/Definitions.cpp:111-112 makes glFlush() and glFinish()
|
||||
// LITERALLY EMPTY BODIES - one MGLOG_D and a return. A scenario that called glFlush to order
|
||||
// its readback would be ordering nothing and would still pass, which makes the ordering it
|
||||
// believes in unfalsifiable. glReadPixels IS the ordering point: it is a blocking readback on
|
||||
// both backends today and a SEG_REPLY round trip under split, so the pixels it returns are
|
||||
// the pixels the draw produced or the case fails.
|
||||
//
|
||||
// 3. THE FIRST CASE ENDS WITH EndFrame(), DELIBERATELY. `Present` has ZERO call sites in
|
||||
// MG_Impl - it is reached only through EGLImpl.cpp:178 -> BackendObject.cpp:396 - so a
|
||||
// scenario that never swaps never touches it, and B would then exercise a STRICT SUBSET of
|
||||
// what ClearThenReadPixelsScenario already covers. BRIEF-P5 4.B lists Present(67) among the
|
||||
// catalogue rows this target needs, so the frame boundary is here on purpose: B is A's slot
|
||||
// set plus DrawArrays, not minus Present.
|
||||
//
|
||||
// 4. THE SECOND CASE REDRAWS ACROSS A FRAME BOUNDARY WITHOUT REBUILDING ANYTHING. The VBO, the
|
||||
// program and the VAO outlive the swap and only the clear colour changes. Under split that
|
||||
// is the difference between "the client re-declares every object every frame" (which would
|
||||
// pass a single-frame test and be the whole cost of the design) and a steady state; under
|
||||
// monolith it is the backend's per-frame retire/aging path, which is exactly where P3a's
|
||||
// respecify bug lived.
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "../Harness/HeadlessGL.h"
|
||||
#include "../Harness/ScenarioFixture.h"
|
||||
|
||||
#ifdef GLAPI
|
||||
#undef GLAPI
|
||||
#endif
|
||||
#define GL_GLEXT_PROTOTYPES
|
||||
#include <GL/gl.h>
|
||||
#include <GL/glcorearb.h>
|
||||
#undef GL_GLEXT_PROTOTYPES
|
||||
|
||||
namespace MGITest {
|
||||
namespace {
|
||||
|
||||
// #version 330 core, because that is what the retrace lane's
|
||||
// MESA_GLSL_VERSION_OVERRIDE pins and what every other scenario in this module that does
|
||||
// not need a later feature uses.
|
||||
constexpr const char* kVertexSource = R"(#version 330 core
|
||||
layout(location = 0) in vec2 aPos;
|
||||
layout(location = 1) in vec3 aColor;
|
||||
out vec3 vColor;
|
||||
void main() {
|
||||
vColor = aColor;
|
||||
gl_Position = vec4(aPos, 0.0, 1.0);
|
||||
}
|
||||
)";
|
||||
|
||||
constexpr const char* kFragmentSource = R"(#version 330 core
|
||||
in vec3 vColor;
|
||||
out vec4 oColor;
|
||||
void main() { oColor = vec4(vColor, 1.0); }
|
||||
)";
|
||||
|
||||
struct Vertex {
|
||||
float x, y;
|
||||
float r, g, b;
|
||||
};
|
||||
|
||||
// A single triangle with its base at y = -0.8 and its apex at y = +0.8, so the
|
||||
// interior box the cases assert on (the middle 10% of the width, a fifth of the way up)
|
||||
// is far from every edge and the corner box they assert the CLEAR on is far outside it.
|
||||
// Flat green: one colour over the whole primitive means an offender pixel is a real
|
||||
// disagreement rather than an interpolation rounding difference between two drivers.
|
||||
constexpr Vertex kTriangle[3] = {
|
||||
{-0.8f, -0.8f, 0.0f, 1.0f, 0.0f},
|
||||
{0.8f, -0.8f, 0.0f, 1.0f, 0.0f},
|
||||
{0.0f, 0.8f, 0.0f, 1.0f, 0.0f},
|
||||
};
|
||||
|
||||
class TriangleScenario : public ScenarioTest {
|
||||
protected:
|
||||
void SetUp() override {
|
||||
ScenarioTest::SetUp();
|
||||
// Ready() is false both when there is no GPU and when the base SetUp skipped a
|
||||
// Split lane that has no client to assert against (ScenarioFixture.h).
|
||||
if (!Ready()) return;
|
||||
|
||||
std::string error;
|
||||
m_program = CompileProgram(kVertexSource, kFragmentSource, &error);
|
||||
ASSERT_NE(m_program, 0u) << error;
|
||||
|
||||
glGenVertexArrays(1, &m_vao);
|
||||
glBindVertexArray(m_vao);
|
||||
glGenBuffers(1, &m_vbo);
|
||||
glBindBuffer(GL_ARRAY_BUFFER, m_vbo);
|
||||
glBufferData(GL_ARRAY_BUFFER, GLsizeiptr(sizeof(kTriangle)), kTriangle, GL_STATIC_DRAW);
|
||||
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), nullptr);
|
||||
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex),
|
||||
reinterpret_cast<void*>(2 * sizeof(float)));
|
||||
glEnableVertexAttribArray(0);
|
||||
glEnableVertexAttribArray(1);
|
||||
ASSERT_EQ(FirstGLError(), 0u) << "building the one VBO and one VAO this scenario has";
|
||||
}
|
||||
|
||||
void TearDown() override {
|
||||
if (!Ready() || IsSkipped()) return;
|
||||
glBindVertexArray(0);
|
||||
glBindBuffer(GL_ARRAY_BUFFER, 0);
|
||||
if (m_vbo != 0) glDeleteBuffers(1, &m_vbo);
|
||||
if (m_vao != 0) glDeleteVertexArrays(1, &m_vao);
|
||||
if (m_program != 0) glDeleteProgram(m_program);
|
||||
m_vbo = m_vao = m_program = 0;
|
||||
}
|
||||
|
||||
// Clear, draw, read back. No glFlush between the draw and the readback: see the
|
||||
// file header, point 2.
|
||||
Image ClearThenDrawThenRead(float clearR, float clearG, float clearB) {
|
||||
HeadlessGL& gl = Gl();
|
||||
BindDefaultFramebuffer();
|
||||
glViewport(0, 0, gl.Width(), gl.Height());
|
||||
glDisable(GL_SCISSOR_TEST);
|
||||
glDisable(GL_DEPTH_TEST);
|
||||
ClearTo(clearR, clearG, clearB, 1.0f);
|
||||
glUseProgram(m_program);
|
||||
glBindVertexArray(m_vao);
|
||||
glDrawArrays(GL_TRIANGLES, 0, 3);
|
||||
return ReadPixels(gl.Width(), gl.Height());
|
||||
}
|
||||
|
||||
// The box inside the triangle: the middle tenth of the width, a fifth of the way up
|
||||
// from the base, which is interior for the vertex set above at any surface size the
|
||||
// harness uses.
|
||||
void ExpectTriangleInterior(const Image& image, const char* color, const std::string& when) {
|
||||
const int w = image.Width();
|
||||
const int h = image.Height();
|
||||
EXPECT_TRUE(RegionIsMostly(image, (w * 45) / 100, (w * 55) / 100, (h * 20) / 100,
|
||||
(h * 30) / 100, color, 0.0, when));
|
||||
}
|
||||
|
||||
// The bottom-left corner, which is below the triangle's base and left of its left
|
||||
// edge, so it carries the clear and nothing else.
|
||||
void ExpectClearedCorner(const Image& image, const char* color, const std::string& when) {
|
||||
const int w = image.Width();
|
||||
const int h = image.Height();
|
||||
EXPECT_TRUE(RegionIsMostly(image, 0, (w * 5) / 100, 0, (h * 5) / 100, color, 0.0, when));
|
||||
}
|
||||
|
||||
unsigned int m_program = 0;
|
||||
unsigned int m_vao = 0;
|
||||
unsigned int m_vbo = 0;
|
||||
};
|
||||
|
||||
} // namespace
|
||||
|
||||
// The reduced path's target B, in one case: GetCaps (reached by the first glCompileShader of
|
||||
// the context, not by any verb - verb-census trap 2), Clear, DrawArrays, ReadPixels, Present.
|
||||
TEST_F(TriangleScenario, AVboBackedTriangleReachesReadPixels) {
|
||||
if (!Ready() || IsSkipped()) return;
|
||||
|
||||
const Image image = ClearThenDrawThenRead(0.0f, 0.0f, 1.0f);
|
||||
EXPECT_EQ(FirstGLError(), 0u);
|
||||
ExpectTriangleInterior(image, "green", "the interior of a VBO-backed glDrawArrays triangle");
|
||||
ExpectClearedCorner(image, "blue", "the corner outside the triangle, which carries the clear");
|
||||
|
||||
// The frame boundary, deliberately (file header, point 3): this is the only thing in the
|
||||
// scenario that reaches the Present slot.
|
||||
Gl().EndFrame();
|
||||
}
|
||||
|
||||
// Steady state: the same VBO, program and VAO across a swap, with only the clear colour
|
||||
// changing. Nothing is re-created, so a client that re-declared its objects every frame and
|
||||
// a backend that lost them at the frame boundary both show up here and in no single-frame
|
||||
// case.
|
||||
TEST_F(TriangleScenario, TheSameVboAndVaoRedrawAcrossAFrameBoundary) {
|
||||
if (!Ready() || IsSkipped()) return;
|
||||
|
||||
const Image first = ClearThenDrawThenRead(0.0f, 0.0f, 1.0f);
|
||||
ExpectTriangleInterior(first, "green", "frame 0's triangle");
|
||||
ExpectClearedCorner(first, "blue", "frame 0's clear");
|
||||
Gl().EndFrame();
|
||||
|
||||
// Second frame: black clear, nothing else touched.
|
||||
const Image second = ClearThenDrawThenRead(0.0f, 0.0f, 0.0f);
|
||||
EXPECT_EQ(FirstGLError(), 0u);
|
||||
ExpectTriangleInterior(second, "green",
|
||||
"frame 1's triangle, drawn from the SAME VBO and VAO with no "
|
||||
"re-specification of either");
|
||||
ExpectClearedCorner(second, "black", "frame 1's clear, which is the only thing that changed");
|
||||
Gl().EndFrame();
|
||||
}
|
||||
|
||||
} // namespace MGITest
|
||||
@@ -0,0 +1,300 @@
|
||||
// MobileGL - MobileGL/MG_Pipe/FieldOwnership.def
|
||||
// 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
|
||||
|
||||
// The hand-maintained half of TABLE 2 (CONTRACT-P5.md section 3, R-7): where every
|
||||
// PipeInputs field's value comes from once the backend is a server.
|
||||
//
|
||||
// scripts/gen_pipe_field_ownership.py joins this file against the DERIVED half and writes
|
||||
// generated/PipeFieldOwnership.inc. CI runs `--check` and `--self-test` beside gen_pipe.py's.
|
||||
//
|
||||
// THE FOUR CLASSES (CONTRACT-P5.md section 3):
|
||||
//
|
||||
// RECORD_SUPPLIED a pushed record supplies the WHOLE field, so the server never needs
|
||||
// the client for it. THIS CLASS IS DERIVED, NOT LISTED: it is
|
||||
// kMGPipeFieldEmittedBy != kNone (Coverage.def's MGP_COVERAGE_EMITTED_LIST)
|
||||
// minus the fields EmittedCallSuppliesTheWholeField refuses
|
||||
// (MG_Impl/Pipe/PipeFill.cpp). 32 fields today. A row below that names a
|
||||
// field the derivation already placed here is a CONTRADICTION and stops
|
||||
// the generator - which is the only way this file can stay true as the
|
||||
// emitted list grows.
|
||||
//
|
||||
// APPLIER_DERIVED the applier writes it out of records it already applies, but no row of
|
||||
// the emitted list claims it, so the derivation above cannot see it.
|
||||
//
|
||||
// BARRIER_PULLED P5's DEBT. The server answers by reading a value the client's residual
|
||||
// fill (PipeFill.cpp step 4) left in the single shared gPipeInputs while
|
||||
// the verb barrier holds both threads apart (R-1). Correct only because
|
||||
// of that barrier, which is why the barrier is load-bearing rather than
|
||||
// cautious. Every row NAMES THE PHASE THAT RETIRES IT; a row with no
|
||||
// phase stops the generator. Each such read increments
|
||||
// PipeStats::CallClass::ResidualPulls (`rsp`) and, under
|
||||
// MOBILEGL_IPC_STRICT_ERRORS=1, is Fatal.
|
||||
//
|
||||
// FATAL no carrier, and the reduced path never reads it, so a read is a real
|
||||
// defect: Fatal{UnmigratedPipeInput, "<Field>@<verb>"}.
|
||||
//
|
||||
// A field in NONE of the four is a generator error and therefore a build failure (R-7.1).
|
||||
// A field in TWO is the same. That is the whole mechanism: a hand-maintained table would be
|
||||
// wrong within a week, and this one cannot be silently incomplete.
|
||||
//
|
||||
// clang-format off
|
||||
|
||||
// X(Field, Class, RetiringPhase, Why)
|
||||
//
|
||||
// RetiringPhase is `-` for every class but BARRIER_PULLED, where it is the ROADMAP phase
|
||||
// whose row stops the pull. It is a string, not an enum, because two of them name two
|
||||
// phases for the two backends and flattening that would lose the half that matters.
|
||||
#define MGP_FIELD_OWNERSHIP_LIST(X) \
|
||||
/* ---- BARRIER_PULLED: the 20 non-sticky rows the reduced path actually reads ---- */ \
|
||||
/* scout-unmigrated-census section 3 intersects each verb class's may-read mask with "no */ \
|
||||
/* record supplies it" and unions kClear (7 of 18), kDraw (19 of 47) and kReadback (12 of */ \
|
||||
/* 17). That union is 21 fields; GetPixelStoreParameters is the 21st and it is */ \
|
||||
/* APPLIER_DERIVED below, for the reason written there. OpenRA adds no field to this set - */ \
|
||||
/* it widens the SITE set, not the field set. */ \
|
||||
X(GetActiveTextureUnit, BARRIER_PULLED, "P3b/P4b", \
|
||||
"the server answers from its own state; Coverage.def:215-219 says no call carries it") \
|
||||
/* DirectGLES.cpp:4486, PrepareForDraw, UNCONDITIONAL ON EVERY DRAW. No #if, no arm guard, */ \
|
||||
/* no record fallback, and PipeFill.cpp:1902-1905 says outright that what retires the pull */ \
|
||||
/* is P8, not a better applier: the storage is a SharedPtr<VertexArrayObject> and */ \
|
||||
/* bind_vertex_elements carries an eight-byte {slot, gen}. */ \
|
||||
X(GetBoundVertexArray, BARRIER_PULLED, "P8", \
|
||||
"frontend heap reference; the record carries a handle, the mirror is a pointer") \
|
||||
/* 18 Espryt sites + 11 Magma. Coverage.def:37-70 splits the 15 BufferTargets across three */ \
|
||||
/* calls and leaves SEVEN with no carrier at all (CopyRead, CopyWrite, PixelPack, */ \
|
||||
/* PixelUnpack, Texture, DispatchIndirect, Query), which is why the FIELD is pulled even */ \
|
||||
/* though eight targets are covered. */ \
|
||||
X(GetBufferBindingSlot, BARRIER_PULLED, "P8 (indirect), P9 (readback), P13 (transfer)", \
|
||||
"7 of 15 BufferTargets have no call; the field is one array over all 15") \
|
||||
X(GetBufferBindingPoint, BARRIER_PULLED, "P3b/P4b, P7", \
|
||||
"frontend BindingSlotRange1D pointer") \
|
||||
X(GetTouchedBufferBindingPointCount, BARRIER_PULLED, "P3b/P4b", \
|
||||
"no call carries the touched-count high-water mark") \
|
||||
/* The applier CANNOT reproduce GLContext's cross-view conversion: the frontend writes */ \
|
||||
/* (Int32)value into intValue while MGPipeApplySetVertexAttribDefaults memcpys one Data[4] */ \
|
||||
/* into all three views (PipeFill.cpp:1884-1896). So the record exists, the applier writes */ \
|
||||
/* the field, and the value is still wrong - which is BARRIER_PULLED, not APPLIER_DERIVED. */ \
|
||||
X(GetCurrentVertexAttribute, BARRIER_PULLED, "P3b/P4b", \
|
||||
"the applier writes it but cannot reproduce the cross-view conversion") \
|
||||
/* 8 Espryt sites through GetFramebufferBindingSlotChecked + 13 Magma. SyncCurrentFBO */ \
|
||||
/* (:2995) is SELF-DECLARED monolith glue (DirectGLES.cpp:2961-2965) while BindCurrentFBO */ \
|
||||
/* (:4303-4353) is already split-clean - the bind is migrated, the sync is not. */ \
|
||||
X(GetFramebufferBindingSlot, BARRIER_PULLED, "P3b/P4b (Espryt), P7 (Magma)", \
|
||||
"frontend BindingSlot<FramebufferObject> pointer") \
|
||||
X(GetImageTextureBinding, BARRIER_PULLED, "P3b/P4b, P7", \
|
||||
"frontend ImageTextureBinding base pointer") \
|
||||
/* set_sampler_views' Count IS this value plus one, but the set is suppressed on an */ \
|
||||
/* unchanged content hash while the high-water mark still moves (PipeFill.cpp:1917-1923). */ \
|
||||
X(GetMaxTouchedTextureUnit, BARRIER_PULLED, "P3b/P4b", \
|
||||
"hash-suppressed set, high-water mark still moves") \
|
||||
/* The three texture SHUTTERS. Coverage.def:220-224 is explicit that no call carries them */ \
|
||||
/* and none should: what replaces them server-side is the applier's own Serial, a different */ \
|
||||
/* value with a different owner. So these are not values to migrate. */ \
|
||||
X(GetSamplingResolutionGeneration, BARRIER_PULLED, "P3b/P4b", \
|
||||
"a shutter, not a value: the server answers from its own Serial") \
|
||||
X(GetTextureBindGeneration, BARRIER_PULLED, "P3b/P4b", \
|
||||
"a shutter, not a value: the server answers from its own Serial") \
|
||||
X(GetTextureContextId, BARRIER_PULLED, "P3b/P4b", \
|
||||
"a shutter, not a value: the server answers from its own Serial") \
|
||||
X(GetTextureUnitObject, BARRIER_PULLED, "P3b/P4b, P7", \
|
||||
"frontend TextureUnit base pointer; 13 Espryt + 8 Magma sites") \
|
||||
/* DirectGLES.cpp:4497, PrepareForDraw, the second unconditional pointer read of every draw. */ \
|
||||
X(GetProgramForDraw, BARRIER_PULLED, "P8 (Espryt), P7 (Magma)", \
|
||||
"frontend SharedPtr<ProgramObject>; the record carries a handle") \
|
||||
/* The XFB six. XFB itself is off the reduced path, but kDraw's may-read mask carries all */ \
|
||||
/* six and the draw walk reads them regardless - which is exactly the case a field census */ \
|
||||
/* taken from "what the scenario does" rather than from the mask would miss. */ \
|
||||
X(IsTransformFeedbackActive, BARRIER_PULLED, "P3b/P4b (Espryt), P7 (Magma)", \
|
||||
"read on every kDraw walk although XFB is off the reduced path") \
|
||||
X(IsTransformFeedbackPaused, BARRIER_PULLED, "P3b/P4b (Espryt), P7 (Magma)", \
|
||||
"read on every kDraw walk although XFB is off the reduced path") \
|
||||
X(GetTransformFeedbackProgram, BARRIER_PULLED, "P3b/P4b (Espryt), P7 (Magma)", \
|
||||
"frontend SharedPtr<ProgramObject>") \
|
||||
X(GetTransformFeedbackGeneration, BARRIER_PULLED, "P3b/P4b (Espryt), P7 (Magma)", \
|
||||
"no call carries it") \
|
||||
X(GetBoundTransformFeedbackLifetimeId, BARRIER_PULLED, "P3b/P4b (Espryt), P7 (Magma)", \
|
||||
"the D21 counter-slot rekey's key; no call carries it") \
|
||||
X(GetTransformFeedbackCapturedVertices, BARRIER_PULLED, "P3b/P4b (Espryt), P7 (Magma)", \
|
||||
"no call carries it") \
|
||||
\
|
||||
/* ---- APPLIER_DERIVED ---- */ \
|
||||
/* THE ONE ROW, and it is the one the contract asked P5 to split into two field ids. It is */ \
|
||||
/* split HERE INSTEAD, by ARGUMENT, in the argument-exception list below - see that list's */ \
|
||||
/* header for the evidence and for what would overturn the decision. The field itself is */ \
|
||||
/* APPLIER_DERIVED because set_pixel_pack_state arrives and MGPipeApplyAccess::PackState */ \
|
||||
/* writes m_pixelStore[0] out of it (PipeApply.cpp:1373), while no row of the emitted list */ \
|
||||
/* claims the field (Coverage.def:173 keeps it out deliberately, because the record supplies */ \
|
||||
/* half of it). */ \
|
||||
X(GetPixelStoreParameters, APPLIER_DERIVED, "-", \
|
||||
"set_pixel_pack_state; the applier writes m_pixelStore[0] (PipeApply.cpp:1373)") \
|
||||
\
|
||||
/* ---- FATAL: three non-sticky fields, each off the reduced path for a checkable reason --- */ \
|
||||
X(GetBoundTransformFeedbackName, FATAL, "-", \
|
||||
"DEAD: read by no backend since the D21 rekey (PipeInputs.h:232-234)") \
|
||||
X(GetTransformFeedbackPausedPrimitiveCounter, FATAL, "-", \
|
||||
"reachable only from class kQuery, which the reduced path never enters") \
|
||||
X(GetProgramForDispatch, FATAL, "-", \
|
||||
"reachable only from kDispatch; there is no compute on the reduced path") \
|
||||
\
|
||||
/* ---- the seven sticky forwards, as FIELD rows ---- */ \
|
||||
/* They have no storage, so a read of the FIELD is a call of the FORWARD; the field row and */ \
|
||||
/* the forward row below carry the same class by construction, and the generator refuses a */ \
|
||||
/* pair that disagrees. Their poison exemption (generated/PipeFilled.inc:422's sticky arm) */ \
|
||||
/* is cancelled under split by the server stamp, which zeroes their FilledGen - and 0 loses */ \
|
||||
/* to nothing, because :419's "never filled" test runs first. */ \
|
||||
X(GetBufferBindingPointCount, BARRIER_PULLED, "P7/P13", \
|
||||
"an argument-keyed lookup into the frontend's binding-point table") \
|
||||
X(GetProgramObject, BARRIER_PULLED, "P9", \
|
||||
"hands the backend a frontend SharedPtr<ProgramObject> keyed by GL name") \
|
||||
X(GetTextureObject, BARRIER_PULLED, "P7", \
|
||||
"hands the backend a frontend SharedPtr<ITextureObject> keyed by GL name") \
|
||||
X(HasOpenTransformFeedbackSpan, BARRIER_PULLED, "P7/P9", \
|
||||
"a lookup into frontend XFB span state keyed by lifetime id") \
|
||||
X(ValidateProgramName, BARRIER_PULLED, "P9", \
|
||||
"a frontend name-table probe; Coverage.def calls it kClientResolved") \
|
||||
X(InvalidateCompileEnv, BARRIER_PULLED, "P5", \
|
||||
"a WRITE INTO THE FRONTEND; R-12 replaces it with the re-arriving caps snapshot") \
|
||||
X(RecordError, BARRIER_PULLED, "P9", \
|
||||
"a WRITE INTO THE FRONTEND; R-12's OnGlError, whose ordering is P9's")
|
||||
|
||||
// X(Field, Class, RetiringPhase, Mechanism) - the SEVEN STICKY FORWARDS as their own rows.
|
||||
//
|
||||
// CONTRACT-P5.md section 3: "The domain is 63 fields plus the 7 sticky forwards, which are
|
||||
// among those 63 but are exempted from the poison and so need their own row. 70 rows."
|
||||
// The reason they need a second row is that they are the seven that hand the server a raw
|
||||
// FRONTEND OBJECT or write INTO the frontend, so "the exit gate is structurally blind on the
|
||||
// seven most dangerous fields" - and the row that fixes that is about the FORWARD (a live
|
||||
// call with no stored value), not about the field's storage, which does not exist.
|
||||
//
|
||||
// Mechanism is what replaces the forward, which is NOT the same question as which phase
|
||||
// retires the pull.
|
||||
#define MGP_FIELD_OWNERSHIP_FORWARD_LIST(X) \
|
||||
X(GetBufferBindingPointCount, BARRIER_PULLED, "P7/P13", \
|
||||
"a server-side binding-point table") \
|
||||
X(GetProgramObject, BARRIER_PULLED, "P9", \
|
||||
"a client-resolved program handle table (ARCHITECTURE 3.2 explicitly-not-ported)") \
|
||||
X(GetTextureObject, BARRIER_PULLED, "P7", \
|
||||
"a server-side texture handle table") \
|
||||
X(HasOpenTransformFeedbackSpan, BARRIER_PULLED, "P7/P9", \
|
||||
"server-side XFB span state") \
|
||||
X(ValidateProgramName, BARRIER_PULLED, "P9", \
|
||||
"a client-resolved program name probe") \
|
||||
X(InvalidateCompileEnv, BARRIER_PULLED, "P5", \
|
||||
"OnCapsInvalidated - the re-arriving caps snapshot IS the invalidation (R-12)") \
|
||||
X(RecordError, BARRIER_PULLED, "P9", \
|
||||
"OnGlError, the ordered reverse-channel error post (R-12); its ordering is P9's")
|
||||
|
||||
// X(Field, Arg0, Class, Why) - ARGUMENT-KEYED EXCEPTIONS.
|
||||
//
|
||||
// A row here narrows ONE argument value of ONE field to a different class. The field keeps
|
||||
// its single row above; this is the same shape Coverage.def:62-69 already rules for
|
||||
// GetBufferBindingSlot - "THE ROW STAYS ONE ROW, and that is structural rather than a
|
||||
// shortcut: this list IS the MGPipeInputField enum and the PipeInputs field set, and the
|
||||
// field is ONE array that a second row of the same name could only duplicate".
|
||||
//
|
||||
// GetPixelStoreParameters is m_pixelStore[2] indexed by its own `isUnpack` argument, exactly
|
||||
// as GetBufferBindingSlot is m_bufferBindingSlot[15] indexed by its BufferTarget. Only [0]
|
||||
// (pack) has a carrier, and the applier writes it.
|
||||
//
|
||||
// AND THE UNPACK HALF HAS NO BACKEND READER AT ALL. Every MGB_CTX->GetPixelStoreParameters
|
||||
// call site in the tree passes `false`: DirectGLES.cpp:7924, :9399, :10893, :11272,
|
||||
// Utils.cpp:2302 and VulkanRenderer.cpp:10980 - six, not the five the scout named, and the
|
||||
// scout did not open them. PipeFill.cpp's own EmitPixelPackState says the same thing from
|
||||
// the other side: "PACK only, deliberately: nothing on the far side of the boundary reads
|
||||
// unpack state". So the honest class for the unpack half is FATAL, not BARRIER_PULLED: a
|
||||
// future backend read of it would otherwise be served a stale struct in silence, and this
|
||||
// way it is a named abort on the first read.
|
||||
#define MGP_FIELD_OWNERSHIP_ARG_LIST(X) \
|
||||
X(GetPixelStoreParameters, 1, FATAL, \
|
||||
"the unpack half has no carrier AND no backend reader; all six MGB_CTX sites pass false")
|
||||
|
||||
// X(WireOp, Verb) - WHERE THE SERVER STAMPS.
|
||||
//
|
||||
// The stamp rule needs one thing the wire does not carry: which MGPipeVerb a record belongs
|
||||
// to. The two name spaces are not the same and do not line up by name - the DRAW verb is
|
||||
// `DrawArrays` and its record is `draw_vbo`, the BLIT verb is `BlitFramebuffer` and its record
|
||||
// is `blit` - so the map is written here and checked against both sources (PipeCalls.def for
|
||||
// the op, FillPoints.def for the verb) rather than believed.
|
||||
//
|
||||
// EXACTLY THE OPS THAT ARE VERB BOUNDARIES. CONTRACT-P5.md section 7 puts five slots in class
|
||||
// B (emitted in P5): Clear, DrawArrays, ReadPixels, BlitFramebuffer and Present. FOUR OF THEM
|
||||
// ARE HERE AND PRESENT IS NOT, and that is a ruling rather than an omission: FillPoints.def:21
|
||||
// says in so many words that "Present and SetSwapInterval go through BackendObject virtuals
|
||||
// and read no frontend state, so they are not verbs here". There is no MGPipeVerb::Present to
|
||||
// stamp for, MGPipeValidateForVerb is never called for it, and stamping at Present would
|
||||
// retire the previous verb's answers with nothing to put in their place.
|
||||
//
|
||||
// An op that is not in this list is NOT a verb boundary and the applier must not stamp on it:
|
||||
// a set_dynamic_state between two draws is part of the draw's verb, not a new one.
|
||||
//
|
||||
// THE GENERATOR REFUSES AN OMISSION, NOT ONLY A TYPO, and that is the half the first version of
|
||||
// this file did not have. Every call that is VERB-SHAPED must have a row here or an exemption
|
||||
// row below with a reason. "Verb-shaped" is the union of two mechanical tests, both derived:
|
||||
// (a) PipeCalls.def gives the call kind kCtxVerb - the catalogue's own word for it;
|
||||
// (b) the call's name is also an MGPipeVerb name in FillPoints.def.
|
||||
// Eighteen rows and three exemptions cover all twenty-one (P5: twelve and three; P5b appended
|
||||
// the five kCtxVerb rows 72..76 and settled ResourceCopyRegion). Only four of the rows could
|
||||
// arrive in P5 (CONTRACT §7 class B minus Present); the rest are Fatal{UnmigratedVerb} on the
|
||||
// client until a P5b migration package flips them and are mapped ANYWAY, because the failure
|
||||
// mode of an absent row is silent: the applier would run the record under the PREVIOUS verb's
|
||||
// serial, mask and name, and a field inside that mask would read FRESH while holding the
|
||||
// previous verb's value.
|
||||
//
|
||||
// NOT MECHANICALLY DETECTABLE, and so not claimed: a call that is a verb boundary, is not
|
||||
// kCtxVerb, and whose name differs from its verb's. `ResourceCopyRegion` WAS the one in the
|
||||
// tree (its verbs could have been CopyImageSubData / CopyTexSubImage2D / CopyTexImage2D). P5b
|
||||
// decided: resource_copy_region is glCopyImageSubData only, and the two framebuffer-sourced
|
||||
// copies have their own row (copy_framebuffer_to_texture), so the choice is a row here rather
|
||||
// than a rule in a reader's head.
|
||||
#define MGP_VERB_OP_LIST(X) \
|
||||
/* CONTRACT §7 class B - the four that can actually arrive in P5. */ \
|
||||
X(Clear, Clear) \
|
||||
X(DrawVbo, DrawArrays) \
|
||||
X(ReadPixels, ReadPixels) \
|
||||
X(Blit, BlitFramebuffer) \
|
||||
/* Class C today (Fatal{UnmigratedVerb}); mapped so the phase that emits one cannot get NO */ \
|
||||
/* stamp by omission. DrawVbo above has the same shape and a worse case: it stands for all */ \
|
||||
/* twenty draw verbs, which share the kDraw mask but not the NAME a Fatal prints. */ \
|
||||
X(LaunchGrid, DispatchCompute) \
|
||||
X(MemoryBarrier, MemoryBarrier) \
|
||||
X(BeginStreamOutput, BeginTransformFeedback) \
|
||||
X(EndStreamOutput, EndTransformFeedback) \
|
||||
X(PauseStreamOutput, PauseTransformFeedback) \
|
||||
X(ResumeStreamOutput, ResumeTransformFeedback) \
|
||||
X(GenerateMipmap, GenerateMipmap) \
|
||||
X(GetTextureImage, GetTextureImage) \
|
||||
/* P5b (MG_Remote/CONTRACT-P5B.md). The ONE renamed, non-kCtxVerb boundary the file above */ \
|
||||
/* said "the phase that emits it adds its row and decides which verb it is": P5b rules */ \
|
||||
/* resource_copy_region = glCopyImageSubData ONLY; the two framebuffer-sourced copies */ \
|
||||
/* (CopyTexImage2D / CopyTexSubImage2D) are copy_framebuffer_to_texture below, stamped as */ \
|
||||
/* CopyTexImage2D - both are kBlitOrCopy, one mask, and a row can name one verb. */ \
|
||||
X(ResourceCopyRegion, CopyImageSubData) \
|
||||
/* The five P5b-appended verbs, opcodes 72..76, each stamped as the GLFunctionsTable verb */ \
|
||||
/* it reproduces. */ \
|
||||
X(BindShaderImage, BindImageTexture) \
|
||||
X(PatchParameter, PatchParameteri) \
|
||||
X(BindStreamOutput, BindTransformFeedback) \
|
||||
X(SetStorageBlockBinding, ShaderStorageBlockBinding) \
|
||||
X(CopyFramebufferToTexture, CopyTexImage2D)
|
||||
|
||||
// X(Op, Why) - verb-shaped calls that are deliberately NOT stamp points.
|
||||
//
|
||||
// An exemption is a ROW, not an absence, so that the reason is in the file rather than in a
|
||||
// reviewer's head and so that the generator's completeness check has something to accept.
|
||||
#define MGP_VERB_OP_EXEMPT_LIST(X) \
|
||||
X(Present, \
|
||||
"FillPoints.def:21 - Present and SetSwapInterval go through BackendObject virtuals and " \
|
||||
"read no frontend state, so they are not verbs here. There is no MGPipeVerb::Present, " \
|
||||
"MGPipeValidateForVerb is never called for it, and stamping would retire the previous " \
|
||||
"verb's answers with nothing to put in their place. It is class B all the same.") \
|
||||
X(SetSwapInterval, \
|
||||
"the same sentence of FillPoints.def:21, and it is class C besides") \
|
||||
X(Flush, \
|
||||
"not a verb at all: the verb census (BRIEF §12 C-3) found Flush is not a GLFunctionsTable " \
|
||||
"slot and glFlush/glFinish are empty function bodies (Definitions.cpp:111-112), so there " \
|
||||
"is no MGPipeVerb::Flush for a row to name")
|
||||
// clang-format on
|
||||
@@ -1075,7 +1075,27 @@ namespace MobileGL::MG_Pipe {
|
||||
// Replaces the backend's `uploadData == mipData` pointer comparison: are these
|
||||
// bytes an untransformed level shadow?
|
||||
Uint8 SourceIsVerbatimLevelShadow;
|
||||
Uint8 Pad0[3];
|
||||
// P5 (b1): DOES THIS RESOURCE HAVE A LIVE HOST WRITER RIGHT NOW? One byte out of the
|
||||
// pad, so MGP_ASSERT_POD(MGPSubData, 72) below does not move.
|
||||
//
|
||||
// It is here rather than on MGPResourceDesc, and that is a ruling with a reason. The
|
||||
// fact is CONTENT-shaped - "someone may be writing these bytes without telling you" -
|
||||
// and MGPResourceDesc's only carrier is resource_respecify, which for a BUFFER is
|
||||
// never classified as metadata-only (PipeApply.cpp's RespecifyRedefinesNoStorage
|
||||
// refuses the buffer target outright, so that ID-18 M4's "no reallocation ack" is true
|
||||
// by construction). Announcing a map on a descriptor would therefore have cost a
|
||||
// spurious reallocation per map - precisely the failure the brief warned about - or a
|
||||
// change to that rule, which is a P4a contract the buffer family should not be
|
||||
// re-opening for a flag.
|
||||
//
|
||||
// WHO SETS IT: MGPipeEmitResourceSubData, from BufferObject::HasLiveHostWritesForWire.
|
||||
// WHO READS IT: ApplyBufferWrite, into MGPipeResourceRecord::HasLiveHostWrites, which
|
||||
// is what IsBufferDrawCleanByHandle asks instead of the frontend object's IsMapped().
|
||||
// ZERO IS THE ANSWER, NOT THE ABSENCE OF ONE: a record that does not set it says "no
|
||||
// live writer", which is what every monolith emission means and why the monolith path
|
||||
// needs no edit at all.
|
||||
Uint8 HasLiveHostWrites;
|
||||
Uint8 Pad0[2];
|
||||
MGPBox UnionBox;
|
||||
Uint32 RegionCount; // MGPSubRegion[] in the variable tail
|
||||
Uint32 Pad1;
|
||||
@@ -1227,15 +1247,39 @@ namespace MobileGL::MG_Pipe {
|
||||
};
|
||||
MGP_ASSERT_POD(MGPReadback, 24);
|
||||
|
||||
// resource_copy_region = glCopyImageSubData (P5b, CONTRACT-P5B.md i1). The record had no
|
||||
// producer and no consumer before P5b, so its shape is settled here for the first time:
|
||||
//
|
||||
// Src / Dst the two endpoints' handles - kind Texture, or kind Renderbuffer when the
|
||||
// matching *Target is GL_RENDERBUFFER. The handle is the identity.
|
||||
// SrcTarget / the GL target enum the APPLICATION named, verbatim (GL_TEXTURE_2D,
|
||||
// DstTarget GL_TEXTURE_CUBE_MAP, GL_RENDERBUFFER, ...); every one fits a Uint16.
|
||||
// Espryt's own MakeGLESCopyImageEndpoint does the ES lowering
|
||||
// (DirectGLES.cpp) and must keep seeing the enum the app passed.
|
||||
// SrcBox {SrcX, SrcY, SrcZ, Width, Height, Depth} of the copied region.
|
||||
// SrcGlName / THE P5b DEBT, stated rather than hidden. GLFunctionsTable::
|
||||
// DstGlName CopyImageSubData takes two CopyImageEndpoints, each a frontend SharedPtr,
|
||||
// and the server has none. Under inproc and the verb barrier the server
|
||||
// rebuilds a TEXTURE endpoint from the GL name through the barrier-pulled
|
||||
// sticky forward MGB_CTX->GetTextureObject(name) (counted in `rsp`,
|
||||
// retired by P7 / P3b-P4b when the backend takes handles). A GL name is
|
||||
// NEVER an identity (section 4.2.1); it is the lookup key of a pull the
|
||||
// handle beside it will replace. No forward hands out a renderbuffer,
|
||||
// so a RENDERBUFFER endpoint is refused by name in P5b
|
||||
// (Fatal{UnmigratedVerb, "CopyImageSubData+RENDERBUFFER"}, ID-57's shape).
|
||||
//
|
||||
// 64 -> 72: the two names did not fit the four pad bytes, and the record had no wire history
|
||||
// to preserve.
|
||||
struct MGPCopyRegion {
|
||||
MGPipeHandle Src, Dst;
|
||||
MGPBox SrcBox;
|
||||
Int32 DstX, DstY, DstZ;
|
||||
Uint16 SrcTarget, DstTarget;
|
||||
Uint16 SrcLevel, DstLevel;
|
||||
Uint32 SrcGlName, DstGlName;
|
||||
Uint32 Pad0;
|
||||
};
|
||||
MGP_ASSERT_POD(MGPCopyRegion, 64);
|
||||
MGP_ASSERT_POD(MGPCopyRegion, 72);
|
||||
|
||||
struct MGPBlit {
|
||||
MGPipeHandle ReadFbo, DrawFbo;
|
||||
@@ -1250,16 +1294,61 @@ namespace MobileGL::MG_Pipe {
|
||||
// glClearNamedFramebuffer* entry points (section 4.4.4).
|
||||
struct MGPClear {
|
||||
MGPipeHandle Fbo;
|
||||
Uint32 Kind; // Whole | Color | Depth | Stencil | DepthStencil
|
||||
Uint32 Kind; // kMGPipeClearKind*, below
|
||||
Int32 DrawBufferIndex;
|
||||
Uint32 BufferMask; // GL_COLOR_BUFFER_BIT etc. for the whole-framebuffer form
|
||||
Uint32 ValueClass; // Float | Int | Uint
|
||||
Uint32 ValueClass; // kMGPipeClearValueClass*, below
|
||||
Uint32 ColorValue[4];
|
||||
Float DepthValue;
|
||||
Int32 StencilValue;
|
||||
};
|
||||
MGP_ASSERT_POD(MGPClear, 48);
|
||||
|
||||
// MGPClear's two discriminants, and THE ONLY SPELLING OF THEM (P5b, CONTRACT-P5B.md f1).
|
||||
// Through P5 the list lived in this struct's comment and both the client emitter
|
||||
// (MG_Remote/Client/EmitTables.h) and the server sink (MG_Remote/Server/PipeApplier.h)
|
||||
// minted their own copy of the numbers, each flagged "this belongs in MGPipeTypes.h". A
|
||||
// disagreement between the two copies is a clear of the wrong attachment with the wrong
|
||||
// value type, which renders plausibly - table 0's "a decoder that open-codes it is the
|
||||
// class-1 defect". Both files now alias these.
|
||||
//
|
||||
// Kind is the comment's order, left to right. ValueClass reuses the numbering
|
||||
// MG_State/GLState/Core.h gives the identical three-way split on MGPAttribValue::ValueClass.
|
||||
//
|
||||
// WHICH GL ENTRY POINT PRODUCES WHICH KIND, so the emitter and the sink cannot disagree:
|
||||
// glClear(mask) Whole, BufferMask = mask, DrawBufferIndex = -1
|
||||
// glClearBuffer{f,i,ui}v(GL_COLOR, i, v) Color, DrawBufferIndex = i, ValueClass by suffix
|
||||
// glClearBufferfv(GL_DEPTH, 0, &d) Depth, DepthValue = d
|
||||
// glClearBufferiv(GL_STENCIL, 0, &s) Stencil, StencilValue = s
|
||||
// glClearBufferfi(GL_DEPTH_STENCIL, 0, d, s) DepthStencil, DepthValue = d, StencilValue = s
|
||||
// The four glClearNamedFramebuffer* forms are the same rows with Fbo = the named
|
||||
// framebuffer's handle (preceded by its MGPipeFramebufferTarget::Named record, ID-19);
|
||||
// the bound forms carry Fbo = kMGPipeNullHandle, "the bound draw framebuffer".
|
||||
inline constexpr Uint32 kMGPipeClearKindWhole = 0;
|
||||
inline constexpr Uint32 kMGPipeClearKindColor = 1;
|
||||
inline constexpr Uint32 kMGPipeClearKindDepth = 2;
|
||||
inline constexpr Uint32 kMGPipeClearKindStencil = 3;
|
||||
inline constexpr Uint32 kMGPipeClearKindDepthStencil = 4;
|
||||
inline constexpr Uint32 kMGPipeClearKindCount = 5;
|
||||
inline constexpr Uint32 kMGPipeClearValueClassFloat = 0;
|
||||
inline constexpr Uint32 kMGPipeClearValueClassInt = 1;
|
||||
inline constexpr Uint32 kMGPipeClearValueClassUint = 2;
|
||||
inline constexpr Uint32 kMGPipeClearValueClassCount = 3;
|
||||
|
||||
// generate_mipmap = glGenerateMipmap (P5b, CONTRACT-P5B.md f1). First producer and first
|
||||
// consumer in P5b, so the fields are settled here:
|
||||
// Res the texture bound to the active unit at `Target`, resolved on the client. The
|
||||
// server's backend slot takes only the GL target and resolves the bound texture
|
||||
// itself through the barrier-pulled unit state (kTextureOp's may-read mask), so
|
||||
// Res is the P8 form's identity and is not what the P5b sink dispatches on.
|
||||
// Target the GL texture target enum VERBATIM (GL_TEXTURE_2D 0x0DE1, GL_TEXTURE_3D
|
||||
// 0x806F, GL_TEXTURE_CUBE_MAP 0x8513, GL_TEXTURE_2D_ARRAY 0x8C1A ...), which
|
||||
// is what GLFunctionsTable::GenerateMipmap takes; every GL texture target fits
|
||||
// a Uint16 and the sink passes it straight through. NOT MGPipeResourceTarget:
|
||||
// there is no resource-target -> GL-enum inverse in the tree to spend on it.
|
||||
// BaseLevel / the plan the client computed from GL_TEXTURE_BASE_LEVEL and the level count:
|
||||
// LevelCount informational in P5b (the backend derives its own), load-bearing in P8's
|
||||
// "generate_mipmap plan + CPU fallback texels" row.
|
||||
struct MGPMipPlan {
|
||||
MGPipeHandle Res;
|
||||
Uint16 Target, BaseLevel, LevelCount, Pad0;
|
||||
@@ -1287,6 +1376,14 @@ namespace MobileGL::MG_Pipe {
|
||||
kDrawIndicesAreClient = 1u << 2,
|
||||
kDrawHasIndexRange = 1u << 3,
|
||||
kDrawHasXfbCount = 1u << 4,
|
||||
// P5b (CONTRACT-P5B.md d1): the draw's ranges come from a GL_DRAW_INDIRECT_BUFFER and
|
||||
// the record's SECOND TAIL is one MGPDrawIndirect rather than an MGHostSpan. The two
|
||||
// flags are EXCLUSIVE - an indirect draw takes its indices from the bound element
|
||||
// buffer by GL rule, so it can never carry user indices - and a record that sets both
|
||||
// is Fatal{ProtocolCorruption} at the layout. NumDraws is 0 for an indirect draw: the
|
||||
// server never reads the indirect buffer to learn a count and the client never sends
|
||||
// ranges it does not have.
|
||||
kDrawIsIndirect = 1u << 5,
|
||||
};
|
||||
|
||||
// = pipe_draw_info. Today's twenty draw entry points collapse onto this one call, with
|
||||
@@ -1321,8 +1418,22 @@ namespace MobileGL::MG_Pipe {
|
||||
};
|
||||
MGP_ASSERT_POD(MGPDrawRange, 12);
|
||||
|
||||
// Present when the draw is indirect. The client resolves the COUNT itself, so the
|
||||
// server never reads an indirect command block to learn how many draws there are.
|
||||
// Present when the draw is indirect: draw_vbo's second tail under kDrawIsIndirect (P5b,
|
||||
// CONTRACT-P5B.md d1), 8-aligned behind the (empty) range tail exactly where the user-index
|
||||
// span would sit. The client resolves the COUNT itself, so the server never reads an
|
||||
// indirect command block to learn how many draws there are:
|
||||
// glMultiDraw*Indirect DrawCount = drawcount, ParameterBuffer = null
|
||||
// glMultiDraw*IndirectCount DrawCount = maxdrawcount, ParameterBuffer = the bound
|
||||
// GL_PARAMETER_BUFFER, ParameterOffset = drawcount (the byte
|
||||
// offset the GL call spells as GLintptr drawcount). The server's
|
||||
// backend slot takes exactly that pair and reads the real count
|
||||
// where it does today; nothing about the parameter buffer's
|
||||
// CONTENT crosses. (ROADMAP P8's HostResolve.cpp is where a
|
||||
// client-side count resolve would live if a backend ever needed
|
||||
// the number rather than the buffer; no backend does.)
|
||||
// Buffer / Offset / Stride the bound GL_DRAW_INDIRECT_BUFFER handle, the command byte
|
||||
// offset the GL call passed as `indirect`, and the stride (0 =
|
||||
// tightly packed, as GL spells it - the backend normalises).
|
||||
struct MGPDrawIndirect {
|
||||
MGPipeHandle Buffer;
|
||||
MGPipeHandle ParameterBuffer;
|
||||
@@ -1387,6 +1498,127 @@ namespace MobileGL::MG_Pipe {
|
||||
};
|
||||
MGP_ASSERT_POD(MGPSwapInterval, 8);
|
||||
|
||||
// ---------------------------------------------------------------------------------
|
||||
// P5b: the five appended rows (MG_Remote/CONTRACT-P5B.md). APPENDED, never inserted:
|
||||
// the wire opcode is a call's position in PipeCalls.def, so these sit after
|
||||
// FenceWaitServer at opcodes 72..76 and no earlier opcode moved.
|
||||
//
|
||||
// Every one of them is a GLFunctionsTable VERB the class-C census measured as a first
|
||||
// blocker and for which no existing row could carry the call. Four of the five exist
|
||||
// because the backend slot does REAL WORK AT THE CALL rather than at the next validate,
|
||||
// so a validate-time set record (set_shader_images, set_patch_state) cannot stand in for
|
||||
// it: Espryt's BindImageTexture syncs the unit's binding to the driver on the spot,
|
||||
// PatchParameteri pushes glPatchParameteri, BindTransformFeedback rebinds the driver
|
||||
// object and invalidates the capture-binding shadows, and ShaderStorageBlockBinding
|
||||
// pushes a rebinding onto an already-built driver program. The fifth,
|
||||
// copy_framebuffer_to_texture, is a copy WITH the read framebuffer as its source, which
|
||||
// resource_copy_region (resource -> resource) cannot express.
|
||||
//
|
||||
// NONE OF THEM HAS AN MGPipeApply* ENTRY POINT AND NONE GAINS ONE. They reach
|
||||
// MG_Remote::Wire::WireVerbSink like the five P5 class-B verbs (the census's correction:
|
||||
// a verb reaches the sink, not an applier), and under monolith they have no producer at
|
||||
// all - the backend's own slot is called directly, byte for byte as today (G2/G14).
|
||||
// ---------------------------------------------------------------------------------
|
||||
|
||||
// bind_shader_image = glBindImageTexture (P5b i1). The arguments VERBATIM plus the handle:
|
||||
// Res the texture's handle (kind Texture); kMGPipeNullHandle for texture 0.
|
||||
// Unit the image unit.
|
||||
// GlName the GL texture name the app passed - what the ES backend slot is handed as
|
||||
// `texture` and what it currently ignores ((void)texture); never an identity.
|
||||
// Level / Layer / Layered / Access / Format the GL arguments verbatim. Access is the
|
||||
// GL token (GL_READ_ONLY 0x88B8, GL_WRITE_ONLY 0x88B9, GL_READ_WRITE 0x88BA),
|
||||
// NOT MGPImageView's three-value encoding: this record reproduces a call, and
|
||||
// the encoding belongs to the validate-time set record, which still travels
|
||||
// beside it. Format is the GL internal-format enum.
|
||||
// The server's slot reads the unit's binding from the barrier-pulled GetImageTextureBinding
|
||||
// (kTextureOp's mask) exactly as it does in monolith; the record is the verb boundary and
|
||||
// the stamp, and the fields are what P7 / P3b-P4b will dispatch on instead.
|
||||
struct MGPImageBind {
|
||||
MGPipeHandle Res;
|
||||
Uint32 Unit;
|
||||
Uint32 GlName;
|
||||
Int32 Level;
|
||||
Int32 Layer;
|
||||
Uint32 Access;
|
||||
Uint32 Format;
|
||||
Uint8 Layered;
|
||||
Uint8 Pad0[7];
|
||||
};
|
||||
MGP_ASSERT_POD(MGPImageBind, 40);
|
||||
|
||||
// patch_parameter = glPatchParameteri (P5b t2). Pname is GL_PATCH_VERTICES - the only
|
||||
// pname that reaches the backend slot; the frontend answers GL_PATCH_DEFAULT_*_LEVEL itself
|
||||
// (GL_Drawing.cpp's PatchParameterfv) and bakes them into set_patch_state. It is carried
|
||||
// verbatim so the sink reproduces the call and not a reading of it. set_patch_state (op 43)
|
||||
// still travels at the next validate: it is the applier's working-block copy, this is the
|
||||
// driver push Espryt does at the call, and the two are two pushes today too.
|
||||
struct MGPPatchParameter {
|
||||
Uint32 Pname;
|
||||
Int32 Value;
|
||||
};
|
||||
MGP_ASSERT_POD(MGPPatchParameter, 8);
|
||||
|
||||
// bind_stream_output = glBindTransformFeedback (P5b t2). The XFB object namespace is the
|
||||
// frontend's and has no wire lifetime (no create/delete row); Espryt keys its driver
|
||||
// objects by the GL NAME (XfbImpl::g_xfbObjects[name]) and the D21 rekey by the lifetime
|
||||
// id, so both cross. Name 0 is the default object. A GL name is never an identity; here it
|
||||
// is the key the backend has always used, carried so the backend need not change.
|
||||
struct MGPStreamOutputBind {
|
||||
Uint32 GlName;
|
||||
Uint32 Pad0;
|
||||
Uint64 LifetimeId;
|
||||
};
|
||||
MGP_ASSERT_POD(MGPStreamOutputBind, 16);
|
||||
|
||||
// set_storage_block_binding = glShaderStorageBlockBinding (P5b i1). The block is named,
|
||||
// not indexed: BackendObject.h says why - the application's index is the frontend
|
||||
// interface-query enumeration's and no backend shares that index space, the NAME is the
|
||||
// one coordinate all three agree on. The name is bytes of unbounded length, so it rides
|
||||
// the ONE client -> server byte carrier, SEG_STAGE, as a kHasBlob blob: Name.Size is
|
||||
// strlen + 1 (the NUL travels), never 0.
|
||||
// ShaderCso the program's CSO handle - the identity, and what P7 dispatches on.
|
||||
// GlName the GL program name the backend slot takes; under inproc the slot resolves
|
||||
// it through the barrier-pulled sticky forward GetProgramObject(name)
|
||||
// (`rsp`, retired by P9). The P5b debt, stated.
|
||||
// Binding storageBlockBinding.
|
||||
struct MGPStorageBlockBinding {
|
||||
MGPipeHandle ShaderCso;
|
||||
Uint32 GlName;
|
||||
Uint32 Binding;
|
||||
MGPBlobRef Name;
|
||||
};
|
||||
MGP_ASSERT_POD(MGPStorageBlockBinding, 40);
|
||||
|
||||
// copy_framebuffer_to_texture = glCopyTexImage2D / glCopyTexSubImage2D (P5b f1). The
|
||||
// source is the READ framebuffer the server already has bound (set_framebuffer_state), so
|
||||
// no source handle crosses; the destination is the texture bound to the active unit at
|
||||
// Target, which the backend slot resolves through the barrier-pulled unit state exactly as
|
||||
// generate_mipmap does. glCopyTexImage2D (SubImage = 0) also REDEFINES the level, and the
|
||||
// frontend's own TexImage2D_State has already emitted that level's resource_respecify
|
||||
// (GL_Texture.cpp's CopyTexImage2D validator) before the backend slot is reached, so the
|
||||
// record carries the copy and nothing about storage.
|
||||
// Dst the destination texture's handle (P8 form; the P5b sink does not
|
||||
// dispatch on it).
|
||||
// Target the GL texture target enum verbatim (a 2D target or a cube face).
|
||||
// Level the destination level.
|
||||
// InternalFormat glCopyTexImage2D's internalformat (GL enum); 0 for the sub-image form.
|
||||
// X, Y, Width, Height the read-framebuffer rectangle.
|
||||
// XOffset, YOffset the sub-image form's destination origin; 0 for the image form.
|
||||
// SubImage 0 = glCopyTexImage2D, 1 = glCopyTexSubImage2D (unmeasured; shares
|
||||
// the row because the two calls differ in exactly these two fields).
|
||||
struct MGPCopyFromFramebuffer {
|
||||
MGPipeHandle Dst;
|
||||
Uint32 Target;
|
||||
Int32 Level;
|
||||
Uint32 InternalFormat;
|
||||
Int32 X, Y;
|
||||
Int32 Width, Height;
|
||||
Int32 XOffset, YOffset;
|
||||
Uint8 SubImage;
|
||||
Uint8 Pad0[3];
|
||||
};
|
||||
MGP_ASSERT_POD(MGPCopyFromFramebuffer, 48);
|
||||
|
||||
// ---------------------------------------------------------------------------------
|
||||
// Reverse channel payloads (section 7.1)
|
||||
// ---------------------------------------------------------------------------------
|
||||
|
||||
@@ -16,6 +16,12 @@
|
||||
|
||||
#include <MG_Backend/MGPipe/PipeInputs.h>
|
||||
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
// MGPipeUnmigratedEmulation's split arm reads MG_Config::Transport, which is what tells an
|
||||
// emulation site whether it is running inside a server or in the monolith it was written for.
|
||||
#include <Config.h>
|
||||
#endif
|
||||
|
||||
#if MOBILEGL_PIPE_VERIFY
|
||||
// THE ONE PLACE THE PROGRAM ARCHIVE'S CODEC IS CALLED, and it is compiled into the VERIFY
|
||||
// build only. In monolith the archive does not travel - MGPProgramDesc's seven blob refs are
|
||||
@@ -26,6 +32,13 @@
|
||||
#include <MG_State/GLState/ProgramState/ProgramArtifactsCodec.h>
|
||||
#endif
|
||||
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
// R-6's tier gate. One spelling, asked at the one place the decline is decided. Outside the
|
||||
// MOBILEGL_PIPE_VERIFY block above on purpose: the tier is a property of the BUILD, not of the
|
||||
// comparator, and a split build without the comparator still declines every acquisition.
|
||||
#include <MG_Remote/Client/PersistentMapTracker.h>
|
||||
#endif
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstdlib>
|
||||
@@ -835,12 +848,18 @@ namespace MobileGL::MG_Pipe {
|
||||
return true;
|
||||
}
|
||||
|
||||
#if MOBILEGL_PIPE_VERIFY
|
||||
// D-A4's pin. HasLiveHostWrites is ALWAYS false in this phase and is written by
|
||||
// nobody: it exists so the phase that pushes persistent-mapped host writes can set it
|
||||
// with no new record kind. A producer that landed under it would change what
|
||||
// IsBufferDrawClean answers with no other visible edit, so a verify build refuses to
|
||||
// let one arrive unannounced.
|
||||
#if MOBILEGL_PIPE_VERIFY && !MOBILEGL_BUILD_DISAGGREGATED
|
||||
// D-A4's pin, AND P5 (b1) IS THE PHASE IT WAS WAITING FOR. It said "HasLiveHostWrites
|
||||
// is always false in this phase and is written by nobody: it exists so the phase that
|
||||
// pushes persistent-mapped host writes can set it with no new record kind", and a
|
||||
// verify build refused to let such a producer arrive unannounced.
|
||||
//
|
||||
// The producer is announced: MGPSubData::HasLiveHostWrites, set by
|
||||
// MGPipeEmitResourceSubData from BufferObject::HasLiveHostWritesForWire and read by
|
||||
// ApplyBufferWrite below. So the pin is LIFTED FOR A SPLIT BUILD ONLY, and left
|
||||
// standing everywhere else - in a monolith build nothing sets the bit and the wire is
|
||||
// still the thing that would say so if something started to. That is the whole value
|
||||
// of the pin and it survives the phase it was written for.
|
||||
void PinNoLiveHostWrites(const MGPipeResourceRecord& record, MGPipeHandle res, const char* call) {
|
||||
if (!record.HasLiveHostWrites) return;
|
||||
MGP_TRIP_WIRE_REPORT("MGPipe: " MGP_TRIP_WIRE_TAG("PipeLiveHostWrites")
|
||||
@@ -876,6 +895,32 @@ namespace MobileGL::MG_Pipe {
|
||||
void PinWholeResourceRespecifyScope(const MGPResourceDesc&, MGPipeHandle, const char*) {}
|
||||
#endif
|
||||
|
||||
#if MOBILEGL_PIPE_VERIFY
|
||||
// P5 b1's wire, and the one statement about HasLiveHostWrites that IS still always
|
||||
// true once the field has a producer: the bit is the BUFFER family's. It answers "does
|
||||
// this resource have a live host writer right now", which only a buffer can have - a
|
||||
// texture's host writes are the unpack path's and are announced by the upload itself -
|
||||
// and the two emitters that set it (MGPipeEmitResourceSubData,
|
||||
// MGPipeEmitBufferSubDataResident) are both buffer-only. A texture sub-data carrying
|
||||
// it is therefore an encoder that copied a field across payload halves, which is
|
||||
// precisely the class of defect a shared record type invites.
|
||||
//
|
||||
// It replaces the always-false pin in a split build. That pin could not survive the
|
||||
// producer it existed to announce; this one can, and unlike that one it is compiled in
|
||||
// EVERY verify build, including build-verify-split - the matrix cell where the field
|
||||
// can actually be non-zero.
|
||||
void PinLiveHostWritesNamesABuffer(const MGPSubData& record, const char* call) {
|
||||
if (record.HasLiveHostWrites == 0) return;
|
||||
MGP_TRIP_WIRE_REPORT("MGPipe: " MGP_TRIP_WIRE_TAG("PipeLiveHostWritesTarget")
|
||||
" %s {slot=%u, gen=%u}: a record whose resource target is not a "
|
||||
"buffer (target=%u) declares live host writes, and only the buffer "
|
||||
"family has any",
|
||||
call, record.Res.Slot, record.Res.Gen, record.Target);
|
||||
}
|
||||
#else
|
||||
void PinLiveHostWritesNamesABuffer(const MGPSubData&, const char*) {}
|
||||
#endif
|
||||
|
||||
// The one gate every content-carrying buffer write goes through. resource_subdata and
|
||||
// buffer_subdata_resident differ only in which backend hook takes the bytes and in the
|
||||
// fact that one of them is allowed to be absent, so a second copy of this arithmetic
|
||||
@@ -905,6 +950,16 @@ namespace MobileGL::MG_Pipe {
|
||||
return false;
|
||||
}
|
||||
PinNoLiveHostWrites(*stored, record.Res, call);
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
// P5 (b1): THE PRODUCER. The record's own statement about the resource, applied
|
||||
// before the serial moves so that a probe re-entered from inside the backend hook
|
||||
// below already sees it. It is an assignment and not an OR: the bit is a STATE,
|
||||
// and a content record emitted while nothing maps the buffer is exactly how the
|
||||
// state goes back to false - which is why the falling edge pushes one block
|
||||
// (BufferObject::NotePersistentMapStateChanged) rather than relying on the next
|
||||
// ordinary write to arrive.
|
||||
stored->HasLiveHostWrites = record.HasLiveHostWrites != 0;
|
||||
#endif
|
||||
|
||||
// THE SERIAL MOVES BEFORE THE BACKEND IS TOLD, and that order is load-bearing:
|
||||
// the backend stamps its own synced serial from this record inside the hook, so a
|
||||
@@ -1771,6 +1826,7 @@ namespace MobileGL::MG_Pipe {
|
||||
// accumulate a pending upload onto whatever TEXTURE holds slot N in the texture slot
|
||||
// space. Renderbuffers have no sub-data path at all, so no correct client can produce
|
||||
// one and this is a protocol fault rather than a dropped call.
|
||||
PinLiveHostWritesNamesABuffer(record, "resource_subdata");
|
||||
const Uint8 resourceTarget = MGPipeSubDataResourceTargetOf(record.Target);
|
||||
if (resourceTarget == kMGPipeResourceTargetBuffer ||
|
||||
resourceTarget == static_cast<Uint8>(MGPipeResourceTarget::Renderbuffer) ||
|
||||
@@ -1814,7 +1870,20 @@ namespace MobileGL::MG_Pipe {
|
||||
if (stored == nullptr) return;
|
||||
|
||||
const char* fault = BufferRangeFault(record.Offset, record.Size, stored->Desc.Width);
|
||||
if (fault == nullptr && record.Size != 0 && bytes == nullptr) {
|
||||
// item-12 / R-13.2 / ID-37: the "a non-empty flush carries no bytes" fault is a MONOLITH
|
||||
// rule. Under an ACTIVE TRANSPORT resource_flush_range carries no companion pointer AT ALL
|
||||
// (contract table 1 row 20 / R-13.2): the covering resource_subdata already staged those
|
||||
// bytes into the server-owned StagedShadowStore (R-11), and Ops_H_FlushRange reads that
|
||||
// shadow, not the record. So a null `bytes` on a non-empty flush is the NORMAL split case,
|
||||
// not corruption - and a flush whose bytes were genuinely never staged is caught more
|
||||
// precisely downstream by R-11's Fatal{StageSnapshotTooNarrow}, which names the missing
|
||||
// subdata rather than the flush. The check stays exact under monolith
|
||||
// (MG_Config::Transport is a constexpr Monolith in a non-disaggregated build, so this is
|
||||
// `&& true` there and the codegen is unchanged). This was the only seam between the joint
|
||||
// inproc lane's 14/21 and 21/21: all seven PersistentCoherentMapScenario entries aborted
|
||||
// here (c1-v2.md 6).
|
||||
if (fault == nullptr && record.Size != 0 && bytes == nullptr &&
|
||||
MG_Config::Transport == MG_Config::TransportMode::Monolith) {
|
||||
fault = "a non-empty flush carries no bytes";
|
||||
}
|
||||
if (fault != nullptr) {
|
||||
@@ -1932,6 +2001,26 @@ namespace MobileGL::MG_Pipe {
|
||||
// the flag exists to announce, and the wire is what refuses to let it arrive unnamed.
|
||||
PinNoLiveHostWrites(*record, handle.Handle, "map_persistent");
|
||||
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
// R-6: A SPLIT BUILD RUNS AT TIER T2 AND DECLINES EVERY ACQUISITION, ALWAYS.
|
||||
//
|
||||
// The mint returns a raw void* that the client stores as the store's base
|
||||
// (BufferObject.cpp:238 / :603 / :658). Across a process boundary that address is
|
||||
// meaningless, and under `inproc` it is WORSE than meaningless: it happens to work,
|
||||
// so a lane that kept adoption alive would be green for a reason spawn cannot
|
||||
// reproduce, and persistent-map-push - an exit-gate counter - would be structurally
|
||||
// zero (PipeStats.cpp says so in as many words). Forcing T2 here rather than at the
|
||||
// three client call sites is what keeps `mpr` identical between the arms: the
|
||||
// roundtrip is COUNTED above, unconditionally, because a decline costs the same round
|
||||
// trip as a mint.
|
||||
//
|
||||
// The frontend already tolerates a decline in all three places, and has since P3a.
|
||||
if (MG_Config::Transport != MG_Config::TransportMode::Monolith &&
|
||||
MG_Remote::Client::AdoptTierIsEmulate()) {
|
||||
return nullptr;
|
||||
}
|
||||
#endif
|
||||
|
||||
// NO SERIAL MOVES and NO DESCRIPTOR CHANGES: the donation re-mints the backend's own
|
||||
// driver object, which is a server-local event that the backend's own id generation
|
||||
// already catches, and the client's view of the store's extent is untouched by it.
|
||||
@@ -2842,5 +2931,26 @@ namespace MobileGL::MG_Pipe {
|
||||
// It takes a literal and does nothing with it. Not a log line, not a counter: it sits on
|
||||
// paths a frame can reach many times, and ROADMAP.md forbids committing hot-path
|
||||
// instrumentation.
|
||||
void MGPipeUnmigratedEmulation(const char* name) { (void)name; }
|
||||
// P5 GIVES IT TEETH, and this is the whole of it: ONE function edit arms FIVE call sites
|
||||
// (Managers.cpp:5334, DirectGLES.cpp:8051, :8702, :8997, :10623), exactly as the header
|
||||
// and P4a's comment above promised. Every one of them reaches back into the CLIENT's
|
||||
// address space - a texture shadow, a CPU mipmap fallback, a host-side copy - and a server
|
||||
// has no client address space to reach into, so degrading silently is the one outcome that
|
||||
// must not happen.
|
||||
//
|
||||
// THE ARM IS THE TRANSPORT, NOT THE BUILD. build-split runs MOBILEGL_TRANSPORT=monolith in
|
||||
// every unit and integration-gpu lane, and several of the five are on ordinary monolith
|
||||
// paths that those lanes exercise (glGenerateMipmap reaches two of them); arming on the
|
||||
// build would turn 1117 integration cases red for running code that is correct in the role
|
||||
// they run it in. None of the five is on P5's reduced path, so under a real transport this
|
||||
// costs nothing and catches a lot.
|
||||
void MGPipeUnmigratedEmulation(const char* name) {
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
if (MG_Config::Transport != MG_Config::TransportMode::Monolith) {
|
||||
MGLOG_F("MGPipe: Fatal{UnmigratedEmulation, \"%s\"}", name != nullptr ? name : "<null>");
|
||||
std::abort();
|
||||
}
|
||||
#endif
|
||||
(void)name;
|
||||
}
|
||||
} // namespace MobileGL::MG_Pipe
|
||||
|
||||
@@ -219,9 +219,20 @@ namespace MobileGL::MG_Pipe {
|
||||
// sub-data). It is what replaces the frontend change serial the backend used to
|
||||
// mirror, and no MGPipe call may require the client to provide or know one.
|
||||
Uint64 Serial = 0;
|
||||
// ALWAYS FALSE IN P3a, AND WRITTEN BY NOBODY. It exists so the phase that pushes
|
||||
// persistent-mapped host writes can set it with zero new record kinds; a verify build
|
||||
// pins that it is false, so that phase cannot land a silent semantic change under it.
|
||||
// "DOES THIS RESOURCE HAVE A LIVE HOST WRITER RIGHT NOW?"
|
||||
//
|
||||
// False and written by nobody through P3a and P4a; P5 (b1) is the phase it was waiting
|
||||
// for and gives it its producer, with zero new record kinds exactly as planned: the
|
||||
// bit rides MGPSubData::HasLiveHostWrites - a byte out of that payload's existing pad -
|
||||
// and ApplyBufferWrite assigns it here. In a MONOLITH build nothing sets it and the
|
||||
// MOBILEGL_PIPE_VERIFY wire (PinNoLiveHostWrites) still refuses a producer, so the pin
|
||||
// survives the phase it was written for instead of being deleted by it.
|
||||
//
|
||||
// It is what IsBufferDrawCleanByHandle asks under split INSTEAD of the frontend
|
||||
// object's IsMapped(), because a spawned server has no frontend object to ask. Getting
|
||||
// that substitution wrong once already cost a silent regression - an emulated
|
||||
// persistent map read draw-clean for ever - which MG_Test/SanityTest.cpp's
|
||||
// DirectGLESBufferDrawProbe pair now pins from both sides.
|
||||
Bool HasLiveHostWrites = false;
|
||||
|
||||
// ---- P4a. Only a record of kind Texture ever carries these; a buffer's stay at
|
||||
|
||||
@@ -47,8 +47,11 @@
|
||||
// kCtxCso 13 CSO create/bind/delete
|
||||
// kCtxState 17 16 of the 17 set_* calls + the temporary set_residual_value_state
|
||||
// kCtxObject 9 set_texture_params (the 17th set_*) + 8 object-scoped transfers
|
||||
// kCtxVerb 13 3 context-reading transfer calls + the 10 commands
|
||||
// total 71
|
||||
// kCtxVerb 18 3 context-reading transfer calls + the 10 commands, plus the five
|
||||
// P5b-appended verbs (bind_shader_image, patch_parameter,
|
||||
// bind_stream_output, set_storage_block_binding,
|
||||
// copy_framebuffer_to_texture - MG_Remote/CONTRACT-P5B.md)
|
||||
// total 76
|
||||
//
|
||||
// Reconciliation with the plan's headline numbers (section 4.4 / appendix A), because they
|
||||
// do not add up to a set of UNIQUE records and this file has to hold unique records:
|
||||
@@ -78,9 +81,16 @@
|
||||
// QueryTimestamp, QueryCounter and FenceWaitServer, APPENDED at the end of the list -
|
||||
// not slotted into their groups - because the wire opcode is the position, so a record
|
||||
// that arrives late goes last. 71 unique records.
|
||||
// - P5b appended FIVE more after them (opcodes 72..76), for the same reason and by the same
|
||||
// rule: five GLFunctionsTable verbs the class-C census measured as first blockers - the
|
||||
// image bind, the patch parameter, the XFB object bind, the storage-block rebinding and
|
||||
// the framebuffer-to-texture copy - for which no existing row could carry the call.
|
||||
// 76 unique records. The catalogue footer's "ShaderStorageBlockBinding is folded into the
|
||||
// reflection archive" is CORRECTED by the row: the archive carries the bindings the
|
||||
// program LINKED with, and glShaderStorageBlockBinding moves one AFTER link.
|
||||
// ---------------------------------------------------------------------------------------
|
||||
|
||||
#define MGP_CALL_LIST_DOCUMENTED_COUNT 71
|
||||
#define MGP_CALL_LIST_DOCUMENTED_COUNT 76
|
||||
|
||||
// clang-format off
|
||||
#define MGP_CALL_LIST(X) \
|
||||
@@ -90,7 +100,14 @@
|
||||
/* property of the payload, so its absence was simply wrong. Adding a flag does not */ \
|
||||
/* move an opcode: the opcode is this line's 1-based position. */ \
|
||||
X(GetCaps, MGPCaps, kScreen, kReplySlot|kHasBlob) \
|
||||
X(ResourceCreate, MGPResourceDesc, kScreen, kNone) \
|
||||
/* THE FOUR ACCEPTANCE ROWS (P5 R-5, R-16). These four and map_persistent are the only */ \
|
||||
/* applier entry points that RETURN something the client acts on destructively - clearing */ \
|
||||
/* per-level dirty flags, latching parameters, advancing its own bookkeeping - so the */ \
|
||||
/* answer has to come back, and kReplySlot is how a record says so. They carried no flag */ \
|
||||
/* until P5, because in monolith the answer is the return value of a direct call and there */ \
|
||||
/* was nothing to declare. kMGPipeCallFlags is now what sizes the reply pool and what the */ \
|
||||
/* decoder posts against, so a row that answers without the flag is a waiter that hangs. */ \
|
||||
X(ResourceCreate, MGPResourceDesc, kScreen, kReplySlot) \
|
||||
/* NO kHasBlob, BY RULING (P5 R-13.3; CONTRACT-P5.md table 1 row 19). MGPResourceDesc */ \
|
||||
/* owns no MGPBlobRef and gains none: under split `initialBytes` is always nullptr and */ \
|
||||
/* the initial content of a glBufferData(size, data) / glTexImage*(..., data) arrives */ \
|
||||
@@ -99,7 +116,7 @@
|
||||
/* cost is one extra record. NOTE the SECOND uncarried companion on this call, the */ \
|
||||
/* MGPRespecifiedLevel* scope (PipeApply.h:792) - it is NOT bytes and NOT covered by */ \
|
||||
/* this ruling; table 1 row 19 gives it the two pad fields of MGPResourceDesc. */ \
|
||||
X(ResourceRespecify, MGPResourceDesc, kScreen, kNeedsAck) \
|
||||
X(ResourceRespecify, MGPResourceDesc, kScreen, kNeedsAck|kReplySlot) \
|
||||
X(ResourceDestroy, MGPHandleOnly, kScreen, kNone) \
|
||||
X(MapPersistent, MGPHandleOnly, kScreen, kReplySlot|kOptional) \
|
||||
X(UnmapPersistent, MGPHandleOnly, kScreen, kOptional) \
|
||||
@@ -154,8 +171,8 @@
|
||||
/* final step asserts sizeof(ResidualValueBlock) == 0 (plan 6.3). */ \
|
||||
X(SetResidualValueState, MGPResidualValueState, kCtxState, kHasBlob) \
|
||||
/* ---- context: per-object state and transfer (plan 4.4.3 set_texture_params, 4.4.4) ---- */ \
|
||||
X(SetTextureParams, MGPTextureParams, kCtxObject, kNone) \
|
||||
X(ResourceSubData, MGPSubData, kCtxObject, kHasBlob|kVarTail) \
|
||||
X(SetTextureParams, MGPTextureParams, kCtxObject, kReplySlot) \
|
||||
X(ResourceSubData, MGPSubData, kCtxObject, kHasBlob|kVarTail|kReplySlot) \
|
||||
X(BufferSubDataResident, MGPSubData, kCtxObject, kHasBlob|kOptional) \
|
||||
X(ResourceSubDataComplete, MGPSubDataComplete, kCtxObject, kNone) \
|
||||
/* NO kHasBlob AND NO MGPBlobRef, BY RULING (P5 R-13.2; CONTRACT-P5.md table 1 row 21). */ \
|
||||
@@ -194,7 +211,26 @@
|
||||
X(QueryCounter, MGPQueryDesc, kCtxQuery, kNone) \
|
||||
/* glWaitSync - WaitSync, the GPU-side wait, distinct from FenceWait's client-side one. */ \
|
||||
/* TimeoutNs is GL_TIMEOUT_IGNORED by contract. */ \
|
||||
X(FenceWaitServer, MGPFenceWait, kScreen, kNone)
|
||||
X(FenceWaitServer, MGPFenceWait, kScreen, kNone) \
|
||||
/* ---- APPENDED BY P5b (MG_Remote/CONTRACT-P5B.md): five GLFunctionsTable verbs the ---- */ \
|
||||
/* ---- class-C census measured as first blockers and that no existing row could carry. ---- */ \
|
||||
/* ---- Opcodes 72..76. Every one reaches WireVerbSink, none has an MGPipeApply* entry ---- */ \
|
||||
/* ---- point, and under monolith none has a producer - the backend slot is called ---- */ \
|
||||
/* ---- directly, as today. The payload comments in MGPipeTypes.h say why each exists. ---- */ \
|
||||
/* glBindImageTexture - Espryt syncs the unit's binding to the driver AT THE CALL */ \
|
||||
/* (SyncImageTextureBinding), so the validate-time set_shader_images cannot stand in. */ \
|
||||
X(BindShaderImage, MGPImageBind, kCtxVerb, kNone) \
|
||||
/* glPatchParameteri(GL_PATCH_VERTICES) - Espryt pushes glPatchParameteri at the call. */ \
|
||||
X(PatchParameter, MGPPatchParameter, kCtxVerb, kNone) \
|
||||
/* glBindTransformFeedback - the driver object rebind and the capture-binding shadow */ \
|
||||
/* invalidation happen at the call; the XFB namespace has no wire lifetime. */ \
|
||||
X(BindStreamOutput, MGPStreamOutputBind, kCtxVerb, kNone) \
|
||||
/* glShaderStorageBlockBinding - the block NAME is the coordinate all three sides share */ \
|
||||
/* (BackendObject.h), and a name is bytes: kHasBlob, staged whole in SEG_STAGE, NUL included. */ \
|
||||
X(SetStorageBlockBinding, MGPStorageBlockBinding, kCtxVerb, kHasBlob) \
|
||||
/* glCopyTexImage2D / glCopyTexSubImage2D - a copy whose SOURCE is the read framebuffer, */ \
|
||||
/* which resource_copy_region (resource -> resource) cannot express. */ \
|
||||
X(CopyFramebufferToTexture, MGPCopyFromFramebuffer, kCtxVerb, kNone)
|
||||
// clang-format on
|
||||
|
||||
// Explicitly NOT migrated (plan 4.4.6 / appendix A "explicit deletions"):
|
||||
@@ -208,7 +244,10 @@
|
||||
// - GetProgramiv. GL_COMPUTE_WORK_GROUP_SIZE is a FRONTEND link artifact
|
||||
// (ProgramObject::GetComputeLocalSize, what GL_Program.cpp has always answered from), not
|
||||
// a backend answer at all; nothing a backend knows about a program crosses this way.
|
||||
// - ShaderStorageBlockBinding (folded into MGPProgramDesc's reflection archive),
|
||||
// - ShaderStorageBlockBinding WAS listed here as "folded into MGPProgramDesc's reflection
|
||||
// archive". P5b's set_storage_block_binding row (opcode 75) replaces that: the archive
|
||||
// carries the bindings as LINKED, and the call moves one after link, which the backend
|
||||
// applies to an already-built driver program (DirectGLES.cpp ShaderStorageBlockBinding).
|
||||
// set_pixel_unpack_state (no such state crosses the line - plan 4.6 D5), a
|
||||
// compressed-format concept, pipe_transfer, and the stage dimension of set_sampler_views
|
||||
// (MobileGL's texture unit space is merged, not per stage - plan 4.4.3).
|
||||
|
||||
@@ -173,7 +173,8 @@
|
||||
F(X) F(Y) F(Z) F(W) F(H) F(D) F(SrcOffset) F(SrcRowStride) F(SrcSliceStride)
|
||||
|
||||
#define MGP_FIELDS_MGPSubData(F) \
|
||||
F(Res) F(Target) F(Level) F(SourceIsVerbatimLevelShadow) F(UnionBox) F(RegionCount) F(Blob)
|
||||
F(Res) F(Target) F(Level) F(SourceIsVerbatimLevelShadow) F(HasLiveHostWrites) F(UnionBox) \
|
||||
F(RegionCount) F(Blob)
|
||||
|
||||
#define MGP_FIELDS_MGPSubDataComplete(F) \
|
||||
F(Res) F(Target) F(FirstLevel) F(LevelCount) F(PullSerial)
|
||||
@@ -184,8 +185,11 @@
|
||||
#define MGP_FIELDS_MGPReadback(F) \
|
||||
F(Res) F(Offset) F(Size)
|
||||
|
||||
// P5b (CONTRACT-P5B.md i1): the two GL names are the barrier-pulled lookup keys the sink
|
||||
// rebuilds the CopyImageEndpoints from; listed like any member, so a verify build sees them.
|
||||
#define MGP_FIELDS_MGPCopyRegion(F) \
|
||||
F(Src) F(Dst) F(SrcBox) F(DstX) F(DstY) F(DstZ) F(SrcTarget) F(DstTarget) F(SrcLevel) F(DstLevel)
|
||||
F(Src) F(Dst) F(SrcBox) F(DstX) F(DstY) F(DstZ) F(SrcTarget) F(DstTarget) F(SrcLevel) F(DstLevel) \
|
||||
F(SrcGlName) F(DstGlName)
|
||||
|
||||
#define MGP_FIELDS_MGPBlit(F) \
|
||||
F(ReadFbo) F(DrawFbo) F(SrcX0) F(SrcY0) F(SrcX1) F(SrcY1) F(DstX0) F(DstY0) F(DstX1) F(DstY1) \
|
||||
@@ -239,6 +243,25 @@
|
||||
#define MGP_FIELDS_MGPSurfaceInfo(F) \
|
||||
F(Width) F(Height) F(InternalFormat) F(Samples) F(Layers) F(IsDefault)
|
||||
|
||||
// ---- P5b's five appended rows (MG_Remote/CONTRACT-P5B.md). Pad-named members excluded, as
|
||||
// everywhere; MGPStorageBlockBinding's Name is an MGPBlobRef and recurses into that list.
|
||||
|
||||
#define MGP_FIELDS_MGPImageBind(F) \
|
||||
F(Res) F(Unit) F(GlName) F(Level) F(Layer) F(Access) F(Format) F(Layered)
|
||||
|
||||
#define MGP_FIELDS_MGPPatchParameter(F) \
|
||||
F(Pname) F(Value)
|
||||
|
||||
#define MGP_FIELDS_MGPStreamOutputBind(F) \
|
||||
F(GlName) F(LifetimeId)
|
||||
|
||||
#define MGP_FIELDS_MGPStorageBlockBinding(F) \
|
||||
F(ShaderCso) F(GlName) F(Binding) F(Name)
|
||||
|
||||
#define MGP_FIELDS_MGPCopyFromFramebuffer(F) \
|
||||
F(Dst) F(Target) F(Level) F(InternalFormat) F(X) F(Y) F(Width) F(Height) F(XOffset) F(YOffset) \
|
||||
F(SubImage)
|
||||
|
||||
// ---- the value structs and the host span (P1 brief D8). Not call payloads themselves, but
|
||||
// members of ones (ResidualValueBlock, MGPPixelPackState, MGPCaps) and of PipeInputs, so the
|
||||
// comparator has to see INTO them: with these lists the memcmp fallback of MGPipeFieldEqual is
|
||||
@@ -354,6 +377,8 @@
|
||||
P(MGPDrawRange) P(MGPDrawIndirect) P(MGPGridInfo) P(MGPMemoryBarrier) P(MGPStreamOutputBegin) \
|
||||
P(MGPXfbAccounting) P(MGPStreamOutputControl) P(MGPFlush) P(MGPPresent) P(MGPSwapInterval) \
|
||||
P(MGPSurfaceInfo) \
|
||||
P(MGPImageBind) P(MGPPatchParameter) P(MGPStreamOutputBind) P(MGPStorageBlockBinding) \
|
||||
P(MGPCopyFromFramebuffer) \
|
||||
P(RenderStateParameters) P(PixelStoreParameters) P(SamplerParameters) P(PerBufferBlendState) \
|
||||
P(StencilFaceState) \
|
||||
P(DynamicBackendParameters) P(MGHostSpan) \
|
||||
|
||||
@@ -0,0 +1,366 @@
|
||||
// MobileGL - MobileGL/MG_Pipe/PipeRoute.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
|
||||
|
||||
// The MONOLITH arm of R-17's routing: thirty-seven adapters that unpack a generated table
|
||||
// row's parameters and call the MGPipeApply* entry point the call site used to call directly.
|
||||
// Owner: package c1. See PipeRoute.h for why the arm exists and what R-17 actually cost.
|
||||
//
|
||||
// G2 IS THE WHOLE SPECIFICATION OF THIS FILE. Under monolith transport the thunks must reach
|
||||
// EXACTLY the code they reach today - so every adapter below is a parameter shuffle and
|
||||
// nothing else. There is no branch, no cache, no early return and no logging on any of them,
|
||||
// because each of those is a way for `MOBILEGL_TRANSPORT=monolith` to stop being the control
|
||||
// arm that the split arm is measured against. The one thing an adapter may do beyond calling
|
||||
// through is POST A REPLY, and only the five rows whose call site consumes a value do that.
|
||||
//
|
||||
// WHO CALLS THE INSTALL, AND WHY IT IS NOT IN THIS FILE. `gMGPipeScreen` and `gMGPipeContext`
|
||||
// are inline variables with CONSTANT initialisation, so they are zero - every entry null,
|
||||
// which is the pre-migration state - before any dynamic initialiser runs. The installer is
|
||||
// driven from an inline variable in PipeRoute.h rather than from a static initialiser here,
|
||||
// and the comment beside `detail::gMonolithTablesInstalled` says why: a static initialiser in
|
||||
// THIS file is only in the program if THIS object file is in the link, and over a static
|
||||
// archive it was not. That makes "the tables are installed" an invariant rather than a step
|
||||
// someone can forget, and it is why no MGP_* thunk needs a null check - which matters, because
|
||||
// a null check on a table slot is precisely the shape CONTRACT-P5 §7 spends the 41 call sites
|
||||
// killing.
|
||||
|
||||
#include "PipeRoute.h"
|
||||
|
||||
#if MOBILEGL_PIPE_PUSH
|
||||
|
||||
#include <MG_Util/Debug/Log.h>
|
||||
|
||||
#include <cstdint>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
|
||||
namespace MobileGL::MG_Pipe {
|
||||
|
||||
namespace {
|
||||
|
||||
// ---------------------------------------------------------------------------------
|
||||
// The reply mailbox
|
||||
// ---------------------------------------------------------------------------------
|
||||
|
||||
struct ReplyMailbox {
|
||||
Uint64 Slot = 0; // the MGPReplySlot::Id this answer belongs to; 0 = empty
|
||||
Int32 Status = 0; // 0 OK, 1 DECLINED, 2 ERROR (Transport::ReplyStatus)
|
||||
Uint64 Value = 0; // the Bool, or the pointer, the row answered with
|
||||
Uint64 NextTicket = 0;
|
||||
Uint64 Taken = 0;
|
||||
Uint64 Declined = 0;
|
||||
};
|
||||
|
||||
// THREAD-LOCAL, and one entry deep, because R-1's verb barrier makes the in-flight
|
||||
// depth exactly one. A second post before the first is taken is not a capacity problem:
|
||||
// it is a barrier that has stopped holding, and it Fatals rather than overwriting.
|
||||
thread_local ReplyMailbox g_reply;
|
||||
|
||||
MGPipeRouteArm g_arm = MGPipeRouteArm::kNone;
|
||||
|
||||
// The monolith adapters, kept as tables of their own so the split arm can reach them
|
||||
// on the server role's thread. See PipeRoute.h.
|
||||
MGPipeScreen g_monolithScreen{};
|
||||
MGPipeContext g_monolithContext{};
|
||||
MGPipeRouteEscapes g_monolithEscapes{};
|
||||
|
||||
} // namespace
|
||||
|
||||
const MGPipeScreen& MGPipeMonolithScreen() { return g_monolithScreen; }
|
||||
const MGPipeContext& MGPipeMonolithContext() { return g_monolithContext; }
|
||||
const MGPipeRouteEscapes& MGPipeMonolithEscapes() { return g_monolithEscapes; }
|
||||
|
||||
MGPReplySlot MGPipeMintReplySlot() {
|
||||
// 1-based, for ReplySlot.h's reason: "Seq is 1-based; 0 means 'no record'". A zero id
|
||||
// must stay unmintable so an un-posted mailbox is distinguishable from a posted one.
|
||||
return MGPReplySlot{++g_reply.NextTicket};
|
||||
}
|
||||
|
||||
void MGPipePostReply(const MGPReplySlot& slot, Int32 status, Uint64 value) {
|
||||
if (slot.Id == 0) {
|
||||
MGLOG_F("MGPipe: Fatal{ReplyToNoSlot} - a table row posted an answer against reply "
|
||||
"slot 0, which ReplySlot.h reserves for \"no record\"");
|
||||
std::abort();
|
||||
}
|
||||
if (g_reply.Slot != 0 && g_reply.Slot != slot.Id) {
|
||||
MGLOG_F("MGPipe: Fatal{ReplyOverrun} - slot %llu posted while slot %llu was still "
|
||||
"unread. The mailbox is one deep because R-1's verb barrier makes the "
|
||||
"in-flight depth one; two outstanding answers means the barrier is not "
|
||||
"holding",
|
||||
static_cast<unsigned long long>(slot.Id),
|
||||
static_cast<unsigned long long>(g_reply.Slot));
|
||||
std::abort();
|
||||
}
|
||||
g_reply.Slot = slot.Id;
|
||||
g_reply.Status = status;
|
||||
g_reply.Value = value;
|
||||
}
|
||||
|
||||
namespace {
|
||||
// The one reader. Fatals rather than defaulting, in both directions - see PipeRoute.h.
|
||||
Uint64 TakeReply(const MGPReplySlot& slot, const char* row, Int32* statusOut) {
|
||||
if (g_reply.Slot == 0) {
|
||||
MGLOG_F("MGPipe: Fatal{ReplyMissing, \"%s\"} - the row was routed and nothing "
|
||||
"posted an answer. R-5 forbids re-deriving acceptance on the client and "
|
||||
"forbids assuming it, so there is no default to fall back to",
|
||||
row);
|
||||
std::abort();
|
||||
}
|
||||
if (g_reply.Slot != slot.Id) {
|
||||
MGLOG_F("MGPipe: Fatal{ReplyMismatched, \"%s\"} - waiting on slot %llu, the "
|
||||
"mailbox holds slot %llu",
|
||||
row, static_cast<unsigned long long>(slot.Id),
|
||||
static_cast<unsigned long long>(g_reply.Slot));
|
||||
std::abort();
|
||||
}
|
||||
const Uint64 value = g_reply.Value;
|
||||
if (statusOut != nullptr) *statusOut = g_reply.Status;
|
||||
if (g_reply.Status == 1) ++g_reply.Declined;
|
||||
++g_reply.Taken;
|
||||
g_reply.Slot = 0;
|
||||
g_reply.Value = 0;
|
||||
g_reply.Status = 0;
|
||||
return value;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
Bool MGPipeTakeReplyBool(const MGPReplySlot& slot, const char* row) {
|
||||
Int32 status = 0;
|
||||
const Uint64 value = TakeReply(slot, row, &status);
|
||||
// DECLINED IS A REAL ANSWER AND IT IS `false`, not a failure (ReplySlot.h). ERROR is
|
||||
// not an acceptance answer at all and may not be folded into either.
|
||||
if (status == 2) {
|
||||
MGLOG_F("MGPipe: Fatal{ReplyError, \"%s\"} - the row answered ERROR, which is not an "
|
||||
"acceptance answer; folding it into accepted or refused would make a "
|
||||
"transport fault look like a resource decision",
|
||||
row);
|
||||
std::abort();
|
||||
}
|
||||
if (status == 1) return false;
|
||||
return value != 0;
|
||||
}
|
||||
|
||||
void* MGPipeTakeReplyPointer(const MGPReplySlot& slot, const char* row) {
|
||||
Int32 status = 0;
|
||||
const Uint64 value = TakeReply(slot, row, &status);
|
||||
if (status == 2) {
|
||||
MGLOG_F("MGPipe: Fatal{ReplyError, \"%s\"}", row);
|
||||
std::abort();
|
||||
}
|
||||
// DECLINED is the null pointer, and it is R-6's answer for map_persistent under split.
|
||||
if (status == 1) return nullptr;
|
||||
return reinterpret_cast<void*>(static_cast<std::uintptr_t>(value));
|
||||
}
|
||||
|
||||
Uint64 MGPipeRepliesTaken() { return g_reply.Taken; }
|
||||
Uint64 MGPipeRepliesDeclined() { return g_reply.Declined; }
|
||||
|
||||
MGPipeRouteArm MGPipeInstalledArm() { return g_arm; }
|
||||
void MGPipeNoteInstalledArm(MGPipeRouteArm arm) { g_arm = arm; }
|
||||
Bool MGPipeTablesAreInstalled() { return g_arm != MGPipeRouteArm::kNone; }
|
||||
|
||||
// ---------------------------------------------------------------------------------
|
||||
// The thirty-seven monolith adapters
|
||||
// ---------------------------------------------------------------------------------
|
||||
//
|
||||
// Three shapes, so the eye can check them against PipeTables.inc in one pass rather than
|
||||
// reading thirty-seven bodies. A row that does not fit one of the three is written out by
|
||||
// hand BELOW the macros, never by widening a macro - a macro that grew a special case is
|
||||
// how one of these silently stops being a parameter shuffle.
|
||||
|
||||
namespace {
|
||||
|
||||
#define MGP_MONO_PLAIN(Name, Payload) \
|
||||
void Mono_##Name(const Payload* payload) { MGPipeApply##Name(*payload); }
|
||||
|
||||
#define MGP_MONO_BLOB(Name, Payload) \
|
||||
void Mono_##Name(const Payload* payload, const void* blobBytes, Uint64) { \
|
||||
MGPipeApply##Name(*payload, blobBytes); \
|
||||
}
|
||||
|
||||
#define MGP_MONO_TAIL(Name, Payload, TailType) \
|
||||
void Mono_##Name(const Payload* payload, const void* varTail, Uint32) { \
|
||||
MGPipeApply##Name(*payload, static_cast<const TailType*>(varTail)); \
|
||||
}
|
||||
|
||||
// -- screen -------------------------------------------------------------------
|
||||
MGP_MONO_PLAIN(ResourceDestroy, MGPHandleOnly)
|
||||
MGP_MONO_PLAIN(UnmapPersistent, MGPHandleOnly)
|
||||
|
||||
// -- context, plain -----------------------------------------------------------
|
||||
MGP_MONO_PLAIN(BindRenderState, MGPBindRenderState)
|
||||
MGP_MONO_PLAIN(DeleteRenderState, MGPHandleOnly)
|
||||
MGP_MONO_PLAIN(BindVertexElements, MGPHandleOnly)
|
||||
MGP_MONO_PLAIN(DeleteVertexElements, MGPHandleOnly)
|
||||
MGP_MONO_PLAIN(DeleteSamplerState, MGPHandleOnly)
|
||||
MGP_MONO_PLAIN(CreateSamplerView, MGPSamplerView)
|
||||
MGP_MONO_PLAIN(DeleteSamplerView, MGPHandleOnly)
|
||||
MGP_MONO_PLAIN(BindShaderState, MGPHandleOnly)
|
||||
MGP_MONO_PLAIN(DeleteShaderState, MGPHandleOnly)
|
||||
MGP_MONO_PLAIN(SetDrawProgram, MGPHandleOnly)
|
||||
MGP_MONO_PLAIN(SetDispatchProgram, MGPHandleOnly)
|
||||
MGP_MONO_PLAIN(SetFramebufferState, MGPFramebufferState)
|
||||
MGP_MONO_PLAIN(SetIndexBuffer, MGPIndexBuffer)
|
||||
MGP_MONO_PLAIN(SetPixelPackState, MGPPixelPackState)
|
||||
MGP_MONO_PLAIN(SetPatchState, MGPPatchState)
|
||||
|
||||
// -- context, blob companion --------------------------------------------------
|
||||
MGP_MONO_BLOB(CreateRenderState, MGPRenderStateDesc)
|
||||
MGP_MONO_BLOB(CreateVertexElements, MGPVertexElements)
|
||||
MGP_MONO_BLOB(SetDynamicState, MGPDynamicState)
|
||||
MGP_MONO_BLOB(SetGlobalConstants, MGPGlobalConstants)
|
||||
MGP_MONO_BLOB(BufferSubDataResident, MGPSubData)
|
||||
|
||||
// -- context, variable tail ---------------------------------------------------
|
||||
MGP_MONO_TAIL(SetVertexBuffers, MGPVertexBuffers, MGPVertexBuffer)
|
||||
MGP_MONO_TAIL(SetSamplerViews, MGPSamplerViews, MGPBoundView)
|
||||
MGP_MONO_TAIL(BindSamplerStates, MGPSamplerStates, MGPipeHandle)
|
||||
MGP_MONO_TAIL(SetShaderImages, MGPShaderImages, MGPImageView)
|
||||
MGP_MONO_TAIL(SetVertexAttribDefaults, MGPVertexAttribDefaults, MGPAttribValue)
|
||||
|
||||
#undef MGP_MONO_PLAIN
|
||||
#undef MGP_MONO_BLOB
|
||||
#undef MGP_MONO_TAIL
|
||||
|
||||
// -- the rows that fit none of the three shapes --------------------------------
|
||||
|
||||
// create_sampler_state: the blob is a TYPED frontend struct, not bytes the applier
|
||||
// reads through a void*. The cast is the whole adapter, and it is exact: the client
|
||||
// stages sizeof(SamplerParameters) bytes of the same object (CONTRACT-P5 table 1
|
||||
// row 17, including its padding trap - the bytes staged must be the bytes a later
|
||||
// memcmp compares).
|
||||
void Mono_CreateSamplerState(const MGPSamplerDesc* payload, const void* blobBytes, Uint64) {
|
||||
MGPipeApplyCreateSamplerState(*payload,
|
||||
static_cast<const SamplerParameters*>(blobBytes));
|
||||
}
|
||||
|
||||
// set_residual_value_state: CONTRACT-P5 table 1 row 6, "the hardest row in the table".
|
||||
// The applier takes `const ResidualValueBlock&` - a frontend type - and
|
||||
// MGPResidualValueState is never instantiated on the live path. So the BLOCK IS THE
|
||||
// BLOB, in both arms, and the adapter copies it back out. Requiring exact equality
|
||||
// rather than ">=" is the decoder's rule too (PipeWireCodec.cpp): a size that only
|
||||
// ever ratchets down makes a short read silently lose CapabilityBits.
|
||||
void Mono_SetResidualValueState(const MGPResidualValueState*, const void* blobBytes,
|
||||
Uint64 blobByteCount) {
|
||||
if (blobByteCount != sizeof(ResidualValueBlock) || blobBytes == nullptr) {
|
||||
MGLOG_F("MGPipe: Fatal{ResidualBlockSize} - set_residual_value_state carries %llu "
|
||||
"bytes, the block is %llu",
|
||||
static_cast<unsigned long long>(blobByteCount),
|
||||
static_cast<unsigned long long>(sizeof(ResidualValueBlock)));
|
||||
std::abort();
|
||||
}
|
||||
ResidualValueBlock block{};
|
||||
std::memcpy(&block, blobBytes, sizeof(block));
|
||||
MGPipeApplySetResidualValueState(block);
|
||||
}
|
||||
|
||||
// resource_readback carries kReplySlot but its answer is COMPLETION, not a value: the
|
||||
// bytes go server -> client through SEG_EVENT's OnBufferWriteback (CONTRACT-P5 table 1
|
||||
// row 22), and the split decoder posts exactly kStatusOk with a zero-length payload.
|
||||
// The monolith arm says the same thing, so the two arms hand their caller the same
|
||||
// answer rather than one of them handing it nothing.
|
||||
void Mono_ResourceReadback(const MGPReadback* payload, MGPReplySlot* reply) {
|
||||
MGPipeApplyResourceReadback(*payload);
|
||||
MGPipePostReply(*reply, 0, 0);
|
||||
}
|
||||
|
||||
// The three acceptance rows that DO fit a generated signature. Each posts the
|
||||
// applier's own answer; none of them invents one.
|
||||
void Mono_ResourceCreate(const MGPResourceDesc* payload, MGPReplySlot* reply) {
|
||||
const Bool accepted = MGPipeApplyResourceCreate(*payload);
|
||||
MGPipePostReply(*reply, accepted ? 0 : 1, accepted ? 1u : 0u);
|
||||
}
|
||||
|
||||
void Mono_SetTextureParams(const MGPTextureParams* payload, MGPReplySlot* reply) {
|
||||
const Bool accepted = MGPipeApplySetTextureParams(*payload);
|
||||
MGPipePostReply(*reply, accepted ? 0 : 1, accepted ? 1u : 0u);
|
||||
}
|
||||
|
||||
void Mono_ResourceSubData(const MGPSubData* payload, const void* blobBytes, Uint64,
|
||||
const void* varTail, Uint32, MGPReplySlot* reply) {
|
||||
const Bool accepted = MGPipeApplyResourceSubData(
|
||||
*payload, blobBytes, static_cast<const MGPSubRegion*>(varTail));
|
||||
MGPipePostReply(*reply, accepted ? 0 : 1, accepted ? 1u : 0u);
|
||||
}
|
||||
|
||||
// -- the four escapes ----------------------------------------------------------
|
||||
|
||||
Bool Mono_Escape_ResourceRespecify(const MGPResourceDesc* desc, const void* initialBytes,
|
||||
const MGPRespecifiedLevel* level) {
|
||||
return MGPipeApplyResourceRespecify(*desc, initialBytes, level);
|
||||
}
|
||||
|
||||
void Mono_Escape_ResourceFlushRange(const MGPFlushRange* record, const void* bytes) {
|
||||
MGPipeApplyResourceFlushRange(*record, bytes);
|
||||
}
|
||||
|
||||
void* Mono_Escape_MapPersistent(const MGPHandleOnly* handle, Uint64 size,
|
||||
const void* seedBytes) {
|
||||
return MGPipeApplyMapPersistent(*handle, size, seedBytes);
|
||||
}
|
||||
|
||||
void Mono_Escape_CreateShaderState(const MGPProgramDesc* desc,
|
||||
const MG_State::GLState::LinkArtifacts* link,
|
||||
const MG_State::GLState::SpirvArtifacts* spirv) {
|
||||
MGPipeApplyCreateShaderState(*desc, link, spirv);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
void MGPipeInstallMonolithTables() {
|
||||
gMGPipeScreen.ResourceCreate = &Mono_ResourceCreate;
|
||||
gMGPipeScreen.ResourceDestroy = &Mono_ResourceDestroy;
|
||||
gMGPipeScreen.UnmapPersistent = &Mono_UnmapPersistent;
|
||||
|
||||
gMGPipeContext.CreateRenderState = &Mono_CreateRenderState;
|
||||
gMGPipeContext.BindRenderState = &Mono_BindRenderState;
|
||||
gMGPipeContext.DeleteRenderState = &Mono_DeleteRenderState;
|
||||
gMGPipeContext.CreateVertexElements = &Mono_CreateVertexElements;
|
||||
gMGPipeContext.BindVertexElements = &Mono_BindVertexElements;
|
||||
gMGPipeContext.DeleteVertexElements = &Mono_DeleteVertexElements;
|
||||
gMGPipeContext.CreateSamplerState = &Mono_CreateSamplerState;
|
||||
gMGPipeContext.DeleteSamplerState = &Mono_DeleteSamplerState;
|
||||
gMGPipeContext.CreateSamplerView = &Mono_CreateSamplerView;
|
||||
gMGPipeContext.DeleteSamplerView = &Mono_DeleteSamplerView;
|
||||
gMGPipeContext.BindShaderState = &Mono_BindShaderState;
|
||||
gMGPipeContext.DeleteShaderState = &Mono_DeleteShaderState;
|
||||
gMGPipeContext.SetDrawProgram = &Mono_SetDrawProgram;
|
||||
gMGPipeContext.SetDispatchProgram = &Mono_SetDispatchProgram;
|
||||
gMGPipeContext.SetDynamicState = &Mono_SetDynamicState;
|
||||
gMGPipeContext.SetFramebufferState = &Mono_SetFramebufferState;
|
||||
gMGPipeContext.SetVertexBuffers = &Mono_SetVertexBuffers;
|
||||
gMGPipeContext.SetIndexBuffer = &Mono_SetIndexBuffer;
|
||||
gMGPipeContext.SetSamplerViews = &Mono_SetSamplerViews;
|
||||
gMGPipeContext.BindSamplerStates = &Mono_BindSamplerStates;
|
||||
gMGPipeContext.SetShaderImages = &Mono_SetShaderImages;
|
||||
gMGPipeContext.SetGlobalConstants = &Mono_SetGlobalConstants;
|
||||
gMGPipeContext.SetVertexAttribDefaults = &Mono_SetVertexAttribDefaults;
|
||||
gMGPipeContext.SetPixelPackState = &Mono_SetPixelPackState;
|
||||
gMGPipeContext.SetPatchState = &Mono_SetPatchState;
|
||||
gMGPipeContext.SetResidualValueState = &Mono_SetResidualValueState;
|
||||
gMGPipeContext.SetTextureParams = &Mono_SetTextureParams;
|
||||
gMGPipeContext.ResourceSubData = &Mono_ResourceSubData;
|
||||
gMGPipeContext.BufferSubDataResident = &Mono_BufferSubDataResident;
|
||||
gMGPipeContext.ResourceReadback = &Mono_ResourceReadback;
|
||||
|
||||
gMGPipeRouteEscapes.ResourceRespecify = &Mono_Escape_ResourceRespecify;
|
||||
gMGPipeRouteEscapes.ResourceFlushRange = &Mono_Escape_ResourceFlushRange;
|
||||
gMGPipeRouteEscapes.MapPersistent = &Mono_Escape_MapPersistent;
|
||||
gMGPipeRouteEscapes.CreateShaderState = &Mono_Escape_CreateShaderState;
|
||||
|
||||
// KEPT, not merely installed. The client arm overwrites the three tables above; these
|
||||
// three copies are what it forwards to when it finds itself on the server's own thread.
|
||||
g_monolithScreen = gMGPipeScreen;
|
||||
g_monolithContext = gMGPipeContext;
|
||||
g_monolithEscapes = gMGPipeRouteEscapes;
|
||||
|
||||
MGPipeNoteInstalledArm(MGPipeRouteArm::kMonolith);
|
||||
}
|
||||
|
||||
} // namespace MobileGL::MG_Pipe
|
||||
|
||||
#endif // MOBILEGL_PIPE_PUSH
|
||||
@@ -0,0 +1,400 @@
|
||||
// MobileGL - MobileGL/MG_Pipe/PipeRoute.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
|
||||
|
||||
// THE CLIENT -> WIRE ROUTING OF THE 37 MGPipeApply* ENTRY POINTS (P5, integrator ruling R-17).
|
||||
// Owner: package c1.
|
||||
//
|
||||
// WHAT WAS MISSING. `gMGPipeWireRecordApply` is the DECODE hook and it has existed since w1:
|
||||
// a record arrives, `PipeWireCodec` picks it apart and calls `MGPipeApply<Name>`. There was no
|
||||
// encode twin. Every `MG_Impl/Pipe` emitter called `MGPipeApply<Name>` DIRECTLY, so under
|
||||
// `MOBILEGL_TRANSPORT=inproc` every resource, CSO, texture and program record still executed
|
||||
// synchronously on the GL thread against a context v1 is moving to the apply thread - where
|
||||
// all sixteen `IsBackendContextCurrentOnThisThread()` and sixteen `CanTouchGLNow()` guards
|
||||
// answer false. `ClearThenReadPixels` might have survived that; `TriangleScenario` needs a VBO
|
||||
// and a program and could not.
|
||||
//
|
||||
// The two generated tables (`gMGPipeScreen`, `gMGPipeContext`, `generated/PipeTables.inc`) are
|
||||
// the boundary this repository already had, and they were never installed - every entry null,
|
||||
// which `MGPipe.h` correctly calls "precisely the pre-migration state". R-17 installs them.
|
||||
// This header is the frontend-facing half: the names `MG_Impl/Pipe` calls, and the mechanism
|
||||
// that gets a kReplySlot row's answer back to its call site.
|
||||
//
|
||||
// ---------------------------------------------------------------------------------------
|
||||
// THE SIZE OF R-17, MEASURED RATHER THAN ESTIMATED
|
||||
// ---------------------------------------------------------------------------------------
|
||||
//
|
||||
// R-17 costed this as "37 thin client emitters over EmitAndWait". The emitters are thin. The
|
||||
// ROUTING was not, and the reason is that the generated table signature is the P2-era monolith
|
||||
// interface: `void (*Name)(const Payload* payload, ...)`, async-with-handle, no return value,
|
||||
// and NO COMPANION POINTER. Of the 37 entry points, as the tables stood:
|
||||
//
|
||||
// 24 the row could carry every argument the call site passes today
|
||||
// 13 it could not
|
||||
//
|
||||
// The thirteen split three ways, and only one of the three is a generator question:
|
||||
//
|
||||
// (a) NINE carry a blob companion - `chunkBytes`, `blobBytes`, `parameters`, `bytes`,
|
||||
// `initialBytes` - which is CONTRACT-P5 table 1's "companion pointer today" column. A
|
||||
// kVarTail row already gains `const void* varTail, Uint32 varTailCount`; a kHasBlob row
|
||||
// gained nothing. THE GENERATOR CHANGE IS THAT ONE ASYMMETRY, and nothing else: five
|
||||
// lines in `Call.Signature` giving a kHasBlob row `const void* blobBytes, Uint64
|
||||
// blobByteCount`. Ten rows gained the pair (the nine plus `GetCaps`, which has no applier
|
||||
// entry point). `--check` up to date, `--self-test` 9/9 trips.
|
||||
//
|
||||
// (b) FOUR return a value the row cannot: `ResourceCreate`, `ResourceRespecify`,
|
||||
// `ResourceSubData` and `SetTextureParams` return Bool and `MapPersistent` returns void*.
|
||||
// These are exactly CONTRACT-P5 §2's reply-slot rows, and R-5 forbids re-deriving any of
|
||||
// them on the client. The answer therefore has to come back THROUGH the reply slot, which
|
||||
// is what `MGPipeTakeReply*` below is, and it is the part of R-17 that no amount of
|
||||
// "thin emitter" covers: `MGPReplySlot` is `{Uint64 Id;}` - an IDENTIFIER, not a value -
|
||||
// so a reader had to exist for the identifier to be worth minting.
|
||||
//
|
||||
// (c) FOUR CANNOT GO THROUGH A GENERATED ROW AT ALL, and each one is a contract ruling
|
||||
// rather than an oversight. They are the ESCAPES below. Saying "four" out loud is the
|
||||
// honest answer to "tell me if it is bigger than it looks": it is, by four rows and one
|
||||
// reply-reading mechanism.
|
||||
//
|
||||
// ---------------------------------------------------------------------------------------
|
||||
// THE REPLY MAILBOX, AND WHY ONE ENTRY IS THE RIGHT DEPTH
|
||||
// ---------------------------------------------------------------------------------------
|
||||
//
|
||||
// `MGPReplySlot` carries an id; the answer lands beside it. The mailbox is ONE ENTRY DEEP and
|
||||
// thread-local, and that is not a simplification - it is R-1's verb barrier stated as a data
|
||||
// structure. While the barrier holds, the in-flight depth is exactly one (`ReplySlot.h`:
|
||||
// "under R-1's verb barrier the in-flight depth is one"), so a second posting before the first
|
||||
// is taken is not a capacity problem, it is a barrier that has stopped working. It Fatals.
|
||||
//
|
||||
// THE MAILBOX HAS NO DEFAULT ANSWER AND THIS IS THE WHOLE POINT. `MGPipeTakeReplyBool` on a
|
||||
// slot nothing posted to is `Fatal{ReplyMissing, "<row>"}`, not `false` and emphatically not
|
||||
// `true`. "Always accept" is ID-39's 66 lost DirectVulkan uploads with a wire in between, and
|
||||
// "always refuse" is an emitter that re-sends for ever. A row that forgets to answer is a bug
|
||||
// that must be impossible to ship, so it is impossible to READ.
|
||||
//
|
||||
// WHEN THE BARRIER RETIRES (R-1 opens family by family) this becomes a real slot pool keyed on
|
||||
// seq, which is what `Transport::ReplySlot` already is on the wire side. The mailbox is the
|
||||
// frontend-side handle onto it and nothing else; it is deliberately NOT a second id space,
|
||||
// because the split arm stamps the record's own seq into `MGPReplySlot::Id` (R-3).
|
||||
|
||||
#pragma once
|
||||
#include <Includes.h>
|
||||
|
||||
#if MOBILEGL_PIPE_PUSH
|
||||
|
||||
#include "MGPipe.h"
|
||||
#include "PipeApply.h"
|
||||
|
||||
namespace MobileGL::MG_Pipe {
|
||||
|
||||
// ---------------------------------------------------------------------------------
|
||||
// The reply mailbox
|
||||
// ---------------------------------------------------------------------------------
|
||||
|
||||
// Mints the id for one call's answer. Monolith's ids and the wire's seqs are separate
|
||||
// spaces on purpose: under split the emitter OVERWRITES this with the record's own seq
|
||||
// (R-3: "the reply slot id IS the record sequence number"), so the id a caller finally
|
||||
// reads is the wire's, and under monolith it is a local ticket that only has to be unique
|
||||
// against the one outstanding call the barrier permits.
|
||||
MGPReplySlot MGPipeMintReplySlot();
|
||||
|
||||
// Posts one answer. Called by whichever table is installed - the monolith adapter with
|
||||
// the applier's return value, the client emitter with the bytes the server put in
|
||||
// SEG_REPLY. `status` is Transport::ReplyStatus' value space (0 OK, 1 DECLINED, 2 ERROR),
|
||||
// restated as a plain Int32 so MG_Pipe does not have to see MG_Remote at all.
|
||||
void MGPipePostReply(const MGPReplySlot& slot, Int32 status, Uint64 value);
|
||||
|
||||
// Takes the answer for `slot`. Fatals - naming `row` - if nothing was posted, if what was
|
||||
// posted belongs to a different slot, or if the answer has already been taken.
|
||||
Bool MGPipeTakeReplyBool(const MGPReplySlot& slot, const char* row);
|
||||
void* MGPipeTakeReplyPointer(const MGPReplySlot& slot, const char* row);
|
||||
|
||||
// How many answers this thread has taken, and how many of those were DECLINED. Counted
|
||||
// rather than inferred, for R-8's reason one level out: "the client accepted everything"
|
||||
// and "the client never asked" are otherwise the same observation from outside.
|
||||
Uint64 MGPipeRepliesTaken();
|
||||
Uint64 MGPipeRepliesDeclined();
|
||||
|
||||
// ---------------------------------------------------------------------------------
|
||||
// The escapes: the four rows no generated signature can express
|
||||
// ---------------------------------------------------------------------------------
|
||||
//
|
||||
// A hand-written third table, installed and uninstalled by the same two functions as the
|
||||
// generated pair, so there is ONE mechanism and not two. Each row's signature is the
|
||||
// applier's own, because that is the shape the monolith arm has to reproduce byte for
|
||||
// byte (G2), and each row is here for a ruling that is written down:
|
||||
//
|
||||
// ResourceRespecify `initialBytes` has NO kHasBlob and R-13.3 forbids giving it one
|
||||
// ("initialBytes is always nullptr under split; initial content
|
||||
// arrives as ResourceSubData records immediately after this one").
|
||||
// So the row is correct to omit it AND monolith must still pass it.
|
||||
// ResourceFlushRange `bytes` likewise, by R-13.2, and for a sharper reason: a blobref
|
||||
// here would be "a second, forgeable way to say the same thing".
|
||||
// MapPersistent `size` and `seedBytes` have no carrier at all - `MGPHandleOnly` is
|
||||
// {Handle, Kind} - and the call returns void*. R-6 makes the split
|
||||
// answer a constant DECLINE, so the carrier is not needed; the
|
||||
// monolith arm needs both arguments.
|
||||
// CreateShaderState SEVEN blobrefs (`Spirv[6]` + `Reflection`) and TWO typed frontend
|
||||
// pointers. One `blobBytes` pair cannot express seven runs, and
|
||||
// serialising under monolith to un-serialise in the adapter would put
|
||||
// `EncodeProgramArtifacts` on the monolith path, which `PipeApply.h`
|
||||
// explicitly promises it is not ("zero serialisation cost on the
|
||||
// monolith path").
|
||||
//
|
||||
// OVERTURN CONDITIONS, one per row: give `MGPResourceDesc` and `MGPFlushRange` a blobref
|
||||
// (overturns R-13.2/R-13.3, and c0 owns `MGPipeTypes.h`); give `MGPHandleOnly` a size
|
||||
// (same owner) and P6 a real remote map; measure that a per-stage SPIR-V run beats one
|
||||
// archive, at which point `CreateShaderState` needs a multi-blob row rather than this one.
|
||||
struct MGPipeRouteEscapes {
|
||||
Bool (*ResourceRespecify)(const MGPResourceDesc* desc, const void* initialBytes,
|
||||
const MGPRespecifiedLevel* level);
|
||||
void (*ResourceFlushRange)(const MGPFlushRange* record, const void* bytes);
|
||||
void* (*MapPersistent)(const MGPHandleOnly* handle, Uint64 size, const void* seedBytes);
|
||||
void (*CreateShaderState)(const MGPProgramDesc* desc,
|
||||
const MG_State::GLState::LinkArtifacts* link,
|
||||
const MG_State::GLState::SpirvArtifacts* spirv);
|
||||
};
|
||||
inline MGPipeRouteEscapes gMGPipeRouteEscapes{};
|
||||
|
||||
// ---------------------------------------------------------------------------------
|
||||
// The two install functions
|
||||
// ---------------------------------------------------------------------------------
|
||||
|
||||
// Installs the monolith adapters into all three tables. Idempotent.
|
||||
void MGPipeInstallMonolithTables();
|
||||
|
||||
// The monolith adapters, kept beside the installed tables rather than only written into
|
||||
// them. THE SPLIT ARM NEEDS THEM AT RUNTIME, and the reason is table 3's role split made
|
||||
// concrete: `gMGPipeScreen` / `gMGPipeContext` are PROCESS globals, and under `inproc` the
|
||||
// server role lives in the same process on the apply thread. When that thread runs the
|
||||
// server's own backend - the EGL bring-up, InitCapabilities, or the applier itself - it
|
||||
// reaches the very same `MG_Impl/Pipe` emitters the client does, and a wire emitter there
|
||||
// publishes a record and then waits for the apply thread to apply it. That thread IS the
|
||||
// apply thread, so it waits for itself: `Fatal{BarrierTimeout, "ResourceRespecify"}`,
|
||||
// logged by `mgl-srv-apply`, thirty seconds after bring-up starts.
|
||||
//
|
||||
// So the client emitters ask "am I the server role right now?" and, if so, run the
|
||||
// monolith adapter - which is exactly what `PipeWireCodec` already does on the decode side
|
||||
// by calling `MGPipeApply*` directly. The predicate is v1's `ServerLoop::OnApplyThread()`;
|
||||
// these three accessors are what makes the other half reachable.
|
||||
const MGPipeScreen& MGPipeMonolithScreen();
|
||||
const MGPipeContext& MGPipeMonolithContext();
|
||||
const MGPipeRouteEscapes& MGPipeMonolithEscapes();
|
||||
|
||||
namespace detail {
|
||||
// THE INSTALL THAT CANNOT BE LINKED AWAY, and the first version of this WAS.
|
||||
//
|
||||
// It began as a static initialiser inside PipeRoute.cpp, on the reasoning that
|
||||
// `gMGPipeScreen` and `gMGPipeContext` are inline variables with CONSTANT (zero)
|
||||
// initialisation - sequenced before every dynamic initialiser - so an installer in
|
||||
// dynamic init necessarily beats any GL entry point. That reasoning is correct and the
|
||||
// mechanism still failed, because it assumed PipeRoute.o would be in the link at all:
|
||||
// every MG_Test target is its OWN binary over a static archive, `CsoCache.h` reaches
|
||||
// the table through an inline thunk and names no symbol from PipeRoute.o, so the
|
||||
// linker dropped the object, the initialiser never ran, and five CsoCacheTest cases
|
||||
// took a null function pointer. The shared library linked it and was fine, which is
|
||||
// exactly the shape that ships.
|
||||
//
|
||||
// AN INLINE VARIABLE FIXES BOTH HALVES AT ONCE. Its initialiser is emitted as a COMDAT
|
||||
// in every translation unit that includes this header, so any binary that can call a
|
||||
// thunk has one copy of it; and naming `MGPipeInstallMonolithTables` from a header the
|
||||
// call sites already include is an undefined reference that forces the archive member
|
||||
// into the link. There is still exactly one install, and it still happens before main.
|
||||
inline const Bool gMonolithTablesInstalled = (MGPipeInstallMonolithTables(), true);
|
||||
} // namespace detail
|
||||
|
||||
// True once the tables hold something. Exposed for the gates only: a probe that armed
|
||||
// against an un-installed table would be arming against the pre-migration state.
|
||||
Bool MGPipeTablesAreInstalled();
|
||||
|
||||
// Which arm is installed, so a case can assert the arm it thinks it is testing rather than
|
||||
// trusting `MOBILEGL_TRANSPORT`. `MG_Config::Transport` says what was ASKED for; this says
|
||||
// what the table actually does.
|
||||
enum class MGPipeRouteArm : Uint8 { kNone, kMonolith, kClientWire };
|
||||
MGPipeRouteArm MGPipeInstalledArm();
|
||||
void MGPipeNoteInstalledArm(MGPipeRouteArm arm);
|
||||
|
||||
// ---------------------------------------------------------------------------------
|
||||
// The call-site names: MGPipeRoute<Name> for each of the thirty-seven
|
||||
// ---------------------------------------------------------------------------------
|
||||
//
|
||||
// EVERY ONE TAKES THE APPLIER'S OWN SIGNATURE, so converting a call site is a rename and
|
||||
// nothing else. That is not tidiness, it is the G1 lesson from round 1 stated as a rule:
|
||||
// rewriting `if (const auto f = TABLE.GL.Slot)` into a Bool-valued macro is semantically
|
||||
// identical and generates DIFFERENT code (-144 bytes, two symbols resized). A wrapper that
|
||||
// took `&expr` would force every site holding a temporary - `HandleOnly(handle)`,
|
||||
// `BufferHandleOnly(handle)` - to grow a named local, which is a second expression shape
|
||||
// change at forty sites. A reference parameter keeps the call site's text identical but
|
||||
// for the name.
|
||||
//
|
||||
// THREE OF THE THIRTY-SEVEN TAKE ONE ARGUMENT MORE THAN THEIR APPLIER, and the extra is
|
||||
// always the same thing: A BYTE COUNT THE RECORD DOES NOT DECLARE. CONTRACT-P5 table 1
|
||||
// rule A requires every kHasBlob row to declare its length under split; five rows already
|
||||
// do and the wrapper reads it back off the record, three do not and their call site is the
|
||||
// only place the number exists:
|
||||
// SetGlobalConstants declares 0 (ProgramEmit.h); the length is GetUBOSize()
|
||||
// ResourceSubData buffer half declares real, TEXTURE half declares 0 on the
|
||||
// grounds that the count is "the server's to compute" - which
|
||||
// table 1 row 7 says "cannot be a bounds check". The level
|
||||
// shadow's byte size is in scope at that call site.
|
||||
// BufferSubDataResident the application's staging store, sized by the caller
|
||||
// A defaulted argument was rejected: a default would let a site that has the number forget
|
||||
// to pass it and still compile, and the failure would be a silently short upload.
|
||||
|
||||
// ---- screen ------------------------------------------------------------------------
|
||||
inline Bool MGPipeRouteResourceCreate(const MGPResourceDesc& desc) {
|
||||
MGPReplySlot reply = MGPipeMintReplySlot();
|
||||
MGP_ResourceCreate(&desc, &reply);
|
||||
return MGPipeTakeReplyBool(reply, "resource_create");
|
||||
}
|
||||
inline Bool MGPipeRouteResourceRespecify(const MGPResourceDesc& desc, const void* initialBytes,
|
||||
const MGPRespecifiedLevel* level = nullptr) {
|
||||
return gMGPipeRouteEscapes.ResourceRespecify(&desc, initialBytes, level);
|
||||
}
|
||||
inline void MGPipeRouteResourceDestroy(const MGPHandleOnly& handle) {
|
||||
MGP_ResourceDestroy(&handle);
|
||||
}
|
||||
inline void* MGPipeRouteMapPersistent(const MGPHandleOnly& handle, Uint64 size,
|
||||
const void* seedBytes) {
|
||||
return gMGPipeRouteEscapes.MapPersistent(&handle, size, seedBytes);
|
||||
}
|
||||
inline void MGPipeRouteUnmapPersistent(const MGPHandleOnly& handle) {
|
||||
MGP_UnmapPersistent(&handle);
|
||||
}
|
||||
|
||||
// ---- resources ---------------------------------------------------------------------
|
||||
inline Bool MGPipeRouteResourceSubData(const MGPSubData& record, const void* bytes,
|
||||
Uint64 byteCount,
|
||||
const MGPSubRegion* regions = nullptr) {
|
||||
MGPReplySlot reply = MGPipeMintReplySlot();
|
||||
MGP_ResourceSubData(&record, bytes, byteCount, regions, record.RegionCount, &reply);
|
||||
return MGPipeTakeReplyBool(reply, "resource_subdata");
|
||||
}
|
||||
inline void MGPipeRouteBufferSubDataResident(const MGPSubData& record, const void* bytes,
|
||||
Uint64 byteCount) {
|
||||
MGP_BufferSubDataResident(&record, bytes, byteCount);
|
||||
}
|
||||
inline void MGPipeRouteResourceFlushRange(const MGPFlushRange& record, const void* bytes) {
|
||||
gMGPipeRouteEscapes.ResourceFlushRange(&record, bytes);
|
||||
}
|
||||
inline void MGPipeRouteResourceReadback(const MGPReadback& record) {
|
||||
MGPReplySlot reply = MGPipeMintReplySlot();
|
||||
MGP_ResourceReadback(&record, &reply);
|
||||
// The answer is COMPLETION, not a value: the bytes come back through SEG_EVENT's
|
||||
// OnBufferWriteback (table 1 row 22). It is still TAKEN, because an untaken mailbox
|
||||
// entry is what the next row's ReplyOverrun Fatal is looking for.
|
||||
(void)MGPipeTakeReplyBool(reply, "resource_readback");
|
||||
}
|
||||
|
||||
// ---- render state ------------------------------------------------------------------
|
||||
inline void MGPipeRouteCreateRenderState(const MGPRenderStateDesc& desc,
|
||||
const void* chunkBytes) {
|
||||
MGP_CreateRenderState(&desc, chunkBytes, desc.Blob.Size);
|
||||
}
|
||||
inline void MGPipeRouteBindRenderState(const MGPBindRenderState& bind) {
|
||||
MGP_BindRenderState(&bind);
|
||||
}
|
||||
inline void MGPipeRouteDeleteRenderState(const MGPHandleOnly& handle) {
|
||||
MGP_DeleteRenderState(&handle);
|
||||
}
|
||||
inline void MGPipeRouteSetDynamicState(const MGPDynamicState& dyn, const void* chunkBytes) {
|
||||
MGP_SetDynamicState(&dyn, chunkBytes, dyn.Blob.Size);
|
||||
}
|
||||
inline void MGPipeRouteSetPixelPackState(const MGPPixelPackState& pack) {
|
||||
MGP_SetPixelPackState(&pack);
|
||||
}
|
||||
inline void MGPipeRouteSetPatchState(const MGPPatchState& patch) { MGP_SetPatchState(&patch); }
|
||||
inline void MGPipeRouteSetVertexAttribDefaults(const MGPVertexAttribDefaults& hdr,
|
||||
const MGPAttribValue* tail) {
|
||||
MGP_SetVertexAttribDefaults(&hdr, tail, hdr.Count);
|
||||
}
|
||||
// The block IS the blob (table 1 row 6) and its size is a header constant both sides
|
||||
// read, so no call site has to know it.
|
||||
inline void MGPipeRouteSetResidualValueState(const ResidualValueBlock& block) {
|
||||
MGPResidualValueState record{};
|
||||
record.Version = 0;
|
||||
MGP_SetResidualValueState(&record, &block, sizeof(ResidualValueBlock));
|
||||
}
|
||||
|
||||
// ---- vertex input ------------------------------------------------------------------
|
||||
inline void MGPipeRouteCreateVertexElements(const MGPVertexElements& desc,
|
||||
const void* blobBytes) {
|
||||
MGP_CreateVertexElements(&desc, blobBytes, desc.Blob.Size);
|
||||
}
|
||||
inline void MGPipeRouteBindVertexElements(const MGPHandleOnly& handle) {
|
||||
MGP_BindVertexElements(&handle);
|
||||
}
|
||||
inline void MGPipeRouteDeleteVertexElements(const MGPHandleOnly& handle) {
|
||||
MGP_DeleteVertexElements(&handle);
|
||||
}
|
||||
inline void MGPipeRouteSetVertexBuffers(const MGPVertexBuffers& hdr,
|
||||
const MGPVertexBuffer* tail) {
|
||||
MGP_SetVertexBuffers(&hdr, tail, hdr.Count);
|
||||
}
|
||||
inline void MGPipeRouteSetIndexBuffer(const MGPIndexBuffer& record) {
|
||||
MGP_SetIndexBuffer(&record);
|
||||
}
|
||||
|
||||
// ---- framebuffer, samplers, images -------------------------------------------------
|
||||
inline void MGPipeRouteSetFramebufferState(const MGPFramebufferState& state) {
|
||||
MGP_SetFramebufferState(&state);
|
||||
}
|
||||
// The parameters row declares Size 0 today and table 1 row 17 puts it under rule A, so
|
||||
// the length is stated here once, from the type the applier stores by value.
|
||||
inline void MGPipeRouteCreateSamplerState(const MGPSamplerDesc& desc,
|
||||
const SamplerParameters* parameters) {
|
||||
MGP_CreateSamplerState(&desc, parameters, sizeof(SamplerParameters));
|
||||
}
|
||||
inline void MGPipeRouteDeleteSamplerState(const MGPHandleOnly& handle) {
|
||||
MGP_DeleteSamplerState(&handle);
|
||||
}
|
||||
inline void MGPipeRouteCreateSamplerView(const MGPSamplerView& view) {
|
||||
MGP_CreateSamplerView(&view);
|
||||
}
|
||||
inline void MGPipeRouteDeleteSamplerView(const MGPHandleOnly& handle) {
|
||||
MGP_DeleteSamplerView(&handle);
|
||||
}
|
||||
inline Bool MGPipeRouteSetTextureParams(const MGPTextureParams& params) {
|
||||
MGPReplySlot reply = MGPipeMintReplySlot();
|
||||
MGP_SetTextureParams(¶ms, &reply);
|
||||
return MGPipeTakeReplyBool(reply, "set_texture_params");
|
||||
}
|
||||
inline void MGPipeRouteSetSamplerViews(const MGPSamplerViews& hdr, const MGPBoundView* tail) {
|
||||
MGP_SetSamplerViews(&hdr, tail, hdr.Count);
|
||||
}
|
||||
inline void MGPipeRouteBindSamplerStates(const MGPSamplerStates& hdr, const MGPipeHandle* tail) {
|
||||
MGP_BindSamplerStates(&hdr, tail, hdr.Count);
|
||||
}
|
||||
inline void MGPipeRouteSetShaderImages(const MGPShaderImages& hdr, const MGPImageView* tail) {
|
||||
MGP_SetShaderImages(&hdr, tail, hdr.Count);
|
||||
}
|
||||
|
||||
// ---- programs ----------------------------------------------------------------------
|
||||
inline void MGPipeRouteCreateShaderState(const MGPProgramDesc& desc,
|
||||
const MG_State::GLState::LinkArtifacts* link,
|
||||
const MG_State::GLState::SpirvArtifacts* spirv) {
|
||||
gMGPipeRouteEscapes.CreateShaderState(&desc, link, spirv);
|
||||
}
|
||||
inline void MGPipeRouteBindShaderState(const MGPHandleOnly& handle) {
|
||||
MGP_BindShaderState(&handle);
|
||||
}
|
||||
inline void MGPipeRouteDeleteShaderState(const MGPHandleOnly& handle) {
|
||||
MGP_DeleteShaderState(&handle);
|
||||
}
|
||||
inline void MGPipeRouteSetDrawProgram(const MGPHandleOnly& handle) {
|
||||
MGP_SetDrawProgram(&handle);
|
||||
}
|
||||
inline void MGPipeRouteSetDispatchProgram(const MGPHandleOnly& handle) {
|
||||
MGP_SetDispatchProgram(&handle);
|
||||
}
|
||||
inline void MGPipeRouteSetGlobalConstants(const MGPGlobalConstants& record, const void* bytes,
|
||||
Uint64 byteCount) {
|
||||
MGP_SetGlobalConstants(&record, bytes, byteCount);
|
||||
}
|
||||
|
||||
} // namespace MobileGL::MG_Pipe
|
||||
|
||||
#endif // MOBILEGL_PIPE_PUSH
|
||||
@@ -0,0 +1,303 @@
|
||||
// MobileGL - MobileGL/MG_Pipe/generated/PipeFieldOwnership.inc
|
||||
// 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
|
||||
|
||||
// TABLE 2: PipeInputs field ownership (CONTRACT-P5.md section 3, R-7).
|
||||
//
|
||||
// GENERATED by scripts/gen_pipe_field_ownership.py from Coverage.def, FieldOwnership.def and
|
||||
// MG_Impl/Pipe/PipeFill.cpp - DO NOT EDIT. Regenerate with
|
||||
// `python3 scripts/gen_pipe_field_ownership.py`; CI runs it and diffs the result.
|
||||
//
|
||||
// Included from MG_Backend/MGPipe/PipeInputs.h inside namespace MobileGL::MG_Pipe, which is
|
||||
// the one header that both the poison check and the server's verb stamp already see. It is
|
||||
// NOT included from MG_Pipe/MGPipe.h with the other seven generated files, on purpose: that
|
||||
// header is in the PULL build's include closure and G1 admits no symbol motion there.
|
||||
|
||||
|
||||
// The four classes. kUnclassified exists so the static_assert below has something to refuse;
|
||||
// the generator never emits it, which is what makes "a field in no class fails the build"
|
||||
// true at two independent points rather than one.
|
||||
enum class MGPipeFieldOwnership : Uint8 {
|
||||
kUnclassified = 0,
|
||||
kRecordSupplied, // a pushed record supplies the WHOLE field
|
||||
kApplierDerived, // the applier writes it out of records it already applies
|
||||
kBarrierPulled, // P5's debt: read out of the client's residual fill under the verb barrier
|
||||
kFatal, // no carrier and the reduced path never reads it
|
||||
};
|
||||
|
||||
inline constexpr const char* kMGPipeFieldOwnershipNames[] = {
|
||||
"UNCLASSIFIED", "RECORD-SUPPLIED", "APPLIER-DERIVED", "BARRIER-PULLED", "FATAL",
|
||||
};
|
||||
|
||||
inline constexpr MGPipeFieldOwnership kMGPipeFieldOwnership[kMGPipeInputFieldCount] = {
|
||||
MGPipeFieldOwnership::kBarrierPulled, // GetActiveTextureUnit
|
||||
MGPipeFieldOwnership::kRecordSupplied, // GetBlendColor
|
||||
MGPipeFieldOwnership::kRecordSupplied, // GetBlendEquationIndexed
|
||||
MGPipeFieldOwnership::kRecordSupplied, // GetBlendFuncIndexed
|
||||
MGPipeFieldOwnership::kFatal, // GetBoundTransformFeedbackName
|
||||
MGPipeFieldOwnership::kBarrierPulled, // GetBoundVertexArray
|
||||
MGPipeFieldOwnership::kBarrierPulled, // GetBufferBindingSlot
|
||||
MGPipeFieldOwnership::kBarrierPulled, // GetBufferBindingPoint
|
||||
MGPipeFieldOwnership::kBarrierPulled, // GetBufferBindingPointCount
|
||||
MGPipeFieldOwnership::kBarrierPulled, // GetTouchedBufferBindingPointCount
|
||||
MGPipeFieldOwnership::kRecordSupplied, // GetClampReadColor
|
||||
MGPipeFieldOwnership::kRecordSupplied, // GetClearColor
|
||||
MGPipeFieldOwnership::kRecordSupplied, // GetClearDepth
|
||||
MGPipeFieldOwnership::kRecordSupplied, // GetClearStencil
|
||||
MGPipeFieldOwnership::kRecordSupplied, // GetColorMaskIndexed
|
||||
MGPipeFieldOwnership::kRecordSupplied, // GetCullFaceMode
|
||||
MGPipeFieldOwnership::kBarrierPulled, // GetCurrentVertexAttribute
|
||||
MGPipeFieldOwnership::kRecordSupplied, // GetDepthFunc
|
||||
MGPipeFieldOwnership::kRecordSupplied, // GetDepthMask
|
||||
MGPipeFieldOwnership::kRecordSupplied, // GetDepthRangeIndexed
|
||||
MGPipeFieldOwnership::kBarrierPulled, // GetFramebufferBindingSlot
|
||||
MGPipeFieldOwnership::kBarrierPulled, // GetImageTextureBinding
|
||||
MGPipeFieldOwnership::kRecordSupplied, // GetLineWidth
|
||||
MGPipeFieldOwnership::kRecordSupplied, // GetLogicOp
|
||||
MGPipeFieldOwnership::kBarrierPulled, // GetMaxTouchedTextureUnit
|
||||
MGPipeFieldOwnership::kRecordSupplied, // GetMinSampleShadingValue
|
||||
MGPipeFieldOwnership::kRecordSupplied, // GetPatchDefaultInnerLevel
|
||||
MGPipeFieldOwnership::kRecordSupplied, // GetPatchDefaultOuterLevel
|
||||
MGPipeFieldOwnership::kRecordSupplied, // GetPatchVertices
|
||||
MGPipeFieldOwnership::kRecordSupplied, // GetPipelineStateVersion
|
||||
MGPipeFieldOwnership::kApplierDerived, // GetPixelStoreParameters
|
||||
MGPipeFieldOwnership::kRecordSupplied, // GetPolygonModeFront
|
||||
MGPipeFieldOwnership::kRecordSupplied, // GetPolygonOffsetFactor
|
||||
MGPipeFieldOwnership::kRecordSupplied, // GetPolygonOffsetUnits
|
||||
MGPipeFieldOwnership::kRecordSupplied, // GetPrimitiveRestartIndex
|
||||
MGPipeFieldOwnership::kFatal, // GetProgramForDispatch
|
||||
MGPipeFieldOwnership::kBarrierPulled, // GetProgramForDraw
|
||||
MGPipeFieldOwnership::kBarrierPulled, // GetProgramObject
|
||||
MGPipeFieldOwnership::kRecordSupplied, // GetProvokingVertexMode
|
||||
MGPipeFieldOwnership::kRecordSupplied, // GetRenderStateParameters
|
||||
MGPipeFieldOwnership::kRecordSupplied, // GetRenderStateParametersVersion
|
||||
MGPipeFieldOwnership::kBarrierPulled, // GetSamplingResolutionGeneration
|
||||
MGPipeFieldOwnership::kRecordSupplied, // GetScissorBox
|
||||
MGPipeFieldOwnership::kRecordSupplied, // GetStencilState
|
||||
MGPipeFieldOwnership::kBarrierPulled, // GetTextureBindGeneration
|
||||
MGPipeFieldOwnership::kBarrierPulled, // GetTextureContextId
|
||||
MGPipeFieldOwnership::kBarrierPulled, // GetTextureObject
|
||||
MGPipeFieldOwnership::kBarrierPulled, // GetTextureUnitObject
|
||||
MGPipeFieldOwnership::kBarrierPulled, // GetTransformFeedbackCapturedVertices
|
||||
MGPipeFieldOwnership::kBarrierPulled, // GetTransformFeedbackGeneration
|
||||
MGPipeFieldOwnership::kFatal, // GetTransformFeedbackPausedPrimitiveCounter
|
||||
MGPipeFieldOwnership::kBarrierPulled, // GetTransformFeedbackProgram
|
||||
MGPipeFieldOwnership::kRecordSupplied, // GetViewport
|
||||
MGPipeFieldOwnership::kRecordSupplied, // GetViewportIndexed
|
||||
MGPipeFieldOwnership::kRecordSupplied, // IsCapabilityEnabled
|
||||
MGPipeFieldOwnership::kRecordSupplied, // IsCapabilityEnabledIndexed
|
||||
MGPipeFieldOwnership::kBarrierPulled, // IsTransformFeedbackActive
|
||||
MGPipeFieldOwnership::kBarrierPulled, // IsTransformFeedbackPaused
|
||||
MGPipeFieldOwnership::kBarrierPulled, // InvalidateCompileEnv
|
||||
MGPipeFieldOwnership::kBarrierPulled, // ValidateProgramName
|
||||
MGPipeFieldOwnership::kBarrierPulled, // RecordError
|
||||
MGPipeFieldOwnership::kBarrierPulled, // GetBoundTransformFeedbackLifetimeId
|
||||
MGPipeFieldOwnership::kBarrierPulled, // HasOpenTransformFeedbackSpan
|
||||
};
|
||||
|
||||
// The ROADMAP phase whose row retires the pull. "-" for every class but BARRIER-PULLED.
|
||||
inline constexpr const char* kMGPipeFieldRetiringPhase[kMGPipeInputFieldCount] = {
|
||||
"P3b/P4b", // GetActiveTextureUnit
|
||||
"-", // GetBlendColor
|
||||
"-", // GetBlendEquationIndexed
|
||||
"-", // GetBlendFuncIndexed
|
||||
"-", // GetBoundTransformFeedbackName
|
||||
"P8", // GetBoundVertexArray
|
||||
"P8 (indirect), P9 (readback), P13 (transfer)", // GetBufferBindingSlot
|
||||
"P3b/P4b, P7", // GetBufferBindingPoint
|
||||
"P7/P13", // GetBufferBindingPointCount
|
||||
"P3b/P4b", // GetTouchedBufferBindingPointCount
|
||||
"-", // GetClampReadColor
|
||||
"-", // GetClearColor
|
||||
"-", // GetClearDepth
|
||||
"-", // GetClearStencil
|
||||
"-", // GetColorMaskIndexed
|
||||
"-", // GetCullFaceMode
|
||||
"P3b/P4b", // GetCurrentVertexAttribute
|
||||
"-", // GetDepthFunc
|
||||
"-", // GetDepthMask
|
||||
"-", // GetDepthRangeIndexed
|
||||
"P3b/P4b (Espryt), P7 (Magma)", // GetFramebufferBindingSlot
|
||||
"P3b/P4b, P7", // GetImageTextureBinding
|
||||
"-", // GetLineWidth
|
||||
"-", // GetLogicOp
|
||||
"P3b/P4b", // GetMaxTouchedTextureUnit
|
||||
"-", // GetMinSampleShadingValue
|
||||
"-", // GetPatchDefaultInnerLevel
|
||||
"-", // GetPatchDefaultOuterLevel
|
||||
"-", // GetPatchVertices
|
||||
"-", // GetPipelineStateVersion
|
||||
"-", // GetPixelStoreParameters
|
||||
"-", // GetPolygonModeFront
|
||||
"-", // GetPolygonOffsetFactor
|
||||
"-", // GetPolygonOffsetUnits
|
||||
"-", // GetPrimitiveRestartIndex
|
||||
"-", // GetProgramForDispatch
|
||||
"P8 (Espryt), P7 (Magma)", // GetProgramForDraw
|
||||
"P9", // GetProgramObject
|
||||
"-", // GetProvokingVertexMode
|
||||
"-", // GetRenderStateParameters
|
||||
"-", // GetRenderStateParametersVersion
|
||||
"P3b/P4b", // GetSamplingResolutionGeneration
|
||||
"-", // GetScissorBox
|
||||
"-", // GetStencilState
|
||||
"P3b/P4b", // GetTextureBindGeneration
|
||||
"P3b/P4b", // GetTextureContextId
|
||||
"P7", // GetTextureObject
|
||||
"P3b/P4b, P7", // GetTextureUnitObject
|
||||
"P3b/P4b (Espryt), P7 (Magma)", // GetTransformFeedbackCapturedVertices
|
||||
"P3b/P4b (Espryt), P7 (Magma)", // GetTransformFeedbackGeneration
|
||||
"-", // GetTransformFeedbackPausedPrimitiveCounter
|
||||
"P3b/P4b (Espryt), P7 (Magma)", // GetTransformFeedbackProgram
|
||||
"-", // GetViewport
|
||||
"-", // GetViewportIndexed
|
||||
"-", // IsCapabilityEnabled
|
||||
"-", // IsCapabilityEnabledIndexed
|
||||
"P3b/P4b (Espryt), P7 (Magma)", // IsTransformFeedbackActive
|
||||
"P3b/P4b (Espryt), P7 (Magma)", // IsTransformFeedbackPaused
|
||||
"P5", // InvalidateCompileEnv
|
||||
"P9", // ValidateProgramName
|
||||
"P9", // RecordError
|
||||
"P3b/P4b (Espryt), P7 (Magma)", // GetBoundTransformFeedbackLifetimeId
|
||||
"P7/P9", // HasOpenTransformFeedbackSpan
|
||||
};
|
||||
|
||||
// The seven sticky forwards, which are among the 63 above and need a row of their own:
|
||||
// they are the ones that hand the server a raw frontend object or write into the
|
||||
// frontend, so the exit gate is structurally blind on them without one.
|
||||
inline constexpr SizeT kMGPipeFieldOwnershipForwardCount = 7;
|
||||
static_assert(kMGPipeFieldOwnershipForwardCount == kMGPipeInputStickyFieldCount,
|
||||
"the forward rows and Coverage.def's sticky set are the same seven");
|
||||
inline constexpr MGPipeInputField kMGPipeFieldOwnershipForwardField[kMGPipeFieldOwnershipForwardCount] = {
|
||||
MGPipeInputField::GetBufferBindingPointCount,
|
||||
MGPipeInputField::GetProgramObject,
|
||||
MGPipeInputField::GetTextureObject,
|
||||
MGPipeInputField::HasOpenTransformFeedbackSpan,
|
||||
MGPipeInputField::ValidateProgramName,
|
||||
MGPipeInputField::InvalidateCompileEnv,
|
||||
MGPipeInputField::RecordError,
|
||||
};
|
||||
inline constexpr MGPipeFieldOwnership kMGPipeFieldOwnershipForward[kMGPipeFieldOwnershipForwardCount] = {
|
||||
MGPipeFieldOwnership::kBarrierPulled, // GetBufferBindingPointCount
|
||||
MGPipeFieldOwnership::kBarrierPulled, // GetProgramObject
|
||||
MGPipeFieldOwnership::kBarrierPulled, // GetTextureObject
|
||||
MGPipeFieldOwnership::kBarrierPulled, // HasOpenTransformFeedbackSpan
|
||||
MGPipeFieldOwnership::kBarrierPulled, // ValidateProgramName
|
||||
MGPipeFieldOwnership::kBarrierPulled, // InvalidateCompileEnv
|
||||
MGPipeFieldOwnership::kBarrierPulled, // RecordError
|
||||
};
|
||||
inline constexpr const char* kMGPipeFieldOwnershipForwardMechanism[kMGPipeFieldOwnershipForwardCount] = {
|
||||
"a server-side binding-point table", // GetBufferBindingPointCount, retires in P7/P13
|
||||
"a client-resolved program handle table (ARCHITECTURE 3.2 explicitly-not-ported)", // GetProgramObject, retires in P9
|
||||
"a server-side texture handle table", // GetTextureObject, retires in P7
|
||||
"server-side XFB span state", // HasOpenTransformFeedbackSpan, retires in P7/P9
|
||||
"a client-resolved program name probe", // ValidateProgramName, retires in P9
|
||||
"OnCapsInvalidated - the re-arriving caps snapshot IS the invalidation (R-12)", // InvalidateCompileEnv, retires in P5
|
||||
"OnGlError, the ordered reverse-channel error post (R-12); its ordering is P9's", // RecordError, retires in P9
|
||||
};
|
||||
|
||||
// CONTRACT-P5.md section 3: "70 rows, each in exactly one class".
|
||||
inline constexpr SizeT kMGPipeFieldOwnershipRowCount =
|
||||
kMGPipeInputFieldCount + kMGPipeFieldOwnershipForwardCount;
|
||||
static_assert(kMGPipeFieldOwnershipRowCount == 70, "table 2's row count moved");
|
||||
|
||||
// An ARGUMENT-KEYED narrowing of one field. The field keeps its single row above; this
|
||||
// says that one argument value of it belongs to a different class. Coverage.def:62-69 already
|
||||
// rules the shape for GetBufferBindingSlot - "THE ROW STAYS ONE ROW ... the field is ONE array
|
||||
// that a second row of the same name could only duplicate" - and m_pixelStore[2] is the same
|
||||
// shape indexed by its own isUnpack argument.
|
||||
struct MGPipeFieldArgumentOwnership {
|
||||
MGPipeInputField Field;
|
||||
Uint32 Arg0;
|
||||
MGPipeFieldOwnership Class;
|
||||
};
|
||||
inline constexpr SizeT kMGPipeFieldArgumentOwnershipCount = 1;
|
||||
inline constexpr MGPipeFieldArgumentOwnership
|
||||
kMGPipeFieldArgumentOwnership[kMGPipeFieldArgumentOwnershipCount] = {
|
||||
{MGPipeInputField::GetPixelStoreParameters, 1u, MGPipeFieldOwnership::kFatal}, // the unpack half has no carrier AND no backend reader; all six MGB_CTX sites pass false
|
||||
};
|
||||
|
||||
constexpr MGPipeFieldOwnership MGPipeFieldOwnershipOf(MGPipeInputField field) {
|
||||
return kMGPipeFieldOwnership[static_cast<SizeT>(field)];
|
||||
}
|
||||
|
||||
// The same answer, narrowed by the accessor's first argument. Every accessor that takes one
|
||||
// may call this; only the fields with a row above answer differently from the field's class.
|
||||
constexpr MGPipeFieldOwnership MGPipeFieldOwnershipOf(MGPipeInputField field, Uint32 arg0) {
|
||||
for (SizeT i = 0; i < kMGPipeFieldArgumentOwnershipCount; ++i) {
|
||||
if (kMGPipeFieldArgumentOwnership[i].Field == field &&
|
||||
kMGPipeFieldArgumentOwnership[i].Arg0 == arg0) {
|
||||
return kMGPipeFieldArgumentOwnership[i].Class;
|
||||
}
|
||||
}
|
||||
return MGPipeFieldOwnershipOf(field);
|
||||
}
|
||||
|
||||
constexpr const char* MGPipeFieldOwnershipName(MGPipeFieldOwnership ownership) {
|
||||
return kMGPipeFieldOwnershipNames[static_cast<SizeT>(ownership)];
|
||||
}
|
||||
|
||||
// THE BUILD FAILURE R-7.1 ASKS FOR. The generator refuses to emit an unclassified row, so
|
||||
// this can only fire on a hand-edited header - which is exactly the edit the DO NOT EDIT
|
||||
// banner cannot prevent on its own.
|
||||
constexpr Bool MGPipeEveryFieldIsClassified() {
|
||||
for (SizeT i = 0; i < kMGPipeInputFieldCount; ++i) {
|
||||
if (kMGPipeFieldOwnership[i] == MGPipeFieldOwnership::kUnclassified) return false;
|
||||
}
|
||||
for (SizeT i = 0; i < kMGPipeFieldOwnershipForwardCount; ++i) {
|
||||
if (kMGPipeFieldOwnershipForward[i] == MGPipeFieldOwnership::kUnclassified) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
static_assert(MGPipeEveryFieldIsClassified(),
|
||||
"a PipeInputs field is in none of the four ownership classes (CONTRACT-P5 table 2, R-7.1)");
|
||||
|
||||
// WHERE THE SERVER STAMPS. The wire's op and the fill's verb are different name spaces
|
||||
// and do not line up by name (draw_vbo is DrawArrays, blit is BlitFramebuffer), so this is the
|
||||
// join. An op with no row is NOT a verb boundary and the applier must not stamp on it.
|
||||
//
|
||||
// EVERY VERB-SHAPED CALL IS ANSWERED HERE OR EXEMPTED BY NAME, and the generator refuses an
|
||||
// omission: a verb-shaped record with no row would apply under the PREVIOUS verb's serial,
|
||||
// mask and name, so a field inside that mask would read FRESH while holding the previous
|
||||
// verb's value - the one silent failure this table has. The exemptions:
|
||||
// Flush not a verb at all: the verb census (BRIEF §12 C-3) found Flush is not a GLFunctionsTable
|
||||
// Present FillPoints.def:21 - Present and SetSwapInterval go through BackendObject virtuals and
|
||||
// SetSwapInterval the same sentence of FillPoints.def:21, and it is class C besides
|
||||
constexpr MGPipeVerb MGPipeVerbForWireOp(MGPWireOp op) {
|
||||
switch (op) {
|
||||
case MGPWireOp::Clear: return MGPipeVerb::Clear;
|
||||
case MGPWireOp::DrawVbo: return MGPipeVerb::DrawArrays;
|
||||
case MGPWireOp::ReadPixels: return MGPipeVerb::ReadPixels;
|
||||
case MGPWireOp::Blit: return MGPipeVerb::BlitFramebuffer;
|
||||
case MGPWireOp::LaunchGrid: return MGPipeVerb::DispatchCompute;
|
||||
case MGPWireOp::MemoryBarrier: return MGPipeVerb::MemoryBarrier;
|
||||
case MGPWireOp::BeginStreamOutput: return MGPipeVerb::BeginTransformFeedback;
|
||||
case MGPWireOp::EndStreamOutput: return MGPipeVerb::EndTransformFeedback;
|
||||
case MGPWireOp::PauseStreamOutput: return MGPipeVerb::PauseTransformFeedback;
|
||||
case MGPWireOp::ResumeStreamOutput: return MGPipeVerb::ResumeTransformFeedback;
|
||||
case MGPWireOp::GenerateMipmap: return MGPipeVerb::GenerateMipmap;
|
||||
case MGPWireOp::GetTextureImage: return MGPipeVerb::GetTextureImage;
|
||||
case MGPWireOp::ResourceCopyRegion: return MGPipeVerb::CopyImageSubData;
|
||||
case MGPWireOp::BindShaderImage: return MGPipeVerb::BindImageTexture;
|
||||
case MGPWireOp::PatchParameter: return MGPipeVerb::PatchParameteri;
|
||||
case MGPWireOp::BindStreamOutput: return MGPipeVerb::BindTransformFeedback;
|
||||
case MGPWireOp::SetStorageBlockBinding: return MGPipeVerb::ShaderStorageBlockBinding;
|
||||
case MGPWireOp::CopyFramebufferToTexture: return MGPipeVerb::CopyTexImage2D;
|
||||
default:
|
||||
return MGPipeVerb::kVerbCount;
|
||||
}
|
||||
}
|
||||
|
||||
inline constexpr SizeT kMGPipeVerbBoundaryOpCount = 18;
|
||||
inline constexpr SizeT kMGPipeVerbBoundaryExemptCount = 3;
|
||||
|
||||
// The class sizes, as constants a test can pin without recounting the table.
|
||||
inline constexpr SizeT kMGPipeRecordSuppliedFieldCount = 32;
|
||||
inline constexpr SizeT kMGPipeApplierDerivedFieldCount = 1;
|
||||
inline constexpr SizeT kMGPipeBarrierPulledFieldCount = 27;
|
||||
inline constexpr SizeT kMGPipeFatalFieldCount = 3;
|
||||
static_assert(kMGPipeRecordSuppliedFieldCount + kMGPipeApplierDerivedFieldCount + kMGPipeBarrierPulledFieldCount + kMGPipeFatalFieldCount == kMGPipeInputFieldCount, "the four class sizes do not partition the field set");
|
||||
@@ -15,9 +15,9 @@
|
||||
// share group: 11 calls. A null entry means the backend does not implement this
|
||||
// call and the frontend keeps its own path (plan B section 4.1).
|
||||
struct MGPipeScreen {
|
||||
void (*GetCaps)(const MGPCaps* payload, MGPReplySlot* reply);
|
||||
void (*ResourceCreate)(const MGPResourceDesc* payload);
|
||||
void (*ResourceRespecify)(const MGPResourceDesc* payload);
|
||||
void (*GetCaps)(const MGPCaps* payload, const void* blobBytes, Uint64 blobByteCount, MGPReplySlot* reply);
|
||||
void (*ResourceCreate)(const MGPResourceDesc* payload, MGPReplySlot* reply);
|
||||
void (*ResourceRespecify)(const MGPResourceDesc* payload, MGPReplySlot* reply);
|
||||
void (*ResourceDestroy)(const MGPHandleOnly* payload);
|
||||
void (*MapPersistent)(const MGPHandleOnly* payload, MGPReplySlot* reply);
|
||||
void (*UnmapPersistent)(const MGPHandleOnly* payload);
|
||||
@@ -28,7 +28,7 @@ struct MGPipeScreen {
|
||||
void (*FenceWaitServer)(const MGPFenceWait* payload);
|
||||
};
|
||||
|
||||
// context: 60 calls. A null entry means the backend does not implement this
|
||||
// context: 65 calls. A null entry means the backend does not implement this
|
||||
// call and the frontend keeps its own path (plan B section 4.1).
|
||||
struct MGPipeContext {
|
||||
void (*QueryCreate)(const MGPQueryDesc* payload);
|
||||
@@ -37,20 +37,20 @@ struct MGPipeContext {
|
||||
void (*QueryAvailable)(const MGPHandleOnly* payload, MGPReplySlot* reply);
|
||||
void (*QueryResult)(const MGPQueryResultRequest* payload, MGPReplySlot* reply);
|
||||
void (*QueryDestroy)(const MGPHandleOnly* payload);
|
||||
void (*CreateRenderState)(const MGPRenderStateDesc* payload);
|
||||
void (*CreateRenderState)(const MGPRenderStateDesc* payload, const void* blobBytes, Uint64 blobByteCount);
|
||||
void (*BindRenderState)(const MGPBindRenderState* payload);
|
||||
void (*DeleteRenderState)(const MGPHandleOnly* payload);
|
||||
void (*CreateVertexElements)(const MGPVertexElements* payload);
|
||||
void (*CreateVertexElements)(const MGPVertexElements* payload, const void* blobBytes, Uint64 blobByteCount);
|
||||
void (*BindVertexElements)(const MGPHandleOnly* payload);
|
||||
void (*DeleteVertexElements)(const MGPHandleOnly* payload);
|
||||
void (*CreateSamplerState)(const MGPSamplerDesc* payload);
|
||||
void (*CreateSamplerState)(const MGPSamplerDesc* payload, const void* blobBytes, Uint64 blobByteCount);
|
||||
void (*DeleteSamplerState)(const MGPHandleOnly* payload);
|
||||
void (*CreateSamplerView)(const MGPSamplerView* payload);
|
||||
void (*DeleteSamplerView)(const MGPHandleOnly* payload);
|
||||
void (*CreateShaderState)(const MGPProgramDesc* payload);
|
||||
void (*CreateShaderState)(const MGPProgramDesc* payload, const void* blobBytes, Uint64 blobByteCount);
|
||||
void (*BindShaderState)(const MGPHandleOnly* payload);
|
||||
void (*DeleteShaderState)(const MGPHandleOnly* payload);
|
||||
void (*SetDynamicState)(const MGPDynamicState* payload);
|
||||
void (*SetDynamicState)(const MGPDynamicState* payload, const void* blobBytes, Uint64 blobByteCount);
|
||||
void (*SetFramebufferState)(const MGPFramebufferState* payload);
|
||||
void (*SetVertexBuffers)(const MGPVertexBuffers* payload, const void* varTail, Uint32 varTailCount);
|
||||
void (*SetIndexBuffer)(const MGPIndexBuffer* payload);
|
||||
@@ -60,16 +60,16 @@ struct MGPipeContext {
|
||||
void (*SetShaderImages)(const MGPShaderImages* payload, const void* varTail, Uint32 varTailCount);
|
||||
void (*SetShaderBuffers)(const MGPShaderBuffers* payload, const void* varTail, Uint32 varTailCount);
|
||||
void (*SetStreamOutputTargets)(const MGPStreamOutputTargets* payload, const void* varTail, Uint32 varTailCount);
|
||||
void (*SetGlobalConstants)(const MGPGlobalConstants* payload);
|
||||
void (*SetGlobalConstants)(const MGPGlobalConstants* payload, const void* blobBytes, Uint64 blobByteCount);
|
||||
void (*SetVertexAttribDefaults)(const MGPVertexAttribDefaults* payload, const void* varTail, Uint32 varTailCount);
|
||||
void (*SetPixelPackState)(const MGPPixelPackState* payload);
|
||||
void (*SetPatchState)(const MGPPatchState* payload);
|
||||
void (*SetDrawProgram)(const MGPHandleOnly* payload);
|
||||
void (*SetDispatchProgram)(const MGPHandleOnly* payload);
|
||||
void (*SetResidualValueState)(const MGPResidualValueState* payload);
|
||||
void (*SetTextureParams)(const MGPTextureParams* payload);
|
||||
void (*ResourceSubData)(const MGPSubData* payload, const void* varTail, Uint32 varTailCount);
|
||||
void (*BufferSubDataResident)(const MGPSubData* payload);
|
||||
void (*SetResidualValueState)(const MGPResidualValueState* payload, const void* blobBytes, Uint64 blobByteCount);
|
||||
void (*SetTextureParams)(const MGPTextureParams* payload, MGPReplySlot* reply);
|
||||
void (*ResourceSubData)(const MGPSubData* payload, const void* blobBytes, Uint64 blobByteCount, const void* varTail, Uint32 varTailCount, MGPReplySlot* reply);
|
||||
void (*BufferSubDataResident)(const MGPSubData* payload, const void* blobBytes, Uint64 blobByteCount);
|
||||
void (*ResourceSubDataComplete)(const MGPSubDataComplete* payload);
|
||||
void (*ResourceFlushRange)(const MGPFlushRange* payload);
|
||||
void (*ResourceReadback)(const MGPReadback* payload, MGPReplySlot* reply);
|
||||
@@ -91,11 +91,16 @@ struct MGPipeContext {
|
||||
void (*SetSwapInterval)(const MGPSwapInterval* payload);
|
||||
void (*QueryTimestamp)(const MGPTimestampRequest* payload, MGPReplySlot* reply);
|
||||
void (*QueryCounter)(const MGPQueryDesc* payload);
|
||||
void (*BindShaderImage)(const MGPImageBind* payload);
|
||||
void (*PatchParameter)(const MGPPatchParameter* payload);
|
||||
void (*BindStreamOutput)(const MGPStreamOutputBind* payload);
|
||||
void (*SetStorageBlockBinding)(const MGPStorageBlockBinding* payload, const void* blobBytes, Uint64 blobByteCount);
|
||||
void (*CopyFramebufferToTexture)(const MGPCopyFromFramebuffer* payload);
|
||||
};
|
||||
|
||||
inline constexpr SizeT kMGPipeScreenCallCount = 11;
|
||||
inline constexpr SizeT kMGPipeContextCallCount = 60;
|
||||
inline constexpr SizeT kMGPipeCallCount = 71;
|
||||
inline constexpr SizeT kMGPipeContextCallCount = 65;
|
||||
inline constexpr SizeT kMGPipeCallCount = 76;
|
||||
|
||||
// A table that is not exactly its call count of function pointers has grown a
|
||||
// member that no generator knows about.
|
||||
|
||||
@@ -17,16 +17,16 @@
|
||||
// unimplemented (null) entry is the caller's business to check, exactly as it is
|
||||
// with the table this replaces.
|
||||
|
||||
inline void MGP_GetCaps(const MGPCaps* payload, MGPReplySlot* reply) {
|
||||
gMGPipeScreen.GetCaps(payload, reply);
|
||||
inline void MGP_GetCaps(const MGPCaps* payload, const void* blobBytes, Uint64 blobByteCount, MGPReplySlot* reply) {
|
||||
gMGPipeScreen.GetCaps(payload, blobBytes, blobByteCount, reply);
|
||||
}
|
||||
|
||||
inline void MGP_ResourceCreate(const MGPResourceDesc* payload) {
|
||||
gMGPipeScreen.ResourceCreate(payload);
|
||||
inline void MGP_ResourceCreate(const MGPResourceDesc* payload, MGPReplySlot* reply) {
|
||||
gMGPipeScreen.ResourceCreate(payload, reply);
|
||||
}
|
||||
|
||||
inline void MGP_ResourceRespecify(const MGPResourceDesc* payload) {
|
||||
gMGPipeScreen.ResourceRespecify(payload);
|
||||
inline void MGP_ResourceRespecify(const MGPResourceDesc* payload, MGPReplySlot* reply) {
|
||||
gMGPipeScreen.ResourceRespecify(payload, reply);
|
||||
}
|
||||
|
||||
inline void MGP_ResourceDestroy(const MGPHandleOnly* payload) {
|
||||
@@ -81,8 +81,8 @@ inline void MGP_QueryDestroy(const MGPHandleOnly* payload) {
|
||||
gMGPipeContext.QueryDestroy(payload);
|
||||
}
|
||||
|
||||
inline void MGP_CreateRenderState(const MGPRenderStateDesc* payload) {
|
||||
gMGPipeContext.CreateRenderState(payload);
|
||||
inline void MGP_CreateRenderState(const MGPRenderStateDesc* payload, const void* blobBytes, Uint64 blobByteCount) {
|
||||
gMGPipeContext.CreateRenderState(payload, blobBytes, blobByteCount);
|
||||
}
|
||||
|
||||
inline void MGP_BindRenderState(const MGPBindRenderState* payload) {
|
||||
@@ -93,8 +93,8 @@ inline void MGP_DeleteRenderState(const MGPHandleOnly* payload) {
|
||||
gMGPipeContext.DeleteRenderState(payload);
|
||||
}
|
||||
|
||||
inline void MGP_CreateVertexElements(const MGPVertexElements* payload) {
|
||||
gMGPipeContext.CreateVertexElements(payload);
|
||||
inline void MGP_CreateVertexElements(const MGPVertexElements* payload, const void* blobBytes, Uint64 blobByteCount) {
|
||||
gMGPipeContext.CreateVertexElements(payload, blobBytes, blobByteCount);
|
||||
}
|
||||
|
||||
inline void MGP_BindVertexElements(const MGPHandleOnly* payload) {
|
||||
@@ -105,8 +105,8 @@ inline void MGP_DeleteVertexElements(const MGPHandleOnly* payload) {
|
||||
gMGPipeContext.DeleteVertexElements(payload);
|
||||
}
|
||||
|
||||
inline void MGP_CreateSamplerState(const MGPSamplerDesc* payload) {
|
||||
gMGPipeContext.CreateSamplerState(payload);
|
||||
inline void MGP_CreateSamplerState(const MGPSamplerDesc* payload, const void* blobBytes, Uint64 blobByteCount) {
|
||||
gMGPipeContext.CreateSamplerState(payload, blobBytes, blobByteCount);
|
||||
}
|
||||
|
||||
inline void MGP_DeleteSamplerState(const MGPHandleOnly* payload) {
|
||||
@@ -121,8 +121,8 @@ inline void MGP_DeleteSamplerView(const MGPHandleOnly* payload) {
|
||||
gMGPipeContext.DeleteSamplerView(payload);
|
||||
}
|
||||
|
||||
inline void MGP_CreateShaderState(const MGPProgramDesc* payload) {
|
||||
gMGPipeContext.CreateShaderState(payload);
|
||||
inline void MGP_CreateShaderState(const MGPProgramDesc* payload, const void* blobBytes, Uint64 blobByteCount) {
|
||||
gMGPipeContext.CreateShaderState(payload, blobBytes, blobByteCount);
|
||||
}
|
||||
|
||||
inline void MGP_BindShaderState(const MGPHandleOnly* payload) {
|
||||
@@ -133,8 +133,8 @@ inline void MGP_DeleteShaderState(const MGPHandleOnly* payload) {
|
||||
gMGPipeContext.DeleteShaderState(payload);
|
||||
}
|
||||
|
||||
inline void MGP_SetDynamicState(const MGPDynamicState* payload) {
|
||||
gMGPipeContext.SetDynamicState(payload);
|
||||
inline void MGP_SetDynamicState(const MGPDynamicState* payload, const void* blobBytes, Uint64 blobByteCount) {
|
||||
gMGPipeContext.SetDynamicState(payload, blobBytes, blobByteCount);
|
||||
}
|
||||
|
||||
inline void MGP_SetFramebufferState(const MGPFramebufferState* payload) {
|
||||
@@ -173,8 +173,8 @@ inline void MGP_SetStreamOutputTargets(const MGPStreamOutputTargets* payload, co
|
||||
gMGPipeContext.SetStreamOutputTargets(payload, varTail, varTailCount);
|
||||
}
|
||||
|
||||
inline void MGP_SetGlobalConstants(const MGPGlobalConstants* payload) {
|
||||
gMGPipeContext.SetGlobalConstants(payload);
|
||||
inline void MGP_SetGlobalConstants(const MGPGlobalConstants* payload, const void* blobBytes, Uint64 blobByteCount) {
|
||||
gMGPipeContext.SetGlobalConstants(payload, blobBytes, blobByteCount);
|
||||
}
|
||||
|
||||
inline void MGP_SetVertexAttribDefaults(const MGPVertexAttribDefaults* payload, const void* varTail, Uint32 varTailCount) {
|
||||
@@ -197,20 +197,20 @@ inline void MGP_SetDispatchProgram(const MGPHandleOnly* payload) {
|
||||
gMGPipeContext.SetDispatchProgram(payload);
|
||||
}
|
||||
|
||||
inline void MGP_SetResidualValueState(const MGPResidualValueState* payload) {
|
||||
gMGPipeContext.SetResidualValueState(payload);
|
||||
inline void MGP_SetResidualValueState(const MGPResidualValueState* payload, const void* blobBytes, Uint64 blobByteCount) {
|
||||
gMGPipeContext.SetResidualValueState(payload, blobBytes, blobByteCount);
|
||||
}
|
||||
|
||||
inline void MGP_SetTextureParams(const MGPTextureParams* payload) {
|
||||
gMGPipeContext.SetTextureParams(payload);
|
||||
inline void MGP_SetTextureParams(const MGPTextureParams* payload, MGPReplySlot* reply) {
|
||||
gMGPipeContext.SetTextureParams(payload, reply);
|
||||
}
|
||||
|
||||
inline void MGP_ResourceSubData(const MGPSubData* payload, const void* varTail, Uint32 varTailCount) {
|
||||
gMGPipeContext.ResourceSubData(payload, varTail, varTailCount);
|
||||
inline void MGP_ResourceSubData(const MGPSubData* payload, const void* blobBytes, Uint64 blobByteCount, const void* varTail, Uint32 varTailCount, MGPReplySlot* reply) {
|
||||
gMGPipeContext.ResourceSubData(payload, blobBytes, blobByteCount, varTail, varTailCount, reply);
|
||||
}
|
||||
|
||||
inline void MGP_BufferSubDataResident(const MGPSubData* payload) {
|
||||
gMGPipeContext.BufferSubDataResident(payload);
|
||||
inline void MGP_BufferSubDataResident(const MGPSubData* payload, const void* blobBytes, Uint64 blobByteCount) {
|
||||
gMGPipeContext.BufferSubDataResident(payload, blobBytes, blobByteCount);
|
||||
}
|
||||
|
||||
inline void MGP_ResourceSubDataComplete(const MGPSubDataComplete* payload) {
|
||||
@@ -300,3 +300,23 @@ inline void MGP_QueryCounter(const MGPQueryDesc* payload) {
|
||||
inline void MGP_FenceWaitServer(const MGPFenceWait* payload) {
|
||||
gMGPipeScreen.FenceWaitServer(payload);
|
||||
}
|
||||
|
||||
inline void MGP_BindShaderImage(const MGPImageBind* payload) {
|
||||
gMGPipeContext.BindShaderImage(payload);
|
||||
}
|
||||
|
||||
inline void MGP_PatchParameter(const MGPPatchParameter* payload) {
|
||||
gMGPipeContext.PatchParameter(payload);
|
||||
}
|
||||
|
||||
inline void MGP_BindStreamOutput(const MGPStreamOutputBind* payload) {
|
||||
gMGPipeContext.BindStreamOutput(payload);
|
||||
}
|
||||
|
||||
inline void MGP_SetStorageBlockBinding(const MGPStorageBlockBinding* payload, const void* blobBytes, Uint64 blobByteCount) {
|
||||
gMGPipeContext.SetStorageBlockBinding(payload, blobBytes, blobByteCount);
|
||||
}
|
||||
|
||||
inline void MGP_CopyFramebufferToTexture(const MGPCopyFromFramebuffer* payload) {
|
||||
gMGPipeContext.CopyFramebufferToTexture(payload);
|
||||
}
|
||||
|
||||
@@ -107,6 +107,11 @@ inline Bool MGPipeVerify(const MGPFlush& a, const MGPFlush& b, const char** outF
|
||||
inline Bool MGPipeVerify(const MGPPresent& a, const MGPPresent& b, const char** outField);
|
||||
inline Bool MGPipeVerify(const MGPSwapInterval& a, const MGPSwapInterval& b, const char** outField);
|
||||
inline Bool MGPipeVerify(const MGPSurfaceInfo& a, const MGPSurfaceInfo& b, const char** outField);
|
||||
inline Bool MGPipeVerify(const MGPImageBind& a, const MGPImageBind& b, const char** outField);
|
||||
inline Bool MGPipeVerify(const MGPPatchParameter& a, const MGPPatchParameter& b, const char** outField);
|
||||
inline Bool MGPipeVerify(const MGPStreamOutputBind& a, const MGPStreamOutputBind& b, const char** outField);
|
||||
inline Bool MGPipeVerify(const MGPStorageBlockBinding& a, const MGPStorageBlockBinding& b, const char** outField);
|
||||
inline Bool MGPipeVerify(const MGPCopyFromFramebuffer& a, const MGPCopyFromFramebuffer& b, const char** outField);
|
||||
inline Bool MGPipeVerify(const RenderStateParameters& a, const RenderStateParameters& b, const char** outField);
|
||||
inline Bool MGPipeVerify(const PixelStoreParameters& a, const PixelStoreParameters& b, const char** outField);
|
||||
inline Bool MGPipeVerify(const SamplerParameters& a, const SamplerParameters& b, const char** outField);
|
||||
@@ -244,6 +249,16 @@ struct MGPipeHasFieldVerifier<MGPSwapInterval> : std::true_type {};
|
||||
template <>
|
||||
struct MGPipeHasFieldVerifier<MGPSurfaceInfo> : std::true_type {};
|
||||
template <>
|
||||
struct MGPipeHasFieldVerifier<MGPImageBind> : std::true_type {};
|
||||
template <>
|
||||
struct MGPipeHasFieldVerifier<MGPPatchParameter> : std::true_type {};
|
||||
template <>
|
||||
struct MGPipeHasFieldVerifier<MGPStreamOutputBind> : std::true_type {};
|
||||
template <>
|
||||
struct MGPipeHasFieldVerifier<MGPStorageBlockBinding> : std::true_type {};
|
||||
template <>
|
||||
struct MGPipeHasFieldVerifier<MGPCopyFromFramebuffer> : std::true_type {};
|
||||
template <>
|
||||
struct MGPipeHasFieldVerifier<RenderStateParameters> : std::true_type {};
|
||||
template <>
|
||||
struct MGPipeHasFieldVerifier<PixelStoreParameters> : std::true_type {};
|
||||
@@ -622,6 +637,31 @@ inline Bool MGPipeVerify(const MGPSurfaceInfo& a, const MGPSurfaceInfo& b, const
|
||||
return true;
|
||||
}
|
||||
|
||||
inline Bool MGPipeVerify(const MGPImageBind& a, const MGPImageBind& b, const char** outField) {
|
||||
MGP_FIELDS_MGPImageBind(MGP_VERIFY_FIELD)
|
||||
return true;
|
||||
}
|
||||
|
||||
inline Bool MGPipeVerify(const MGPPatchParameter& a, const MGPPatchParameter& b, const char** outField) {
|
||||
MGP_FIELDS_MGPPatchParameter(MGP_VERIFY_FIELD)
|
||||
return true;
|
||||
}
|
||||
|
||||
inline Bool MGPipeVerify(const MGPStreamOutputBind& a, const MGPStreamOutputBind& b, const char** outField) {
|
||||
MGP_FIELDS_MGPStreamOutputBind(MGP_VERIFY_FIELD)
|
||||
return true;
|
||||
}
|
||||
|
||||
inline Bool MGPipeVerify(const MGPStorageBlockBinding& a, const MGPStorageBlockBinding& b, const char** outField) {
|
||||
MGP_FIELDS_MGPStorageBlockBinding(MGP_VERIFY_FIELD)
|
||||
return true;
|
||||
}
|
||||
|
||||
inline Bool MGPipeVerify(const MGPCopyFromFramebuffer& a, const MGPCopyFromFramebuffer& b, const char** outField) {
|
||||
MGP_FIELDS_MGPCopyFromFramebuffer(MGP_VERIFY_FIELD)
|
||||
return true;
|
||||
}
|
||||
|
||||
inline Bool MGPipeVerify(const RenderStateParameters& a, const RenderStateParameters& b, const char** outField) {
|
||||
MGP_FIELDS_RenderStateParameters(MGP_VERIFY_FIELD)
|
||||
return true;
|
||||
@@ -669,4 +709,4 @@ inline Bool MGPipeVerify(const MGPVertexBindingPointWire& a, const MGPVertexBind
|
||||
|
||||
#undef MGP_VERIFY_FIELD
|
||||
|
||||
inline constexpr SizeT kMGPipeVerifiedPayloadCount = 72;
|
||||
inline constexpr SizeT kMGPipeVerifiedPayloadCount = 77;
|
||||
|
||||
@@ -34,7 +34,33 @@
|
||||
|
||||
struct MGPWireRecHeader {
|
||||
Uint16 Op; // MGPWireOp
|
||||
Uint16 Flags; // MGPipeCallFlags of the call, for asserts and tracing
|
||||
// RING FRAMING FLAGS - MG_Remote::Transport::RingRecordFlags - NOT MGPipeCallFlags.
|
||||
//
|
||||
// This field IS RingRecordHeader::flags (Ring.h): the two structs are the same eight bytes
|
||||
// and the ring writes this one. The two flag spaces OVERLAP AND DISAGREE, so stamping
|
||||
// MGPipeCallFlagsFor(op) in here is a silent, data-dependent corruption:
|
||||
//
|
||||
// bit 0 kNeedsAck == kRecNeedsAck agree
|
||||
// bit 1 kHasBlob == kRecHasBlob agree
|
||||
// bit 2 kVarTail vs kRecPad DISAGREE
|
||||
// bit 3 kHostSpan vs kRecBorrowSlot DISAGREE
|
||||
// bit 4 kReplySlot vs kRecVarTail DISAGREE
|
||||
// bit 5 kOptional vs (nothing) no ring counterpart
|
||||
//
|
||||
// The first two agreeing is exactly what makes this dangerous: a naive stamp looks right
|
||||
// in a debugger. It is not. RingProducer::Reserve masks kRecPad out of a caller's flags,
|
||||
// so bit 2 is defended for anyone who goes through it - and ONLY bit 2, and only on that
|
||||
// path. A producer that writes this header itself (these are the same eight bytes, so a
|
||||
// codec with its own header struct does exactly that) loses even that: Pop treats kRecPad
|
||||
// as a WRAP FILLER AND SKIPS THE RECORD. Bits 3 and 4 are undefended everywhere - a
|
||||
// stamped kHostSpan tells the consumer this record borrowed a slot into the GPU timeline
|
||||
// and must retire late, and a stamped kReplySlot claims a tail that is not there.
|
||||
//
|
||||
// THE TWO SPACES ARE DISJOINT BY TRANSLATION, NOT SHARED. The encoder maps one to the
|
||||
// other explicitly (MG_Remote/Wire/PipeWireCodec.cpp) and nothing else may write this
|
||||
// field. The CALL's flags are not on the wire at all and do not need to be: the opcode is,
|
||||
// and MGPipeCallFlagsFor(op) recovers them exactly on either side.
|
||||
Uint16 Flags;
|
||||
Uint32 Size; // bytes of this record including the header and the variable tail
|
||||
};
|
||||
static_assert(sizeof(MGPWireRecHeader) == 8, "the wire header is 8 bytes");
|
||||
@@ -115,7 +141,12 @@ enum class MGPWireOp : Uint16 {
|
||||
QueryTimestamp = 69,
|
||||
QueryCounter = 70,
|
||||
FenceWaitServer = 71,
|
||||
kOpCount = 72,
|
||||
BindShaderImage = 72,
|
||||
PatchParameter = 73,
|
||||
BindStreamOutput = 74,
|
||||
SetStorageBlockBinding = 75,
|
||||
CopyFramebufferToTexture = 76,
|
||||
kOpCount = 77,
|
||||
};
|
||||
|
||||
// THE FLAGS, EXPORTED ONCE, INDEXED BY OPCODE (P5 R-13.4). MGPWireRecHeader::Flags is
|
||||
@@ -138,8 +169,8 @@ enum class MGPWireOp : Uint16 {
|
||||
inline constexpr Uint32 kMGPipeCallFlags[static_cast<SizeT>(MGPWireOp::kOpCount)] = {
|
||||
/* 0 kInvalid */ static_cast<Uint32>(kNone),
|
||||
/* 1 GetCaps */ static_cast<Uint32>(kReplySlot | kHasBlob),
|
||||
/* 2 ResourceCreate */ static_cast<Uint32>(kNone),
|
||||
/* 3 ResourceRespecify */ static_cast<Uint32>(kNeedsAck),
|
||||
/* 2 ResourceCreate */ static_cast<Uint32>(kReplySlot),
|
||||
/* 3 ResourceRespecify */ static_cast<Uint32>(kNeedsAck | kReplySlot),
|
||||
/* 4 ResourceDestroy */ static_cast<Uint32>(kNone),
|
||||
/* 5 MapPersistent */ static_cast<Uint32>(kReplySlot | kOptional),
|
||||
/* 6 UnmapPersistent */ static_cast<Uint32>(kOptional),
|
||||
@@ -183,8 +214,8 @@ inline constexpr Uint32 kMGPipeCallFlags[static_cast<SizeT>(MGPWireOp::kOpCount)
|
||||
/* 44 SetDrawProgram */ static_cast<Uint32>(kNone),
|
||||
/* 45 SetDispatchProgram */ static_cast<Uint32>(kNone),
|
||||
/* 46 SetResidualValueState */ static_cast<Uint32>(kHasBlob),
|
||||
/* 47 SetTextureParams */ static_cast<Uint32>(kNone),
|
||||
/* 48 ResourceSubData */ static_cast<Uint32>(kHasBlob | kVarTail),
|
||||
/* 47 SetTextureParams */ static_cast<Uint32>(kReplySlot),
|
||||
/* 48 ResourceSubData */ static_cast<Uint32>(kHasBlob | kVarTail | kReplySlot),
|
||||
/* 49 BufferSubDataResident */ static_cast<Uint32>(kHasBlob | kOptional),
|
||||
/* 50 ResourceSubDataComplete */ static_cast<Uint32>(kNone),
|
||||
/* 51 ResourceFlushRange */ static_cast<Uint32>(kNone),
|
||||
@@ -208,6 +239,11 @@ inline constexpr Uint32 kMGPipeCallFlags[static_cast<SizeT>(MGPWireOp::kOpCount)
|
||||
/* 69 QueryTimestamp */ static_cast<Uint32>(kReplySlot),
|
||||
/* 70 QueryCounter */ static_cast<Uint32>(kNone),
|
||||
/* 71 FenceWaitServer */ static_cast<Uint32>(kNone),
|
||||
/* 72 BindShaderImage */ static_cast<Uint32>(kNone),
|
||||
/* 73 PatchParameter */ static_cast<Uint32>(kNone),
|
||||
/* 74 BindStreamOutput */ static_cast<Uint32>(kNone),
|
||||
/* 75 SetStorageBlockBinding */ static_cast<Uint32>(kHasBlob),
|
||||
/* 76 CopyFramebufferToTexture*/ static_cast<Uint32>(kNone),
|
||||
};
|
||||
static_assert(sizeof(kMGPipeCallFlags) / sizeof(kMGPipeCallFlags[0]) ==
|
||||
static_cast<SizeT>(MGPWireOp::kOpCount),
|
||||
@@ -239,6 +275,28 @@ static_assert((MGPipeCallFlagsFor(MGPWireOp::DrawVbo) &
|
||||
static_cast<Uint32>(kHostSpan | kVarTail)) == static_cast<Uint32>(kHostSpan | kVarTail),
|
||||
"draw_vbo is the conditional-tail plus host-span shape the codec is measured on");
|
||||
|
||||
|
||||
// The bit layout of MGPipeCallFlags, read out of MGPipe.h by the generator.
|
||||
// MG_Test/Wire/RingTest.cpp holds the other half: what each of these bits means
|
||||
// in MG_Remote::Transport::RingRecordFlags, which is NOT the same thing.
|
||||
static_assert(static_cast<Uint32>(kNeedsAck) == (1u << 0),
|
||||
"MGPipeCallFlags::kNeedsAck moved bit; MG_Remote's translation is keyed on it");
|
||||
static_assert(static_cast<Uint32>(kHasBlob) == (1u << 1),
|
||||
"MGPipeCallFlags::kHasBlob moved bit; MG_Remote's translation is keyed on it");
|
||||
static_assert(static_cast<Uint32>(kVarTail) == (1u << 2),
|
||||
"MGPipeCallFlags::kVarTail moved bit; MG_Remote's translation is keyed on it");
|
||||
static_assert(static_cast<Uint32>(kHostSpan) == (1u << 3),
|
||||
"MGPipeCallFlags::kHostSpan moved bit; MG_Remote's translation is keyed on it");
|
||||
static_assert(static_cast<Uint32>(kReplySlot) == (1u << 4),
|
||||
"MGPipeCallFlags::kReplySlot moved bit; MG_Remote's translation is keyed on it");
|
||||
static_assert(static_cast<Uint32>(kOptional) == (1u << 5),
|
||||
"MGPipeCallFlags::kOptional moved bit; MG_Remote's translation is keyed on it");
|
||||
// ... and this is ALL of them. A seventh flag changes this number, which is the
|
||||
// build break that sends its author to the ring's flag space before it ships.
|
||||
inline constexpr Uint32 kMGPipeCallFlagsAllBits = static_cast<Uint32>(kNeedsAck | kHasBlob | kVarTail | kHostSpan | kReplySlot | kOptional);
|
||||
static_assert(kMGPipeCallFlagsAllBits == 0x3Fu,
|
||||
"the MGPipeCallFlags bit set changed; see RingTest's cross-enum table");
|
||||
|
||||
struct alignas(8) MGPWireRec_GetCaps {
|
||||
MGPWireRecHeader Header;
|
||||
MGPCaps Payload;
|
||||
@@ -807,6 +865,46 @@ static_assert(sizeof(MGPWireRec_FenceWaitServer) ==
|
||||
((sizeof(MGPWireRecHeader) + sizeof(MGPFenceWait) + 7u) & ~SizeT(7u)),
|
||||
"MGPWireRec_FenceWaitServer gained padding; the wire format moved");
|
||||
|
||||
struct alignas(8) MGPWireRec_BindShaderImage {
|
||||
MGPWireRecHeader Header;
|
||||
MGPImageBind Payload;
|
||||
};
|
||||
static_assert(sizeof(MGPWireRec_BindShaderImage) ==
|
||||
((sizeof(MGPWireRecHeader) + sizeof(MGPImageBind) + 7u) & ~SizeT(7u)),
|
||||
"MGPWireRec_BindShaderImage gained padding; the wire format moved");
|
||||
|
||||
struct alignas(8) MGPWireRec_PatchParameter {
|
||||
MGPWireRecHeader Header;
|
||||
MGPPatchParameter Payload;
|
||||
};
|
||||
static_assert(sizeof(MGPWireRec_PatchParameter) ==
|
||||
((sizeof(MGPWireRecHeader) + sizeof(MGPPatchParameter) + 7u) & ~SizeT(7u)),
|
||||
"MGPWireRec_PatchParameter gained padding; the wire format moved");
|
||||
|
||||
struct alignas(8) MGPWireRec_BindStreamOutput {
|
||||
MGPWireRecHeader Header;
|
||||
MGPStreamOutputBind Payload;
|
||||
};
|
||||
static_assert(sizeof(MGPWireRec_BindStreamOutput) ==
|
||||
((sizeof(MGPWireRecHeader) + sizeof(MGPStreamOutputBind) + 7u) & ~SizeT(7u)),
|
||||
"MGPWireRec_BindStreamOutput gained padding; the wire format moved");
|
||||
|
||||
struct alignas(8) MGPWireRec_SetStorageBlockBinding {
|
||||
MGPWireRecHeader Header;
|
||||
MGPStorageBlockBinding Payload;
|
||||
};
|
||||
static_assert(sizeof(MGPWireRec_SetStorageBlockBinding) ==
|
||||
((sizeof(MGPWireRecHeader) + sizeof(MGPStorageBlockBinding) + 7u) & ~SizeT(7u)),
|
||||
"MGPWireRec_SetStorageBlockBinding gained padding; the wire format moved");
|
||||
|
||||
struct alignas(8) MGPWireRec_CopyFramebufferToTexture {
|
||||
MGPWireRecHeader Header;
|
||||
MGPCopyFromFramebuffer Payload;
|
||||
};
|
||||
static_assert(sizeof(MGPWireRec_CopyFramebufferToTexture) ==
|
||||
((sizeof(MGPWireRecHeader) + sizeof(MGPCopyFromFramebuffer) + 7u) & ~SizeT(7u)),
|
||||
"MGPWireRec_CopyFramebufferToTexture gained padding; the wire format moved");
|
||||
|
||||
[[noreturn]] inline void MGPipeWireProtocolFatal(const char* call, Uint64 size, Uint64 remaining) {
|
||||
MGLOG_F("MGPipe: protocol corruption applying %s: size=%llu remaining=%llu", call,
|
||||
static_cast<unsigned long long>(size), static_cast<unsigned long long>(remaining));
|
||||
@@ -820,233 +918,281 @@ static_assert(sizeof(MGPWireRec_FenceWaitServer) ==
|
||||
} \
|
||||
} while (0)
|
||||
|
||||
// Returns whether the record was applied. P0 is a SKELETON: every case validates its
|
||||
// bounds and then reports "not applied", because no applier exists until P5 wires
|
||||
// MG_Remote/Server/PipeApplier.cpp to the real backend tables. The switch and the opcode
|
||||
// enum come from the same list, so a call added to the catalogue cannot be forgotten here;
|
||||
// the default arm is for the opcode that never came from this catalogue at all - a byte
|
||||
// off a corrupt stream - and it is fatal for the same reason the bounds check is.
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
// THE DECODER HOOK (P5 w1). MG_Pipe is BELOW MG_Remote and may not include it, so the real
|
||||
// 71-arm decoder - MG_Remote/Wire/PipeWireCodec.cpp, which resolves the segments, cross-checks
|
||||
// the variable tails and calls today's MGPipeApply* free functions - installs itself here.
|
||||
// The indirection is the layering, not a policy: gMGPipeSegmentResolver
|
||||
// (MGPipeHostSpan.h:47) is the same shape for the same reason.
|
||||
//
|
||||
// It lives behind the build option because G1 admits no symbol movement in a PULL build, and
|
||||
// an inline variable that MGPipeApplyWireRecord odr-uses would be one.
|
||||
using MGPipeWireRecordApplyFn = Bool (*)(MGPWireOp op, const void* record, Uint64 size,
|
||||
Uint64 remaining);
|
||||
inline MGPipeWireRecordApplyFn gMGPipeWireRecordApply = nullptr;
|
||||
#endif
|
||||
|
||||
// Returns whether the record was applied.
|
||||
//
|
||||
// THE SWITCH IS THE PER-OPCODE BOUNDS GATE AND NOTHING ELSE, AND IT CANNOT SEE THE TAIL.
|
||||
// MGP_WIRE_CHECK_BOUNDS proves `size >= sizeof(MGPWireRec_X)`, `size <= remaining` and
|
||||
// 8-alignment - which is exactly the part a generator can state, because it is the part that
|
||||
// follows from the opcode alone. A kVarTail record declaring Count = 4000 while carrying 8
|
||||
// bytes passes every one of those, so the SECOND check - recompute the total from the
|
||||
// record's own count fields and require it to EQUAL MGPWireRecHeader::Size - belongs to the
|
||||
// decoder, which has the payload (MG_Remote/Wire's MGPipeWireRecordLayout, P5 w1).
|
||||
//
|
||||
// The switch and the opcode enum come from the same list, so a call added to the catalogue
|
||||
// cannot be forgotten here; the default arm is for the opcode that never came from this
|
||||
// catalogue at all - a byte off a corrupt stream - and it is fatal for the same reason the
|
||||
// bounds check is.
|
||||
//
|
||||
// With no decoder installed - every monolith build, and a split build before
|
||||
// ClientSession::Start - this returns false, "this build does not implement it". That is the
|
||||
// P0 skeleton's answer, kept deliberately: a codec that has not been installed must not look
|
||||
// like one that applied the record.
|
||||
inline Bool MGPipeApplyWireRecord(MGPWireOp op, const void* record, Uint64 size, Uint64 remaining) {
|
||||
(void)record;
|
||||
switch (op) {
|
||||
case MGPWireOp::GetCaps:
|
||||
MGP_WIRE_CHECK_BOUNDS(MGPWireRec_GetCaps, "GetCaps");
|
||||
return false;
|
||||
break;
|
||||
case MGPWireOp::ResourceCreate:
|
||||
MGP_WIRE_CHECK_BOUNDS(MGPWireRec_ResourceCreate, "ResourceCreate");
|
||||
return false;
|
||||
break;
|
||||
case MGPWireOp::ResourceRespecify:
|
||||
MGP_WIRE_CHECK_BOUNDS(MGPWireRec_ResourceRespecify, "ResourceRespecify");
|
||||
return false;
|
||||
break;
|
||||
case MGPWireOp::ResourceDestroy:
|
||||
MGP_WIRE_CHECK_BOUNDS(MGPWireRec_ResourceDestroy, "ResourceDestroy");
|
||||
return false;
|
||||
break;
|
||||
case MGPWireOp::MapPersistent:
|
||||
MGP_WIRE_CHECK_BOUNDS(MGPWireRec_MapPersistent, "MapPersistent");
|
||||
return false;
|
||||
break;
|
||||
case MGPWireOp::UnmapPersistent:
|
||||
MGP_WIRE_CHECK_BOUNDS(MGPWireRec_UnmapPersistent, "UnmapPersistent");
|
||||
return false;
|
||||
break;
|
||||
case MGPWireOp::FenceCreate:
|
||||
MGP_WIRE_CHECK_BOUNDS(MGPWireRec_FenceCreate, "FenceCreate");
|
||||
return false;
|
||||
break;
|
||||
case MGPWireOp::FenceStatus:
|
||||
MGP_WIRE_CHECK_BOUNDS(MGPWireRec_FenceStatus, "FenceStatus");
|
||||
return false;
|
||||
break;
|
||||
case MGPWireOp::FenceWait:
|
||||
MGP_WIRE_CHECK_BOUNDS(MGPWireRec_FenceWait, "FenceWait");
|
||||
return false;
|
||||
break;
|
||||
case MGPWireOp::FenceDestroy:
|
||||
MGP_WIRE_CHECK_BOUNDS(MGPWireRec_FenceDestroy, "FenceDestroy");
|
||||
return false;
|
||||
break;
|
||||
case MGPWireOp::QueryCreate:
|
||||
MGP_WIRE_CHECK_BOUNDS(MGPWireRec_QueryCreate, "QueryCreate");
|
||||
return false;
|
||||
break;
|
||||
case MGPWireOp::QueryBegin:
|
||||
MGP_WIRE_CHECK_BOUNDS(MGPWireRec_QueryBegin, "QueryBegin");
|
||||
return false;
|
||||
break;
|
||||
case MGPWireOp::QueryEnd:
|
||||
MGP_WIRE_CHECK_BOUNDS(MGPWireRec_QueryEnd, "QueryEnd");
|
||||
return false;
|
||||
break;
|
||||
case MGPWireOp::QueryAvailable:
|
||||
MGP_WIRE_CHECK_BOUNDS(MGPWireRec_QueryAvailable, "QueryAvailable");
|
||||
return false;
|
||||
break;
|
||||
case MGPWireOp::QueryResult:
|
||||
MGP_WIRE_CHECK_BOUNDS(MGPWireRec_QueryResult, "QueryResult");
|
||||
return false;
|
||||
break;
|
||||
case MGPWireOp::QueryDestroy:
|
||||
MGP_WIRE_CHECK_BOUNDS(MGPWireRec_QueryDestroy, "QueryDestroy");
|
||||
return false;
|
||||
break;
|
||||
case MGPWireOp::CreateRenderState:
|
||||
MGP_WIRE_CHECK_BOUNDS(MGPWireRec_CreateRenderState, "CreateRenderState");
|
||||
return false;
|
||||
break;
|
||||
case MGPWireOp::BindRenderState:
|
||||
MGP_WIRE_CHECK_BOUNDS(MGPWireRec_BindRenderState, "BindRenderState");
|
||||
return false;
|
||||
break;
|
||||
case MGPWireOp::DeleteRenderState:
|
||||
MGP_WIRE_CHECK_BOUNDS(MGPWireRec_DeleteRenderState, "DeleteRenderState");
|
||||
return false;
|
||||
break;
|
||||
case MGPWireOp::CreateVertexElements:
|
||||
MGP_WIRE_CHECK_BOUNDS(MGPWireRec_CreateVertexElements, "CreateVertexElements");
|
||||
return false;
|
||||
break;
|
||||
case MGPWireOp::BindVertexElements:
|
||||
MGP_WIRE_CHECK_BOUNDS(MGPWireRec_BindVertexElements, "BindVertexElements");
|
||||
return false;
|
||||
break;
|
||||
case MGPWireOp::DeleteVertexElements:
|
||||
MGP_WIRE_CHECK_BOUNDS(MGPWireRec_DeleteVertexElements, "DeleteVertexElements");
|
||||
return false;
|
||||
break;
|
||||
case MGPWireOp::CreateSamplerState:
|
||||
MGP_WIRE_CHECK_BOUNDS(MGPWireRec_CreateSamplerState, "CreateSamplerState");
|
||||
return false;
|
||||
break;
|
||||
case MGPWireOp::DeleteSamplerState:
|
||||
MGP_WIRE_CHECK_BOUNDS(MGPWireRec_DeleteSamplerState, "DeleteSamplerState");
|
||||
return false;
|
||||
break;
|
||||
case MGPWireOp::CreateSamplerView:
|
||||
MGP_WIRE_CHECK_BOUNDS(MGPWireRec_CreateSamplerView, "CreateSamplerView");
|
||||
return false;
|
||||
break;
|
||||
case MGPWireOp::DeleteSamplerView:
|
||||
MGP_WIRE_CHECK_BOUNDS(MGPWireRec_DeleteSamplerView, "DeleteSamplerView");
|
||||
return false;
|
||||
break;
|
||||
case MGPWireOp::CreateShaderState:
|
||||
MGP_WIRE_CHECK_BOUNDS(MGPWireRec_CreateShaderState, "CreateShaderState");
|
||||
return false;
|
||||
break;
|
||||
case MGPWireOp::BindShaderState:
|
||||
MGP_WIRE_CHECK_BOUNDS(MGPWireRec_BindShaderState, "BindShaderState");
|
||||
return false;
|
||||
break;
|
||||
case MGPWireOp::DeleteShaderState:
|
||||
MGP_WIRE_CHECK_BOUNDS(MGPWireRec_DeleteShaderState, "DeleteShaderState");
|
||||
return false;
|
||||
break;
|
||||
case MGPWireOp::SetDynamicState:
|
||||
MGP_WIRE_CHECK_BOUNDS(MGPWireRec_SetDynamicState, "SetDynamicState");
|
||||
return false;
|
||||
break;
|
||||
case MGPWireOp::SetFramebufferState:
|
||||
MGP_WIRE_CHECK_BOUNDS(MGPWireRec_SetFramebufferState, "SetFramebufferState");
|
||||
return false;
|
||||
break;
|
||||
case MGPWireOp::SetVertexBuffers:
|
||||
MGP_WIRE_CHECK_BOUNDS(MGPWireRec_SetVertexBuffers, "SetVertexBuffers");
|
||||
return false;
|
||||
break;
|
||||
case MGPWireOp::SetIndexBuffer:
|
||||
MGP_WIRE_CHECK_BOUNDS(MGPWireRec_SetIndexBuffer, "SetIndexBuffer");
|
||||
return false;
|
||||
break;
|
||||
case MGPWireOp::SetIndirectBuffers:
|
||||
MGP_WIRE_CHECK_BOUNDS(MGPWireRec_SetIndirectBuffers, "SetIndirectBuffers");
|
||||
return false;
|
||||
break;
|
||||
case MGPWireOp::SetSamplerViews:
|
||||
MGP_WIRE_CHECK_BOUNDS(MGPWireRec_SetSamplerViews, "SetSamplerViews");
|
||||
return false;
|
||||
break;
|
||||
case MGPWireOp::BindSamplerStates:
|
||||
MGP_WIRE_CHECK_BOUNDS(MGPWireRec_BindSamplerStates, "BindSamplerStates");
|
||||
return false;
|
||||
break;
|
||||
case MGPWireOp::SetShaderImages:
|
||||
MGP_WIRE_CHECK_BOUNDS(MGPWireRec_SetShaderImages, "SetShaderImages");
|
||||
return false;
|
||||
break;
|
||||
case MGPWireOp::SetShaderBuffers:
|
||||
MGP_WIRE_CHECK_BOUNDS(MGPWireRec_SetShaderBuffers, "SetShaderBuffers");
|
||||
return false;
|
||||
break;
|
||||
case MGPWireOp::SetStreamOutputTargets:
|
||||
MGP_WIRE_CHECK_BOUNDS(MGPWireRec_SetStreamOutputTargets, "SetStreamOutputTargets");
|
||||
return false;
|
||||
break;
|
||||
case MGPWireOp::SetGlobalConstants:
|
||||
MGP_WIRE_CHECK_BOUNDS(MGPWireRec_SetGlobalConstants, "SetGlobalConstants");
|
||||
return false;
|
||||
break;
|
||||
case MGPWireOp::SetVertexAttribDefaults:
|
||||
MGP_WIRE_CHECK_BOUNDS(MGPWireRec_SetVertexAttribDefaults, "SetVertexAttribDefaults");
|
||||
return false;
|
||||
break;
|
||||
case MGPWireOp::SetPixelPackState:
|
||||
MGP_WIRE_CHECK_BOUNDS(MGPWireRec_SetPixelPackState, "SetPixelPackState");
|
||||
return false;
|
||||
break;
|
||||
case MGPWireOp::SetPatchState:
|
||||
MGP_WIRE_CHECK_BOUNDS(MGPWireRec_SetPatchState, "SetPatchState");
|
||||
return false;
|
||||
break;
|
||||
case MGPWireOp::SetDrawProgram:
|
||||
MGP_WIRE_CHECK_BOUNDS(MGPWireRec_SetDrawProgram, "SetDrawProgram");
|
||||
return false;
|
||||
break;
|
||||
case MGPWireOp::SetDispatchProgram:
|
||||
MGP_WIRE_CHECK_BOUNDS(MGPWireRec_SetDispatchProgram, "SetDispatchProgram");
|
||||
return false;
|
||||
break;
|
||||
case MGPWireOp::SetResidualValueState:
|
||||
MGP_WIRE_CHECK_BOUNDS(MGPWireRec_SetResidualValueState, "SetResidualValueState");
|
||||
return false;
|
||||
break;
|
||||
case MGPWireOp::SetTextureParams:
|
||||
MGP_WIRE_CHECK_BOUNDS(MGPWireRec_SetTextureParams, "SetTextureParams");
|
||||
return false;
|
||||
break;
|
||||
case MGPWireOp::ResourceSubData:
|
||||
MGP_WIRE_CHECK_BOUNDS(MGPWireRec_ResourceSubData, "ResourceSubData");
|
||||
return false;
|
||||
break;
|
||||
case MGPWireOp::BufferSubDataResident:
|
||||
MGP_WIRE_CHECK_BOUNDS(MGPWireRec_BufferSubDataResident, "BufferSubDataResident");
|
||||
return false;
|
||||
break;
|
||||
case MGPWireOp::ResourceSubDataComplete:
|
||||
MGP_WIRE_CHECK_BOUNDS(MGPWireRec_ResourceSubDataComplete, "ResourceSubDataComplete");
|
||||
return false;
|
||||
break;
|
||||
case MGPWireOp::ResourceFlushRange:
|
||||
MGP_WIRE_CHECK_BOUNDS(MGPWireRec_ResourceFlushRange, "ResourceFlushRange");
|
||||
return false;
|
||||
break;
|
||||
case MGPWireOp::ResourceReadback:
|
||||
MGP_WIRE_CHECK_BOUNDS(MGPWireRec_ResourceReadback, "ResourceReadback");
|
||||
return false;
|
||||
break;
|
||||
case MGPWireOp::ResourceCopyRegion:
|
||||
MGP_WIRE_CHECK_BOUNDS(MGPWireRec_ResourceCopyRegion, "ResourceCopyRegion");
|
||||
return false;
|
||||
break;
|
||||
case MGPWireOp::GenerateMipmap:
|
||||
MGP_WIRE_CHECK_BOUNDS(MGPWireRec_GenerateMipmap, "GenerateMipmap");
|
||||
return false;
|
||||
break;
|
||||
case MGPWireOp::GetTextureImage:
|
||||
MGP_WIRE_CHECK_BOUNDS(MGPWireRec_GetTextureImage, "GetTextureImage");
|
||||
return false;
|
||||
break;
|
||||
case MGPWireOp::Blit:
|
||||
MGP_WIRE_CHECK_BOUNDS(MGPWireRec_Blit, "Blit");
|
||||
return false;
|
||||
break;
|
||||
case MGPWireOp::Clear:
|
||||
MGP_WIRE_CHECK_BOUNDS(MGPWireRec_Clear, "Clear");
|
||||
return false;
|
||||
break;
|
||||
case MGPWireOp::ReadPixels:
|
||||
MGP_WIRE_CHECK_BOUNDS(MGPWireRec_ReadPixels, "ReadPixels");
|
||||
return false;
|
||||
break;
|
||||
case MGPWireOp::DrawVbo:
|
||||
MGP_WIRE_CHECK_BOUNDS(MGPWireRec_DrawVbo, "DrawVbo");
|
||||
return false;
|
||||
break;
|
||||
case MGPWireOp::LaunchGrid:
|
||||
MGP_WIRE_CHECK_BOUNDS(MGPWireRec_LaunchGrid, "LaunchGrid");
|
||||
return false;
|
||||
break;
|
||||
case MGPWireOp::MemoryBarrier:
|
||||
MGP_WIRE_CHECK_BOUNDS(MGPWireRec_MemoryBarrier, "MemoryBarrier");
|
||||
return false;
|
||||
break;
|
||||
case MGPWireOp::BeginStreamOutput:
|
||||
MGP_WIRE_CHECK_BOUNDS(MGPWireRec_BeginStreamOutput, "BeginStreamOutput");
|
||||
return false;
|
||||
break;
|
||||
case MGPWireOp::EndStreamOutput:
|
||||
MGP_WIRE_CHECK_BOUNDS(MGPWireRec_EndStreamOutput, "EndStreamOutput");
|
||||
return false;
|
||||
break;
|
||||
case MGPWireOp::PauseStreamOutput:
|
||||
MGP_WIRE_CHECK_BOUNDS(MGPWireRec_PauseStreamOutput, "PauseStreamOutput");
|
||||
return false;
|
||||
break;
|
||||
case MGPWireOp::ResumeStreamOutput:
|
||||
MGP_WIRE_CHECK_BOUNDS(MGPWireRec_ResumeStreamOutput, "ResumeStreamOutput");
|
||||
return false;
|
||||
break;
|
||||
case MGPWireOp::Flush:
|
||||
MGP_WIRE_CHECK_BOUNDS(MGPWireRec_Flush, "Flush");
|
||||
return false;
|
||||
break;
|
||||
case MGPWireOp::Present:
|
||||
MGP_WIRE_CHECK_BOUNDS(MGPWireRec_Present, "Present");
|
||||
return false;
|
||||
break;
|
||||
case MGPWireOp::SetSwapInterval:
|
||||
MGP_WIRE_CHECK_BOUNDS(MGPWireRec_SetSwapInterval, "SetSwapInterval");
|
||||
return false;
|
||||
break;
|
||||
case MGPWireOp::QueryTimestamp:
|
||||
MGP_WIRE_CHECK_BOUNDS(MGPWireRec_QueryTimestamp, "QueryTimestamp");
|
||||
return false;
|
||||
break;
|
||||
case MGPWireOp::QueryCounter:
|
||||
MGP_WIRE_CHECK_BOUNDS(MGPWireRec_QueryCounter, "QueryCounter");
|
||||
return false;
|
||||
break;
|
||||
case MGPWireOp::FenceWaitServer:
|
||||
MGP_WIRE_CHECK_BOUNDS(MGPWireRec_FenceWaitServer, "FenceWaitServer");
|
||||
return false;
|
||||
break;
|
||||
case MGPWireOp::BindShaderImage:
|
||||
MGP_WIRE_CHECK_BOUNDS(MGPWireRec_BindShaderImage, "BindShaderImage");
|
||||
break;
|
||||
case MGPWireOp::PatchParameter:
|
||||
MGP_WIRE_CHECK_BOUNDS(MGPWireRec_PatchParameter, "PatchParameter");
|
||||
break;
|
||||
case MGPWireOp::BindStreamOutput:
|
||||
MGP_WIRE_CHECK_BOUNDS(MGPWireRec_BindStreamOutput, "BindStreamOutput");
|
||||
break;
|
||||
case MGPWireOp::SetStorageBlockBinding:
|
||||
MGP_WIRE_CHECK_BOUNDS(MGPWireRec_SetStorageBlockBinding, "SetStorageBlockBinding");
|
||||
break;
|
||||
case MGPWireOp::CopyFramebufferToTexture:
|
||||
MGP_WIRE_CHECK_BOUNDS(MGPWireRec_CopyFramebufferToTexture, "CopyFramebufferToTexture");
|
||||
break;
|
||||
case MGPWireOp::kInvalid:
|
||||
case MGPWireOp::kOpCount:
|
||||
default:
|
||||
MGPipeWireProtocolFatal("<unknown opcode>", size, remaining);
|
||||
}
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
if (gMGPipeWireRecordApply != nullptr) {
|
||||
return gMGPipeWireRecordApply(op, record, size, remaining);
|
||||
}
|
||||
#endif
|
||||
return false;
|
||||
}
|
||||
|
||||
#undef MGP_WIRE_CHECK_BOUNDS
|
||||
|
||||
@@ -72,6 +72,8 @@ P2/P3a; everything else that is not a plain scalar is here.
|
||||
| **`MGPFramebufferState::DrawBuffers[8]`** | The `-1` / default-token narrowing at `FramebufferEmit.h:146-163`, verbatim. A draw-buffer entry naming a colour attachment outside the record's own array is `Fatal{ProtocolCorruption}` (the applier already says so). | `-1` = "no attachment" | decoder, applier | Same status. |
|
||||
| **`MGPReplySlot::Id`** | **= the record's sequence number** (R-3). No new id space, no allocator. The server writes the answer into `SEG_REPLY[seq % slots]` and **stamps `seq` back into the slot header** so a wrong-slot read is detectable rather than plausible. | seq is 1-based; `0` = "no record / not encoded" | client barrier wait | `ARCHITECTURE.md:124`: the wire carries no per-record seq field, so seq *is* the ordinal. `MGPReplySlot` exists (`MGPipeTypes.h:78-81`) and **no payload of the ten `kReplySlot` calls contains one** — which is exactly why the id must be derived rather than carried. P9 generalises this to "seq is the id's initial value", which extends the rule rather than overturning it. |
|
||||
| **reply slot header** | `{Uint64 Seq; Int32 Status; Uint32 Size;}` — 16 bytes, then the payload. `Status`: **0 = OK, 1 = DECLINED, 2 = ERROR**. | — | client | **`DECLINED` is a real answer, not a failure.** It is how `MapPersistent` says `nullptr` (R-6) and how the four `Bool` acceptance entry points say `false` (R-5). A client that treats DECLINED as an error re-creates ID-39's 66 lost uploads from the other side. |
|
||||
| **which rows own a reply slot** | **14, and `kMGPipeCallFlags` is the single source of truth** (R-16). The ten always-declared answers plus the **four acceptance rows** — `ResourceCreate`, `ResourceRespecify`, `ResourceSubData`, `SetTextureParams`. | a row without `kReplySlot` has no slot and must never be posted to | s1 sizes the pool from it; w1 posts against it | The four are exactly the `MGPipeApply*` entry points returning `Bool` (`PipeApply.h:820`, `:868`, `:897`, `:1023`); `MapPersistent`'s `void*` is the fifth answer and was already declared. They carried no flag because in monolith the answer is a direct call's return value and there was nothing to declare — but this table already said DECLINED is how they answer, so the catalogue and the contract could not both stand. Pinned by `PipeCatalogueTest`: 14 by count **and** the four by name, so a row cannot lose the flag while another gains one. |
|
||||
| **`kReplySlot` vs "never blocks"** | Both hold, and the barrier is why. | — | reviewers | `MGPipe.h:49` says a reply-slot call "never blocks", and R-5 says the four acceptance answers are read synchronously. That reads as a contradiction and is not one: **under the verb barrier the client is already waiting for `appliedSeq >= mySeq` at this verb boundary**, and the reply is read inside that wait. A `kReplySlot` row therefore adds **no** block — it adds a read to a wait that was already happening (R-3). The flag keeps its literal meaning: the CALL does not block; the barrier does, and the barrier is a retiring object. When it retires per family, these four become genuinely asynchronous and the acceptance answer becomes a real latency question — which is P9's account, not P5's. |
|
||||
| **`kRecPad` and seq** | A wrap filler **does not advance seq**, on either side. | — | both | R-9. `RingConsumer::Pop` already skips fillers; the rule is stated because the *counter* is the caller's, not `Pop`'s. A side that counts pads drifts by one per wrap, for ever — and since seq is the reply-slot id, a drifted seq reads another call's answer instead of failing. Pinned by `RingTest.AWrapFillerDoesNotAdvanceTheRecordSequence`. |
|
||||
| **per-opcode flags** | `kMGPipeCallFlags[MGPWireOp::kOpCount]` in `generated/PipeWire.inc`, read only through `MGPipeCallFlagsFor(op)`. Index 0 (`kInvalid`) is `kNone`. | `kNone` = no flags | every package | R-13.4. Before this table existed nothing generated exported the flags, so six packages were each about to hard-code `PipeCalls.def`'s fourth column — which is how `GetCaps` and `CreateSamplerState` came to own an `MGPBlobRef` with no `kHasBlob` on their line. `gen_pipe.py` now also refuses a flag token that is not an `MGPipeCallFlags` enumerator, with two negative controls in `--self-test`. |
|
||||
| **`kHasBlob`'s meaning** | **Exactly "the payload owns an `MGPBlobRef` member"** — nothing weaker. | — | decoder | `PipeApply.h:78-79` already says so. Three calls carry bytes with **no** `MGPBlobRef`; they are table 1 rows 19–21 and are deliberately unflagged, because a decoder that trusts `kHasBlob` has to find a member to read. |
|
||||
@@ -142,7 +144,7 @@ These three are the reason `kHasBlob` had to be given an exact meaning (table 0)
|
||||
|---|---|---|---|---|
|
||||
| 21 | `MapPersistent` (5) | `kReplySlot\|kOptional` | **Returns `nullptr` under split, always** (R-6/R-2.4). Its `const void* seedBytes` companion (`PipeApply.h:917`) therefore never crosses in P5 and needs no carrier. The three frontend sites already tolerate a decline (`BufferObject.cpp:238`, `:603-606`, `:657-660`). Answer travels as `Status = DECLINED` with a zero-length payload. | `map_persistent.decline` |
|
||||
| 22 | `ResourceReadback` (52) | `kReplySlot` | Bytes go **server → client** in `SEG_EVENT` via `OnBufferWriteback` (#3), not in the reply slot: the destination is the client's shadow and the size is the resource's, not a fixed slot's. The reply slot carries only completion. **The ordering rule is load-bearing:** the writeback is applied **before** the mutation epoch bumps, never after (`ARCHITECTURE.md:292-294`, `Managers.cpp:2120-2136`). | `resource_readback.done` |
|
||||
| 23 | `ReadPixels` (58) / `GetTextureImage` (55) | `kReplySlot` | **`ReadPixels` blocks in P5** and its pixels come back in the reply slot, which is why `ReplyPool::SlotBytes()` is sized from the scenario's largest read rather than guessed. `MGPReadbackInfo` has `DstOffset`/`DstSize` but **no `Seg`** (`MGPipeTypes.h:1197-1206`): ruling — the destination is **always `SEG_REPLY`** in P5, so no `Seg` field is added; the PBO destination (fire-and-forget plus a client-side `MarkGpuWritten`) is b1's and also needs none, because a PBO destination is a resource handle rather than a segment. `GetTextureImage` is **not on P5's reduced path** and its slot stays `Fatal{UnmigratedVerb}`. | `read_pixels.pixels` |
|
||||
| 23 | `ReadPixels` (58) / `GetTextureImage` (55) | `kReplySlot` | **`ReadPixels` blocks in P5** and its pixels come back in the reply slot, which is why `ReplyPool::SlotBytes()` is sized from the scenario's largest read rather than guessed. **ID-47: `SEG_REPLY` is 16 MiB, eight slots of 2 MiB, `MaxReplyBytes = 2 MiB − 16 = 2,097,136`** — the canonical sizes are 8/32/16 MiB + 256 KiB (`ProtocolSmokeTest` pins them on the wire, `SessionTest` on the mapping); the largest P5 read is E2's full-surface 640×480 RGBA8 snapshot, 1,228,800 bytes, which the previous 8 MiB pool refused. **A read whose answer would exceed `MaxReplyBytes` is refused at the CLIENT before emission** with `Fatal{ReplyTooLarge, "ReadPixels <w>x<h> <format> <bytes> > <cap>"}` (`ReplySlotPool::RequireReadPixelsFits`, forwarded by `ClientSession::RequireReadPixelsReplyFits`, called once by c1's `OnReadPixels` emitter) — never truncated, never a server-side abort the client cannot name; `Post`'s own refusal stays as the last line of defence. Reads larger than 2 MiB (a 2400×1080 RGBA8 device surface) are a P6 debt, not a bigger pool; §5 has no knob for this segment by design. `MGPReadbackInfo` has `DstOffset`/`DstSize` but **no `Seg`** (`MGPipeTypes.h:1197-1206`): ruling — the destination is **always `SEG_REPLY`** in P5, so no `Seg` field is added; the PBO destination (fire-and-forget plus a client-side `MarkGpuWritten`) is b1's and also needs none, because a PBO destination is a resource handle rather than a segment. `GetTextureImage` is **not on P5's reduced path** and its slot stays `Fatal{UnmigratedVerb}`. | `read_pixels.pixels` |
|
||||
|
||||
---
|
||||
|
||||
@@ -563,6 +565,62 @@ probe", now with a concrete list of what has to move.
|
||||
|
||||
---
|
||||
|
||||
## §7b R-17 — `MGPWireRecHeader::Flags` is ring framing, never call flags
|
||||
|
||||
**The wire record header and the ring record header are the same eight bytes**, and
|
||||
`MGPWireRecHeader::Flags` **is** `RingRecordHeader::flags`. The two enums that name those bits
|
||||
overlap and disagree:
|
||||
|
||||
| bit | `MGPipeCallFlags` | `RingRecordFlags` | |
|
||||
|---|---|---|---|
|
||||
| 0 | `kNeedsAck` | `kRecNeedsAck` | agree |
|
||||
| 1 | `kHasBlob` | `kRecHasBlob` | agree |
|
||||
| 2 | `kVarTail` | `kRecPad` | **collide** |
|
||||
| 3 | `kHostSpan` | `kRecBorrowSlot` | **collide** |
|
||||
| 4 | `kReplySlot` | `kRecVarTail` | **collide** |
|
||||
| 5 | `kOptional` | — | no counterpart |
|
||||
|
||||
**Stamping `MGPipeCallFlagsFor(op)` into that field is a silent, data-dependent corruption**, and
|
||||
the first two bits agreeing is exactly what makes it survive a debugger.
|
||||
|
||||
**One of the three is already defended, and only one.** `RingProducer::Reserve` masks `kRecPad`
|
||||
out of whatever the caller passes (`Ring.cpp`: `flags & ~kRecPad`), so a stamped `kVarTail` does
|
||||
**not** delete the record for anyone who goes through `Reserve`. That defence is exactly one bit
|
||||
wide:
|
||||
|
||||
- `kVarTail` → `kRecPad`: **masked by `Reserve`.** But the mask is not in the path of a producer
|
||||
that writes the header *itself* — which is precisely what a codec with its own header struct
|
||||
does, since these are the same eight bytes. Then `Pop` skips the record as a wrap filler and
|
||||
it vanishes with no error raised anywhere.
|
||||
- `kHostSpan` → `kRecBorrowSlot`: **undefended.** The consumer believes the record borrowed a
|
||||
slot into the GPU timeline, so it retires on `completedFrameSerial` instead of on apply.
|
||||
- `kReplySlot` → `kRecVarTail`: **undefended.** The record claims a variable tail it does not
|
||||
have — and after R-16 this now fires on **fourteen** rows rather than ten.
|
||||
|
||||
So the failure is not one dramatic disappearance; it is a lifetime lie and a phantom tail on
|
||||
every affected record, plus a disappearance only on the path that skips `Reserve`. The test
|
||||
below pins all three shapes, including the masking, so the defence cannot quietly go away either.
|
||||
|
||||
**Ruling: the two spaces are disjoint by translation, not shared.** The encoder maps one to the
|
||||
other explicitly and nothing else writes the field. The call's flags are **not on the wire at
|
||||
all** and do not need to be — the opcode is, and `MGPipeCallFlagsFor(op)` recovers them exactly
|
||||
on either side.
|
||||
|
||||
Enforcement, split by what each file can see:
|
||||
|
||||
- the generator pins each `MGPipeCallFlags` bit **read out of `MGPipe.h`**, plus
|
||||
`kMGPipeCallFlagsAllBits == 0x3F`, so a renumbering or a seventh flag is a build break;
|
||||
- `MG_Test/Wire/RingTest.cpp` holds the **cross-enum table** — the one place in the tree that
|
||||
sees both, since MG_Pipe is below MG_Remote and may not include `Ring.h`. It asserts all six
|
||||
correspondences and both totals, and then *demonstrates* the defect: a record framed with
|
||||
`draw_vbo`'s call flags is popped as a wrap filler and vanishes, while the same record framed
|
||||
with `kRecVarTail` round-trips.
|
||||
|
||||
The generated comment on the field said "MGPipeCallFlags of the call, for asserts and tracing",
|
||||
which **invited** the defect. It now says what the field is for.
|
||||
|
||||
---
|
||||
|
||||
## §8 Ownership amendments
|
||||
|
||||
- **`MobileGL/MG_Pipe/MGPipeTypes.h` is c0's file** (integrator ruling A; the BRIEF §5 ownership
|
||||
|
||||
@@ -0,0 +1,438 @@
|
||||
# CONTRACT-P5B — the wire contract for the 25 measured class-C slots
|
||||
|
||||
Authority: this file, beside `CONTRACT-P5.md`, which stays authoritative for everything it
|
||||
covers (table 0's encodings, the byte carriers, field ownership, role/thread ownership, the
|
||||
knobs, R-1…R-17). This file ADDS rows to those tables for the verb-migration phase P5b
|
||||
(`~/w7/notes/p5/INTEGRATOR-DECISIONS.md` ID-66, ID-68; the census
|
||||
`~/w7/notes/p6/census-classC.md`) and makes the rulings the census left open. Where it
|
||||
disagrees with CONTRACT-P5.md, this file is newer and wins, and §6 lists every such place.
|
||||
|
||||
**How to change it.** Package c0b's file, edited by the integrator first. A migration package
|
||||
that needs a row changed goes through the integrator; the packages compile against the rows
|
||||
below from day one, which is the whole reason the file exists.
|
||||
|
||||
Base: `feat/disaggregated @ c9878d69` (P5's c1g landed). Every `file:line` below was read at
|
||||
that commit.
|
||||
|
||||
---
|
||||
|
||||
## §0 What P5b is, and the four rules above every row
|
||||
|
||||
P5 landed the first IPC frame on the reduced path: six verbs cross the wire to a real apply
|
||||
thread under `MOBILEGL_TRANSPORT=inproc`, and 64 of the 71 client slots are
|
||||
`Fatal{UnmigratedVerb, "<slot>"}`. The census measured which of the 64 real workloads hit
|
||||
first: **every Minecraft trace first-stops at `DrawElements`**
|
||||
(`improved-transparency-minecraft-26.3` at `DrawElementsInstancedBaseVertex`), and the
|
||||
inproc integration lane's 505 verb aborts are led by `BindImageTexture` 138,
|
||||
`BeginTransformFeedback` 95, `DrawElements` 56, `DispatchCompute` 49, `PatchParameteri` 43,
|
||||
`CopyImageSubData` 30, `MemoryBarrier` 18, `MultiDrawElementsBaseVertex` 18, `ClearBufferiv`
|
||||
12, `ClearBufferuiv` 8 and a measured tail of 15. **P5b migrates those 25, in four packages,
|
||||
under inproc, with the lane's abort count and the traces' first-blocker list as the only
|
||||
gates.**
|
||||
|
||||
The four rules every row below is held to. A, B and C are CONTRACT-P5 §0's, restated only
|
||||
where P5b sharpens them; D is new.
|
||||
|
||||
**Rule A — a content record declares its bytes.** Unchanged. P5b adds ONE content-carrying
|
||||
row (`set_storage_block_binding`'s block name) and it is `kHasBlob`, staged whole in
|
||||
`SEG_STAGE`, `Size = strlen + 1`, never 0.
|
||||
|
||||
**Rule B — no host pointer crosses.** Unchanged, and P5b is the phase that ARMS the one
|
||||
conditional `MGHostSpan` on the hot path: `draw_vbo`'s user-index span
|
||||
(CONTRACT-P5 table 1 row 16). d1 fills it with `Ptr = nullptr, Seg = SEG_STAGE`, the encoder
|
||||
and decoder run all four honesty arms on it, and the sink resolves it through
|
||||
`MG_Pipe::MGPipeHostBytes`. `kCapNeedsHostIndexBytes` and `kCapNeedsHostUboBytes` STAY 0 in
|
||||
P5b — they are about the SERVER needing the bytes of VBO-backed index buffers (P8's index host
|
||||
mirror, ARCHITECTURE §10.3), not about a client array the client alone holds.
|
||||
|
||||
**Rule C — an applier entry point may not hold a pointer past its return.** Unchanged, and
|
||||
it now binds the sinks: every `WireVerbSink::On*` argument that points into a record or a
|
||||
staged run (`ranges`, `userIndices`, `indirect`, the block `name`) is valid for the call only.
|
||||
|
||||
**Rule D — a P5b verb crosses AS THE CALL, not as a reading of it.** A record for one of the
|
||||
25 carries the GL arguments the frontend handed the backend slot - the GL enums verbatim,
|
||||
the GL names the backend keys on, the offsets as the app spelled them - plus the handle the
|
||||
P7/P8 form will dispatch on instead. The server's `ServerVerbSink` reproduces the backend
|
||||
call the monolith makes, and the backend keeps reading the frontend state it reads today
|
||||
through the BARRIER-PULLED fields of its verb class (CONTRACT-P5 table 2, `rsp`). That is
|
||||
what makes migrating a verb a two-file change per slot rather than a backend rewrite, it is
|
||||
why the monolith adapter is byte-identical (nothing on the monolith path changes at all),
|
||||
and it is also the honest statement of the debt: P5b makes the verbs CROSS; retiring the
|
||||
pulls they read is P3b/P4b/P7/P8's, exactly as CONTRACT-P5 table 2 already says, one row per
|
||||
field. Under `MOBILEGL_IPC_STRICT_ERRORS=1` every such pull is still `Fatal`, so the debt
|
||||
stays measurable.
|
||||
|
||||
**The census's correction, made structural.** None of the five P5 class-B verbs has an
|
||||
`MGPipeApply*` entry point; they reach `WireVerbSink`. None of the 25 P5b slots has one
|
||||
either and NONE GAINS ONE (§6.1). The seam a migration package writes is one
|
||||
`ServerVerbSink::On<Row>` body plus one emit-table row on the client - and both already exist
|
||||
as named stubs on this head.
|
||||
|
||||
---
|
||||
|
||||
## §1 Table 0 additions — encodings the P5b rows introduce
|
||||
|
||||
| field | the ruling | zero means | who reads it |
|
||||
|---|---|---|---|
|
||||
| **`MGPClear::Kind` / `::ValueClass`** | `kMGPipeClearKind{Whole=0, Color=1, Depth=2, Stencil=3, DepthStencil=4}`, `kMGPipeClearValueClass{Float=0, Int=1, Uint=2}`, in `MGPipeTypes.h` beside the struct. **One spelling.** Through P5 the numbers lived in `Client/EmitTables.h` and `Server/PipeApplier.h` as two hand-minted copies, each flagged for the integrator; both now alias the contract's. The GL-entry → Kind map is written beside the constants. | `Whole` with `BufferMask = 0`: a clear of nothing, legal | f1's emitters, `ServerVerbSink::OnClear` (live for all five kinds since v1) |
|
||||
| **`MGPDrawFlagBit::kDrawIsIndirect` (1<<5)** | The draw's ranges come from a `GL_DRAW_INDIRECT_BUFFER`; `draw_vbo`'s SECOND TAIL is one `MGPDrawIndirect` instead of the user-index span. **Exclusive with `kDrawHasUserIndices`** and **`NumDraws` must be 0** - both `Fatal{ProtocolCorruption}` at the layout, on both sides. | clear = the range tail describes the draw | d1's emitters, the layout, `OnDrawVbo` |
|
||||
| **`draw_vbo`'s second tail** | `WireRecordLayout::SecondTailIsHostSpans` says what it is: spans (`kDrawHasUserIndices`, and `set_shader_buffers` always) or the indirect block (`kDrawIsIndirect`). The encoder's host-span honesty pass reads the flag, not "a second tail exists" - a 40-byte indirect block read as spans is one span and a quarter of garbage. | — | codec |
|
||||
| **GL enums on the wire** | `MGPMipPlan::Target`, `MGPCopyRegion::SrcTarget/DstTarget`, `MGPCopyFromFramebuffer::Target/InternalFormat`, `MGPImageBind::Access/Format`, `MGPPatchParameter::Pname`, `MGPMemoryBarrier::Bits`: **the GL token verbatim**, in a field wide enough for it (every GL texture target and access token fits a `Uint16`; formats and bitfields take a `Uint32`). Rule D: the sink passes the token to the backend slot that takes it. NOT `MGPipeResourceTarget`: the tree has no resource-target → GL-enum inverse to spend on a field the backend only ever forwards. | 0 = no target / no bits, refused where the backend would refuse it | sinks |
|
||||
| **`MGPImageBind::Access`** | the GL access token (`GL_READ_ONLY` 0x88B8 …), NOT `MGPImageView::Access`'s three-value encoding (CONTRACT-P5 table 0 row `MGPImageView::Access`). Two different records, two different jobs: the set record describes a resolved unit for the draw prep, this record reproduces a call. | — | `OnBindShaderImage` |
|
||||
| **GL names on the wire (`GlName` fields)** | `MGPCopyRegion::SrcGlName/DstGlName`, `MGPImageBind::GlName`, `MGPStreamOutputBind::GlName`, `MGPStorageBlockBinding::GlName`. **A GL name is never an identity** (ARCHITECTURE 4.2.1); it is either the key the backend has ALWAYS used (`XfbImpl::g_xfbObjects[name]`, `DirectGLES.cpp:1401`) or the key of a BARRIER-PULLED sticky forward the P5b sink resolves through (`MGB_CTX->GetTextureObject(name)`, `GetProgramObject(name)` - CONTRACT-P5 table 2's forward rows, retired by P7/P9). Every such field sits beside the handle that replaces it. | 0 = GL's name 0 (the default object / no texture) | sinks, through the forwards |
|
||||
| **the block name blob** | `MGPStorageBlockBinding::Name`: `SEG_STAGE`, `Size = strlen + 1`, the NUL travels. Decoder bound: 4096 bytes; a run whose last byte is not NUL is `Fatal{ProtocolCorruption, "SetStorageBlockBinding.Name"}`. | `Size == 0` is Fatal (rule A) | decoder |
|
||||
|
||||
---
|
||||
|
||||
## §2 Table 1 additions — the 25 slots, by package
|
||||
|
||||
Columns per slot: **wire record** (row it rides, every new field and its carrier) · **class**
|
||||
(all move C → B when the package flips them) · **sink** (`WireVerbSink` method; `ServerVerbSink`
|
||||
override, a named-Fatal stub on this head) · **reply slot** · **thread rule** · **refusals** ·
|
||||
**monolith**.
|
||||
|
||||
Every row: **no reply slot** (nothing the client acts on comes back - ID-31/R-5 apply to
|
||||
the four acceptance rows only), **thread rule = CONTRACT-P5 table 3 unchanged** (the verb
|
||||
barrier holds; the client's `EmitAndWait` blocks until `appliedSeq >= seq`; the server stamps
|
||||
the verb boundary named in `FieldOwnership.def`'s `MGP_VERB_OP_LIST` before the sink runs;
|
||||
`gPipeInputs` has one writer at a time), **monolith = untouched** (the client emit table
|
||||
exists only under split; the backend slot is called directly as today; G2/G14 name-for-name).
|
||||
Those three columns are therefore stated once here and the rows carry only what differs.
|
||||
|
||||
Refusal vocabulary, shared by all four packages: a record the codec cannot prove is
|
||||
`Fatal{ProtocolCorruption, "<row>.<field>"}`; a shape the sink does not implement yet is
|
||||
`Fatal{UnmigratedVerb, "<GL slot>[+<QUALIFIER>]"}` - the SAME family the client's class-C
|
||||
table raises and the census greps, with the qualifier naming the arm
|
||||
(`DrawElements+CLIENT_INDICES`, `CopyImageSubData+RENDERBUFFER`,
|
||||
`ClearNamedFramebufferfv+UNBOUND`); a backend that leaves the slot null DECLINES
|
||||
(`return false`), which is the monolith's null-slot answer in the same words.
|
||||
|
||||
### d1 — indexed / instanced / multi-draw / indirect (10 measured + 9 companions)
|
||||
|
||||
**One row: `draw_vbo` (59), `MGPDrawInfo` + `MGPDrawRange[NumDraws]` + a conditional second
|
||||
tail.** ROADMAP P8's "`draw_vbo` 收编 multi-draw 族" is exactly this: the twenty GL draw entry
|
||||
points collapse onto one record, and the `MGPDrawRange` array already has the shape the
|
||||
`glMultiDraw*` family has. The P5 sink (`Server/PipeApplier.cpp` `OnDrawVbo`) implements
|
||||
`NumDraws == 1`, non-instanced, VBO-backed; d1 fills in the cross product.
|
||||
|
||||
| slot (census entries) | record fields | sink dispatch (`GLFunctionsTable` slot the sink calls) |
|
||||
|---|---|---|
|
||||
| `DrawElements` (56 + every Minecraft trace) | `IndexSize` = 1/2/4 from `type`; `IndexResource` = the VAO's bound element buffer handle (the same handle `set_index_buffer` (32) carried at validate); one range `{Start = indices / IndexSize, Count = count, IndexBias = 0}`; `Flags = 0` | `DrawElementsBaseVertex(mode, count, type, (void*)(Start*IndexSize), 0)` - the P5 arm, unchanged |
|
||||
| `DrawElementsBaseVertex` (4) | as above, `IndexBias = basevertex` | `DrawElementsBaseVertex(…, basevertex)` |
|
||||
| `DrawElementsInstancedBaseVertex` (trace-only, `improved-transparency-minecraft-26.3`) | `InstanceCount = instancecount`, `IndexBias = basevertex` | `DrawElementsInstancedBaseVertex(mode, count, type, offset, instancecount, basevertex)` |
|
||||
| `DrawArraysInstanced` (2) | `IndexSize = 0`, range `{first, count, 0}`, `InstanceCount` | `DrawArraysInstanced` |
|
||||
| `DrawArraysInstancedBaseInstance` (4) | + `StartInstance = baseinstance`. The vertex-FETCH base instance already crossed in `set_vertex_buffers::BaseInstance` at validate (D-H1; `MGP_SET_BASE_INSTANCE` runs before `MGP_FILL`, `GL_Drawing.cpp:663-688`); `StartInstance` is `gl_BaseInstance`'s value and feeds the GL call | `DrawArraysInstancedBaseInstance` |
|
||||
| `MultiDrawArrays` (2) | `IndexSize = 0`, `NumDraws = drawcount`, range i = `{first[i], count[i], 0}` | `MultiDrawArrays(mode, first[], count[], drawcount)` - the sink rebuilds the two arrays from the ranges (bounded locals; rule C) |
|
||||
| `MultiDrawElements` (2) | `NumDraws = drawcount`, range i = `{indices[i] / IndexSize, count[i], 0}` | `MultiDrawElementsBaseVertex(mode, count[], type, offsets[], drawcount, zeros[])` |
|
||||
| `MultiDrawElementsBaseVertex` (18) | range i `IndexBias = basevertex[i]` | `MultiDrawElementsBaseVertex(…, basevertex[])` |
|
||||
| `MultiDrawElementsIndirect` (2) | `Flags = kDrawIsIndirect`, `NumDraws = 0`, second tail `MGPDrawIndirect{Buffer = the bound GL_DRAW_INDIRECT_BUFFER handle, ParameterBuffer = null, Offset = (Uint64)indirect, ParameterOffset = 0, Stride = stride, DrawCount = drawcount}` | `MultiDrawElementsIndirect(mode, type, (void*)Offset, DrawCount, Stride)` |
|
||||
| `MultiDrawArraysIndirectCount` (2) | as above with `IndexSize = 0`, `ParameterBuffer = the bound GL_PARAMETER_BUFFER handle`, `ParameterOffset = (Uint64)drawcount` (the GLintptr the call spells `drawcount`), `DrawCount = maxdrawcount` | `MultiDrawArraysIndirectCount(mode, (void*)Offset, (GLintptr)ParameterOffset, DrawCount, Stride)` - the backend reads the count where it does today (`DirectGLES.cpp:6510`) |
|
||||
| companions, unmeasured, same row, d1 owns the slots: `DrawElementsInstanced`, `DrawElementsInstancedBaseInstance`, `DrawElementsInstancedBaseVertexBaseInstance`, `DrawRangeElements`, `DrawRangeElementsBaseVertex` (`Flags |= kDrawHasIndexRange`, `MinIndex/MaxIndex = start/end`), `MultiDrawArraysIndirect`, `MultiDrawElementsIndirectCount`, `DrawArraysIndirect`, `DrawElementsIndirect` (`kDrawIsIndirect`, `DrawCount = 1`) | | |
|
||||
|
||||
**Sink:** `WireVerbSink::OnDrawVbo(const MGPDrawInfo&, const MGPDrawRange* ranges, const
|
||||
MGHostSpan* userIndices, const MGPDrawIndirect* indirect)` - the P5 signature plus the
|
||||
indirect block. On this head the sink declines by name: `MultiDrawArrays` /
|
||||
`MultiDrawElements` for `NumDraws != 1`, `DrawArraysInstanced` / `DrawElementsInstanced` for
|
||||
the instanced arms, `DrawElements+CLIENT_INDICES` for a span,
|
||||
`MultiDraw{Arrays,Elements}Indirect` for the block.
|
||||
|
||||
**Client-side index arrays (no element buffer bound) — the P8 resolve-on-client rule,
|
||||
applied.** The bytes exist on the client only, so the client resolves them: d1's emitter
|
||||
stages `count * IndexSize` bytes at `indices` into `SEG_STAGE` and names the run in the
|
||||
existing conditional `MGHostSpan` tail (`Flags |= kDrawHasUserIndices`, `Ptr = nullptr, Seg =
|
||||
SEG_STAGE`). The codec already runs all four honesty arms on it
|
||||
(`PipeWireCodec.cpp` `CheckHostSpanIsHonest(span, segments)`); the sink resolves it with
|
||||
`MGPipeHostBytes` and passes the pointer as `indices`. This is the shape CONTRACT-P5 table 1
|
||||
row 16 froze and table 0 said "P5 must produce none of"; P5b produces it for exactly the
|
||||
case where nothing else can. **`kCapNeedsHostIndexBytes` stays 0**: it asks for the bytes of
|
||||
VBO-backed index buffers (restart rewriting, multi-draw flattening) and is answered by P8's
|
||||
`Server/IndexHostMirror` (ARCHITECTURE §10.3), not by a per-draw span. **A multi-draw with
|
||||
client-side indices** (`indices[i]` are `drawcount` separate client pointers, one span can
|
||||
name one run) is refused by name, `Fatal{UnmigratedVerb, "MultiDrawElements+CLIENT_INDICES"}`,
|
||||
until P8's `HostResolve.cpp` flattens it; no measured workload has one.
|
||||
|
||||
**Client-side VERTEX arrays** (attribute pointers into client memory, no VBO) are NOT d1's
|
||||
and are not a wire question: Espryt's `SyncClientSideAttributesForDrawArrays`
|
||||
(`DirectGLES.cpp:6284-6291`) and its `DrawElements` twin upload them on the SERVER by reading
|
||||
the frontend VAO through the BARRIER-PULLED `GetBoundVertexArray` (CONTRACT-P5 table 2, "P8").
|
||||
Under inproc that read dereferences the client's pointers in the same address space and is
|
||||
correct by the barrier; under spawn (P6) it is exactly the pull P8's `HostResolve.cpp`
|
||||
(client array ranges, max-index scan) retires. d1 changes nothing there.
|
||||
|
||||
**`MinIndex / MaxIndex`** stay `~0` (unknown) for every P5b draw except the two
|
||||
`DrawRangeElements*` companions; **`XfbCpuCapturedVertices`** rides only when the client's
|
||||
XFB accounting has a value (`kDrawHasXfbCount`), which t2's rows make possible;
|
||||
**`RestartIndex` / `kDrawPrimitiveRestart`** carry the frontend's primitive-restart state
|
||||
verbatim (the backend's `ScopedRestartIndexSubstitution` reads the index bytes it needs on
|
||||
its side - from the bound buffer, or from the resolved span).
|
||||
|
||||
**Stamp:** `DrawVbo → DrawArrays` (all twenty share `kDraw`'s mask; the Fatal NAME a pull
|
||||
prints is `DrawArrays` for every one of them - known, accepted, and the reason d1 reports
|
||||
next blockers by the wire's `UnmigratedVerb` name, which is exact).
|
||||
|
||||
**d1's gate:** the lane's `DrawElements` / `MultiDrawElementsBaseVertex` / `DrawArrays*` /
|
||||
`DrawElementsBaseVertex` / `MultiDraw*` first-blocker entries → 0, each affected scenario at
|
||||
its NEXT first blocker by name; **and every Minecraft trace reaches its next first blocker
|
||||
under inproc, reported by name** (the census could not see past `DrawElements`).
|
||||
|
||||
### i1 — image / compute / barrier / copy-image / storage block (5 measured + 2 companions)
|
||||
|
||||
| slot (entries) | row (opcode) | record | sink | on this head |
|
||||
|---|---|---|---|---|
|
||||
| `BindImageTexture` (138) | **`bind_shader_image` (72), NEW**, `MGPImageBind` 40 B | `Res` = the texture's handle (null for 0), `Unit`, `GlName`, `Level`, `Layer`, `Layered`, `Access` = GL token, `Format` = GL enum. Emitted at the call (`GL_Texture.cpp:6736`), AFTER the frontend has written the unit's `ImageTextureBinding` and `MGP_FILL(BindImageTexture)` has run - the record's verb boundary is what makes the server's read of that binding legal. `set_shader_images` (37) still travels at the next validate, untouched: it is the draw-prep set, this is the call. | `OnBindShaderImage(const MGPImageBind&)` → `GL.BindImageTexture(Unit, GlName, Level, Layered, Layer, Access, Format)`. Espryt ignores everything but `Unit` and syncs the unit's binding from the barrier-pulled `GetImageTextureBinding` (`DirectGLES.cpp:9154`, `:2471`); Magma's slot is a no-op (`DirectVulkan.cpp:665`), so the same call is right for both. | `Fatal{UnmigratedVerb, "BindImageTexture"}` stub |
|
||||
| `DispatchCompute` (49) | `launch_grid` (60), `MGPGridInfo` | `GridX/Y/Z` = the three counts; `Block* = 0` in P5b (the local size is a link artifact the backend reads from its own program; P7 Magma may fill it from the reflection archive); `IsIndirect = 0`. Companion `DispatchComputeIndirect`: `IsIndirect = 1`, `IndirectBuffer` = the bound `GL_DISPATCH_INDIRECT_BUFFER` handle, `IndirectOffset = indirect`. The emitter keeps b1's pre-verb hook ORDER the class-C stub already has: `PushPersistentMapsBeforeVerb(); MarkGpuWritesForDispatch();` then the record (`EmitTables.cpp` `DispatchCompute_Unmigrated`). | `OnLaunchGrid(const MGPGridInfo&)` → `GL.DispatchCompute(GridX, GridY, GridZ)` / `GL.DispatchComputeIndirect(IndirectOffset)` | stub, `"DispatchCompute"` / `"DispatchComputeIndirect"` by `IsIndirect` |
|
||||
| `MemoryBarrier` (18) | `memory_barrier` (61), `MGPMemoryBarrier` | `Bits` = the GLbitfield verbatim (the frontend already validated it and already folds `glTextureBarrier` onto it, `GL_Drawing.cpp:920-937`); `ByRegion = 0`. Companion `MemoryBarrierByRegion`: `ByRegion = 1`. | `OnMemoryBarrier(const MGPMemoryBarrier&)` → `GL.MemoryBarrier(Bits)` / `GL.MemoryBarrierByRegion(Bits)`; Espryt's atomic-counter lowering stays inside the backend (`DirectGLES.cpp:8836`) | stub |
|
||||
| `CopyImageSubData` (30) | `resource_copy_region` (53), `MGPCopyRegion` **64 → 72 B** | `Src/Dst` handles (kind Texture, or Renderbuffer when the target is `GL_RENDERBUFFER`), `SrcTarget/DstTarget` = the GL targets verbatim, `SrcBox = {srcX, srcY, srcZ, w, h, d}`, `DstX/Y/Z`, `SrcLevel/DstLevel`, **`SrcGlName/DstGlName`** (new). | `OnResourceCopyRegion(const MGPCopyRegion&)` → rebuilds two `CopyImageEndpoint`s (`BackendObject.h:33`) from the GL names through the barrier-pulled `MGB_CTX->GetTextureObject(name)` (`rsp`) and calls `GL.CopyImageSubData(src, SrcTarget, SrcLevel, SrcBox.X/Y/Z, dst, DstTarget, DstLevel, DstX/Y/Z, SrcBox.W/H/D)`. **A renderbuffer endpoint is refused by name** (`"CopyImageSubData+RENDERBUFFER"`): no sticky forward hands out a renderbuffer object, and P7 is where the backend takes handles. | stub |
|
||||
| `ShaderStorageBlockBinding` (4) | **`set_storage_block_binding` (75), NEW**, `MGPStorageBlockBinding` 40 B, `kHasBlob` | `ShaderCso` = the program's CSO handle, `GlName` = the GL program name, `Binding`, `Name` = the block name staged in `SEG_STAGE`, `Size = strlen + 1`. Emitted at `GL_Program.cpp:3394` after the frontend recorded the binding on the program (`SetShaderStorageBlockBinding`, `:3392` - which is what reseeds a rebuilt backend program and what `GL_BUFFER_BINDING` reports; the record is the "push it onto the already-built driver program" optimisation Espryt performs, `DirectGLES.cpp:9182-9218`). | `OnSetStorageBlockBinding(const MGPStorageBlockBinding&, const char* name)` → `GL.ShaderStorageBlockBinding(GlName, name, Binding)`; both backends resolve the program through the barrier-pulled `GetProgramObject(GlName)` / `TryGetDirectVulkanProgram` (`rsp`, P9). | stub |
|
||||
|
||||
**The `copy-image-shadow-mirror` emulation** (`DirectGLES.cpp:8997`, `MGPipeUnmigratedEmulation`
|
||||
→ `Fatal{UnmigratedEmulation}` under any non-monolith transport, `PipeApply.cpp:2947`).
|
||||
Migrating `CopyImageSubData` moves the first blocker from the client's
|
||||
`Fatal{UnmigratedVerb, "CopyImageSubData"}` to the server's
|
||||
`Fatal{UnmigratedEmulation, "copy-image-shadow-mirror"}` on every Espryt copy between two
|
||||
textures with CPU shadows. **Ruling (i1): under split the server SKIPS the mirror** - the site
|
||||
becomes `if (monolith) mirror else skip`, behind `#if MOBILEGL_BUILD_DISAGGREGATED` so the
|
||||
pull build's code does not move (G1) - and the client-side mirror ROADMAP P8 names ("CopyImage
|
||||
镜像搬到 client") is P8's. What the skip loses is bounded by two Fatals: a later `glGetTexImage`
|
||||
of the destination served from the client shadow (class C, wave 3, P9) and a texture re-mint
|
||||
that re-uploads it (`texture-remint-pull`, also Fatal). i1 reports which scenarios reach either.
|
||||
|
||||
**Stamps:** `BindShaderImage → BindImageTexture` (kTextureOp), `LaunchGrid → DispatchCompute`
|
||||
(kDispatch; `GetProgramForDispatch` is FATAL in CONTRACT-P5 table 2 because "there is no
|
||||
compute on the reduced path" - **i1 moves it to BARRIER_PULLED, "P7 (Magma), P8 (Espryt)"**, the
|
||||
same shape as `GetProgramForDraw`, in `FieldOwnership.def`; that is a one-row edit in a c0b file
|
||||
and i1 may make it), `MemoryBarrier → MemoryBarrier`, `ResourceCopyRegion → CopyImageSubData`
|
||||
(new row, §6.3), `SetStorageBlockBinding → ShaderStorageBlockBinding`.
|
||||
|
||||
**i1's gate:** the lane's five first-blocker counts → 0; each affected scenario at its next
|
||||
first blocker by name (the census predicts `DispatchCompute` → `MemoryBarrier` → readback for
|
||||
the image-store cases, and the emulation Fatal for some copies).
|
||||
|
||||
### t2 — transform-feedback spans, the XFB object bind, the patch parameter (3 measured + 4 companions)
|
||||
|
||||
| slot (entries) | row (opcode) | record | sink | on this head |
|
||||
|---|---|---|---|---|
|
||||
| `BeginTransformFeedback` (95) | `begin_stream_output` (62), `MGPStreamOutputBegin` | `PrimitiveMode` verbatim. Emitted at `GL_Drawing.cpp:1274` after the frontend's `BeginTransformFeedback(primitiveMode, program)` recorded the span - the capture program and the capture-buffer bindings the backend reads at the next draw (`StartPendingTransformFeedback`, `DirectGLES.cpp:1224-1250`) are `kXfbSpan`/`kDraw` BARRIER-PULLED fields (`GetTransformFeedbackProgram`, `GetBufferBindingPoint`…). **`set_stream_output_targets` (39) is NOT required for t2**: it has no applier and no producer, and the pulls cover the bindings while the barrier holds. Producing it is P9's (XFB scatter) and would need the consumer nobody can test yet (CONTRACT-P5 §7 `WireVerbSink` header). | `OnBeginStreamOutput(const MGPStreamOutputBegin&)` → `GL.BeginTransformFeedback(PrimitiveMode)` | stub |
|
||||
| `PatchParameteri` (43) | **`patch_parameter` (73), NEW**, `MGPPatchParameter` 8 B | `Pname = GL_PATCH_VERTICES`, `Value`. Espryt pushes `glPatchParameteri` at the call (`DirectGLES.cpp:8760`) and NOT from its draw sync, so `set_patch_state` (43) - which carries the same number into the applier's working block at validate - cannot stand in; both travel, as both pushes happen today. Emitted at `GL_Drawing.cpp:844`. Magma registers no slot: the sink's null-slot DECLINE is the monolith's null-slot skip in the same words. | `OnPatchParameter(const MGPPatchParameter&)` → `GL.PatchParameteri(Pname, Value)` | stub |
|
||||
| `BindTransformFeedback` (2) | **`bind_stream_output` (74), NEW**, `MGPStreamOutputBind` 16 B | `GlName` (Espryt's own key, `XfbImpl::g_xfbObjects[name]`, `DirectGLES.cpp:1401`; 0 = the default object), `LifetimeId` (the D21 counter-slot rekey's key; the frontend's `GetBoundTransformFeedbackLifetimeId`). Emitted at `GL_Drawing.cpp:1673` after `BindTransformFeedbackObject(id)`. | `OnBindStreamOutput(const MGPStreamOutputBind&)` → `GL.BindTransformFeedback(GlName)` | stub |
|
||||
| companions, same rows, t2 owns the slots: `EndTransformFeedback` → `end_stream_output` (63) `MGPXfbAccounting{CapturedVertices, PrimitivesWritten, PrimitiveMode}` = the frontend's own accounting at the end (`GL_Drawing.cpp:1371`; the client's fence wait there is dropped per ARCHITECTURE 8.5 / CONTRACT-P5 table 2's "two new producers" - the capture targets are marked GPU-written instead); `PauseTransformFeedback` / `ResumeTransformFeedback` → (64)/(65) `MGPStreamOutputControl{Reserved = 0}`; `DeleteTransformFeedback` has no row in P5b (unmeasured; a `bind_stream_output` of name 0 is what the backend does on delete of the bound object, `DirectGLES.cpp:1422`, and the driver object leak until P9 is recorded, not solved). | | `OnEndStreamOutput` / `OnPauseStreamOutput` / `OnResumeStreamOutput` → the three GL slots | stubs |
|
||||
|
||||
**`FixupGsStripCaptureOrder` (`GL_Drawing.cpp:1290`)** probes `EndTransformFeedback != nullptr`
|
||||
to decide whether the backend owns the capture. `SlotCaps.h` deliberately did not convert this
|
||||
probe ("absent would be wrong"); with t2's emitter installed the slot is non-null on the
|
||||
client, which for a server running Espryt is the right answer and for a server running Magma
|
||||
(slot null on the server, the sink DECLINES) is WRONG in the P5 direction: the client would
|
||||
skip a reorder Magma needs. **Ruling:** t2 answers the probe from the caps mirror - the
|
||||
existing `kCapCpuXfbPrimitiveAccounting`-style shape, a new cap bit
|
||||
`kCapBackendOwnsXfbCapture` (1<<9) in `MGPCapBit`, set by the server from its own table's
|
||||
`EndTransformFeedback != nullptr` - through `MGL_BACKEND_SLOT_CAP`. That is the one new cap
|
||||
bit of P5b and it is c0b's file; t2 adds it (§6.5).
|
||||
|
||||
**Stamps:** `BeginStreamOutput → BeginTransformFeedback`, `EndStreamOutput →
|
||||
EndTransformFeedback`, `Pause/Resume` likewise (all pre-existing rows), `PatchParameter →
|
||||
PatchParameteri` (kQuery: reads nothing), `BindStreamOutput → BindTransformFeedback` (kXfbSpan).
|
||||
|
||||
**t2's gate:** the three first-blocker counts → 0; each scenario at its next blocker by name
|
||||
(the census predicts `EndTransformFeedback` or an XFB query end - the query family is wave 3
|
||||
and stays `Fatal{UnmigratedVerb}`).
|
||||
|
||||
### f1 — the clear family, the framebuffer-sourced copies, mips (7 measured + 4 companions)
|
||||
|
||||
| slot (entries) | row (opcode) | record | sink | on this head |
|
||||
|---|---|---|---|---|
|
||||
| `ClearBufferiv` (12), `ClearBufferuiv` (8), `ClearBufferfv` (6), `ClearBufferfi` (1) | `clear` (57), `MGPClear` | `Fbo = kMGPipeNullHandle` (the bound draw framebuffer, as `EmitClear` does), `Kind` / `ValueClass` per the table in `MGPipeTypes.h` beside the constants, `DrawBufferIndex = drawbuffer`, `ColorValue[4]` = the four values' bits (`memcpy`; a float clear crosses as its bit pattern, exactly as MOBILEGL_PIPE_VERIFY compares floats), `DepthValue`, `StencilValue`. Emitted at `GL_Framebuffer.cpp:2829-2850` with `BeforeReadOnlyVerb()` first, as `EmitClear`. | `OnClear` - **already live for all five kinds** (`PipeApplier.cpp` `OnClear`): `GL.ClearBuffer{fv,iv,uiv,fi}` by `Kind`/`ValueClass`. The only work is the client. | live |
|
||||
| `ClearNamedFramebufferfv` (2) + companions `fi/iv/uiv` | `clear` (57) | as above with **`Fbo` = the named framebuffer's handle**, preceded by its `MGPipeFramebufferTarget::Named` record (ID-19; the frontend already emits it: `PipePublishFramebufferByName`, `GL_Framebuffer.cpp:690`). | `OnClear`: `Fbo` null or equal to the applier's `BoundFramebuffer[Draw]` → the bound-form clear above. **Otherwise refused by name, `Fatal{UnmigratedVerb, "ClearNamedFramebufferfv+UNBOUND"}`**: the backend slot takes a frontend `SharedPtr<FramebufferObject>` (`DirectGLES.cpp:9308`), no forward hands one out, and the bound-form entries re-sync the CLIENT's binding through the barrier-pulled `GetFramebufferBindingSlot` (`SyncCurrentFBO`), so a server-side rebind-clear-restore through the applier would be undone by the pull. The handle-keyed `SyncAndBindFramebufferObject` sibling Espryt needs (`DirectGLES.cpp:4409`) is P7's / P3b-P4b's, or f1's stretch behind `#if MOBILEGL_BUILD_DISAGGREGATED` if the one measured scenario needs it. | live for the bound case; the unbound refusal is f1's to add |
|
||||
| `CopyTexImage2D` (3) + companion `CopyTexSubImage2D` | **`copy_framebuffer_to_texture` (76), NEW**, `MGPCopyFromFramebuffer` 48 B | `Dst` = the bound texture's handle at the active unit (P8 form), `Target` = the GL target verbatim, `Level`, `InternalFormat` (image form; 0 for sub-image), `X, Y, Width, Height` = the read-framebuffer rectangle, `XOffset, YOffset` (sub-image form), `SubImage = 0/1`. The image form's level redefinition has already crossed as the level's `resource_respecify` from the frontend's own `TexImage2D_State` (`GL_Texture.cpp:4541`) before the backend slot is reached (`:4550`); the record carries only the copy. The read framebuffer is the bound one (`set_framebuffer_state`). | `OnCopyFramebufferToTexture(const MGPCopyFromFramebuffer&)` → `GL.CopyTexImage2D(Target, Level, InternalFormat, X, Y, Width, Height, 0)` or `GL.CopyTexSubImage2D(Target, Level, XOffset, YOffset, X, Y, Width, Height)`; the backend resolves the bound texture through the barrier-pulled unit state (`DirectGLES.cpp:8528-8531`, kBlitOrCopy's mask). | stub, `"CopyTexImage2D"` / `"CopyTexSubImage2D"` |
|
||||
| `GenerateMipmap` (2) | `generate_mipmap` (54), `MGPMipPlan` | `Res` = the bound texture's handle, `Target` = the GL target verbatim, `BaseLevel/LevelCount` from the texture's base level and level count (informational in P5b). Emitted at `GL_Texture.cpp:1681`. | `OnGenerateMipmap(const MGPMipPlan&)` → `GL.GenerateMipmap(Target)`; the backend resolves the bound texture through the barrier-pulled unit state (`DirectGLES.cpp:8769-8772`). | stub |
|
||||
|
||||
**The two mipmap emulations** (`generate-mipmap-storage` `DirectGLES.cpp:8051`,
|
||||
`generate-mipmap-cpu-fallback` `:8702`, both `Fatal{UnmigratedEmulation}` under split) are
|
||||
reached only for `R11FG11FB10F`, depth-only, `RGB16F` and `RGB32F` textures
|
||||
(`DirectGLES.cpp:8774-8778`). **Ruling (f1):** migrating `GenerateMipmap` moves those cases'
|
||||
first blocker to the emulation Fatal, reported by name; every other format renders. The
|
||||
storage grow reads the frontend level shadows to DECIDE the levels and could be re-derived from
|
||||
the applier's descriptor (`Levels`) - f1 may do that behind `#if MOBILEGL_BUILD_DISAGGREGATED`;
|
||||
the CPU three-channel fallback needs `OnTextureWriteback` (ROADMAP P8/P9) and stays Fatal.
|
||||
|
||||
**Stamps:** `Clear → Clear` (pre-existing), `CopyFramebufferToTexture → CopyTexImage2D` (the
|
||||
sub-image companion shares the kBlitOrCopy mask), `GenerateMipmap → GenerateMipmap`.
|
||||
|
||||
**f1's gate:** the seven first-blocker counts → 0; each scenario at its next blocker by name.
|
||||
|
||||
---
|
||||
|
||||
## §3 Table 2 — field ownership under P5b
|
||||
|
||||
**P5b adds no PipeInputs field and retires none.** Every one of the 25 verbs reads, on the
|
||||
server, exactly the fields its verb class's may-read mask names (`FillPoints.def`) and finds
|
||||
them in the class CONTRACT-P5 table 2 already assigned: RECORD_SUPPLIED where a record
|
||||
carries them, BARRIER_PULLED (counted in `rsp`) for the frontend-object and shutter fields,
|
||||
FATAL for the three off-path ones. Two of the three FATAL rows are reached by P5b verbs and
|
||||
move:
|
||||
|
||||
| field | CONTRACT-P5 class | P5b | why |
|
||||
|---|---|---|---|
|
||||
| `GetProgramForDispatch` | FATAL ("no compute on the reduced path") | **BARRIER_PULLED, "P7 (Magma), P8 (Espryt)"** | i1 puts compute on the path; the field is `GetProgramForDraw`'s twin (`DirectGLES.cpp:5779`, `VulkanRenderer.cpp:7327`) and takes its class and its retiring phases. i1 edits the row. |
|
||||
| `GetTransformFeedbackPausedPrimitiveCounter` | FATAL ("reachable only from kQuery") | unchanged | its one reader is Magma's XFB query end (`kQuery`), and the query family is wave 3. |
|
||||
| `GetBoundTransformFeedbackName` | FATAL (dead) | unchanged | |
|
||||
|
||||
**`rsp` grows, and that is the phase's measurement.** Every P5b verb that draws, dispatches
|
||||
or copies pulls the same 20 non-sticky rows a P5 draw pulled plus the sticky forwards its arm
|
||||
uses (`GetTextureObject` for `CopyImageSubData`, `GetProgramObject` for
|
||||
`ShaderStorageBlockBinding`). The end-of-P5b `rsp` per Minecraft frame is the number that
|
||||
sizes P3b/P4b/P7/P8, and each package's report carries it for its scenarios.
|
||||
|
||||
**The server stamp:** every P5b row that is a verb boundary has a `MGP_VERB_OP_LIST` row in
|
||||
`FieldOwnership.def` on this head (18 rows; `FieldOwnershipTest` pins them). A P5b record that
|
||||
arrived with NO stamp row would apply under the previous verb's serial and read a stale field
|
||||
as fresh - the one silent failure the table has - which is why the six rows landed in c0b
|
||||
rather than being left to the packages.
|
||||
|
||||
---
|
||||
|
||||
## §4 Table 3 — role and thread ownership under P5b
|
||||
|
||||
Unchanged, and the one thing to restate: **the verb barrier holds for every P5b verb.**
|
||||
`ClientSession::EmitAndWait` blocks the GL thread until `appliedSeq >= seq` for every one of
|
||||
the 25 records as it does for the five P5 verbs; the server's `PipeApplier::ApplyOne` stamps
|
||||
the verb boundary, runs the sink, clears the stamp, and only then does the session publish
|
||||
`appliedSeq` (R-1, R-9). The pre-verb hooks keep their P5 order on the client:
|
||||
`PushPersistentMapsBeforeVerb()` then `MarkGpuWritesFor{Draw,Dispatch}()` then the record
|
||||
(`EmitTables.cpp` `BeforeDrawVerb` / `DispatchCompute_Unmigrated`; ID-18). A P5b emitter for a
|
||||
verb that reads buffers but starts no shader (the clears, the copies, the mip generation, the
|
||||
barrier, the XFB and patch controls) calls `BeforeReadOnlyVerb()`.
|
||||
|
||||
**What the barrier buys P5b and what it costs.** It is why Rule D works at all - the server's
|
||||
backend reads the client's `gPipeInputs` fill of the moment - and it is why P5b's inproc is
|
||||
lockstep and slow (P5 said so; "P5 预期变慢" is P5b's expectation too, recorded, not gated).
|
||||
Retiring it per family is P9's, after the pulls it protects are gone.
|
||||
|
||||
---
|
||||
|
||||
## §5 Knobs
|
||||
|
||||
**No new knob.** `MOBILEGL_TRANSPORT=inproc` with the P5 defaults is P5b's whole
|
||||
configuration. One cap bit is added (§6.5, `kCapBackendOwnsXfbCapture`), which is not a knob.
|
||||
`MOBILEGL_IPC_STRICT_ERRORS=1` remains the way to see the pulls a P5b verb costs, and
|
||||
`MOBILEGL_IPC_AUDIT=1` remains rule C's control - now with a second consumer worth auditing,
|
||||
the user-index span.
|
||||
|
||||
---
|
||||
|
||||
## §6 Rulings this file makes, and what would overturn each
|
||||
|
||||
1. **No P5b slot gains an `MGPipeApply*` entry point; all 25 reach `WireVerbSink`.** The
|
||||
applier's 37 entry points are the object and state families and write `gPipeInputs` /
|
||||
the applier's records; a verb is a backend CALL, and the census's correction - the five P5
|
||||
class-B verbs already go to the sink - is the pattern, not the exception. The generated
|
||||
route tables (`PipeRoute.h`, R-17, 33 + 4 = 37) are therefore untouched and
|
||||
`PipeCatalogueTest`'s partition still reads 33 installed + (76 − 33) null + 4 escapes.
|
||||
*Overturned by:* a verb that must be replayable from the monolith side through a table
|
||||
(the MGPipe recorder, ROADMAP P13) - at which point every sink method becomes a table row
|
||||
and the monolith adapter is the backend call; none of P5b needs it.
|
||||
|
||||
2. **Five rows appended, none inserted, opcodes 72..76.** `bind_shader_image`,
|
||||
`patch_parameter`, `bind_stream_output`, `set_storage_block_binding`,
|
||||
`copy_framebuffer_to_texture`. Each exists because the backend does work AT THE CALL that
|
||||
no validate-time set record reproduces (§0 Rule D; the evidence per row is in
|
||||
`MGPipeTypes.h` beside the struct). *Overturned by:* the backend moving that work into its
|
||||
draw prep (e.g. Espryt applying `glPatchParameteri` from `SyncRenderState`), which is a G5
|
||||
byte-identical region and therefore not P5b's to touch.
|
||||
|
||||
3. **`resource_copy_region` is `glCopyImageSubData` and nothing else.** CONTRACT-P5 / the
|
||||
`FieldOwnership.def` header left "which of three verbs" to the emitting phase; P5b gives
|
||||
the two framebuffer-sourced copies their own row (76) because they have a different
|
||||
source (the read framebuffer, no handle) and a different shape (a level redefinition on
|
||||
the image form). *Overturned by:* nothing cheaper than a second stamp rule.
|
||||
|
||||
4. **`kCapNeedsHostIndexBytes` stays 0; the user-index span is armed anyway.** The cap is the
|
||||
server's request for VBO-backed index bytes (P8's mirror); the span is the client's only
|
||||
way to hand over bytes only it has. The two were conflated in CONTRACT-P5 table 0's cap-bit
|
||||
row ("the two bits are the only things that ask for [a span]") because P5 produced neither.
|
||||
*Overturned by:* a measured draw whose client-side index array exceeds what one staged
|
||||
run can hold at the default `SEG_STAGE` (32 MiB; the R-10 `maxrec=` counter is what would
|
||||
say so), at which point d1 chunks or refuses by size.
|
||||
|
||||
5. **One new cap bit, `kCapBackendOwnsXfbCapture` (1<<9).** The `EndTransformFeedback !=
|
||||
nullptr` probe at `GL_Drawing.cpp:1290` decides whether the CLIENT reorders captured
|
||||
records; under split the answer is the SERVER's table, so it is a cap, set by the server
|
||||
from `GL.EndTransformFeedback != nullptr` and read through `MGL_BACKEND_SLOT_CAP`. It is the
|
||||
first of the "XFB span family" cap bits `SlotCaps.h` said would come; t2 adds it to
|
||||
`MGPCapBit` (c0b's file, granted for this bit) in the same commit that flips the probe.
|
||||
*Overturned by:* Magma registering `EndTransformFeedback`, which removes the difference.
|
||||
|
||||
6. **`MGPCopyRegion` widens 64 → 72 for two GL names.** A record with no producer and no
|
||||
consumer has no wire history to preserve; the names are the barrier-pulled lookup keys
|
||||
the P5b sink needs and the handles beside them are the identities P7 will use.
|
||||
*Overturned by:* P7 landing handle-keyed endpoints, when the two fields become padding
|
||||
again (and stay in the layout - a shrink would move every field behind them).
|
||||
|
||||
7. **Renderbuffer endpoints, unbound DSA clears and multi-draws with client-side indices are
|
||||
refused BY NAME, ID-57's shape.** Each is a form no barrier-pulled forward can serve, none
|
||||
was measured, and a named Fatal at the client or sink is the outcome R-4 asks for; a
|
||||
silently wrong picture is the one it forbids. *Overturned by:* a measured workload hitting
|
||||
one, which then gets its P7/P8 mechanism moved forward.
|
||||
|
||||
8. **The `copy-image-shadow-mirror` site is skipped under split; the two mipmap emulation
|
||||
sites stay Fatal.** The mirror's loss is bounded by two other Fatals (§2 i1); the mipmap
|
||||
storage grow may be re-derived from the descriptor, the CPU fallback cannot be without
|
||||
`OnTextureWriteback`. *Overturned by:* a measured `GetTexImage` of a copy destination
|
||||
before P9's readback carrier lands - which would show as the wave-3 `GetTexImage` Fatal
|
||||
anyway.
|
||||
|
||||
9. **`GetProgramForDispatch` moves FATAL → BARRIER_PULLED.** §3. *Overturned by:* nothing;
|
||||
the FATAL class was a statement about the reduced path, and P5b widens the path.
|
||||
|
||||
10. **The emit table's class-C list is partitioned per package** (`EmitTables.cpp`:
|
||||
`MGR_UNMIGRATED_{D1,I1,T2,F1,TAIL}_SLOTS`, `kEmittedSlots{D1,I1,T2,F1}`, five ownership
|
||||
`static_assert`s: 19 / 7 / 7 / 11 / 20 = 64). Four packages editing one X-macro list and
|
||||
one count would conflict on every landing; four lists and four counts do not, and a
|
||||
package that touches another's list breaks the other's assertion. *Overturned by:*
|
||||
nothing - it is arithmetic, and the totals `UnmigratedSlotCount() == 64` /
|
||||
`ImplementedVerbCount() == 5` the P5 tests pin are unchanged on this head.
|
||||
|
||||
11. **The server stubs are `Fatal{UnmigratedVerb, "<GL slot>"}`, the same family and name
|
||||
as the client's**, suffixed "(server sink)" in the message text only. A client flipped
|
||||
ahead of its server half therefore aborts under the census's own grep with the right
|
||||
slot name, and the lane's first-blocker table stays meaningful across a partial landing.
|
||||
*Overturned by:* nothing.
|
||||
|
||||
12. **Client-side vertex arrays are not a P5b question.** They are served on the server
|
||||
through the barrier-pulled `GetBoundVertexArray` (CONTRACT-P5 table 2, "P8"), correct
|
||||
under inproc by the barrier and the shared address space, and retired by P8's
|
||||
`HostResolve.cpp`. *Overturned by:* P6's spawn transport - which is after P5b by ID-68.
|
||||
|
||||
---
|
||||
|
||||
## §7 The 71 slots after P5b's contract commit, and after the four packages
|
||||
|
||||
On this head the partition is CONTRACT-P5 §7's, unchanged: **A = 2, B = 5, C = 64**
|
||||
(`RemoteClientTest` pins it). When the four packages land it is **A = 2, B = 5 + 25 (+ the
|
||||
companions each package flips, up to 44), C = the wave-3 tail (20 at least)**, and the
|
||||
`static_assert`s in `EmitTables.cpp` say which package moved which slot.
|
||||
|
||||
The wave-3 tail no P5b package owns, by name, so nobody discovers it by grep: `BlitNamedFramebuffer`,
|
||||
`GetTexImage`, `GetTextureImage`, `WaitSync`, `DeleteSync`, `FenceSync`, `ClientWaitSync`,
|
||||
`GetSyncStatus`, `BeginTimeElapsedQuery`, `EndTimeElapsedQuery`, `QueryCounterTimestamp`,
|
||||
`IsQueryResultAvailable`, `GetQueryResult64`, `DeleteBackendQuery`, `BeginOcclusionQuery`,
|
||||
`EndOcclusionQuery`, `BeginXfbPrimitivesQuery`, `EndXfbPrimitivesQuery`, `GetGpuTimestampNs`,
|
||||
`SetSwapInterval` - P9 (readbacks), P10 (queries, syncs, swap interval).
|
||||
|
||||
---
|
||||
|
||||
## §8 Ownership
|
||||
|
||||
- `MG_Pipe/MGPipeTypes.h`, the three `.def` files, `FieldOwnership.def`, `gen_pipe*.py`,
|
||||
`CONTRACT-P5.md`, `CONTRACT-P5B.md`: c0b's (inherited from c0). A package that needs a payload
|
||||
shape changed goes through the integrator. Two grants are pre-made in this file: t2 may add
|
||||
`kCapBackendOwnsXfbCapture` (§6.5); i1 may edit `GetProgramForDispatch`'s row (§6.9).
|
||||
- `MG_Remote/Wire/PipeWireCodec.{h,cpp}`: w1's; c0b landed the sink methods and the arms; a
|
||||
package edits ONLY the layout arm of a row it owns, and only with the integrator.
|
||||
- `MG_Remote/Server/PipeApplier.{h,cpp}`: v1's; each package replaces ITS stub bodies and
|
||||
nothing else (the per-package blocks are marked).
|
||||
- `MG_Remote/Client/EmitTables.{h,cpp}`: c1's; each package edits ITS `MGR_UNMIGRATED_*_SLOTS`
|
||||
list, ITS `kEmittedSlots*`, and adds ITS emitters in the class-B block.
|
||||
- `MG_Test/Wire/PipeWireCodecTest.cpp`: each package appends cases for its rows below c0b's.
|
||||
- The backends (`MG_Backend/DirectGLES`, `DirectVulkan`): untouched by c0b; a package that
|
||||
must touch one does so behind `#if MOBILEGL_BUILD_DISAGGREGATED` and names the region in
|
||||
its report (G1 admits no pull-build symbol motion; G5's untouched regions are pinned).
|
||||
@@ -6,11 +6,41 @@
|
||||
// SPDX-License-Identifier: LGPL-3.0-only
|
||||
// End of Source File Header
|
||||
|
||||
// P5 package w1: MGPCaps's two blob serializers, the pair MGPipeTypes.h:134-136 defers to
|
||||
// this phase by name ("Their serializers land with the transport (P5)").
|
||||
//
|
||||
// THE FORMAT, and every part of it is a refusal rather than a guess. It is
|
||||
// ProgramArtifactsCodec's shape on purpose - that codec is the tree's one worked example of a
|
||||
// wire format that has survived a real transport, so copying it is cheaper than being
|
||||
// original and much cheaper than being wrong:
|
||||
//
|
||||
// * a VERSION word first, and the two TABLE DIMENSIONS second, so a peer whose
|
||||
// TextureInternalFormat enum grew is a mismatch AT READ TIME rather than a silent shear
|
||||
// that reads one format's capabilities as another's;
|
||||
// * length-prefixed everything, with the count checked against the bytes that REMAIN before
|
||||
// a single element is reserved, so a corrupt count cannot become a four-billion-element
|
||||
// resize;
|
||||
// * SPARSE for all three capability tables. The dense form is
|
||||
// 2 * targets * formats * 8 bytes plus the sample-count lists - with 13 targets and 77
|
||||
// internal formats that is ~16 KiB of mostly zeroes, PER CONTEXT AND PER CAPS
|
||||
// INVALIDATION, because R-12 makes a re-arriving snapshot the invalidation rather than a
|
||||
// once-per-process cost. The tables are overwhelmingly empty, so what crosses is
|
||||
// (index, value) pairs and the decoder Clear()s first;
|
||||
// * little-endian by memcpy of fixed-width scalars, which is what every other MobileGL wire
|
||||
// struct already assumes and what the ABI fingerprint below makes checkable;
|
||||
// * every decoder returns FALSE on truncation, a bad version, a dimension mismatch, an
|
||||
// out-of-range index or TRAILING BYTES THE FORMAT DOES NOT ACCOUNT FOR. These bytes
|
||||
// arrive over a wire and the outputs are left in a defined, default state on a refusal.
|
||||
|
||||
#include "CapsCodec.h"
|
||||
|
||||
#include "Protocol/mg_protocol_base.h"
|
||||
|
||||
#include <MGGitHash.h>
|
||||
#include <MG_Util/Debug/Log.h>
|
||||
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
|
||||
namespace MobileGL::MG_Remote {
|
||||
|
||||
@@ -29,28 +59,433 @@ namespace MobileGL::MG_Remote {
|
||||
static_assert(MG_Pipe::kMGPipeSubsystemsMigratedAtP4a <= 0xFFFFull,
|
||||
"the subsystem mask no longer fits CallMask's sixteen consumer bits");
|
||||
|
||||
#define MGP5_C0_STUB(what) \
|
||||
do { \
|
||||
MGLOG_F("MGPipe: Fatal{UnimplementedCapsCodec, \"%s\"} - P5 package w1 has not landed " \
|
||||
"this yet; c0 shipped the signature only", \
|
||||
what); \
|
||||
std::abort(); \
|
||||
} while (0)
|
||||
namespace {
|
||||
|
||||
Bool EncodeFormatCapabilities(const MG_Backend::FormatCapabilityCache&, Vector<Uint8>&) {
|
||||
MGP5_C0_STUB("EncodeFormatCapabilities");
|
||||
// Bumped whenever the bytes change in a way a previous reader would misread. A reader
|
||||
// that sees a different word REFUSES; it never tries to guess a layout.
|
||||
constexpr Uint32 kFormatCapabilitiesCodecVersion = 1;
|
||||
constexpr Uint32 kRendererInfoCodecVersion = 1;
|
||||
|
||||
// A count is never believed before it is weighed against the bytes that are left. The
|
||||
// largest legal element count in either blob is bounded by the tables' own dimensions,
|
||||
// but a String's length is not, so the reader checks bytes rather than a constant.
|
||||
class Writer {
|
||||
public:
|
||||
explicit Writer(Vector<Uint8>& out) : m_out(out) {}
|
||||
|
||||
void Raw(const void* bytes, SizeT size) {
|
||||
if (size == 0) {
|
||||
return;
|
||||
}
|
||||
const auto* p = static_cast<const Uint8*>(bytes);
|
||||
m_out.insert(m_out.end(), p, p + size);
|
||||
}
|
||||
void U8(Uint8 v) { Raw(&v, sizeof(v)); }
|
||||
void U32(Uint32 v) { Raw(&v, sizeof(v)); }
|
||||
void U64(Uint64 v) { Raw(&v, sizeof(v)); }
|
||||
void I32(Int32 v) { Raw(&v, sizeof(v)); }
|
||||
void Str(const String& s) {
|
||||
U32(static_cast<Uint32>(s.size()));
|
||||
Raw(s.data(), s.size());
|
||||
}
|
||||
void OptStr(const Optional<String>& s) {
|
||||
U8(s.has_value() ? 1u : 0u);
|
||||
if (s.has_value()) {
|
||||
Str(*s);
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
Vector<Uint8>& m_out;
|
||||
};
|
||||
|
||||
class Reader {
|
||||
public:
|
||||
Reader(const void* bytes, Uint64 size)
|
||||
: m_p(static_cast<const Uint8*>(bytes)), m_left(bytes != nullptr ? size : 0) {}
|
||||
|
||||
Bool Raw(void* out, Uint64 size) {
|
||||
if (!m_ok || size > m_left) {
|
||||
m_ok = false;
|
||||
return false;
|
||||
}
|
||||
std::memcpy(out, m_p, static_cast<SizeT>(size));
|
||||
m_p += size;
|
||||
m_left -= size;
|
||||
return true;
|
||||
}
|
||||
Bool U8(Uint8& v) { return Raw(&v, sizeof(v)); }
|
||||
Bool U32(Uint32& v) { return Raw(&v, sizeof(v)); }
|
||||
Bool U64(Uint64& v) { return Raw(&v, sizeof(v)); }
|
||||
Bool I32(Int32& v) { return Raw(&v, sizeof(v)); }
|
||||
Bool Str(String& s) {
|
||||
Uint32 length = 0;
|
||||
if (!U32(length)) {
|
||||
return false;
|
||||
}
|
||||
// THE CHECK THAT MATTERS: the count is weighed against the bytes that remain
|
||||
// BEFORE the string is sized, so a corrupt length is a refusal rather than a
|
||||
// four-gigabyte allocation.
|
||||
if (length > m_left) {
|
||||
m_ok = false;
|
||||
return false;
|
||||
}
|
||||
s.assign(reinterpret_cast<const char*>(m_p), static_cast<SizeT>(length));
|
||||
m_p += length;
|
||||
m_left -= length;
|
||||
return true;
|
||||
}
|
||||
Bool OptStr(Optional<String>& s) {
|
||||
Uint8 present = 0;
|
||||
if (!U8(present)) {
|
||||
return false;
|
||||
}
|
||||
if (present == 0) {
|
||||
s.reset();
|
||||
return true;
|
||||
}
|
||||
String value;
|
||||
if (!Str(value)) {
|
||||
return false;
|
||||
}
|
||||
s = Move(value);
|
||||
return true;
|
||||
}
|
||||
// How many elements of `elementBytes` could still possibly be there. The gate a
|
||||
// length-prefixed array is held to before it reserves anything.
|
||||
Uint64 RoomFor(Uint64 elementBytes) const {
|
||||
return elementBytes == 0 ? 0 : m_left / elementBytes;
|
||||
}
|
||||
Bool Ok() const { return m_ok; }
|
||||
Uint64 Left() const { return m_left; }
|
||||
// Trailing bytes the format does not account for are a REFUSAL: they mean the
|
||||
// writer and the reader disagree about the shape, and the half that was read is
|
||||
// not trustworthy just because it parsed.
|
||||
Bool Finished() const { return m_ok && m_left == 0; }
|
||||
|
||||
private:
|
||||
const Uint8* m_p = nullptr;
|
||||
Uint64 m_left = 0;
|
||||
Bool m_ok = true;
|
||||
};
|
||||
|
||||
using MG_Backend::FormatCapabilityCache;
|
||||
using MG_Backend::FormatCapabilityFlags;
|
||||
|
||||
constexpr Uint64 kFormatCells = static_cast<Uint64>(MG_Backend::kFormatCapabilityTargetCount) *
|
||||
static_cast<Uint64>(MG_Backend::kFormatCapabilityFormatCount);
|
||||
|
||||
} // namespace
|
||||
|
||||
// ---------------------------------------------------------------------------------
|
||||
// FormatCapabilityCache
|
||||
// ---------------------------------------------------------------------------------
|
||||
|
||||
Bool EncodeFormatCapabilities(const FormatCapabilityCache& cache, Vector<Uint8>& out) {
|
||||
Writer w(out);
|
||||
w.U32(kFormatCapabilitiesCodecVersion);
|
||||
w.U32(static_cast<Uint32>(MG_Backend::kFormatCapabilityTargetCount));
|
||||
w.U32(static_cast<Uint32>(MG_Backend::kFormatCapabilityFormatCount));
|
||||
w.U32(0); // reserved, keeps the header 16 bytes and 8-aligned for the pairs below
|
||||
|
||||
// The two flag tables, sparse. A cell is written only when it is non-zero, so what
|
||||
// crosses is proportional to what the driver actually supports rather than to the
|
||||
// square of two enum spaces.
|
||||
const auto writeTable = [&](const MG_Backend::FormatCapabilityTable& table) {
|
||||
Uint32 populated = 0;
|
||||
for (SizeT t = 0; t < MG_Backend::kFormatCapabilityTargetCount; ++t) {
|
||||
for (SizeT f = 0; f < MG_Backend::kFormatCapabilityFormatCount; ++f) {
|
||||
if (table[t][f].GetRaw() != 0) {
|
||||
++populated;
|
||||
}
|
||||
}
|
||||
}
|
||||
w.U32(populated);
|
||||
for (SizeT t = 0; t < MG_Backend::kFormatCapabilityTargetCount; ++t) {
|
||||
for (SizeT f = 0; f < MG_Backend::kFormatCapabilityFormatCount; ++f) {
|
||||
const Uint64 raw = static_cast<Uint64>(table[t][f].GetRaw());
|
||||
if (raw == 0) {
|
||||
continue;
|
||||
}
|
||||
w.U32(static_cast<Uint32>(t * MG_Backend::kFormatCapabilityFormatCount + f));
|
||||
w.U64(raw);
|
||||
}
|
||||
}
|
||||
};
|
||||
writeTable(cache.FullCaps);
|
||||
writeTable(cache.CaveatCaps);
|
||||
|
||||
// The sample-count lists: the Vector<Int> that is the reason this cannot be a memcpy.
|
||||
Uint32 populated = 0;
|
||||
for (SizeT t = 0; t < MG_Backend::kFormatCapabilityTargetCount; ++t) {
|
||||
for (SizeT f = 0; f < MG_Backend::kFormatCapabilityFormatCount; ++f) {
|
||||
if (!cache.SampleCounts[t][f].empty()) {
|
||||
++populated;
|
||||
}
|
||||
}
|
||||
}
|
||||
w.U32(populated);
|
||||
for (SizeT t = 0; t < MG_Backend::kFormatCapabilityTargetCount; ++t) {
|
||||
for (SizeT f = 0; f < MG_Backend::kFormatCapabilityFormatCount; ++f) {
|
||||
const Vector<Int>& counts = cache.SampleCounts[t][f];
|
||||
if (counts.empty()) {
|
||||
continue;
|
||||
}
|
||||
w.U32(static_cast<Uint32>(t * MG_Backend::kFormatCapabilityFormatCount + f));
|
||||
w.U32(static_cast<Uint32>(counts.size()));
|
||||
for (const Int value : counts) {
|
||||
w.I32(static_cast<Int32>(value));
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
Bool DecodeFormatCapabilities(const void*, Uint64, MG_Backend::FormatCapabilityCache&) {
|
||||
MGP5_C0_STUB("DecodeFormatCapabilities");
|
||||
Bool DecodeFormatCapabilities(const void* bytes, Uint64 size, FormatCapabilityCache& out) {
|
||||
out.Clear();
|
||||
Reader r(bytes, size);
|
||||
|
||||
Uint32 version = 0;
|
||||
Uint32 targets = 0;
|
||||
Uint32 formats = 0;
|
||||
Uint32 reserved = 0;
|
||||
if (!r.U32(version) || !r.U32(targets) || !r.U32(formats) || !r.U32(reserved)) {
|
||||
return false;
|
||||
}
|
||||
if (version != kFormatCapabilitiesCodecVersion) {
|
||||
MGLOG_E("MG_Remote caps: format-capability blob is version %u, this build reads %u",
|
||||
version, kFormatCapabilitiesCodecVersion);
|
||||
return false;
|
||||
}
|
||||
if (targets != MG_Backend::kFormatCapabilityTargetCount ||
|
||||
formats != MG_Backend::kFormatCapabilityFormatCount) {
|
||||
// Not a corrupt stream: a peer whose TextureTarget or TextureInternalFormat enum
|
||||
// is a different size. Reading it anyway shears every cell onto a neighbouring
|
||||
// format, which is exactly the failure the ABI fingerprint exists to make loud.
|
||||
MGLOG_E("MG_Remote caps: format-capability blob is %ux%u, this build is %llux%llu",
|
||||
targets, formats,
|
||||
static_cast<unsigned long long>(MG_Backend::kFormatCapabilityTargetCount),
|
||||
static_cast<unsigned long long>(MG_Backend::kFormatCapabilityFormatCount));
|
||||
return false;
|
||||
}
|
||||
|
||||
const auto readTable = [&](MG_Backend::FormatCapabilityTable& table) -> Bool {
|
||||
Uint32 populated = 0;
|
||||
if (!r.U32(populated)) {
|
||||
return false;
|
||||
}
|
||||
if (populated > r.RoomFor(sizeof(Uint32) + sizeof(Uint64))) {
|
||||
return false;
|
||||
}
|
||||
for (Uint32 i = 0; i < populated; ++i) {
|
||||
Uint32 index = 0;
|
||||
Uint64 raw = 0;
|
||||
if (!r.U32(index) || !r.U64(raw)) {
|
||||
return false;
|
||||
}
|
||||
if (static_cast<Uint64>(index) >= kFormatCells) {
|
||||
return false;
|
||||
}
|
||||
table[index / MG_Backend::kFormatCapabilityFormatCount]
|
||||
[index % MG_Backend::kFormatCapabilityFormatCount] =
|
||||
FormatCapabilityFlags(raw);
|
||||
}
|
||||
return true;
|
||||
};
|
||||
if (!readTable(out.FullCaps) || !readTable(out.CaveatCaps)) {
|
||||
out.Clear();
|
||||
return false;
|
||||
}
|
||||
|
||||
Uint32 populated = 0;
|
||||
if (!r.U32(populated) || populated > r.RoomFor(2 * sizeof(Uint32))) {
|
||||
out.Clear();
|
||||
return false;
|
||||
}
|
||||
for (Uint32 i = 0; i < populated; ++i) {
|
||||
Uint32 index = 0;
|
||||
Uint32 count = 0;
|
||||
if (!r.U32(index) || !r.U32(count)) {
|
||||
out.Clear();
|
||||
return false;
|
||||
}
|
||||
if (static_cast<Uint64>(index) >= kFormatCells || count > r.RoomFor(sizeof(Int32))) {
|
||||
out.Clear();
|
||||
return false;
|
||||
}
|
||||
Vector<Int>& counts = out.SampleCounts[index / MG_Backend::kFormatCapabilityFormatCount]
|
||||
[index % MG_Backend::kFormatCapabilityFormatCount];
|
||||
counts.resize(static_cast<SizeT>(count));
|
||||
for (Uint32 j = 0; j < count; ++j) {
|
||||
Int32 value = 0;
|
||||
if (!r.I32(value)) {
|
||||
out.Clear();
|
||||
return false;
|
||||
}
|
||||
counts[j] = static_cast<Int>(value);
|
||||
}
|
||||
}
|
||||
|
||||
if (!r.Finished()) {
|
||||
MGLOG_E("MG_Remote caps: format-capability blob has %llu trailing bytes the format "
|
||||
"does not account for",
|
||||
static_cast<unsigned long long>(r.Left()));
|
||||
out.Clear();
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
Bool EncodeRendererInfo(const RendererInfo&, Vector<Uint8>&) { MGP5_C0_STUB("EncodeRendererInfo"); }
|
||||
// ---------------------------------------------------------------------------------
|
||||
// RendererInfo
|
||||
// ---------------------------------------------------------------------------------
|
||||
|
||||
Bool DecodeRendererInfo(const void*, Uint64, RendererInfo&) { MGP5_C0_STUB("DecodeRendererInfo"); }
|
||||
namespace {
|
||||
|
||||
Uint64 CapsAbiFingerprint() { MGP5_C0_STUB("CapsAbiFingerprint"); }
|
||||
void WriteVersion(Writer& w, const Version& v) {
|
||||
w.I32(static_cast<Int32>(v.Major));
|
||||
w.I32(static_cast<Int32>(v.Minor));
|
||||
w.I32(static_cast<Int32>(v.Patch));
|
||||
w.OptStr(v.Suffix);
|
||||
w.U8(v.Type.has_value() ? 1u : 0u);
|
||||
w.U8(v.Type.has_value() ? static_cast<Uint8>(*v.Type) : 0u);
|
||||
}
|
||||
|
||||
#undef MGP5_C0_STUB
|
||||
Bool ReadVersion(Reader& r, Version& v) {
|
||||
Int32 major = 0;
|
||||
Int32 minor = 0;
|
||||
Int32 patch = 0;
|
||||
if (!r.I32(major) || !r.I32(minor) || !r.I32(patch)) {
|
||||
return false;
|
||||
}
|
||||
v.Major = static_cast<Int>(major);
|
||||
v.Minor = static_cast<Int>(minor);
|
||||
v.Patch = static_cast<Int>(patch);
|
||||
if (!r.OptStr(v.Suffix)) {
|
||||
return false;
|
||||
}
|
||||
Uint8 hasType = 0;
|
||||
Uint8 type = 0;
|
||||
if (!r.U8(hasType) || !r.U8(type)) {
|
||||
return false;
|
||||
}
|
||||
if (hasType != 0) {
|
||||
v.Type = static_cast<VersionType>(type);
|
||||
} else {
|
||||
v.Type.reset();
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
Bool EncodeRendererInfo(const RendererInfo& info, Vector<Uint8>& out) {
|
||||
Writer w(out);
|
||||
w.U32(kRendererInfoCodecVersion);
|
||||
w.Str(info.RendererName);
|
||||
w.Str(info.BackendName);
|
||||
w.OptStr(info.ExtraVendor);
|
||||
WriteVersion(w, info.RendererGLInfo.TargetGLVersion);
|
||||
WriteVersion(w, info.RendererGLInfo.TargetGLSLVersion);
|
||||
w.U32(static_cast<Uint32>(info.RendererGLInfo.Extensions.size()));
|
||||
for (const GLExtension extension : info.RendererGLInfo.Extensions) {
|
||||
w.U32(static_cast<Uint32>(extension));
|
||||
}
|
||||
w.U8(info.RendererGLInfo.IsCompatibilityProfile ? 1u : 0u);
|
||||
w.U8(info.StaticBackendCapability.AllowVSOnlyPrograms ? 1u : 0u);
|
||||
return true;
|
||||
}
|
||||
|
||||
Bool DecodeRendererInfo(const void* bytes, Uint64 size, RendererInfo& out) {
|
||||
out = RendererInfo{};
|
||||
Reader r(bytes, size);
|
||||
|
||||
Uint32 version = 0;
|
||||
if (!r.U32(version)) {
|
||||
return false;
|
||||
}
|
||||
if (version != kRendererInfoCodecVersion) {
|
||||
MGLOG_E("MG_Remote caps: renderer-info blob is version %u, this build reads %u", version,
|
||||
kRendererInfoCodecVersion);
|
||||
return false;
|
||||
}
|
||||
if (!r.Str(out.RendererName) || !r.Str(out.BackendName) || !r.OptStr(out.ExtraVendor) ||
|
||||
!ReadVersion(r, out.RendererGLInfo.TargetGLVersion) ||
|
||||
!ReadVersion(r, out.RendererGLInfo.TargetGLSLVersion)) {
|
||||
out = RendererInfo{};
|
||||
return false;
|
||||
}
|
||||
|
||||
Uint32 extensionCount = 0;
|
||||
if (!r.U32(extensionCount) || extensionCount > r.RoomFor(sizeof(Uint32))) {
|
||||
out = RendererInfo{};
|
||||
return false;
|
||||
}
|
||||
out.RendererGLInfo.Extensions.resize(static_cast<SizeT>(extensionCount));
|
||||
for (Uint32 i = 0; i < extensionCount; ++i) {
|
||||
Uint32 value = 0;
|
||||
if (!r.U32(value)) {
|
||||
out = RendererInfo{};
|
||||
return false;
|
||||
}
|
||||
out.RendererGLInfo.Extensions[i] = static_cast<GLExtension>(value);
|
||||
}
|
||||
|
||||
Uint8 compatibility = 0;
|
||||
Uint8 vsOnly = 0;
|
||||
if (!r.U8(compatibility) || !r.U8(vsOnly)) {
|
||||
out = RendererInfo{};
|
||||
return false;
|
||||
}
|
||||
out.RendererGLInfo.IsCompatibilityProfile = compatibility != 0;
|
||||
out.StaticBackendCapability.AllowVSOnlyPrograms = vsOnly != 0;
|
||||
|
||||
if (!r.Finished()) {
|
||||
MGLOG_E("MG_Remote caps: renderer-info blob has %llu trailing bytes the format does "
|
||||
"not account for",
|
||||
static_cast<unsigned long long>(r.Left()));
|
||||
out = RendererInfo{};
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------
|
||||
// The ABI assertion the handshake carries
|
||||
// ---------------------------------------------------------------------------------
|
||||
|
||||
Transport::AbiFingerprintInputs CapsAbiFingerprintInputs() {
|
||||
// MGPCaps has only a COMPOSITIONAL size assertion (MGPipeTypes.h:145-146) because
|
||||
// DynamicBackendParameters still carries SizeT and GLenum members - P0.5's fixed-width
|
||||
// rewrite did not happen and P5 does not do it either (table 0's ABI row; the rewrite
|
||||
// is P7's account). So the caps block's literal size IS ABI-dependent, and this
|
||||
// fingerprint is what turns that from a latent hazard into a named refusal.
|
||||
//
|
||||
// The git stamp is in it because two builds of the same sizes can still disagree about
|
||||
// a FIELD ORDER, which no sizeof can see; P6's spawn is same-machine and same-binary,
|
||||
// so it inherits this unchanged rather than needing a looser rule.
|
||||
Transport::AbiFingerprintInputs inputs;
|
||||
inputs.DynamicParamsSize = sizeof(MG_Backend::DynamicBackendParameters);
|
||||
inputs.CapsSize = sizeof(MG_Pipe::MGPCaps);
|
||||
inputs.FunctionTableSize = sizeof(MG_Backend::GLFunctionsTable);
|
||||
inputs.FormatCapabilityTargets = static_cast<Uint64>(MG_Backend::kFormatCapabilityTargetCount);
|
||||
inputs.FormatCapabilityFormats = static_cast<Uint64>(MG_Backend::kFormatCapabilityFormatCount);
|
||||
inputs.FormatCapabilitiesCodecVersion = kFormatCapabilitiesCodecVersion;
|
||||
inputs.RendererInfoCodecVersion = kRendererInfoCodecVersion;
|
||||
inputs.OpCount = static_cast<Uint64>(MG_Pipe::MGPWireOp::kOpCount);
|
||||
// The declared protocol ABI, carried over from s1's version of this function at
|
||||
// integration (ID-33). The sizeofs above catch a struct that changed shape; this
|
||||
// catches a peer that changed the PROTOCOL while every struct stayed the same size,
|
||||
// which is the one break the rest of the mix is blind to.
|
||||
inputs.AbiVersion =
|
||||
static_cast<Uint32>(MOBILEGL_ABI_VERSION(MOBILEGL_PROTOCOL_ABI_MAJOR, MOBILEGL_PROTOCOL_ABI_MINOR));
|
||||
inputs.BuildStamp = GIT_COMMIT_HASH_SHORT;
|
||||
return inputs;
|
||||
}
|
||||
|
||||
// ONE implementation, deliberately a one-liner: the wave-1 review (ID-46 finding 6) found a
|
||||
// second hand-rolled FNV loop here while the mixer under Transport/ had no production caller,
|
||||
// so the sensitivity test could not see this function change. Now it starts from here.
|
||||
Uint64 CapsAbiFingerprint() { return Transport::MixAbiFingerprint(CapsAbiFingerprintInputs()); }
|
||||
|
||||
} // namespace MobileGL::MG_Remote
|
||||
|
||||
@@ -34,6 +34,8 @@
|
||||
#include <MG_Backend/BackendObject.h>
|
||||
#include <MG_Pipe/MGPipe.h>
|
||||
|
||||
#include "Transport/SessionRings.h" // AbiFingerprintInputs / MixAbiFingerprint
|
||||
|
||||
namespace MobileGL::MG_Remote {
|
||||
|
||||
// ---- CallMask's layout (c0's ruling, extending R-8) ---------------------------------
|
||||
@@ -90,10 +92,17 @@ namespace MobileGL::MG_Remote {
|
||||
|
||||
// ---- the ABI assertion the handshake carries ----------------------------------------
|
||||
//
|
||||
// Mixes sizeof(DynamicBackendParameters), sizeof(MGPCaps), sizeof(GLFunctionsTable) and
|
||||
// the compile-time build fingerprint. Compared in Hello/Welcome; a mismatch is
|
||||
// Fatal{AbiMismatch} and never a downgrade, because every alternative silently reads one
|
||||
// struct as another.
|
||||
// The inputs, as this build sees them: sizeof(DynamicBackendParameters), sizeof(MGPCaps),
|
||||
// sizeof(GLFunctionsTable), the format-capability table's extents, the two caps-blob codec
|
||||
// versions, MGPWireOp::kOpCount, the protocol ABI version and the compile-time git stamp.
|
||||
// Public so that the sensitivity control can pin every one of them to the real value AND
|
||||
// perturb them one at a time through the same mixer the handshake uses.
|
||||
Transport::AbiFingerprintInputs CapsAbiFingerprintInputs();
|
||||
|
||||
// What Hello/Welcome carry and compare: EXACTLY Transport::MixAbiFingerprint(
|
||||
// CapsAbiFingerprintInputs()) - one implementation, no second hash (ID-46 finding 6). A
|
||||
// mismatch is Fatal{AbiMismatch} and never a downgrade, because every alternative silently
|
||||
// reads one struct as another.
|
||||
Uint64 CapsAbiFingerprint();
|
||||
|
||||
} // namespace MobileGL::MG_Remote
|
||||
|
||||
@@ -0,0 +1,282 @@
|
||||
// MobileGL - MobileGL/MG_Remote/Client/BackendObject_Remote.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
|
||||
|
||||
// P5 package c1. See BackendObject_Remote.h for the three traps and why each is paid here.
|
||||
|
||||
#include "BackendObject_Remote.h"
|
||||
|
||||
#include "CapsMirror.h"
|
||||
#include "ClientSession.h"
|
||||
#include "EmitTables.h"
|
||||
|
||||
#include "../Server/ServerLoop.h"
|
||||
|
||||
#include <MG_Util/Debug/Log.h>
|
||||
|
||||
// Declared rather than included: MG_Backend/BackendObjects.h drags in both concrete backend
|
||||
// objects, and this translation unit must not depend on either - the client role links the same
|
||||
// library but never constructs one.
|
||||
namespace MobileGL::MG_Backend {
|
||||
extern UniquePtr<BackendObject>& pActiveBackendObject;
|
||||
}
|
||||
|
||||
namespace MobileGL::MG_Remote::Client {
|
||||
|
||||
namespace {
|
||||
|
||||
// ---- the EGL seam ------------------------------------------------------------------
|
||||
//
|
||||
// THE NINE EGL VIRTUALS CALL v1's TWELVE FORWARDERS AND NOTHING ELSE. c1 round 1 built
|
||||
// its own trampolines over ServerLoop::RunOnApplyThread and ServerLoop::Backend(),
|
||||
// which ran the right driver call on the right thread and was still wrong, because
|
||||
// three of the twelve do MORE than forward:
|
||||
//
|
||||
// ServerMakeEGLCurrent re-publishes the caps snapshot after the server's own
|
||||
// InitCapabilities has run (R-12 arm (a))
|
||||
// ServerInitCapabilities the same, on the explicit path
|
||||
// ServerSetWindowHandle hands the surface to the server's backend
|
||||
//
|
||||
// Calling `Backend()->MakeEGLCurrent(...)` skips the republish, so the client's mirror
|
||||
// keeps the snapshot Accept() sent BEFORE any context existed - every limit, every
|
||||
// advertised extension and the compile-env fingerprint read off an empty backend, with
|
||||
// InitCapabilities below happily reporting success because a snapshot did arrive once.
|
||||
// That is the failure this seam exists to make impossible: there is no second route to
|
||||
// the server's EGL, so there is no route that can skip what the forwarder does.
|
||||
//
|
||||
// The forwarders block on mgl-srv-apply themselves and run INLINE when the caller is
|
||||
// already on that thread, so this file no longer needs RunOnApplyThread, a per-call
|
||||
// args struct, or a null-backend check of its own - ServerBackendOrNull() inside each
|
||||
// forwarder is the one place that answers "the bring-up did not complete", and it
|
||||
// answers `false` rather than crashing or succeeding locally.
|
||||
|
||||
// CapsMirror's adoption hook. A free function because the hook is a raw function
|
||||
// pointer (ID-8: this can fire on a path that must not allocate), and it reaches the
|
||||
// live object through pActiveBackendObject rather than through a second global.
|
||||
void OnCapsAdopted() {
|
||||
auto* self = dynamic_cast<BackendObject_Remote*>(MG_Backend::pActiveBackendObject.get());
|
||||
if (self != nullptr) self->RefreshFormatCapabilities();
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
BackendObject_Remote::BackendObject_Remote() {
|
||||
// Installed in the constructor rather than at the first snapshot, because the first
|
||||
// snapshot has usually already arrived by then: ClientSession::Start pumps the control
|
||||
// plane during the handshake, and MG_Backend::Init() constructs this object after it.
|
||||
// RefreshFormatCapabilities below picks up that already-adopted generation.
|
||||
SetCapsAdoptedHook(&OnCapsAdopted);
|
||||
RefreshFormatCapabilities();
|
||||
}
|
||||
|
||||
BackendObject_Remote::~BackendObject_Remote() {
|
||||
// The hook holds a raw function pointer, not a pointer to this - but the function it
|
||||
// names reaches pActiveBackendObject, which is being destroyed right now. Uninstall.
|
||||
SetCapsAdoptedHook(nullptr);
|
||||
}
|
||||
|
||||
void BackendObject_Remote::RefreshFormatCapabilities() {
|
||||
CapsMirror& mirror = CapsMirrorInstance();
|
||||
if (!mirror.Valid() || mirror.Generation() == m_formatsGeneration) return;
|
||||
// TRAP 2. GetFormatCapabilities() is non-virtual and hands back this member, so the
|
||||
// only way a remote object can answer it is to fill it.
|
||||
MutableFormatCapabilities() = mirror.Formats();
|
||||
m_formatsGeneration = mirror.Generation();
|
||||
MGLOG_I("MG_Remote client: format capabilities filled from caps mirror generation %llu",
|
||||
static_cast<unsigned long long>(m_formatsGeneration));
|
||||
}
|
||||
|
||||
// ---- the eight pure virtuals ----------------------------------------------------------
|
||||
|
||||
void BackendObject_Remote::Initialize() {
|
||||
// NOT FORWARDED. The server's own BackendObject_DirectGLES is created and initialised
|
||||
// by v1's ServerLoop, on the apply thread, before this object exists; forwarding here
|
||||
// would be a second Initialize() on an already-initialised backend. What this call
|
||||
// does is drain whatever the handshake left and take the caps that came with it.
|
||||
if (ClientSession* session = ClientSession::Active()) {
|
||||
session->PumpControlPlane();
|
||||
}
|
||||
RefreshFormatCapabilities();
|
||||
}
|
||||
|
||||
Bool BackendObject_Remote::InitCapabilities() {
|
||||
// Reached from the base class's MakeEGLCurrent, lazily, once per surface lifetime
|
||||
// (BackendObject.cpp:341-347). By this point MakeEGLCurrent below has already run the
|
||||
// SERVER's MakeEGLCurrent on the apply thread, whose own base class ran the server
|
||||
// backend's InitCapabilities and whose ServerSession re-published the snapshot - so
|
||||
// the client's job here is to pick that snapshot up. R-12: re-arrival IS the
|
||||
// invalidation, and this is the second place it is drained (the other is Present).
|
||||
ClientSession* session = ClientSession::Active();
|
||||
if (session == nullptr) {
|
||||
MGLOG_E("MG_Remote client: InitCapabilities with no session");
|
||||
return false;
|
||||
}
|
||||
// ASK THE SERVER RATHER THAN ASSUMING ServerMakeEGLCurrent HAS ALREADY ASKED IT. The
|
||||
// comment above says "by this point MakeEGLCurrent has already run the SERVER's
|
||||
// MakeEGLCurrent", and that is true on the make-current path - but the base class
|
||||
// reaches InitCapabilities lazily, once per SURFACE lifetime, and a surface can be
|
||||
// replaced without a new make-current. ServerInitCapabilities re-publishes the
|
||||
// snapshot the same way, so asking twice costs one snapshot and never asking costs
|
||||
// every limit in the mirror. It is idempotent on the server's side.
|
||||
if (!Server::ServerInitCapabilities()) {
|
||||
MGLOG_E("MG_Remote client: the server's InitCapabilities failed, so there is no "
|
||||
"snapshot to adopt and going current would read default limits");
|
||||
return false;
|
||||
}
|
||||
session->PumpControlPlane();
|
||||
RefreshFormatCapabilities();
|
||||
// A PLACEHOLDER MIRROR IS A FAILURE HERE, unlike at startup. LogBackendInfo reading a
|
||||
// placeholder costs one wrong log line; a context going current on one costs every
|
||||
// limit, every advertised extension and the compile-env fingerprint.
|
||||
if (!CapsMirrorInstance().Valid()) {
|
||||
MGLOG_E("MG_Remote client: InitCapabilities found no CapsSnapshot - the server has "
|
||||
"not published one. Going current on a placeholder caps mirror would put "
|
||||
"default limits into every glGetIntegerv answer and into the compile env");
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
Bool BackendObject_Remote::InitWindowSurface() {
|
||||
// The real surface work happened on the apply thread inside the server backend's own
|
||||
// ActivateEGLSurface; this is the client's half of the base state machine and has
|
||||
// nothing of its own to do.
|
||||
return true;
|
||||
}
|
||||
|
||||
Bool BackendObject_Remote::InitPbufferSurface(EGLint, EGLint) { return true; }
|
||||
|
||||
const RendererInfo& BackendObject_Remote::GetRendererInfo() const {
|
||||
// TRAP 1: a reference, so the storage is the mirror's and not a temporary's.
|
||||
return CapsMirrorInstance().Renderer();
|
||||
}
|
||||
|
||||
String BackendObject_Remote::GetBackendAPIVersionString() const {
|
||||
return CapsMirrorInstance().ApiVersion();
|
||||
}
|
||||
|
||||
const MG_Backend::GlobalBackendFunctionsTable& BackendObject_Remote::GetBackendFunctions() const {
|
||||
return RemoteEmitTable();
|
||||
}
|
||||
|
||||
const MG_Backend::DynamicBackendParameters& BackendObject_Remote::GetDynamicParameters() const {
|
||||
return CapsMirrorInstance().Dynamic();
|
||||
}
|
||||
|
||||
BackendType BackendObject_Remote::GetBackendType() const {
|
||||
// TRAP 3: the SERVER's backend, never a new enumerator.
|
||||
return CapsMirrorInstance().Backend();
|
||||
}
|
||||
|
||||
// ---- the nine EGL lifecycle virtuals ---------------------------------------------------
|
||||
//
|
||||
// FORWARD FIRST, THEN RUN THE BASE. The server has to own the context before the client's
|
||||
// base class latches "the surface is initialised" and calls InitCapabilities, because
|
||||
// InitCapabilities' answer comes from a snapshot the server can only publish once its own
|
||||
// InitCapabilities has run.
|
||||
|
||||
Bool BackendObject_Remote::InitializeEGLDisplay(EGLDisplay dpy, EGLint* major, EGLint* minor) {
|
||||
if (!Server::ServerInitializeEGLDisplay(dpy, major, minor)) return false;
|
||||
return MG_Backend::BackendObject::InitializeEGLDisplay(dpy, major, minor);
|
||||
}
|
||||
|
||||
Bool BackendObject_Remote::CreateEGLWindowSurface(EGLSurface surface,
|
||||
const MG_Backend::WindowHandle& handle) {
|
||||
// The handle first: the server's backend has to know which window it is about to make
|
||||
// a surface for, and ServerSetWindowHandle is the only way to tell it.
|
||||
Server::ServerSetWindowHandle(handle);
|
||||
if (!Server::ServerCreateEGLWindowSurface(surface, handle)) return false;
|
||||
return MG_Backend::BackendObject::CreateEGLWindowSurface(surface, handle);
|
||||
}
|
||||
|
||||
Bool BackendObject_Remote::ResizeEGLWindowSurface(EGLSurface surface, Uint32 width, Uint32 height) {
|
||||
if (!Server::ServerResizeEGLWindowSurface(surface, width, height)) return false;
|
||||
return MG_Backend::BackendObject::ResizeEGLWindowSurface(surface, width, height);
|
||||
}
|
||||
|
||||
Bool BackendObject_Remote::CreateEGLPbufferSurface(EGLSurface surface, EGLint width, EGLint height) {
|
||||
if (!Server::ServerCreateEGLPbufferSurface(surface, width, height)) return false;
|
||||
return MG_Backend::BackendObject::CreateEGLPbufferSurface(surface, width, height);
|
||||
}
|
||||
|
||||
Bool BackendObject_Remote::MakeEGLCurrent(EGLDisplay dpy, EGLSurface draw, EGLSurface read,
|
||||
EGLContext ctx) {
|
||||
// FORWARD FIRST, THEN RUN THE BASE. The server has to own the context before the base
|
||||
// class latches "the surface is initialised" and calls InitCapabilities, because
|
||||
// InitCapabilities' answer comes from a snapshot the server can only publish once its
|
||||
// own InitCapabilities has run - and ServerMakeEGLCurrent is what publishes it.
|
||||
if (!Server::ServerMakeEGLCurrent(dpy, draw, read, ctx)) return false;
|
||||
if (!MG_Backend::BackendObject::MakeEGLCurrent(dpy, draw, read, ctx)) return false;
|
||||
|
||||
// R-12 ARM (a) ON EVERY SUCCESSFUL MAKE-CURRENT (codex 12). ServerMakeEGLCurrent above
|
||||
// republishes the caps snapshot on every call (ServerLoop.cpp:613-628), but the base
|
||||
// class only runs InitCapabilities - the one place that pumps and refreshes - on the
|
||||
// FIRST make-current per surface (BackendObject.cpp:341-347). A repeated make-current
|
||||
// onto an already-initialised surface therefore left the client mirror one generation
|
||||
// behind while unpumped snapshots accumulated, so a cap getter or a shader compile before
|
||||
// the next Present read the prior mirror. Adopting here closes that: "a second snapshot
|
||||
// arrival IS the invalidation" (R-12) now holds AT the make-current that caused it. It is
|
||||
// idempotent - on the first make-current InitCapabilities already pumped, so this adopts
|
||||
// 0 - and a release-current (draw/ctx cleared) publishes nothing and is skipped.
|
||||
if (draw != EGL_NO_SURFACE && ctx != EGL_NO_CONTEXT) {
|
||||
if (ClientSession* session = ClientSession::Active()) {
|
||||
session->PumpControlPlane();
|
||||
RefreshFormatCapabilities();
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
Bool BackendObject_Remote::SwapEGLBuffers(EGLDisplay dpy, EGLSurface draw) {
|
||||
// NOT FORWARDED, and this is the one that must not be. The base implementation's last
|
||||
// act is GetBackendFunctions().Present() (BackendObject.cpp:396) - which is this
|
||||
// client's class-B Present EMITTER, the only route by which Present is reached at all
|
||||
// (it has zero MG_Impl call sites). Calling Server::ServerSwapEGLBuffers would present
|
||||
// on the server directly and put no record on the wire, which is the shape every gate
|
||||
// in this phase exists to catch. The forwarder exists for a spawned P6 client whose
|
||||
// Present record cannot carry the swap; in P5 it has no caller and that is deliberate.
|
||||
return MG_Backend::BackendObject::SwapEGLBuffers(dpy, draw);
|
||||
}
|
||||
|
||||
void BackendObject_Remote::SetEGLSwapInterval(Int interval) {
|
||||
// OVERRIDDEN BECAUSE THE BASE WOULD FATAL. BackendObject.cpp:402 null-checks
|
||||
// GetBackendFunctions().SetSwapInterval and calls it when non-null - one of the 41
|
||||
// null checks R-4 turns into "always supported" - and SetSwapInterval is class C, so
|
||||
// the base implementation would abort on every eglSwapInterval. The answer is the
|
||||
// caps-mirror-read rule's general shape: the question "can the presentation path take
|
||||
// an interval" belongs to the server, so it is asked of the server.
|
||||
Server::ServerSetEGLSwapInterval(interval);
|
||||
}
|
||||
|
||||
void BackendObject_Remote::ReleaseEGLSurface(EGLSurface surface) {
|
||||
Server::ServerReleaseEGLSurface(surface);
|
||||
MG_Backend::BackendObject::ReleaseEGLSurface(surface);
|
||||
}
|
||||
|
||||
void BackendObject_Remote::ReleaseEGLResources() {
|
||||
// BLOCKING BY CONTRACT (ServerLoop.h's header note): MobileGL::Destroy()
|
||||
// (MobileGL/Init.cpp:68) walks on the moment this returns, and the server still holds
|
||||
// the context until the apply thread has run it.
|
||||
Server::ServerReleaseEGLResources();
|
||||
MG_Backend::BackendObject::ReleaseEGLResources();
|
||||
}
|
||||
|
||||
// NO strong CreateRemoteBackendObject() lives here, and the reason is a link fact, not an
|
||||
// oversight. v1's Init.cpp calls MG_Remote::Client::CreateRemoteBackendObject() and ships a
|
||||
// __attribute__((weak)) placeholder for it beside ServerLoop that aborts by name; its comment
|
||||
// expects "c1's strong definition [to] displace it at link time". A strong definition here
|
||||
// does NOT: libMobileGL is linked from a static archive, ServerLoop.o (weak) is already in
|
||||
// the link and satisfies Init's reference, and nothing else references this TU's
|
||||
// CreateRemoteBackendObject - so BackendObject_Remote.o is never pulled to override it, and
|
||||
// the weak's abort fires (measured: readelf shows one local symbol, the log shows
|
||||
// Fatal{UnimplementedRemoteBackendObject}). The integrator's Init.cpp hunk works because it
|
||||
// constructs BackendObject_Remote DIRECTLY (MakeUnique<BackendObject_Remote>), which both
|
||||
// references this object - forcing its TU into the link - and bypasses the weak symbol. So
|
||||
// the merge-time construction stays v1's Init.cpp edit (or a --whole-archive / forced
|
||||
// reference the integrator adds); see c1-v3.md.
|
||||
|
||||
} // namespace MobileGL::MG_Remote::Client
|
||||
@@ -0,0 +1,96 @@
|
||||
// MobileGL - MobileGL/MG_Remote/Client/BackendObject_Remote.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
|
||||
|
||||
// THE CLIENT ROLE'S BackendObject. Owner: package c1.
|
||||
//
|
||||
// MG_Backend::Init() installs one of these into pActiveBackendObject when the transport
|
||||
// resolved (the hook is v1's; the object is c1's, table 3). It is NOT a backend: it owns no
|
||||
// context, no driver and no GL state. It is the frontend's single answer to four questions -
|
||||
// "what can the device do", "what backend is it", "what table do I call", and the nine EGL
|
||||
// lifecycle calls - and each of the four is answered somewhere that is not here.
|
||||
//
|
||||
// THE THREE TRAPS THE SCOUT FOUND, AND WHERE EACH IS PAID:
|
||||
//
|
||||
// 1. GetRendererInfo() RETURNS A REFERENCE (BackendObject.h:590), so the object cannot
|
||||
// synthesise one per call. CapsMirror owns the storage; this class forwards. And
|
||||
// LogBackendInfo() reads it at MG_Backend/Init.cpp:21, DURING MG_Backend::Init(), before
|
||||
// any surface exists - so the mirror answers a placeholder and P5 accepts one imprecise
|
||||
// startup log line. MG_Backend::Init() is NOT restructured (scout-caps-reply §1.2 (a)).
|
||||
//
|
||||
// 2. GetFormatCapabilities() IS NOT VIRTUAL (BackendObject.h:594). It returns the base class's
|
||||
// own m_formatCapabilities member, so there is no accessor to override: the cache has to be
|
||||
// PUSHED into that member, and the only moment this object can know to is when a snapshot
|
||||
// lands. CapsMirror's adoption hook is that moment.
|
||||
//
|
||||
// 3. GetBackendType() MUST ANSWER THE SERVER'S BACKEND. There is no "Remote" enumerator and
|
||||
// there must not be one: GL_Framebuffer.cpp:47, GL_Texture.cpp:6536 and CompileEnv.cpp:122
|
||||
// switch on this value, and a value they do not know takes a WRONG ARM rather than failing.
|
||||
//
|
||||
// THE EGL VIRTUALS ARE BOTH FORWARDED AND KEPT. The base class runs a real state machine -
|
||||
// surface registration, per-thread current-context bookkeeping, the lazy InitCapabilities latch,
|
||||
// and SwapEGLBuffers' route into GetBackendFunctions().Present() - and the client needs all of
|
||||
// it, because Present is a class-B emitter reached through exactly that route (the verb census's
|
||||
// trap 3: Present has zero MG_Impl call sites). So each override does BOTH: it runs the real
|
||||
// EGL work on the apply thread, through v1's ServerLoop::RunOnApplyThread, and then lets the
|
||||
// base class keep the client-side books.
|
||||
//
|
||||
// SetEGLSwapInterval IS THE ONE THAT MUST NOT REACH THE TABLE. The base implementation
|
||||
// null-checks GetBackendFunctions().SetSwapInterval (BackendObject.cpp:402) - one of the 41
|
||||
// null checks R-4 turns into "always supported" - and SetSwapInterval is class C, so the base
|
||||
// implementation would Fatal on every eglSwapInterval. It is overridden to forward instead,
|
||||
// which is the caps-mirror-read rule's shape for a slot whose answer is "ask the server".
|
||||
|
||||
#pragma once
|
||||
#include <Includes.h>
|
||||
|
||||
#include <MG_Backend/BackendObject.h>
|
||||
|
||||
namespace MobileGL::MG_Remote::Client {
|
||||
|
||||
class BackendObject_Remote final : public MG_Backend::BackendObject {
|
||||
public:
|
||||
BackendObject_Remote();
|
||||
~BackendObject_Remote() override;
|
||||
|
||||
// ---- the eight pure virtuals ------------------------------------------------------
|
||||
void Initialize() override;
|
||||
Bool InitCapabilities() override;
|
||||
Bool InitWindowSurface() override;
|
||||
const RendererInfo& GetRendererInfo() const override;
|
||||
String GetBackendAPIVersionString() const override;
|
||||
const MG_Backend::GlobalBackendFunctionsTable& GetBackendFunctions() const override;
|
||||
const MG_Backend::DynamicBackendParameters& GetDynamicParameters() const override;
|
||||
BackendType GetBackendType() const override;
|
||||
|
||||
// ---- the nine EGL lifecycle virtuals ---------------------------------------------
|
||||
Bool InitializeEGLDisplay(EGLDisplay dpy, EGLint* major, EGLint* minor) override;
|
||||
Bool CreateEGLWindowSurface(EGLSurface surface, const MG_Backend::WindowHandle& handle) override;
|
||||
Bool ResizeEGLWindowSurface(EGLSurface surface, Uint32 width, Uint32 height) override;
|
||||
Bool CreateEGLPbufferSurface(EGLSurface surface, EGLint width, EGLint height) override;
|
||||
Bool MakeEGLCurrent(EGLDisplay dpy, EGLSurface draw, EGLSurface read, EGLContext ctx) override;
|
||||
Bool SwapEGLBuffers(EGLDisplay dpy, EGLSurface draw) override;
|
||||
void SetEGLSwapInterval(Int interval) override;
|
||||
void ReleaseEGLSurface(EGLSurface surface) override;
|
||||
void ReleaseEGLResources() override;
|
||||
|
||||
// Copies the caps mirror's FormatCapabilityCache into the base class's
|
||||
// m_formatCapabilities. Public because CapsMirror's adoption hook is a free function
|
||||
// and this is what it calls; it is the whole of trap 2's answer.
|
||||
void RefreshFormatCapabilities();
|
||||
|
||||
protected:
|
||||
Bool InitPbufferSurface(EGLint width, EGLint height) override;
|
||||
|
||||
private:
|
||||
// The generation of the snapshot m_formatCapabilities was filled from. Exposed only
|
||||
// through the log line on a refresh: a cache that silently stopped tracking the mirror
|
||||
// is exactly the shape trap 2 exists to prevent.
|
||||
Uint64 m_formatsGeneration = 0;
|
||||
};
|
||||
|
||||
} // namespace MobileGL::MG_Remote::Client
|
||||
@@ -6,49 +6,161 @@
|
||||
// SPDX-License-Identifier: LGPL-3.0-only
|
||||
// End of Source File Header
|
||||
|
||||
// P5 c0 stubs for package c1. Every body is MGLOG_F + std::abort and never a silent no-op: a
|
||||
// caps accessor that answers a default is how a split lane runs on the wrong device's limits.
|
||||
// P5 package c1.
|
||||
//
|
||||
// EVERY ACCESSOR ANSWERS BEFORE THE FIRST SNAPSHOT, AND THAT IS THE RULING, NOT A WEAKENING.
|
||||
// c0's stubs aborted on all but Valid()/Generation() so that nothing could answer from a zeroed
|
||||
// mirror by accident. But scout-caps-reply §1.2's option (a) - the one the brief adopts - says
|
||||
// LogBackendInfo() reads GetRendererInfo() at MG_Backend/Init.cpp:21, during MG_Backend::Init(),
|
||||
// BEFORE any surface exists, and that P5 accepts one imprecise startup log line rather than
|
||||
// restructure MG_Backend::Init(). An abort there is not a stricter mirror; it is a process that
|
||||
// cannot start. So the mirror answers a placeholder and SAYS SO, once per accessor: a wrong
|
||||
// number that announced itself is auditable, and the announcement is what a case asserts on.
|
||||
//
|
||||
// THE PLACEHOLDER IS A REAL OBJECT, NOT A TEMPORARY. GetRendererInfo() and
|
||||
// GetDynamicParameters() return const references, so the storage has to outlive every caller;
|
||||
// the members below are it, default-constructed, and Adopt() replaces them in place.
|
||||
|
||||
#include "CapsMirror.h"
|
||||
|
||||
#include <MG_Util/Debug/Log.h>
|
||||
#include "../CapsCodec.h"
|
||||
|
||||
#include <cstdlib>
|
||||
#include <MG_State/GLState/Core.h>
|
||||
#include <MG_Util/Debug/Log.h>
|
||||
|
||||
namespace MobileGL::MG_Remote::Client {
|
||||
|
||||
#define MGP5_C0_STUB(what) \
|
||||
do { \
|
||||
MGLOG_F("MGPipe: Fatal{UnimplementedCapsMirror, \"%s\"} - P5 package c1 has not landed " \
|
||||
"this yet; c0 shipped the signature only", \
|
||||
what); \
|
||||
std::abort(); \
|
||||
} while (0)
|
||||
namespace {
|
||||
CapsAdoptedHook g_capsAdoptedHook = nullptr;
|
||||
|
||||
void CapsMirror::Adopt(const MG_Pipe::MGPCaps&, const MG_Backend::FormatCapabilityCache&,
|
||||
const RendererInfo&, const String&, BackendType) {
|
||||
MGP5_C0_STUB("CapsMirror::Adopt");
|
||||
// R-8's negative control, counted at the funnel. Not atomics: every reader of this
|
||||
// mirror is the GL thread, by the same argument that makes one gPipeInputs legal.
|
||||
Uint64 g_consumerRefusals = 0;
|
||||
Uint64 g_lastRefusedSubsystem = 0;
|
||||
Uint64 g_refusedSubsystemsLogged = 0;
|
||||
|
||||
// One line per accessor, once, and only while the mirror is a placeholder. MGLOG_W_ONCE
|
||||
// keys on the call site, so each accessor gets its own line and a hot getter cannot
|
||||
// flood the log.
|
||||
void WarnPlaceholder(const char* what, Uint64 generation) {
|
||||
if (generation != 0) return;
|
||||
MGLOG_W("MG_Remote client: CapsMirror::%s read before the first CapsSnapshot - "
|
||||
"answering a PLACEHOLDER. Expected exactly once at startup, from "
|
||||
"LogBackendInfo (MG_Backend/Init.cpp:21); anything later means a caps read "
|
||||
"beat the handshake",
|
||||
what);
|
||||
}
|
||||
} // namespace
|
||||
|
||||
void CapsMirror::Adopt(const MG_Pipe::MGPCaps& caps, const MG_Backend::FormatCapabilityCache& formats,
|
||||
const RendererInfo& renderer, const String& apiVersion,
|
||||
BackendType backend) {
|
||||
m_caps = caps;
|
||||
// The two blobrefs inside MGPCaps name SEG_STAGE runs that belong to the SERVER's
|
||||
// encoder and are meaningless on this side; the decoded objects beside them are the
|
||||
// answer. Clearing them is not tidiness - a later reader that resolved one would read
|
||||
// whatever the stage allocator has since put there.
|
||||
m_caps.FormatCapabilities = MG_Pipe::MGPBlobRef{};
|
||||
m_caps.RendererInfo = MG_Pipe::MGPBlobRef{};
|
||||
m_formats = formats;
|
||||
m_renderer = renderer;
|
||||
m_apiVersion = apiVersion;
|
||||
m_backend = backend;
|
||||
++m_generation;
|
||||
|
||||
// R-12: RE-ARRIVAL IS THE INVALIDATION, and this is the one place that acts on it.
|
||||
// GLContext::GetCompileEnv() memoises on the raw pActiveBackendObject pointer
|
||||
// (Core.cpp:34); under split that pointer is the single long-lived BackendObject_Remote
|
||||
// and NEVER changes, so without this line the compile env, its preprocess memos and the
|
||||
// advertised-extension list stay stale for ever after a server-side InitCapabilities
|
||||
// re-run. DirectVulkan already spells the monolith half of this exactly this way
|
||||
// (BackendObject_DirectVulkan.cpp:390).
|
||||
if (m_generation > 1 && MG_State::pGLContext != nullptr) {
|
||||
MG_State::pGLContext->InvalidateCompileEnv();
|
||||
}
|
||||
MGLOG_I("MG_Remote client: CapsMirror generation %llu adopted (backend=%d, callMask=0x%llx)",
|
||||
static_cast<unsigned long long>(m_generation), static_cast<int>(m_backend),
|
||||
static_cast<unsigned long long>(m_caps.CallMask));
|
||||
|
||||
// LAST, and after the generation has moved: the hook reads this mirror.
|
||||
if (g_capsAdoptedHook != nullptr) g_capsAdoptedHook();
|
||||
}
|
||||
|
||||
// Not stubs: the two the placeholder contract above promises are readable before the first
|
||||
// snapshot. Everything else aborts, so nothing can accidentally answer from a zeroed mirror.
|
||||
void SetCapsAdoptedHook(CapsAdoptedHook hook) { g_capsAdoptedHook = hook; }
|
||||
|
||||
Bool CapsMirror::Valid() const { return m_generation != 0; }
|
||||
Uint64 CapsMirror::Generation() const { return m_generation; }
|
||||
|
||||
const RendererInfo& CapsMirror::Renderer() const { MGP5_C0_STUB("CapsMirror::Renderer"); }
|
||||
const RendererInfo& CapsMirror::Renderer() const {
|
||||
WarnPlaceholder("Renderer", m_generation);
|
||||
return m_renderer;
|
||||
}
|
||||
|
||||
const MG_Backend::DynamicBackendParameters& CapsMirror::Dynamic() const {
|
||||
MGP5_C0_STUB("CapsMirror::Dynamic");
|
||||
WarnPlaceholder("Dynamic", m_generation);
|
||||
return m_caps.Dynamic;
|
||||
}
|
||||
|
||||
const MG_Backend::FormatCapabilityCache& CapsMirror::Formats() const {
|
||||
MGP5_C0_STUB("CapsMirror::Formats");
|
||||
WarnPlaceholder("Formats", m_generation);
|
||||
return m_formats;
|
||||
}
|
||||
const String& CapsMirror::ApiVersion() const { MGP5_C0_STUB("CapsMirror::ApiVersion"); }
|
||||
BackendType CapsMirror::Backend() const { MGP5_C0_STUB("CapsMirror::Backend"); }
|
||||
Uint64 CapsMirror::CallMask() const { MGP5_C0_STUB("CapsMirror::CallMask"); }
|
||||
Bool CapsMirror::HasCap(MG_Pipe::MGPCapBit) const { MGP5_C0_STUB("CapsMirror::HasCap"); }
|
||||
Bool CapsMirror::ServerConsumes(Uint64) const { MGP5_C0_STUB("CapsMirror::ServerConsumes"); }
|
||||
|
||||
const String& CapsMirror::ApiVersion() const {
|
||||
WarnPlaceholder("ApiVersion", m_generation);
|
||||
return m_apiVersion;
|
||||
}
|
||||
|
||||
BackendType CapsMirror::Backend() const {
|
||||
WarnPlaceholder("Backend", m_generation);
|
||||
return m_backend;
|
||||
}
|
||||
|
||||
Uint64 CapsMirror::CallMask() const { return m_caps.CallMask; }
|
||||
|
||||
Bool CapsMirror::HasCap(MG_Pipe::MGPCapBit bit) const {
|
||||
return (m_caps.CallMask & static_cast<Uint64>(bit)) != 0;
|
||||
}
|
||||
|
||||
Bool CapsMirror::ServerConsumes(Uint64 subsystemBit) const {
|
||||
// THE ONLY LEGAL CLIENT-SIDE SPELLING (R-8). Never MGPipeGetResourceOps(): that is the
|
||||
// SERVER's registration, a process-wide global, right by accident under inproc and null
|
||||
// under spawn - and a null read there silently stops five record families while the
|
||||
// client goes on clearing its dirty flags, which is ID-39's 66 lost uploads with a wire
|
||||
// in between. Folded through CapsCodec.h's helper rather than shifted here, because two
|
||||
// spellings of one bit layout is how the two sides come to disagree about it.
|
||||
//
|
||||
// A PLACEHOLDER MIRROR CONSUMES NOTHING, and that is the safe direction: with no
|
||||
// snapshot the mask is 0, every family answers "no consumer", the client emits nothing
|
||||
// and the LEGACY PULL PATH runs untouched. The unsafe direction - emitting to a server
|
||||
// that has no consumer - is the one that loses uploads.
|
||||
const Bool consumes = MGCapsServerConsumes(m_caps.CallMask, subsystemBit);
|
||||
if (!consumes) {
|
||||
++g_consumerRefusals;
|
||||
g_lastRefusedSubsystem = subsystemBit;
|
||||
if ((g_refusedSubsystemsLogged & subsystemBit) == 0) {
|
||||
g_refusedSubsystemsLogged |= subsystemBit;
|
||||
MGLOG_W("MG_Remote client: the server does not consume MGPipe subsystem 0x%llx - "
|
||||
"this family emits NOTHING and the legacy pull path runs for it "
|
||||
"(R-8). callMask=0x%llx, caps generation %llu",
|
||||
static_cast<unsigned long long>(subsystemBit),
|
||||
static_cast<unsigned long long>(m_caps.CallMask),
|
||||
static_cast<unsigned long long>(m_generation));
|
||||
}
|
||||
}
|
||||
return consumes;
|
||||
}
|
||||
|
||||
Uint64 ConsumerRefusals() { return g_consumerRefusals; }
|
||||
Uint64 LastRefusedSubsystem() { return g_lastRefusedSubsystem; }
|
||||
void ResetConsumerRefusalsForTest() {
|
||||
g_consumerRefusals = 0;
|
||||
g_lastRefusedSubsystem = 0;
|
||||
g_refusedSubsystemsLogged = 0;
|
||||
}
|
||||
|
||||
Bool CapsMirror::PrefersCpuXfbPrimitiveAccounting() const {
|
||||
MGP5_C0_STUB("CapsMirror::PrefersCpuXfbPrimitiveAccounting");
|
||||
return HasCap(MG_Pipe::kCapCpuXfbPrimitiveAccounting);
|
||||
}
|
||||
|
||||
CapsMirror& CapsMirrorInstance() {
|
||||
@@ -58,6 +170,4 @@ namespace MobileGL::MG_Remote::Client {
|
||||
return instance;
|
||||
}
|
||||
|
||||
#undef MGP5_C0_STUB
|
||||
|
||||
} // namespace MobileGL::MG_Remote::Client
|
||||
|
||||
@@ -97,4 +97,28 @@ namespace MobileGL::MG_Remote::Client {
|
||||
// reach pipe or backend state from an exit handler.
|
||||
CapsMirror& CapsMirrorInstance();
|
||||
|
||||
// ---- c1's addition to c0's signature block -----------------------------------------
|
||||
//
|
||||
// WHY A HOOK AND NOT A READ. BackendObject::GetFormatCapabilities() is NON-VIRTUAL
|
||||
// (BackendObject.h:594) and returns the base class's own m_formatCapabilities member, so a
|
||||
// remote backend object cannot answer it lazily from the mirror - it has to PUSH the cache
|
||||
// into that member, and the only moment it can know to is when a snapshot lands. A raw
|
||||
// function pointer rather than std::function, for ID-8's reason: this can fire on paths
|
||||
// that must not allocate. One hook, installed by BackendObject_Remote's constructor.
|
||||
using CapsAdoptedHook = void (*)();
|
||||
void SetCapsAdoptedHook(CapsAdoptedHook hook);
|
||||
|
||||
// R-8's NEGATIVE CONTROL NEEDS TO SEE THE WITHHOLDING, NOT INFER IT FROM AN ABSENCE.
|
||||
// "the client emits nothing for a family the server does not consume" is, on its own,
|
||||
// indistinguishable from "the client emits nothing because nothing called it" - and the
|
||||
// second is how a gate goes green for the wrong reason. So the one funnel that answers the
|
||||
// question counts its own refusals and names the family, once per family, in the log.
|
||||
//
|
||||
// Counted inside ServerConsumes(), which is R-8's only legal spelling, so a refusal that
|
||||
// happened cannot fail to be counted and a count that moved cannot have come from anywhere
|
||||
// else.
|
||||
Uint64 ConsumerRefusals();
|
||||
Uint64 LastRefusedSubsystem();
|
||||
void ResetConsumerRefusalsForTest();
|
||||
|
||||
} // namespace MobileGL::MG_Remote::Client
|
||||
|
||||
@@ -6,13 +6,27 @@
|
||||
// SPDX-License-Identifier: LGPL-3.0-only
|
||||
// End of Source File Header
|
||||
|
||||
// P5 c0 stubs for packages s1 (construction, handshake) and c1 (barrier, reply read).
|
||||
// P5: construction, the handshake and lifetime are package s1's; the verb barrier and the
|
||||
// reply read that sits inside it are package c1's (EmitAndWait below is still c0's stub).
|
||||
|
||||
#include "ClientSession.h"
|
||||
|
||||
#include "../CapsCodec.h"
|
||||
#include "../Protocol/generated/protocol_generated.h"
|
||||
#include "../Server/ServerLoop.h"
|
||||
#include "../Server/ServerSession.h"
|
||||
#include "../Transport/InProcessTransport.h"
|
||||
#include "WireTables.h"
|
||||
|
||||
#include <MGGitHash.h>
|
||||
#include <MG_Pipe/MGPipeCallbacks.h>
|
||||
#include <MG_Util/Debug/Log.h>
|
||||
|
||||
#include <atomic>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
namespace MobileGL::MG_Remote::Client {
|
||||
|
||||
@@ -24,32 +38,869 @@ namespace MobileGL::MG_Remote::Client {
|
||||
std::abort(); \
|
||||
} while (0)
|
||||
|
||||
namespace {
|
||||
|
||||
ClientSession* g_active = nullptr;
|
||||
|
||||
// The same bounded handshake deadline the server uses. Bounded, not kWaitForever: a
|
||||
// bring-up that never answers has to be a red lane rather than a wedged CI job.
|
||||
constexpr Uint32 kHandshakeTimeoutMs = 5000;
|
||||
// Teardown's drain. Also bounded, and for the same reason - table 3's order is
|
||||
// "publish and wait for the server to drain and acknowledge", and a wait with no
|
||||
// deadline there turns a lost record into a hung process exit.
|
||||
constexpr Uint32 kDrainTimeoutMs = 5000;
|
||||
|
||||
MobileGLResult ReceiveEnvelope(Transport::ITransport& transport, std::vector<Uint8>& out,
|
||||
Uint32 timeoutMs) {
|
||||
Uint64 size = 0;
|
||||
MobileGLMutableByteSpan empty{nullptr, 0};
|
||||
const MobileGLResult probe = transport.ReceiveFrame(empty, &size, timeoutMs);
|
||||
if (probe != MOBILEGL_ERR_BUFFER_TOO_SMALL) {
|
||||
return probe == MOBILEGL_OK ? MOBILEGL_ERR_PROTOCOL_MISMATCH : probe;
|
||||
}
|
||||
out.resize(static_cast<SizeT>(size));
|
||||
MobileGLMutableByteSpan span{out.data(), out.size()};
|
||||
return transport.ReceiveFrame(span, &size, 0);
|
||||
}
|
||||
|
||||
const ::MobileGL::Wire::CtrlEnvelope* ParseEnvelope(const std::vector<Uint8>& bytes) {
|
||||
::flatbuffers::Verifier verifier(bytes.data(), bytes.size());
|
||||
if (!::MobileGL::Wire::VerifyCtrlEnvelopeBuffer(verifier)) {
|
||||
return nullptr;
|
||||
}
|
||||
if (!::MobileGL::Wire::CtrlEnvelopeBufferHasIdentifier(bytes.data())) {
|
||||
return nullptr;
|
||||
}
|
||||
return ::MobileGL::Wire::GetCtrlEnvelope(bytes.data());
|
||||
}
|
||||
|
||||
[[noreturn]] void FatalAbiMismatch(const char* what, Uint64 ours, Uint64 theirs,
|
||||
const char* theirStamp) {
|
||||
MGLOG_F("MGPipe: Fatal{AbiMismatch, \"%s\"} ours=%llu theirs=%llu ourBuild=%s "
|
||||
"theirBuild=%s - never a downgrade: the caps block's size is ABI-dependent "
|
||||
"and every field past the first difference would be read at the wrong offset",
|
||||
what, static_cast<unsigned long long>(ours),
|
||||
static_cast<unsigned long long>(theirs), GIT_COMMIT_HASH_SHORT,
|
||||
theirStamp == nullptr ? "?" : theirStamp);
|
||||
std::abort();
|
||||
}
|
||||
|
||||
// Guarded the same way ServerSession's helpers are: MG_Config::Ipc only exists
|
||||
// behind MOBILEGL_BUILD_DISAGGREGATED (Config.h), and this file is only compiled
|
||||
// there today - but the guard is what keeps that true if the source list ever
|
||||
// changes, and an unguarded read would be a compile error nobody could read.
|
||||
Uint32 SpinUsFromConfig() {
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
return MG_Config::Ipc.SpinUs;
|
||||
#else
|
||||
return Transport::kDefaultSpinUs;
|
||||
#endif
|
||||
}
|
||||
|
||||
Bool VerbBarrierFromConfig() {
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
return MG_Config::Ipc.VerbBarrier != 0;
|
||||
#else
|
||||
return true;
|
||||
#endif
|
||||
}
|
||||
|
||||
// ---- c1: the barrier's two flags ------------------------------------------------
|
||||
//
|
||||
// thread_local for the client's own "am I waiting", a shared atomic for "is the apply
|
||||
// thread inside the applier" - see ClientSession::InBarrierWait's note.
|
||||
thread_local Bool g_inBarrierWait = false;
|
||||
std::atomic<Bool> g_applyThreadInsideApplier{false};
|
||||
|
||||
struct BarrierWaitScope {
|
||||
BarrierWaitScope() { g_inBarrierWait = true; }
|
||||
~BarrierWaitScope() { g_inBarrierWait = false; }
|
||||
BarrierWaitScope(const BarrierWaitScope&) = delete;
|
||||
BarrierWaitScope& operator=(const BarrierWaitScope&) = delete;
|
||||
};
|
||||
|
||||
// BOUNDED, AND THE BOUND IS GENEROUS RATHER THAN TIGHT. The barrier is a correctness
|
||||
// device, not a watchdog: a slow readback on a software rasterizer is a legitimate
|
||||
// second-scale wait, while a lost record never completes at all. 30 s separates the two
|
||||
// without turning a loaded CI machine into a red lane, and the Fatal names the seq.
|
||||
constexpr Uint32 kBarrierTimeoutMs = 30000;
|
||||
// How many queued control frames one pump will drain. A backlog deeper than this is a
|
||||
// finding, not a steady state.
|
||||
constexpr Uint32 kMaxControlFramesPerPump = 16;
|
||||
|
||||
const char* TransportModeName(MG_Config::TransportMode mode) {
|
||||
switch (mode) {
|
||||
case MG_Config::TransportMode::Monolith: return "monolith";
|
||||
case MG_Config::TransportMode::InProcess: return "inproc";
|
||||
case MG_Config::TransportMode::Spawn: return "spawn";
|
||||
case MG_Config::TransportMode::UnixSocket: return "unix:";
|
||||
case MG_Config::TransportMode::NamedPipe: return "pipe:";
|
||||
}
|
||||
return "?";
|
||||
}
|
||||
|
||||
// ---- c1: the reverse channel's reading end ---------------------------------------
|
||||
//
|
||||
// R-12's three: OnBufferWriteback (#3), OnGpuWritten (#2), OnSurfaceChanged (#7).
|
||||
// Drained BY THE GL THREAD BETWEEN VERBS, which under the barrier means immediately
|
||||
// after appliedSeq reaches this record - the one moment at which the apply thread is
|
||||
// known not to be inside the applier.
|
||||
//
|
||||
// THE BYTES LIVE IN THE RING ITSELF, so Drained() is called only after every payload
|
||||
// pointer popped here has been consumed: retiring earlier is R-11's violation one level
|
||||
// down (EventRing.h:168-171 says so in as many words).
|
||||
Uint32 DrainEventRing(Transport::EventRingConsumer& events) {
|
||||
if (!events.Valid()) return 0;
|
||||
Uint32 delivered = 0;
|
||||
Transport::RingRecordView view{};
|
||||
Bool corrupt = false;
|
||||
while (events.Pop(view, &corrupt)) {
|
||||
if (corrupt) {
|
||||
MGLOG_F("MGPipe: Fatal{ProtocolCorruption, \"event-ring\"} - the reverse "
|
||||
"channel's record stream is corrupt");
|
||||
std::abort();
|
||||
}
|
||||
switch (view.kind) {
|
||||
case Transport::kEventBufferWriteback: {
|
||||
if (view.payloadSize < sizeof(Transport::EventBufferWritebackHead)) break;
|
||||
const auto* head =
|
||||
static_cast<const Transport::EventBufferWritebackHead*>(view.payload);
|
||||
const void* bytes = static_cast<const Uint8*>(view.payload) + sizeof(*head);
|
||||
if (view.payloadSize - sizeof(*head) < head->Size) {
|
||||
MGLOG_F("MGPipe: Fatal{ProtocolCorruption, \"buffer-writeback\"} - the "
|
||||
"head declares %llu inline bytes and the record carries %llu",
|
||||
static_cast<unsigned long long>(head->Size),
|
||||
static_cast<unsigned long long>(view.payloadSize - sizeof(*head)));
|
||||
std::abort();
|
||||
}
|
||||
if (MG_Pipe::gMGPipeCallbacks.OnBufferWriteback != nullptr) {
|
||||
// The blobref names SEG_EVENT and the IN-SEGMENT offset of those inline
|
||||
// bytes - never a host address (R-2's rule B), which is the whole reason
|
||||
// EventRingConsumer exposes OffsetInSegment at all.
|
||||
MG_Pipe::MGPBlobRef blob{};
|
||||
blob.Seg = Wire::kSegEvent;
|
||||
blob.Offset = events.OffsetInSegment(bytes);
|
||||
blob.Size = head->Size;
|
||||
MG_Pipe::gMGPipeCallbacks.OnBufferWriteback(
|
||||
MG_Pipe::MGPipeHandle{head->Resource.Slot, head->Resource.Gen},
|
||||
head->Offset, blob);
|
||||
++delivered;
|
||||
}
|
||||
break;
|
||||
}
|
||||
case Transport::kEventGpuWritten: {
|
||||
if (view.payloadSize < sizeof(Transport::EventGpuWrittenHead)) break;
|
||||
const auto* head =
|
||||
static_cast<const Transport::EventGpuWrittenHead*>(view.payload);
|
||||
const Uint64 tail = view.payloadSize - sizeof(*head);
|
||||
if (tail / sizeof(Transport::EventRange) < head->RangeCount) {
|
||||
MGLOG_F("MGPipe: Fatal{ProtocolCorruption, \"gpu-written\"} - RangeCount "
|
||||
"%u does not fit the record's %llu tail bytes",
|
||||
static_cast<unsigned>(head->RangeCount),
|
||||
static_cast<unsigned long long>(tail));
|
||||
std::abort();
|
||||
}
|
||||
if (MG_Pipe::gMGPipeCallbacks.OnGpuWritten != nullptr) {
|
||||
// EventRange and MGPRange are the same two Uint64s (EventRing.h:61-66
|
||||
// asserts it), so the tail is handed over as-is rather than copied into
|
||||
// a second array a later reader could get out of step with.
|
||||
const auto* ranges = reinterpret_cast<const MG_Pipe::MGPRange*>(
|
||||
static_cast<const Uint8*>(view.payload) + sizeof(*head));
|
||||
MG_Pipe::gMGPipeCallbacks.OnGpuWritten(
|
||||
MG_Pipe::MGPipeHandle{head->Resource.Slot, head->Resource.Gen},
|
||||
static_cast<Uint>(head->RangeCount), ranges);
|
||||
++delivered;
|
||||
}
|
||||
break;
|
||||
}
|
||||
case Transport::kEventSurfaceChanged: {
|
||||
if (view.payloadSize < sizeof(Transport::EventSurfaceChangedHead)) break;
|
||||
if (MG_Pipe::gMGPipeCallbacks.OnSurfaceChanged != nullptr) {
|
||||
const auto* head =
|
||||
static_cast<const Transport::EventSurfaceChangedHead*>(view.payload);
|
||||
MG_Pipe::MGPSurfaceInfo info{};
|
||||
info.Width = head->Width;
|
||||
info.Height = head->Height;
|
||||
info.InternalFormat = head->InternalFormat;
|
||||
info.Samples = head->Samples;
|
||||
info.Layers = head->Layers;
|
||||
info.IsDefault = head->IsDefault;
|
||||
MG_Pipe::gMGPipeCallbacks.OnSurfaceChanged(&info);
|
||||
++delivered;
|
||||
}
|
||||
break;
|
||||
}
|
||||
default:
|
||||
MGLOG_W("MG_Remote client: reverse-channel record kind %u is not consumed in "
|
||||
"P5 (R-12 takes three and a half of the ten callbacks)",
|
||||
static_cast<unsigned>(view.kind));
|
||||
break;
|
||||
}
|
||||
}
|
||||
// AND ONLY NOW. Every payload pointer above has been consumed.
|
||||
events.Drained();
|
||||
return delivered;
|
||||
}
|
||||
|
||||
// ---- c1: the CapsSnapshot -> CapsMirror adoption, in ONE place -------------------
|
||||
//
|
||||
// Every field of the snapshot has exactly one reader, and a field that fails to decode
|
||||
// is a REFUSAL rather than a partial adopt: CompileEnv.cpp:123 copies the whole
|
||||
// DynamicBackendParameters struct into the compile env, so a mirror that adopted three
|
||||
// of four members would put the fourth's default into a shader fingerprint.
|
||||
Bool AdoptCapsSnapshot(const ::MobileGL::Wire::CapsSnapshot* snapshot) {
|
||||
if (snapshot == nullptr) return false;
|
||||
|
||||
MG_Pipe::MGPCaps caps{};
|
||||
const auto* dynamicBytes = snapshot->dynamicParameters();
|
||||
if (dynamicBytes == nullptr || dynamicBytes->size() != sizeof(caps.Dynamic)) {
|
||||
// The Hello/Welcome fingerprint already asserted both peers agree on
|
||||
// sizeof(DynamicBackendParameters), so a disagreement HERE is a corrupt frame
|
||||
// rather than an ABI skew - which is why it is a refusal and not FatalAbiMismatch.
|
||||
MGLOG_E("MG_Remote client: CapsSnapshot carries %llu dynamic bytes, this build's "
|
||||
"struct is %llu - the snapshot is refused whole",
|
||||
static_cast<unsigned long long>(dynamicBytes == nullptr ? 0
|
||||
: dynamicBytes->size()),
|
||||
static_cast<unsigned long long>(sizeof(caps.Dynamic)));
|
||||
return false;
|
||||
}
|
||||
std::memcpy(&caps.Dynamic, dynamicBytes->data(), sizeof(caps.Dynamic));
|
||||
caps.CallMask = snapshot->callMask();
|
||||
|
||||
RendererInfo renderer{};
|
||||
const auto* rendererBytes = snapshot->rendererInfo();
|
||||
if (rendererBytes == nullptr ||
|
||||
!DecodeRendererInfo(rendererBytes->data(), rendererBytes->size(), renderer)) {
|
||||
MGLOG_E("MG_Remote client: CapsSnapshot's rendererInfo blob did not decode");
|
||||
return false;
|
||||
}
|
||||
|
||||
MG_Backend::FormatCapabilityCache formats{};
|
||||
const auto* formatBytes = snapshot->formatCaps();
|
||||
if (formatBytes == nullptr ||
|
||||
!DecodeFormatCapabilities(formatBytes->data(), formatBytes->size(), formats)) {
|
||||
MGLOG_E("MG_Remote client: CapsSnapshot's formatCaps blob did not decode");
|
||||
return false;
|
||||
}
|
||||
|
||||
const String apiVersion =
|
||||
snapshot->apiVersion() == nullptr ? String{} : String{snapshot->apiVersion()->c_str()};
|
||||
|
||||
// THE SERVER'S BACKEND TYPE, NEVER A NEW "Remote" ENUMERATOR and never guessed from
|
||||
// the renderer string: GL_Framebuffer.cpp:47, GL_Texture.cpp:6536 and
|
||||
// CompileEnv.cpp:122 SWITCH on it, and a value they do not know takes a wrong arm
|
||||
// rather than failing.
|
||||
const Uint32 rawBackend = snapshot->backendType();
|
||||
if (rawBackend >= static_cast<Uint32>(BackendType::BackendTypeCount)) {
|
||||
MGLOG_E("MG_Remote client: CapsSnapshot names backend type %u, which this build "
|
||||
"has no enumerator for - the snapshot is refused rather than folded onto "
|
||||
"Unknown, which three frontend switches would silently mis-branch on",
|
||||
static_cast<unsigned>(rawBackend));
|
||||
return false;
|
||||
}
|
||||
CapsMirrorInstance().Adopt(caps, formats, renderer, apiVersion,
|
||||
static_cast<BackendType>(rawBackend));
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
// Null, not a Fatal: MG_Backend::Init() asks whether a session exists before it decides to
|
||||
// install the remote backend object, and that question has a legitimate "no" - it is the
|
||||
// monolith answer. Every call that PRESUMES a session aborts instead.
|
||||
ClientSession* ClientSession::Active() { return nullptr; }
|
||||
ClientSession* ClientSession::Active() { return g_active; }
|
||||
|
||||
MobileGLResult ClientSession::Start(MG_Config::TransportMode, const String&) {
|
||||
MGP5_C0_STUB("ClientSession::Start");
|
||||
ClientSession& ClientSessionInstance() {
|
||||
// Leak at exit, deliberately and per ID-8, exactly as ServerSessionInstance does.
|
||||
static ClientSession* instance = new ClientSession{};
|
||||
return *instance;
|
||||
}
|
||||
|
||||
void ClientSession::Stop() { MGP5_C0_STUB("ClientSession::Stop"); }
|
||||
ClientSession::~ClientSession() {
|
||||
if (m_started) {
|
||||
Stop();
|
||||
}
|
||||
}
|
||||
|
||||
Bool ClientSession::Started() const { return m_started; }
|
||||
|
||||
MobileGLResult ClientSession::Start(MG_Config::TransportMode mode, const String& endpoint) {
|
||||
if (m_started) {
|
||||
return MOBILEGL_ERR_INVALID_ARGUMENT;
|
||||
}
|
||||
// A NAMED ERROR, NEVER A FALLBACK TO MONOLITH. A silent fallback here is exactly the
|
||||
// "the split lane ran monolith and went green" failure the whole phase is built to
|
||||
// make impossible (ARCHITECTURE.md 10.3), so every mode this build cannot serve is
|
||||
// refused by name rather than degraded.
|
||||
if (mode != MG_Config::TransportMode::InProcess) {
|
||||
MGLOG_E("MG_Remote client: MOBILEGL_TRANSPORT=%s%s is refused by name - P5 implements "
|
||||
"`inproc` only, and falling back to monolith would make this lane green for "
|
||||
"the wrong reason. spawn / unix: / pipe: are P6's",
|
||||
TransportModeName(mode), endpoint.empty() ? "" : endpoint.c_str());
|
||||
return MOBILEGL_ERR_UNSUPPORTED;
|
||||
}
|
||||
|
||||
// ---- 1. the control plane and the two bells. The transport owns the bells; THE
|
||||
// SESSION owns the rings, and the accessors stay off ITransport (contract §3.9).
|
||||
std::unique_ptr<Transport::InProcessTransport> clientEnd;
|
||||
std::unique_ptr<Transport::InProcessTransport> serverEnd;
|
||||
Transport::InProcessTransport::CreatePair(clientEnd, serverEnd);
|
||||
return StartOverTransportPair(std::move(clientEnd), std::move(serverEnd));
|
||||
}
|
||||
|
||||
MobileGLResult ClientSession::StartOverTransportPair(
|
||||
std::unique_ptr<Transport::InProcessTransport> clientEnd,
|
||||
std::unique_ptr<Transport::InProcessTransport> serverEnd) {
|
||||
if (m_started) {
|
||||
return MOBILEGL_ERR_INVALID_ARGUMENT;
|
||||
}
|
||||
if (clientEnd == nullptr || serverEnd == nullptr) {
|
||||
MGLOG_E("MG_Remote client: StartOverTransportPair needs both ends of one "
|
||||
"InProcessTransport::CreatePair");
|
||||
return MOBILEGL_ERR_INVALID_ARGUMENT;
|
||||
}
|
||||
m_clientTransport = std::move(clientEnd);
|
||||
m_serverTransport = std::move(serverEnd);
|
||||
m_transport = m_clientTransport.get();
|
||||
|
||||
// ---- 2. Hello. Sent before the server accepts: InProcessTransport queues whole
|
||||
// messages, so one thread can drive both halves of the handshake in order.
|
||||
const Uint64 fingerprint = CapsAbiFingerprint();
|
||||
{
|
||||
::flatbuffers::FlatBufferBuilder builder(512);
|
||||
auto stamp = builder.CreateString(GIT_COMMIT_HASH_SHORT);
|
||||
auto hello = ::MobileGL::Wire::CreateHello(
|
||||
builder, MOBILEGL_PROTOCOL_ABI_MAJOR, MOBILEGL_PROTOCOL_ABI_MINOR, stamp,
|
||||
/*backendType=*/0u, /*pid=*/0u, /*configBlob=*/0, fingerprint);
|
||||
auto root = ::MobileGL::Wire::CreateCtrlEnvelope(
|
||||
builder, ::MobileGL::Wire::CtrlMsg::Hello, hello.Union());
|
||||
::MobileGL::Wire::FinishCtrlEnvelopeBuffer(builder, root);
|
||||
const MobileGLResult sent = m_transport->SendFrame(
|
||||
MobileGLByteSpan{builder.GetBufferPointer(), builder.GetSize()});
|
||||
if (sent != MOBILEGL_OK) {
|
||||
Stop();
|
||||
return sent;
|
||||
}
|
||||
}
|
||||
|
||||
// ---- 3. the server half: ABI assert, four segments, Welcome.
|
||||
Server::ServerSession& server = Server::ServerSessionInstance();
|
||||
const MobileGLResult accepted = server.Accept(*m_serverTransport);
|
||||
if (accepted != MOBILEGL_OK) {
|
||||
Stop();
|
||||
return accepted;
|
||||
}
|
||||
|
||||
// ---- 4. Welcome, and this side's half of the ABI assertion.
|
||||
{
|
||||
std::vector<Uint8> frame;
|
||||
const MobileGLResult received = ReceiveEnvelope(*m_transport, frame, kHandshakeTimeoutMs);
|
||||
if (received != MOBILEGL_OK) {
|
||||
MGLOG_E("MG_Remote client: no Welcome within %u ms (rc=%d)", kHandshakeTimeoutMs,
|
||||
static_cast<int>(received));
|
||||
Stop();
|
||||
return received;
|
||||
}
|
||||
const ::MobileGL::Wire::CtrlEnvelope* envelope = ParseEnvelope(frame);
|
||||
// msg_as_Welcome() IS PART OF THE GUARD - flatbuffers' Verifier::VerifyTable is
|
||||
// `return !table || table->Verify(*this)`, so a NULL union member verifies while
|
||||
// msg_type() still reports Welcome. See ServerSession::Accept for the same guard.
|
||||
if (envelope == nullptr || envelope->msg_type() != ::MobileGL::Wire::CtrlMsg::Welcome ||
|
||||
envelope->msg_as_Welcome() == nullptr) {
|
||||
MGLOG_E("MG_Remote client: the server's first control frame is not a verifiable "
|
||||
"Welcome");
|
||||
Stop();
|
||||
return MOBILEGL_ERR_PROTOCOL_MISMATCH;
|
||||
}
|
||||
const ::MobileGL::Wire::Welcome* welcome = envelope->msg_as_Welcome();
|
||||
const char* theirStamp = welcome->buildFingerprint() == nullptr
|
||||
? nullptr
|
||||
: welcome->buildFingerprint()->c_str();
|
||||
if (welcome->abiFingerprint() != fingerprint) {
|
||||
FatalAbiMismatch("struct shapes", fingerprint, welcome->abiFingerprint(),
|
||||
theirStamp);
|
||||
}
|
||||
// The four SegmentRefs are what a spawn client MAPS (P6). Under inproc the mapping
|
||||
// already exists, so what they are good for here is the cross-check that the two
|
||||
// sides agree about the geometry at all - which is the assertion that would
|
||||
// otherwise first run in P6, on the day it is expensive to be wrong.
|
||||
using Slot = Transport::SessionSegmentSlot;
|
||||
const auto agrees = [&](const ::MobileGL::Wire::SegmentRef* ref, Slot slot,
|
||||
const char* name) {
|
||||
if (ref == nullptr || ref->sizeBytes() != server.Shm().AnnouncedSize(slot)) {
|
||||
MGLOG_E("MG_Remote client: Welcome's %s SegmentRef announces %llu bytes, the "
|
||||
"server mapped %llu",
|
||||
name,
|
||||
static_cast<unsigned long long>(ref == nullptr ? 0 : ref->sizeBytes()),
|
||||
static_cast<unsigned long long>(server.Shm().AnnouncedSize(slot)));
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
};
|
||||
if (!agrees(welcome->cmdRing(), Slot::Cmd, "cmd") ||
|
||||
!agrees(welcome->stageRing(), Slot::Stage, "stage") ||
|
||||
!agrees(welcome->replyPool(), Slot::Reply, "reply") ||
|
||||
!agrees(welcome->eventRing(), Slot::Event, "event")) {
|
||||
Stop();
|
||||
return MOBILEGL_ERR_PROTOCOL_MISMATCH;
|
||||
}
|
||||
}
|
||||
|
||||
// ---- 5. attach to the four segments. Under `inproc` this is the SAME mapping booked
|
||||
// under the client role; under `spawn` it becomes ShmSegment::Adopt of the fds the
|
||||
// server passed by SCM_RIGHTS, which is why nothing below this line knows which it was.
|
||||
const MobileGLResult attached =
|
||||
m_shm.AttachInProcess(server.Shm(), Transport::MemoryRole::Client);
|
||||
if (attached != MOBILEGL_OK) {
|
||||
Stop();
|
||||
return attached;
|
||||
}
|
||||
|
||||
Transport::RingControl* control = m_shm.CmdControl();
|
||||
m_cmd = Transport::RingProducer(control, m_shm.CmdRingBase(), m_shm.CmdRingCapacity(),
|
||||
Transport::RingCursorSet::Cmd);
|
||||
// NO STAGE RING. SEG_STAGE is package w1's encoder-local LINEAR ALLOCATOR:
|
||||
// a staged byte run carries no RingRecordHeader, nothing consumes SEG_STAGE,
|
||||
// and the allocator reclaims on retiredSeq. A RingProducer over
|
||||
// RingCursorSet::Stage would publish stageHead with nothing advancing the
|
||||
// two tails, so FreeBytes() would fall to zero the first time the head
|
||||
// lapped the capacity and never recover - a guaranteed hang. See
|
||||
// RingControl's stage triple in Ring.h.
|
||||
if (!m_cmd.Valid()) {
|
||||
Stop();
|
||||
return MOBILEGL_ERR_INVALID_ARGUMENT;
|
||||
}
|
||||
// PeerDoorbell() is the bell the SERVER parks on and this side rings; SelfDoorbell() is
|
||||
// this side's own. Which is which is the session's knowledge, not the transport's.
|
||||
m_producer.Attach(control, &m_cmd, &m_clientTransport->PeerDoorbell(),
|
||||
&m_clientTransport->SelfDoorbell(), SpinUsFromConfig());
|
||||
|
||||
m_replies = Transport::ReplySlotPool(m_shm.ReplyBase(), m_shm.ReplyBytes(),
|
||||
m_shm.ReplySlotCount());
|
||||
m_events = Transport::EventRingConsumer(m_shm.EventControl(), control,
|
||||
m_shm.EventRingBase(), m_shm.EventRingCapacity(),
|
||||
m_shm.EventSegmentBase());
|
||||
if (!m_replies.Valid() || !m_events.Valid()) {
|
||||
Stop();
|
||||
return MOBILEGL_ERR_INVALID_ARGUMENT;
|
||||
}
|
||||
|
||||
m_barrierArmed = VerbBarrierFromConfig();
|
||||
if (!m_barrierArmed) {
|
||||
MGLOG_W("MG_Remote client: MOBILEGL_IPC_VERB_BARRIER=0 - this is R-1's NEGATIVE "
|
||||
"CONTROL and is EXPECTED to be red. 31 of the 63 PipeInputs fields are still "
|
||||
"pulled from a live GLContext by the client's residual fill, so a free-running "
|
||||
"queue lets the server read a FUTURE value of them");
|
||||
}
|
||||
|
||||
// ---- 6. the client's segment table. IT MUST NOT INSTALL THE PROCESS RESOLVER: there is
|
||||
// exactly one gMGPipeSegmentResolver per process, the SERVER role owns it (table 3), and
|
||||
// the client never resolves a span at all - it only ever writes Ptr = nullptr (R-2's
|
||||
// rule B). Two roles racing on that one inline variable is precisely what the server's
|
||||
// InstallProcessResolver asserts against.
|
||||
//
|
||||
// The Install calls themselves are package w1's and are named-Fatal stubs until w1
|
||||
// lands; see ServerSession::Accept for why they are called anyway.
|
||||
m_segments.Install(Wire::kSegCmd,
|
||||
Wire::SegmentView{m_shm.CmdRingBase(), m_shm.CmdRingCapacity()});
|
||||
m_segments.Install(Wire::kSegStage,
|
||||
Wire::SegmentView{m_shm.StageBase(), m_shm.StageBytes()});
|
||||
m_segments.Install(Wire::kSegReply,
|
||||
Wire::SegmentView{m_shm.ReplyBase(), m_shm.ReplyBytes()});
|
||||
m_segments.Install(Wire::kSegEvent,
|
||||
Wire::SegmentView{m_shm.EventSegmentBase(),
|
||||
m_shm.AnnouncedSize(Transport::SessionSegmentSlot::Event)});
|
||||
// nullptr for the stage producer, and that is the honest value: c0's
|
||||
// signature predates w1's ruling that SEG_STAGE is a linear allocator, and
|
||||
// the encoder reaches its bytes through the SegmentTable above. Handing it
|
||||
// a live RingProducer over a cursor triple nobody consumes would be the
|
||||
// half-wired shape this session exists not to have.
|
||||
m_encoder = Wire::PipeWireEncoder(control, &m_cmd, nullptr, &m_segments);
|
||||
|
||||
// ---- 7. the first CapsSnapshot, if the server had a backend to publish one from.
|
||||
// ONE DRAIN, ONE ADOPTER (c1): PumpControlPlane below is the only thing in the client
|
||||
// that turns a CapsSnapshot into a CapsMirror generation, so R-12's "a second arrival
|
||||
// IS the invalidation" lives in exactly one place. s1's step here used to stop at
|
||||
// "the snapshot arrived and is verifiable"; it now goes all the way, through the same
|
||||
// function every later arrival goes through.
|
||||
if (PumpControlPlane() == 0) {
|
||||
MGLOG_W("MG_Remote client: the handshake carried no CapsSnapshot - the caps mirror is "
|
||||
"a PLACEHOLDER until one arrives. Every caps read until then answers a "
|
||||
"default and says so");
|
||||
}
|
||||
|
||||
// BOTH, AND m_started FIRST. `Active()` is what the integration lane's skip reads and
|
||||
// `m_started` is what `EmitAndWait` reads, and c1's round-1 rewrite of this function
|
||||
// set only the second of the two - so a fully-handshaken session with an apply thread
|
||||
// running and a caps mirror adopted took Fatal{NoClientSession, "Clear"} on its very
|
||||
// first verb, which is the most confusing possible spelling of "the session is up".
|
||||
// The order matters for the same reason it does at the other end: `Active()` hands a
|
||||
// caller a session it may immediately emit on, so the flag that permits emitting has
|
||||
// to be true before the pointer that grants access to it is published. `Stop()` takes
|
||||
// them down in the mirror order (m_started = false, then g_active = nullptr).
|
||||
m_started = true;
|
||||
g_active = this;
|
||||
LogMemory("handshake");
|
||||
|
||||
// ---- 8. and only now the apply thread. It is package v1's ServerLoop: it names the
|
||||
// thread mgl-srv-apply, applies MOBILEGL_IPC_SERVER_AFFINITY and logs the RESOLVED
|
||||
// mask. Under `inproc` the client is what starts the server role, which is why this
|
||||
// call is here rather than in some server-side main.
|
||||
const MobileGLResult running = Server::ServerLoopInstance().Start(server);
|
||||
if (running != MOBILEGL_OK) {
|
||||
Stop();
|
||||
return running;
|
||||
}
|
||||
|
||||
// ---- 9. AND ONLY NOW THE THIRTY-SEVEN WIRE EMITTERS (R-17). This is the line that
|
||||
// arms `integration-split`: the 21 `DirectGLES.Split.*` entries skip on
|
||||
// `ClientSession::Active() == nullptr`, and every one of the four arming facts is true
|
||||
// at exactly this point and at no earlier one.
|
||||
//
|
||||
// IT IS LAST, AND EACH OF THE FOUR REASONS IS A DIFFERENT FAILURE:
|
||||
// - after Hello/Welcome (step 2-4), or an emitter would publish into a ring the peer
|
||||
// has not mapped;
|
||||
// - after the first CapsSnapshot (step 7), because R-8's liveness gates read the caps
|
||||
// mirror and a PLACEHOLDER mirror consumes nothing - a record emitted before it
|
||||
// would go to a server this client has not been told consumes that family;
|
||||
// - after ServerLoop::Start (step 8), because EmitAndWait BLOCKS on appliedSeq and
|
||||
// with no apply thread nothing advances it: the first resource_create would spend
|
||||
// 30 seconds in the barrier and then Fatal{BarrierTimeout};
|
||||
// - on THIS thread, the one that called MG_Backend::Init(), because it is the GL
|
||||
// thread and table 3 makes gPipeInputs its to touch while the barrier holds.
|
||||
// The publication is safe without a fence because the apply thread never reads these
|
||||
// tables - the server decodes straight into MGPipeApply* - and this thread wrote them
|
||||
// before it can reach any GL entry point.
|
||||
InstallClientWireTables();
|
||||
return MOBILEGL_OK;
|
||||
}
|
||||
|
||||
void ClientSession::Stop() {
|
||||
// FIRST, BEFORE ANYTHING ELSE GOES AWAY (R-17 / codex 4). Every later step here frees
|
||||
// something an emitter dereferences - the rings, the segments, the transports - so a
|
||||
// routed GL-thread call that arrives during teardown must not run the applier on the
|
||||
// caller and must not reach a half-freed ring. Round 2 reinstalled the monolith adapters
|
||||
// HERE, which is running the applier on the caller - the forbidden path table 3 draws.
|
||||
// Uninstall now RAISES A FLAG and leaves the wire rows in place; the next routed call
|
||||
// aborts by name (Fatal{ClientTablesUninstalled}) inside RequireSession before it touches
|
||||
// anything. The monolith adapters go back only at the END of teardown
|
||||
// (ReinstallMonolithAfterTeardown), for the at-exit ~BufferObject deletes that reach a
|
||||
// process with no session at all - and by then the rings are gone, so the applier a
|
||||
// monolith adapter runs is a defined no-op rather than a use-after-free.
|
||||
UninstallClientWireTables();
|
||||
if (!m_started) {
|
||||
// Start's own failure paths land here with a half-built session. FIVE of them are
|
||||
// reached AFTER ServerSession::Accept has already returned OK, so tearing down
|
||||
// only the client half is not enough and gets three things wrong at once: the
|
||||
// server keeps its four mappings and stays m_accepted, so Accept's own guard
|
||||
// refuses every later Start and the process can never open a session again; the
|
||||
// process-wide segment resolver stays installed; and resetting m_serverTransport
|
||||
// destroys a transport that ServerSession::m_transport and its two Doorbell*
|
||||
// still point at. The server closes FIRST, in the same order the started path
|
||||
// gets right, and only then do the transports go.
|
||||
m_producer.Detach();
|
||||
m_shm.Close();
|
||||
Server::ServerSessionInstance().Close();
|
||||
m_clientTransport.reset();
|
||||
m_serverTransport.reset();
|
||||
m_transport = nullptr;
|
||||
// The rings are gone; put the monolith adapters back for a process that will make no
|
||||
// more routed calls except, possibly, at-exit deletes (codex 4).
|
||||
ReinstallMonolithAfterTeardown();
|
||||
return;
|
||||
}
|
||||
|
||||
// TABLE 3's TEARDOWN ORDER, and every step of it is load-bearing.
|
||||
//
|
||||
// 1. publish and let the server drain. Bounded: a lost record must be a red lane, not
|
||||
// a hung exit.
|
||||
Transport::RingControl* control = m_shm.CmdControl();
|
||||
if (control != nullptr) {
|
||||
// The PRODUCER's own last-published seq, not RingControl::submittedSeq. Ring.h:72-77
|
||||
// permits submittedSeq to be published lazily and Ring.h:243 encourages batching
|
||||
// the publish, so the shared watermark is allowed to lag the emitter - and a drain
|
||||
// that waited for `appliedSeq >= submittedSeq` would then under-wait and free an
|
||||
// emitter-owned var-tail while a record still names it. With the verb barrier armed
|
||||
// the two are equal; under MOBILEGL_IPC_VERB_BARRIER=0, R-1's negative control that
|
||||
// the phase has to run once, they are not.
|
||||
const Uint64 submitted = m_producer.LastPublishedSeq();
|
||||
m_producer.PublishAndNotify(submitted);
|
||||
if (submitted != 0 &&
|
||||
m_producer.WaitForApplied(submitted, kDrainTimeoutMs) != Transport::SessionWait::Reached) {
|
||||
MGLOG_E("MG_Remote client: the server did not drain to seq %llu within %u ms; "
|
||||
"tearing down anyway, and anything an emitter still owns is freed below "
|
||||
"AFTER the join, which is what keeps that from being a use-after-free",
|
||||
static_cast<unsigned long long>(submitted), kDrainTimeoutMs);
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Doorbell::Kill(). THE ONLY thing that can wake an apply thread parked on
|
||||
// kWaitForever (Doorbell.h:211-221): a Notify is consumed by one Park, after which
|
||||
// Doorbell::Wait re-tests a condition nothing published, finds the bell alive and
|
||||
// parks again, forever. InProcessChannel::Close kills both bells.
|
||||
if (m_transport != nullptr) {
|
||||
m_transport->Shutdown();
|
||||
}
|
||||
|
||||
// 3. JOIN, bounded - package v1's ServerLoop::Stop, which also destroys the server's
|
||||
// private BackendObject on that thread before it exits.
|
||||
Server::ServerLoopInstance().Stop();
|
||||
|
||||
// 4. and ONLY NOW may anything an emitter owns be released: a var-tail still
|
||||
// referenced by an unapplied record is a use-after-free the join is what prevents.
|
||||
LogMemory("teardown");
|
||||
m_producer.Detach();
|
||||
m_encoder = Wire::PipeWireEncoder();
|
||||
m_events = Transport::EventRingConsumer();
|
||||
m_replies = Transport::ReplySlotPool();
|
||||
m_cmd = Transport::RingProducer();
|
||||
m_shm.Close();
|
||||
Server::ServerSessionInstance().Close();
|
||||
m_clientTransport.reset();
|
||||
m_serverTransport.reset();
|
||||
m_transport = nullptr;
|
||||
m_started = false;
|
||||
if (g_active == this) {
|
||||
g_active = nullptr;
|
||||
}
|
||||
// AND ONLY NOW the monolith adapters go back (codex 4): every ring an emitter would have
|
||||
// used is freed above, so from here a routed call - an at-exit ~BufferObject delete - runs
|
||||
// the applier exactly as it does under monolith, which is the correct answer for a
|
||||
// process that no longer has a session. During the whole span above, the raised flag made
|
||||
// any routed call abort by name instead.
|
||||
ReinstallMonolithAfterTeardown();
|
||||
}
|
||||
|
||||
Wire::PipeWireEncoder& ClientSession::Encoder() { return m_encoder; }
|
||||
|
||||
CapsMirror& ClientSession::Caps() { return CapsMirrorInstance(); }
|
||||
|
||||
Uint64 ClientSession::EmitAndWait(MG_Pipe::MGPWireOp, const void*, Uint64, const void*, Uint64,
|
||||
void*, Uint64, Int32*) {
|
||||
MGP5_C0_STUB("ClientSession::EmitAndWait");
|
||||
// PACKAGE c1's. The barrier's wait and the reply's wait are ONE wait (R-3/R-5), which is
|
||||
// what makes a blocking ReadPixels, MapPersistent's decline and the four Bool acceptances
|
||||
// cost zero extra round trips - and the client may not re-derive any of those four answers
|
||||
// locally. s1 supplies the four primitives it composes from: Encoder(), Producer(),
|
||||
// WaitForApplied() and ReadReply().
|
||||
//
|
||||
// THE ORDER IS ENCODE -> PUBLISH+NOTIFY -> WAIT -> READ REPLY, and it is not negotiable.
|
||||
// Splitting the wait from the read is how a package ends up answering an acceptance
|
||||
// question locally, which is the c0f/c0g defect P4a paid two contract corrections for; and
|
||||
// "always accept" is ID-39's 66 lost DirectVulkan uploads with a wire in between.
|
||||
Uint64 ClientSession::EmitAndWait(MG_Pipe::MGPWireOp op, const void* payload, Uint64 payloadBytes,
|
||||
const void* varTail, Uint64 varTailBytes, void* replyOut,
|
||||
Uint64 replyBytes, Int32* statusOut, Uint64* replySizeOut) {
|
||||
if (statusOut != nullptr) *statusOut = Wire::ReplySink::kStatusError;
|
||||
if (replySizeOut != nullptr) *replySizeOut = 0;
|
||||
if (!m_started) {
|
||||
MGLOG_F("MGPipe: Fatal{NoClientSession, \"%s\"} - EmitAndWait on a session that has "
|
||||
"not started. There is no fall-through: a record that could not be emitted "
|
||||
"is a verb that did not happen",
|
||||
Wire::WireOpName(op));
|
||||
std::abort();
|
||||
}
|
||||
|
||||
// R-1's INVARIANT, AS A RUNTIME CHECK RATHER THAN A SENTENCE. While the barrier holds,
|
||||
// at most one of {GL thread, apply thread} is runnable - and that is the whole reason a
|
||||
// single process-wide gPipeInputs is legal (table 3). The client is about to publish a
|
||||
// record whose fields the applier will read out of gPipeInputs, so the apply thread
|
||||
// being inside the applier right now means the invariant has already been broken and
|
||||
// the next record would be read against a half-written residual fill.
|
||||
if (ApplyThreadIsInsideApplier()) {
|
||||
MGLOG_F("MGPipe: Fatal{BarrierViolation, \"%s\"} - the apply thread is inside the "
|
||||
"applier while the GL thread is emitting. R-1 makes at most one of them "
|
||||
"runnable, which is what keeps one process-wide gPipeInputs legal",
|
||||
Wire::WireOpName(op));
|
||||
std::abort();
|
||||
}
|
||||
|
||||
const Uint64 seq =
|
||||
m_encoder.EncodeRecord(op, payload, payloadBytes, varTail, varTailBytes);
|
||||
if (seq == Wire::kInvalidSeq) {
|
||||
// The ring refused it. NOT a silent drop and not a retry loop: R-10 says P5 does no
|
||||
// chunking and must prove it needs none, so a refusal is the proof failing.
|
||||
MGLOG_F("MGPipe: Fatal{RingOverrun, \"%s\"} - the command ring refused a %llu-byte "
|
||||
"record. P5 does not chunk (R-10); this is the proof obligation failing, not "
|
||||
"a back-pressure case",
|
||||
Wire::WireOpName(op),
|
||||
static_cast<unsigned long long>(payloadBytes + varTailBytes));
|
||||
std::abort();
|
||||
}
|
||||
|
||||
// Publish the head, record submittedSeq, THEN ring - in that order, which is
|
||||
// SessionProducer's one job and RingTest.cpp:446's pin. Notify-then-publish loses the
|
||||
// wakeup.
|
||||
m_producer.PublishAndNotify(seq);
|
||||
|
||||
// Does this row own a reply slot? kMGPipeCallFlags IS THE SINGLE SOURCE OF TRUTH
|
||||
// (R-16 / ID-31) - fourteen rows now, because the four Bool acceptance entry points
|
||||
// gained the flag. Asking the catalogue rather than the caller is what stops a caller
|
||||
// that forgot to pass a buffer from silently turning an answer into a guess.
|
||||
const Bool ownsReplySlot =
|
||||
(MG_Pipe::MGPipeCallFlagsFor(op) & static_cast<Uint32>(MG_Pipe::kReplySlot)) != 0;
|
||||
|
||||
if (!m_barrierArmed && !ownsReplySlot) {
|
||||
// R-1's NEGATIVE CONTROL ARM, and the only thing it turns off is the barrier. A
|
||||
// reply-slot row still waits: the answer is not derivable here and R-5 forbids
|
||||
// inventing one, so MOBILEGL_IPC_VERB_BARRIER=0 makes the queue free-running, not
|
||||
// the client clairvoyant.
|
||||
return seq;
|
||||
}
|
||||
|
||||
const BarrierWaitScope waiting;
|
||||
const Transport::SessionWait wait = m_producer.WaitForApplied(seq, kBarrierTimeoutMs);
|
||||
if (wait == Transport::SessionWait::ShutDown) {
|
||||
// The doorbell died: the server went away. The only thing that returns from a
|
||||
// kWaitForever park, and therefore the only way a client blocked in the barrier
|
||||
// survives a server that is gone. It is teardown, not a server fault - so the answer
|
||||
// handed back is DECLINED, not the ERROR the status was pre-set to (M4): a
|
||||
// reply-owning row that saw ERROR here would abort Fatal{ReplyError} on a shutting-
|
||||
// down session, which is what the "teardown legitimately reaches here" comment
|
||||
// promised would NOT happen. DECLINED is honest - "the verb did not happen" - and the
|
||||
// acceptance rows already treat it as `false` / nullptr without aborting.
|
||||
// ReadPixels intentionally refuses this with Fatal{ReadbackDeclined, "ReadPixels"}:
|
||||
// unlike acceptance rows it cannot return successfully without complete pixels.
|
||||
if (statusOut != nullptr) *statusOut = Wire::ReplySink::kStatusDeclined;
|
||||
MGLOG_E("MG_Remote client: the barrier for %s (seq %llu) woke on a dead doorbell; the "
|
||||
"server is gone and this verb did not happen (reported as DECLINED, not ERROR)",
|
||||
Wire::WireOpName(op), static_cast<unsigned long long>(seq));
|
||||
return seq;
|
||||
}
|
||||
if (wait != Transport::SessionWait::Reached) {
|
||||
MGLOG_F("MGPipe: Fatal{BarrierTimeout, \"%s\"} - appliedSeq did not reach %llu within "
|
||||
"%u ms. A bounded wait is deliberate: a wedged CI job and a lost record look "
|
||||
"identical from outside, and only one of them is a bug worth finding",
|
||||
Wire::WireOpName(op), static_cast<unsigned long long>(seq), kBarrierTimeoutMs);
|
||||
std::abort();
|
||||
}
|
||||
|
||||
// THE REVERSE CHANNEL IS DRAINED HERE, and here is the only place it can be: under the
|
||||
// barrier this is the one instant at which the apply thread is known not to be inside
|
||||
// the applier, and MGPipeClientOnGpuWritten / OnBufferWriteback write frontend objects.
|
||||
// It is what gives AwaitBufferWriteback something to have waited FOR: b1's third state
|
||||
// clears when the writeback lands, and the writeback lands on this ring.
|
||||
DrainEventRing(m_events);
|
||||
|
||||
if (!ownsReplySlot) return seq;
|
||||
|
||||
// THE SAME WAIT, NOT A SECOND ONE. appliedSeq >= seq already means the server wrote
|
||||
// this record's answer, because it writes the slot before it advances the watermark.
|
||||
Uint64 replySize = 0;
|
||||
Int32 status = Wire::ReplySink::kStatusError;
|
||||
if (!ReadReply(seq, replyOut, replyBytes, &status, &replySize)) {
|
||||
MGLOG_F("MGPipe: Fatal{ReplyMissing, \"%s\"} - seq %llu carries kReplySlot and the "
|
||||
"server applied it, but its slot does not stamp that seq. The stamp is what "
|
||||
"makes a wrong-slot read detectable rather than plausible (R-3)",
|
||||
Wire::WireOpName(op), static_cast<unsigned long long>(seq));
|
||||
std::abort();
|
||||
}
|
||||
if (statusOut != nullptr) *statusOut = status;
|
||||
if (replySizeOut != nullptr) *replySizeOut = replySize;
|
||||
if (status == Wire::ReplySink::kStatusError) {
|
||||
MGLOG_E("MG_Remote client: %s (seq %llu) answered ERROR", Wire::WireOpName(op),
|
||||
static_cast<unsigned long long>(seq));
|
||||
}
|
||||
// DECLINED is NOT an error and is deliberately not logged as one: it is how
|
||||
// MapPersistent says nullptr (R-6) and how the four Bool acceptance rows say false
|
||||
// (R-5). A client that treated it as a failure would re-create ID-39 from the other
|
||||
// side.
|
||||
if (replyOut != nullptr && replySize > replyBytes) {
|
||||
MGLOG_F("MGPipe: Fatal{ReplyTooLarge, \"%s\"} - the answer is %llu bytes and the "
|
||||
"caller offered %llu. P5 does not chunk a reply",
|
||||
Wire::WireOpName(op), static_cast<unsigned long long>(replySize),
|
||||
static_cast<unsigned long long>(replyBytes));
|
||||
std::abort();
|
||||
}
|
||||
return seq;
|
||||
}
|
||||
|
||||
Bool ClientSession::BarrierArmed() const { return m_barrierArmed; }
|
||||
|
||||
// False, not a Fatal, for both: these are the R-1 mutual-exclusion assertion's two probes,
|
||||
// and an assertion helper that aborts when asked is worse than useless.
|
||||
Bool ClientSession::InBarrierWait() { return false; }
|
||||
Bool ClientSession::ApplyThreadIsInsideApplier() { return false; }
|
||||
// R-1's mutual-exclusion invariant, as two probes that answer honestly.
|
||||
//
|
||||
// THE CLIENT'S FLAG IS THREAD-LOCAL AND THE SERVER'S IS NOT, and the asymmetry is the
|
||||
// point: "am I inside a barrier wait" is a question about the calling thread, while "is the
|
||||
// apply thread inside the applier" is a question the GL thread asks about a DIFFERENT
|
||||
// thread - so the second has to be a shared atomic and the first must not be, or a second
|
||||
// GL thread would see the first one's wait as its own.
|
||||
Bool ClientSession::InBarrierWait() { return g_inBarrierWait; }
|
||||
Bool ClientSession::ApplyThreadIsInsideApplier() {
|
||||
return g_applyThreadInsideApplier.load(std::memory_order_acquire);
|
||||
}
|
||||
void ClientSession::NoteApplyThreadEnteredApplier() {
|
||||
g_applyThreadInsideApplier.store(true, std::memory_order_release);
|
||||
}
|
||||
void ClientSession::NoteApplyThreadLeftApplier() {
|
||||
g_applyThreadInsideApplier.store(false, std::memory_order_release);
|
||||
}
|
||||
|
||||
Uint32 ClientSession::PumpControlPlane() {
|
||||
// NOT gated on m_started. The first snapshot arrives DURING Start(), before this session
|
||||
// is started or active - and s1's half-built teardown path depends on m_started staying
|
||||
// false until step 8 has succeeded, so the flag cannot be moved earlier to suit this.
|
||||
if (m_transport == nullptr) return 0;
|
||||
Uint32 adopted = 0;
|
||||
// Bounded rather than `while (true)`: a server that queued frames faster than this
|
||||
// drains them would otherwise hold the GL thread here for ever, and a frame backlog
|
||||
// deeper than this is a finding rather than a steady state.
|
||||
for (Uint32 guard = 0; guard < kMaxControlFramesPerPump; ++guard) {
|
||||
if (m_transport->PeekFrameSize() == 0) break;
|
||||
std::vector<Uint8> frame;
|
||||
if (ReceiveEnvelope(*m_transport, frame, 0) != MOBILEGL_OK) break;
|
||||
const ::MobileGL::Wire::CtrlEnvelope* envelope = ParseEnvelope(frame);
|
||||
if (envelope == nullptr) {
|
||||
MGLOG_E("MG_Remote client: an unverifiable control frame (%llu bytes) was dropped",
|
||||
static_cast<unsigned long long>(frame.size()));
|
||||
continue;
|
||||
}
|
||||
if (envelope->msg_type() != ::MobileGL::Wire::CtrlMsg::CapsSnapshot) {
|
||||
// SurfaceOp / SurfaceReply / ResyncRequest / AuxRequest / LogLine are P6's and
|
||||
// P7's. Named rather than ignored, so a phase that starts sending one does not
|
||||
// discover this loop swallowing it.
|
||||
MGLOG_W("MG_Remote client: control message %d is not consumed in P5",
|
||||
static_cast<int>(envelope->msg_type()));
|
||||
continue;
|
||||
}
|
||||
if (AdoptCapsSnapshot(envelope->msg_as_CapsSnapshot())) ++adopted;
|
||||
}
|
||||
return adopted;
|
||||
}
|
||||
|
||||
Transport::SessionProducer& ClientSession::Producer() { return m_producer; }
|
||||
|
||||
Transport::SessionWait ClientSession::WaitForApplied(Uint64 seq, Uint32 timeoutMs) {
|
||||
return m_producer.WaitForApplied(seq, timeoutMs);
|
||||
}
|
||||
|
||||
Bool ClientSession::ReadReply(Uint64 seq, void* outBytes, Uint64 outCapacity, Int32* outStatus,
|
||||
Uint64* outSize) {
|
||||
return m_replies.Read(seq, outBytes, outCapacity, outStatus, outSize);
|
||||
}
|
||||
|
||||
Uint32 ClientSession::MaxReplyBytes() const { return m_replies.MaxReplyBytes(); }
|
||||
|
||||
Bool ClientSession::ReplyCanHold(Uint64 bytes) const { return m_replies.CanHold(bytes); }
|
||||
|
||||
// ID-47. Forwarded verbatim so that the message, the boundary and the abort are the pool's
|
||||
// and are pinned once, in SessionTest, rather than re-derived per caller.
|
||||
void ClientSession::RequireReadPixelsReplyFits(Uint32 width, Uint32 height, Uint32 format,
|
||||
Uint32 type, Uint64 bytes) const {
|
||||
m_replies.RequireReadPixelsFits(width, height, format, type, bytes);
|
||||
}
|
||||
|
||||
Transport::EventRingConsumer& ClientSession::Events() { return m_events; }
|
||||
|
||||
Transport::RingControl* ClientSession::Control() { return m_shm.CmdControl(); }
|
||||
|
||||
Transport::SessionSegments& ClientSession::Shm() { return m_shm; }
|
||||
|
||||
Transport::ITransport* ClientSession::Control_Plane() { return m_transport; }
|
||||
|
||||
Transport::RoleMemorySample ClientSession::SampleMemory() const {
|
||||
return Transport::SampleRoleMemory(Transport::MemoryRole::Client);
|
||||
}
|
||||
|
||||
void ClientSession::LogMemory(const char* phase) const {
|
||||
Transport::LogRoleMemory(phase, SampleMemory());
|
||||
}
|
||||
|
||||
#undef MGP5_C0_STUB
|
||||
|
||||
|
||||
@@ -38,9 +38,22 @@
|
||||
#include <Config.h>
|
||||
#include <MG_Pipe/MGPipe.h>
|
||||
|
||||
#include "../Transport/Doorbell.h"
|
||||
#include "../Transport/EventRing.h"
|
||||
#include "../Transport/ITransport.h"
|
||||
#include "../Transport/ReplySlot.h"
|
||||
#include "../Transport/Ring.h"
|
||||
#include "../Transport/RoleMemory.h"
|
||||
#include "../Transport/SessionRings.h"
|
||||
#include "../Wire/PipeWireCodec.h"
|
||||
#include "CapsMirror.h"
|
||||
|
||||
#include <memory>
|
||||
|
||||
namespace MobileGL::MG_Remote::Transport {
|
||||
class InProcessTransport;
|
||||
}
|
||||
|
||||
namespace MobileGL::MG_Remote::Client {
|
||||
|
||||
class ClientSession {
|
||||
@@ -48,12 +61,27 @@ namespace MobileGL::MG_Remote::Client {
|
||||
// Null until Start() succeeds; MG_Backend::Init() is the only caller of Start().
|
||||
static ClientSession* Active();
|
||||
|
||||
~ClientSession();
|
||||
|
||||
// Builds the four segments, performs Hello/Welcome, takes the first CapsSnapshot, and
|
||||
// - for TransportMode::InProcess - starts the server role's apply thread. Returns a
|
||||
// named error rather than falling back to monolith: a fallback here is the "split lane
|
||||
// ran monolith and went green" failure, and it must be loud.
|
||||
MobileGLResult Start(MG_Config::TransportMode mode, const String& endpoint);
|
||||
|
||||
// Start()'s second half: the handshake and everything after it, over a transport pair
|
||||
// the CALLER made with InProcessTransport::CreatePair. Start() refuses every mode but
|
||||
// `inproc`, makes the pair, and calls this; it is public for exactly one reason. The
|
||||
// Welcome guard below (envelope->msg_as_Welcome() == nullptr, ID-46 finding 7) can only
|
||||
// be reached by a frame that arrives on the server->client direction BEFORE the
|
||||
// server's own Welcome, and Start() builds that pair itself, so no control could put
|
||||
// one there. SessionHandshakeTest does it through here, and the null-union Welcome must
|
||||
// come back as MOBILEGL_ERR_PROTOCOL_MISMATCH with the guard's own line. Not a second
|
||||
// way to start a session: MG_Backend::Init() calls Start(), and nothing else may call
|
||||
// this with a pair it did not just create.
|
||||
MobileGLResult StartOverTransportPair(std::unique_ptr<Transport::InProcessTransport> clientEnd,
|
||||
std::unique_ptr<Transport::InProcessTransport> serverEnd);
|
||||
|
||||
// Teardown order matters and is table 3's fourth column: publish and let the server
|
||||
// drain, Doorbell::Kill() (the ONLY thing that wakes an apply thread parked on
|
||||
// kWaitForever, Doorbell.h:211-221), then join, and only then release anything an
|
||||
@@ -68,11 +96,17 @@ namespace MobileGL::MG_Remote::Client {
|
||||
// name where a kReplySlot answer lands; pass {nullptr, 0} for a call that has none.
|
||||
// Returns the record's seq, which is also its reply-slot id.
|
||||
//
|
||||
// `replySizeOut` (optional) receives the answer's OWN byte count as the server stamped
|
||||
// it - which is not always `replyBytes`: a short OK reply stamps fewer, and a DECLINE or
|
||||
// ERROR stamps 0. ReadPixels is the one caller that must know, because scattering a
|
||||
// reply that arrived short would spray stale bytes as pixels (M2 / codex 11); it reads
|
||||
// this and refuses `replySize != DstSize` by name rather than trust the copy.
|
||||
//
|
||||
// Waiting is spin(MOBILEGL_IPC_SPIN_US) then park, through Doorbell::Wait, with
|
||||
// producerParked set before blocking - the shape Doorbell.h:121 already implements.
|
||||
Uint64 EmitAndWait(MG_Pipe::MGPWireOp op, const void* payload, Uint64 payloadBytes,
|
||||
const void* varTail, Uint64 varTailBytes, void* replyOut,
|
||||
Uint64 replyBytes, Int32* statusOut);
|
||||
Uint64 replyBytes, Int32* statusOut, Uint64* replySizeOut = nullptr);
|
||||
|
||||
// MOBILEGL_IPC_VERB_BARRIER. False is the R-1 negative control and is EXPECTED to be
|
||||
// red; it must be run once and the way it goes red recorded.
|
||||
@@ -85,11 +119,108 @@ namespace MobileGL::MG_Remote::Client {
|
||||
static Bool InBarrierWait();
|
||||
static Bool ApplyThreadIsInsideApplier();
|
||||
|
||||
// ---- c1's additions ---------------------------------------------------------------
|
||||
|
||||
// The apply thread's half of R-1's invariant. v1's apply loop brackets its
|
||||
// DecodeAndApply with these; the client checks the flag before it publishes, so
|
||||
// "at most one of {GL thread, apply thread} is runnable" is a runtime assertion rather
|
||||
// than a sentence in a brief. A raw pair rather than an RAII type in this header
|
||||
// because the server side owns its own scoping and must not have to include a client
|
||||
// header to get it - ScopedApplierEntry below is the convenience, not the contract.
|
||||
static void NoteApplyThreadEnteredApplier();
|
||||
static void NoteApplyThreadLeftApplier();
|
||||
struct ScopedApplierEntry {
|
||||
ScopedApplierEntry() { NoteApplyThreadEnteredApplier(); }
|
||||
~ScopedApplierEntry() { NoteApplyThreadLeftApplier(); }
|
||||
ScopedApplierEntry(const ScopedApplierEntry&) = delete;
|
||||
ScopedApplierEntry& operator=(const ScopedApplierEntry&) = delete;
|
||||
};
|
||||
|
||||
// R-12's INVALIDATION EDGE. Drains whatever the server has queued on the control plane
|
||||
// and adopts every CapsSnapshot in it - and a SECOND snapshot IS the invalidation,
|
||||
// which is why there is no Invalidate(). Non-blocking: it peeks and returns.
|
||||
//
|
||||
// Called at the handshake, from BackendObject_Remote's Initialize/InitCapabilities, and
|
||||
// once per Present. Present is the boundary every one of P5's three targets crosses,
|
||||
// and a caps re-run can only follow a surface event, so once a frame is both sufficient
|
||||
// and the cheapest place that is.
|
||||
//
|
||||
// Returns how many snapshots it adopted, so a case can assert the edge fired rather
|
||||
// than assert that a number downstream of it happened to change.
|
||||
Uint32 PumpControlPlane();
|
||||
|
||||
// ---- s1's additions: the four primitives c1's EmitAndWait composes ---------------
|
||||
//
|
||||
// s1 owns construction and lifetime; c1 owns the barrier POLICY. So the plumbing is
|
||||
// here and the composition is c1's: encode (w1) -> PublishAndNotify -> WaitForApplied
|
||||
// -> ReadReply. Splitting it the other way round is how a package ends up
|
||||
// re-deriving an acceptance answer locally, which is the c0f/c0g defect P4a paid two
|
||||
// contract corrections for.
|
||||
|
||||
Bool Started() const;
|
||||
|
||||
// Publish the ring head, record submittedSeq, then ring the server IF IT IS PARKED -
|
||||
// in that order. RingTest.cpp:446 pins the order; SessionProducer is where it lives.
|
||||
Transport::SessionProducer& Producer();
|
||||
|
||||
// Wait for RingControl::appliedSeq >= seq. Returns ShutDown when the doorbell died,
|
||||
// which is the only thing that returns from a kWaitForever park and therefore the
|
||||
// only way a client blocked in the barrier survives a server that went away.
|
||||
Transport::SessionWait WaitForApplied(Uint64 seq, Uint32 timeoutMs);
|
||||
|
||||
// The reply slot for `seq`, addressed seq % slots with the seq stamped back into the
|
||||
// header for self-check (R-3). `outStatus` is 0 OK / 1 DECLINED / 2 ERROR, and
|
||||
// DECLINED IS A REAL ANSWER - MapPersistent's nullptr and the four Bool acceptances.
|
||||
Bool ReadReply(Uint64 seq, void* outBytes, Uint64 outCapacity, Int32* outStatus,
|
||||
Uint64* outSize);
|
||||
// What one answer may carry. A ReadPixels bigger than this is Fatal rather than
|
||||
// chunked, so the client checks BEFORE it emits.
|
||||
Uint32 MaxReplyBytes() const;
|
||||
// ID-47, the fifth primitive: true exactly when an answer of `bytes` can be posted.
|
||||
Bool ReplyCanHold(Uint64 bytes) const;
|
||||
// ID-47's named refusal, forwarded verbatim to ReplySlotPool::RequireReadPixelsFits.
|
||||
// Returns when the answer fits; otherwise
|
||||
// Fatal{ReplyTooLarge, "ReadPixels <w>x<h> <format> <bytes> > <cap>"}
|
||||
// and abort - AT THE CLIENT, BEFORE EMISSION. Package c1's OnReadPixels emitter calls
|
||||
// this once, immediately before EmitAndWait(MGPWireOp::ReadPixels, ...), with the
|
||||
// record's box, its Format/Type enums and the DstSize it computed; the server's Post
|
||||
// keeps its own refusal as the last line of defence, but that one fires on the apply
|
||||
// thread with the record already on the wire, where all the client sees is a hang.
|
||||
void RequireReadPixelsReplyFits(Uint32 width, Uint32 height, Uint32 format, Uint32 type,
|
||||
Uint64 bytes) const;
|
||||
|
||||
// The reverse channel's reading end: OnBufferWriteback / OnGpuWritten /
|
||||
// OnSurfaceChanged. Drained by the GL thread between verbs.
|
||||
Transport::EventRingConsumer& Events();
|
||||
|
||||
Transport::RingControl* Control();
|
||||
Transport::SessionSegments& Shm();
|
||||
Transport::ITransport* Control_Plane();
|
||||
|
||||
// Peak-RSS accounting for t1 (RoleMemory.h).
|
||||
Transport::RoleMemorySample SampleMemory() const;
|
||||
void LogMemory(const char* phase) const;
|
||||
|
||||
private:
|
||||
Wire::PipeWireEncoder m_encoder;
|
||||
Wire::SegmentTable m_segments;
|
||||
CapsMirror* m_caps = nullptr;
|
||||
Bool m_barrierArmed = true;
|
||||
|
||||
std::unique_ptr<Transport::InProcessTransport> m_clientTransport;
|
||||
std::unique_ptr<Transport::InProcessTransport> m_serverTransport;
|
||||
Transport::SessionSegments m_shm;
|
||||
Transport::RingProducer m_cmd;
|
||||
Transport::SessionProducer m_producer;
|
||||
Transport::EventRingConsumer m_events;
|
||||
Transport::ReplySlotPool m_replies;
|
||||
Transport::ITransport* m_transport = nullptr;
|
||||
Bool m_started = false;
|
||||
};
|
||||
|
||||
// One per process in P5, because P5 serves one context, and LEAKED AT EXIT like every other
|
||||
// MG_Remote singleton (ID-8): no frontend destructor may reach pipe or backend state from an
|
||||
// exit handler, and a session destroyed before them would be a use-after-free rather than a
|
||||
// tidy teardown. MG_Backend::Init() calls Start() on this one.
|
||||
ClientSession& ClientSessionInstance();
|
||||
|
||||
} // namespace MobileGL::MG_Remote::Client
|
||||
|
||||
@@ -6,13 +6,39 @@
|
||||
// SPDX-License-Identifier: LGPL-3.0-only
|
||||
// End of Source File Header
|
||||
|
||||
// P5 c0 stubs for package c1.
|
||||
// P5 package c1: the 71-slot emit table.
|
||||
//
|
||||
// THE PARTITION IS CONTRACT-P5.md §7's AND IS NOT RE-DERIVED HERE (R-15, ID-12):
|
||||
// class A 2 slots answered locally from the caps mirror, never emitted, never Fatal
|
||||
// class B 5 slots emitted
|
||||
// class C 64 slots Fatal{UnmigratedVerb, "<slot>"}
|
||||
// The three counts are static_asserted to sum to kRemoteEmitSlotCount below, so a slot that
|
||||
// changes class without changing the arithmetic is a build break rather than a behaviour
|
||||
// change nobody reviewed.
|
||||
//
|
||||
// THE PRE-VERB HOOKS RUN BEFORE THE RECORD, NEVER AFTER (b1, ID-18). PushPersistentMapsBeforeVerb
|
||||
// publishes the bytes an application wrote through a coherent map with no API call at all, and
|
||||
// MarkGpuWritesForDraw builds the conservative GPU-write set the client now owns. Both describe
|
||||
// the work the record is ABOUT TO START, so a hook deferred past its own record is the C-1
|
||||
// regression re-committed at the transport layer.
|
||||
|
||||
#include "EmitTables.h"
|
||||
|
||||
#include "ClientSession.h"
|
||||
#include "GpuWritePending.h"
|
||||
#include "PersistentMapTracker.h"
|
||||
|
||||
#include <MG_Util/Converters/GLToMG/TextureEnumConverter.h>
|
||||
#include <MG_Util/Debug/Log.h>
|
||||
#include <MG_Util/Metrics/TextureMetrics.h>
|
||||
|
||||
#include <MG_State/GLState/BufferState/BufferObject.h>
|
||||
#include <MG_State/GLState/Core.h>
|
||||
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
|
||||
#include "WireTables.h"
|
||||
|
||||
namespace MobileGL::MG_Remote::Client {
|
||||
|
||||
@@ -36,12 +62,711 @@ namespace MobileGL::MG_Remote::Client {
|
||||
std::abort();
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
Bool g_dropClearEmission = false;
|
||||
Uint64 g_droppedClearEmissions = 0;
|
||||
|
||||
// E2's control has to be armable from OUTSIDE the process that runs the replay, because
|
||||
// the statement it makes is about a trace lane and not about a unit case: "drop one
|
||||
// Clear emission and OpenRA's SSIM falls below 0.99". A recompile would make the control
|
||||
// arm against source text, which is ID-22(a)'s defect.
|
||||
//
|
||||
// READ WITH getenv RATHER THAN THROUGH MG_Config, DELIBERATELY AND TEMPORARILY. Config.h
|
||||
// is c0's and a new MOBILEGL_IPC_* knob goes through the integrator; this is a
|
||||
// NEGATIVE-CONTROL switch no operator may ever set, and it announces itself at warning
|
||||
// level every time it arms so it cannot be on by accident. Flagged for adoption into
|
||||
// IpcTable if the integrator wants it there.
|
||||
Bool ReadDropClearFromEnvironment() {
|
||||
const char* value = std::getenv("MOBILEGL_IPC_E2_DROP_CLEAR");
|
||||
const Bool armed = value != nullptr && value[0] == '1' && value[1] == '\0';
|
||||
if (armed) {
|
||||
MGLOG_W("MG_Remote client: MOBILEGL_IPC_E2_DROP_CLEAR=1 - E2's NEGATIVE CONTROL is "
|
||||
"armed and every glClear will be DROPPED on the wire. This arm is expected "
|
||||
"to fail its SSIM threshold; a lane that stays green with it set is not "
|
||||
"going through the wire at all");
|
||||
}
|
||||
return armed;
|
||||
}
|
||||
|
||||
// ID-49's two halves, in one place so the emitter and its control read the same
|
||||
// arithmetic.
|
||||
//
|
||||
// GL 4.6 8.4.4, pack side: the destination row stride is ROW_LENGTH (or the width)
|
||||
// pixels rounded UP to PACK_ALIGNMENT, the first written byte is offset by SKIP_ROWS
|
||||
// whole strides plus SKIP_PIXELS pixels, and only `width * bytesPerPixel` bytes of each
|
||||
// stride are written - the gaps belong to the application and are never touched. That
|
||||
// last clause is what the control checks with a sentinel.
|
||||
Bool ReadbackPackStateIsTight(GLsizei width, Uint64 bytesPerPixel,
|
||||
const PixelStoreParameters& pack) {
|
||||
// SKIP_IMAGES (and IMAGE_HEIGHT) are NOT consulted: glReadPixels is a 2-D read and GL
|
||||
// ignores the image-level pack parameters for it, exactly as the monolith conversion
|
||||
// path does at DirectGLES.cpp:10905 (honorPackImageParams=false). A non-zero
|
||||
// SkipImages therefore does not make the layout non-tight (codex 6).
|
||||
if (pack.SkipRows != 0 || pack.SkipPixels != 0) return false;
|
||||
if (pack.RowLength != 0 && pack.RowLength != width) return false;
|
||||
const Uint64 alignment = pack.Alignment > 0 ? static_cast<Uint64>(pack.Alignment) : 1ull;
|
||||
const Uint64 rowBytes = static_cast<Uint64>(width) * bytesPerPixel;
|
||||
return (rowBytes % alignment) == 0;
|
||||
}
|
||||
|
||||
// ---- the session, demanded rather than assumed --------------------------------
|
||||
//
|
||||
// Every class-B slot needs one. A null session here is NOT the monolith answer - the
|
||||
// monolith answer is that this table was never installed at all, because
|
||||
// MG_Backend::Init() only reaches BackendObject_Remote when the transport resolved. So
|
||||
// a null one is a Fatal by name and not a fall-through to the driver: a pass-through
|
||||
// slot is the "split lane ran monolith and went green" shape that every gate in this
|
||||
// phase exists to prevent (R-4).
|
||||
ClientSession& RequireSession(const char* slot) {
|
||||
RequireClientTablesInstalled(slot);
|
||||
ClientSession* session = ClientSession::Active();
|
||||
if (session == nullptr) {
|
||||
MGLOG_F("MGPipe: Fatal{NoClientSession, \"%s\"} - the remote emit table is "
|
||||
"installed but no ClientSession is active. A slot may not fall through "
|
||||
"to a driver this role does not have",
|
||||
slot);
|
||||
std::abort();
|
||||
}
|
||||
return *session;
|
||||
}
|
||||
|
||||
// The two hooks b1 wrote and deliberately left with no caller, because the call site is
|
||||
// this file's. ORDER: the push first (it produces resource_subdata records that must
|
||||
// precede the verb on SEG_CMD), then the mark walk, then the verb record.
|
||||
void BeforeDrawVerb() {
|
||||
PushPersistentMapsBeforeVerb();
|
||||
MarkGpuWritesForDraw();
|
||||
}
|
||||
|
||||
// A verb that reads buffers but starts no shader: clear, blit, readback, present. The
|
||||
// push still has to run - a coherent map is read by the GPU on any of them - but there
|
||||
// is no shader that could write one, so no mark walk.
|
||||
void BeforeReadOnlyVerb() { PushPersistentMapsBeforeVerb(); }
|
||||
|
||||
// =============================================================================
|
||||
// CLASS B - the five slots the verb census measured (CONTRACT-P5.md §7)
|
||||
// =============================================================================
|
||||
|
||||
void EmitClear(GLbitfield mask) {
|
||||
ClientSession& session = RequireSession("Clear");
|
||||
BeforeReadOnlyVerb();
|
||||
|
||||
if (g_dropClearEmission) {
|
||||
// E2's negative control. Everything above still ran, so the only difference
|
||||
// between this arm and the live one is the record - which is exactly the
|
||||
// statement "the picture comes from the wire" that E2 exists to prove.
|
||||
++g_droppedClearEmissions;
|
||||
return;
|
||||
}
|
||||
|
||||
MG_Pipe::MGPClear record{};
|
||||
// The DRAW framebuffer is whatever the server's own SyncRenderState resolves from
|
||||
// gPipeInputs, which the client's MGP_FILL(Clear) at GL_Drawing.cpp:534 has just
|
||||
// written and the verb barrier keeps still (R-1). Naming a handle here would be a
|
||||
// SECOND statement of the binding, and the second one is the one that goes stale.
|
||||
record.Fbo = MG_Pipe::kMGPipeNullHandle;
|
||||
record.Kind = kRemoteClearWhole;
|
||||
record.DrawBufferIndex = -1;
|
||||
record.BufferMask = static_cast<Uint32>(mask);
|
||||
record.ValueClass = 0;
|
||||
session.EmitAndWait(MG_Pipe::MGPWireOp::Clear, &record, sizeof(record), nullptr, 0,
|
||||
nullptr, 0, nullptr);
|
||||
}
|
||||
|
||||
void EmitDrawArrays(GLenum mode, GLint first, GLsizei count) {
|
||||
ClientSession& session = RequireSession("DrawArrays");
|
||||
BeforeDrawVerb();
|
||||
|
||||
MG_Pipe::MGPDrawInfo info{};
|
||||
info.Mode = static_cast<Uint32>(mode);
|
||||
info.IndexSize = 0; // arrays
|
||||
info.Flags = 0; // NO kDrawHasUserIndices: the reduced path draws from a VBO
|
||||
info.InstanceCount = 1;
|
||||
info.StartInstance = 0;
|
||||
info.RestartIndex = 0;
|
||||
info.DrawIdOffset = 0;
|
||||
info.IndexResource = MG_Pipe::kMGPipeNullHandle;
|
||||
info.MinIndex = ~0u; // "unknown", MGPipeTypes.h:1330
|
||||
info.MaxIndex = ~0u;
|
||||
info.XfbCpuCapturedVertices = 0;
|
||||
info.NumDraws = 1;
|
||||
|
||||
const MG_Pipe::MGPDrawRange range{static_cast<Uint32>(first), static_cast<Uint32>(count), 0};
|
||||
// One tail of exactly NumDraws entries. w1's encoder recomputes that from the
|
||||
// payload and Fatals on a disagreement, on THIS side - so a NumDraws that drifted
|
||||
// from the tail is a producer-side abort rather than a corrupt stream a peer has to
|
||||
// diagnose.
|
||||
session.EmitAndWait(MG_Pipe::MGPWireOp::DrawVbo, &info, sizeof(info), &range,
|
||||
sizeof(range), nullptr, 0, nullptr);
|
||||
}
|
||||
|
||||
void EmitBlitFramebuffer(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0,
|
||||
GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask,
|
||||
GLenum filter) {
|
||||
ClientSession& session = RequireSession("BlitFramebuffer");
|
||||
BeforeReadOnlyVerb();
|
||||
|
||||
MG_Pipe::MGPBlit record{};
|
||||
// Same reasoning as Clear's Fbo: the read and draw bindings are gPipeInputs', set
|
||||
// by MGP_FILL(BlitFramebuffer) at GL_Framebuffer.cpp:660 and held still by the
|
||||
// barrier. glBlitNamedFramebuffer, which DOES name two framebuffers, is class C.
|
||||
record.ReadFbo = MG_Pipe::kMGPipeNullHandle;
|
||||
record.DrawFbo = MG_Pipe::kMGPipeNullHandle;
|
||||
record.SrcX0 = srcX0;
|
||||
record.SrcY0 = srcY0;
|
||||
record.SrcX1 = srcX1;
|
||||
record.SrcY1 = srcY1;
|
||||
record.DstX0 = dstX0;
|
||||
record.DstY0 = dstY0;
|
||||
record.DstX1 = dstX1;
|
||||
record.DstY1 = dstY1;
|
||||
record.Mask = static_cast<Uint32>(mask);
|
||||
record.Filter = static_cast<Uint32>(filter);
|
||||
session.EmitAndWait(MG_Pipe::MGPWireOp::Blit, &record, sizeof(record), nullptr, 0,
|
||||
nullptr, 0, nullptr);
|
||||
}
|
||||
|
||||
// How many bytes glReadPixels will pack for this rectangle, from the PACK half of the
|
||||
// pixel-store state.
|
||||
//
|
||||
// ID-49: THE PACK STATE NEVER CROSSES FOR A READ, AND DstSize IS THE TIGHT EXTENT.
|
||||
// The first version of this computed GL 4.6 8.4.4's PACKED size - row length, skips,
|
||||
// alignment - and handed it over as DstSize. v1's server allocates exactly DstSize and
|
||||
// the real backend honours the live pack state, so a 4x3 RGBA8 read with
|
||||
// PACK_ROW_LENGTH=8, SKIP_ROWS=1, SKIP_PIXELS=2 allocated 80 bytes and the driver wrote
|
||||
// to byte 120. That is the shape of the joint inproc lane's two
|
||||
// DepthReadbackHonoursThePackPixelStoreParameters SEGFAULTs, on both backends.
|
||||
//
|
||||
// So the wire carries a RECTANGLE and not a layout: the server reads with NEUTRAL pack
|
||||
// state into a tight w*h*bytesPerPixel run that IS the reply payload, and the CLIENT -
|
||||
// which is the side that holds the application's pack state, and the only side that
|
||||
// can - scatters those rows into the application's pointer. "OnReadPixels writes
|
||||
// exactly DstSize bytes" still holds; DstSize is now a number both sides derive from
|
||||
// the same three values instead of one side deriving it from state the other cannot
|
||||
// see.
|
||||
//
|
||||
// IT IS FORMAT-AGNOSTIC ON PURPOSE. The depth and depth-stencil reads the 21 split
|
||||
// entries touch take the same rule with no special case, because the rule is about the
|
||||
// LAYOUT and not about the component: bytesPerPixel is whatever the format sizes to.
|
||||
Uint64 ReadbackBytesPerPixel(GLenum format, GLenum type) {
|
||||
const TextureInputFormat inputFormat =
|
||||
MG_Util::ConvertGLEnumToTextureInputFormat(format);
|
||||
const TexturePixelDataType dataType = MG_Util::ConvertGLEnumToTexturePixelDataType(type);
|
||||
const SizeT bytesPerPixel = MG_Util::GetInputBytesPerPixel(inputFormat, dataType);
|
||||
if (bytesPerPixel == 0) {
|
||||
// NOT a guess and not a zero-length reply. A format this build cannot size is a
|
||||
// readback whose answer would be silently truncated, which is the one failure a
|
||||
// picture comparison cannot see.
|
||||
MGLOG_F("MGPipe: Fatal{UnsizedReadback, \"read_pixels\"} format=0x%04x type=0x%04x "
|
||||
"- the client must declare MGPReadbackInfo::DstSize and cannot size this "
|
||||
"pair; P5's reduced path reads RGBA/UNSIGNED_BYTE",
|
||||
static_cast<unsigned>(format), static_cast<unsigned>(type));
|
||||
std::abort();
|
||||
}
|
||||
return static_cast<Uint64>(bytesPerPixel);
|
||||
}
|
||||
|
||||
Uint64 TightReadbackBytes(GLsizei width, GLsizei height, GLenum format, GLenum type) {
|
||||
if (width <= 0 || height <= 0) return 0;
|
||||
return static_cast<Uint64>(width) * static_cast<Uint64>(height) *
|
||||
ReadbackBytesPerPixel(format, type);
|
||||
}
|
||||
|
||||
// M2 / codex 11: the reply the server posted is COMPLETE and OK. A short OK reply, and a
|
||||
// DECLINED or ERROR reply with a zero payload, both leave the destination full of stale
|
||||
// bytes; scattering or returning it is the silently truncated picture ID-47's own comment
|
||||
// says an SSIM comparison cannot see, arriving through the status field rather than
|
||||
// through truncation. `expected` is the record's own DstSize (CONTRACT-P5 row 23: the
|
||||
// reply's exact extent). The predicate is at namespace scope (below) and exposed for the
|
||||
// control, so R-16's "drive the production predicate" holds rather than a second copy of
|
||||
// the rule in the test.
|
||||
|
||||
// The same predicate at the call site, with the named Fatal each failure mode owns.
|
||||
// status > expected cannot reach here: EmitAndWait already aborts Fatal{ReplyTooLarge} on
|
||||
// an oversize reply, so the only failures left are a wrong status or a SHORT one.
|
||||
void RequireReadbackReplyComplete(Int32 status, Uint64 replySize, Uint64 expected) {
|
||||
if (status == Wire::ReplySink::kStatusError) {
|
||||
MGLOG_F("MGPipe: Fatal{ReplyError, \"ReadPixels\"} - the readback answered ERROR; "
|
||||
"the destination is left untouched rather than filled with stale bytes");
|
||||
std::abort();
|
||||
}
|
||||
if (status == Wire::ReplySink::kStatusDeclined) {
|
||||
MGLOG_F("MGPipe: Fatal{ReadbackDeclined, \"ReadPixels\"} - the server has no "
|
||||
"GL.ReadPixels and DECLINED; a decline is a real answer for an acceptance "
|
||||
"row (R-5) but a blocking readback has no pixels to return, so it is a "
|
||||
"Fatal here rather than a buffer of stale bytes");
|
||||
std::abort();
|
||||
}
|
||||
if (replySize != expected) {
|
||||
MGLOG_F("MGPipe: Fatal{ReadbackReplyShort, \"ReadPixels %llu < %llu\"} - the OK "
|
||||
"reply carried fewer bytes than the read's own DstSize (CONTRACT-P5 row "
|
||||
"23's exact extent); the missing rows would otherwise be scattered as "
|
||||
"whatever the destination held",
|
||||
static_cast<unsigned long long>(replySize),
|
||||
static_cast<unsigned long long>(expected));
|
||||
std::abort();
|
||||
}
|
||||
}
|
||||
|
||||
void EmitReadPixels(GLint x, GLint y, GLsizei width, GLsizei height, GLenum format,
|
||||
GLenum type, void* pixels) {
|
||||
ClientSession& session = RequireSession("ReadPixels");
|
||||
|
||||
// ID-57 / M8: A PACK-PBO DESTINATION IS REFUSED BY NAME, BEFORE ANY EMISSION AND
|
||||
// BEFORE `pixels` IS TOUCHED. With GL_PIXEL_PACK_BUFFER bound, the frontend permits
|
||||
// `pixels` to be a byte OFFSET into that buffer, not an address (GL_Framebuffer.cpp:
|
||||
// 3055 aligns it to the type size, one byte for UNSIGNED_BYTE) - and this emitter has
|
||||
// no PBO branch: it sets DstOffset = 0, hands the offset to EmitAndWait as a host
|
||||
// buffer, and the reply is memcpy'd to CPU address <offset>. Under monolith the
|
||||
// backend maps the PBO and writes the reply into the buffer (unchanged). The real
|
||||
// split form - the server writes the reply into the buffer resource and the client
|
||||
// marks it GPU-written (b1's MarkReadPixelsPackBuffer becoming the producer contract
|
||||
// §3 names) - is a P6 ROADMAP item. In P5 it is class C's shape (R-4), refused here.
|
||||
if (MG_State::pGLContext != nullptr &&
|
||||
MG_State::pGLContext->GetBufferBindingSlot(::MobileGL::BufferTarget::PixelPack)
|
||||
.GetBoundObject()) {
|
||||
UnmigratedVerbFatal("ReadPixels+PACK_BUFFER");
|
||||
}
|
||||
|
||||
BeforeReadOnlyVerb();
|
||||
|
||||
// THE PBO HALF IS b1's DESIGN AND b1 ALREADY WIRED ITS MARK, at
|
||||
// GL_Framebuffer.cpp:3109 - immediately after this table call returns, inside
|
||||
// ReadPixels_Backend itself. So this emitter deliberately does NOT call
|
||||
// MarkReadPixelsPackBuffer(): a second call there would be the "wire it twice"
|
||||
// shape, and the per-row counter b1's unit cases assert on would then count one
|
||||
// read as two. (In P5 the refusal above means no PBO read reaches here at all; the
|
||||
// note stays for the P6 form.)
|
||||
if (width <= 0 || height <= 0) return;
|
||||
const Uint64 bytesPerPixel = ReadbackBytesPerPixel(format, type);
|
||||
// ONE tight-size function for production AND the control (M3 / codex 10a). The first
|
||||
// cut computed this inline here while the test drove TightReadbackByteCount, so a
|
||||
// `+16` on the production line stayed green - the test observed a different number.
|
||||
// Now the number the server allocates and the number the test asserts come from the
|
||||
// same body.
|
||||
const Uint64 tight = TightReadbackBytes(width, height, format, type);
|
||||
|
||||
MG_Pipe::MGPReadbackInfo info{};
|
||||
info.Res = MG_Pipe::kMGPipeNullHandle; // "the bound read surface answers"
|
||||
info.Box = MG_Pipe::MGPBox{x, y, 0, static_cast<Uint32>(width),
|
||||
static_cast<Uint32>(height), 1};
|
||||
info.Format = static_cast<Uint32>(format);
|
||||
info.Type = static_cast<Uint32>(type);
|
||||
info.Target = 0;
|
||||
info.Level = 0;
|
||||
info.DstOffset = 0;
|
||||
info.DstSize = tight;
|
||||
|
||||
// CHECKED BEFORE THE EMISSION, not after the answer (ID-47), and through S1's
|
||||
// HELPER rather than a copy of it here. A reply bigger than a slot is Fatal on the
|
||||
// SERVER too, and s1 keeps that as the last line of defence - but it fires on the
|
||||
// apply thread with the record already on the wire, where all the client sees is a
|
||||
// hang. This one names the read, at the call site that knows what the read was.
|
||||
//
|
||||
// THE NUMBER IS ID-49's TIGHT EXTENT and not the packed one: the pack state never
|
||||
// crosses, so the answer that has to fit a slot is w*h*bytesPerPixel. The cap is
|
||||
// the pool's own, read live, so s1's growth of SEG_REPLY to 16 MiB / eight 2 MiB
|
||||
// slots needed no edit in this file - only the merge.
|
||||
session.RequireReadPixelsReplyFits(static_cast<Uint32>(width),
|
||||
static_cast<Uint32>(height),
|
||||
static_cast<Uint32>(format),
|
||||
static_cast<Uint32>(type), tight);
|
||||
|
||||
PixelStoreParameters pack{};
|
||||
if (MG_State::pGLContext != nullptr) {
|
||||
pack = MG_State::pGLContext->GetPixelStoreParameters(/*isUnpack=*/false);
|
||||
}
|
||||
|
||||
Int32 status = 0;
|
||||
Uint64 replySize = 0;
|
||||
if (ReadbackPackStateIsTight(width, bytesPerPixel, pack)) {
|
||||
// THE COMMON CASE, AND IT KEEPS THE ZERO-COPY. A neutral pack state means the
|
||||
// destination layout IS the tight layout, so the reply lands straight in the
|
||||
// application's buffer and there is no bounce at all. It is a fast path for the
|
||||
// SAME bytes, not a second rule: ScatterTightReadback below is a memcpy of the
|
||||
// whole run in exactly this case, and the control drives that function.
|
||||
session.EmitAndWait(MG_Pipe::MGPWireOp::ReadPixels, &info, sizeof(info), nullptr, 0,
|
||||
pixels, tight, &status, &replySize);
|
||||
// M2 / codex 11: an OK reply that arrived short, or a DECLINE/ERROR, must not be
|
||||
// handed back as pixels. The Fatal aborts before the application reads the buffer,
|
||||
// so the bytes EmitAndWait already copied into `pixels` are never observed.
|
||||
RequireReadbackReplyComplete(status, replySize, tight);
|
||||
return;
|
||||
}
|
||||
|
||||
// The bounce is the price of the application having asked for a layout. It is the
|
||||
// tight size and never more, and it is freed before this returns - R-11's rule one
|
||||
// level out: nothing here outlives the call.
|
||||
Vector<Uint8> bounce(static_cast<SizeT>(tight));
|
||||
session.EmitAndWait(MG_Pipe::MGPWireOp::ReadPixels, &info, sizeof(info), nullptr, 0,
|
||||
bounce.data(), tight, &status, &replySize);
|
||||
// BEFORE THE SCATTER, so a short or non-OK reply never reaches the application's
|
||||
// pointer at all (the bounce is the only thing that held the partial bytes).
|
||||
RequireReadbackReplyComplete(status, replySize, tight);
|
||||
ScatterTightReadbackIntoPackState(bounce.data(), pixels, width, height, bytesPerPixel,
|
||||
pack);
|
||||
}
|
||||
|
||||
void EmitPresent() {
|
||||
ClientSession& session = RequireSession("Present");
|
||||
BeforeReadOnlyVerb();
|
||||
|
||||
MG_Pipe::MGPPresent record{};
|
||||
// FrameSerial 0 = "the server stamps its own". P5 has no client-side present credit
|
||||
// (MOBILEGL_IPC_PRESENT_CREDIT is P6's), so a client-minted serial would be a second
|
||||
// id space with no consumer.
|
||||
record.FrameSerial = 0;
|
||||
session.EmitAndWait(MG_Pipe::MGPWireOp::Present, &record, sizeof(record), nullptr, 0,
|
||||
nullptr, 0, nullptr);
|
||||
|
||||
// R-12's invalidation edge, drained at the one boundary every target crosses. A
|
||||
// second CapsSnapshot IS the invalidation; nothing else on the client can see that
|
||||
// the server re-ran InitCapabilities, because GLContext::GetCompileEnv()'s memo is
|
||||
// keyed on pActiveBackendObject.get() (Core.cpp:34) and that pointer never changes
|
||||
// under split.
|
||||
session.PumpControlPlane();
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// CLASS A - answered locally from the caps mirror (R-15). NO RECORD, EVER.
|
||||
// =============================================================================
|
||||
|
||||
void AnswerGetIntegeri_v(GLenum target, GLuint index, GLint* data) {
|
||||
if (data == nullptr) return;
|
||||
const MG_Backend::DynamicBackendParameters& dynamic = CapsMirrorInstance().Dynamic();
|
||||
// The ONLY two indexed pnames the device owns; every other indexed pname names
|
||||
// frontend state and is answered in GL_Getter::GetIntegeri_v before any table is
|
||||
// consulted (BackendObject.h:196-205). The existing gate is
|
||||
// AdvertisedLimitsScenario.ComputeWorkGroupLimitsAreTheCapsBlocksAnswer, which pins
|
||||
// that this answer and the caps copy are ONE number.
|
||||
switch (target) {
|
||||
case GL_MAX_COMPUTE_WORK_GROUP_COUNT:
|
||||
if (index < 3) *data = static_cast<GLint>(dynamic.MaxComputeWorkGroupCount[index]);
|
||||
return;
|
||||
case GL_MAX_COMPUTE_WORK_GROUP_SIZE:
|
||||
if (index < 3) *data = static_cast<GLint>(dynamic.MaxComputeWorkGroupSize[index]);
|
||||
return;
|
||||
default:
|
||||
// Not a Fatal: the slot's own contract is "whatever pname the frontend has no
|
||||
// case for at all", and the monolith backends answer such a pname by leaving
|
||||
// the driver's own default in place. Answering a wrong number would be worse
|
||||
// than answering none.
|
||||
MGLOG_W_ONCE("MG_Remote client: GetIntegeri_v(0x%04x, %u) is not one of the two "
|
||||
"device-owned indexed pnames and has no caps-mirror answer",
|
||||
static_cast<unsigned>(target), static_cast<unsigned>(index));
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
Bool AnswerIsTimerQuerySupported() {
|
||||
// A capability predicate, not a call. Today a null slot means COUNTER_BITS == 0
|
||||
// (GL_Query.cpp:792) - which is precisely the null check R-4 forbids, so it moves
|
||||
// here, to the bit the server published.
|
||||
return CapsMirrorInstance().HasCap(MG_Pipe::kCapTimerQuery);
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// CLASS C - Fatal{UnmigratedVerb}. 64 slots: 63 in GLFunctionsTable + SetSwapInterval.
|
||||
// =============================================================================
|
||||
//
|
||||
// PARTITIONED BY THE P5b PACKAGE THAT OWNS THE FLIP (MG_Remote/CONTRACT-P5B.md,
|
||||
// ~/w7/notes/p5b/BRIEF-P5B.md), so that four packages migrating in parallel edit four
|
||||
// DISJOINT lists and four DISJOINT counts rather than one list and one number. To flip a
|
||||
// slot a package (1) removes its X row from ITS list, (2) assigns the real emitter in
|
||||
// BuildRemoteEmitTable's class-B block, (3) raises ITS kEmittedSlots* by one. The
|
||||
// per-package ownership assertions below then still hold, the totals stay arithmetic,
|
||||
// and a slot that changes class without changing the arithmetic is a build break. The
|
||||
// X-macro shape is kept so the DEFINITION and the ASSIGNMENT cannot drift apart. Three
|
||||
// slots carry a body the macro cannot (DispatchCompute, DispatchComputeIndirect,
|
||||
// SetSwapInterval) and are written out by hand below.
|
||||
//
|
||||
// d1 indexed / instanced / multi-draw / indirect draws -> draw_vbo (59), its
|
||||
// kDrawIsIndirect tail and its kDrawHasUserIndices span
|
||||
// i1 image bind, compute, barriers, copy-image, storage block -> bind_shader_image
|
||||
// (72), launch_grid (60), memory_barrier (61), resource_copy_region (53),
|
||||
// set_storage_block_binding (75)
|
||||
// t2 the XFB spans and object bind, the patch parameter -> begin/end/pause/resume_
|
||||
// stream_output (62..65), bind_stream_output (74), patch_parameter (73)
|
||||
// f1 the clear family, the framebuffer-sourced copies, mips -> clear (57),
|
||||
// copy_framebuffer_to_texture (76), generate_mipmap (54)
|
||||
// tail the wave-3 remainder nothing measured: queries, syncs, the texture readbacks,
|
||||
// the DSA blit, the swap interval (census-classC.md "static cross")
|
||||
|
||||
#define MGR_UNMIGRATED_D1_SLOTS(X) \
|
||||
X(DrawElements, void, (GLenum, GLsizei, GLenum, const void*)) \
|
||||
X(DrawElementsBaseVertex, void, (GLenum, GLsizei, GLenum, const void*, GLint)) \
|
||||
X(MultiDrawArrays, void, (GLenum, const GLint*, const GLsizei*, GLsizei)) \
|
||||
X(MultiDrawElements, void, (GLenum, const GLsizei*, GLenum, const GLvoid* const*, GLsizei)) \
|
||||
X(MultiDrawElementsBaseVertex, void, \
|
||||
(GLenum, const GLsizei*, GLenum, const GLvoid* const*, GLsizei, const GLint*)) \
|
||||
X(MultiDrawElementsIndirect, void, (GLenum, GLenum, const void*, GLsizei, GLsizei)) \
|
||||
X(MultiDrawArraysIndirect, void, (GLenum, const void*, GLsizei, GLsizei)) \
|
||||
X(MultiDrawElementsIndirectCount, void, (GLenum, GLenum, const void*, GLintptr, GLsizei, GLsizei)) \
|
||||
X(MultiDrawArraysIndirectCount, void, (GLenum, const void*, GLintptr, GLsizei, GLsizei)) \
|
||||
X(DrawRangeElementsBaseVertex, void, \
|
||||
(GLenum, GLuint, GLuint, GLsizei, GLenum, const void*, GLint)) \
|
||||
X(DrawRangeElements, void, (GLenum, GLuint, GLuint, GLsizei, GLenum, const void*)) \
|
||||
X(DrawElementsInstancedBaseVertexBaseInstance, void, \
|
||||
(GLenum, GLsizei, GLenum, const void*, GLsizei, GLint, GLuint)) \
|
||||
X(DrawElementsInstancedBaseVertex, void, (GLenum, GLsizei, GLenum, const void*, GLsizei, GLint)) \
|
||||
X(DrawElementsInstancedBaseInstance, void, \
|
||||
(GLenum, GLsizei, GLenum, const void*, GLsizei, GLuint)) \
|
||||
X(DrawElementsInstanced, void, (GLenum, GLsizei, GLenum, const void*, GLsizei)) \
|
||||
X(DrawArraysInstancedBaseInstance, void, (GLenum, GLint, GLsizei, GLsizei, GLuint)) \
|
||||
X(DrawArraysInstanced, void, (GLenum, GLint, GLsizei, GLsizei)) \
|
||||
X(DrawElementsIndirect, void, (GLenum, GLenum, const void*)) \
|
||||
X(DrawArraysIndirect, void, (GLenum, const void*))
|
||||
|
||||
// DispatchCompute and DispatchComputeIndirect are i1's too; they are hand-written below
|
||||
// because they carry b1's dispatch hook before the Fatal.
|
||||
#define MGR_UNMIGRATED_I1_SLOTS(X) \
|
||||
X(BindImageTexture, void, (GLuint, GLuint, GLint, GLboolean, GLint, GLenum, GLenum)) \
|
||||
X(CopyImageSubData, void, \
|
||||
(const MG_Backend::CopyImageEndpoint&, GLenum, GLint, GLint, GLint, GLint, \
|
||||
const MG_Backend::CopyImageEndpoint&, GLenum, GLint, GLint, GLint, GLint, GLsizei, GLsizei, \
|
||||
GLsizei)) \
|
||||
X(MemoryBarrier, void, (GLbitfield)) \
|
||||
X(MemoryBarrierByRegion, void, (GLbitfield)) \
|
||||
X(ShaderStorageBlockBinding, void, (GLuint, const GLchar*, GLuint))
|
||||
|
||||
#define MGR_UNMIGRATED_T2_SLOTS(X) \
|
||||
X(PatchParameteri, void, (GLenum, GLint)) \
|
||||
X(BeginTransformFeedback, void, (GLenum)) \
|
||||
X(EndTransformFeedback, void, ()) \
|
||||
X(PauseTransformFeedback, void, ()) \
|
||||
X(ResumeTransformFeedback, void, ()) \
|
||||
X(BindTransformFeedback, void, (GLuint)) \
|
||||
X(DeleteTransformFeedback, void, (GLuint))
|
||||
|
||||
#define MGR_UNMIGRATED_F1_SLOTS(X) \
|
||||
X(ClearBufferfi, void, (GLenum, GLint, GLfloat, GLint)) \
|
||||
X(ClearBufferfv, void, (GLenum, GLint, const GLfloat*)) \
|
||||
X(ClearBufferuiv, void, (GLenum, GLint, const GLuint*)) \
|
||||
X(ClearBufferiv, void, (GLenum, GLint, const GLint*)) \
|
||||
X(ClearNamedFramebufferfv, void, \
|
||||
(const SharedPtr<MG_State::GLState::FramebufferObject>&, GLenum, GLint, const GLfloat*)) \
|
||||
X(ClearNamedFramebufferfi, void, \
|
||||
(const SharedPtr<MG_State::GLState::FramebufferObject>&, GLenum, GLint, GLfloat, GLint)) \
|
||||
X(ClearNamedFramebufferiv, void, \
|
||||
(const SharedPtr<MG_State::GLState::FramebufferObject>&, GLenum, GLint, const GLint*)) \
|
||||
X(ClearNamedFramebufferuiv, void, \
|
||||
(const SharedPtr<MG_State::GLState::FramebufferObject>&, GLenum, GLint, const GLuint*)) \
|
||||
X(CopyTexImage2D, void, (GLenum, GLint, GLenum, GLint, GLint, GLsizei, GLsizei, GLint)) \
|
||||
X(CopyTexSubImage2D, void, (GLenum, GLint, GLint, GLint, GLint, GLint, GLsizei, GLsizei)) \
|
||||
X(GenerateMipmap, void, (GLenum))
|
||||
|
||||
// The wave-3 tail. SetSwapInterval is hand-written below (it is not a GL.* slot).
|
||||
#define MGR_UNMIGRATED_TAIL_SLOTS(X) \
|
||||
X(BlitNamedFramebuffer, void, \
|
||||
(const SharedPtr<MG_State::GLState::FramebufferObject>&, \
|
||||
const SharedPtr<MG_State::GLState::FramebufferObject>&, GLint, GLint, GLint, GLint, GLint, \
|
||||
GLint, GLint, GLint, GLbitfield, GLenum)) \
|
||||
X(GetTexImage, void, (GLenum, GLint, GLenum, GLenum, GLvoid*)) \
|
||||
X(GetTextureImage, void, \
|
||||
(const SharedPtr<MG_State::GLState::ITextureObject>&, TextureUploadTarget, GLint, GLenum, \
|
||||
GLenum, GLsizei, GLvoid*)) \
|
||||
X(WaitSync, void, (MG_Backend::BackendSyncHandle, GLbitfield, GLuint64)) \
|
||||
X(DeleteSync, void, (MG_Backend::BackendSyncHandle)) \
|
||||
X(EndTimeElapsedQuery, void, (MG_Backend::BackendQueryHandle)) \
|
||||
X(DeleteBackendQuery, void, (MG_Backend::BackendQueryHandle)) \
|
||||
X(EndOcclusionQuery, void, (MG_Backend::BackendQueryHandle)) \
|
||||
X(EndXfbPrimitivesQuery, void, (MG_Backend::BackendQueryHandle))
|
||||
|
||||
// The non-void ones, kept apart only because the macro body differs: a [[noreturn]]
|
||||
// call is a complete body for a void slot and for a value-returning one alike, but a
|
||||
// compiler that does not see UnmigratedVerbFatal's attribute through the macro would
|
||||
// warn on the second. It does see it; they are split for readability. All ten are the
|
||||
// wave-3 tail.
|
||||
#define MGR_UNMIGRATED_TAIL_VALUE_SLOTS(X) \
|
||||
X(FenceSync, MG_Backend::BackendSyncHandle, ()) \
|
||||
X(ClientWaitSync, GLenum, (MG_Backend::BackendSyncHandle, GLbitfield, GLuint64)) \
|
||||
X(GetSyncStatus, Bool, (MG_Backend::BackendSyncHandle)) \
|
||||
X(BeginTimeElapsedQuery, MG_Backend::BackendQueryHandle, ()) \
|
||||
X(QueryCounterTimestamp, MG_Backend::BackendQueryHandle, ()) \
|
||||
X(IsQueryResultAvailable, Bool, (MG_Backend::BackendQueryHandle)) \
|
||||
X(GetQueryResult64, Bool, (MG_Backend::BackendQueryHandle, Bool, Uint64*)) \
|
||||
X(BeginOcclusionQuery, MG_Backend::BackendQueryHandle, ()) \
|
||||
X(BeginXfbPrimitivesQuery, MG_Backend::BackendQueryHandle, (Bool)) \
|
||||
X(GetGpuTimestampNs, Int64, ())
|
||||
|
||||
// The union, for the places that want every class-C row at once (the definitions and
|
||||
// the assignments). A package never edits THIS; it edits its own list above.
|
||||
#define MGR_UNMIGRATED_GL_SLOTS(X) \
|
||||
MGR_UNMIGRATED_D1_SLOTS(X) \
|
||||
MGR_UNMIGRATED_I1_SLOTS(X) \
|
||||
MGR_UNMIGRATED_T2_SLOTS(X) \
|
||||
MGR_UNMIGRATED_F1_SLOTS(X) \
|
||||
MGR_UNMIGRATED_TAIL_SLOTS(X)
|
||||
#define MGR_UNMIGRATED_GL_VALUE_SLOTS(X) MGR_UNMIGRATED_TAIL_VALUE_SLOTS(X)
|
||||
|
||||
#define MGR_DEFINE_UNMIGRATED(Name, Ret, Sig) \
|
||||
Ret Name##_Unmigrated Sig { UnmigratedVerbFatal(#Name); }
|
||||
|
||||
MGR_UNMIGRATED_GL_SLOTS(MGR_DEFINE_UNMIGRATED)
|
||||
MGR_UNMIGRATED_GL_VALUE_SLOTS(MGR_DEFINE_UNMIGRATED)
|
||||
#undef MGR_DEFINE_UNMIGRATED
|
||||
|
||||
// THE TWO COMPUTE SLOTS CARRY b1's DISPATCH HOOK BEFORE THE FATAL, and this is stated
|
||||
// rather than hidden. MarkGpuWritesForDispatch() belongs immediately before the
|
||||
// dispatch record, and the dispatch record is class C until i1 lands - so the call site
|
||||
// is here, in the right place, and is UNREACHABLE-IN-EFFECT: the abort follows it. The
|
||||
// package that moves DispatchCompute into class B (i1: launch_grid, opcode 60) replaces
|
||||
// the Fatal and inherits a call site that is already correct rather than discovering
|
||||
// that the mark walk was never wired.
|
||||
void DispatchCompute_Unmigrated(GLuint, GLuint, GLuint) {
|
||||
PushPersistentMapsBeforeVerb();
|
||||
MarkGpuWritesForDispatch();
|
||||
UnmigratedVerbFatal("DispatchCompute");
|
||||
}
|
||||
void DispatchComputeIndirect_Unmigrated(GLintptr) {
|
||||
PushPersistentMapsBeforeVerb();
|
||||
MarkGpuWritesForDispatch();
|
||||
UnmigratedVerbFatal("DispatchComputeIndirect");
|
||||
}
|
||||
|
||||
void SetSwapInterval_Unmigrated(Int) { UnmigratedVerbFatal("SetSwapInterval"); }
|
||||
|
||||
// The counts, as arithmetic. MGR_COUNT_ONE expands to `+ 1` per row.
|
||||
#define MGR_COUNT_ONE(Name, Ret, Sig) +1
|
||||
constexpr Uint32 kUnmigratedD1 = 0 MGR_UNMIGRATED_D1_SLOTS(MGR_COUNT_ONE);
|
||||
// + DispatchCompute, DispatchComputeIndirect, written out by hand.
|
||||
constexpr Uint32 kUnmigratedI1 = 0 MGR_UNMIGRATED_I1_SLOTS(MGR_COUNT_ONE) + 2;
|
||||
constexpr Uint32 kUnmigratedT2 = 0 MGR_UNMIGRATED_T2_SLOTS(MGR_COUNT_ONE);
|
||||
constexpr Uint32 kUnmigratedF1 = 0 MGR_UNMIGRATED_F1_SLOTS(MGR_COUNT_ONE);
|
||||
// + SetSwapInterval, written out by hand.
|
||||
constexpr Uint32 kUnmigratedTail =
|
||||
0 MGR_UNMIGRATED_TAIL_SLOTS(MGR_COUNT_ONE) MGR_UNMIGRATED_TAIL_VALUE_SLOTS(MGR_COUNT_ONE) + 1;
|
||||
#undef MGR_COUNT_ONE
|
||||
constexpr Uint32 kUnmigratedSlots =
|
||||
kUnmigratedD1 + kUnmigratedI1 + kUnmigratedT2 + kUnmigratedF1 + kUnmigratedTail;
|
||||
|
||||
// The emitted counts, PER OWNER. P5's five are c1's; each P5b package raises its own.
|
||||
constexpr Uint32 kEmittedSlotsP5 = 5; // Clear, DrawArrays, ReadPixels, Blit, Present
|
||||
constexpr Uint32 kEmittedSlotsD1 = 0;
|
||||
constexpr Uint32 kEmittedSlotsI1 = 0;
|
||||
constexpr Uint32 kEmittedSlotsT2 = 0;
|
||||
constexpr Uint32 kEmittedSlotsF1 = 0;
|
||||
constexpr Uint32 kEmittedSlots =
|
||||
kEmittedSlotsP5 + kEmittedSlotsD1 + kEmittedSlotsI1 + kEmittedSlotsT2 + kEmittedSlotsF1;
|
||||
constexpr Uint32 kLocallyAnsweredSlots = 2; // GetIntegeri_v, IsTimerQuerySupported
|
||||
|
||||
// EACH PACKAGE'S OWNERSHIP, PINNED. A package that flips a slot removes one row and
|
||||
// adds one to its emitted count; a package that touches another's list breaks the
|
||||
// other's line, not its own. The four numbers are the census's package tables plus the
|
||||
// unmeasured companions that share a wire row (BRIEF-P5B.md file-ownership table).
|
||||
static_assert(kUnmigratedD1 + kEmittedSlotsD1 == 19, "d1 owns the 19 draw slots");
|
||||
static_assert(kUnmigratedI1 + kEmittedSlotsI1 == 7, "i1 owns the 7 image/compute/barrier/copy/SSBO slots");
|
||||
static_assert(kUnmigratedT2 + kEmittedSlotsT2 == 7, "t2 owns the 7 XFB/tessellation slots");
|
||||
static_assert(kUnmigratedF1 + kEmittedSlotsF1 == 11, "f1 owns the 11 clear/copy/mip slots");
|
||||
static_assert(kUnmigratedTail == 20, "the wave-3 tail is 20 slots and no P5b package owns one");
|
||||
static_assert(kUnmigratedSlots == 64, "CONTRACT-P5.md §7 class C is 64 slots at the P5b contract commit");
|
||||
static_assert(kLocallyAnsweredSlots + kEmittedSlots + kUnmigratedSlots == kRemoteEmitSlotCount,
|
||||
"the three classes no longer partition the 71 slots");
|
||||
|
||||
MG_Backend::GlobalBackendFunctionsTable BuildRemoteEmitTable() {
|
||||
g_dropClearEmission = ReadDropClearFromEnvironment();
|
||||
MG_Backend::GlobalBackendFunctionsTable table{};
|
||||
|
||||
// ---- class C first, so that a slot forgotten below stays Fatal rather than null.
|
||||
// Order matters for exactly this reason: if class B's assignment were first, a
|
||||
// typo in class C would leave a NULL slot, and a null slot is 91 potential null
|
||||
// calls with no diagnostic. This way the worst a mistake can do is name a verb
|
||||
// that was supposed to be emitted, loudly.
|
||||
#define MGR_ASSIGN_UNMIGRATED(Name, Ret, Sig) table.GL.Name = &Name##_Unmigrated;
|
||||
MGR_UNMIGRATED_GL_SLOTS(MGR_ASSIGN_UNMIGRATED)
|
||||
MGR_UNMIGRATED_GL_VALUE_SLOTS(MGR_ASSIGN_UNMIGRATED)
|
||||
#undef MGR_ASSIGN_UNMIGRATED
|
||||
table.GL.DispatchCompute = &DispatchCompute_Unmigrated;
|
||||
table.GL.DispatchComputeIndirect = &DispatchComputeIndirect_Unmigrated;
|
||||
table.SetSwapInterval = &SetSwapInterval_Unmigrated;
|
||||
|
||||
// ---- class A
|
||||
table.GL.GetIntegeri_v = &AnswerGetIntegeri_v;
|
||||
table.GL.IsTimerQuerySupported = &AnswerIsTimerQuerySupported;
|
||||
// NOT A SLOT and not a verb: a Bool member of the table, whose one non-test client
|
||||
// reader is GL_Query.cpp:221. It does NOT ride inside MGPCaps::Dynamic - it is a
|
||||
// member of GLFunctionsTable, which is exactly the thing a split client never
|
||||
// receives - so it is answered from kCapCpuXfbPrimitiveAccounting.
|
||||
table.GL.PrefersCpuXfbPrimitiveAccounting =
|
||||
CapsMirrorInstance().PrefersCpuXfbPrimitiveAccounting();
|
||||
|
||||
// ---- class B
|
||||
table.GL.Clear = &EmitClear;
|
||||
table.GL.DrawArrays = &EmitDrawArrays;
|
||||
table.GL.ReadPixels = &EmitReadPixels;
|
||||
table.GL.BlitFramebuffer = &EmitBlitFramebuffer;
|
||||
table.Present = &EmitPresent;
|
||||
|
||||
return table;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
const MG_Backend::GlobalBackendFunctionsTable& RemoteEmitTable() {
|
||||
MGLOG_F("MGPipe: Fatal{UnimplementedEmitTable, \"RemoteEmitTable\"} - P5 package c1 has "
|
||||
"not landed this yet; c0 shipped the signature only");
|
||||
std::abort();
|
||||
// Leaked at exit like every other MG_Remote singleton (ID-8): MG_Backend::Init()
|
||||
// copies it into gBackendFunctionsTable and MobileGL::Destroy() clears that copy from
|
||||
// an exit handler, by which point a static destructor here would already have run.
|
||||
static const MG_Backend::GlobalBackendFunctionsTable& table =
|
||||
*new MG_Backend::GlobalBackendFunctionsTable{BuildRemoteEmitTable()};
|
||||
return table;
|
||||
}
|
||||
|
||||
Uint32 ImplementedVerbCount() { return 0; }
|
||||
Uint32 ImplementedVerbCount() { return kEmittedSlots; }
|
||||
Uint32 LocallyAnsweredSlotCount() { return kLocallyAnsweredSlots; }
|
||||
Uint32 UnmigratedSlotCount() { return kUnmigratedSlots; }
|
||||
|
||||
void SetDropClearEmissionForNegativeControl(Bool drop) { g_dropClearEmission = drop; }
|
||||
Uint64 DroppedClearEmissions() { return g_droppedClearEmissions; }
|
||||
|
||||
Bool ReadbackPackStateIsTightForTest(GLsizei width, Uint64 bytesPerPixel,
|
||||
const PixelStoreParameters& pack) {
|
||||
return ReadbackPackStateIsTight(width, bytesPerPixel, pack);
|
||||
}
|
||||
|
||||
Uint64 TightReadbackByteCount(GLsizei width, GLsizei height, GLenum format, GLenum type) {
|
||||
return TightReadbackBytes(width, height, format, type);
|
||||
}
|
||||
|
||||
// M2 / codex 11's predicate at namespace scope: the one RequireReadbackReplyComplete decides
|
||||
// on and the one the control drives. 0=OK / 1=DECLINED / 2=ERROR.
|
||||
Bool ReadbackReplyIsComplete(Int32 status, Uint64 replySize, Uint64 expected) {
|
||||
return status == Wire::ReplySink::kStatusOk && replySize == expected;
|
||||
}
|
||||
|
||||
// ID-49's scatter. Exported for the same reason as the refusal above: the control drives
|
||||
// THIS, which is what the emitter calls, rather than a second copy of 8.4.4's arithmetic.
|
||||
void ScatterTightReadbackIntoPackState(const void* tight, void* destination, GLsizei width,
|
||||
GLsizei height, Uint64 bytesPerPixel,
|
||||
const PixelStoreParameters& pack) {
|
||||
if (tight == nullptr || destination == nullptr || width <= 0 || height <= 0) return;
|
||||
const Uint64 rowPixels =
|
||||
pack.RowLength > 0 ? static_cast<Uint64>(pack.RowLength) : static_cast<Uint64>(width);
|
||||
const Uint64 alignment = pack.Alignment > 0 ? static_cast<Uint64>(pack.Alignment) : 1ull;
|
||||
const Uint64 strideBytes =
|
||||
((rowPixels * bytesPerPixel + alignment - 1) / alignment) * alignment;
|
||||
// m6: the client re-derives GL 4.6 8.4.4's pack layout, so it honours GL_PACK_ROW_LENGTH
|
||||
// VERBATIM - including the ill-formed 0 < ROW_LENGTH < width, where the row stride is
|
||||
// narrower than a written row and consecutive rows overlap. GL leaves that case to the
|
||||
// implementation; the client reproduces exactly what the monolith backend's own scatter
|
||||
// would do with the same state rather than clamping, so the two arms stay byte-identical.
|
||||
// The fast path (ReadbackPackStateIsTight) already rejects any ROW_LENGTH != width, so
|
||||
// this only runs on the scatter path the application asked for.
|
||||
const Uint64 writtenPerRow = static_cast<Uint64>(width) * bytesPerPixel;
|
||||
// SKIP_IMAGES and IMAGE_HEIGHT ARE IGNORED (codex 6). glReadPixels is a 2-D read; GL
|
||||
// does not apply the image-level pack parameters to it, and the monolith conversion path
|
||||
// says so explicitly with honorPackImageParams=false (DirectGLES.cpp:10905). Applying
|
||||
// SKIP_IMAGES here shifted a read with SKIP_IMAGES=1 by a whole image and overran an
|
||||
// application buffer sized for exactly `height` rows. Only SKIP_ROWS and SKIP_PIXELS -
|
||||
// the 2-D skips - offset the first written byte.
|
||||
auto* out = static_cast<Uint8*>(destination) +
|
||||
static_cast<Uint64>(pack.SkipRows) * strideBytes +
|
||||
static_cast<Uint64>(pack.SkipPixels) * bytesPerPixel;
|
||||
const auto* in = static_cast<const Uint8*>(tight);
|
||||
for (Uint64 row = 0; row < static_cast<Uint64>(height); ++row) {
|
||||
std::memcpy(out + row * strideBytes, in + row * writtenPerRow,
|
||||
static_cast<SizeT>(writtenPerRow));
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace MobileGL::MG_Remote::Client
|
||||
|
||||
@@ -47,19 +47,36 @@
|
||||
// disappears. A null check on a slot may not survive into the client: it becomes a caps-mirror
|
||||
// read, which is what ARCHITECTURE.md:114 means by "CallMask replaces 'is this table slot null'".
|
||||
//
|
||||
// NOTE the asymmetry this table does not resolve: the resource, CSO, framebuffer, texture,
|
||||
// sampler and program families do NOT come through here. They are emitted from
|
||||
// MG_Impl/Pipe/* by direct MGPipeApply* calls (37 entry points, 41 call sites), and under
|
||||
// split each of those becomes an encode. This table covers only the verbs - the draws,
|
||||
// clears, blits, readbacks, queries, fences and present.
|
||||
// NOTE the asymmetry this table does not resolve, AND WHERE IT IS RESOLVED (R-17): the
|
||||
// resource, CSO, framebuffer, texture, sampler and program families do NOT come through here.
|
||||
// They were emitted from MG_Impl/Pipe/* by 40 direct calls to the 37 MGPipeApply* entry
|
||||
// points; those call sites now go through the two generated tables
|
||||
// (MG_Pipe/PipeRoute.h -> MG_Remote/Client/WireTables.cpp). This table covers only the verbs -
|
||||
// the draws, clears, blits, readbacks, queries, fences and present.
|
||||
|
||||
#pragma once
|
||||
#include <Includes.h>
|
||||
|
||||
#include <MG_Backend/BackendObject.h>
|
||||
// P5b: the clear discriminants below alias MGPipeTypes.h's (CONTRACT-P5B.md f1). The header
|
||||
// was already in this file's closure through BackendObject.h's neighbours; naming it makes
|
||||
// the dependency the aliases have explicit.
|
||||
#include <MG_Pipe/MGPipeTypes.h>
|
||||
#include <MG_Pipe/MGPipeValueTypes.h>
|
||||
|
||||
namespace MobileGL::MG_Remote::Client {
|
||||
|
||||
// MGPClear::Kind and ::ValueClass. P5b MOVED THE NUMBERS INTO MGPipeTypes.h
|
||||
// (kMGPipeClearKind* / kMGPipeClearValueClass*, CONTRACT-P5B.md f1) - the single spelling
|
||||
// this header and the server's PipeApplier.h each said they were waiting for. These are
|
||||
// aliases so c1's EmitClear reads unchanged; f1's four ClearBuffer* emitters and the DSA
|
||||
// form name the MG_Pipe constants directly.
|
||||
inline constexpr Uint32 kRemoteClearWhole = MG_Pipe::kMGPipeClearKindWhole;
|
||||
inline constexpr Uint32 kRemoteClearColor = MG_Pipe::kMGPipeClearKindColor;
|
||||
inline constexpr Uint32 kRemoteClearDepth = MG_Pipe::kMGPipeClearKindDepth;
|
||||
inline constexpr Uint32 kRemoteClearStencil = MG_Pipe::kMGPipeClearKindStencil;
|
||||
inline constexpr Uint32 kRemoteClearDepthStencil = MG_Pipe::kMGPipeClearKindDepthStencil;
|
||||
|
||||
// The table MG_Backend::Init() installs into gBackendFunctionsTable for the remote role.
|
||||
// A reference to a never-destroyed block, like every other MG_Remote singleton (ID-8).
|
||||
const MG_Backend::GlobalBackendFunctionsTable& RemoteEmitTable();
|
||||
@@ -77,4 +94,63 @@ namespace MobileGL::MG_Remote::Client {
|
||||
// a slot added to GLFunctionsTable without a decision here is a build break.
|
||||
inline constexpr Uint32 kRemoteEmitSlotCount = 71;
|
||||
|
||||
// The other two thirds of the census, so a case can assert the WHOLE partition rather than
|
||||
// only the half that emits. CONTRACT-P5.md §7's three classes are 2 + 5 + 64, and
|
||||
// EmitTables.cpp static_asserts that they sum to kRemoteEmitSlotCount: a slot that quietly
|
||||
// changes class shows up as a build break in the sum, not as a silent behaviour change.
|
||||
Uint32 LocallyAnsweredSlotCount(); // class A - answered from the caps mirror, R-15
|
||||
Uint32 UnmigratedSlotCount(); // class C - Fatal{UnmigratedVerb}
|
||||
|
||||
// THE E2 NEGATIVE CONTROL (t1's debt against c1, BRIEF §7). When set, the Clear emitter
|
||||
// SKIPS its record - it still runs the pre-verb hooks and still returns - so a replay that
|
||||
// is really going through the wire loses one clear per frame and its SSIM falls below the
|
||||
// 0.99 threshold, while a replay that fell through to the driver is unaffected. It is a
|
||||
// function rather than a knob in Config.h for two reasons: the control has to be settable
|
||||
// from a test process that has already started, and a knob would be a
|
||||
// MOBILEGL_IPC_-shaped name for something no operator may ever set.
|
||||
//
|
||||
// Emissions actually skipped, so the control can assert that it DID something rather than
|
||||
// that a picture changed - a control that silently never fired is the third shape of R-16's
|
||||
// "a gate that cannot go red for its own reason".
|
||||
void SetDropClearEmissionForNegativeControl(Bool drop);
|
||||
Uint64 DroppedClearEmissions();
|
||||
|
||||
// ID-47. The CLIENT refuses a readback whose answer would not fit a reply slot, BEFORE it
|
||||
// emits the record, and names the read. THE REFUSAL ITSELF IS s1's -
|
||||
// ClientSession::RequireReadPixelsReplyFits, forwarding to
|
||||
// ReplySlotPool::RequireReadPixelsFits - and this package does not own a second copy of the
|
||||
// message: two spellings of one refusal is how the two sides come to disagree about which
|
||||
// reads are legal. What c1 owns is the CALL SITE and the number it passes, which is ID-49's
|
||||
// tight extent; the control below is over that, and s1-v3.md §1's cases are over the
|
||||
// helper.
|
||||
|
||||
// ID-49. `MGPReadbackInfo::DstSize` is the TIGHT w*h*bytesPerPixel extent - the reply
|
||||
// payload - and nothing about the application's pack state crosses the wire. The server
|
||||
// reads with a NEUTRAL pack state into that run; this is the number both sides derive.
|
||||
Uint64 TightReadbackByteCount(GLsizei width, GLsizei height, GLenum format, GLenum type);
|
||||
|
||||
// ID-49. Scatters the tight rows into the application's pointer per the application's own
|
||||
// pack state (ROW_LENGTH, SKIP_*, ALIGNMENT), which only the client holds. Exposed for the
|
||||
// same reason as the refusal above: the control drives the function the emitter calls
|
||||
// rather than a second copy of GL 4.6 8.4.4's arithmetic. THE GAPS ARE NEVER WRITTEN -
|
||||
// they belong to the application - and that is what the control checks with a sentinel.
|
||||
void ScatterTightReadbackIntoPackState(const void* tight, void* destination, GLsizei width,
|
||||
GLsizei height, Uint64 bytesPerPixel,
|
||||
const PixelStoreParameters& pack);
|
||||
|
||||
// ID-49. True when the destination layout IS the tight layout, which is the only condition
|
||||
// under which EmitReadPixels may read the reply straight into the application pointer and
|
||||
// skip the bounce. Exported because the FAST PATH and the SCATTER have to agree, and the
|
||||
// only honest way to state that is to drive both and compare - a case that tested either
|
||||
// alone would pass a predicate that said yes to a layout the scatter would have rearranged.
|
||||
Bool ReadbackPackStateIsTightForTest(GLsizei width, Uint64 bytesPerPixel,
|
||||
const PixelStoreParameters& pack);
|
||||
|
||||
// M2 / codex 11. True exactly when the readback reply is OK and carries the read's own exact
|
||||
// extent (CONTRACT-P5 row 23). EmitReadPixels calls this and Fatals by name when it is false
|
||||
// - a short OK reply, or a DECLINE/ERROR with a zero payload, is refused rather than scattered
|
||||
// as pixels. Exposed so the control drives the production predicate (R-16), not a copy: pass
|
||||
// 0=OK / 1=DECLINED / 2=ERROR as `status`.
|
||||
Bool ReadbackReplyIsComplete(Int32 status, Uint64 replySize, Uint64 expected);
|
||||
|
||||
} // namespace MobileGL::MG_Remote::Client
|
||||
|
||||
@@ -0,0 +1,200 @@
|
||||
// MobileGL - MobileGL/MG_Remote/Client/GpuWritePending.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 "GpuWritePending.h"
|
||||
|
||||
#include "ClientSession.h"
|
||||
|
||||
#include <MG_Pipe/PipeMutation.h>
|
||||
#include <MG_State/GLState/BufferState/BufferObject.h>
|
||||
#include <MG_State/GLState/Core.h>
|
||||
#include <MG_State/GLState/TextureState/TextureObjectBuffer.h>
|
||||
#include <MG_State/GLState/TextureState/TextureState.h>
|
||||
#include <MG_Util/Debug/Log.h>
|
||||
|
||||
#include <cstdlib>
|
||||
|
||||
namespace MobileGL::MG_Remote::Client {
|
||||
|
||||
using MG_State::GLState::BufferObject;
|
||||
using MobileGL::BufferTarget;
|
||||
using MG_State::GLState::ImageTextureBinding;
|
||||
|
||||
namespace {
|
||||
// Per-row tallies. Diagnostics, and the only thing a unit case can assert on: an
|
||||
// over-approximating set has no observable difference when a row fires too OFTEN, so
|
||||
// "did this row fire at all, for this buffer" has to be readable directly.
|
||||
Array<Uint64, static_cast<SizeT>(GpuWriteProducer::Count)> g_producerMarks{};
|
||||
|
||||
// The transform-feedback rows, shared by the draw walk (row 3) and by
|
||||
// glEndTransformFeedback (row 5). Both mark the SAME set - the capture targets of the
|
||||
// capture program - and the split exists only so the two can be counted apart.
|
||||
void MarkTransformFeedbackTargets(GpuWriteProducer producer) {
|
||||
auto& context = MG_State::pGLContext;
|
||||
if (!context) return;
|
||||
if (!context->IsTransformFeedbackActive()) return;
|
||||
const auto& program = context->GetTransformFeedbackProgram();
|
||||
if (program == nullptr) return;
|
||||
const SizeT declared = program->GetTransformFeedbackBufferCount();
|
||||
const SizeT count =
|
||||
declared < MG_State::GLState::GLContext::MAX_TRANSFORM_FEEDBACK_BUFFERS
|
||||
? declared
|
||||
: static_cast<SizeT>(MG_State::GLState::GLContext::MAX_TRANSFORM_FEEDBACK_BUFFERS);
|
||||
for (SizeT i = 0; i < count; ++i) {
|
||||
const auto& point =
|
||||
context->GetBufferBindingPoint(BufferTarget::TransformFeedback, static_cast<Uint>(i));
|
||||
MarkBufferForProducer(point.GetBoundObject(), producer);
|
||||
}
|
||||
}
|
||||
|
||||
void MarkShaderStorageBindings() {
|
||||
auto& context = MG_State::pGLContext;
|
||||
if (!context) return;
|
||||
// The TOUCHED count, exactly as the backend twin uses it
|
||||
// (DirectGLES.cpp:559-560): the binding-point array is 84 entries wide and
|
||||
// walking all of them on every draw is what the high-water mark exists to avoid.
|
||||
const SizeT points = context->GetTouchedBufferBindingPointCount(BufferTarget::ShaderStorage);
|
||||
for (SizeT i = 0; i < points; ++i) {
|
||||
const auto& point = context->GetBufferBindingPoint(BufferTarget::ShaderStorage, static_cast<Uint>(i));
|
||||
MarkBufferForProducer(point.GetBoundObject(), GpuWriteProducer::ShaderStorageBinding);
|
||||
}
|
||||
}
|
||||
|
||||
void MarkAtomicCounterBindings() {
|
||||
auto& context = MG_State::pGLContext;
|
||||
if (!context) return;
|
||||
// WIDER THAN ITS BACKEND TWIN, ON PURPOSE AND IN THE SAFE DIRECTION.
|
||||
// SyncAtomicCounterBuffers (DirectGLES.cpp:578-583) walks the GL bindings the
|
||||
// TRANSPILED program declared, which is a subset of what is bound; the client has
|
||||
// the bindings but not that per-program list at this point, so it marks every
|
||||
// touched atomic-counter point. Over-approximating costs a readback the narrowing
|
||||
// channel then removes. Under-approximating reads a stale counter and says
|
||||
// nothing, which is the failure every atomic-counter conformance case is.
|
||||
const SizeT points = context->GetTouchedBufferBindingPointCount(BufferTarget::AtomicCounter);
|
||||
for (SizeT i = 0; i < points; ++i) {
|
||||
const auto& point = context->GetBufferBindingPoint(BufferTarget::AtomicCounter, static_cast<Uint>(i));
|
||||
MarkBufferForProducer(point.GetBoundObject(), GpuWriteProducer::AtomicCounterBinding);
|
||||
}
|
||||
}
|
||||
|
||||
void MarkWritableImageBufferTextures() {
|
||||
auto& context = MG_State::pGLContext;
|
||||
if (!context) return;
|
||||
// The backend keeps a bitset of writable image-buffer units
|
||||
// (DirectGLES.cpp:2350-2352, maintained from its own SyncImageTextureBinding) and
|
||||
// the client has no equivalent, so it sweeps. The sweep is bounded by the array,
|
||||
// not by a device limit read: MaxImageUnits would be a backend read, and a stale
|
||||
// or absent backend object would silently shorten the walk - which is the one
|
||||
// direction this set may not fail in. The loop body is a null test on a
|
||||
// contiguous array until a unit is actually bound. P5 records cost and does not
|
||||
// gate on it (2026-09-08 rule); an image-unit high-water mark on GLContext is the
|
||||
// obvious narrowing and belongs with P8's binding-walk migration.
|
||||
for (Int unit = 0; unit < MG_State::GLState::TextureState::MAX_TEXTURE_IMAGE_UNITS; ++unit) {
|
||||
const auto& binding = context->GetImageTextureBinding(unit);
|
||||
if (!ImageUnitIsAWritableBufferTexture(binding)) continue;
|
||||
auto* textureBuffer = static_cast<MG_State::GLState::TextureObjectBuffer*>(binding.Texture.get());
|
||||
MarkBufferForProducer(textureBuffer->GetBufferBindingSlot().GetBoundObject(),
|
||||
GpuWriteProducer::WritableImageBufferTexture);
|
||||
}
|
||||
}
|
||||
} // namespace
|
||||
|
||||
Bool GpuWriteSetIsClientSide() {
|
||||
return MG_Config::Transport != MG_Config::TransportMode::Monolith;
|
||||
}
|
||||
|
||||
Bool ImageUnitIsAWritableBufferTexture(const ImageTextureBinding& binding) {
|
||||
// Verbatim from IsWritableImageBufferTexture (DirectGLES.cpp:2354-2357). All three
|
||||
// terms are client state; none of them is a driver question.
|
||||
return binding.Texture != nullptr && binding.Access != GL_READ_ONLY &&
|
||||
binding.Texture->GetStorageType() == TextureStorageType::Buffer;
|
||||
}
|
||||
|
||||
void MarkBufferForProducer(const SharedPtr<BufferObject>& buffer, GpuWriteProducer producer) {
|
||||
if (!GpuWriteSetIsClientSide()) return;
|
||||
if (buffer == nullptr) return;
|
||||
if (producer >= GpuWriteProducer::Count) return;
|
||||
buffer->MarkGpuWritten();
|
||||
++g_producerMarks[static_cast<SizeT>(producer)];
|
||||
}
|
||||
|
||||
void MarkGpuWritesForDraw() {
|
||||
if (!GpuWriteSetIsClientSide()) return;
|
||||
MarkShaderStorageBindings();
|
||||
MarkAtomicCounterBindings();
|
||||
MarkWritableImageBufferTextures();
|
||||
MarkTransformFeedbackTargets(GpuWriteProducer::TransformFeedbackCapture);
|
||||
}
|
||||
|
||||
void MarkGpuWritesForDispatch() {
|
||||
if (!GpuWriteSetIsClientSide()) return;
|
||||
MarkShaderStorageBindings();
|
||||
MarkAtomicCounterBindings();
|
||||
MarkWritableImageBufferTextures();
|
||||
}
|
||||
|
||||
void MarkReadPixelsPackBuffer() {
|
||||
if (!GpuWriteSetIsClientSide()) return;
|
||||
auto& context = MG_State::pGLContext;
|
||||
if (!context) return;
|
||||
MarkBufferForProducer(context->GetBufferBindingSlot(BufferTarget::PixelPack).GetBoundObject(),
|
||||
GpuWriteProducer::ReadPixelsPackBuffer);
|
||||
}
|
||||
|
||||
void MarkEndTransformFeedbackCaptureTargets() {
|
||||
if (!GpuWriteSetIsClientSide()) return;
|
||||
MarkTransformFeedbackTargets(GpuWriteProducer::EndTransformFeedbackCapture);
|
||||
}
|
||||
|
||||
Uint64 ProducerMarkCount(GpuWriteProducer producer) {
|
||||
if (producer >= GpuWriteProducer::Count) return 0;
|
||||
return g_producerMarks[static_cast<SizeT>(producer)];
|
||||
}
|
||||
|
||||
void ResetProducerMarkCountsForTest() {
|
||||
g_producerMarks.fill(0);
|
||||
}
|
||||
|
||||
Bool BufferWritebackIsReachable(const BufferObject& buffer) {
|
||||
if (buffer.GetSize() == 0) return false;
|
||||
#if MOBILEGL_PIPE_PUSH
|
||||
return MG_Pipe::MGPipeResourceSubsystemEnabled();
|
||||
#else
|
||||
return false;
|
||||
#endif
|
||||
}
|
||||
|
||||
void AwaitBufferWriteback(BufferObject& buffer) {
|
||||
// THE WAIT IS THE BARRIER'S WAIT (R-3). The reply-slot id IS the record's seq, so
|
||||
// "appliedSeq reached my readback" and "my answer is back" are one condition, and
|
||||
// ClientSession::EmitAndWait is what pays for it. With no session - a build-split lane
|
||||
// running monolith, and every unit case - the emission WAS the application,
|
||||
// synchronously, so the writeback has already landed and there is nothing to wait for.
|
||||
// Spelling that as "return" rather than as a loop is deliberate: a loop here would be
|
||||
// a hang in exactly that configuration, which is the configuration every gate lane
|
||||
// runs.
|
||||
if (ClientSession::Active() == nullptr) return;
|
||||
|
||||
// AND THE OTHER ARM IS A NAMED FATAL, NOT AN EMPTY BODY. A session exists, so the
|
||||
// apply side is no longer synchronous, and if the flag is still set the shadow this
|
||||
// caller is about to read is STALE - which is the whole failure the third state was
|
||||
// introduced to stop. An empty body here would make that failure silent and would let
|
||||
// s1/c1 land a session without noticing that nobody ever wrote the wait; a stub that
|
||||
// aborts by name is the house shape for exactly this (EmitTables.cpp's
|
||||
// UnmigratedVerbFatal), and it is what gives the hole a red spelling before the
|
||||
// transport arrives.
|
||||
if (!buffer.HasOutstandingGpuWrite()) return;
|
||||
MGLOG_F("MGPipe: Fatal{UnimplementedWritebackWait} - a ClientSession is active and buffer %u "
|
||||
"still has an outstanding GPU write after its readback was emitted. The wait is "
|
||||
"ClientSession::EmitAndWait's (R-3: the reply slot id IS the record seq); P5 package "
|
||||
"b1 landed the third state and s1/c1 own the wait itself.",
|
||||
buffer.GetExternalIndex());
|
||||
std::abort();
|
||||
}
|
||||
|
||||
} // namespace MobileGL::MG_Remote::Client
|
||||
@@ -0,0 +1,152 @@
|
||||
// MobileGL - MobileGL/MG_Remote/Client/GpuWritePending.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
|
||||
|
||||
// THE CLIENT-SIDE CONSERVATIVE GPU-WRITE SET (ARCHITECTURE.md:575 names this component;
|
||||
// CONTRACT-P5.md section 3, table 2's first set). Owner: package b1.
|
||||
//
|
||||
// WHY IT HAS TO MOVE SIDES. `BufferObject::SyncGpuWrites` (BufferObject.cpp:369) runs
|
||||
// synchronously, on the application's thread, the moment the application calls glMapBuffer or
|
||||
// glGetBufferSubData. It has to answer "did the GPU write this buffer since I last read it?"
|
||||
// - and today all six producers of that answer are BACKEND-side (DirectGLES.cpp:570, :618,
|
||||
// :2603, UniformManager.cpp:1075, :1231, VulkanRenderer.cpp:11618), i.e. on the server's side
|
||||
// of a split. Asking the server is a round trip the design forbids in steady state, so the
|
||||
// client must build the set itself, from state it already owns: the SSBO and atomic-counter
|
||||
// binding points, the image units whose Access is not GL_READ_ONLY, and the transform-feedback
|
||||
// capture targets.
|
||||
//
|
||||
// CONSERVATIVE MEANS OVER-APPROXIMATE, AND THAT IS THE WHOLE DESIGN. The reverse channel's
|
||||
// OnGpuWritten is a NARROWING channel (ResourceTracker.h:577-581): the client marks
|
||||
// everything a shader COULD have written and the server only ever removes entries. So a row
|
||||
// here that fires too often costs a readback; a row that fires too rarely reads a stale shadow
|
||||
// and is silent. Every row below therefore mirrors its backend twin exactly, including the two
|
||||
// places the twin is deliberately NARROW - a GL_READ_ONLY image binding is left alone, and the
|
||||
// image walk runs from draw preparation rather than from glBindImageTexture's eager sync.
|
||||
//
|
||||
// NO NARROWING IN P5. ResourceTracker.h:587-592's `rangeCount == 1` assertion STAYS. Zero
|
||||
// ranges will mean "a fully narrowed set - nothing is dirty" at P8/P9, and a package that
|
||||
// reads ResourceTracker.h:577-581 alone will think it owns that already. It does not.
|
||||
//
|
||||
// THE TWO NEW PRODUCERS. Rows 4 and 5 have no backend twin: they are behaviour P5 ADDS
|
||||
// (ARCHITECTURE.md:508), and both are strictly better than what monolith does.
|
||||
// * glReadPixels into a pack PBO becomes fire-and-forget plus a client-side mark. Monolith
|
||||
// maps the PBO and copies it into the shadow inside the call (DirectGLES.cpp:10983-10993),
|
||||
// which is an unconditional stall on every glReadPixels whether or not anyone reads the
|
||||
// shadow; marking instead defers the cost to the first read that actually wants it.
|
||||
// * glEndTransformFeedback drops its unbounded ClientWaitSync (GL_Drawing.cpp:1367, timeout
|
||||
// ~0ull) and marks the capture targets, for the same reason: the wait exists only so that
|
||||
// a later MapBuffer sees real results, which is precisely what the flag is for.
|
||||
//
|
||||
// WHAT NO ROW COVERS, WRITTEN DOWN SO THE NEXT READER DOES NOT HAVE TO ASK. The set is built
|
||||
// from the APPLICATION's bindings, so it says nothing about a backend's own scratch buffers -
|
||||
// Espryt's converted-vertex-stream and primitive-restart substitution buffers, Magma's UBO
|
||||
// ring. None of those has a MarkGpuWritten today either, so the client set is no NARROWER than
|
||||
// monolith's and this is not a regression; it is a standing hole in both, and it stays one
|
||||
// until the phase that migrates the backend's own allocations.
|
||||
//
|
||||
// GATED ON THE TRANSPORT, like everything else in this package: on the monolith path the six
|
||||
// backend sites still run and a second marker would be new behaviour (D-J), and rows 4 and 5
|
||||
// would remove a stall monolith is entitled to keep.
|
||||
|
||||
#pragma once
|
||||
#include <Includes.h>
|
||||
|
||||
#include <Config.h>
|
||||
|
||||
namespace MobileGL::MG_State::GLState {
|
||||
class BufferObject;
|
||||
struct ImageTextureBinding;
|
||||
} // namespace MobileGL::MG_State::GLState
|
||||
|
||||
namespace MobileGL::MG_Remote::Client {
|
||||
|
||||
// ONE ROW PER PRODUCER, and the enum is the inventory: six that mirror a backend
|
||||
// MarkGpuWritten site one-for-one, two that P5 adds. Each has exactly one unit case, and
|
||||
// the per-row counters below are what those cases assert on - a row that stops firing is
|
||||
// otherwise invisible, because an over-approximating set fails SILENTLY in the direction
|
||||
// that matters.
|
||||
enum class GpuWriteProducer : Uint8 {
|
||||
// DirectGLES.cpp:570 (MarkShaderStorageBuffersGpuWritten) and
|
||||
// UniformManager.cpp:1231 (ResolveStorageBufferDescriptor): every SSBO binding point,
|
||||
// unconditional, once the points are bound and the draw or dispatch is going out.
|
||||
ShaderStorageBinding = 0,
|
||||
// DirectGLES.cpp:618 (SyncAtomicCounterBuffers): every bound atomic counter. The
|
||||
// point of a counter is that the shader increments it and every conformance case
|
||||
// reads the increment back with glMapBufferRange or glGetBufferSubData.
|
||||
AtomicCounterBinding,
|
||||
// DirectGLES.cpp:2603 (MarkWritableImageBufferTexturesGpuWritten) and
|
||||
// UniformManager.cpp:1075 (ResolveStorageTexelBufferDescriptor): a buffer texture on
|
||||
// an image unit, ONLY when Access != GL_READ_ONLY. Marking a read-only binding would
|
||||
// make the next map wait on - and then re-read - a dispatch that could not have
|
||||
// changed a byte of it.
|
||||
WritableImageBufferTexture,
|
||||
// VulkanRenderer.cpp:11618 (BeginXfbCaptureForDraw): the capture targets, because
|
||||
// "the capture is a GPU write like any shader's".
|
||||
TransformFeedbackCapture,
|
||||
// P5, new: glReadPixels into a bound GL_PIXEL_PACK_BUFFER.
|
||||
ReadPixelsPackBuffer,
|
||||
// P5, new: glEndTransformFeedback, in place of the unbounded fence wait.
|
||||
EndTransformFeedbackCapture,
|
||||
Count
|
||||
};
|
||||
|
||||
// Transport != Monolith. False means every entry point below is a no-op and the six
|
||||
// backend sites are still the only producers, which is exactly today's behaviour.
|
||||
Bool GpuWriteSetIsClientSide();
|
||||
|
||||
// ---- the walks -------------------------------------------------------------------
|
||||
//
|
||||
// Called from the client's own draw / dispatch emission point, BEFORE the verb record
|
||||
// goes out, for the same ordering reason the persistent-map push has: the set must
|
||||
// describe the work the record is about to start.
|
||||
|
||||
// Rows 0, 1, 2 and 3.
|
||||
void MarkGpuWritesForDraw();
|
||||
// Rows 0, 1 and 2. A dispatch has no transform feedback.
|
||||
void MarkGpuWritesForDispatch();
|
||||
|
||||
// ---- the two new producers -------------------------------------------------------
|
||||
|
||||
// Row 4. Marks whatever is bound to GL_PIXEL_PACK_BUFFER, or nothing when the read goes
|
||||
// to client memory - which is the case the backend's map-and-copy never had to consider,
|
||||
// because it only ran when a PBO was bound in the first place.
|
||||
void MarkReadPixelsPackBuffer();
|
||||
// Row 5. Must be called while the capture state is still ACTIVE: GLContext's
|
||||
// EndTransformFeedback clears the live bindings, so a mark taken after it marks nothing.
|
||||
void MarkEndTransformFeedbackCaptureTargets();
|
||||
|
||||
// ---- the row predicates, exposed so a unit case can drive one row at a time -------
|
||||
|
||||
// Row 2's discriminator, verbatim from DirectGLES.cpp:2354-2357. It is a function rather
|
||||
// than three inline conditions at the call site because it is the one row whose backend
|
||||
// twin is narrow on purpose, and a client that re-derived it slightly wider would mark
|
||||
// read-only image bindings with nothing able to see that it had.
|
||||
Bool ImageUnitIsAWritableBufferTexture(const MG_State::GLState::ImageTextureBinding& binding);
|
||||
|
||||
// The one place a row actually marks. Null and duplicate marks are absorbed here so the
|
||||
// walks stay readable, and the per-row counter moves only when a buffer really was
|
||||
// marked.
|
||||
void MarkBufferForProducer(const SharedPtr<MG_State::GLState::BufferObject>& buffer,
|
||||
GpuWriteProducer producer);
|
||||
|
||||
Uint64 ProducerMarkCount(GpuWriteProducer producer);
|
||||
void ResetProducerMarkCountsForTest();
|
||||
|
||||
// ---- SyncGpuWrites' third state (CONTRACT-P5.md section 3) -----------------------
|
||||
|
||||
// Blocks until this buffer's OnBufferWriteback has landed. With no session - a build-split
|
||||
// lane running monolith, and every unit case - the emission was synchronous and the answer
|
||||
// is already in, so this returns at once; that is why it is a call rather than a loop the
|
||||
// caller writes, because the loop would be a hang in exactly that configuration.
|
||||
void AwaitBufferWriteback(MG_State::GLState::BufferObject& buffer);
|
||||
|
||||
// Is there a readback route at all? A buffer with no size, or one whose backend registered
|
||||
// no resource ops, can never catch up, and SyncGpuWrites must clear rather than block for
|
||||
// ever. It is the ONE case monolith's unconditional clear covers that a writeback cannot.
|
||||
Bool BufferWritebackIsReachable(const MG_State::GLState::BufferObject& buffer);
|
||||
|
||||
} // namespace MobileGL::MG_Remote::Client
|
||||
@@ -0,0 +1,145 @@
|
||||
// MobileGL - MobileGL/MG_Remote/Client/PersistentMapTracker.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 "PersistentMapTracker.h"
|
||||
|
||||
#include <MG_State/GLState/BufferState/BufferObject.h>
|
||||
#include <MG_Util/Debug/Log.h>
|
||||
|
||||
#include <cstdlib>
|
||||
|
||||
namespace MobileGL::MG_Remote::Client {
|
||||
|
||||
using MG_State::GLState::BufferObject;
|
||||
using MobileGL::BufferMappingAccessBit;
|
||||
|
||||
PersistentMapTracker& PersistentMapTracker::Instance() {
|
||||
// Leaked on purpose, once, like every other role-local singleton (ID-8): a buffer's
|
||||
// destructor runs from exit handlers after this TU's globals would already be gone,
|
||||
// and it calls Forget().
|
||||
static PersistentMapTracker* instance = new PersistentMapTracker{};
|
||||
return *instance;
|
||||
}
|
||||
|
||||
Uint64 PersistentMapTracker::BlockBytes() {
|
||||
return static_cast<Uint64>(MG_Config::Ipc.PersistentBlockKb) * 1024ull;
|
||||
}
|
||||
|
||||
Bool PersistentMapTracker::PushIsArmed() {
|
||||
return MG_Config::Transport != MG_Config::TransportMode::Monolith;
|
||||
}
|
||||
|
||||
// SyncPersistentMappedRange's early-out chain (BufferObject.cpp:341-353), in its order,
|
||||
// read as a membership test. Every line here has a line there; if one of them moves, the
|
||||
// unit case that drives both against each other is what says so.
|
||||
Bool PersistentMapTracker::IsLivePersistentMap(const BufferObject& buffer) {
|
||||
if (!buffer.IsMapped()) return false;
|
||||
// GPU-resident: the application already wrote into coherent GPU memory and there is
|
||||
// nothing to ship. At tier T2 this arm is unreachable - MapPersistent declines - but
|
||||
// the predicate must still read the chain, not the tier: a build that reaches T0/T1
|
||||
// later must see this row answer for itself.
|
||||
if (buffer.IsBackendPersistentMapped()) return false;
|
||||
const auto access = buffer.GetMappingAccess();
|
||||
if (!(access & BufferMappingAccessBit::Persistent)) return false;
|
||||
if (!(access & BufferMappingAccessBit::Write)) return false;
|
||||
// FLUSH_EXPLICIT: the application promises to announce its own writes with
|
||||
// glFlushMappedBufferRange, which already crosses as resource_flush_range. Pushing
|
||||
// here as well would ship the same bytes twice and take the upload-shape decision
|
||||
// away from the side that pays for it.
|
||||
if (access & BufferMappingAccessBit::FlushExplicit) return false;
|
||||
const auto range = buffer.GetMappedRange();
|
||||
if (range.start >= range.end) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
void PersistentMapTracker::NoteMapStateChanged(BufferObject& buffer) {
|
||||
const Uint64 key = buffer.GetLifetimeId();
|
||||
if (IsLivePersistentMap(buffer)) {
|
||||
m_livePersistentMaps[key] = &buffer;
|
||||
return;
|
||||
}
|
||||
m_livePersistentMaps.erase(key);
|
||||
}
|
||||
|
||||
void PersistentMapTracker::Forget(const BufferObject& buffer) {
|
||||
m_livePersistentMaps.erase(buffer.GetLifetimeId());
|
||||
}
|
||||
|
||||
void PersistentMapTracker::PushBlocksFor(BufferObject& buffer) {
|
||||
if (!PushIsArmed()) return;
|
||||
// Re-checked rather than trusted. The set is maintained at five events and a sixth
|
||||
// one arriving without a NoteMapStateChanged would otherwise push a buffer whose
|
||||
// shadow has been released - an adopted store's Bytes() is the GPU map, and reading
|
||||
// it as if it were the shadow is how a "conservative" push turns into a fault.
|
||||
if (!IsLivePersistentMap(buffer)) {
|
||||
Forget(buffer);
|
||||
return;
|
||||
}
|
||||
const Uint64 blockBytes = BlockBytes();
|
||||
// 0 IS THE NEGATIVE CONTROL, NOT "unlimited" (E3(a)). Pushing one whole-span block
|
||||
// here would make the control green for the wrong reason - it has to disable the
|
||||
// push, so that PersistentCoherentMapScenario draws the last uploaded bytes and goes
|
||||
// red exactly the way an unpushed map does.
|
||||
if (blockBytes == 0) return;
|
||||
|
||||
const auto range = buffer.GetMappedRange();
|
||||
const Uint64 begin = static_cast<Uint64>(range.start);
|
||||
const Uint64 end = static_cast<Uint64>(range.end);
|
||||
for (Uint64 at = begin; at < end; at += blockBytes) {
|
||||
const Uint64 length = (end - at) < blockBytes ? (end - at) : blockBytes;
|
||||
buffer.PushMappedSpanBlock(static_cast<SizeT>(at), static_cast<SizeT>(length));
|
||||
++m_blocksPushed;
|
||||
m_bytesPushed += length;
|
||||
}
|
||||
}
|
||||
|
||||
void PersistentMapTracker::PushAllMembers() {
|
||||
if (!PushIsArmed()) return;
|
||||
if (m_livePersistentMaps.empty()) return;
|
||||
// Copied out first: PushBlocksFor can erase its own entry (a member that stopped
|
||||
// being one), and ska::flat_hash_map invalidates on erase.
|
||||
Vector<BufferObject*> members;
|
||||
members.reserve(m_livePersistentMaps.size());
|
||||
for (const auto& entry : m_livePersistentMaps) members.push_back(entry.second);
|
||||
for (BufferObject* buffer : members) {
|
||||
if (buffer != nullptr) PushBlocksFor(*buffer);
|
||||
}
|
||||
}
|
||||
|
||||
void PushPersistentMapsBeforeVerb() {
|
||||
PersistentMapTracker::Instance().PushAllMembers();
|
||||
}
|
||||
|
||||
Bool AdoptTierIsEmulate() {
|
||||
const Uint32 tier = MG_Config::Ipc.AdoptTier;
|
||||
if (tier == 2) return true;
|
||||
// A NAMED refusal, not a silent fall back to T2. T0 (a real cross-process shared
|
||||
// mapping) and T1 (a server-side staging map) are P11's, and the reason the knob
|
||||
// parses them today is that the negative control needs a spelling before the thing
|
||||
// it controls exists. Falling back would make `MOBILEGL_IPC_ADOPT_TIER=0` look like
|
||||
// a working T0 run and silently produce pmap bytes it must not produce.
|
||||
// 0 and 1 are the two CONTRACT §5 promises - a real cross-process shared mapping and a
|
||||
// server-side staging map - and they name P11. Anything else is not a tier at all, and
|
||||
// saying "P11 implements it" of a 7 would be a lie the operator then repeats. Both die
|
||||
// here rather than at parse, which is late: the abort lands at the first
|
||||
// map_persistent, so a mis-set run gets through EGL bring-up and a frame of setup
|
||||
// first. Moving it to the parse means a knob-validity rule in ConfigLoader, which is
|
||||
// c0's file; filed for the integrator rather than taken here.
|
||||
if (tier <= 1) {
|
||||
MGLOG_F("MGPipe: MOBILEGL_IPC_ADOPT_TIER=%u names adoption tier T%u, which P11 implements "
|
||||
"and P5 does not; P5 runs at T2 (emulate) only.",
|
||||
static_cast<unsigned>(tier), static_cast<unsigned>(tier));
|
||||
} else {
|
||||
MGLOG_F("MGPipe: MOBILEGL_IPC_ADOPT_TIER=%u is not an adoption tier; the only values are 0 "
|
||||
"and 1 (P11) and 2 (emulate, the P5 default).",
|
||||
static_cast<unsigned>(tier));
|
||||
}
|
||||
std::abort();
|
||||
}
|
||||
|
||||
} // namespace MobileGL::MG_Remote::Client
|
||||
@@ -0,0 +1,139 @@
|
||||
// MobileGL - MobileGL/MG_Remote/Client/PersistentMapTracker.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
|
||||
|
||||
// THE BLOCK-GRANULARITY PERSISTENT-MAP PUSH (P5 R-6, CONTRACT-P5.md section 3, table 2's
|
||||
// second set). Owner: package b1.
|
||||
//
|
||||
// WHY THIS EXISTS AT ALL. A coherent persistent map is the one buffer shape with no per-write
|
||||
// API call: the application memcpys through the pointer and neither a serial, an epoch nor a
|
||||
// record moves. In monolith that is free, because the pointer IS the backend's GPU storage -
|
||||
// MEASUREMENTS.md:87 prices the adoption at p99 163 -> 21 ms and ~400 MB saved, and
|
||||
// ARCHITECTURE.md:481 requires it to hold unmoved for the whole monolith track. Across a
|
||||
// process boundary the adopted address is meaningless, so P5 runs at tier T2 (emulate): the
|
||||
// client keeps the shadow, MGPipeApplyMapPersistent declines, and the bytes the application
|
||||
// wrote with no call have to be SHIPPED. `persistent-map-push` (PipeStats `pmap`) is exactly
|
||||
// those bytes, and it is structurally zero while adoption survives - which is why forcing T2
|
||||
// and wiring the counter are one deliverable and not two.
|
||||
//
|
||||
// THE SET. `m_livePersistentMaps` is SyncPersistentMappedRange's own early-out chain
|
||||
// (BufferObject.cpp:341-353) read as a membership test - mapped, NOT GPU-resident, Persistent,
|
||||
// Write, NOT FlushExplicit, non-empty mapped range - and nothing else. Reading it as a
|
||||
// predicate rather than re-deriving one is deliberate: the day that chain grows a sixth
|
||||
// early-out, a re-derived predicate silently keeps pushing a buffer the monolith path stopped
|
||||
// pushing, and the two arms diverge with no test able to say so. IsLivePersistentMap() is the
|
||||
// single spelling; BufferObject::SyncPersistentMappedRange is held to it by a unit case.
|
||||
//
|
||||
// THE GRANULARITY. MOBILEGL_IPC_PERSISTENT_BLOCK_KB (default 64) blocks, keyed
|
||||
// {MGPipeHandle, blockIndex} - the key is implicit, because a block ships as an ORDINARY
|
||||
// resource_subdata record whose destination range is [blockIndex * blockBytes, + blockBytes).
|
||||
// NO NEW RECORD KIND: the existing record is already chunked by
|
||||
// MGPipeForEachSubDataRecordRange and already acceptance-gated, and a second way to say
|
||||
// "these bytes go there" is a second way to get it wrong. A block size of 0 is E3(a)'s
|
||||
// NEGATIVE CONTROL and means "push nothing" - not "one unlimited block" - so
|
||||
// PersistentCoherentMapScenario must go red under it.
|
||||
//
|
||||
// PHASE 1 IS CONSERVATIVE, AND SAYS SO. The whole mapped span is pushed, by block, at every
|
||||
// validate point; no dirty bits, no memcmp. Phase 2 (MOBILEGL_IPC_SHADOW_SHM, P6+) makes it
|
||||
// precise, and ARCHITECTURE.md:499 grants it the right to be pulled forward if Phase 1 is
|
||||
// unacceptable on the Create/Flywheel fixtures - the one place in the plan where a
|
||||
// measurement may reorder phases.
|
||||
//
|
||||
// ORDERING IS THE CORRECTNESS PROPERTY, NOT THE GRANULARITY. In monolith the push is a memcpy
|
||||
// on the same thread as the draw that follows it, so the bytes the application wrote before
|
||||
// the draw are the bytes the draw sees. Under split both travel SEG_CMD in order, so the ring
|
||||
// preserves it - PROVIDED the push is emitted AT the validate point and not lazily. A push
|
||||
// deferred past its own draw record is the C-1 regression re-committed at the transport layer.
|
||||
|
||||
#pragma once
|
||||
#include <Includes.h>
|
||||
|
||||
#include <Config.h>
|
||||
|
||||
namespace MobileGL::MG_State::GLState {
|
||||
class BufferObject;
|
||||
}
|
||||
|
||||
namespace MobileGL::MG_Remote::Client {
|
||||
|
||||
class PersistentMapTracker {
|
||||
public:
|
||||
// Client-role singleton (table 3: the MG_Impl/MG_Remote/Client singletons are
|
||||
// client-exclusive). Leaks at exit for ID-8's reason, once per role-local singleton.
|
||||
static PersistentMapTracker& Instance();
|
||||
|
||||
// MOBILEGL_IPC_PERSISTENT_BLOCK_KB * 1024. Zero means the push is OFF (E3(a)).
|
||||
static Uint64 BlockBytes();
|
||||
// Transport != Monolith. The whole module is inert on the monolith path: an extra
|
||||
// resource_subdata record there would be new behaviour, which D-J forbids.
|
||||
static Bool PushIsArmed();
|
||||
|
||||
// SyncPersistentMappedRange's early-out chain as a predicate. THE only spelling.
|
||||
static Bool IsLivePersistentMap(const MG_State::GLState::BufferObject& buffer);
|
||||
|
||||
// Membership maintenance, both idempotent and both safe to call on a buffer that is
|
||||
// not a member. Called from BufferObject on every event that can move the predicate:
|
||||
// map, unmap, respecify, adoption, destruction.
|
||||
void NoteMapStateChanged(MG_State::GLState::BufferObject& buffer);
|
||||
void Forget(const MG_State::GLState::BufferObject& buffer);
|
||||
|
||||
// One member's whole mapped span, by block. Re-checks the predicate first, so a
|
||||
// member that stopped being one (an adoption, an unmap that did not route through
|
||||
// NoteMapStateChanged) is dropped rather than pushed.
|
||||
void PushBlocksFor(MG_State::GLState::BufferObject& buffer);
|
||||
|
||||
// THE VALIDATE-POINT HOOK. Every member, before the verb record is emitted.
|
||||
void PushAllMembers();
|
||||
|
||||
SizeT MemberCount() const { return m_livePersistentMaps.size(); }
|
||||
Uint64 BlocksPushed() const { return m_blocksPushed; }
|
||||
Uint64 BytesPushed() const { return m_bytesPushed; }
|
||||
// Unit tests only: the counters are diagnostics, the set is not reset by it.
|
||||
void ResetCountersForTest() {
|
||||
m_blocksPushed = 0;
|
||||
m_bytesPushed = 0;
|
||||
}
|
||||
void ClearForTest() {
|
||||
m_livePersistentMaps.clear();
|
||||
ResetCountersForTest();
|
||||
}
|
||||
|
||||
private:
|
||||
// Keyed on BufferObject::GetLifetimeId(), which is globally unique and never reused -
|
||||
// never the GL name (LIFO-recycled by glGenBuffers) and never the heap address
|
||||
// (recycled by the allocator). The raw pointer is safe because every removal path is
|
||||
// explicit: ~BufferObject and ReleaseMemory both call Forget/NoteMapStateChanged, and
|
||||
// PushBlocksFor re-checks the predicate before it dereferences anything it kept.
|
||||
UnorderedMap<Uint64, MG_State::GLState::BufferObject*> m_livePersistentMaps;
|
||||
Uint64 m_blocksPushed = 0;
|
||||
Uint64 m_bytesPushed = 0;
|
||||
};
|
||||
|
||||
// What the client's emit table calls immediately BEFORE emitting any verb that can read a
|
||||
// buffer (draw, dispatch, readback, blit, present). It is a free function rather than a
|
||||
// method so the emit table does not have to name the singleton, and so the one-line call
|
||||
// reads as what it is: "publish everything the application wrote with no call".
|
||||
//
|
||||
// In P5 the 21 SyncPersistentMappedRange sites (CONTRACT-P5.md section 3: 9 Espryt + 12
|
||||
// Magma, MEASUREMENTS.md:111's 20 being one low) still stand where they are and route
|
||||
// into PushBlocksFor through BufferObject::SyncPersistentMappedRange, so the push already
|
||||
// happens at every point monolith pushes at. They retire into THIS call at P8, when the
|
||||
// draw-path binding walks move to the client.
|
||||
void PushPersistentMapsBeforeVerb();
|
||||
|
||||
// R-6's tier gate, and the ONE spelling of it. True for MOBILEGL_IPC_ADOPT_TIER=2, the
|
||||
// only tier P5 implements; 0 (a real cross-process shared mapping) and 1 (a server-side
|
||||
// staging map) parse - so the negative control has a name before the thing it controls
|
||||
// exists - and are a NAMED refusal here rather than a silent fall back to T2. It is asked
|
||||
// by MGPipeApplyMapPersistent, which is where the decline is decided, so the client's
|
||||
// three adoption call sites keep their existing "null means declined" branch and the
|
||||
// map-persistent-roundtrips counter keeps counting ATTEMPTS in both arms (E3(c) asserts
|
||||
// mpr is equal between the monolith and the split arm, which is only true if the decline
|
||||
// happens after the count, on the applier's side of the emission).
|
||||
Bool AdoptTierIsEmulate();
|
||||
|
||||
} // namespace MobileGL::MG_Remote::Client
|
||||
@@ -0,0 +1,135 @@
|
||||
// MobileGL - MobileGL/MG_Remote/Client/SlotCaps.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
|
||||
|
||||
// THE 41 NULL CHECKS. Owner: package c1 (CONTRACT-P5.md §7, ID-14).
|
||||
//
|
||||
// FORTY-ONE OF THE SIXTY-NINE GLFunctionsTable SLOTS ARE NULL-CHECKED AT THEIR CALL SITE, AND
|
||||
// SEVERAL OF THOSE CHECKS ARE CAPABILITY PROBES RATHER THAN SAFETY CHECKS. R-4 forbids a null
|
||||
// slot in the client's emit table - so in that table every one of those probes would answer
|
||||
// "supported", and whatever fallback sits behind it would silently disappear. That is not a
|
||||
// theoretical risk: it is how a split lane produces a plausible picture for the wrong reason.
|
||||
// ARCHITECTURE.md:114 already said what replaces the probe - "CallMask replaces 'is this table
|
||||
// slot null' as the implicit capability probe" - and this header is the concrete list.
|
||||
//
|
||||
// TWO SPELLINGS, AND WHICH ONE A SITE TAKES IS DECIDED BY THE SLOT'S CLASS, NOT BY TASTE:
|
||||
//
|
||||
// MGL_BACKEND_SLOT_CAP(Slot, CapBit)
|
||||
// The capability has a published bit. Under split the answer is the SERVER's bit;
|
||||
// under monolith it is exactly today's null check, character for character.
|
||||
// The three cases CONTRACT-P5.md §7 names by hand are all of this shape:
|
||||
// GL_Query.cpp:481 / :558 / :785 BeginOcclusionQuery -> kCapOcclusionQuery
|
||||
// GL_Query.cpp:534 BeginXfbPrimitivesQuery -> kCapXfbPrimitivesQuery
|
||||
// PipeFill.cpp SubDataResident -> kCapResidentSubData
|
||||
// (the third is not a GLFunctionsTable slot but an op-table one, so it reads the bit
|
||||
// directly in PipeFill.cpp rather than through this header).
|
||||
//
|
||||
// MGL_BACKEND_SLOT_LOCAL(Slot)
|
||||
// The capability has NO published bit and the slot is CONTRACT-P5.md §7 class C -
|
||||
// Fatal{UnmigratedVerb} in the client's table. Under split the honest answer is
|
||||
// "absent", which is precisely what the monolith nullptr meant, so every fallback the
|
||||
// site already has survives instead of being replaced by an abort. Under monolith it is
|
||||
// again today's null check.
|
||||
//
|
||||
// WHY "ABSENT" AND NOT "LET IT FATAL". A Fatal is loud, and for the 28 UNGUARDED slots it is
|
||||
// strictly better than today (a null there is already an immediate crash with no diagnostic).
|
||||
// But a guarded site is guarded because the frontend has a real answer for the absent case -
|
||||
// always-signaled syncs, a CPU readback, CPU primitive accounting - and turning that answer
|
||||
// into an abort is a behaviour change nobody asked for, in the direction that stops a lane
|
||||
// dead. The class-C slot IS absent from this client; saying so is the accurate answer, not a
|
||||
// weakening of R-4.
|
||||
//
|
||||
// THE TEST THAT DECIDES WHETHER A GUARDED SITE IS CONVERTED AT ALL, and it is the half of the
|
||||
// walk the contract leaves to whoever does it: A PROBE MOVES ONLY WHERE "ABSENT" IS A CORRECT
|
||||
// AND SUFFICIENT ANSWER. Where the fallback behind the probe produces a RIGHT result, "absent"
|
||||
// is the accurate description of a client that does not have the slot, and converting keeps
|
||||
// the lane running. Where the fallback produces a SILENTLY WRONG result, converting would
|
||||
// manufacture exactly the defect R-4 exists to prevent, and the probe is left alone so the
|
||||
// class-C slot Fatals by name instead.
|
||||
//
|
||||
// Converted, because the fallback is right:
|
||||
// GL_Sync.cpp:59 FenceSync -> always-signaled syncs, which the table's own
|
||||
// header documents as the fallback and which GL
|
||||
// permits; every other sync site is already
|
||||
// guarded on syncObject->backendHandle, so this
|
||||
// one gate carries the whole family.
|
||||
// GL_Texture.cpp:6537 GetTextureImage -> the frontend's own CPU readback, which is exact
|
||||
// GL_Texture.cpp:6799 GetTexImage -> the same
|
||||
// GL_Getter.cpp x2 GetGpuTimestampNs -> 0, which BackendObject.h:192 already names as
|
||||
// the unsupported answer
|
||||
// GL_Query.cpp the four query probes -> CPU primitive accounting / target rejection /
|
||||
// COUNTER_BITS 0, all of them spec answers
|
||||
//
|
||||
// NOT converted, deliberately, because "absent" would be wrong rather than quiet:
|
||||
// GL_Drawing.cpp:1274/:1371/:1420/:1435/:1641/:1673 the transform-feedback span family. The
|
||||
// frontend reads a null EndTransformFeedback as "this backend does NOT own the capture,
|
||||
// so reorder the captured records for it" (FixupGsStripCaptureOrder, :1290). Under split
|
||||
// the server's backend DOES own it, so answering "absent" would reorder a capture that
|
||||
// was already in GL order - a silently corrupt buffer. Transform feedback is off P5's
|
||||
// reduced path (BRIEF §4's exclusion list) and its slots are class C, so the first XFB
|
||||
// call aborts by name, which is the outcome R-4 asks for.
|
||||
// GL_Drawing.cpp:844 PatchParameteri. "Absent" means the patch size is never set and every
|
||||
// tessellation draw silently uses the previous one. Class C; it aborts by name.
|
||||
//
|
||||
// WHAT THIS HEADER DELIBERATELY DOES NOT DO. It does not touch the 28 unguarded slots: those
|
||||
// have no probe to convert, and calling one reaches Fatal{UnmigratedVerb, "<slot>"} by name,
|
||||
// which is R-4's intent. And it does not invent a cap bit - a new MGPCapBit is an
|
||||
// MGPipeTypes.h edit and that file is c0's, so a family that needs one goes through the
|
||||
// integrator (the XFB span family is the first that will).
|
||||
//
|
||||
// G1: in a build without MOBILEGL_BUILD_DISAGGREGATED both macros expand to the null check the
|
||||
// site already had, so the pull build's code generation is unchanged.
|
||||
|
||||
#pragma once
|
||||
#include <Includes.h>
|
||||
|
||||
#include <Config.h>
|
||||
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
#include <MG_Pipe/MGPipeTypes.h>
|
||||
#include <MG_Remote/Client/CapsMirror.h>
|
||||
|
||||
#define MGL_BACKEND_SLOT_CAP(Slot, CapBit) \
|
||||
(::MobileGL::MG_Config::Transport != ::MobileGL::MG_Config::TransportMode::Monolith \
|
||||
? ::MobileGL::MG_Remote::Client::CapsMirrorInstance().HasCap(CapBit) \
|
||||
: ::MobileGL::MG_Backend::gBackendFunctionsTable.GL.Slot != nullptr)
|
||||
|
||||
#define MGL_BACKEND_SLOT_LOCAL(Slot) \
|
||||
(::MobileGL::MG_Config::Transport == ::MobileGL::MG_Config::TransportMode::Monolith && \
|
||||
::MobileGL::MG_Backend::gBackendFunctionsTable.GL.Slot != nullptr)
|
||||
|
||||
// The POINTER-valued forms, for the several sites shaped `if (const auto f = TABLE.GL.Slot)`.
|
||||
// They exist for G1 and for nothing else: a site rewritten from that shape into
|
||||
// `if (MGL_BACKEND_SLOT_CAP(...)) { const auto f = TABLE.GL.Slot; ... }` is semantically the
|
||||
// same and generated DIFFERENT CODE - the first measurement of this change moved
|
||||
// GL_Getter.cpp's GetInteger64v by -150 bytes and GetIntegerv by +2, which is two "resized"
|
||||
// symbols and a red G1. In a pull build these two expand to the slot expression ITSELF, so the
|
||||
// init-statement survives verbatim and the pull build's code generation cannot move.
|
||||
#define MGL_BACKEND_SLOT_PTR_CAP(Slot, CapBit) \
|
||||
(::MobileGL::MG_Config::Transport != ::MobileGL::MG_Config::TransportMode::Monolith \
|
||||
? (::MobileGL::MG_Remote::Client::CapsMirrorInstance().HasCap(CapBit) \
|
||||
? ::MobileGL::MG_Backend::gBackendFunctionsTable.GL.Slot \
|
||||
: nullptr) \
|
||||
: ::MobileGL::MG_Backend::gBackendFunctionsTable.GL.Slot)
|
||||
|
||||
#define MGL_BACKEND_SLOT_PTR_LOCAL(Slot) \
|
||||
(::MobileGL::MG_Config::Transport != ::MobileGL::MG_Config::TransportMode::Monolith \
|
||||
? nullptr \
|
||||
: ::MobileGL::MG_Backend::gBackendFunctionsTable.GL.Slot)
|
||||
|
||||
#else
|
||||
|
||||
#define MGL_BACKEND_SLOT_CAP(Slot, CapBit) \
|
||||
(::MobileGL::MG_Backend::gBackendFunctionsTable.GL.Slot != nullptr)
|
||||
#define MGL_BACKEND_SLOT_LOCAL(Slot) \
|
||||
(::MobileGL::MG_Backend::gBackendFunctionsTable.GL.Slot != nullptr)
|
||||
#define MGL_BACKEND_SLOT_PTR_CAP(Slot, CapBit) \
|
||||
(::MobileGL::MG_Backend::gBackendFunctionsTable.GL.Slot)
|
||||
#define MGL_BACKEND_SLOT_PTR_LOCAL(Slot) \
|
||||
(::MobileGL::MG_Backend::gBackendFunctionsTable.GL.Slot)
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,596 @@
|
||||
// MobileGL - MobileGL/MG_Remote/Client/WireTables.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
|
||||
|
||||
// The ENCODE TWIN of gMGPipeWireRecordApply: thirty-seven emitters that turn a table call into
|
||||
// a wire record. Owner: package c1 (P5 ruling R-17). See WireTables.h for the install order
|
||||
// and MG_Pipe/PipeRoute.h for what R-17 actually cost.
|
||||
//
|
||||
// EVERY EMITTER IS THE SAME FOUR STEPS, and the macros below exist so that a reader can check
|
||||
// thirty-seven rows against PipeTables.inc in one pass instead of reading thirty-seven bodies:
|
||||
//
|
||||
// 1. require a session - a slot that fell through to a driver this role does not have is
|
||||
// the failure R-4 exists to prevent, and there is no fall-through here either;
|
||||
// 2. stage the blob, if the row has one, and name the SEG_STAGE run in the payload's own
|
||||
// MGPBlobRef - which is why the payload is COPIED: the table hands it over const, and
|
||||
// the blobref is the one field the client must write after the caller is done with it;
|
||||
// 3. EmitAndWait, which is the barrier's wait and the reply's wait at once (R-3/R-5);
|
||||
// 4. post the answer, for the rows that have one, into MG_Pipe's reply mailbox.
|
||||
//
|
||||
// WHAT IS DELIBERATELY NOT HERE. b1's `PushPersistentMapsBeforeVerb` / `MarkGpuWritesFor*` are
|
||||
// NOT called from these thirty-seven. They are pre-VERB hooks and these are not verbs: they
|
||||
// are the resource, CSO and state records that a verb is later drawn against. The five class-B
|
||||
// verbs in EmitTables.cpp call them, once each, immediately before their record, which is the
|
||||
// ordering b1's B-1 fix depends on. Calling them here as well would push a persistent map
|
||||
// before every `set_dynamic_state` - hundreds of times a frame, and each one a real record.
|
||||
|
||||
#include "WireTables.h"
|
||||
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
|
||||
#include "ClientSession.h"
|
||||
|
||||
#include "../Server/ServerLoop.h"
|
||||
|
||||
#include <MG_Pipe/MGPipe.h>
|
||||
#include <MG_Pipe/PipeRoute.h>
|
||||
#include <MG_State/GLState/ProgramState/ProgramArtifactsCodec.h>
|
||||
#include <MG_Util/Debug/Log.h>
|
||||
|
||||
#include <atomic>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
|
||||
namespace MobileGL::MG_Remote::Client {
|
||||
|
||||
using MG_Pipe::MGPWireOp;
|
||||
|
||||
// TABLE 3's ROLE SPLIT, AS A RUNTIME CHECK. gMGPipeScreen / gMGPipeContext are PROCESS
|
||||
// globals and under `inproc` the server role is a thread in this same process, so the
|
||||
// apply thread running the server's own backend - the EGL bring-up, InitCapabilities,
|
||||
// the applier - reaches these very emitters. A record published there would be waited
|
||||
// for by the thread that is supposed to apply it: `Fatal{BarrierTimeout,
|
||||
// "ResourceRespecify"}` from `mgl-srv-apply`, thirty seconds into bring-up, which is
|
||||
// exactly how this was found.
|
||||
//
|
||||
// THE ANSWER IS NOT "SUPPRESS THE RECORD" - it is "run the server's own code", because
|
||||
// on that thread this process IS the server and the applier is one call away. It is
|
||||
// the same thing PipeWireCodec does on the decode side, where every arm calls
|
||||
// MGPipeApply* directly and never goes through a table.
|
||||
//
|
||||
// Under `spawn` (P6) the predicate is constantly false in the client process and
|
||||
// constantly true in the server's, so this costs one atomic load and changes nothing.
|
||||
//
|
||||
// NOT in the anonymous namespace, because M5 needs it from MG_Impl/Pipe/PipeFill.cpp too
|
||||
// (its split-only respecify/flush branches must not run on the apply thread). Declared in
|
||||
// WireTables.h.
|
||||
Bool RunsAsTheServerRole() { return Server::ServerLoop::OnApplyThread(); }
|
||||
|
||||
namespace {
|
||||
|
||||
Uint64 g_emitted = 0;
|
||||
Uint64 g_declined = 0;
|
||||
|
||||
// TEARDOWN REFUSAL (codex 4). ClientSession::Stop marks the routed tables uninstalled
|
||||
// BEFORE it frees the rings, the segments and the transport - so the window between then
|
||||
// and the moment the monolith adapters go back is one in which a routed GL-thread call
|
||||
// must not run the applier on the caller (the forbidden path table 3 draws) and must not
|
||||
// reach a half-freed ring. Round 2 reinstalled the monolith adapters at the top of Stop,
|
||||
// which is exactly running the applier on the caller; a routed mutation after
|
||||
// UninstallClientWireTables() moved no wire ordinal and never refused (the cross-family
|
||||
// verifier reproduced it). So Uninstall now RAISES THIS FLAG and leaves the wire rows in
|
||||
// place; RequireSession below reads it and refuses by name before it touches anything.
|
||||
// Atomic because the apply thread's own role check races a GL-thread teardown.
|
||||
std::atomic<Bool> g_clientTablesUninstalled{false};
|
||||
|
||||
ClientSession& RequireSession(const char* row) {
|
||||
// BEFORE the session lookup and before any ring access. A routed call that arrives
|
||||
// once Stop has begun tearing the session down is refused by name rather than run
|
||||
// on the caller's thread - the applier is server-exclusive (table 3), and a wire
|
||||
// emit into a ring being freed is a use-after-free. The monolith adapters are put
|
||||
// back only as the LAST step of teardown, for the at-exit ~BufferObject deletes that
|
||||
// legitimately reach a process with no session (see ReinstallMonolithAfterTeardown).
|
||||
RequireClientTablesInstalled(row);
|
||||
ClientSession* session = ClientSession::Active();
|
||||
if (session == nullptr) {
|
||||
MGLOG_F("MGPipe: Fatal{NoClientSession, \"%s\"} - the client wire tables are "
|
||||
"installed but no ClientSession is active. A row may not fall through to "
|
||||
"a driver this role does not have",
|
||||
row);
|
||||
std::abort();
|
||||
}
|
||||
return *session;
|
||||
}
|
||||
|
||||
// Stages a mandatory blob. `StageBytes` Fatals on a zero size by design (R-2.2: "the
|
||||
// record declared no blob" and "the record declared an empty blob" must not be spelled
|
||||
// the same way on a wire), so a row whose decoder calls RequireDeclaredBlob or
|
||||
// ResolveOrFatal is checked HERE, on the producing side, where the row has a name.
|
||||
MG_Pipe::MGPBlobRef StageRequired(ClientSession& session, const char* row,
|
||||
const void* bytes, Uint64 count) {
|
||||
if (bytes == nullptr || count == 0) {
|
||||
MGLOG_F("MGPipe: Fatal{BlobMissing, \"%s\"} - the row's decoder requires a "
|
||||
"declared blob and the call site handed over %llu bytes at %p. Under "
|
||||
"monolith the companion pointer carries them; under split they have to "
|
||||
"be staged, and there is nothing to stage",
|
||||
row, static_cast<unsigned long long>(count), bytes);
|
||||
std::abort();
|
||||
}
|
||||
return session.Encoder().StageBytes(bytes, count);
|
||||
}
|
||||
|
||||
// Stages an OPTIONAL blob: the two sub-data rows, whose decoders resolve only when the
|
||||
// record's own size field says there are bytes. All three fields zero is the wire's
|
||||
// "no blob declared", and CheckBlobIsHonest refuses any other spelling of it.
|
||||
MG_Pipe::MGPBlobRef StageOptional(ClientSession& session, const void* bytes, Uint64 count) {
|
||||
if (bytes == nullptr || count == 0) return MG_Pipe::MGPBlobRef{};
|
||||
return session.Encoder().StageBytes(bytes, count);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------
|
||||
// The three regular shapes
|
||||
// ---------------------------------------------------------------------------------
|
||||
|
||||
#define MGP_WIRE_PLAIN(Name, Payload, Table) \
|
||||
void Wire_##Name(const MG_Pipe::Payload* payload) { \
|
||||
if (RunsAsTheServerRole()) { MG_Pipe::MGPipeMonolith##Table().Name(payload); return; } \
|
||||
ClientSession& session = RequireSession(#Name); \
|
||||
session.EmitAndWait(MGPWireOp::Name, payload, sizeof(*payload), nullptr, 0, nullptr, 0, \
|
||||
nullptr); \
|
||||
++g_emitted; \
|
||||
}
|
||||
|
||||
#define MGP_WIRE_BLOB(Name, Payload, BlobMember) \
|
||||
void Wire_##Name(const MG_Pipe::Payload* payload, const void* blobBytes, \
|
||||
Uint64 blobByteCount) { \
|
||||
if (RunsAsTheServerRole()) { \
|
||||
MG_Pipe::MGPipeMonolithContext().Name(payload, blobBytes, blobByteCount); \
|
||||
return; \
|
||||
} \
|
||||
ClientSession& session = RequireSession(#Name); \
|
||||
MG_Pipe::Payload record = *payload; \
|
||||
record.BlobMember = StageRequired(session, #Name, blobBytes, blobByteCount); \
|
||||
session.EmitAndWait(MGPWireOp::Name, &record, sizeof(record), nullptr, 0, nullptr, 0, \
|
||||
nullptr); \
|
||||
++g_emitted; \
|
||||
}
|
||||
|
||||
#define MGP_WIRE_TAIL(Name, Payload, TailType) \
|
||||
void Wire_##Name(const MG_Pipe::Payload* payload, const void* varTail, Uint32 varTailCount) { \
|
||||
if (RunsAsTheServerRole()) { \
|
||||
MG_Pipe::MGPipeMonolithContext().Name(payload, varTail, varTailCount); \
|
||||
return; \
|
||||
} \
|
||||
ClientSession& session = RequireSession(#Name); \
|
||||
session.EmitAndWait(MGPWireOp::Name, payload, sizeof(*payload), varTail, \
|
||||
static_cast<Uint64>(varTailCount) * sizeof(MG_Pipe::TailType), \
|
||||
nullptr, 0, nullptr); \
|
||||
++g_emitted; \
|
||||
}
|
||||
|
||||
// -- screen -------------------------------------------------------------------
|
||||
MGP_WIRE_PLAIN(ResourceDestroy, MGPHandleOnly, Screen)
|
||||
MGP_WIRE_PLAIN(UnmapPersistent, MGPHandleOnly, Screen)
|
||||
|
||||
// -- context, plain -----------------------------------------------------------
|
||||
MGP_WIRE_PLAIN(BindRenderState, MGPBindRenderState, Context)
|
||||
MGP_WIRE_PLAIN(DeleteRenderState, MGPHandleOnly, Context)
|
||||
MGP_WIRE_PLAIN(BindVertexElements, MGPHandleOnly, Context)
|
||||
MGP_WIRE_PLAIN(DeleteVertexElements, MGPHandleOnly, Context)
|
||||
MGP_WIRE_PLAIN(DeleteSamplerState, MGPHandleOnly, Context)
|
||||
MGP_WIRE_PLAIN(CreateSamplerView, MGPSamplerView, Context)
|
||||
MGP_WIRE_PLAIN(DeleteSamplerView, MGPHandleOnly, Context)
|
||||
MGP_WIRE_PLAIN(BindShaderState, MGPHandleOnly, Context)
|
||||
MGP_WIRE_PLAIN(DeleteShaderState, MGPHandleOnly, Context)
|
||||
MGP_WIRE_PLAIN(SetDrawProgram, MGPHandleOnly, Context)
|
||||
MGP_WIRE_PLAIN(SetDispatchProgram, MGPHandleOnly, Context)
|
||||
MGP_WIRE_PLAIN(SetFramebufferState, MGPFramebufferState, Context)
|
||||
MGP_WIRE_PLAIN(SetIndexBuffer, MGPIndexBuffer, Context)
|
||||
MGP_WIRE_PLAIN(SetPixelPackState, MGPPixelPackState, Context)
|
||||
MGP_WIRE_PLAIN(SetPatchState, MGPPatchState, Context)
|
||||
|
||||
// -- context, mandatory blob --------------------------------------------------
|
||||
MGP_WIRE_BLOB(CreateRenderState, MGPRenderStateDesc, Blob)
|
||||
MGP_WIRE_BLOB(CreateVertexElements, MGPVertexElements, Blob)
|
||||
MGP_WIRE_BLOB(CreateSamplerState, MGPSamplerDesc, Parameters)
|
||||
MGP_WIRE_BLOB(SetGlobalConstants, MGPGlobalConstants, Blob)
|
||||
|
||||
// -- context, variable tail ---------------------------------------------------
|
||||
MGP_WIRE_TAIL(SetVertexBuffers, MGPVertexBuffers, MGPVertexBuffer)
|
||||
MGP_WIRE_TAIL(SetSamplerViews, MGPSamplerViews, MGPBoundView)
|
||||
MGP_WIRE_TAIL(BindSamplerStates, MGPSamplerStates, MGPipeHandle)
|
||||
MGP_WIRE_TAIL(SetShaderImages, MGPShaderImages, MGPImageView)
|
||||
MGP_WIRE_TAIL(SetVertexAttribDefaults, MGPVertexAttribDefaults, MGPAttribValue)
|
||||
|
||||
#undef MGP_WIRE_PLAIN
|
||||
#undef MGP_WIRE_BLOB
|
||||
#undef MGP_WIRE_TAIL
|
||||
|
||||
// -- the rows that fit none of the three shapes --------------------------------
|
||||
|
||||
// set_dynamic_state. AN OPTIONAL BLOB, NOT A MANDATORY ONE (round-2 regression, the
|
||||
// census's Fatal{BlobMissing, "SetDynamicState"}). EmitRenderState (PipeFill.cpp:2405-
|
||||
// 2421) sends a set_dynamic_state whenever the RenderState VERSION moved, and when the
|
||||
// chunk-level suppressor finds NO dynamic chunk changed it sends the 32-byte header with
|
||||
// ChunkMask == 0 and blobByteCount == 0 - a version-only update, which the comment there
|
||||
// calls out as deliberate. The generic MGP_WIRE_BLOB wrapper stages through StageRequired,
|
||||
// which Fatals on a zero count, so a legal header-only update aborted the process with a
|
||||
// blob-shape complaint that had nothing to do with the actual state of the pipe. The
|
||||
// DECODER already handles it: PipeWireCodec.cpp:1571-1587 takes the `ChunkMask == 0` arm
|
||||
// (CheckBlobIsHonest, no blob resolved) and applies the header alone. So the emitter is
|
||||
// the only side that was wrong; it stages OPTIONALLY, exactly like the two sub-data rows.
|
||||
// A non-empty mask still stages (blobByteCount > 0), so the reduced-path scenarios, whose
|
||||
// first draw is freshly primed with every chunk, are byte-for-byte unchanged.
|
||||
void Wire_SetDynamicState(const MG_Pipe::MGPDynamicState* payload, const void* blobBytes,
|
||||
Uint64 blobByteCount) {
|
||||
if (RunsAsTheServerRole()) {
|
||||
MG_Pipe::MGPipeMonolithContext().SetDynamicState(payload, blobBytes, blobByteCount);
|
||||
return;
|
||||
}
|
||||
ClientSession& session = RequireSession("SetDynamicState");
|
||||
MG_Pipe::MGPDynamicState record = *payload;
|
||||
record.Blob = StageOptional(session, blobBytes, blobByteCount);
|
||||
session.EmitAndWait(MGPWireOp::SetDynamicState, &record, sizeof(record), nullptr, 0,
|
||||
nullptr, 0, nullptr);
|
||||
++g_emitted;
|
||||
}
|
||||
|
||||
// set_residual_value_state. CONTRACT-P5 table 1 row 6: the applier takes a frontend
|
||||
// `ResidualValueBlock&` and `MGPResidualValueState` is never instantiated on the live
|
||||
// path, so the encoder invents BOTH the record fill and the blob fill. The block IS
|
||||
// the blob, whole - the decoder requires exactly sizeof(ResidualValueBlock) and says
|
||||
// why ("a size that only ever ratchets down makes a short read silently lose
|
||||
// CapabilityBits"), so the two sides state the same number from the same header.
|
||||
void Wire_SetResidualValueState(const MG_Pipe::MGPResidualValueState* payload,
|
||||
const void* blobBytes, Uint64 blobByteCount) {
|
||||
if (RunsAsTheServerRole()) {
|
||||
MG_Pipe::MGPipeMonolithContext().SetResidualValueState(payload, blobBytes,
|
||||
blobByteCount);
|
||||
return;
|
||||
}
|
||||
ClientSession& session = RequireSession("SetResidualValueState");
|
||||
MG_Pipe::MGPResidualValueState record = *payload;
|
||||
record.Blob = StageRequired(session, "SetResidualValueState", blobBytes, blobByteCount);
|
||||
session.EmitAndWait(MGPWireOp::SetResidualValueState, &record, sizeof(record), nullptr,
|
||||
0, nullptr, 0, nullptr);
|
||||
++g_emitted;
|
||||
}
|
||||
|
||||
// resource_readback. kReplySlot, and the answer is COMPLETION only: the bytes travel
|
||||
// server -> client in SEG_EVENT through OnBufferWriteback, because the destination is
|
||||
// the client's shadow and its size is the resource's, not a slot's (CONTRACT-P5 table 1
|
||||
// row 22). So the reply buffer is deliberately {nullptr, 0} and the wait is what makes
|
||||
// the writeback already drained by the time this returns.
|
||||
void Wire_ResourceReadback(const MG_Pipe::MGPReadback* payload, MG_Pipe::MGPReplySlot* reply) {
|
||||
if (RunsAsTheServerRole()) { MG_Pipe::MGPipeMonolithContext().ResourceReadback(payload, reply); return; }
|
||||
ClientSession& session = RequireSession("ResourceReadback");
|
||||
Int32 status = 0;
|
||||
const Uint64 seq = session.EmitAndWait(MGPWireOp::ResourceReadback, payload,
|
||||
sizeof(*payload), nullptr, 0, nullptr, 0,
|
||||
&status);
|
||||
reply->Id = seq;
|
||||
MG_Pipe::MGPipePostReply(*reply, status, 0);
|
||||
++g_emitted;
|
||||
}
|
||||
|
||||
// ---- the three acceptance rows that fit a generated signature ----------------
|
||||
//
|
||||
// THE ANSWER IS THE SERVER'S AND NOTHING ELSE. `EmitAndWait` returns the record's seq
|
||||
// and fills `status` from the reply slot the server stamped; DECLINED is `false` and OK
|
||||
// is `true`, and neither is derived from anything this side knows. R-5 exists because
|
||||
// "always accept" is ID-39's 66 lost DirectVulkan uploads and "accept if we emitted" is
|
||||
// the same bug wearing a counter.
|
||||
|
||||
void Wire_ResourceCreate(const MG_Pipe::MGPResourceDesc* payload, MG_Pipe::MGPReplySlot* reply) {
|
||||
if (RunsAsTheServerRole()) { MG_Pipe::MGPipeMonolithScreen().ResourceCreate(payload, reply); return; }
|
||||
ClientSession& session = RequireSession("ResourceCreate");
|
||||
Int32 status = 0;
|
||||
const Uint64 seq = session.EmitAndWait(MGPWireOp::ResourceCreate, payload,
|
||||
sizeof(*payload), nullptr, 0, nullptr, 0,
|
||||
&status);
|
||||
reply->Id = seq;
|
||||
MG_Pipe::MGPipePostReply(*reply, status, status == 0 ? 1u : 0u);
|
||||
++g_emitted;
|
||||
if (status == 1) ++g_declined;
|
||||
}
|
||||
|
||||
void Wire_SetTextureParams(const MG_Pipe::MGPTextureParams* payload, MG_Pipe::MGPReplySlot* reply) {
|
||||
if (RunsAsTheServerRole()) { MG_Pipe::MGPipeMonolithContext().SetTextureParams(payload, reply); return; }
|
||||
ClientSession& session = RequireSession("SetTextureParams");
|
||||
Int32 status = 0;
|
||||
const Uint64 seq = session.EmitAndWait(MGPWireOp::SetTextureParams, payload,
|
||||
sizeof(*payload), nullptr, 0, nullptr, 0,
|
||||
&status);
|
||||
reply->Id = seq;
|
||||
MG_Pipe::MGPipePostReply(*reply, status, status == 0 ? 1u : 0u);
|
||||
++g_emitted;
|
||||
if (status == 1) ++g_declined;
|
||||
}
|
||||
|
||||
void Wire_ResourceSubData(const MG_Pipe::MGPSubData* payload, const void* blobBytes,
|
||||
Uint64 blobByteCount, const void* varTail, Uint32 varTailCount,
|
||||
MG_Pipe::MGPReplySlot* reply) {
|
||||
if (RunsAsTheServerRole()) {
|
||||
MG_Pipe::MGPipeMonolithContext().ResourceSubData(payload, blobBytes, blobByteCount,
|
||||
varTail, varTailCount, reply);
|
||||
return;
|
||||
}
|
||||
ClientSession& session = RequireSession("ResourceSubData");
|
||||
MG_Pipe::MGPSubData record = *payload;
|
||||
record.Blob = StageOptional(session, blobBytes, blobByteCount);
|
||||
Int32 status = 0;
|
||||
const Uint64 seq = session.EmitAndWait(
|
||||
MGPWireOp::ResourceSubData, &record, sizeof(record), varTail,
|
||||
static_cast<Uint64>(varTailCount) * sizeof(MG_Pipe::MGPSubRegion), nullptr, 0,
|
||||
&status);
|
||||
reply->Id = seq;
|
||||
MG_Pipe::MGPipePostReply(*reply, status, status == 0 ? 1u : 0u);
|
||||
++g_emitted;
|
||||
if (status == 1) ++g_declined;
|
||||
}
|
||||
|
||||
void Wire_BufferSubDataResident(const MG_Pipe::MGPSubData* payload, const void* blobBytes,
|
||||
Uint64 blobByteCount) {
|
||||
if (RunsAsTheServerRole()) {
|
||||
MG_Pipe::MGPipeMonolithContext().BufferSubDataResident(payload, blobBytes,
|
||||
blobByteCount);
|
||||
return;
|
||||
}
|
||||
ClientSession& session = RequireSession("BufferSubDataResident");
|
||||
MG_Pipe::MGPSubData record = *payload;
|
||||
record.Blob = StageOptional(session, blobBytes, blobByteCount);
|
||||
session.EmitAndWait(MGPWireOp::BufferSubDataResident, &record, sizeof(record), nullptr,
|
||||
0, nullptr, 0, nullptr);
|
||||
++g_emitted;
|
||||
}
|
||||
|
||||
// ---- the four escapes --------------------------------------------------------
|
||||
|
||||
// resource_respecify. R-13.3: `initialBytes` is ALWAYS nullptr under split and the
|
||||
// initial content arrives as resource_subdata records immediately after this one. The
|
||||
// caller's bytes are therefore not dropped - they are re-expressed - and PipeFill.cpp's
|
||||
// emitter is where that happens, because the chunking walk that has to size them
|
||||
// (MGPipeForEachSubDataRecordRange) lives there. What this emitter owes is the REFUSAL:
|
||||
// a non-null pointer arriving here means the call site was not converted, and silently
|
||||
// ignoring it would lose exactly the bytes R-13.3 promised would follow.
|
||||
Bool Wire_Escape_ResourceRespecify(const MG_Pipe::MGPResourceDesc* desc,
|
||||
const void* initialBytes,
|
||||
const MG_Pipe::MGPRespecifiedLevel* level) {
|
||||
if (RunsAsTheServerRole()) {
|
||||
return MG_Pipe::MGPipeMonolithEscapes().ResourceRespecify(desc, initialBytes, level);
|
||||
}
|
||||
ClientSession& session = RequireSession("ResourceRespecify");
|
||||
if (initialBytes != nullptr) {
|
||||
MGLOG_F("MGPipe: Fatal{UncarriedInitialBytes, \"resource_respecify\"} - a call "
|
||||
"site handed initial content to a split respecify. R-13.3 rules that "
|
||||
"initialBytes never crosses and that the content follows as "
|
||||
"resource_subdata; a caller that still passes it has bytes nothing will "
|
||||
"carry");
|
||||
std::abort();
|
||||
}
|
||||
// The scope rides in the descriptor's own pads (CONTRACT-P5 table 1 row 19b, LANDED)
|
||||
// and is written only through MGPipeSetRespecifiedLevel - three fields are one
|
||||
// value, and an open-coded writer that forgets the presence byte says "level 0 of
|
||||
// upload target 0" where it meant "the whole resource".
|
||||
MG_Pipe::MGPResourceDesc record = *desc;
|
||||
if (level != nullptr) {
|
||||
MG_Pipe::MGPipeSetRespecifiedLevel(record, level->UploadTarget, level->Level);
|
||||
} else {
|
||||
MG_Pipe::MGPipeClearRespecifiedLevel(record);
|
||||
}
|
||||
Int32 status = 0;
|
||||
const Uint64 seq =
|
||||
session.EmitAndWait(MGPWireOp::ResourceRespecify, &record, sizeof(record), nullptr,
|
||||
0, nullptr, 0, &status);
|
||||
(void)seq;
|
||||
++g_emitted;
|
||||
// ERROR IS NOT A DECLINE (M4 / codex 5 / R-5). status is 0 OK / 1 DECLINED / 2 ERROR;
|
||||
// an escape may not fold 2 into `false`, which is what a bare `return status == 0`
|
||||
// did - a transport fault then read as "the server said no". Every reply-owning row
|
||||
// - the generated acceptance rows through MGPipeTakeReplyBool, and now these two
|
||||
// escapes - answers ERROR with the same named Fatal.
|
||||
if (status == 2) {
|
||||
MGLOG_F("MGPipe: Fatal{ReplyError, \"resource_respecify\"} - the row answered "
|
||||
"ERROR, which is not an acceptance answer; folding it into accepted or "
|
||||
"refused would make a transport fault look like a resource decision");
|
||||
std::abort();
|
||||
}
|
||||
if (status == 1) ++g_declined;
|
||||
return status == 0;
|
||||
}
|
||||
|
||||
// resource_flush_range. R-13.2: it carries NO bytes under split - it is a
|
||||
// {range, AccessFlags} control record and the bytes of exactly that range arrive ahead
|
||||
// of it as resource_subdata. Same refusal as above, for the same reason: a blobref here
|
||||
// would be "a second, forgeable way to say the same thing".
|
||||
void Wire_Escape_ResourceFlushRange(const MG_Pipe::MGPFlushRange* record,
|
||||
const void* bytes) {
|
||||
if (RunsAsTheServerRole()) {
|
||||
MG_Pipe::MGPipeMonolithEscapes().ResourceFlushRange(record, bytes);
|
||||
return;
|
||||
}
|
||||
ClientSession& session = RequireSession("ResourceFlushRange");
|
||||
(void)bytes; // ruled uncarried; the emitter in PipeFill.cpp sends the range first
|
||||
session.EmitAndWait(MGPWireOp::ResourceFlushRange, record, sizeof(*record), nullptr, 0,
|
||||
nullptr, 0, nullptr);
|
||||
++g_emitted;
|
||||
}
|
||||
|
||||
// map_persistent. R-6/R-2.4: the split answer is a CONSTANT DECLINE, and it still costs
|
||||
// a record, because the server has to know the client asked - the applier's
|
||||
// MapPersistentRoundtrips counter is defined as "one per storage definition in both
|
||||
// modes" and a client that answered locally would zero it. `size` and `seedBytes` have
|
||||
// no carrier (MGPHandleOnly is {Handle, Kind}) and need none: nothing is minted.
|
||||
void* Wire_Escape_MapPersistent(const MG_Pipe::MGPHandleOnly* handle, Uint64 size,
|
||||
const void* seedBytes) {
|
||||
if (RunsAsTheServerRole()) {
|
||||
return MG_Pipe::MGPipeMonolithEscapes().MapPersistent(handle, size, seedBytes);
|
||||
}
|
||||
ClientSession& session = RequireSession("MapPersistent");
|
||||
(void)size;
|
||||
(void)seedBytes;
|
||||
Int32 status = 0;
|
||||
session.EmitAndWait(MGPWireOp::MapPersistent, handle, sizeof(*handle), nullptr, 0,
|
||||
nullptr, 0, &status);
|
||||
++g_emitted;
|
||||
// ERROR IS NOT A DECLINE (M4 / codex 5 / R-5), the same rule the respecify escape and
|
||||
// the generated acceptance rows obey: status 2 is a transport fault, and returning
|
||||
// nullptr for it would make it indistinguishable from R-6's legitimate decline.
|
||||
if (status == 2) {
|
||||
MGLOG_F("MGPipe: Fatal{ReplyError, \"map_persistent\"} - the row answered ERROR, "
|
||||
"which is not an acceptance answer; a transport fault is not a resource "
|
||||
"decision and may not be folded into the decline R-6 predicts");
|
||||
std::abort();
|
||||
}
|
||||
if (status == 1) ++g_declined;
|
||||
// NOT "always nullptr": the answer is READ. R-6 says the server declines, and the
|
||||
// day it stops declining this returns what it actually said rather than what the
|
||||
// ruling predicted.
|
||||
if (status == 0) {
|
||||
MGLOG_F("MGPipe: Fatal{UnexpectedMapAccept, \"map_persistent\"} - the server "
|
||||
"accepted a persistent map under split. R-6 makes the split answer a "
|
||||
"constant decline because there is no way to hand a host pointer across "
|
||||
"a process boundary in P5; a pointer arriving here is one this client "
|
||||
"cannot dereference");
|
||||
std::abort();
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
// create_shader_state. SEVEN blobrefs and TWO typed frontend pointers; one blobBytes
|
||||
// pair cannot express seven runs. The serializer already exists and no package may
|
||||
// write a second one (CONTRACT-P5 table 1 row 3): EncodeProgramArtifacts produces one
|
||||
// archive, the decoder's DecodeProgramArtifacts consumes it, and the six per-stage runs
|
||||
// stay UNDECLARED because the modules already travel inside the archive - a declared
|
||||
// Spirv[i] is Fatal on the far side rather than ignored.
|
||||
void Wire_Escape_CreateShaderState(const MG_Pipe::MGPProgramDesc* desc,
|
||||
const MG_State::GLState::LinkArtifacts* link,
|
||||
const MG_State::GLState::SpirvArtifacts* spirv) {
|
||||
if (RunsAsTheServerRole()) {
|
||||
MG_Pipe::MGPipeMonolithEscapes().CreateShaderState(desc, link, spirv);
|
||||
return;
|
||||
}
|
||||
ClientSession& session = RequireSession("CreateShaderState");
|
||||
if (link == nullptr || spirv == nullptr) {
|
||||
MGLOG_F("MGPipe: Fatal{ArtefactsMissing, \"create_shader_state\"} - the record's "
|
||||
"two typed companions are null. Under monolith the applier reads the "
|
||||
"modules out of spirv->generatedSpirv; under split there is nothing to "
|
||||
"serialise, and emitting the record anyway would create a CSO with no "
|
||||
"code");
|
||||
std::abort();
|
||||
}
|
||||
// EncodeProgramArtifacts APPENDS and never fails - everything it walks is owned
|
||||
// plain data - so an empty archive means the two structs themselves were empty,
|
||||
// which is a linked program with no artefacts and is not a codec question.
|
||||
Vector<Uint8> archive;
|
||||
MG_State::GLState::EncodeProgramArtifacts(*link, *spirv, archive);
|
||||
if (archive.empty()) {
|
||||
MGLOG_F("MGPipe: Fatal{ArchiveEmpty, \"create_shader_state\"} - the program's "
|
||||
"artefacts serialised to nothing");
|
||||
std::abort();
|
||||
}
|
||||
MG_Pipe::MGPProgramDesc record = *desc;
|
||||
for (Uint32 i = 0; i < 6; ++i) record.Spirv[i] = MG_Pipe::MGPBlobRef{};
|
||||
record.Reflection = session.Encoder().StageBytes(archive.data(), archive.size());
|
||||
session.EmitAndWait(MGPWireOp::CreateShaderState, &record, sizeof(record), nullptr, 0,
|
||||
nullptr, 0, nullptr);
|
||||
++g_emitted;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
void RequireClientTablesInstalled(const char* row) {
|
||||
if (g_clientTablesUninstalled.load(std::memory_order_acquire)) {
|
||||
MGLOG_F("MGPipe: Fatal{ClientTablesUninstalled, \"%s\"} - the client tables are "
|
||||
"being torn down; refusing before session or ring access", row);
|
||||
std::abort();
|
||||
}
|
||||
}
|
||||
|
||||
void InstallClientWireTables() {
|
||||
using namespace MG_Pipe;
|
||||
|
||||
// A fresh install means the routed tables are live again: a Start after a previous
|
||||
// session's Stop clears the teardown-refusal flag so its own routed calls are not
|
||||
// refused. (Stop already puts the monolith adapters back and clears the flag; this is
|
||||
// the belt to that braces.)
|
||||
g_clientTablesUninstalled.store(false, std::memory_order_release);
|
||||
|
||||
gMGPipeScreen.ResourceCreate = &Wire_ResourceCreate;
|
||||
gMGPipeScreen.ResourceDestroy = &Wire_ResourceDestroy;
|
||||
gMGPipeScreen.UnmapPersistent = &Wire_UnmapPersistent;
|
||||
|
||||
gMGPipeContext.CreateRenderState = &Wire_CreateRenderState;
|
||||
gMGPipeContext.BindRenderState = &Wire_BindRenderState;
|
||||
gMGPipeContext.DeleteRenderState = &Wire_DeleteRenderState;
|
||||
gMGPipeContext.CreateVertexElements = &Wire_CreateVertexElements;
|
||||
gMGPipeContext.BindVertexElements = &Wire_BindVertexElements;
|
||||
gMGPipeContext.DeleteVertexElements = &Wire_DeleteVertexElements;
|
||||
gMGPipeContext.CreateSamplerState = &Wire_CreateSamplerState;
|
||||
gMGPipeContext.DeleteSamplerState = &Wire_DeleteSamplerState;
|
||||
gMGPipeContext.CreateSamplerView = &Wire_CreateSamplerView;
|
||||
gMGPipeContext.DeleteSamplerView = &Wire_DeleteSamplerView;
|
||||
gMGPipeContext.BindShaderState = &Wire_BindShaderState;
|
||||
gMGPipeContext.DeleteShaderState = &Wire_DeleteShaderState;
|
||||
gMGPipeContext.SetDrawProgram = &Wire_SetDrawProgram;
|
||||
gMGPipeContext.SetDispatchProgram = &Wire_SetDispatchProgram;
|
||||
gMGPipeContext.SetDynamicState = &Wire_SetDynamicState;
|
||||
gMGPipeContext.SetFramebufferState = &Wire_SetFramebufferState;
|
||||
gMGPipeContext.SetVertexBuffers = &Wire_SetVertexBuffers;
|
||||
gMGPipeContext.SetIndexBuffer = &Wire_SetIndexBuffer;
|
||||
gMGPipeContext.SetSamplerViews = &Wire_SetSamplerViews;
|
||||
gMGPipeContext.BindSamplerStates = &Wire_BindSamplerStates;
|
||||
gMGPipeContext.SetShaderImages = &Wire_SetShaderImages;
|
||||
gMGPipeContext.SetGlobalConstants = &Wire_SetGlobalConstants;
|
||||
gMGPipeContext.SetVertexAttribDefaults = &Wire_SetVertexAttribDefaults;
|
||||
gMGPipeContext.SetPixelPackState = &Wire_SetPixelPackState;
|
||||
gMGPipeContext.SetPatchState = &Wire_SetPatchState;
|
||||
gMGPipeContext.SetResidualValueState = &Wire_SetResidualValueState;
|
||||
gMGPipeContext.SetTextureParams = &Wire_SetTextureParams;
|
||||
gMGPipeContext.ResourceSubData = &Wire_ResourceSubData;
|
||||
gMGPipeContext.BufferSubDataResident = &Wire_BufferSubDataResident;
|
||||
gMGPipeContext.ResourceReadback = &Wire_ResourceReadback;
|
||||
|
||||
gMGPipeRouteEscapes.ResourceRespecify = &Wire_Escape_ResourceRespecify;
|
||||
gMGPipeRouteEscapes.ResourceFlushRange = &Wire_Escape_ResourceFlushRange;
|
||||
gMGPipeRouteEscapes.MapPersistent = &Wire_Escape_MapPersistent;
|
||||
gMGPipeRouteEscapes.CreateShaderState = &Wire_Escape_CreateShaderState;
|
||||
|
||||
MGPipeNoteInstalledArm(MGPipeRouteArm::kClientWire);
|
||||
}
|
||||
|
||||
void UninstallClientWireTables() {
|
||||
// MARK THE ROUTED TABLES UNINSTALLED (codex 4). It does NOT reinstall the monolith
|
||||
// adapters, and that is the whole fix: round 2 reinstalled them here, at the TOP of
|
||||
// Stop, so a routed GL-thread call arriving during teardown ran the applier on the
|
||||
// caller - the forbidden path - and moved no wire ordinal, with no refusal. Raising the
|
||||
// flag leaves the Wire_* rows in place; the next routed call reaches RequireSession,
|
||||
// reads the flag and aborts by name (Fatal{ClientTablesUninstalled}) before it touches a
|
||||
// ring that Stop is about to free. The monolith adapters are put back only once teardown
|
||||
// is complete, by ReinstallMonolithAfterTeardown, for the at-exit deletes that reach a
|
||||
// process with no session at all. Idempotent: safe to call when nothing was installed.
|
||||
g_clientTablesUninstalled.store(true, std::memory_order_release);
|
||||
}
|
||||
|
||||
void ReinstallMonolithAfterTeardown() {
|
||||
// THE LAST STEP OF ClientSession::Stop, after the rings, segments and transport are gone
|
||||
// and the apply thread has joined. Now a routed call can only be a process that no
|
||||
// longer has a session - the canonical case is ~BufferObject running from an exit
|
||||
// handler (ID-8) - and the monolith adapter, which runs the applier synchronously, is
|
||||
// the correct answer for it, exactly as it is in a pure-monolith build. Clearing the
|
||||
// flag re-enables the (now monolith) rows. A null row here would be an undiagnosed crash
|
||||
// at whatever GL call an exit handler makes; the applier is a defined no-op-or-apply.
|
||||
MG_Pipe::MGPipeInstallMonolithTables();
|
||||
g_clientTablesUninstalled.store(false, std::memory_order_release);
|
||||
}
|
||||
|
||||
Uint64 ClientWireRecordsEmitted() { return g_emitted; }
|
||||
Uint64 ClientWireRecordsDeclined() { return g_declined; }
|
||||
|
||||
} // namespace MobileGL::MG_Remote::Client
|
||||
|
||||
#endif // MOBILEGL_BUILD_DISAGGREGATED
|
||||
@@ -0,0 +1,91 @@
|
||||
// MobileGL - MobileGL/MG_Remote/Client/WireTables.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
|
||||
|
||||
// THE CLIENT ARM OF R-17's ROUTING: the encode twin of `gMGPipeWireRecordApply`. Owner: c1.
|
||||
//
|
||||
// Thirty-seven thin emitters over `ClientSession::EmitAndWait`, installed over the two
|
||||
// generated tables and the escape table that `MG_Pipe/PipeRoute.h` declares, so that under
|
||||
// split every resource, CSO, texture and program record leaves the GL thread as a WIRE RECORD
|
||||
// instead of executing synchronously against a context the apply thread now owns.
|
||||
//
|
||||
// WHAT ARMS `integration-split`. The 21 `DirectGLES.Split.*` entries skip on
|
||||
// `ClientSession::Active() == nullptr`. `Install()` below is called from the END of a
|
||||
// successful `ClientSession::Start()`, on the GL thread (the thread that called
|
||||
// `MG_Backend::Init()`), AFTER the Hello/Welcome handshake, after the first CapsSnapshot has
|
||||
// been adopted, and after the in-process server role's apply thread has been started. That
|
||||
// order is not a preference:
|
||||
// - after the handshake, because an emitter that published before Welcome would be writing
|
||||
// into a ring the peer has not mapped;
|
||||
// - after the first snapshot, because R-8's liveness gates read the caps mirror and a
|
||||
// placeholder mirror consumes nothing, so a record emitted before it would be emitted to a
|
||||
// server this client has not yet been told consumes that family;
|
||||
// - after the apply thread exists, because `EmitAndWait` BLOCKS on `appliedSeq` and nothing
|
||||
// would advance it - a barrier wait with no applier is the 30-second Fatal, not a hang;
|
||||
// - on the GL thread, because that is the only thread that may touch `gPipeInputs` while the
|
||||
// barrier holds (table 3), and installing from the apply thread would publish the table to
|
||||
// the GL thread with no synchronisation at all.
|
||||
// `Uninstall()` runs at the TOP of `Stop()`, before the rings go away, so the last thing any
|
||||
// straggling GL-thread call reaches is a named refusal rather than a dangling session.
|
||||
|
||||
#pragma once
|
||||
#include <Includes.h>
|
||||
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
|
||||
namespace MobileGL::MG_Remote::Client {
|
||||
|
||||
// Installs the thirty-seven wire emitters over gMGPipeScreen / gMGPipeContext /
|
||||
// gMGPipeRouteEscapes and records the arm. Idempotent.
|
||||
void InstallClientWireTables();
|
||||
|
||||
// Marks the routed tables uninstalled so a routed call refuses by name
|
||||
// (Fatal{ClientTablesUninstalled, "<row>"}) rather than running the applier on the caller
|
||||
// (codex 4). It does NOT restore the monolith adapters - that is ReinstallMonolithAfterTeardown
|
||||
// below, run only once the session's rings are freed. Idempotent.
|
||||
void UninstallClientWireTables();
|
||||
|
||||
// Shared by routed rows and the five class-B emitters, before session/ring access.
|
||||
void RequireClientTablesInstalled(const char* row);
|
||||
|
||||
// The LAST step of ClientSession::Stop: after the rings, segments and transport are gone,
|
||||
// puts the monolith adapters back and clears the refusal flag, so the at-exit ~BufferObject
|
||||
// deletes that reach a process with no session run the applier as they do under monolith.
|
||||
void ReinstallMonolithAfterTeardown();
|
||||
|
||||
// How many records the thirty-seven emitters have published. It counts the ROUTED rows
|
||||
// only - a resource_create, a set_vertex_buffers, a create_shader_state - and never the
|
||||
// five class-B verbs, so it is the one number that says "the resource/CSO/state path really
|
||||
// ran" as opposed to "a Clear crossed".
|
||||
//
|
||||
// WHAT IT IS NOT (M7, corrected). This is NOT what arms the split lane. WireTables.h round 2
|
||||
// claimed it was "t1's FOURTH arming fact", and that was wrong: the harness reads the
|
||||
// encoder's EmitSeq (Harness/SplitRuntimePeek.cpp:50, Harness/ScenarioFixture.h:85), which
|
||||
// moves for the class-B verbs too. So an armed Clear-only lane is green on EmitSeq while this
|
||||
// counter stays 0. Making the harness read THIS instead is t1's file (SplitRuntimePeek), so
|
||||
// the honest statement is the one here: c1 counts the routed ordinal at the only place that
|
||||
// can, PipeFill's InitialBytesNotCarried self-check reads it (PipeFill.cpp:755), and the
|
||||
// lane's own arming remains EmitSeq until t1 re-points it. c1-v3.md M7 has the full note.
|
||||
Uint64 ClientWireRecordsEmitted();
|
||||
|
||||
// How many of those were refused by the server, by acceptance row. Counted rather than
|
||||
// inferred, R-8's rule one level out.
|
||||
Uint64 ClientWireRecordsDeclined();
|
||||
|
||||
// TRUE ON THE SERVER ROLE's OWN THREAD (the apply thread), false everywhere else. It is
|
||||
// v1's ServerLoop::OnApplyThread(), exposed here because it is table 3's role split made
|
||||
// into one predicate and TWO packages read it: the wire emitters below (a routed call that
|
||||
// finds itself on the apply thread runs the monolith adapter, because on that thread this
|
||||
// process IS the server), and MG_Impl/Pipe/PipeFill.cpp's split-only respecify/flush
|
||||
// branches (M5: those branches emit CLIENT wire records and must not run on the server's
|
||||
// apply thread, which produces none - the InitialBytesNotCarried self-check would abort the
|
||||
// server otherwise). Declared here so PipeFill does not have to include a server header.
|
||||
Bool RunsAsTheServerRole();
|
||||
|
||||
} // namespace MobileGL::MG_Remote::Client
|
||||
|
||||
#endif // MOBILEGL_BUILD_DISAGGREGATED
|
||||
@@ -532,7 +532,8 @@ struct Hello FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table {
|
||||
VT_BUILDFINGERPRINT = 8,
|
||||
VT_BACKENDTYPE = 10,
|
||||
VT_PID = 12,
|
||||
VT_CONFIGBLOB = 14
|
||||
VT_CONFIGBLOB = 14,
|
||||
VT_ABIFINGERPRINT = 16
|
||||
};
|
||||
uint32_t abiMajor() const {
|
||||
return GetField<uint32_t>(VT_ABIMAJOR, 0);
|
||||
@@ -552,6 +553,9 @@ struct Hello FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table {
|
||||
const ::flatbuffers::Vector<uint8_t> *configBlob() const {
|
||||
return GetPointer<const ::flatbuffers::Vector<uint8_t> *>(VT_CONFIGBLOB);
|
||||
}
|
||||
uint64_t abiFingerprint() const {
|
||||
return GetField<uint64_t>(VT_ABIFINGERPRINT, 0);
|
||||
}
|
||||
template <bool B = false>
|
||||
bool Verify(::flatbuffers::VerifierTemplate<B> &verifier) const {
|
||||
return VerifyTableStart(verifier) &&
|
||||
@@ -563,6 +567,7 @@ struct Hello FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table {
|
||||
VerifyField<uint32_t>(verifier, VT_PID, 4) &&
|
||||
VerifyOffset(verifier, VT_CONFIGBLOB) &&
|
||||
verifier.VerifyVector(configBlob()) &&
|
||||
VerifyField<uint64_t>(verifier, VT_ABIFINGERPRINT, 8) &&
|
||||
verifier.EndTable();
|
||||
}
|
||||
};
|
||||
@@ -589,6 +594,9 @@ struct HelloBuilder {
|
||||
void add_configBlob(::flatbuffers::Offset<::flatbuffers::Vector<uint8_t>> configBlob) {
|
||||
fbb_.AddOffset(Hello::VT_CONFIGBLOB, configBlob);
|
||||
}
|
||||
void add_abiFingerprint(uint64_t abiFingerprint) {
|
||||
fbb_.AddElement<uint64_t>(Hello::VT_ABIFINGERPRINT, abiFingerprint, 0);
|
||||
}
|
||||
explicit HelloBuilder(::flatbuffers::FlatBufferBuilder &_fbb)
|
||||
: fbb_(_fbb) {
|
||||
start_ = fbb_.StartTable();
|
||||
@@ -607,8 +615,10 @@ inline ::flatbuffers::Offset<Hello> CreateHello(
|
||||
::flatbuffers::Offset<::flatbuffers::String> buildFingerprint = 0,
|
||||
uint32_t backendType = 0,
|
||||
uint32_t pid = 0,
|
||||
::flatbuffers::Offset<::flatbuffers::Vector<uint8_t>> configBlob = 0) {
|
||||
::flatbuffers::Offset<::flatbuffers::Vector<uint8_t>> configBlob = 0,
|
||||
uint64_t abiFingerprint = 0) {
|
||||
HelloBuilder builder_(_fbb);
|
||||
builder_.add_abiFingerprint(abiFingerprint);
|
||||
builder_.add_configBlob(configBlob);
|
||||
builder_.add_pid(pid);
|
||||
builder_.add_backendType(backendType);
|
||||
@@ -630,7 +640,8 @@ inline ::flatbuffers::Offset<Hello> CreateHelloDirect(
|
||||
const char *buildFingerprint = nullptr,
|
||||
uint32_t backendType = 0,
|
||||
uint32_t pid = 0,
|
||||
const std::vector<uint8_t> *configBlob = nullptr) {
|
||||
const std::vector<uint8_t> *configBlob = nullptr,
|
||||
uint64_t abiFingerprint = 0) {
|
||||
auto buildFingerprint__ = buildFingerprint ? _fbb.CreateString(buildFingerprint) : 0;
|
||||
auto configBlob__ = configBlob ? _fbb.CreateVector<uint8_t>(*configBlob) : 0;
|
||||
return MobileGL::Wire::CreateHello(
|
||||
@@ -640,7 +651,8 @@ inline ::flatbuffers::Offset<Hello> CreateHelloDirect(
|
||||
buildFingerprint__,
|
||||
backendType,
|
||||
pid,
|
||||
configBlob__);
|
||||
configBlob__,
|
||||
abiFingerprint);
|
||||
}
|
||||
|
||||
struct Welcome FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table {
|
||||
@@ -653,7 +665,9 @@ struct Welcome FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table {
|
||||
VT_CMDRING = 10,
|
||||
VT_STAGERING = 12,
|
||||
VT_REPLYPOOL = 14,
|
||||
VT_EVENTRING = 16
|
||||
VT_EVENTRING = 16,
|
||||
VT_BUILDFINGERPRINT = 18,
|
||||
VT_ABIFINGERPRINT = 20
|
||||
};
|
||||
uint32_t abiMajor() const {
|
||||
return GetField<uint32_t>(VT_ABIMAJOR, 0);
|
||||
@@ -676,6 +690,12 @@ struct Welcome FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table {
|
||||
const MobileGL::Wire::SegmentRef *eventRing() const {
|
||||
return GetPointer<const MobileGL::Wire::SegmentRef *>(VT_EVENTRING);
|
||||
}
|
||||
const ::flatbuffers::String *buildFingerprint() const {
|
||||
return GetPointer<const ::flatbuffers::String *>(VT_BUILDFINGERPRINT);
|
||||
}
|
||||
uint64_t abiFingerprint() const {
|
||||
return GetField<uint64_t>(VT_ABIFINGERPRINT, 0);
|
||||
}
|
||||
template <bool B = false>
|
||||
bool Verify(::flatbuffers::VerifierTemplate<B> &verifier) const {
|
||||
return VerifyTableStart(verifier) &&
|
||||
@@ -690,6 +710,9 @@ struct Welcome FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table {
|
||||
verifier.VerifyTable(replyPool()) &&
|
||||
VerifyOffset(verifier, VT_EVENTRING) &&
|
||||
verifier.VerifyTable(eventRing()) &&
|
||||
VerifyOffset(verifier, VT_BUILDFINGERPRINT) &&
|
||||
verifier.VerifyString(buildFingerprint()) &&
|
||||
VerifyField<uint64_t>(verifier, VT_ABIFINGERPRINT, 8) &&
|
||||
verifier.EndTable();
|
||||
}
|
||||
};
|
||||
@@ -719,6 +742,12 @@ struct WelcomeBuilder {
|
||||
void add_eventRing(::flatbuffers::Offset<MobileGL::Wire::SegmentRef> eventRing) {
|
||||
fbb_.AddOffset(Welcome::VT_EVENTRING, eventRing);
|
||||
}
|
||||
void add_buildFingerprint(::flatbuffers::Offset<::flatbuffers::String> buildFingerprint) {
|
||||
fbb_.AddOffset(Welcome::VT_BUILDFINGERPRINT, buildFingerprint);
|
||||
}
|
||||
void add_abiFingerprint(uint64_t abiFingerprint) {
|
||||
fbb_.AddElement<uint64_t>(Welcome::VT_ABIFINGERPRINT, abiFingerprint, 0);
|
||||
}
|
||||
explicit WelcomeBuilder(::flatbuffers::FlatBufferBuilder &_fbb)
|
||||
: fbb_(_fbb) {
|
||||
start_ = fbb_.StartTable();
|
||||
@@ -738,8 +767,12 @@ inline ::flatbuffers::Offset<Welcome> CreateWelcome(
|
||||
::flatbuffers::Offset<MobileGL::Wire::SegmentRef> cmdRing = 0,
|
||||
::flatbuffers::Offset<MobileGL::Wire::SegmentRef> stageRing = 0,
|
||||
::flatbuffers::Offset<MobileGL::Wire::SegmentRef> replyPool = 0,
|
||||
::flatbuffers::Offset<MobileGL::Wire::SegmentRef> eventRing = 0) {
|
||||
::flatbuffers::Offset<MobileGL::Wire::SegmentRef> eventRing = 0,
|
||||
::flatbuffers::Offset<::flatbuffers::String> buildFingerprint = 0,
|
||||
uint64_t abiFingerprint = 0) {
|
||||
WelcomeBuilder builder_(_fbb);
|
||||
builder_.add_abiFingerprint(abiFingerprint);
|
||||
builder_.add_buildFingerprint(buildFingerprint);
|
||||
builder_.add_eventRing(eventRing);
|
||||
builder_.add_replyPool(replyPool);
|
||||
builder_.add_stageRing(stageRing);
|
||||
@@ -755,6 +788,31 @@ struct Welcome::Traits {
|
||||
static auto constexpr Create = CreateWelcome;
|
||||
};
|
||||
|
||||
inline ::flatbuffers::Offset<Welcome> CreateWelcomeDirect(
|
||||
::flatbuffers::FlatBufferBuilder &_fbb,
|
||||
uint32_t abiMajor = 0,
|
||||
uint32_t abiMinor = 0,
|
||||
uint32_t serverPid = 0,
|
||||
::flatbuffers::Offset<MobileGL::Wire::SegmentRef> cmdRing = 0,
|
||||
::flatbuffers::Offset<MobileGL::Wire::SegmentRef> stageRing = 0,
|
||||
::flatbuffers::Offset<MobileGL::Wire::SegmentRef> replyPool = 0,
|
||||
::flatbuffers::Offset<MobileGL::Wire::SegmentRef> eventRing = 0,
|
||||
const char *buildFingerprint = nullptr,
|
||||
uint64_t abiFingerprint = 0) {
|
||||
auto buildFingerprint__ = buildFingerprint ? _fbb.CreateString(buildFingerprint) : 0;
|
||||
return MobileGL::Wire::CreateWelcome(
|
||||
_fbb,
|
||||
abiMajor,
|
||||
abiMinor,
|
||||
serverPid,
|
||||
cmdRing,
|
||||
stageRing,
|
||||
replyPool,
|
||||
eventRing,
|
||||
buildFingerprint__,
|
||||
abiFingerprint);
|
||||
}
|
||||
|
||||
struct CapsSnapshot FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table {
|
||||
typedef CapsSnapshotBuilder Builder;
|
||||
struct Traits;
|
||||
@@ -764,10 +822,8 @@ struct CapsSnapshot FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table {
|
||||
VT_FORMATCAPS = 8,
|
||||
VT_EXTENSIONS = 10,
|
||||
VT_APIVERSION = 12,
|
||||
VT_MAXCOMPUTEWORKGROUPCOUNT = 14,
|
||||
VT_MAXCOMPUTEWORKGROUPSIZE = 16,
|
||||
VT_TABLESLOTMASK = 18,
|
||||
VT_PREFERSCPUXFBPRIMITIVEACCOUNTING = 20
|
||||
VT_CALLMASK = 22,
|
||||
VT_BACKENDTYPE = 24
|
||||
};
|
||||
const ::flatbuffers::Vector<uint8_t> *dynamicParameters() const {
|
||||
return GetPointer<const ::flatbuffers::Vector<uint8_t> *>(VT_DYNAMICPARAMETERS);
|
||||
@@ -784,17 +840,11 @@ struct CapsSnapshot FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table {
|
||||
const ::flatbuffers::String *apiVersion() const {
|
||||
return GetPointer<const ::flatbuffers::String *>(VT_APIVERSION);
|
||||
}
|
||||
const ::flatbuffers::Vector<int32_t> *maxComputeWorkGroupCount() const {
|
||||
return GetPointer<const ::flatbuffers::Vector<int32_t> *>(VT_MAXCOMPUTEWORKGROUPCOUNT);
|
||||
uint64_t callMask() const {
|
||||
return GetField<uint64_t>(VT_CALLMASK, 0);
|
||||
}
|
||||
const ::flatbuffers::Vector<int32_t> *maxComputeWorkGroupSize() const {
|
||||
return GetPointer<const ::flatbuffers::Vector<int32_t> *>(VT_MAXCOMPUTEWORKGROUPSIZE);
|
||||
}
|
||||
uint64_t tableSlotMask() const {
|
||||
return GetField<uint64_t>(VT_TABLESLOTMASK, 0);
|
||||
}
|
||||
bool prefersCpuXfbPrimitiveAccounting() const {
|
||||
return GetField<uint8_t>(VT_PREFERSCPUXFBPRIMITIVEACCOUNTING, 0) != 0;
|
||||
uint32_t backendType() const {
|
||||
return GetField<uint32_t>(VT_BACKENDTYPE, 0);
|
||||
}
|
||||
template <bool B = false>
|
||||
bool Verify(::flatbuffers::VerifierTemplate<B> &verifier) const {
|
||||
@@ -810,12 +860,8 @@ struct CapsSnapshot FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table {
|
||||
verifier.VerifyVectorOfStrings(extensions()) &&
|
||||
VerifyOffset(verifier, VT_APIVERSION) &&
|
||||
verifier.VerifyString(apiVersion()) &&
|
||||
VerifyOffset(verifier, VT_MAXCOMPUTEWORKGROUPCOUNT) &&
|
||||
verifier.VerifyVector(maxComputeWorkGroupCount()) &&
|
||||
VerifyOffset(verifier, VT_MAXCOMPUTEWORKGROUPSIZE) &&
|
||||
verifier.VerifyVector(maxComputeWorkGroupSize()) &&
|
||||
VerifyField<uint64_t>(verifier, VT_TABLESLOTMASK, 8) &&
|
||||
VerifyField<uint8_t>(verifier, VT_PREFERSCPUXFBPRIMITIVEACCOUNTING, 1) &&
|
||||
VerifyField<uint64_t>(verifier, VT_CALLMASK, 8) &&
|
||||
VerifyField<uint32_t>(verifier, VT_BACKENDTYPE, 4) &&
|
||||
verifier.EndTable();
|
||||
}
|
||||
};
|
||||
@@ -839,17 +885,11 @@ struct CapsSnapshotBuilder {
|
||||
void add_apiVersion(::flatbuffers::Offset<::flatbuffers::String> apiVersion) {
|
||||
fbb_.AddOffset(CapsSnapshot::VT_APIVERSION, apiVersion);
|
||||
}
|
||||
void add_maxComputeWorkGroupCount(::flatbuffers::Offset<::flatbuffers::Vector<int32_t>> maxComputeWorkGroupCount) {
|
||||
fbb_.AddOffset(CapsSnapshot::VT_MAXCOMPUTEWORKGROUPCOUNT, maxComputeWorkGroupCount);
|
||||
void add_callMask(uint64_t callMask) {
|
||||
fbb_.AddElement<uint64_t>(CapsSnapshot::VT_CALLMASK, callMask, 0);
|
||||
}
|
||||
void add_maxComputeWorkGroupSize(::flatbuffers::Offset<::flatbuffers::Vector<int32_t>> maxComputeWorkGroupSize) {
|
||||
fbb_.AddOffset(CapsSnapshot::VT_MAXCOMPUTEWORKGROUPSIZE, maxComputeWorkGroupSize);
|
||||
}
|
||||
void add_tableSlotMask(uint64_t tableSlotMask) {
|
||||
fbb_.AddElement<uint64_t>(CapsSnapshot::VT_TABLESLOTMASK, tableSlotMask, 0);
|
||||
}
|
||||
void add_prefersCpuXfbPrimitiveAccounting(bool prefersCpuXfbPrimitiveAccounting) {
|
||||
fbb_.AddElement<uint8_t>(CapsSnapshot::VT_PREFERSCPUXFBPRIMITIVEACCOUNTING, static_cast<uint8_t>(prefersCpuXfbPrimitiveAccounting), 0);
|
||||
void add_backendType(uint32_t backendType) {
|
||||
fbb_.AddElement<uint32_t>(CapsSnapshot::VT_BACKENDTYPE, backendType, 0);
|
||||
}
|
||||
explicit CapsSnapshotBuilder(::flatbuffers::FlatBufferBuilder &_fbb)
|
||||
: fbb_(_fbb) {
|
||||
@@ -869,20 +909,16 @@ inline ::flatbuffers::Offset<CapsSnapshot> CreateCapsSnapshot(
|
||||
::flatbuffers::Offset<::flatbuffers::Vector<uint8_t>> formatCaps = 0,
|
||||
::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset<::flatbuffers::String>>> extensions = 0,
|
||||
::flatbuffers::Offset<::flatbuffers::String> apiVersion = 0,
|
||||
::flatbuffers::Offset<::flatbuffers::Vector<int32_t>> maxComputeWorkGroupCount = 0,
|
||||
::flatbuffers::Offset<::flatbuffers::Vector<int32_t>> maxComputeWorkGroupSize = 0,
|
||||
uint64_t tableSlotMask = 0,
|
||||
bool prefersCpuXfbPrimitiveAccounting = false) {
|
||||
uint64_t callMask = 0,
|
||||
uint32_t backendType = 0) {
|
||||
CapsSnapshotBuilder builder_(_fbb);
|
||||
builder_.add_tableSlotMask(tableSlotMask);
|
||||
builder_.add_maxComputeWorkGroupSize(maxComputeWorkGroupSize);
|
||||
builder_.add_maxComputeWorkGroupCount(maxComputeWorkGroupCount);
|
||||
builder_.add_callMask(callMask);
|
||||
builder_.add_backendType(backendType);
|
||||
builder_.add_apiVersion(apiVersion);
|
||||
builder_.add_extensions(extensions);
|
||||
builder_.add_formatCaps(formatCaps);
|
||||
builder_.add_rendererInfo(rendererInfo);
|
||||
builder_.add_dynamicParameters(dynamicParameters);
|
||||
builder_.add_prefersCpuXfbPrimitiveAccounting(prefersCpuXfbPrimitiveAccounting);
|
||||
return builder_.Finish();
|
||||
}
|
||||
|
||||
@@ -898,17 +934,13 @@ inline ::flatbuffers::Offset<CapsSnapshot> CreateCapsSnapshotDirect(
|
||||
const std::vector<uint8_t> *formatCaps = nullptr,
|
||||
const std::vector<::flatbuffers::Offset<::flatbuffers::String>> *extensions = nullptr,
|
||||
const char *apiVersion = nullptr,
|
||||
const std::vector<int32_t> *maxComputeWorkGroupCount = nullptr,
|
||||
const std::vector<int32_t> *maxComputeWorkGroupSize = nullptr,
|
||||
uint64_t tableSlotMask = 0,
|
||||
bool prefersCpuXfbPrimitiveAccounting = false) {
|
||||
uint64_t callMask = 0,
|
||||
uint32_t backendType = 0) {
|
||||
auto dynamicParameters__ = dynamicParameters ? _fbb.CreateVector<uint8_t>(*dynamicParameters) : 0;
|
||||
auto rendererInfo__ = rendererInfo ? _fbb.CreateVector<uint8_t>(*rendererInfo) : 0;
|
||||
auto formatCaps__ = formatCaps ? _fbb.CreateVector<uint8_t>(*formatCaps) : 0;
|
||||
auto extensions__ = extensions ? _fbb.CreateVector<::flatbuffers::Offset<::flatbuffers::String>>(*extensions) : 0;
|
||||
auto apiVersion__ = apiVersion ? _fbb.CreateString(apiVersion) : 0;
|
||||
auto maxComputeWorkGroupCount__ = maxComputeWorkGroupCount ? _fbb.CreateVector<int32_t>(*maxComputeWorkGroupCount) : 0;
|
||||
auto maxComputeWorkGroupSize__ = maxComputeWorkGroupSize ? _fbb.CreateVector<int32_t>(*maxComputeWorkGroupSize) : 0;
|
||||
return MobileGL::Wire::CreateCapsSnapshot(
|
||||
_fbb,
|
||||
dynamicParameters__,
|
||||
@@ -916,10 +948,8 @@ inline ::flatbuffers::Offset<CapsSnapshot> CreateCapsSnapshotDirect(
|
||||
formatCaps__,
|
||||
extensions__,
|
||||
apiVersion__,
|
||||
maxComputeWorkGroupCount__,
|
||||
maxComputeWorkGroupSize__,
|
||||
tableSlotMask,
|
||||
prefersCpuXfbPrimitiveAccounting);
|
||||
callMask,
|
||||
backendType);
|
||||
}
|
||||
|
||||
struct DefaultFramebufferInfo FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table {
|
||||
|
||||
@@ -63,6 +63,15 @@ table Hello {
|
||||
backendType: uint;
|
||||
pid: uint;
|
||||
configBlob: [ubyte];
|
||||
// CONTRACT-P5 table 0, "ABI agreement": MGPCaps has only a COMPOSITIONAL size
|
||||
// assertion, because DynamicBackendParameters still carries SizeT and GLenum.
|
||||
// So the two peers assert they were built from the same struct shapes instead
|
||||
// of rewriting them fixed-width (that is P7's account). This is
|
||||
// MG_Remote::CapsAbiFingerprint(): sizeof(DynamicBackendParameters),
|
||||
// sizeof(MGPCaps), sizeof(GLFunctionsTable), the protocol ABI version and the
|
||||
// build's git stamp, mixed. A mismatch is Fatal{AbiMismatch} and NEVER a
|
||||
// downgrade - every alternative silently reads one struct as another.
|
||||
abiFingerprint: ulong;
|
||||
}
|
||||
|
||||
table Welcome {
|
||||
@@ -73,6 +82,12 @@ table Welcome {
|
||||
stageRing: SegmentRef;
|
||||
replyPool: SegmentRef;
|
||||
eventRing: SegmentRef;
|
||||
// The server's half of the assertion above. The string is carried beside the
|
||||
// mixed value only so a mismatch can name both builds in the Fatal line; the
|
||||
// COMPARISON is on abiFingerprint, which also covers the three sizeofs the
|
||||
// string cannot.
|
||||
buildFingerprint: string;
|
||||
abiFingerprint: ulong;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -83,16 +98,57 @@ table Welcome {
|
||||
// (plan B appendix A, `get_caps`). The three blobs are byte-for-byte images of
|
||||
// the corresponding POD structs; they are versioned by structSize-first
|
||||
// discipline, not by this schema.
|
||||
// The four fields this table used to end with are RETIRED (CONTRACT-P5 table 0,
|
||||
// "CapsSnapshot redundancy"):
|
||||
//
|
||||
// maxComputeWorkGroupCount / maxComputeWorkGroupSize - they ride inside
|
||||
// `dynamicParameters` already (BackendObject.h:392-393), and two spellings of
|
||||
// one number is how the two sides come to disagree about it.
|
||||
// tableSlotMask - GLFunctionsTable has SIXTY-NINE function-pointer slots
|
||||
// (BackendObject.h:117-292) and a ulong is 64 bits, so the field could never
|
||||
// address the table its own comment named; and ARCHITECTURE.md:114 already
|
||||
// retired "is this table slot null" as the capability probe in favour of
|
||||
// CallMask, so keeping it would re-introduce exactly what replaced it.
|
||||
// prefersCpuXfbPrimitiveAccounting - answered by kCapCpuXfbPrimitiveAccounting
|
||||
// in `callMask` below.
|
||||
//
|
||||
// THEY ARE `(deprecated)`, NOT DELETED, AND THAT IS NOT A STYLE CHOICE. In
|
||||
// FlatBuffers a table field's id IS its vtable slot, and REMOVING a field FREES
|
||||
// that slot for the next field appended to the table - so plainly deleting these
|
||||
// four would have handed slots 14 and 16, which used to carry `[int]` vectors
|
||||
// (4-byte uoffsets), to `callMask` (an 8-byte inline ulong) and `backendType` (a
|
||||
// 4-byte inline uint). Two peers straddling that edit both still announce
|
||||
// abiMajor 1, and the ABI fingerprint mixes struct sizes and a git stamp, not the
|
||||
// schema, so neither the handshake nor the fingerprint could see it: the reader
|
||||
// would parse a uoffset as a ulong. `(deprecated)` keeps 14/18/20 burned, pushes
|
||||
// the two new fields to 22/24, generates no accessor for the retired names so
|
||||
// nothing can read or write them, and costs zero bytes on the wire. The
|
||||
// alternative - bumping MOBILEGL_PROTOCOL_ABI_MAJOR - is a real break for a
|
||||
// change that does not need to be one.
|
||||
table CapsSnapshot {
|
||||
dynamicParameters: [ubyte];
|
||||
rendererInfo: [ubyte];
|
||||
formatCaps: [ubyte];
|
||||
extensions: [string];
|
||||
apiVersion: string;
|
||||
maxComputeWorkGroupCount: [int]; // 3 entries
|
||||
maxComputeWorkGroupSize: [int]; // 3 entries
|
||||
tableSlotMask: ulong; // which GLFunctionsTable slots the peer registered
|
||||
prefersCpuXfbPrimitiveAccounting: bool;
|
||||
maxComputeWorkGroupCount: [int] (deprecated);
|
||||
maxComputeWorkGroupSize: [int] (deprecated);
|
||||
tableSlotMask: ulong (deprecated);
|
||||
prefersCpuXfbPrimitiveAccounting: bool (deprecated);
|
||||
// MGPCaps::CallMask (MGPipeTypes.h:127). Bits 0..8 are MGPCapBit; bits 32..47
|
||||
// are the CONSUMER MASK - bit (32+n) means "the server has a consumer for
|
||||
// MGPipe subsystem bit n" - and MG_Remote/CapsCodec.h holds the four constexprs
|
||||
// that are the only legal way to fold and test them. It needs a carrier of its
|
||||
// own because `dynamicParameters` is the image of DynamicBackendParameters,
|
||||
// which CallMask is not a member of; and without a carrier R-8's rule that the
|
||||
// client's liveness gates read the caps mirror has nothing to read.
|
||||
callMask: ulong;
|
||||
// The SERVER's backend type, for CapsMirror::Backend(). Hello.backendType is
|
||||
// the CLIENT's request; this is the answer, and the frontend branches that
|
||||
// switch on it (GL_Framebuffer.cpp:47, GL_Texture.cpp:6536, CompileEnv.cpp:122)
|
||||
// take a wrong arm rather than fail on a value they do not know, so it may not
|
||||
// be guessed from the renderer string.
|
||||
backendType: uint;
|
||||
}
|
||||
|
||||
table DefaultFramebufferInfo {
|
||||
|
||||
@@ -6,46 +6,528 @@
|
||||
// SPDX-License-Identifier: LGPL-3.0-only
|
||||
// End of Source File Header
|
||||
|
||||
// P5 c0 stubs for package v1 (with p1 for the stamp rule).
|
||||
// P5 package v1: the applier bridge, and the consumer for contract 7's five class-B verbs.
|
||||
|
||||
#include "PipeApplier.h"
|
||||
|
||||
#include "../Transport/ReplySlot.h"
|
||||
|
||||
#include <Config.h>
|
||||
#include <MG_Backend/MGPipe/PipeInputs.h>
|
||||
#include <MG_Remote/Client/ClientSession.h>
|
||||
#include <MG_Pipe/PipeApply.h>
|
||||
#include <MG_Util/Converters/GLToMG/TextureEnumConverter.h>
|
||||
#include <MG_Util/Debug/Log.h>
|
||||
#include <MG_Util/Metrics/TextureMetrics.h>
|
||||
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
|
||||
namespace MobileGL::MG_Remote::Server {
|
||||
|
||||
#define MGP5_C0_STUB(what) \
|
||||
do { \
|
||||
MGLOG_F("MGPipe: Fatal{UnimplementedPipeApplier, \"%s\"} - P5 package v1 has not landed " \
|
||||
"this yet; c0 shipped the signature only", \
|
||||
what); \
|
||||
std::abort(); \
|
||||
} while (0)
|
||||
|
||||
ReplyPool::ReplyPool(void* base, Uint64 sizeBytes, Uint32 slotCount, Uint32 slotBytes)
|
||||
: m_base(static_cast<Uint8*>(base)), m_size(sizeBytes), m_slots(slotCount), m_slotBytes(slotBytes) {}
|
||||
|
||||
void ReplyPool::PostReply(Uint64, Int32, const void*, Uint64) { MGP5_C0_STUB("ReplyPool::PostReply"); }
|
||||
// PACKAGE s1's, not v1's, even though the class is declared in v1's header: the SEG_REPLY
|
||||
// slot pool is s1's deliverable (BRIEF 5) and its addressing lives in one place,
|
||||
// Transport/ReplySlot.h, which the CLIENT reads the same slots back through. Duplicating
|
||||
// `seq % slots` on this side is how the two halves come to disagree about which slot an
|
||||
// answer is in - and because seq IS the reply-slot id (R-3), a disagreement reads another
|
||||
// call's answer instead of failing.
|
||||
//
|
||||
// The view is rebuilt per call rather than stored, so that this body does not change
|
||||
// ReplyPool's four members and therefore does not touch v1's header at all.
|
||||
void ReplyPool::PostReply(Uint64 seq, Int32 status, const void* bytes, Uint64 size) {
|
||||
Transport::ReplySlotPool pool(m_base, m_size, m_slots);
|
||||
// Fatal inside Post when the answer does not fit a slot: P5 does not chunk replies,
|
||||
// and the client knows an answer's size before it emits the record.
|
||||
pool.Post(seq, status, bytes, size);
|
||||
}
|
||||
|
||||
Uint32 ReplyPool::SlotBytes() const { return m_slotBytes; }
|
||||
|
||||
// -----------------------------------------------------------------------------------
|
||||
// ServerVerbSink - the five class-B verbs
|
||||
// -----------------------------------------------------------------------------------
|
||||
|
||||
void ServerVerbSink::SetBackend(MG_Backend::BackendObject* backend) { m_backend = backend; }
|
||||
|
||||
const MG_Backend::GlobalBackendFunctionsTable* ServerVerbSink::Table(const char* verb) const {
|
||||
if (m_backend == nullptr) {
|
||||
// DECLINE BY NAME, DO NOT DEREFERENCE. A verb that arrives before
|
||||
// ServerLoop::CreateBackend has run means the hook order changed under us, and the
|
||||
// honest answer is "this build did not apply it" - which DecodeAndApply reports as
|
||||
// false and the lane sees as a record that did not render, rather than as a crash
|
||||
// with no line saying which verb was first.
|
||||
MGLOG_E_ONCE("MG_Remote server: %s arrived with no backend object; the verb is "
|
||||
"DECLINED. ServerLoop::CreateBackend runs from MG_Backend::Init()'s "
|
||||
"hook, before ClientSession::Start",
|
||||
verb);
|
||||
return nullptr;
|
||||
}
|
||||
return &m_backend->GetBackendFunctions();
|
||||
}
|
||||
|
||||
Bool ServerVerbSink::OnClear(const MG_Pipe::MGPClear& clear) {
|
||||
const MG_Backend::GlobalBackendFunctionsTable* table = Table("clear");
|
||||
if (table == nullptr) return false;
|
||||
const MG_Backend::GLFunctionsTable& gl = table->GL;
|
||||
|
||||
// THE FBO HANDLE IS NOT RESOLVED HERE, AND THAT IS THE RULING RATHER THAN AN OMISSION.
|
||||
// MGPClear::Fbo names the framebuffer the clear belongs to, but the BINDING is already
|
||||
// server state: set_framebuffer_state (op 33) arrives ahead of the clear and the
|
||||
// applier has bound it. Re-resolving the handle to a frontend FramebufferObject here
|
||||
// would need the SharedPtr the four ClearNamedFramebuffer* entries take - a frontend
|
||||
// heap reference that table 2 lists as one of the six fields with no wire carrier. So
|
||||
// P5 clears THE BOUND FRAMEBUFFER, which for the reduced path (default FBO) is exactly
|
||||
// right, and the named form is P7's along with the handle it needs.
|
||||
switch (clear.Kind) {
|
||||
case kMGPClearKindWhole:
|
||||
if (gl.Clear == nullptr) return false;
|
||||
gl.Clear(static_cast<GLbitfield>(clear.BufferMask));
|
||||
break;
|
||||
case kMGPClearKindColor:
|
||||
switch (clear.ValueClass) {
|
||||
case kMGPClearValueClassFloat:
|
||||
if (gl.ClearBufferfv == nullptr) return false;
|
||||
gl.ClearBufferfv(GL_COLOR, clear.DrawBufferIndex,
|
||||
reinterpret_cast<const GLfloat*>(clear.ColorValue));
|
||||
break;
|
||||
case kMGPClearValueClassInt:
|
||||
if (gl.ClearBufferiv == nullptr) return false;
|
||||
gl.ClearBufferiv(GL_COLOR, clear.DrawBufferIndex,
|
||||
reinterpret_cast<const GLint*>(clear.ColorValue));
|
||||
break;
|
||||
case kMGPClearValueClassUint:
|
||||
if (gl.ClearBufferuiv == nullptr) return false;
|
||||
gl.ClearBufferuiv(GL_COLOR, clear.DrawBufferIndex,
|
||||
reinterpret_cast<const GLuint*>(clear.ColorValue));
|
||||
break;
|
||||
default:
|
||||
// A value class outside the three is a wire fault, not a fallback: all three
|
||||
// representations of a clear colour are numerically populated by the frontend
|
||||
// and only this field says which one the backend must use, so guessing renders
|
||||
// a plausible wrong colour.
|
||||
Wire::WireProtocolFatalAt("MGPClear::ValueClass", clear.ValueClass, 3);
|
||||
}
|
||||
break;
|
||||
case kMGPClearKindDepth:
|
||||
if (gl.ClearBufferfv == nullptr) return false;
|
||||
gl.ClearBufferfv(GL_DEPTH, 0, &clear.DepthValue);
|
||||
break;
|
||||
case kMGPClearKindStencil:
|
||||
if (gl.ClearBufferiv == nullptr) return false;
|
||||
gl.ClearBufferiv(GL_STENCIL, 0, &clear.StencilValue);
|
||||
break;
|
||||
case kMGPClearKindDepthStencil:
|
||||
if (gl.ClearBufferfi == nullptr) return false;
|
||||
gl.ClearBufferfi(GL_DEPTH_STENCIL, 0, clear.DepthValue, clear.StencilValue);
|
||||
break;
|
||||
default:
|
||||
Wire::WireProtocolFatalAt("MGPClear::Kind", clear.Kind, kMGPClearKindDepthStencil + 1);
|
||||
}
|
||||
++m_clears;
|
||||
return true;
|
||||
}
|
||||
|
||||
Bool ServerVerbSink::OnBlit(const MG_Pipe::MGPBlit& blit) {
|
||||
const MG_Backend::GlobalBackendFunctionsTable* table = Table("blit");
|
||||
if (table == nullptr) return false;
|
||||
if (table->GL.BlitFramebuffer == nullptr) return false;
|
||||
// Same ruling as OnClear's: the read and draw framebuffers are already bound by the
|
||||
// set_framebuffer_state records that preceded this one, so the unnamed entry point is
|
||||
// the one that matches what the server's state actually is. BlitNamedFramebuffer needs
|
||||
// two frontend SharedPtrs, which table 2 lists as uncarried.
|
||||
table->GL.BlitFramebuffer(blit.SrcX0, blit.SrcY0, blit.SrcX1, blit.SrcY1, blit.DstX0,
|
||||
blit.DstY0, blit.DstX1, blit.DstY1,
|
||||
static_cast<GLbitfield>(blit.Mask),
|
||||
static_cast<GLenum>(blit.Filter));
|
||||
++m_blits;
|
||||
return true;
|
||||
}
|
||||
|
||||
Bool ServerVerbSink::OnPresent(const MG_Pipe::MGPPresent& present) {
|
||||
const MG_Backend::GlobalBackendFunctionsTable* table = Table("present");
|
||||
if (table == nullptr) return false;
|
||||
if (table->Present == nullptr) return false;
|
||||
// Present is the ONLY frame-boundary drain the backend has (DirectGLES.cpp:12424-12470:
|
||||
// the fence poll, the four ring OnPresent hooks, TrimBufferPool, PipeStats::OnPresent),
|
||||
// which is why ARCHITECTURE.md:531 wants present <-> eglSwapBuffers to stay 1:1.
|
||||
//
|
||||
// m-1: THAT 1:1 IS A CONVENTION c1 UPHOLDS, NOT A STRUCTURAL GUARANTEE, and the earlier
|
||||
// claim that it was structural is wrong. This Present() is reached ONLY from a present
|
||||
// RECORD (ServerVerbSink::OnPresent). ServerSwapEGLBuffers does NOT reach it - it calls
|
||||
// backend->SwapEGLBuffers -> BackendObject::SwapEGLBuffers -> eglSwapBuffers, and never
|
||||
// Present() - so the two paths do NOT both end here. The frame count staying in step with
|
||||
// the swap count rests entirely on c1 emitting exactly one present record per swap;
|
||||
// nothing here compares Presents() to a swap count. If that drifts, the frame fence and
|
||||
// TrimBufferPool's recycle watermark stop tracking frames - which is the reason the 1:1
|
||||
// was wanted, recorded here so a future swap-without-present is looked for rather than
|
||||
// assumed impossible. Presents() is exposed for a lane that wants to make the comparison.
|
||||
table->Present();
|
||||
++m_presents;
|
||||
// FrameSerial 0 means "the server stamps its own" (c1-v1 8.3): P5 has no client-side
|
||||
// present credit, so the client sends 0 and the frame count on this side IS the serial.
|
||||
m_lastPresentSerial = present.FrameSerial != 0 ? present.FrameSerial : m_presents;
|
||||
return true;
|
||||
}
|
||||
|
||||
Bool ServerVerbSink::OnReadPixels(const MG_Pipe::MGPReadbackInfo& info, Uint64 seq,
|
||||
Wire::ReplySink* replies) {
|
||||
if (replies == nullptr) {
|
||||
// The decoder always passes its ReplySink; a null one means the applier was built
|
||||
// without a reply pool, and answering nothing would leave the client's barrier
|
||||
// waiting for a slot that never gets stamped - a hang, not a wrong picture.
|
||||
MGLOG_F("MGPipe: Fatal{ProtocolCorruption, \"read_pixels without a reply sink\"} - "
|
||||
"the pixels' only destination in P5 is SEG_REPLY (contract table 1 row 23) "
|
||||
"and a client blocked on seq %llu would never be answered",
|
||||
static_cast<unsigned long long>(seq));
|
||||
std::abort();
|
||||
}
|
||||
const MG_Backend::GlobalBackendFunctionsTable* table = Table("read_pixels");
|
||||
if (table == nullptr || table->GL.ReadPixels == nullptr) {
|
||||
// DECLINED IS A REAL ANSWER (table 0's slot-header row) and it is the RIGHT one
|
||||
// here: the client is parked on this seq inside the verb barrier, so returning
|
||||
// false without posting would convert "not implemented" into "never returns".
|
||||
replies->PostReply(seq, Wire::ReplySink::kStatusDeclined, nullptr, 0);
|
||||
return false;
|
||||
}
|
||||
if (info.DstSize == 0) {
|
||||
replies->PostReply(seq, Wire::ReplySink::kStatusError, nullptr, 0);
|
||||
return false;
|
||||
}
|
||||
// ID-49: THE REPLY CROSSES TIGHT AND PACK STATE NEVER CROSSES FOR A READ. The server reads
|
||||
// with NEUTRAL pack state - ROW_LENGTH 0, SKIP_ROWS/PIXELS/IMAGES 0, ALIGNMENT 1 - into a
|
||||
// w*h*bytesPerPixel extent that IS the reply payload, and restores the pack state
|
||||
// afterwards; the CLIENT scatters those tight rows into the application's pointer per its
|
||||
// own GL_PACK_* state (c1's half). Reading with the client's pack state HERE was the
|
||||
// codex-1 blocker: the backend's ReadPixels honours ROW_LENGTH/SKIP_* and writes PAST a
|
||||
// DstSize the client sized without the initial skip (a 4x3 RGBA8 read with ROW_LENGTH=8,
|
||||
// SKIP_ROWS=1, SKIP_PIXELS=2 allocates 80 and lands its last write at 120), which is the
|
||||
// two DepthReadbackHonoursThePackPixelStoreParameters SEGFAULTs the census omitted. THE
|
||||
// DstSize FORMULA BOTH SIDES AGREE ON: w * h * bytesPerPixel. A non-default server-visible
|
||||
// pack state can no longer change either the reply's size or its bytes.
|
||||
const SizeT bytesPerPixel = MG_Util::GetInputBytesPerPixel(
|
||||
MG_Util::ConvertGLEnumToTextureInputFormat(static_cast<GLenum>(info.Format)),
|
||||
MG_Util::ConvertGLEnumToTexturePixelDataType(static_cast<GLenum>(info.Type)));
|
||||
// Tight size = w*h*bpp, the whole of ID-49's formula. If this build cannot size the
|
||||
// (format, type) pair (bpp == 0) it trusts the client's DstSize - a neutral read still
|
||||
// cannot overflow it via row length or skips, and an unsizeable pair is c1's
|
||||
// Fatal{UnsizedReadback} at emission, not this side's.
|
||||
const Uint64 tight = bytesPerPixel != 0
|
||||
? static_cast<Uint64>(info.Box.W) * static_cast<Uint64>(info.Box.H) *
|
||||
static_cast<Uint64>(bytesPerPixel)
|
||||
: info.DstSize;
|
||||
if (bytesPerPixel != 0 && tight != info.DstSize) {
|
||||
// Both halves compute w*h*bpp under ID-49, so a disagreement is the two sides
|
||||
// disagreeing about the frame. Read (and post) the tight extent this side owns rather
|
||||
// than the client's number, so a wrong DstSize can never make this a short read into
|
||||
// uninitialised scratch.
|
||||
MGLOG_E_ONCE("MG_Remote server: read_pixels DstSize %llu != tight w*h*bpp %llu "
|
||||
"(%ux%u, bpp %zu); reading the tight extent (ID-49)",
|
||||
static_cast<unsigned long long>(info.DstSize),
|
||||
static_cast<unsigned long long>(tight), info.Box.W, info.Box.H,
|
||||
bytesPerPixel);
|
||||
}
|
||||
if (tight > m_readbackScratch.size()) {
|
||||
m_readbackScratch.resize(static_cast<SizeT>(tight));
|
||||
}
|
||||
|
||||
// Save the server-visible pack state, force neutral for the read, restore. Both go through
|
||||
// the applier's own set_pixel_pack_state entry point (MGPipeApplySetPixelPackState writes
|
||||
// gPipeInputs.m_pixelStore[0], which the backend's ReadPixels reads via
|
||||
// MGB_CTX->GetPixelStoreParameters); the read is synchronous on this thread, so the window
|
||||
// in which the pack state is neutral does not outlive the call.
|
||||
const MG_Pipe::PixelStoreParameters savedPack =
|
||||
MG_Pipe::gPipeInputs.GetPixelStoreParameters(/*isUnpack=*/false);
|
||||
MG_Pipe::MGPPixelPackState neutralPack{};
|
||||
neutralPack.Pack.RowLength = 0;
|
||||
neutralPack.Pack.SkipRows = 0;
|
||||
neutralPack.Pack.SkipPixels = 0;
|
||||
neutralPack.Pack.SkipImages = 0;
|
||||
neutralPack.Pack.Alignment = 1;
|
||||
MG_Pipe::MGPipeApplySetPixelPackState(neutralPack);
|
||||
|
||||
table->GL.ReadPixels(info.Box.X, info.Box.Y, static_cast<GLsizei>(info.Box.W),
|
||||
static_cast<GLsizei>(info.Box.H), static_cast<GLenum>(info.Format),
|
||||
static_cast<GLenum>(info.Type), m_readbackScratch.data());
|
||||
|
||||
MG_Pipe::MGPPixelPackState restorePack{};
|
||||
restorePack.Pack = savedPack;
|
||||
MG_Pipe::MGPipeApplySetPixelPackState(restorePack);
|
||||
|
||||
// m-7: the answer is written into the slot HERE, mid-apply, while the verb stamp is still
|
||||
// up - and that is safe for exactly one reason, which is the contract's and is stated so it
|
||||
// is not mistaken for luck: the client reaches a reply slot ONLY through appliedSeq
|
||||
// (ReplySlot.h's ORDERING clause), never by polling the slot's own stamp, and s1's
|
||||
// SessionConsumer::ApplyOne publishes appliedSeq only AFTER PipeApplier::ApplyOne has run
|
||||
// LeaveApplier() and (on the joint tree) dropped the ScopedApplierEntry. So by the time the
|
||||
// client is allowed to look at this slot, the apply-side gPipeInputs flag is already down.
|
||||
replies->PostReply(seq, Wire::ReplySink::kStatusOk, m_readbackScratch.data(), tight);
|
||||
m_readbackBytes += tight;
|
||||
++m_readbacks;
|
||||
return true;
|
||||
}
|
||||
|
||||
// P5b's server-side stub shape (CONTRACT-P5B.md): the same line the client's class-C table
|
||||
// raises (EmitTables.cpp UnmigratedVerbFatal) and the same family the census greps, so a
|
||||
// slot flipped on the client ahead of its server half aborts BY NAME on the apply thread
|
||||
// rather than rendering nothing. Named "(server sink)" in the message so a log reader can
|
||||
// tell which half is missing.
|
||||
[[noreturn]] static void ServerUnmigratedVerbFatal(const char* slot) {
|
||||
MGLOG_F("MGPipe: Fatal{UnmigratedVerb, \"%s\"} (server sink: the record crossed and "
|
||||
"ServerVerbSink has no body for it yet - CONTRACT-P5B.md names the package)",
|
||||
slot);
|
||||
std::abort();
|
||||
}
|
||||
|
||||
Bool ServerVerbSink::OnDrawVbo(const MG_Pipe::MGPDrawInfo& info,
|
||||
const MG_Pipe::MGPDrawRange* ranges,
|
||||
const MG_Pipe::MGHostSpan* userIndices,
|
||||
const MG_Pipe::MGPDrawIndirect* indirect) {
|
||||
const MG_Backend::GlobalBackendFunctionsTable* table = Table("draw_vbo");
|
||||
if (table == nullptr) return false;
|
||||
// P5b d1 (CONTRACT-P5B.md): the three arms the contract gives this sink and P5 did not
|
||||
// implement are DECLINED BY NAME until d1 lands them - the same names the census greps,
|
||||
// so the lane's first-blocker table reads the server's gap as the slot it is.
|
||||
if (indirect != nullptr) {
|
||||
ServerUnmigratedVerbFatal(info.IndexSize == 0 ? "MultiDrawArraysIndirect"
|
||||
: "MultiDrawElementsIndirect");
|
||||
}
|
||||
if (userIndices != nullptr) {
|
||||
// The span is validated and names a SEG_STAGE run the client staged (d1's rule for
|
||||
// client-side index arrays); resolving it is MG_Pipe::MGPipeHostBytes and passing
|
||||
// the pointer to gl.DrawElements is d1's body. Declined by name until then.
|
||||
ServerUnmigratedVerbFatal("DrawElements+CLIENT_INDICES");
|
||||
}
|
||||
if (ranges == nullptr || info.NumDraws == 0) return false;
|
||||
|
||||
// P5 IMPLEMENTS THE TWO SHAPES ITS REDUCED PATH USES AND DECLINES THE REST BY NAME.
|
||||
// draw_vbo collapses all twenty draw entry points, and picking the right one needs the
|
||||
// instancing / base-vertex / base-instance / multi-draw cross product. TriangleScenario
|
||||
// is a single non-instanced array draw and OpenRA's are single indexed draws from a
|
||||
// bound element buffer; the rest are d1's (CONTRACT-P5B.md d1 says which GL entry each
|
||||
// shape of the record dispatches to).
|
||||
const MG_Backend::GLFunctionsTable& gl = table->GL;
|
||||
const Bool instanced = info.InstanceCount > 1 || info.StartInstance != 0;
|
||||
if (info.NumDraws != 1) {
|
||||
ServerUnmigratedVerbFatal(info.IndexSize == 0 ? "MultiDrawArrays" : "MultiDrawElements");
|
||||
}
|
||||
if (instanced) {
|
||||
ServerUnmigratedVerbFatal(info.IndexSize == 0 ? "DrawArraysInstanced"
|
||||
: "DrawElementsInstanced");
|
||||
}
|
||||
const MG_Pipe::MGPDrawRange& range = ranges[0];
|
||||
if (info.IndexSize == 0) {
|
||||
if (gl.DrawArrays == nullptr) return false;
|
||||
gl.DrawArrays(static_cast<GLenum>(info.Mode), static_cast<GLint>(range.Start),
|
||||
static_cast<GLsizei>(range.Count));
|
||||
} else {
|
||||
if (gl.DrawElementsBaseVertex == nullptr) return false;
|
||||
GLenum indexType = GL_UNSIGNED_INT;
|
||||
switch (info.IndexSize) {
|
||||
case 1: indexType = GL_UNSIGNED_BYTE; break;
|
||||
case 2: indexType = GL_UNSIGNED_SHORT; break;
|
||||
case 4: indexType = GL_UNSIGNED_INT; break;
|
||||
default:
|
||||
// IndexSize is "0 = arrays, else 1 / 2 / 4" (MGPipeTypes.h:1323) and nothing
|
||||
// else is a legal width; defaulting to 4 would read past the element buffer.
|
||||
Wire::WireProtocolFatalAt("MGPDrawInfo::IndexSize", info.IndexSize, 4);
|
||||
}
|
||||
// Start is the FIRST INDEX, so the byte offset into the bound element buffer is
|
||||
// Start * IndexSize - the same arithmetic PipeFill's emitter inverted.
|
||||
const auto offset = static_cast<std::uintptr_t>(range.Start) * info.IndexSize;
|
||||
gl.DrawElementsBaseVertex(static_cast<GLenum>(info.Mode),
|
||||
static_cast<GLsizei>(range.Count), indexType,
|
||||
reinterpret_cast<const void*>(offset), range.IndexBias);
|
||||
}
|
||||
++m_draws;
|
||||
return true;
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------------------
|
||||
// P5b: the stubs the four migration packages replace (MG_Remote/CONTRACT-P5B.md).
|
||||
//
|
||||
// Each dies by the GL slot's own name. The record has crossed and been validated by the
|
||||
// codec by the time one of these runs, so the only thing missing is the backend call, and
|
||||
// the package that owns the row writes it here: `Table("<row>")`, the null-slot check
|
||||
// (a backend that leaves the slot null DECLINES, which is the monolith's null-slot answer
|
||||
// in the same words), the call, and a tally the lane can assert moved.
|
||||
// -----------------------------------------------------------------------------------
|
||||
|
||||
// ---- i1 ----
|
||||
Bool ServerVerbSink::OnLaunchGrid(const MG_Pipe::MGPGridInfo& grid) {
|
||||
(void)grid;
|
||||
ServerUnmigratedVerbFatal(grid.IsIndirect ? "DispatchComputeIndirect" : "DispatchCompute");
|
||||
}
|
||||
|
||||
Bool ServerVerbSink::OnMemoryBarrier(const MG_Pipe::MGPMemoryBarrier& barrier) {
|
||||
ServerUnmigratedVerbFatal(barrier.ByRegion ? "MemoryBarrierByRegion" : "MemoryBarrier");
|
||||
}
|
||||
|
||||
Bool ServerVerbSink::OnResourceCopyRegion(const MG_Pipe::MGPCopyRegion& copy) {
|
||||
(void)copy;
|
||||
ServerUnmigratedVerbFatal("CopyImageSubData");
|
||||
}
|
||||
|
||||
Bool ServerVerbSink::OnBindShaderImage(const MG_Pipe::MGPImageBind& bind) {
|
||||
(void)bind;
|
||||
ServerUnmigratedVerbFatal("BindImageTexture");
|
||||
}
|
||||
|
||||
Bool ServerVerbSink::OnSetStorageBlockBinding(const MG_Pipe::MGPStorageBlockBinding& binding,
|
||||
const char* name) {
|
||||
(void)binding;
|
||||
(void)name;
|
||||
ServerUnmigratedVerbFatal("ShaderStorageBlockBinding");
|
||||
}
|
||||
|
||||
// ---- t2 ----
|
||||
Bool ServerVerbSink::OnBeginStreamOutput(const MG_Pipe::MGPStreamOutputBegin& begin) {
|
||||
(void)begin;
|
||||
ServerUnmigratedVerbFatal("BeginTransformFeedback");
|
||||
}
|
||||
|
||||
Bool ServerVerbSink::OnEndStreamOutput(const MG_Pipe::MGPXfbAccounting& accounting) {
|
||||
(void)accounting;
|
||||
ServerUnmigratedVerbFatal("EndTransformFeedback");
|
||||
}
|
||||
|
||||
Bool ServerVerbSink::OnPauseStreamOutput(const MG_Pipe::MGPStreamOutputControl& control) {
|
||||
(void)control;
|
||||
ServerUnmigratedVerbFatal("PauseTransformFeedback");
|
||||
}
|
||||
|
||||
Bool ServerVerbSink::OnResumeStreamOutput(const MG_Pipe::MGPStreamOutputControl& control) {
|
||||
(void)control;
|
||||
ServerUnmigratedVerbFatal("ResumeTransformFeedback");
|
||||
}
|
||||
|
||||
Bool ServerVerbSink::OnBindStreamOutput(const MG_Pipe::MGPStreamOutputBind& bind) {
|
||||
(void)bind;
|
||||
ServerUnmigratedVerbFatal("BindTransformFeedback");
|
||||
}
|
||||
|
||||
Bool ServerVerbSink::OnPatchParameter(const MG_Pipe::MGPPatchParameter& patch) {
|
||||
(void)patch;
|
||||
ServerUnmigratedVerbFatal("PatchParameteri");
|
||||
}
|
||||
|
||||
// ---- f1 ----
|
||||
Bool ServerVerbSink::OnGenerateMipmap(const MG_Pipe::MGPMipPlan& plan) {
|
||||
(void)plan;
|
||||
ServerUnmigratedVerbFatal("GenerateMipmap");
|
||||
}
|
||||
|
||||
Bool ServerVerbSink::OnCopyFramebufferToTexture(const MG_Pipe::MGPCopyFromFramebuffer& copy) {
|
||||
ServerUnmigratedVerbFatal(copy.SubImage ? "CopyTexSubImage2D" : "CopyTexImage2D");
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------------------
|
||||
// PipeApplier
|
||||
// -----------------------------------------------------------------------------------
|
||||
|
||||
PipeApplier::PipeApplier(Wire::SegmentTable* segments, ReplyPool* replies)
|
||||
: m_segments(segments), m_replies(replies) {}
|
||||
|
||||
Bool PipeApplier::ApplyOne(const Transport::RingRecordView&) { MGP5_C0_STUB("PipeApplier::ApplyOne"); }
|
||||
|
||||
void PipeApplier::StampVerbBoundary(MG_Pipe::MGPWireOp) {
|
||||
MGP5_C0_STUB("PipeApplier::StampVerbBoundary");
|
||||
void PipeApplier::Attach(Transport::RingControl* control, MG_Backend::BackendObject* backend) {
|
||||
if (control == nullptr || m_segments == nullptr) {
|
||||
MGLOG_F("MGPipe: Fatal{ProtocolCorruption, \"PipeApplier::Attach\"} - no control "
|
||||
"page or no segment table; ServerSession::Accept builds both before the "
|
||||
"apply thread starts");
|
||||
std::abort();
|
||||
}
|
||||
m_verbs.SetBackend(backend);
|
||||
m_decoder = Wire::PipeWireDecoder(control, m_segments, m_replies);
|
||||
m_decoder.SetVerbSink(&m_verbs);
|
||||
m_attached = true;
|
||||
}
|
||||
|
||||
Uint64 PipeApplier::ResidualPullCount() const { return m_residualPulls; }
|
||||
|
||||
void PipeApplier::PoisonRetiredStageBytes(Uint64, Uint64) {
|
||||
MGP5_C0_STUB("PipeApplier::PoisonRetiredStageBytes");
|
||||
void PipeApplier::Detach() {
|
||||
m_decoder = Wire::PipeWireDecoder();
|
||||
m_verbs.SetBackend(nullptr);
|
||||
m_attached = false;
|
||||
}
|
||||
|
||||
#undef MGP5_C0_STUB
|
||||
Bool PipeApplier::Attached() const { return m_attached; }
|
||||
|
||||
Bool PipeApplier::ApplyOne(const Transport::RingRecordView& record) {
|
||||
if (!m_attached) {
|
||||
MGLOG_F("MGPipe: Fatal{ProtocolCorruption, \"PipeApplier::ApplyOne before Attach\"} "
|
||||
"- a record reached the applier with no decoder; the apply thread calls "
|
||||
"Attach once before its first pop");
|
||||
std::abort();
|
||||
}
|
||||
// R-1's INVARIANT, THE SERVER'S HALF (table 3's gPipeInputs row, c1-v1 8.1). The flag
|
||||
// is raised for the WHOLE of this function and not only around DecodeAndApply: the
|
||||
// stamp below and LeaveApplier at the end are both writes to gPipeInputs, and the client
|
||||
// asserts the flag is down before it publishes (ClientSession::EmitAndWait), so a
|
||||
// bracket that excluded either would leave a real write outside the check. It is
|
||||
// dropped before this function returns, and s1's SessionConsumer::ApplyOne publishes
|
||||
// appliedSeq only after that - so by the time the client is runnable the flag is down.
|
||||
const Client::ClientSession::ScopedApplierEntry insideApplier;
|
||||
// ORDER IS THE CONTRACT'S: stamp, then apply. The stamp is what makes any server-side
|
||||
// read of gPipeInputs legal at all (PipeApplier.h's block 1), so a record applied
|
||||
// before it aborts on the FIRST field inside SyncRenderState.
|
||||
StampVerbBoundary(static_cast<MG_Pipe::MGPWireOp>(record.kind));
|
||||
const Bool applied = m_decoder.DecodeAndApply(record);
|
||||
// AND THE CLEAR IS INSIDE ApplyOne, NOT AFTER THE DRAIN BATCH. That is not tidiness,
|
||||
// it is the barrier invariant. s1's SessionConsumer::ApplyOne publishes appliedSeq the
|
||||
// instant this returns, and publishing appliedSeq is what makes the CLIENT runnable
|
||||
// again (R-1: the barrier waits on exactly that watermark). A clear that ran after the
|
||||
// batch would therefore be a second writer of gPipeInputs while the client is already
|
||||
// touching it - the one thing table 3 says may not be introduced before the barrier
|
||||
// retires - and the first version of this file had it there. It was caught by
|
||||
// AClearRecordCrossesAndIsStampedAsAVerbBoundary failing INTERMITTENTLY, which is what
|
||||
// a race looks like from the outside.
|
||||
//
|
||||
// THE COST, STATED: a record that is NOT a verb boundary now applies with the flag
|
||||
// disarmed, so a sticky forward pulled from inside such a record's applier is not
|
||||
// counted in `rsp`. Closing that needs an "enter the applier" entry point beside
|
||||
// MGPipeServerStampVerbBoundary that arms the flag WITHOUT re-stamping - re-stamping on
|
||||
// a non-verb op is what p1 forbids outright - and PipeInputs.cpp is p1's file. Left for
|
||||
// the integrator to sequence; it makes `rsp` larger, never smaller, so the number this
|
||||
// phase reports is a floor.
|
||||
LeaveApplier();
|
||||
return applied;
|
||||
}
|
||||
|
||||
// p1's rule verbatim (p1-v1 2). MGPipeVerbForWireOp is generated from MGP_VERB_OP_LIST in
|
||||
// FieldOwnership.def and answers kVerbCount for every op that is NOT a verb boundary, so
|
||||
// calling it unconditionally on every record is both correct and cheap. Four ops stamp:
|
||||
// Clear -> Clear, DrawVbo -> DrawArrays, ReadPixels -> ReadPixels, Blit -> BlitFramebuffer.
|
||||
//
|
||||
// PRESENT IS DELIBERATELY NOT ONE, although contract 7 puts it in class B: FillPoints.def:21
|
||||
// says Present and SetSwapInterval "go through BackendObject virtuals and read no frontend
|
||||
// state, so they are not verbs here". There is no MGPipeVerb::Present, and stamping there
|
||||
// would retire the previous verb's answers with nothing to put in their place.
|
||||
void PipeApplier::StampVerbBoundary(MG_Pipe::MGPWireOp op) {
|
||||
const MG_Pipe::MGPipeVerb verb = MG_Pipe::MGPipeVerbForWireOp(op);
|
||||
if (verb == MG_Pipe::MGPipeVerb::kVerbCount) return; // not a verb boundary: stamp nothing
|
||||
MG_Pipe::MGPipeServerStampVerbBoundary(verb);
|
||||
}
|
||||
|
||||
void PipeApplier::LeaveApplier() { MG_Pipe::MGPipeServerClearVerbBoundary(); }
|
||||
|
||||
Uint64 PipeApplier::ResidualPullCount() const { return MG_Pipe::MGPipeResidualPullCount(); }
|
||||
|
||||
// The decoder poisons EXACTLY the runs it resolved, from inside DecodeAndApply, once the
|
||||
// applier has returned - so this entry point is the manual one, for a caller that knows a
|
||||
// range is dead and is not the decoder. It is kept because c0's signature block declares
|
||||
// it and because the R-11 copy in Managers.cpp is verified by poisoning a range by hand in
|
||||
// a unit case; nothing on the live path calls it.
|
||||
void PipeApplier::PoisonRetiredStageBytes(Uint64 offset, Uint64 size) {
|
||||
if (size == 0 || m_segments == nullptr) return;
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
if (!MG_Config::Ipc.Audit) return;
|
||||
#endif
|
||||
const void* run = m_segments->Resolve(Wire::kSegStage, offset, size);
|
||||
if (run == nullptr) return;
|
||||
std::memset(const_cast<void*>(run), 0xDD, static_cast<SizeT>(size));
|
||||
}
|
||||
|
||||
Uint64 PipeApplier::PoisonedStageBytes() const { return m_decoder.PoisonedStageBytes(); }
|
||||
|
||||
Uint64 PipeApplier::DecoderAppliedSeq() const { return m_decoder.AppliedSeq(); }
|
||||
|
||||
} // namespace MobileGL::MG_Remote::Server
|
||||
|
||||
@@ -40,6 +40,7 @@
|
||||
#pragma once
|
||||
#include <Includes.h>
|
||||
|
||||
#include <MG_Backend/BackendObject.h>
|
||||
#include <MG_Pipe/MGPipe.h>
|
||||
|
||||
#include "../Transport/Ring.h"
|
||||
@@ -69,34 +70,176 @@ namespace MobileGL::MG_Remote::Server {
|
||||
Uint32 m_slotBytes = 0;
|
||||
};
|
||||
|
||||
// ---- MGPClear's two discriminants ---------------------------------------------------
|
||||
//
|
||||
// P5b MOVED THEM INTO MGPipeTypes.h (kMGPipeClearKind* / kMGPipeClearValueClass*), which is
|
||||
// where this file said they belonged: through P5 the numbers lived here and in the client's
|
||||
// EmitTables.h as two hand-minted copies, and a disagreement between them is a clear of the
|
||||
// wrong attachment with the wrong value type, which renders plausibly. These are ALIASES so
|
||||
// v1's bodies read unchanged; new code names the MG_Pipe constants directly.
|
||||
inline constexpr Uint32 kMGPClearKindWhole = MG_Pipe::kMGPipeClearKindWhole;
|
||||
inline constexpr Uint32 kMGPClearKindColor = MG_Pipe::kMGPipeClearKindColor;
|
||||
inline constexpr Uint32 kMGPClearKindDepth = MG_Pipe::kMGPipeClearKindDepth;
|
||||
inline constexpr Uint32 kMGPClearKindStencil = MG_Pipe::kMGPipeClearKindStencil;
|
||||
inline constexpr Uint32 kMGPClearKindDepthStencil = MG_Pipe::kMGPipeClearKindDepthStencil;
|
||||
inline constexpr Uint32 kMGPClearValueClassFloat = MG_Pipe::kMGPipeClearValueClassFloat;
|
||||
inline constexpr Uint32 kMGPClearValueClassInt = MG_Pipe::kMGPipeClearValueClassInt;
|
||||
inline constexpr Uint32 kMGPClearValueClassUint = MG_Pipe::kMGPipeClearValueClassUint;
|
||||
|
||||
// ---- the five class-B verbs' consumer ------------------------------------------------
|
||||
//
|
||||
// Contract §7 class B is Clear (57), Blit (56), ReadPixels (58), DrawVbo (59) and Present
|
||||
// (67), and NONE of them has an MGPipeApply* entry point - the 37 that exist are the object
|
||||
// and state families. So w1's decoder validates and hands over a checked argument list and
|
||||
// stops, and this is the other half: the SERVER'S OWN BACKEND CALL, through the private
|
||||
// GlobalBackendFunctionsTable ServerLoop holds. It is not gBackendFunctionsTable, which in
|
||||
// a split process is the client's emit table (table 3) - calling THAT here would re-emit
|
||||
// the record the server is in the middle of applying, which is an infinite loop that
|
||||
// renders nothing and looks like a hang.
|
||||
class ServerVerbSink final : public Wire::WireVerbSink {
|
||||
public:
|
||||
// The server's private backend. Null until ServerLoop::CreateBackend has run, and a
|
||||
// verb that arrives before then declines by name rather than dereferencing.
|
||||
void SetBackend(MG_Backend::BackendObject* backend);
|
||||
|
||||
Bool OnClear(const MG_Pipe::MGPClear& clear) override;
|
||||
Bool OnBlit(const MG_Pipe::MGPBlit& blit) override;
|
||||
Bool OnPresent(const MG_Pipe::MGPPresent& present) override;
|
||||
Bool OnReadPixels(const MG_Pipe::MGPReadbackInfo& info, Uint64 seq,
|
||||
Wire::ReplySink* replies) override;
|
||||
Bool OnDrawVbo(const MG_Pipe::MGPDrawInfo& info, const MG_Pipe::MGPDrawRange* ranges,
|
||||
const MG_Pipe::MGHostSpan* userIndices,
|
||||
const MG_Pipe::MGPDrawIndirect* indirect) override;
|
||||
|
||||
// ---- P5b (MG_Remote/CONTRACT-P5B.md): one override per row a migration package owns.
|
||||
// At the contract commit EVERY BODY BELOW IS A STUB that dies
|
||||
// Fatal{UnmigratedVerb, "<GL slot>"} by the slot's own name - the same line the client's
|
||||
// class-C table raises and the census greps - so a client flipped ahead of its server
|
||||
// half aborts by name rather than rendering nothing, and the census on this head is
|
||||
// unchanged (the client refuses first). The owning package replaces the body.
|
||||
//
|
||||
// i1 OnLaunchGrid ("DispatchCompute"), OnMemoryBarrier, OnResourceCopyRegion
|
||||
// ("CopyImageSubData"), OnBindShaderImage ("BindImageTexture"),
|
||||
// OnSetStorageBlockBinding ("ShaderStorageBlockBinding")
|
||||
// t2 OnBeginStreamOutput / OnEndStreamOutput / OnPauseStreamOutput /
|
||||
// OnResumeStreamOutput ("*TransformFeedback"), OnBindStreamOutput
|
||||
// ("BindTransformFeedback"), OnPatchParameter ("PatchParameteri")
|
||||
// f1 OnGenerateMipmap, OnCopyFramebufferToTexture ("CopyTexImage2D" /
|
||||
// "CopyTexSubImage2D"), and OnClear's four non-Whole kinds (live already)
|
||||
// d1 OnDrawVbo above: the indirect tail, the user-index span, NumDraws > 1 and the
|
||||
// instanced arms (declined by name today)
|
||||
Bool OnLaunchGrid(const MG_Pipe::MGPGridInfo& grid) override;
|
||||
Bool OnMemoryBarrier(const MG_Pipe::MGPMemoryBarrier& barrier) override;
|
||||
Bool OnResourceCopyRegion(const MG_Pipe::MGPCopyRegion& copy) override;
|
||||
Bool OnBindShaderImage(const MG_Pipe::MGPImageBind& bind) override;
|
||||
Bool OnSetStorageBlockBinding(const MG_Pipe::MGPStorageBlockBinding& binding,
|
||||
const char* name) override;
|
||||
Bool OnBeginStreamOutput(const MG_Pipe::MGPStreamOutputBegin& begin) override;
|
||||
Bool OnEndStreamOutput(const MG_Pipe::MGPXfbAccounting& accounting) override;
|
||||
Bool OnPauseStreamOutput(const MG_Pipe::MGPStreamOutputControl& control) override;
|
||||
Bool OnResumeStreamOutput(const MG_Pipe::MGPStreamOutputControl& control) override;
|
||||
Bool OnBindStreamOutput(const MG_Pipe::MGPStreamOutputBind& bind) override;
|
||||
Bool OnPatchParameter(const MG_Pipe::MGPPatchParameter& patch) override;
|
||||
Bool OnGenerateMipmap(const MG_Pipe::MGPMipPlan& plan) override;
|
||||
Bool OnCopyFramebufferToTexture(const MG_Pipe::MGPCopyFromFramebuffer& copy) override;
|
||||
|
||||
// Per-verb tallies. The lane asserts these moved, because "the scenario passed" on a
|
||||
// split build is also what a scenario that ran entirely on the monolith path looks
|
||||
// like (R-16: a probe may not arm against a stub).
|
||||
Uint64 Clears() const { return m_clears; }
|
||||
Uint64 Draws() const { return m_draws; }
|
||||
Uint64 Readbacks() const { return m_readbacks; }
|
||||
Uint64 Blits() const { return m_blits; }
|
||||
Uint64 Presents() const { return m_presents; }
|
||||
Uint64 LastPresentSerial() const { return m_lastPresentSerial; }
|
||||
Uint64 ReadbackBytes() const { return m_readbackBytes; }
|
||||
// ID-49's tight-size control reads this: the scratch a read_pixels grew to. It must equal
|
||||
// the tight w*h*bpp extent of the read, never the client's DstSize - a scratch sized from
|
||||
// DstSize is exactly the heap overflow codex 1 found, one field over.
|
||||
Uint64 ReadbackScratchBytes() const { return static_cast<Uint64>(m_readbackScratch.size()); }
|
||||
|
||||
private:
|
||||
const MG_Backend::GlobalBackendFunctionsTable* Table(const char* verb) const;
|
||||
|
||||
MG_Backend::BackendObject* m_backend = nullptr;
|
||||
Uint64 m_clears = 0;
|
||||
Uint64 m_draws = 0;
|
||||
Uint64 m_readbacks = 0;
|
||||
Uint64 m_blits = 0;
|
||||
Uint64 m_presents = 0;
|
||||
Uint64 m_lastPresentSerial = 0;
|
||||
Uint64 m_readbackBytes = 0;
|
||||
// ReadPixels' destination. The pixels go into the reply slot, but GLFunctionsTable::
|
||||
// ReadPixels writes into a caller buffer, so one staging vector per session sits
|
||||
// between them. Grown, never shrunk, and never handed out past the call.
|
||||
Vector<Uint8> m_readbackScratch;
|
||||
};
|
||||
|
||||
class PipeApplier {
|
||||
public:
|
||||
PipeApplier() = default;
|
||||
PipeApplier(Wire::SegmentTable* segments, ReplyPool* replies);
|
||||
|
||||
// Decode one record, stamp the verb, apply, post the reply if the call has one, then
|
||||
// advance appliedSeq by exactly one. P5 FORBIDS BATCHING appliedSeq (R-9): the barrier's
|
||||
// waiter reads it, and a batched watermark promises work that has not run.
|
||||
// Builds the decoder over the session's control page and points it at this applier's
|
||||
// verb sink. Separate from the constructor because ServerSession::Accept constructs the
|
||||
// applier before it has decided anything about the apply thread, and the decoder needs
|
||||
// the RingControl the constructor was never given.
|
||||
//
|
||||
// CALLED ON THE APPLY THREAD, ONCE, BEFORE THE FIRST RECORD. PipeWireDecoder is "not
|
||||
// thread safe: one decoder on the apply thread, by construction", and its constructor
|
||||
// installs the process-wide apply hook.
|
||||
void Attach(Transport::RingControl* control, MG_Backend::BackendObject* backend);
|
||||
void Detach();
|
||||
Bool Attached() const;
|
||||
|
||||
// Decode one record, stamp the verb, apply, post the reply if the call has one. THE
|
||||
// CALLER advances appliedSeq by exactly one, through s1's SessionConsumer::ApplyOne,
|
||||
// which is that watermark's single writer; P5 FORBIDS BATCHING it (R-9), because the
|
||||
// barrier's waiter reads it and a batched watermark promises work that has not run.
|
||||
Bool ApplyOne(const Transport::RingRecordView& record);
|
||||
|
||||
// p1's rule, v1's call site. Called at the verb boundary, before the record's applier
|
||||
// runs, with the verb the record belongs to.
|
||||
void StampVerbBoundary(MG_Pipe::MGPWireOp op);
|
||||
|
||||
// MANDATORY on leaving the applier (p1's M-5, PipeInputs.h's ServerStampedVerb block).
|
||||
// The client's MGPipeValidateForVerb / MGPipeLeaveVerb also clear it, which is enough
|
||||
// for inproc and NOT enough for a spawned server, where MG_Impl is not in the process:
|
||||
// there the flag would latch TRUE for the server's life, every later read anywhere
|
||||
// would be judged against the last verb's mask, and the sticky forwards would start
|
||||
// aborting under strict on exactly the case their exemption exists for.
|
||||
void LeaveApplier();
|
||||
|
||||
// R-7.2's counter, read by the gate. A BARRIER-PULLED field read on the server side
|
||||
// increments PipeStats::CallClass::ResidualPulls (short name `rsp`); its value at the
|
||||
// end of P5 IS the size of the P6/P7/P8 debt and goes into MEASUREMENTS.
|
||||
//
|
||||
// IT FORWARDS TO MGPipeResidualPullCount() AND KEEPS NO MEMBER OF ITS OWN. The member
|
||||
// c0's signature block declared is deleted rather than wired: the counter is
|
||||
// process-wide in PipeInputs.cpp because the reads that increment it happen inside the
|
||||
// BACKEND, arbitrarily deep under an MGPipeApply* call, with no PipeApplier in scope.
|
||||
// A second copy here could only ever be a number that disagreed with the one the exit
|
||||
// gate reads (p1-v1 5).
|
||||
Uint64 ResidualPullCount() const;
|
||||
|
||||
// R-11's audit: after a record retires, fill the SEG_STAGE bytes it referenced with
|
||||
// 0xDD. Only under MOBILEGL_IPC_AUDIT=1, because it costs a write of every staged byte.
|
||||
void PoisonRetiredStageBytes(Uint64 offset, Uint64 size);
|
||||
|
||||
// How many staged bytes the decoder has poisoned, and how many records it has applied -
|
||||
// the two numbers the audit lane asserts are non-zero, since an instrumentation that
|
||||
// cannot be observed to have run is decoration.
|
||||
Uint64 PoisonedStageBytes() const;
|
||||
Uint64 DecoderAppliedSeq() const;
|
||||
ServerVerbSink& Verbs() { return m_verbs; }
|
||||
const ServerVerbSink& Verbs() const { return m_verbs; }
|
||||
|
||||
private:
|
||||
Wire::SegmentTable* m_segments = nullptr;
|
||||
ReplyPool* m_replies = nullptr;
|
||||
Wire::PipeWireDecoder m_decoder;
|
||||
Uint64 m_residualPulls = 0;
|
||||
ServerVerbSink m_verbs;
|
||||
Bool m_attached = false;
|
||||
};
|
||||
|
||||
} // namespace MobileGL::MG_Remote::Server
|
||||
|
||||
@@ -6,36 +6,653 @@
|
||||
// SPDX-License-Identifier: LGPL-3.0-only
|
||||
// End of Source File Header
|
||||
|
||||
// P5 c0 stubs for package v1 - the phase's highest-risk package.
|
||||
// P5 package v1: the apply thread, its affinity, its parking, and the EGL ownership move.
|
||||
|
||||
#include "ServerLoop.h"
|
||||
|
||||
#include <Config.h>
|
||||
#include <MG_Backend/BackendObjects.h>
|
||||
#include <MG_Util/Debug/Log.h>
|
||||
|
||||
#include <chrono>
|
||||
#include <cstdlib>
|
||||
#include <cstdio>
|
||||
|
||||
#if defined(__linux__) || defined(__ANDROID__)
|
||||
#include <pthread.h>
|
||||
#include <sched.h>
|
||||
#endif
|
||||
|
||||
namespace MobileGL::MG_Remote::Server {
|
||||
|
||||
#define MGP5_C0_STUB(what) \
|
||||
do { \
|
||||
MGLOG_F("MGPipe: Fatal{UnimplementedServerLoop, \"%s\"} - P5 package v1 has not landed " \
|
||||
"this yet; c0 shipped the signature only", \
|
||||
what); \
|
||||
std::abort(); \
|
||||
} while (0)
|
||||
namespace {
|
||||
|
||||
MobileGLResult ServerLoop::Start(ServerSession&) { MGP5_C0_STUB("ServerLoop::Start"); }
|
||||
// The bounded join. InProcessTransportTest.cpp:344 uses five seconds for the same
|
||||
// reason: a lost wakeup must be a RED TEST and not a hung CI job.
|
||||
constexpr Uint32 kJoinTimeoutMs = 5000;
|
||||
|
||||
void ServerLoop::Stop() { MGP5_C0_STUB("ServerLoop::Stop"); }
|
||||
// A core counts as "big" if its cpufreq ceiling is within 15% of the fastest core's -
|
||||
// the identical rule and the identical constant as ShaderCompilePool.cpp:28 and :73-95.
|
||||
// The probe is re-derived here rather than exported from there because the two want
|
||||
// DIFFERENT ANSWERS from the same data: the pool wants a COUNT (how many workers), and
|
||||
// an affinity wants a MASK (which cpus). DetectBigCoreCount() cannot answer the second,
|
||||
// so exporting it would have meant either a second function in another package's file
|
||||
// or a mask reconstructed from a count, which is wrong on any asymmetric topology whose
|
||||
// big cores are not cpu0..cpuN-1.
|
||||
constexpr Uint64 kBigCoreFrequencyPercent = 85;
|
||||
|
||||
// Not a stub: teardown asks this to decide whether to Kill and join at all, and a teardown
|
||||
// helper that aborts when the thread was never started is a hang in the shutdown path.
|
||||
Bool ServerLoop::Running() const { return m_running; }
|
||||
Uint64 ReadCpuMaxFrequencyKHz(const Uint cpu) {
|
||||
char path[128];
|
||||
std::snprintf(path, sizeof(path),
|
||||
"/sys/devices/system/cpu/cpu%u/cpufreq/cpuinfo_max_freq", cpu);
|
||||
std::FILE* file = std::fopen(path, "r");
|
||||
if (file == nullptr) return 0;
|
||||
unsigned long long value = 0;
|
||||
const int scanned = std::fscanf(file, "%llu", &value);
|
||||
std::fclose(file);
|
||||
return scanned == 1 ? static_cast<Uint64>(value) : 0;
|
||||
}
|
||||
|
||||
MG_Backend::BackendObject* ServerLoop::Backend() { MGP5_C0_STUB("ServerLoop::Backend"); }
|
||||
// The set of cpus whose ceiling is within 15% of the peak, as a bit per cpu. Zero when
|
||||
// the topology cannot be read - Windows, macOS, a container that hides the cpufreq
|
||||
// tree, or a partially readable one - because with no asymmetry information the honest
|
||||
// answer is "do not pin", not "pin to a guess".
|
||||
Uint64 DetectBigCoreMask() {
|
||||
const Uint cpuCount = std::min(64u, std::max(1u, std::thread::hardware_concurrency()));
|
||||
Uint64 frequencies[64] = {};
|
||||
for (Uint cpu = 0; cpu < cpuCount; ++cpu) {
|
||||
frequencies[cpu] = ReadCpuMaxFrequencyKHz(cpu);
|
||||
if (frequencies[cpu] == 0) return 0;
|
||||
}
|
||||
Uint64 peak = 0;
|
||||
for (Uint cpu = 0; cpu < cpuCount; ++cpu) peak = std::max(peak, frequencies[cpu]);
|
||||
if (peak == 0) return 0;
|
||||
const Uint64 threshold = peak * kBigCoreFrequencyPercent / 100;
|
||||
Uint64 mask = 0;
|
||||
for (Uint cpu = 0; cpu < cpuCount; ++cpu) {
|
||||
if (frequencies[cpu] >= threshold) mask |= (1ull << cpu);
|
||||
}
|
||||
return mask;
|
||||
}
|
||||
|
||||
MobileGLResult ServerLoop::RunOnApplyThread(ControlWork, void*) {
|
||||
MGP5_C0_STUB("ServerLoop::RunOnApplyThread");
|
||||
// MOBILEGL_IPC_SERVER_AFFINITY = `auto` | `off` | an explicit mask (0x... or decimal).
|
||||
// The RAW STRING is what Config keeps, because the resolved mask is what gets logged -
|
||||
// "an affinity that silently did nothing looks exactly like one that worked"
|
||||
// (CONTRACT-P5 5).
|
||||
Uint64 RequestedAffinityMask(const char* raw, Bool* outRecognised) {
|
||||
*outRecognised = true;
|
||||
if (raw == nullptr || raw[0] == '\0') return DetectBigCoreMask();
|
||||
if (std::strcmp(raw, "auto") == 0) return DetectBigCoreMask();
|
||||
if (std::strcmp(raw, "off") == 0) return 0;
|
||||
char* end = nullptr;
|
||||
const unsigned long long parsed = std::strtoull(raw, &end, 0);
|
||||
if (end == raw || (end != nullptr && *end != '\0')) {
|
||||
*outRecognised = false;
|
||||
return 0;
|
||||
}
|
||||
return static_cast<Uint64>(parsed);
|
||||
}
|
||||
|
||||
void NameThisThread(const char* name) {
|
||||
#if defined(__linux__) || defined(__ANDROID__)
|
||||
pthread_setname_np(pthread_self(), name);
|
||||
#else
|
||||
(void)name;
|
||||
#endif
|
||||
}
|
||||
|
||||
// Returns the mask that the kernel ACTUALLY applied - the EFFECTIVE mask read back with
|
||||
// sched_getaffinity, not the requested one (codex 11). A cpuset that permits only a subset
|
||||
// of the requested cpus is accepted by sched_setaffinity with the intersection, and
|
||||
// logging the request would then claim cpus the thread never ran on - which is precisely
|
||||
// the "an affinity that silently did nothing looks like one that worked" failure the
|
||||
// resolved mask exists to make visible. 0 when nothing was applied.
|
||||
Uint64 ApplyAffinity(Uint64 requested) {
|
||||
if (requested == 0) return 0;
|
||||
#if defined(__linux__) || defined(__ANDROID__)
|
||||
cpu_set_t set;
|
||||
CPU_ZERO(&set);
|
||||
Uint applied = 0;
|
||||
for (Uint cpu = 0; cpu < 64; ++cpu) {
|
||||
if ((requested & (1ull << cpu)) != 0) {
|
||||
CPU_SET(cpu, &set);
|
||||
++applied;
|
||||
}
|
||||
}
|
||||
if (applied == 0) return 0;
|
||||
if (sched_setaffinity(0, sizeof(set), &set) != 0) return 0;
|
||||
// Read back the mask the kernel really honoured. This is the codex-11 fix: the log
|
||||
// and ResolvedAffinityMask() report the EFFECTIVE set, so a request the cpuset trimmed
|
||||
// is visible as a smaller resolved mask rather than as a lie that matched the request.
|
||||
cpu_set_t effective;
|
||||
CPU_ZERO(&effective);
|
||||
if (sched_getaffinity(0, sizeof(effective), &effective) != 0) {
|
||||
return requested; // best effort: the set succeeded, the read did not
|
||||
}
|
||||
Uint64 mask = 0;
|
||||
for (Uint cpu = 0; cpu < 64; ++cpu) {
|
||||
if (CPU_ISSET(cpu, &effective)) mask |= (1ull << cpu);
|
||||
}
|
||||
return mask;
|
||||
#else
|
||||
return 0;
|
||||
#endif
|
||||
}
|
||||
|
||||
Uint32 SpinUsFromConfig() {
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
return MG_Config::Ipc.SpinUs;
|
||||
#else
|
||||
return Transport::kDefaultSpinUs;
|
||||
#endif
|
||||
}
|
||||
|
||||
const char* AffinityStringFromConfig() {
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
return MG_Config::Ipc.ServerAffinity.c_str();
|
||||
#else
|
||||
return "off";
|
||||
#endif
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
// ---------------------------------------------------------------------------------
|
||||
// The private backend object
|
||||
// ---------------------------------------------------------------------------------
|
||||
|
||||
MobileGLResult ServerLoop::CreateBackend(BackendType type) {
|
||||
if (m_backend != nullptr) {
|
||||
return MOBILEGL_ERR_INVALID_ARGUMENT;
|
||||
}
|
||||
switch (type) {
|
||||
case BackendType::DirectGLES:
|
||||
m_backend = MakeUnique<MG_Backend::DirectGLES::BackendObject_DirectGLES>();
|
||||
break;
|
||||
case BackendType::DirectVulkan:
|
||||
m_backend = MakeUnique<MG_Backend::DirectVulkan::BackendObject_DirectVulkan>();
|
||||
break;
|
||||
default:
|
||||
// NOT a fallback to DirectGLES. An unknown backend under split has to be refused by
|
||||
// name: the alternative is a lane that says "split, DirectVulkan" and renders with
|
||||
// the other backend.
|
||||
MGLOG_E("MG_Remote server: MG_Config::ActiveBackendType is Unknown; the server role "
|
||||
"has no backend to own a context with and the session is refused");
|
||||
return MOBILEGL_ERR_UNSUPPORTED;
|
||||
}
|
||||
// Loads the driver entry points and registers the resource op table
|
||||
// (BackendObject_DirectGLES.cpp:844-851). NO GL CALL AND NO EGL CALL HAPPENS HERE - the
|
||||
// native context is created and made current later, on the apply thread, when the
|
||||
// client's eglMakeCurrent crosses as a blocking control request.
|
||||
m_backend->Initialize();
|
||||
return MOBILEGL_OK;
|
||||
}
|
||||
|
||||
MG_Backend::BackendObject* ServerLoop::Backend() { return m_backend.get(); }
|
||||
|
||||
// ---------------------------------------------------------------------------------
|
||||
// Start / the loop / Stop
|
||||
// ---------------------------------------------------------------------------------
|
||||
|
||||
MobileGLResult ServerLoop::Start(ServerSession& session) {
|
||||
if (m_running.load(std::memory_order_acquire)) {
|
||||
return MOBILEGL_ERR_INVALID_ARGUMENT;
|
||||
}
|
||||
if (!session.Accepted()) {
|
||||
MGLOG_E("MG_Remote server: ServerLoop::Start before ServerSession::Accept - there "
|
||||
"are no rings to park on");
|
||||
return MOBILEGL_ERR_NOT_INITIALIZED;
|
||||
}
|
||||
m_session = &session;
|
||||
m_stopRequested.store(false, std::memory_order_release);
|
||||
// m-3: reset THIS session's own diagnostics. DrainedRecords()/ParkCount() are absolute and
|
||||
// a case asserts == N, so a process that opens a SECOND session (context loss, or
|
||||
// Initialize after Destroy) must start them at zero rather than carry the first session's
|
||||
// tally - and a developer running the binary directly gets the count CI sees.
|
||||
m_drained.store(0, std::memory_order_release);
|
||||
m_parks.store(0, std::memory_order_release);
|
||||
m_nativeBinds.store(0, std::memory_order_release);
|
||||
m_clientReleases.store(0, std::memory_order_release);
|
||||
m_makeCurrentRepublishes.store(0, std::memory_order_release);
|
||||
m_haveCurrentTuple = false;
|
||||
{
|
||||
const std::lock_guard<std::mutex> lock(m_exitMutex);
|
||||
m_exited = false;
|
||||
}
|
||||
m_running.store(true, std::memory_order_release);
|
||||
m_thread = std::thread([this] { ApplyThreadMain(); });
|
||||
return MOBILEGL_OK;
|
||||
}
|
||||
|
||||
Bool ServerLoop::Running() const { return m_running.load(std::memory_order_acquire); }
|
||||
|
||||
Bool ServerLoop::OnApplyThread() {
|
||||
ServerLoop& loop = ServerLoopInstance();
|
||||
return loop.m_running.load(std::memory_order_acquire) &&
|
||||
loop.m_applyThreadId.load(std::memory_order_acquire) == std::this_thread::get_id();
|
||||
}
|
||||
|
||||
Uint64 ServerLoop::ResolvedAffinityMask() const { return m_affinityMask; }
|
||||
Uint64 ServerLoop::DrainedRecords() const { return m_drained.load(std::memory_order_acquire); }
|
||||
Uint64 ServerLoop::ParkCount() const { return m_parks.load(std::memory_order_acquire); }
|
||||
Uint64 ServerLoop::NativeBindCount() const { return m_nativeBinds.load(std::memory_order_acquire); }
|
||||
Uint64 ServerLoop::ClientReleaseCount() const {
|
||||
return m_clientReleases.load(std::memory_order_acquire);
|
||||
}
|
||||
Uint64 ServerLoop::MakeCurrentRepublishCount() const {
|
||||
return m_makeCurrentRepublishes.load(std::memory_order_acquire);
|
||||
}
|
||||
void ServerLoop::NoteMakeCurrentRepublished() {
|
||||
m_makeCurrentRepublishes.fetch_add(1, std::memory_order_acq_rel);
|
||||
}
|
||||
|
||||
// C7 / ID-54. A release-current request (the three NO_* markers, exactly IsReleaseCurrentRequest's
|
||||
// test in BackendObject_DirectGLES.cpp) is a ClientRelease the server records but does not
|
||||
// forward. Otherwise an identical (dpy, draw, read, ctx) already held is a RepeatNoOp, and
|
||||
// anything else is a real NativeBind. Pure: a unit case drives it with no EGL context.
|
||||
EglBindAction ClassifyEglMakeCurrent(Bool haveCurrent, EGLDisplay curDpy, EGLSurface curDraw,
|
||||
EGLSurface curRead, EGLContext curCtx, EGLDisplay dpy,
|
||||
EGLSurface draw, EGLSurface read, EGLContext ctx) {
|
||||
if (draw == EGL_NO_SURFACE && read == EGL_NO_SURFACE && ctx == EGL_NO_CONTEXT) {
|
||||
return EglBindAction::ClientRelease;
|
||||
}
|
||||
if (haveCurrent && curDpy == dpy && curDraw == draw && curRead == read && curCtx == ctx) {
|
||||
return EglBindAction::RepeatNoOp;
|
||||
}
|
||||
return EglBindAction::NativeBind;
|
||||
}
|
||||
|
||||
ServerLoop::MakeCurrentOutcome ServerLoop::ApplyMakeCurrent(MG_Backend::BackendObject* backend,
|
||||
EGLDisplay dpy, EGLSurface draw,
|
||||
EGLSurface read, EGLContext ctx) {
|
||||
// Apply thread only (RunOnApplyThread put us here), so m_haveCurrentTuple/m_cur* need no
|
||||
// lock. The counters are atomic for the reader on the test thread.
|
||||
MakeCurrentOutcome outcome;
|
||||
const EglBindAction action = ClassifyEglMakeCurrent(m_haveCurrentTuple, m_curDpy, m_curDraw,
|
||||
m_curRead, m_curCtx, dpy, draw, read, ctx);
|
||||
switch (action) {
|
||||
case EglBindAction::ClientRelease:
|
||||
// Recorded, NOT forwarded (ID-54): the context stays current on this thread until
|
||||
// ~BackendObject_DirectGLES or context loss. Forwarding backend->MakeEGLCurrent here
|
||||
// would route to DirectGLES::ReleaseCurrent, unbind, and clear
|
||||
// g_backendContextOwnerThread - reinstating the off-thread degradation the phase
|
||||
// removes. m_haveCurrentTuple is left intact so a later identical bind is still a
|
||||
// RepeatNoOp (the driver never lost the context).
|
||||
m_clientReleases.fetch_add(1, std::memory_order_acq_rel);
|
||||
outcome.ok = true;
|
||||
outcome.boundNatively = false;
|
||||
return outcome;
|
||||
case EglBindAction::RepeatNoOp:
|
||||
// ID-54's "a no-op apart from the R-12 republish decision": the decision for an
|
||||
// identical repeat is NO republish, because nothing ran that could have moved the
|
||||
// caps - InitCapabilities runs inside the backend's MakeEGLCurrent, which this arm
|
||||
// does not reach, so a republish here would re-send the snapshot the last real bind
|
||||
// already sent. (c1's BackendObject_Remote::InitCapabilities does not lean on this
|
||||
// either way: it asks the server through ServerInitCapabilities, which publishes.)
|
||||
outcome.ok = true;
|
||||
outcome.boundNatively = false;
|
||||
return outcome;
|
||||
case EglBindAction::NativeBind:
|
||||
break;
|
||||
}
|
||||
// "Forwarded" is the honest word: the backend object decides for itself whether the
|
||||
// driver needs a native eglMakeCurrent (BackendObject_DirectGLES skips it for a surface
|
||||
// that is already current on this thread - its own creation bound it), and the C7
|
||||
// control counts THAT at the EGL function table. This counter counts forwards.
|
||||
outcome.ok = backend->MakeEGLCurrent(dpy, draw, read, ctx);
|
||||
if (!outcome.ok) return outcome;
|
||||
m_haveCurrentTuple = true;
|
||||
m_curDpy = dpy;
|
||||
m_curDraw = draw;
|
||||
m_curRead = read;
|
||||
m_curCtx = ctx;
|
||||
m_nativeBinds.fetch_add(1, std::memory_order_acq_rel);
|
||||
outcome.boundNatively = true;
|
||||
return outcome;
|
||||
}
|
||||
|
||||
void ServerLoop::ForgetCurrentTuple() {
|
||||
m_haveCurrentTuple = false;
|
||||
m_curDpy = EGL_NO_DISPLAY;
|
||||
m_curDraw = EGL_NO_SURFACE;
|
||||
m_curRead = EGL_NO_SURFACE;
|
||||
m_curCtx = EGL_NO_CONTEXT;
|
||||
}
|
||||
|
||||
void ServerLoop::ForgetCurrentTupleIfItNames(EGLSurface surface) {
|
||||
if (!m_haveCurrentTuple) return;
|
||||
if (m_curDraw == surface || m_curRead == surface) ForgetCurrentTuple();
|
||||
}
|
||||
|
||||
void ServerLoop::ApplyThreadMain() {
|
||||
m_applyThreadId.store(std::this_thread::get_id(), std::memory_order_release);
|
||||
NameThisThread("mgl-srv-apply");
|
||||
|
||||
Bool recognised = true;
|
||||
const char* raw = AffinityStringFromConfig();
|
||||
const Uint64 requested = RequestedAffinityMask(raw, &recognised);
|
||||
m_affinityMask = ApplyAffinity(requested);
|
||||
if (!recognised) {
|
||||
MGLOG_E("MG_Remote server: MOBILEGL_IPC_SERVER_AFFINITY='%s' is not `auto`, `off` or "
|
||||
"a number; NO affinity was applied. This is logged rather than defaulted "
|
||||
"because an affinity that silently did nothing is indistinguishable from "
|
||||
"one that worked",
|
||||
raw == nullptr ? "" : raw);
|
||||
}
|
||||
// THE RESOLVED MASK, ALWAYS, INCLUDING 0. Contract 5's whole point: the string is what
|
||||
// an operator typed and the mask is what the kernel took.
|
||||
MGLOG_I("MG_Remote server: mgl-srv-apply started. MOBILEGL_IPC_SERVER_AFFINITY='%s' "
|
||||
"requested mask 0x%llx, RESOLVED mask 0x%llx (0 = no affinity applied), spin "
|
||||
"%u us",
|
||||
raw == nullptr ? "" : raw, static_cast<unsigned long long>(requested),
|
||||
static_cast<unsigned long long>(m_affinityMask), SpinUsFromConfig());
|
||||
|
||||
ServerSession& session = *m_session;
|
||||
// The decoder is built HERE, on this thread, because PipeWireDecoder is "not thread
|
||||
// safe: one decoder on the apply thread, by construction" and its constructor installs
|
||||
// the process-wide apply hook.
|
||||
session.Applier().Attach(&session.Control(), m_backend.get());
|
||||
|
||||
Transport::RingControl& control = session.Control();
|
||||
Transport::Doorbell& bell = session.ConsumerDoorbell();
|
||||
Transport::RingConsumer& ring = session.CommandRing();
|
||||
const Uint32 spinUs = SpinUsFromConfig();
|
||||
|
||||
// THE PARK CONDITION IS THREE THINGS, NOT ONE, AND THAT IS THE WHOLE REASON THIS LOOP
|
||||
// DOES NOT CALL SessionConsumer::WaitForWork.
|
||||
//
|
||||
// WaitForWork's predicate is "a record is waiting" and nothing else. Park a thread on
|
||||
// kWaitForever with that predicate and neither a control request nor a Stop() can get
|
||||
// it out: Doorbell::Wait consumes the Notify with one Park, re-tests a condition
|
||||
// nothing published, finds the bell alive, and parks again - forever. Only
|
||||
// CondVarDoorbell::Kill() breaks that, and Kill is the CLIENT's teardown call, not
|
||||
// something an EGL make-current request may perform. So the predicate carries all
|
||||
// three arming conditions and the doorbell wakes the thread for any of them.
|
||||
const auto ready = [this, &control, &ring] {
|
||||
return control.cmdHead.load(std::memory_order_acquire) != ring.LocalTail() ||
|
||||
m_stopRequested.load(std::memory_order_acquire) || ControlIsPending();
|
||||
};
|
||||
|
||||
for (;;) {
|
||||
PumpControlRequest();
|
||||
if (m_stopRequested.load(std::memory_order_acquire)) break;
|
||||
DrainRing();
|
||||
if (m_stopRequested.load(std::memory_order_acquire)) break;
|
||||
if (ready()) continue;
|
||||
|
||||
m_parks.fetch_add(1, std::memory_order_acq_rel);
|
||||
const bool woke = bell.Wait(control.consumerParked, ready, spinUs, Transport::kWaitForever);
|
||||
if (!woke) {
|
||||
// Wait returns false only on a dead bell or an expired deadline, and this park
|
||||
// has no deadline. A dead bell IS the shutdown signal (table 3's teardown step
|
||||
// 2); treating it as anything else would spin at full clock for ever, since
|
||||
// parking on a dead bell no longer blocks.
|
||||
if (bell.Dead()) {
|
||||
MGLOG_D("MG_Remote server: the consumer doorbell is dead; mgl-srv-apply is "
|
||||
"shutting down");
|
||||
break;
|
||||
}
|
||||
MGLOG_E("MG_Remote server: Doorbell::Wait(kWaitForever) returned false on a live "
|
||||
"bell - that is impossible by Doorbell.h:139-178 and means the bell's "
|
||||
"Dead() answer moved under the waiter. Shutting the loop down rather "
|
||||
"than spinning");
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Whatever is still queued gets applied before the context goes. The client's own
|
||||
// drain (ClientSession::Stop step 1) normally empties the ring first and is BOUNDED, so
|
||||
// a timeout there leaves records here; applying them costs nothing and dropping them
|
||||
// would leave the emitter's var-tails referenced by records nobody ever read.
|
||||
PumpControlRequest();
|
||||
DrainRing();
|
||||
|
||||
// THE BACKEND IS DESTROYED ON THIS THREAD, WHILE IT IS STILL THE CONTEXT OWNER.
|
||||
// ~BackendObject_DirectGLES calls DestroyEGLContext (BackendObject_DirectGLES.cpp:
|
||||
// 833-835), which runs eglMakeCurrent(NO_SURFACE) / eglDestroyContext / eglTerminate.
|
||||
// Those must happen on the thread eglMakeCurrent was issued from; doing it on the app
|
||||
// thread - which is what pActiveBackendObject.reset() at MobileGL/Init.cpp:68 would do
|
||||
// - destroys a context this thread still holds current.
|
||||
session.Applier().Detach();
|
||||
if (m_backend != nullptr) {
|
||||
MGLOG_I("MG_Remote server: destroying the server's BackendObject on mgl-srv-apply, "
|
||||
"which is the context owner");
|
||||
m_backend.reset();
|
||||
}
|
||||
// N-3: the context died with the backend; a tuple that outlives it would make the next
|
||||
// session's first make-current onto the same (recycled) handle values a RepeatNoOp.
|
||||
ForgetCurrentTuple();
|
||||
|
||||
// C2: THE m_running CLEAR IS INSIDE THIS SAME CRITICAL SECTION AS THE FINAL DRAIN OF THE
|
||||
// MAILBOX. It used to be a separate store after the block, and that gap was a lost-forever
|
||||
// hang: a caller that read m_running == true just before this thread exited, then had this
|
||||
// thread run the block (finding nothing pending) and clear m_running OUTSIDE the lock,
|
||||
// would go on to publish a request into a mailbox no thread will ever pump and block on
|
||||
// m_controlDone with no answer possible (the bounded join has already succeeded, so there
|
||||
// is not even a Fatal{ApplyThreadJoinTimeout}). With the clear under the lock, a caller
|
||||
// either takes the lock FIRST (its request is here and answered NOT_INITIALIZED) or takes
|
||||
// it AFTER (it sees !m_running under the lock in RunOnApplyThread and returns
|
||||
// NOT_INITIALIZED without publishing). There is no third order.
|
||||
{
|
||||
const std::lock_guard<std::mutex> lock(m_controlMutex);
|
||||
if (m_controlPending) {
|
||||
m_controlPending = false;
|
||||
m_controlFinished = true;
|
||||
m_controlResult = MOBILEGL_ERR_NOT_INITIALIZED;
|
||||
MGLOG_E("MG_Remote server: a control request was still posted when mgl-srv-apply "
|
||||
"exited; it is answered NOT_INITIALIZED rather than left blocking");
|
||||
}
|
||||
m_running.store(false, std::memory_order_release);
|
||||
}
|
||||
m_controlDone.notify_all();
|
||||
|
||||
SignalExited();
|
||||
}
|
||||
|
||||
Bool ServerLoop::ControlIsPending() const {
|
||||
const std::lock_guard<std::mutex> lock(const_cast<std::mutex&>(m_controlMutex));
|
||||
return m_controlPending;
|
||||
}
|
||||
|
||||
Bool ServerLoop::PumpControlRequest() {
|
||||
ControlWork work = nullptr;
|
||||
void* user = nullptr;
|
||||
{
|
||||
const std::lock_guard<std::mutex> lock(m_controlMutex);
|
||||
if (!m_controlPending) return false;
|
||||
work = m_controlWork;
|
||||
user = m_controlUser;
|
||||
}
|
||||
const MobileGLResult result = work == nullptr ? MOBILEGL_ERR_INVALID_ARGUMENT : work(user);
|
||||
{
|
||||
const std::lock_guard<std::mutex> lock(m_controlMutex);
|
||||
m_controlResult = result;
|
||||
m_controlPending = false;
|
||||
m_controlFinished = true;
|
||||
}
|
||||
m_controlDone.notify_all();
|
||||
return true;
|
||||
}
|
||||
|
||||
Uint64 ServerLoop::DrainRing() {
|
||||
ServerSession& session = *m_session;
|
||||
Transport::SessionConsumer& consumer = session.Consumer();
|
||||
PipeApplier& applier = session.Applier();
|
||||
Uint64 applied = 0;
|
||||
for (;;) {
|
||||
bool corrupt = false;
|
||||
const bool popped = consumer.ApplyOne(
|
||||
[this, &applier](const Transport::RingRecordView& record) {
|
||||
applier.ApplyOne(record);
|
||||
// THE TALLY MOVES HERE, INSIDE THE CALLBACK, AND NOT AFTER THE BATCH. s1's
|
||||
// SessionConsumer::ApplyOne publishes appliedSeq the instant this callback
|
||||
// returns, and publishing appliedSeq is what releases the client from the
|
||||
// verb barrier (R-1). Anything this thread records about the record AFTER
|
||||
// that publish is visible to the client only eventually - and a diagnostic
|
||||
// that can lag the watermark it describes is the exact shape of the
|
||||
// LeaveApplier race PipeApplier::ApplyOne's block describes, one level up.
|
||||
// The first version of this function tallied once per batch, below, and
|
||||
// AClearRecordCrossesAndIsStampedAsAVerbBoundary /
|
||||
// TheSessionWatermarkAndTheDecoderTallyAgreeAfterEveryRecord read
|
||||
// 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);
|
||||
},
|
||||
&corrupt);
|
||||
if (corrupt) {
|
||||
// Ring.h's own rule: a header the producer could not have written is
|
||||
// Fatal{ProtocolCorruption}, never a retry. Retrying re-reads the same bytes
|
||||
// for ever; skipping desynchronises seq, and seq IS the reply-slot id.
|
||||
MGLOG_F("MGPipe: Fatal{ProtocolCorruption, \"SEG_CMD record header\"} - the "
|
||||
"consumer refused a record header at applied seq %llu",
|
||||
static_cast<unsigned long long>(consumer.AppliedSeq()));
|
||||
std::abort();
|
||||
}
|
||||
if (!popped) break;
|
||||
++applied;
|
||||
}
|
||||
if (applied != 0) {
|
||||
// THE TWO TALLIES MUST AGREE, AND THAT IS WHAT MAKES R-9's BATCHING BAN CHECKABLE.
|
||||
// RingControl::appliedSeq has one writer (SessionConsumer::ApplyOne, +1 per record)
|
||||
// and PipeWireDecoder keeps its own count; a batched publish would move one and not
|
||||
// the other, which a single counter could not have told apart (w1-v1 5).
|
||||
if (applier.DecoderAppliedSeq() != consumer.AppliedSeq()) {
|
||||
MGLOG_F("MGPipe: Fatal{ProtocolCorruption, \"appliedSeq batched\"} - the "
|
||||
"session's watermark is %llu and the decoder applied %llu records. P5 "
|
||||
"forbids batching appliedSeq (R-9): the verb barrier's waiter reads it, "
|
||||
"and a watermark ahead of the decoder promises work that has not run",
|
||||
static_cast<unsigned long long>(consumer.AppliedSeq()),
|
||||
static_cast<unsigned long long>(applier.DecoderAppliedSeq()));
|
||||
std::abort();
|
||||
}
|
||||
// RETIRE. MANDATORY, not optional: RingProducer::FreeBytes() reclaims against
|
||||
// retiredTail only, and w1's SEG_STAGE linear allocator reclaims on retiredSeq - so
|
||||
// a loop that applies and never retires ends the first MOBILEGL_IPC_STAGE_MB of
|
||||
// staging in Fatal{RingOverrun, "SEG_STAGE"} (w1-v1 5). Once per drain batch, not
|
||||
// once per record: retiring LATE is always legal, retiring EARLY never is.
|
||||
consumer.RetireThrough(consumer.AppliedSeq());
|
||||
// LEAVING THE APPLIER (p1's M-5) IS *NOT* DONE HERE. It is done inside
|
||||
// PipeApplier::ApplyOne, before s1's SessionConsumer::ApplyOne publishes appliedSeq
|
||||
// - see the block there. A clear at this point races the client, which the barrier
|
||||
// has already released by then.
|
||||
}
|
||||
return applied;
|
||||
}
|
||||
|
||||
MobileGLResult ServerLoop::RunOnApplyThread(ControlWork work, void* user) {
|
||||
if (work == nullptr) return MOBILEGL_ERR_INVALID_ARGUMENT;
|
||||
// RE-ENTRANCY IS NOT A DEADLOCK. The teardown path posts from the apply thread itself -
|
||||
// ~BackendObject_DirectGLES reaches ReleaseEGLResources - and so does anything the
|
||||
// applier calls that wants "run this where the context is". Running inline is the
|
||||
// correct answer there and the only non-hanging one.
|
||||
if (OnApplyThread()) return work(user);
|
||||
|
||||
const std::lock_guard<std::mutex> callerLock(m_callerMutex);
|
||||
std::unique_lock<std::mutex> lock(m_controlMutex);
|
||||
// C2 + M-7: the m_running check and the publish are ONE critical section, and m_running is
|
||||
// cleared under this same lock on the way out (ApplyThreadMain's exit block), so this read
|
||||
// cannot see `true` for a thread that then vanishes before the publish. When there is no
|
||||
// thread there are two sub-cases and neither is a silent EGL-on-the-app-thread fallback:
|
||||
if (!m_running.load(std::memory_order_acquire)) {
|
||||
const Bool backendAlive = m_backend != nullptr;
|
||||
lock.unlock();
|
||||
if (backendAlive) {
|
||||
// M-7: the backend exists but no thread owns it - ClientSession::Start refused
|
||||
// (ServerLoop.cpp Start's !Accepted arm) or std::thread's constructor threw.
|
||||
// Running `work` inline here would issue eglMakeCurrent on the APP thread and
|
||||
// stamp g_backendContextOwnerThread with it, so a lane called split would render
|
||||
// correctly with the context on the wrong thread - the one outcome R-1 exists to
|
||||
// make impossible. Fatal by name, never a fallback; compare CreateBackend's
|
||||
// default: arm, which also refuses rather than substitutes.
|
||||
MGLOG_F("MGPipe: Fatal{ApplyThreadNotRunning, \"EGL on the app thread\"} - a "
|
||||
"control request reached RunOnApplyThread with the server's backend built "
|
||||
"but no mgl-srv-apply thread running (ClientSession::Start failed after "
|
||||
"ServerLoop::CreateBackend). Running it inline would make the context "
|
||||
"current on the APP thread - the split lane's whole premise. Refusing by "
|
||||
"name rather than falling back to monolith");
|
||||
std::abort();
|
||||
}
|
||||
// Backend already gone (post-Stop teardown, or the pre-Init window): the forwarders'
|
||||
// ServerBackendOrNull() would answer null anyway, so NOT_INITIALIZED is the honest
|
||||
// result and running inline is pointless. This is the deterministic half of C2 - a
|
||||
// forwarder call after the loop stopped returns NOT_INITIALIZED, it does not hang and
|
||||
// it does not run on the caller.
|
||||
return MOBILEGL_ERR_NOT_INITIALIZED;
|
||||
}
|
||||
m_controlWork = work;
|
||||
m_controlUser = user;
|
||||
m_controlPending = true;
|
||||
m_controlFinished = false;
|
||||
// Publish THEN ring, in that order and never the other (Doorbell.h:186-193). The bell
|
||||
// is rung unconditionally rather than through NotifyIfParked because this side does not
|
||||
// know whether the apply thread is parked or spinning, and CondVarDoorbell remembers a
|
||||
// wakeup that arrives while nobody is waiting. Held under m_controlMutex: wait() releases
|
||||
// it atomically, so the apply thread cannot observe the request until this side is
|
||||
// waiting, and the doorbell remembers the notify regardless.
|
||||
if (m_session != nullptr) {
|
||||
m_session->ConsumerDoorbell().Notify();
|
||||
}
|
||||
m_controlDone.wait(lock, [this] { return m_controlFinished; });
|
||||
return m_controlResult;
|
||||
}
|
||||
|
||||
void ServerLoop::SignalExited() {
|
||||
{
|
||||
const std::lock_guard<std::mutex> lock(m_exitMutex);
|
||||
m_exited = true;
|
||||
}
|
||||
m_exitCv.notify_all();
|
||||
}
|
||||
|
||||
void ServerLoop::Stop() {
|
||||
if (!m_thread.joinable()) {
|
||||
// Never started, or already stopped. The backend may still exist - the hook builds
|
||||
// it before the thread - and it has to go somewhere, so it goes here, on whatever
|
||||
// thread called Stop. No context was ever made current from another thread in that
|
||||
// case, which is exactly the condition that makes this safe.
|
||||
if (m_backend != nullptr) m_backend.reset();
|
||||
// N-3, same reason as ApplyThreadMain's exit: no thread runs, so the apply-thread-only
|
||||
// rule on the tuple has no other writer to race.
|
||||
ForgetCurrentTuple();
|
||||
m_running.store(false, std::memory_order_release);
|
||||
return;
|
||||
}
|
||||
m_stopRequested.store(true, std::memory_order_release);
|
||||
if (m_session != nullptr) {
|
||||
// The bell may already be dead - ClientSession::Stop calls transport->Shutdown()
|
||||
// first, which is what table 3's step 2 requires - and Notify on a dead bell is
|
||||
// harmless. Ringing anyway covers the paths that Stop without a Kill.
|
||||
m_session->ConsumerDoorbell().Notify();
|
||||
}
|
||||
|
||||
// THE JOIN IS BOUNDED. std::thread::join has no deadline, so a lost wakeup would wedge
|
||||
// CI rather than fail it; the thread signals m_exited last and this waits with the same
|
||||
// five seconds InProcessTransportTest.cpp:344 uses.
|
||||
Bool exited = false;
|
||||
{
|
||||
std::unique_lock<std::mutex> lock(m_exitMutex);
|
||||
exited = m_exitCv.wait_for(lock, std::chrono::milliseconds(kJoinTimeoutMs),
|
||||
[this] { return m_exited; });
|
||||
}
|
||||
if (!exited) {
|
||||
// ABORT, NOT DETACH. A detached apply thread still owns the EGL context and would
|
||||
// run on into the client's teardown, reading rings the client is about to unmap -
|
||||
// a use-after-free whose only symptom is an intermittent crash somewhere else.
|
||||
// Aborting here is red, immediate, and names the cause.
|
||||
MGLOG_F("MGPipe: Fatal{ApplyThreadJoinTimeout} - mgl-srv-apply did not exit within "
|
||||
"%u ms of Stop(). Stop() published m_stopRequested (in the park predicate) "
|
||||
"BEFORE it rang, so a plain Notify should already have un-parked the thread; "
|
||||
"Doorbell::Kill() (Doorbell.h:211-221, table 3 step 2) is the belt to that "
|
||||
"Notify's braces. If the thread is still parked after both, the wakeup was "
|
||||
"lost, not slow. Aborting rather than detaching: a detached apply thread still "
|
||||
"owns the context and would read rings the client is about to unmap",
|
||||
kJoinTimeoutMs);
|
||||
std::abort();
|
||||
}
|
||||
m_thread.join();
|
||||
m_applyThreadId.store(std::thread::id{}, std::memory_order_release);
|
||||
m_running.store(false, std::memory_order_release);
|
||||
m_session = nullptr;
|
||||
}
|
||||
|
||||
ServerLoop& ServerLoopInstance() {
|
||||
@@ -44,6 +661,261 @@ namespace MobileGL::MG_Remote::Server {
|
||||
return instance;
|
||||
}
|
||||
|
||||
#undef MGP5_C0_STUB
|
||||
// ---------------------------------------------------------------------------------
|
||||
// The twelve EGL forwarders
|
||||
// ---------------------------------------------------------------------------------
|
||||
|
||||
namespace {
|
||||
|
||||
// One captureless trampoline for every call: ControlWork is a raw function pointer
|
||||
// plus a void*, not a std::function, because these run on the TEARDOWN path and the
|
||||
// teardown path may not allocate (ID-8 exists because frontend destructors reach here
|
||||
// from exit handlers).
|
||||
template <class Args>
|
||||
MobileGLResult RunOnApply(Args& args) {
|
||||
return ServerLoopInstance().RunOnApplyThread(
|
||||
+[](void* user) -> MobileGLResult { return static_cast<Args*>(user)->Run(); },
|
||||
&args);
|
||||
}
|
||||
|
||||
// Null means the hook never ran or the session is already down. Every forwarder
|
||||
// answers false / no-op rather than dereferencing: a client that calls eglMakeCurrent
|
||||
// on a process whose split bring-up failed must see a refusal, not a crash.
|
||||
MG_Backend::BackendObject* ServerBackendOrNull() { return ServerLoopInstance().Backend(); }
|
||||
|
||||
} // namespace
|
||||
|
||||
Bool ServerInitializeEGLDisplay(EGLDisplay dpy, EGLint* major, EGLint* minor) {
|
||||
struct Args {
|
||||
EGLDisplay dpy;
|
||||
EGLint* major;
|
||||
EGLint* minor;
|
||||
Bool ok = false;
|
||||
MobileGLResult Run() {
|
||||
MG_Backend::BackendObject* backend = ServerBackendOrNull();
|
||||
if (backend == nullptr) return MOBILEGL_ERR_NOT_INITIALIZED;
|
||||
ok = backend->InitializeEGLDisplay(dpy, major, minor);
|
||||
return MOBILEGL_OK;
|
||||
}
|
||||
} args{dpy, major, minor};
|
||||
return RunOnApply(args) == MOBILEGL_OK && args.ok;
|
||||
}
|
||||
|
||||
Bool ServerCreateEGLWindowSurface(EGLSurface surface, const MG_Backend::WindowHandle& handle) {
|
||||
struct Args {
|
||||
EGLSurface surface;
|
||||
const MG_Backend::WindowHandle* handle;
|
||||
Bool ok = false;
|
||||
MobileGLResult Run() {
|
||||
MG_Backend::BackendObject* backend = ServerBackendOrNull();
|
||||
if (backend == nullptr) return MOBILEGL_ERR_NOT_INITIALIZED;
|
||||
ok = backend->CreateEGLWindowSurface(surface, *handle);
|
||||
// N-3: BackendObject_DirectGLES destroys and recreates the native context to
|
||||
// create a DIFFERENT surface, so whatever tuple was bound names a dead context.
|
||||
if (ok) ServerLoopInstance().ForgetCurrentTuple();
|
||||
return MOBILEGL_OK;
|
||||
}
|
||||
} args{surface, &handle};
|
||||
return RunOnApply(args) == MOBILEGL_OK && args.ok;
|
||||
}
|
||||
|
||||
Bool ServerResizeEGLWindowSurface(EGLSurface surface, Uint32 width, Uint32 height) {
|
||||
struct Args {
|
||||
EGLSurface surface;
|
||||
Uint32 width;
|
||||
Uint32 height;
|
||||
Bool ok = false;
|
||||
MobileGLResult Run() {
|
||||
MG_Backend::BackendObject* backend = ServerBackendOrNull();
|
||||
if (backend == nullptr) return MOBILEGL_ERR_NOT_INITIALIZED;
|
||||
ok = backend->ResizeEGLWindowSurface(surface, width, height);
|
||||
return MOBILEGL_OK;
|
||||
}
|
||||
} args{surface, width, height};
|
||||
return RunOnApply(args) == MOBILEGL_OK && args.ok;
|
||||
}
|
||||
|
||||
Bool ServerCreateEGLPbufferSurface(EGLSurface surface, EGLint width, EGLint height) {
|
||||
struct Args {
|
||||
EGLSurface surface;
|
||||
EGLint width;
|
||||
EGLint height;
|
||||
Bool ok = false;
|
||||
MobileGLResult Run() {
|
||||
MG_Backend::BackendObject* backend = ServerBackendOrNull();
|
||||
if (backend == nullptr) return MOBILEGL_ERR_NOT_INITIALIZED;
|
||||
ok = backend->CreateEGLPbufferSurface(surface, width, height);
|
||||
// N-3: as for the window surface - a (re)creation may have destroyed the context
|
||||
// the held tuple named. The surface's own creation binds natively, so the client's
|
||||
// make-current that follows is forwarded and deduped one layer down (ID-54).
|
||||
if (ok) ServerLoopInstance().ForgetCurrentTuple();
|
||||
return MOBILEGL_OK;
|
||||
}
|
||||
} args{surface, width, height};
|
||||
return RunOnApply(args) == MOBILEGL_OK && args.ok;
|
||||
}
|
||||
|
||||
Bool ServerMakeEGLCurrent(EGLDisplay dpy, EGLSurface draw, EGLSurface read, EGLContext ctx) {
|
||||
struct Args {
|
||||
EGLDisplay dpy;
|
||||
EGLSurface draw;
|
||||
EGLSurface read;
|
||||
EGLContext ctx;
|
||||
Bool ok = false;
|
||||
MobileGLResult Run() {
|
||||
MG_Backend::BackendObject* backend = ServerBackendOrNull();
|
||||
if (backend == nullptr) return MOBILEGL_ERR_NOT_INITIALIZED;
|
||||
// C7 / ID-54: the apply thread binds the native context ONCE per context
|
||||
// lifetime and holds it for life. ApplyMakeCurrent forwards a bind only for a
|
||||
// tuple it does not hold, treats an identical repeat as a no-op, and records a
|
||||
// client release-current WITHOUT unbinding; the native call for a surface already
|
||||
// current on this thread is skipped one layer down (BackendObject_DirectGLES's
|
||||
// ID-54 arm), which is what makes "the owner slot is written once" TRUE and
|
||||
// measured (ServerLoopTest's C7 control) rather than claimed.
|
||||
const ServerLoop::MakeCurrentOutcome outcome =
|
||||
ServerLoopInstance().ApplyMakeCurrent(backend, dpy, draw, read, ctx);
|
||||
ok = outcome.ok;
|
||||
if (!ok || !outcome.boundNatively) return MOBILEGL_OK;
|
||||
// R-12, arm (a): the caps snapshot is REPUBLISHED because InitCapabilities has
|
||||
// now run for real - on every forwarded bind of a tuple this loop did not hold
|
||||
// (the first, and every DIFFERENT tuple after it), and NEVER on an identical
|
||||
// repeat (ID-67: a repeat is a native no-op AND publishes nothing, so the client's
|
||||
// mirror generation does not move and nothing accumulates). DirectGLES has no
|
||||
// OnCapsInvalidated producer at all, and c0's answer is that a SECOND arrival IS the
|
||||
// invalidation - so the client's mirror is refreshed with no dev-shaped backend edit
|
||||
// and with no eleventh MGPipeCallbacks slot (MGPipeCallbacks.h:56-58's static_assert
|
||||
// exists to make that cost visible). Red once by republishing only on the first
|
||||
// bind: the ID-67 control's different tuple reads 1 republish where 2 are required.
|
||||
ServerSession* session = ServerSession::Active();
|
||||
if (session != nullptr && session->Accepted()) {
|
||||
const MobileGLResult published = session->PublishCapsSnapshot();
|
||||
if (published == MOBILEGL_OK) ServerLoopInstance().NoteMakeCurrentRepublished();
|
||||
if (published != MOBILEGL_OK) {
|
||||
MGLOG_E("MG_Remote server: the post-make-current CapsSnapshot could not "
|
||||
"be published (rc=%d); the client's mirror still holds the empty "
|
||||
"snapshot Accept() sent before any context existed",
|
||||
static_cast<int>(published));
|
||||
}
|
||||
}
|
||||
return MOBILEGL_OK;
|
||||
}
|
||||
} args{dpy, draw, read, ctx};
|
||||
return RunOnApply(args) == MOBILEGL_OK && args.ok;
|
||||
}
|
||||
|
||||
Bool ServerSwapEGLBuffers(EGLDisplay dpy, EGLSurface draw) {
|
||||
struct Args {
|
||||
EGLDisplay dpy;
|
||||
EGLSurface draw;
|
||||
Bool ok = false;
|
||||
MobileGLResult Run() {
|
||||
MG_Backend::BackendObject* backend = ServerBackendOrNull();
|
||||
if (backend == nullptr) return MOBILEGL_ERR_NOT_INITIALIZED;
|
||||
ok = backend->SwapEGLBuffers(dpy, draw);
|
||||
return MOBILEGL_OK;
|
||||
}
|
||||
} args{dpy, draw};
|
||||
return RunOnApply(args) == MOBILEGL_OK && args.ok;
|
||||
}
|
||||
|
||||
void ServerSetEGLSwapInterval(Int interval) {
|
||||
struct Args {
|
||||
Int interval;
|
||||
MobileGLResult Run() {
|
||||
MG_Backend::BackendObject* backend = ServerBackendOrNull();
|
||||
if (backend == nullptr) return MOBILEGL_ERR_NOT_INITIALIZED;
|
||||
backend->SetEGLSwapInterval(interval);
|
||||
return MOBILEGL_OK;
|
||||
}
|
||||
} args{interval};
|
||||
(void)RunOnApply(args);
|
||||
}
|
||||
|
||||
void ServerReleaseEGLSurface(EGLSurface surface) {
|
||||
struct Args {
|
||||
EGLSurface surface;
|
||||
MobileGLResult Run() {
|
||||
MG_Backend::BackendObject* backend = ServerBackendOrNull();
|
||||
if (backend == nullptr) return MOBILEGL_ERR_NOT_INITIALIZED;
|
||||
backend->ReleaseEGLSurface(surface);
|
||||
// N-3: a released surface the held tuple names may have taken the context with
|
||||
// it (BackendObject::ReleaseEGLSurface -> OnEGLSurfaceReleased -> DestroyEGLContext
|
||||
// once nothing holds it current). Forgetting when the base class only DEFERRED
|
||||
// the destroy costs one forwarded bind; remembering when it did not would cost a
|
||||
// silent no-context-current.
|
||||
ServerLoopInstance().ForgetCurrentTupleIfItNames(surface);
|
||||
return MOBILEGL_OK;
|
||||
}
|
||||
} args{surface};
|
||||
(void)RunOnApply(args);
|
||||
}
|
||||
|
||||
void ServerReleaseEGLResources() {
|
||||
// BLOCKING BY CONTRACT. EGLImpl.cpp:326 calls this on the app thread and then, if no
|
||||
// display and no context are left, calls MobileGL::Destroy() at :333. For DirectGLES it
|
||||
// runs DestroyEGLContext - eglMakeCurrent(NO_SURFACE), eglDestroyContext, eglTerminate -
|
||||
// and those must happen on the thread that made the context current. A fire-and-forget
|
||||
// here lets Destroy() walk on while the server still holds the context, which is
|
||||
// scout-install 5.3's named hazard.
|
||||
struct Args {
|
||||
MobileGLResult Run() {
|
||||
MG_Backend::BackendObject* backend = ServerBackendOrNull();
|
||||
if (backend == nullptr) return MOBILEGL_ERR_NOT_INITIALIZED;
|
||||
backend->ReleaseEGLResources();
|
||||
// N-3: DestroyEGLContext just ran; the tuple names nothing. Without this a
|
||||
// destroy-recreate with the same handle values (every EGL handle on this host
|
||||
// is 0x1) classified as a RepeatNoOp, bound nothing, and republished no caps.
|
||||
// Red once by deleting it: ServerLoopTest's recreate control reads
|
||||
// NativeBindCount() == 1 where 2 is required.
|
||||
ServerLoopInstance().ForgetCurrentTuple();
|
||||
return MOBILEGL_OK;
|
||||
}
|
||||
} args{};
|
||||
(void)RunOnApply(args);
|
||||
}
|
||||
|
||||
Bool ServerInitCapabilities() {
|
||||
struct Args {
|
||||
Bool ok = false;
|
||||
MobileGLResult Run() {
|
||||
MG_Backend::BackendObject* backend = ServerBackendOrNull();
|
||||
if (backend == nullptr) return MOBILEGL_ERR_NOT_INITIALIZED;
|
||||
ok = backend->InitCapabilities();
|
||||
if (!ok) return MOBILEGL_OK;
|
||||
ServerSession* session = ServerSession::Active();
|
||||
if (session != nullptr && session->Accepted()) {
|
||||
(void)session->PublishCapsSnapshot();
|
||||
}
|
||||
return MOBILEGL_OK;
|
||||
}
|
||||
} args{};
|
||||
return RunOnApply(args) == MOBILEGL_OK && args.ok;
|
||||
}
|
||||
|
||||
Bool ServerInitWindowSurface() {
|
||||
struct Args {
|
||||
Bool ok = false;
|
||||
MobileGLResult Run() {
|
||||
MG_Backend::BackendObject* backend = ServerBackendOrNull();
|
||||
if (backend == nullptr) return MOBILEGL_ERR_NOT_INITIALIZED;
|
||||
ok = backend->InitWindowSurface();
|
||||
return MOBILEGL_OK;
|
||||
}
|
||||
} args{};
|
||||
return RunOnApply(args) == MOBILEGL_OK && args.ok;
|
||||
}
|
||||
|
||||
void ServerSetWindowHandle(const MG_Backend::WindowHandle& handle) {
|
||||
struct Args {
|
||||
const MG_Backend::WindowHandle* handle;
|
||||
MobileGLResult Run() {
|
||||
MG_Backend::BackendObject* backend = ServerBackendOrNull();
|
||||
if (backend == nullptr) return MOBILEGL_ERR_NOT_INITIALIZED;
|
||||
backend->SetWindowHandle(*handle);
|
||||
return MOBILEGL_OK;
|
||||
}
|
||||
} args{&handle};
|
||||
(void)RunOnApply(args);
|
||||
}
|
||||
|
||||
} // namespace MobileGL::MG_Remote::Server
|
||||
|
||||
@@ -22,15 +22,42 @@
|
||||
// P6 splits it.
|
||||
//
|
||||
// PARKING AND SHUTDOWN. The thread parks on Doorbell::Wait(consumerParked, ready, spinUs,
|
||||
// kWaitForever) and shuts down when Wait returns false with Dead() set. Doorbell::Kill()
|
||||
// (Doorbell.h:211-221) IS THE ONLY THING that wakes a thread parked on kWaitForever - a fact
|
||||
// ARCHITECTURE.md's teardown order (:537) omits and InProcessTransportTest.cpp:344 already
|
||||
// pins. Kill BEFORE join; join before the client frees any emitter-owned Vector; and the join
|
||||
// must be bounded (that test uses 5 s) so a regression is a red test and not a hung CI job.
|
||||
// kWaitForever) and shuts down when Wait returns false with Dead() set. TWO things can un-park a
|
||||
// kWaitForever waiter, not one, and the difference is the whole of review m-4: for the STOP case a
|
||||
// plain Doorbell::Notify() is sufficient, because m_stopRequested is in the park predicate and
|
||||
// Stop() publishes it BEFORE it rings (Doorbell.h re-tests ready() after every Park return);
|
||||
// Doorbell::Kill() (Doorbell.h:211-221) is load-bearing only for a predicate that has NOTHING to
|
||||
// see, which is why the redcheck's park-predicate-loses-control entry - the one that drops the
|
||||
// control flag FROM the predicate - is the case that actually times out. Kill BEFORE join; join
|
||||
// before the client frees any emitter-owned Vector; and the join must be bounded (that test uses
|
||||
// 5 s) so a regression is a red test and not a hung CI job.
|
||||
//
|
||||
// THE EGL OWNERSHIP MOVE. eglMakeCurrent runs ONCE on this thread and is never released
|
||||
// (DirectGLES.cpp:11925 plus the six cache invalidations at :11933-11953, which become a
|
||||
// one-time startup cost instead of a per-make-current storm). The client's nine EGL virtuals
|
||||
// THE EGL OWNERSHIP MOVE, AS MEASURED (ID-54; review v2 item 10 and N-3). The native
|
||||
// eglMakeCurrent for a surface runs ONCE PER CONTEXT LIFETIME on this thread and the context is
|
||||
// then held for life. That "once" lives in TWO layers, because one is not enough:
|
||||
// DirectGLES::MakeCurrent always calls native eglMakeCurrent and rewrites the owner (codex C7),
|
||||
// and it is reached twice per bring-up - once from InitPbufferSurface/InitWindowSurface when the
|
||||
// surface is CREATED, and once more from the client's first eglMakeCurrent. So (1)
|
||||
// ServerMakeEGLCurrent classifies the request against the tuple it last bound
|
||||
// (ClassifyEglMakeCurrent): an identical repeat is a no-op, and the R-12 republish decision for
|
||||
// it is "nothing to republish" (ID-67: the client's mirror generation must not move); a different
|
||||
// tuple is a real forwarded bind AND a caps republish; a client release-current is RECORDED
|
||||
// (ClientReleaseCount) and NOT forwarded. And (2) BackendObject_DirectGLES::MakeEGLCurrent, under
|
||||
// an active transport only, skips the native call when the requested draw surface is the one
|
||||
// already natively current on this thread (IsBackendContextCurrentOnThisThread, which is EGL
|
||||
// ground truth) AND the virtual tuple is the one that bind was for - or the bind is the surface's
|
||||
// own creation, which the first tuple adopts; a different virtual context onto the same surface
|
||||
// binds natively again, because MakeCurrent's invalidations describe the frontend context that
|
||||
// changed (ID-67). Measured at the EGL function
|
||||
// table by ServerLoopTest's C7 control on a real llvmpipe context: surface creation + two
|
||||
// identical make-currents + a client release + a bind after the release = ONE native
|
||||
// eglMakeCurrent, ZERO native releases, and the apply thread still the owner afterwards. So
|
||||
// DirectGLES.cpp's six cache invalidations run once per context lifetime rather than once per
|
||||
// client make-current, and the 16 IsBackendContextCurrentOnThisThread() / 16 CanTouchGLNow()
|
||||
// sites answer TRUE on the server. The tuple is FORGOTTEN (N-3) on every event after which the
|
||||
// native context it names may be gone - ReleaseEGLResources, ReleaseEGLSurface of the surface it
|
||||
// names, a surface (re)creation, backend destruction - so a recycled handle value after a destroy
|
||||
// is a real bind again and never a silent no-context-current. The client's nine EGL virtuals
|
||||
// become BLOCKING control requests executed here. ReleaseEGLResources and
|
||||
// ~BackendObject_DirectGLES MUST be blocking: MobileGL::Destroy() (MobileGL/Init.cpp:68)
|
||||
// otherwise walks on while the server still holds the context.
|
||||
@@ -45,6 +72,11 @@
|
||||
|
||||
#include "ServerSession.h"
|
||||
|
||||
#include <atomic>
|
||||
#include <condition_variable>
|
||||
#include <mutex>
|
||||
#include <thread>
|
||||
|
||||
namespace MobileGL::MG_Remote::Server {
|
||||
|
||||
class ServerLoop {
|
||||
@@ -81,11 +113,193 @@ namespace MobileGL::MG_Remote::Server {
|
||||
using ControlWork = MobileGLResult (*)(void* user);
|
||||
MobileGLResult RunOnApplyThread(ControlWork work, void* user);
|
||||
|
||||
// ---- v1's additions beyond c0's signature block ---------------------------------
|
||||
|
||||
// Constructs the SERVER ROLE's private BackendObject and runs its non-GL Initialize().
|
||||
// Called from MG_Backend::Init()'s single hook, BEFORE ClientSession::Start(), because
|
||||
// ServerSession::Accept() publishes the first CapsSnapshot from it and because the two
|
||||
// CallMask halves - which have no default and Fatal when unset (ServerSession.h) - are
|
||||
// answered from what this backend is.
|
||||
//
|
||||
// NO GL AND NO EGL HAPPENS HERE. BackendObject_DirectGLES::Initialize() loads the
|
||||
// driver's entry points; the native context does not exist until the client's first
|
||||
// eglMakeCurrent crosses as a blocking control request and runs on the apply thread.
|
||||
// That split is what lets the backend object be BUILT on the app thread while its
|
||||
// context is never OWNED by it.
|
||||
MobileGLResult CreateBackend(BackendType type);
|
||||
|
||||
// True on the apply thread itself. RunOnApplyThread uses it to run inline rather than
|
||||
// deadlock when the apply thread posts to itself - which the EGL teardown path does,
|
||||
// because ~BackendObject_DirectGLES runs THERE and reaches ReleaseEGLResources.
|
||||
static Bool OnApplyThread();
|
||||
|
||||
// The CPU mask MOBILEGL_IPC_SERVER_AFFINITY resolved to and sched_setaffinity accepted.
|
||||
// 0 means "no affinity was applied" - the honest answer for `off`, for a platform with
|
||||
// no affinity call, and for a failed syscall - and is exactly why the RESOLVED mask is
|
||||
// logged rather than the string an operator typed.
|
||||
Uint64 ResolvedAffinityMask() const;
|
||||
|
||||
// Diagnostics the tests read. DrainedRecords is how many records this thread has handed
|
||||
// to the applier; ParkCount how many times it actually parked. A shutdown test that
|
||||
// asserts only "Stop() returned" cannot tell a thread that parked and was woken by Kill
|
||||
// from one that never parked at all - which is the R-16 shape of a check that cannot
|
||||
// fail for its own reason.
|
||||
Uint64 DrainedRecords() const;
|
||||
Uint64 ParkCount() const;
|
||||
|
||||
// C7 / ID-54 diagnostics, read by ServerLoopTest's C7 and N-3 controls. NativeBindCount is
|
||||
// how many times ApplyMakeCurrent FORWARDED a bind to the backend (a tuple it did not
|
||||
// hold); ClientReleaseCount how many client release-current requests were recorded and
|
||||
// not forwarded. Two identical binds must move the first by one and the second not at
|
||||
// all. The number of native eglMakeCurrent calls the DRIVER saw is a different number -
|
||||
// the backend object skips the native call for a surface already current (header block)
|
||||
// - and the control reads that one at the EGL function table, not here.
|
||||
Uint64 NativeBindCount() const;
|
||||
Uint64 ClientReleaseCount() const;
|
||||
// ID-67: how many caps snapshots ServerMakeEGLCurrent has re-published (R-12 arm (a)) - one
|
||||
// per forwarded bind of a tuple it did not hold, never for an identical repeat, so the
|
||||
// client's mirror generation moves exactly when the server's answers could have.
|
||||
Uint64 MakeCurrentRepublishCount() const;
|
||||
void NoteMakeCurrentRepublished();
|
||||
|
||||
// The deduped make-current, on the apply thread. Classifies the request (see
|
||||
// ClassifyEglMakeCurrent), forwards a native bind only for a genuinely new tuple, records
|
||||
// a release without forwarding it, and returns whether a native bind happened so the
|
||||
// caller (ServerMakeEGLCurrent) knows whether to re-publish the caps snapshot (R-12).
|
||||
struct MakeCurrentOutcome {
|
||||
Bool ok = false; // the request was honoured
|
||||
Bool boundNatively = false; // a native eglMakeCurrent ran (=> republish caps)
|
||||
};
|
||||
MakeCurrentOutcome ApplyMakeCurrent(MG_Backend::BackendObject* backend, EGLDisplay dpy,
|
||||
EGLSurface draw, EGLSurface read, EGLContext ctx);
|
||||
|
||||
// N-3: forget the tuple ApplyMakeCurrent last bound. Apply thread only, like the tuple
|
||||
// itself (the forwarders that call these run their Args::Run there). Called on every
|
||||
// event after which the native context that tuple named may no longer exist -
|
||||
// ReleaseEGLResources, ReleaseEGLSurface of a surface the tuple names, a surface
|
||||
// (re)creation (BackendObject_DirectGLES destroys the context to create a different
|
||||
// surface), backend destruction - so the next make-current with the SAME handle values
|
||||
// (EGL handles are recycled; on this host every one of them is literally 0x1) is
|
||||
// classified as a real bind, not as a RepeatNoOp that binds nothing, runs no base-class
|
||||
// bookkeeping and republishes no caps. Forgetting is always safe: the cost of a
|
||||
// forgotten-but-still-current tuple is one forwarded bind the backend object dedups
|
||||
// natively; the cost of a remembered-but-dead one is a silent no-context-current.
|
||||
void ForgetCurrentTuple();
|
||||
void ForgetCurrentTupleIfItNames(EGLSurface surface);
|
||||
|
||||
private:
|
||||
void ApplyThreadMain();
|
||||
// Part of the apply thread's park predicate: a posted control request must be able to
|
||||
// un-park a thread waiting on kWaitForever, which a Notify alone cannot do.
|
||||
Bool ControlIsPending() const;
|
||||
// Runs a posted control request, if there is one. Returns true if it ran one.
|
||||
Bool PumpControlRequest();
|
||||
// Pops and applies every record currently in the ring; returns how many it applied.
|
||||
Uint64 DrainRing();
|
||||
void SignalExited();
|
||||
|
||||
ServerSession* m_session = nullptr;
|
||||
Bool m_running = false;
|
||||
std::atomic<Bool> m_running{false};
|
||||
std::atomic<Bool> m_stopRequested{false};
|
||||
std::thread m_thread;
|
||||
std::atomic<std::thread::id> m_applyThreadId{};
|
||||
|
||||
// The private backend object. Destroyed ON the apply thread while it still owns the
|
||||
// context - see Stop().
|
||||
UniquePtr<MG_Backend::BackendObject> m_backend;
|
||||
|
||||
// The blocking control mailbox. ONE slot, because the verb barrier already leaves one
|
||||
// client thread runnable at a time; m_callerMutex serialises anything that is not.
|
||||
std::mutex m_callerMutex;
|
||||
std::mutex m_controlMutex;
|
||||
std::condition_variable m_controlPosted;
|
||||
std::condition_variable m_controlDone;
|
||||
ControlWork m_controlWork = nullptr;
|
||||
void* m_controlUser = nullptr;
|
||||
MobileGLResult m_controlResult = MOBILEGL_OK;
|
||||
Bool m_controlPending = false;
|
||||
Bool m_controlFinished = false;
|
||||
|
||||
// The BOUNDED join's other half. std::thread::join has no deadline, so a lost wakeup
|
||||
// would wedge CI rather than fail it; the thread signals here last and Stop() waits
|
||||
// with a deadline (InProcessTransportTest.cpp:344's five seconds).
|
||||
std::mutex m_exitMutex;
|
||||
std::condition_variable m_exitCv;
|
||||
Bool m_exited = false;
|
||||
|
||||
Uint64 m_affinityMask = 0;
|
||||
std::atomic<Uint64> m_drained{0};
|
||||
std::atomic<Uint64> m_parks{0};
|
||||
|
||||
// C7 / ID-54: the (dpy, draw, read, ctx) currently bound on the apply thread. Written and
|
||||
// read ONLY on the apply thread inside ApplyMakeCurrent, so it needs no lock; the two
|
||||
// counters beside it are atomic because a test reads them from another thread.
|
||||
Bool m_haveCurrentTuple = false;
|
||||
EGLDisplay m_curDpy = EGL_NO_DISPLAY;
|
||||
EGLSurface m_curDraw = EGL_NO_SURFACE;
|
||||
EGLSurface m_curRead = EGL_NO_SURFACE;
|
||||
EGLContext m_curCtx = EGL_NO_CONTEXT;
|
||||
std::atomic<Uint64> m_nativeBinds{0};
|
||||
std::atomic<Uint64> m_clientReleases{0};
|
||||
std::atomic<Uint64> m_makeCurrentRepublishes{0};
|
||||
};
|
||||
|
||||
ServerLoop& ServerLoopInstance();
|
||||
|
||||
// C7 / ID-54, factored out so a unit case can drive the DECISION without a live EGL context
|
||||
// (the native bind itself needs the joint lane). Given the tuple currently held on the apply
|
||||
// thread and the request, is this a native bind, an identical no-op repeat, or a client
|
||||
// release-current the server must record without forwarding?
|
||||
enum class EglBindAction { NativeBind, RepeatNoOp, ClientRelease };
|
||||
EglBindAction ClassifyEglMakeCurrent(Bool haveCurrent, EGLDisplay curDpy, EGLSurface curDraw,
|
||||
EGLSurface curRead, EGLContext curCtx, EGLDisplay dpy,
|
||||
EGLSurface draw, EGLSurface read, EGLContext ctx);
|
||||
|
||||
// ---------------------------------------------------------------------------------
|
||||
// THE EGL OWNERSHIP MOVE - the part that can sink the phase, expressed as twelve calls
|
||||
// ---------------------------------------------------------------------------------
|
||||
//
|
||||
// Under split the app thread must never reach the driver's eglMakeCurrent. Today it does:
|
||||
// EGLImpl.cpp:284 -> BackendObject_DirectGLES.cpp:963 -> DirectGLES.cpp:11925, and the
|
||||
// owner slot g_backendContextOwnerThread (DirectGLES.cpp:11865) is stamped with whatever
|
||||
// thread got there. So BackendObject_Remote's nine EGL virtuals - package c1's - call these
|
||||
// twelve, each of which is a BLOCKING control request that runs the SERVER's backend object
|
||||
// on mgl-srv-apply. The native eglMakeCurrent then runs once per context lifetime on that
|
||||
// thread (the surface's own creation binds; the client's make-currents onto that surface
|
||||
// are deduped at both layers, header block above) and a client release is never forwarded,
|
||||
// so g_backendContextOwnerThread is written once per context lifetime, DirectGLES.cpp's six
|
||||
// cache invalidations run once per context lifetime rather than once per client
|
||||
// make-current, the per-frame EGL re-verification stamp holds, and the 16
|
||||
// IsBackendContextCurrentOnThisThread() sites plus the 16 CanTouchGLNow() sites answer TRUE
|
||||
// on the server instead of silently degrading. Measured, not assumed: ServerLoopTest's C7
|
||||
// control counts the driver's eglMakeCurrent calls at the EGL function table.
|
||||
//
|
||||
// TWO OF THEM MUST BLOCK OR THE PROCESS TEARS ITS OWN CONTEXT DOWN UNDER ITSELF:
|
||||
// ReleaseEGLResources (reached from EGLImpl.cpp:326, which for DirectGLES runs
|
||||
// DestroyEGLContext) and ~BackendObject_DirectGLES (reached from
|
||||
// pActiveBackendObject.reset() at MobileGL/Init.cpp:68). Both are blocking here - the first
|
||||
// by being one of these calls, the second because ServerLoop::Stop() destroys the private
|
||||
// backend ON the apply thread before that thread exits and Stop() itself waits.
|
||||
//
|
||||
// WHY THEY ARE FREE FUNCTIONS AND NOT MEMBERS: c1 needs exactly this surface and nothing
|
||||
// else of the server, so the seam between the two packages is a list of twelve signatures
|
||||
// rather than a class with a lifecycle.
|
||||
Bool ServerInitializeEGLDisplay(EGLDisplay dpy, EGLint* major, EGLint* minor);
|
||||
Bool ServerCreateEGLWindowSurface(EGLSurface surface, const MG_Backend::WindowHandle& handle);
|
||||
Bool ServerResizeEGLWindowSurface(EGLSurface surface, Uint32 width, Uint32 height);
|
||||
Bool ServerCreateEGLPbufferSurface(EGLSurface surface, EGLint width, EGLint height);
|
||||
// Also RE-PUBLISHES THE CAPS SNAPSHOT on success (R-12). BackendObject::MakeEGLCurrent runs
|
||||
// InitCapabilities() on the first make-current per surface (BackendObject.cpp:341-347), so
|
||||
// this is the moment the server's answers stop being the empty ones Accept() published -
|
||||
// and a SECOND arrival IS the invalidation signal, which is how DirectGLES, which has no
|
||||
// OnCapsInvalidated producer at all, tells the client without a dev-shaped backend edit.
|
||||
Bool ServerMakeEGLCurrent(EGLDisplay dpy, EGLSurface draw, EGLSurface read, EGLContext ctx);
|
||||
Bool ServerSwapEGLBuffers(EGLDisplay dpy, EGLSurface draw);
|
||||
void ServerSetEGLSwapInterval(Int interval);
|
||||
void ServerReleaseEGLSurface(EGLSurface surface);
|
||||
void ServerReleaseEGLResources();
|
||||
Bool ServerInitCapabilities();
|
||||
Bool ServerInitWindowSurface();
|
||||
void ServerSetWindowHandle(const MG_Backend::WindowHandle& handle);
|
||||
|
||||
} // namespace MobileGL::MG_Remote::Server
|
||||
|
||||
@@ -6,45 +6,513 @@
|
||||
// SPDX-License-Identifier: LGPL-3.0-only
|
||||
// End of Source File Header
|
||||
|
||||
// P5 c0 stubs for package s1.
|
||||
// P5 package s1: the server half of a session.
|
||||
|
||||
#include "ServerSession.h"
|
||||
|
||||
#include "../CapsCodec.h"
|
||||
#include "../Protocol/generated/protocol_generated.h"
|
||||
#include "../Transport/InProcessTransport.h"
|
||||
|
||||
#include <Config.h>
|
||||
#include <MGGitHash.h>
|
||||
#include <MG_Util/Debug/Log.h>
|
||||
|
||||
#include <cstdlib>
|
||||
#include <vector>
|
||||
|
||||
namespace MobileGL::MG_Remote::Server {
|
||||
|
||||
#define MGP5_C0_STUB(what) \
|
||||
do { \
|
||||
MGLOG_F("MGPipe: Fatal{UnimplementedServerSession, \"%s\"} - P5 package s1 has not landed " \
|
||||
"this yet; c0 shipped the signature only", \
|
||||
what); \
|
||||
std::abort(); \
|
||||
} while (0)
|
||||
// THE THREE FLAG-SPACE COLLISIONS, AS TRIPWIRES RATHER THAN AS A COMMENT.
|
||||
//
|
||||
// MGPipeCallFlags (MG_Pipe/MGPipe.h:42-54) and RingRecordFlags (Ring.h) are separate spaces
|
||||
// that overlap, and three bits mean DIFFERENT things in each. Ring.h's enum carries the
|
||||
// table; these are the assertions that break the build if either enum is renumbered, so the
|
||||
// collision can never become news again. They live here because this is the nearest .cpp
|
||||
// that legally sees both headers - nothing under Transport/ may reach MobileGL/Includes.h.
|
||||
static_assert(static_cast<Uint16>(MG_Pipe::kVarTail) == Transport::kRecPad,
|
||||
"MGPipeCallFlags::kVarTail and kRecPad share bit 2: an encoder that copies call "
|
||||
"flags into RingRecordHeader::flags makes every var-tail record read as a wrap "
|
||||
"filler. RingConsumer::Pop requires kind == kRingPadRecordKind as well, which is "
|
||||
"what keeps that from eating the record - do not relax it");
|
||||
static_assert(static_cast<Uint16>(MG_Pipe::kHostSpan) == Transport::kRecBorrowSlot,
|
||||
"MGPipeCallFlags::kHostSpan and kRecBorrowSlot share bit 3: a host-span record "
|
||||
"would read as borrowed into the GPU timeline and stop the consumer reclaiming "
|
||||
"ring bytes behind it. SessionConsumer counts and names every sighting");
|
||||
static_assert(static_cast<Uint16>(MG_Pipe::kReplySlot) == Transport::kRecVarTail,
|
||||
"MGPipeCallFlags::kReplySlot and kRecVarTail share bit 4");
|
||||
static_assert(static_cast<Uint16>(MG_Pipe::kNeedsAck) == Transport::kRecNeedsAck &&
|
||||
static_cast<Uint16>(MG_Pipe::kHasBlob) == Transport::kRecHasBlob,
|
||||
"the two bits that DO mean the same thing in both spaces have drifted apart, "
|
||||
"which is a different and worse problem than the three that collide");
|
||||
|
||||
ServerSession* ServerSession::Active() { return nullptr; }
|
||||
namespace {
|
||||
|
||||
MobileGLResult ServerSession::Accept(Transport::ITransport&) { MGP5_C0_STUB("ServerSession::Accept"); }
|
||||
// A control-plane frame is small by construction (ITransport.h:56-58: bulk bytes
|
||||
// belong in shm, never here), so one stack-free vector sized from PeekFrameSize is
|
||||
// the whole reader. The BUFFER_TOO_SMALL half of ReceiveFrame's contract is what
|
||||
// makes the two-step safe: a short buffer leaves the message queued.
|
||||
MobileGLResult ReceiveEnvelope(Transport::ITransport& transport, std::vector<Uint8>& out,
|
||||
Uint32 timeoutMs) {
|
||||
Uint64 size = 0;
|
||||
MobileGLMutableByteSpan empty{nullptr, 0};
|
||||
const MobileGLResult probe = transport.ReceiveFrame(empty, &size, timeoutMs);
|
||||
if (probe != MOBILEGL_ERR_BUFFER_TOO_SMALL) {
|
||||
// OK with a zero-size message, or a real failure. A zero-length control
|
||||
// frame is not a legal CtrlEnvelope either way.
|
||||
return probe == MOBILEGL_OK ? MOBILEGL_ERR_PROTOCOL_MISMATCH : probe;
|
||||
}
|
||||
out.resize(static_cast<SizeT>(size));
|
||||
MobileGLMutableByteSpan span{out.data(), out.size()};
|
||||
return transport.ReceiveFrame(span, &size, 0);
|
||||
}
|
||||
|
||||
MobileGLResult SendEnvelope(Transport::ITransport& transport,
|
||||
::flatbuffers::FlatBufferBuilder& builder) {
|
||||
return transport.SendFrame(
|
||||
MobileGLByteSpan{builder.GetBufferPointer(), builder.GetSize()});
|
||||
}
|
||||
|
||||
// Every message from the peer is verified before a single field is read: the control
|
||||
// plane is parsed from another process's memory (P6) and from another role's (P5).
|
||||
const ::MobileGL::Wire::CtrlEnvelope* ParseEnvelope(const std::vector<Uint8>& bytes) {
|
||||
::flatbuffers::Verifier verifier(bytes.data(), bytes.size());
|
||||
if (!::MobileGL::Wire::VerifyCtrlEnvelopeBuffer(verifier)) {
|
||||
return nullptr;
|
||||
}
|
||||
if (!::MobileGL::Wire::CtrlEnvelopeBufferHasIdentifier(bytes.data())) {
|
||||
return nullptr;
|
||||
}
|
||||
return ::MobileGL::Wire::GetCtrlEnvelope(bytes.data());
|
||||
}
|
||||
|
||||
[[noreturn]] void FatalAbiMismatch(const char* what, Uint64 ours, Uint64 theirs,
|
||||
const char* ourStamp, const char* theirStamp) {
|
||||
// NEVER a downgrade. Every alternative to aborting here reads one struct as
|
||||
// another - MGPCaps has only a compositional size assertion because
|
||||
// DynamicBackendParameters still carries SizeT, so a peer built from a different
|
||||
// tree hands over a caps block whose members are at different offsets and whose
|
||||
// bytes are all individually plausible.
|
||||
MGLOG_F("MGPipe: Fatal{AbiMismatch, \"%s\"} ours=%llu theirs=%llu ourBuild=%s "
|
||||
"theirBuild=%s - the two peers were not built from the same struct shapes, "
|
||||
"and there is no downgrade path: the caps block's size is ABI-dependent "
|
||||
"(MGPipeTypes.h:145-146) and every field past the first difference would be "
|
||||
"read at the wrong offset",
|
||||
what, static_cast<unsigned long long>(ours),
|
||||
static_cast<unsigned long long>(theirs),
|
||||
ourStamp == nullptr ? "?" : ourStamp, theirStamp == nullptr ? "?" : theirStamp);
|
||||
std::abort();
|
||||
}
|
||||
|
||||
// MOBILEGL_IPC_RING_MB / MOBILEGL_IPC_STAGE_MB, actually applied.
|
||||
//
|
||||
// The first version of this file called this only `if (m_sizes.CmdBytes == 0)`, and
|
||||
// SessionSegmentSizes has a default member initialiser of 8 MiB, so the condition was
|
||||
// never true and the whole function was dead: ConfigLoader parsed both knobs, echoed
|
||||
// them into the config line, and the session mapped 8/32 MiB regardless. Config.h's
|
||||
// own comment four lines above the declaration is the statement of that bug - "an
|
||||
// environment variable that nothing parses is indistinguishable from one that is
|
||||
// parsed and ignored" - and a knob that REPORTS a value it does not use is worse,
|
||||
// because it makes every measurement taken with it a lie.
|
||||
Transport::SessionSegmentSizes SizesFromConfig() {
|
||||
Transport::SessionSegmentSizes sizes;
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
const Uint64 ringMb = MG_Config::Ipc.RingMb == 0 ? 8u : MG_Config::Ipc.RingMb;
|
||||
const Uint64 stageMb = MG_Config::Ipc.StageMb == 0 ? 32u : MG_Config::Ipc.StageMb;
|
||||
sizes.CmdRingBytes = ringMb * 1024ull * 1024ull;
|
||||
sizes.StageBytes = stageMb * 1024ull * 1024ull;
|
||||
#endif
|
||||
return sizes;
|
||||
}
|
||||
|
||||
Uint32 SpinUsFromConfig() {
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
return MG_Config::Ipc.SpinUs;
|
||||
#else
|
||||
return Transport::kDefaultSpinUs;
|
||||
#endif
|
||||
}
|
||||
|
||||
// The handshake's own deadline. Bounded rather than kWaitForever on purpose: a
|
||||
// bring-up that never answers must be a red lane, not a wedged CI job - the same
|
||||
// reason InProcessTransportTest.cpp:344 bounds its join at five seconds.
|
||||
constexpr Uint32 kHandshakeTimeoutMs = 5000;
|
||||
|
||||
// THERE IS NO DERIVATION OF CallMask, BY RULING. See ServerSession.h's block on
|
||||
// SetCapabilityBits / SetConsumedSubsystems for why the one that used to be here was
|
||||
// the phase's marquee defect committed from the server's side.
|
||||
[[noreturn]] void FatalUnsetCallMask(Bool capBitsSet, Bool consumedSet) {
|
||||
MGLOG_F("MGPipe: Fatal{UnsetCallMask} - %s%s%s was never set on this ServerSession, "
|
||||
"and there is no default: a guessed consumer mask makes the client's R-8 "
|
||||
"liveness gates answer from a server-side fact the server never stated. The "
|
||||
"client would stop emitting whole record families, clear its dirty flags on "
|
||||
"acceptance anyway, and the lane would go green with the uploads lost "
|
||||
"(ID-39, reflected). Call SetConsumedSubsystems() and SetCapabilityBits() "
|
||||
"before Accept(); SetCapabilityBits(0) is a legitimate explicit answer",
|
||||
capBitsSet ? "" : "SetCapabilityBits",
|
||||
(!capBitsSet && !consumedSet) ? " and " : "",
|
||||
consumedSet ? "" : "SetConsumedSubsystems");
|
||||
std::abort();
|
||||
}
|
||||
|
||||
ServerSession* g_active = nullptr;
|
||||
|
||||
} // namespace
|
||||
|
||||
ServerSession& ServerSessionInstance() {
|
||||
// Leak at exit, deliberately and per ID-8: frontend destructors reach pipe and backend
|
||||
// state from exit handlers, and a session destroyed before them would be a
|
||||
// use-after-free rather than a tidy teardown.
|
||||
static ServerSession* instance = new ServerSession{};
|
||||
return *instance;
|
||||
}
|
||||
|
||||
ServerSession* ServerSession::Active() { return g_active; }
|
||||
|
||||
ServerSession::~ServerSession() { Close(); }
|
||||
|
||||
void ServerSession::SetSegmentSizes(const Transport::SessionSegmentSizes& sizes) {
|
||||
if (m_accepted) {
|
||||
MGLOG_E("MG_Remote server: SetSegmentSizes after Accept is ignored - the geometry is "
|
||||
"already on the wire in Welcome and the peer has mapped it");
|
||||
return;
|
||||
}
|
||||
m_sizes = sizes;
|
||||
m_sizesSet = true;
|
||||
}
|
||||
|
||||
void ServerSession::SetBackend(MG_Backend::BackendObject* backend) { m_backend = backend; }
|
||||
|
||||
void ServerSession::SetCapabilityBits(Uint64 capBits) {
|
||||
m_capBits = capBits;
|
||||
m_capBitsSet = true;
|
||||
}
|
||||
|
||||
void ServerSession::SetConsumedSubsystems(Uint64 subsystemMask) {
|
||||
m_consumedSubsystems = subsystemMask;
|
||||
m_consumedSet = true;
|
||||
}
|
||||
|
||||
Bool ServerSession::CallMaskIsSet() const { return m_capBitsSet && m_consumedSet; }
|
||||
|
||||
Uint64 ServerSession::CallMask() const {
|
||||
if (!CallMaskIsSet()) {
|
||||
FatalUnsetCallMask(m_capBitsSet, m_consumedSet);
|
||||
}
|
||||
return m_capBits | MGCapsConsumerBits(m_consumedSubsystems);
|
||||
}
|
||||
|
||||
Bool ServerSession::Accepted() const { return m_accepted; }
|
||||
|
||||
MobileGLResult ServerSession::Accept(Transport::ITransport& transport) {
|
||||
if (m_accepted) {
|
||||
return MOBILEGL_ERR_INVALID_ARGUMENT;
|
||||
}
|
||||
m_transport = &transport;
|
||||
// MOBILEGL_IPC_RING_MB / _STAGE_MB unless SetSegmentSizes overrode them. Unconditional
|
||||
// on purpose - see SizesFromConfig.
|
||||
if (!m_sizesSet) {
|
||||
m_sizes = SizesFromConfig();
|
||||
}
|
||||
|
||||
// ---- 1/2. the ABI assertion, BEFORE a single record is decoded and before a byte of
|
||||
// shared memory exists. Its whole purpose is to refuse to interpret the peer's bytes.
|
||||
std::vector<Uint8> frame;
|
||||
const MobileGLResult received = ReceiveEnvelope(transport, frame, kHandshakeTimeoutMs);
|
||||
if (received != MOBILEGL_OK) {
|
||||
MGLOG_E("MG_Remote server: no Hello within %u ms (rc=%d)", kHandshakeTimeoutMs,
|
||||
static_cast<int>(received));
|
||||
return received;
|
||||
}
|
||||
const ::MobileGL::Wire::CtrlEnvelope* envelope = ParseEnvelope(frame);
|
||||
// msg_as_Hello() IS PART OF THE GUARD, not a consequence of it. FlatBuffers'
|
||||
// Verifier::VerifyTable is `return !table || table->Verify(*this)`, so a NULL union
|
||||
// member passes verification: a 24-byte frame verifies, carries the identifier,
|
||||
// reports msg_type() == Hello and returns nullptr from msg_as_Hello(). A malformed
|
||||
// frame has to be refused, never dereferenced.
|
||||
if (envelope == nullptr || envelope->msg_type() != ::MobileGL::Wire::CtrlMsg::Hello ||
|
||||
envelope->msg_as_Hello() == nullptr) {
|
||||
MGLOG_E("MG_Remote server: the first control frame is not a verifiable Hello");
|
||||
return MOBILEGL_ERR_PROTOCOL_MISMATCH;
|
||||
}
|
||||
const ::MobileGL::Wire::Hello* hello = envelope->msg_as_Hello();
|
||||
const char* theirStamp =
|
||||
hello->buildFingerprint() == nullptr ? nullptr : hello->buildFingerprint()->c_str();
|
||||
|
||||
if (hello->abiMajor() != static_cast<Uint32>(MOBILEGL_PROTOCOL_ABI_MAJOR) ||
|
||||
hello->abiMinor() != static_cast<Uint32>(MOBILEGL_PROTOCOL_ABI_MINOR)) {
|
||||
FatalAbiMismatch("protocol version",
|
||||
MOBILEGL_ABI_VERSION(MOBILEGL_PROTOCOL_ABI_MAJOR,
|
||||
MOBILEGL_PROTOCOL_ABI_MINOR),
|
||||
MOBILEGL_ABI_VERSION(hello->abiMajor(), hello->abiMinor()),
|
||||
GIT_COMMIT_HASH_SHORT, theirStamp);
|
||||
}
|
||||
const Uint64 ourFingerprint = CapsAbiFingerprint();
|
||||
if (hello->abiFingerprint() != ourFingerprint) {
|
||||
FatalAbiMismatch("struct shapes", ourFingerprint, hello->abiFingerprint(),
|
||||
GIT_COMMIT_HASH_SHORT, theirStamp);
|
||||
}
|
||||
|
||||
// ---- 3. the four segments, both control pages, the rings.
|
||||
const MobileGLResult created = m_shm.Create(m_sizes, Transport::MemoryRole::Server);
|
||||
if (created != MOBILEGL_OK) {
|
||||
return created;
|
||||
}
|
||||
|
||||
Transport::RingControl* control = m_shm.CmdControl();
|
||||
m_commands = Transport::RingConsumer(control, m_shm.CmdRingBase(), m_shm.CmdRingCapacity(),
|
||||
Transport::RingCursorSet::Cmd);
|
||||
if (!m_commands.Valid()) {
|
||||
Close();
|
||||
return MOBILEGL_ERR_INVALID_ARGUMENT;
|
||||
}
|
||||
m_consumer.Attach(control, &m_commands, &ProducerDoorbell(), &ConsumerDoorbell(),
|
||||
SpinUsFromConfig());
|
||||
|
||||
{
|
||||
Transport::ReplySlotPool pool(m_shm.ReplyBase(), m_shm.ReplyBytes(),
|
||||
m_shm.ReplySlotCount());
|
||||
if (!pool.Valid()) {
|
||||
Close();
|
||||
return MOBILEGL_ERR_INVALID_ARGUMENT;
|
||||
}
|
||||
// A stale stamp from a previous session must never read as this session's answer.
|
||||
pool.Clear();
|
||||
m_replies = ReplyPool(m_shm.ReplyBase(), m_shm.ReplyBytes(), m_shm.ReplySlotCount(),
|
||||
pool.SlotBytes());
|
||||
}
|
||||
|
||||
m_events = Transport::EventRingProducer(m_shm.EventControl(), control, m_shm.EventRingBase(),
|
||||
m_shm.EventRingCapacity());
|
||||
m_applier = PipeApplier(&m_segments, &m_replies);
|
||||
|
||||
// ---- 4. Welcome: the four SegmentRefs, plus this side's half of the ABI statement.
|
||||
{
|
||||
::flatbuffers::FlatBufferBuilder builder(1024);
|
||||
using Slot = Transport::SessionSegmentSlot;
|
||||
const auto segmentRef = [&](Uint32 id, ::MobileGL::Wire::SegmentKind kind, Slot slot) {
|
||||
return ::MobileGL::Wire::CreateSegmentRefDirect(builder, id, kind,
|
||||
m_shm.AnnouncedSize(slot),
|
||||
m_shm.AnnouncedName(slot));
|
||||
};
|
||||
auto cmd = segmentRef(1, ::MobileGL::Wire::SegmentKind::Cmd, Slot::Cmd);
|
||||
auto stage = segmentRef(2, ::MobileGL::Wire::SegmentKind::Stage, Slot::Stage);
|
||||
auto reply = segmentRef(3, ::MobileGL::Wire::SegmentKind::Reply, Slot::Reply);
|
||||
auto event = segmentRef(4, ::MobileGL::Wire::SegmentKind::Event, Slot::Event);
|
||||
auto stamp = builder.CreateString(GIT_COMMIT_HASH_SHORT);
|
||||
auto welcome = ::MobileGL::Wire::CreateWelcome(
|
||||
builder, MOBILEGL_PROTOCOL_ABI_MAJOR, MOBILEGL_PROTOCOL_ABI_MINOR,
|
||||
static_cast<Uint32>(hello->pid()), cmd, stage, reply, event, stamp, ourFingerprint);
|
||||
auto root = ::MobileGL::Wire::CreateCtrlEnvelope(
|
||||
builder, ::MobileGL::Wire::CtrlMsg::Welcome, welcome.Union());
|
||||
::MobileGL::Wire::FinishCtrlEnvelopeBuffer(builder, root);
|
||||
const MobileGLResult sent = SendEnvelope(transport, builder);
|
||||
if (sent != MOBILEGL_OK) {
|
||||
Close();
|
||||
return sent;
|
||||
}
|
||||
}
|
||||
|
||||
// ---- 5. the segment table and the ONE process-wide resolver.
|
||||
//
|
||||
// Table 3's ruling: gMGPipeSegmentResolver is a plain non-atomic inline variable and
|
||||
// there is exactly one per process, so the SERVER role installs it and the client never
|
||||
// resolves a span at all - it only ever writes Ptr = nullptr. Installed BEFORE the apply
|
||||
// thread starts, uninstalled after the join and never before.
|
||||
//
|
||||
// Both calls are package w1's (Wire/PipeWireCodec.cpp) and are named-Fatal stubs until
|
||||
// w1 lands. That is deliberate and is where the bring-up currently stops: a session
|
||||
// that skipped them and carried on would be a decoder with no segments, which is the
|
||||
// "split lane ran monolith and went green" shape.
|
||||
m_segments.Install(Wire::kSegCmd,
|
||||
Wire::SegmentView{m_shm.CmdRingBase(), m_shm.CmdRingCapacity()});
|
||||
m_segments.Install(Wire::kSegStage,
|
||||
Wire::SegmentView{m_shm.StageBase(), m_shm.StageBytes()});
|
||||
m_segments.Install(Wire::kSegReply,
|
||||
Wire::SegmentView{m_shm.ReplyBase(), m_shm.ReplyBytes()});
|
||||
m_segments.Install(Wire::kSegEvent, Wire::SegmentView{m_shm.EventSegmentBase(),
|
||||
m_shm.AnnouncedSize(
|
||||
Transport::SessionSegmentSlot::Event)});
|
||||
m_segments.InstallProcessResolver();
|
||||
|
||||
m_accepted = true;
|
||||
g_active = this;
|
||||
LogMemory("accept");
|
||||
|
||||
if (!CallMaskIsSet()) {
|
||||
// Not fatal HERE, because a session with no backend legitimately publishes no
|
||||
// snapshot at all and the mask is only needed by one. It becomes
|
||||
// Fatal{UnsetCallMask} the moment PublishCapsSnapshot asks for it, which is the
|
||||
// first thing that would put a guess on the wire.
|
||||
MGLOG_W("MG_Remote server: accepted with no CallMask - SetConsumedSubsystems() and/or "
|
||||
"SetCapabilityBits() were never called. There is no default and there will be "
|
||||
"no guess: the first CapsSnapshot will abort instead");
|
||||
}
|
||||
|
||||
// ---- 6. the first CapsSnapshot, if there is a backend to take it from.
|
||||
if (m_backend != nullptr) {
|
||||
const MobileGLResult published = PublishCapsSnapshot();
|
||||
if (published != MOBILEGL_OK) {
|
||||
return published;
|
||||
}
|
||||
} else {
|
||||
MGLOG_W("MG_Remote server: accepted with NO backend, so the first CapsSnapshot is "
|
||||
"deferred. Call SetBackend() then PublishCapsSnapshot(). A client that emits "
|
||||
"before the snapshot arrives reads a placeholder caps mirror");
|
||||
}
|
||||
return MOBILEGL_OK;
|
||||
}
|
||||
|
||||
MobileGLResult ServerSession::PublishCapsSnapshot() {
|
||||
MGP5_C0_STUB("ServerSession::PublishCapsSnapshot");
|
||||
if (!m_accepted || m_transport == nullptr) {
|
||||
return MOBILEGL_ERR_NOT_INITIALIZED;
|
||||
}
|
||||
if (m_backend == nullptr) {
|
||||
MGLOG_E("MG_Remote server: PublishCapsSnapshot with no backend");
|
||||
return MOBILEGL_ERR_NOT_INITIALIZED;
|
||||
}
|
||||
|
||||
// The two blob codecs are package w1's (CapsCodec.h). They are named-Fatal stubs
|
||||
// today; nothing here may substitute a memcpy for them, because both structures hold
|
||||
// Vectors and Strings and a memcpy of either crosses a host pointer (R-2's rule B).
|
||||
Vector<Uint8> formats;
|
||||
Vector<Uint8> renderer;
|
||||
if (!EncodeFormatCapabilities(m_backend->GetFormatCapabilities(), formats)) {
|
||||
return MOBILEGL_ERR_PROTOCOL_MISMATCH;
|
||||
}
|
||||
if (!EncodeRendererInfo(m_backend->GetRendererInfo(), renderer)) {
|
||||
return MOBILEGL_ERR_PROTOCOL_MISMATCH;
|
||||
}
|
||||
|
||||
const MG_Backend::DynamicBackendParameters& dynamic = m_backend->GetDynamicParameters();
|
||||
const auto* dynamicBytes = reinterpret_cast<const Uint8*>(&dynamic);
|
||||
|
||||
// R-8/C-4: bits 32..47 of CallMask are the CONSUMER MASK, and this is the only place
|
||||
// they are produced.
|
||||
const Uint64 callMask = CallMask();
|
||||
|
||||
::flatbuffers::FlatBufferBuilder builder(4096);
|
||||
auto dynamicVector =
|
||||
builder.CreateVector(dynamicBytes, static_cast<::flatbuffers::uoffset_t>(sizeof(dynamic)));
|
||||
auto rendererVector = builder.CreateVector(renderer.data(), renderer.size());
|
||||
auto formatsVector = builder.CreateVector(formats.data(), formats.size());
|
||||
const RendererInfo& info = m_backend->GetRendererInfo();
|
||||
auto apiVersion = builder.CreateString(info.RendererGLInfo.TargetGLVersion.toString());
|
||||
auto snapshot = ::MobileGL::Wire::CreateCapsSnapshot(
|
||||
builder, dynamicVector, rendererVector, formatsVector, /*extensions=*/0, apiVersion,
|
||||
callMask, static_cast<Uint32>(m_backend->GetBackendType()));
|
||||
auto root = ::MobileGL::Wire::CreateCtrlEnvelope(
|
||||
builder, ::MobileGL::Wire::CtrlMsg::CapsSnapshot, snapshot.Union());
|
||||
::MobileGL::Wire::FinishCtrlEnvelopeBuffer(builder, root);
|
||||
return SendEnvelope(*m_transport, builder);
|
||||
}
|
||||
|
||||
void ServerSession::Close() {
|
||||
if (g_active == this) {
|
||||
g_active = nullptr;
|
||||
}
|
||||
if (m_accepted) {
|
||||
// Uninstall AFTER the apply thread has joined, never before: a record still in
|
||||
// flight can still resolve a segment offset (table 3's fourth column).
|
||||
Wire::SegmentTable::UninstallProcessResolver();
|
||||
}
|
||||
m_consumer.Detach();
|
||||
m_commands = Transport::RingConsumer();
|
||||
m_events = Transport::EventRingProducer();
|
||||
m_replies = ReplyPool();
|
||||
m_shm.Close();
|
||||
m_transport = nullptr;
|
||||
m_accepted = false;
|
||||
}
|
||||
|
||||
Transport::RingConsumer& ServerSession::CommandRing() { return m_commands; }
|
||||
Transport::RingControl& ServerSession::Control() { MGP5_C0_STUB("ServerSession::Control"); }
|
||||
|
||||
Transport::RingControl& ServerSession::Control() {
|
||||
Transport::RingControl* control = m_shm.CmdControl();
|
||||
if (control == nullptr) {
|
||||
MGLOG_F("MGPipe: Fatal{ProtocolCorruption, \"ServerSession::Control\"} - the control "
|
||||
"page does not exist until Accept() has mapped SEG_CMD");
|
||||
std::abort();
|
||||
}
|
||||
return *control;
|
||||
}
|
||||
|
||||
Wire::SegmentTable& ServerSession::Segments() { return m_segments; }
|
||||
PipeApplier& ServerSession::Applier() { return m_applier; }
|
||||
ReplyPool& ServerSession::Replies() { return m_replies; }
|
||||
|
||||
// The bell the apply thread parks on. On the server endpoint of an InProcessTransport that
|
||||
// is SelfDoorbell(); the client reaches the same bell through its own PeerDoorbell().
|
||||
Transport::Doorbell& ServerSession::ConsumerDoorbell() {
|
||||
MGP5_C0_STUB("ServerSession::ConsumerDoorbell");
|
||||
}
|
||||
Transport::Doorbell& ServerSession::ProducerDoorbell() {
|
||||
MGP5_C0_STUB("ServerSession::ProducerDoorbell");
|
||||
if (m_transport == nullptr) {
|
||||
MGLOG_F("MGPipe: Fatal{ProtocolCorruption, \"ServerSession::ConsumerDoorbell\"} - no "
|
||||
"transport; Accept() has not run");
|
||||
std::abort();
|
||||
}
|
||||
if (m_transport->Role() == Transport::TransportRole::InProcess) {
|
||||
return static_cast<Transport::InProcessTransport*>(m_transport)->SelfDoorbell();
|
||||
}
|
||||
// P6: SocketTransport's pair. The accessors stay off ITransport by ruling (contract
|
||||
// §3.9) precisely so that this stays one switch in one file rather than two virtuals
|
||||
// every transport has to invent a home for.
|
||||
MGLOG_F("MGPipe: Fatal{UnmigratedVerb, \"ServerSession::ConsumerDoorbell\"} - transport "
|
||||
"role %u has no doorbell pair yet; that is P6's SocketTransport",
|
||||
static_cast<unsigned>(m_transport->Role()));
|
||||
std::abort();
|
||||
}
|
||||
|
||||
#undef MGP5_C0_STUB
|
||||
Transport::Doorbell& ServerSession::ProducerDoorbell() {
|
||||
if (m_transport == nullptr) {
|
||||
MGLOG_F("MGPipe: Fatal{ProtocolCorruption, \"ServerSession::ProducerDoorbell\"} - no "
|
||||
"transport; Accept() has not run");
|
||||
std::abort();
|
||||
}
|
||||
if (m_transport->Role() == Transport::TransportRole::InProcess) {
|
||||
return static_cast<Transport::InProcessTransport*>(m_transport)->PeerDoorbell();
|
||||
}
|
||||
MGLOG_F("MGPipe: Fatal{UnmigratedVerb, \"ServerSession::ProducerDoorbell\"} - transport "
|
||||
"role %u has no doorbell pair yet; that is P6's SocketTransport",
|
||||
static_cast<unsigned>(m_transport->Role()));
|
||||
std::abort();
|
||||
}
|
||||
|
||||
Transport::SessionSegments& ServerSession::Shm() { return m_shm; }
|
||||
Transport::SessionConsumer& ServerSession::Consumer() { return m_consumer; }
|
||||
Transport::EventRingProducer& ServerSession::Events() { return m_events; }
|
||||
Transport::ITransport* ServerSession::Control_Plane() { return m_transport; }
|
||||
|
||||
void ServerSession::PublishEvents() {
|
||||
if (!m_accepted) {
|
||||
return;
|
||||
}
|
||||
// Publish, THEN ring - the same order as the forward direction, and the session picks
|
||||
// the bell so that no caller can pair the right ring with the wrong flag.
|
||||
m_events.Ring().Publish();
|
||||
m_consumer.NotifyClient();
|
||||
}
|
||||
|
||||
// Both of these advance AND ring, through SessionConsumer. The free functions in namespace
|
||||
// Watermark do not ring: a client parked in WaitForPresentAck(kWaitForever) needs the pair.
|
||||
void ServerSession::AdvanceCompletedFrame(Uint64 serial) {
|
||||
if (!m_accepted) {
|
||||
return;
|
||||
}
|
||||
m_consumer.CompleteFrame(serial);
|
||||
}
|
||||
|
||||
void ServerSession::ReturnPresentCredit(Uint64 serial) {
|
||||
if (!m_accepted) {
|
||||
return;
|
||||
}
|
||||
m_consumer.ReturnPresentCredit(serial);
|
||||
}
|
||||
|
||||
Transport::RoleMemorySample ServerSession::SampleMemory() const {
|
||||
return Transport::SampleRoleMemory(Transport::MemoryRole::Server);
|
||||
}
|
||||
|
||||
void ServerSession::LogMemory(const char* phase) const {
|
||||
Transport::LogRoleMemory(phase, SampleMemory());
|
||||
}
|
||||
|
||||
} // namespace MobileGL::MG_Remote::Server
|
||||
|
||||
@@ -12,13 +12,32 @@
|
||||
// The four segment sizes are already pinned by ProtocolSmokeTest.cpp:72 and are not up for
|
||||
// re-derivation here: SEG_CMD 8 MiB, SEG_STAGE 32 MiB, SEG_REPLY 8 MiB, SEG_EVENT 256 KiB.
|
||||
// MOBILEGL_IPC_RING_MB and MOBILEGL_IPC_STAGE_MB move the first two; the ring caps ONE record
|
||||
// at half its size, so the default 8 MiB caps a record at 4 MiB (R-10).
|
||||
// at half its size (R-10). See SessionRings.h's header for why the ring inside SEG_CMD is 4 MiB
|
||||
// rather than 8 - the control page takes the head and the capacity must be a power of two -
|
||||
// and why that deviation from CONTRACT-P5 §5's arithmetic is in the safe direction.
|
||||
//
|
||||
// THE TWO DOORBELL ACCESSORS ARE ON THE CONCRETE CLASS, NOT ON ITransport
|
||||
// (InProcessTransport.h:64-68). P5 decides this now rather than letting P6 discover it: the
|
||||
// SESSION owns the pair and hands out references, so ITransport stays the dumb control-plane
|
||||
// interface its header says it is and SocketTransport does not have to grow two accessors it
|
||||
// has no natural home for. Discovering this in P6 would mean re-laying one package's call sites.
|
||||
//
|
||||
// WHO CREATES THE SEGMENTS: this side. Welcome announces all four SegmentRefs and Welcome is
|
||||
// server -> client, so the server allocates and the client attaches. "Client-owned" in
|
||||
// protocol.fbs's comments is about who WRITES a segment, not who allocates it.
|
||||
//
|
||||
// WHAT Accept() DOES, IN ORDER. The ABI assertion is FIRST, before a single record is decoded
|
||||
// and before any segment exists, because its whole purpose is to refuse to interpret the peer's
|
||||
// bytes at all:
|
||||
// 1. receive Hello;
|
||||
// 2. compare abiMajor/abiMinor and CapsAbiFingerprint() - Fatal{AbiMismatch} on a difference,
|
||||
// never a downgrade;
|
||||
// 3. create and map the four segments, initialise both control pages, clear the reply pool;
|
||||
// 4. send Welcome with the four SegmentRefs;
|
||||
// 5. publish the first CapsSnapshot, IF a backend has been handed over (SetBackend). Without
|
||||
// one the session is accepted and the snapshot is deferred with a loud line: the caps
|
||||
// blob codecs are w1's and the server's private BackendObject is v1's, and a session that
|
||||
// refused to exist until both landed would block every other package's bring-up.
|
||||
|
||||
#pragma once
|
||||
#include <Includes.h>
|
||||
@@ -26,8 +45,12 @@
|
||||
#include <MG_Pipe/MGPipe.h>
|
||||
|
||||
#include "../Transport/Doorbell.h"
|
||||
#include "../Transport/EventRing.h"
|
||||
#include "../Transport/ITransport.h"
|
||||
#include "../Transport/ReplySlot.h"
|
||||
#include "../Transport/Ring.h"
|
||||
#include "../Transport/RoleMemory.h"
|
||||
#include "../Transport/SessionRings.h"
|
||||
#include "../Wire/PipeWireCodec.h"
|
||||
#include "PipeApplier.h"
|
||||
|
||||
@@ -37,6 +60,8 @@ namespace MobileGL::MG_Remote::Server {
|
||||
public:
|
||||
static ServerSession* Active();
|
||||
|
||||
~ServerSession();
|
||||
|
||||
// Maps the four segments, answers Hello with Welcome, and publishes the first
|
||||
// CapsSnapshot. The ABI assertion (CapsCodec.h) happens HERE, before a single record is
|
||||
// decoded: sizeof(DynamicBackendParameters), sizeof(MGPCaps), sizeof(GLFunctionsTable)
|
||||
@@ -62,11 +87,111 @@ namespace MobileGL::MG_Remote::Server {
|
||||
// cache line otherwise burns a big core for a whole frame on a phone).
|
||||
Transport::Doorbell& ProducerDoorbell();
|
||||
|
||||
// ---- s1's additions beyond c0's signature block ---------------------------------
|
||||
|
||||
// The sizes to create the segments with. Must be called before Accept; after it, the
|
||||
// geometry is on the wire in Welcome and changing it would desynchronise the peer.
|
||||
void SetSegmentSizes(const Transport::SessionSegmentSizes& sizes);
|
||||
|
||||
// The server role's private BackendObject (ServerLoop::Backend(), v1's). It is NOT
|
||||
// pActiveBackendObject - that global holds the client's BackendObject_Remote (table 3).
|
||||
// Set before Accept to have the first CapsSnapshot published there; set later and call
|
||||
// PublishCapsSnapshot yourself.
|
||||
void SetBackend(MG_Backend::BackendObject* backend);
|
||||
|
||||
// MGPCaps::CallMask's two halves. BOTH ARE MANDATORY AND NEITHER HAS A DEFAULT.
|
||||
//
|
||||
// The first version of this file derived a default for each. That was the phase's
|
||||
// marquee defect committed from the server's side: the consumer default read
|
||||
// MGPipeGetResourceOps(), a PROCESS-WIDE global (PipeApply.cpp), so under inproc the
|
||||
// server answered with whatever the client half of the same process had registered,
|
||||
// and under spawn it collapsed to P2's 0x7f. Either way CapsMirror::ServerConsumes
|
||||
// then answers a client-side liveness gate with a guess: the client stops emitting
|
||||
// five P4a families, CLEARS ITS DIRTY FLAGS ON ACCEPTANCE ANYWAY, and the lane goes
|
||||
// green with the uploads lost - ID-39's 66 lost uploads, reflected. R-8's whole point
|
||||
// is that a client-side gate may never be answered by a server-side fact; a
|
||||
// server-side gate answered by a PROCESS-wide fact is the same defect one level down.
|
||||
//
|
||||
// So there is no derivation at all. An unset mask is a programming error and
|
||||
// CallMask() is a named Fatal on one - loud at the first snapshot instead of silent
|
||||
// for a phase. Flagging it in a report was not a mechanism; this is.
|
||||
//
|
||||
// BITS 0..8, THE MGPCapBit FEATURE BITS. What each one answers belongs to the package
|
||||
// that owns the question (kCapTimerQuery to the query family, kCapResidentSubData to
|
||||
// b1, and so on). `SetCapabilityBits(0)` is a legitimate and explicit answer - "this
|
||||
// server offers no optional capability" - and is the right call while those packages
|
||||
// land. kCapNeedsHostIndexBytes / kCapNeedsHostUboBytes must stay 0 for the whole of
|
||||
// P5 by ruling (CONTRACT-P5 table 0): they are the only two things that ask for an
|
||||
// MGHostSpan, and 0 is what keeps every one of them out of the first IPC frame.
|
||||
void SetCapabilityBits(Uint64 capBits);
|
||||
|
||||
// BITS 32..47, THE CONSUMER MASK (R-8 / C-4): which MGPipe subsystems this server has
|
||||
// a consumer for. v1 owns the answer - it owns the apply thread and knows what its
|
||||
// backend took over. Publishing a bit the server does not consume is the failure
|
||||
// above; withholding one the server does consume merely leaves the legacy pull path
|
||||
// running, which is the safe direction.
|
||||
void SetConsumedSubsystems(Uint64 subsystemMask);
|
||||
|
||||
// False until BOTH setters have been called. A caller that can handle the absence
|
||||
// asks this; PublishCapsSnapshot and CallMask abort on it.
|
||||
Bool CallMaskIsSet() const;
|
||||
|
||||
// What PublishCapsSnapshot puts on the wire: capBits | MGCapsConsumerBits(subsystems).
|
||||
// Fatal{UnsetCallMask} if either half was never set.
|
||||
Uint64 CallMask() const;
|
||||
|
||||
Bool Accepted() const;
|
||||
// Teardown: after the apply thread has been joined, never before - a record still in
|
||||
// flight can still resolve a segment offset (table 3's fourth column).
|
||||
void Close();
|
||||
|
||||
Transport::SessionSegments& Shm();
|
||||
// The apply loop's end of the rings: WaitForWork / ApplyOne / RetireThrough. This is
|
||||
// the only thing that advances appliedSeq, and it advances it by exactly one per
|
||||
// record (R-9's ban on batching it while the verb barrier exists).
|
||||
Transport::SessionConsumer& Consumer();
|
||||
// The reverse channel. P5 only has to be able to CARRY OnBufferWriteback /
|
||||
// OnGpuWritten / OnSurfaceChanged; the overflow policy is P9's.
|
||||
Transport::EventRingProducer& Events();
|
||||
// Publish everything reserved on SEG_EVENT and ring the client. USE THIS rather than
|
||||
// EventRingProducer::PublishAndNotify, which takes a bell and a park flag from its
|
||||
// caller and therefore compiles for every wrong pairing; the session is the thing
|
||||
// that knows which bell belongs to the client.
|
||||
void PublishEvents();
|
||||
Transport::ITransport* Control_Plane();
|
||||
|
||||
// completedFrameSerial / presentAckSerial: the two watermarks only the server can
|
||||
// advance, kept together with the other three rather than poked into RingControl from
|
||||
// whatever code happens to notice a present finished.
|
||||
void AdvanceCompletedFrame(Uint64 serial);
|
||||
void ReturnPresentCredit(Uint64 serial);
|
||||
|
||||
// Peak-RSS accounting for t1 (RoleMemory.h). `phase` is a short tag.
|
||||
Transport::RoleMemorySample SampleMemory() const;
|
||||
void LogMemory(const char* phase) const;
|
||||
|
||||
private:
|
||||
Transport::RingConsumer m_commands;
|
||||
Wire::SegmentTable m_segments;
|
||||
PipeApplier m_applier;
|
||||
ReplyPool m_replies;
|
||||
|
||||
Transport::SessionSegments m_shm;
|
||||
Transport::SessionConsumer m_consumer;
|
||||
Transport::EventRingProducer m_events;
|
||||
Transport::ITransport* m_transport = nullptr;
|
||||
MG_Backend::BackendObject* m_backend = nullptr;
|
||||
Transport::SessionSegmentSizes m_sizes;
|
||||
Uint64 m_capBits = 0;
|
||||
Uint64 m_consumedSubsystems = 0;
|
||||
Bool m_capBitsSet = false;
|
||||
Bool m_consumedSet = false;
|
||||
Bool m_sizesSet = false;
|
||||
Bool m_accepted = false;
|
||||
};
|
||||
|
||||
// Leak-at-exit like every other MG_Remote singleton (ID-8): no frontend destructor may
|
||||
// reach pipe or backend state from an exit handler.
|
||||
ServerSession& ServerSessionInstance();
|
||||
|
||||
} // namespace MobileGL::MG_Remote::Server
|
||||
|
||||
@@ -0,0 +1,195 @@
|
||||
// MobileGL - MobileGL/MG_Remote/Server/StagedShadow.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
|
||||
|
||||
// R-11 - THE SERVER'S OWN COPY OF THE STAGED BYTES. Owner: package v1.
|
||||
//
|
||||
// GLESBufferResource::hostBytes (Managers.h:839) is the tree's ONE violation of rule C ("an
|
||||
// applier entry point may not hold a pointer past its return"): Ops_H_SubData (Managers.cpp:
|
||||
// 1980-1983) and Ops_H_FlushRange (:2035) record the client's shadow base and six later drains
|
||||
// read it (:2000, :2062, :2080, :2111, :2741, :2843). In monolith that is correct - the bytes
|
||||
// belong to a frontend object that outlives the call. Under split the pointer names SEG_STAGE,
|
||||
// which is valid only until retiredSeq passes the record that named it, and w1's
|
||||
// MOBILEGL_IPC_AUDIT=1 fills retired staging bytes with 0xDD precisely so an implementation
|
||||
// that kept the pointer is DISTINGUISHABLE from one that copied. So this copies.
|
||||
//
|
||||
// THE SNAPSHOT EXTENT IS EXACTLY WHAT THE RECORD DECLARED, NEVER WIDENED (the integrator's
|
||||
// ruling on b1's open M-6 half). Widening looked free once before and was not: a page-aligned
|
||||
// INVALIDATE_RANGE clobbered GPU-written data - an SSBO counter beside the app's SubData - with
|
||||
// stale shadow bytes (Managers.cpp:1126-1129). Tier 1's INVALIDATE_RANGE is an ASSERTION that
|
||||
// the old bytes are dead, so declaring bytes covered that nothing staged is not a missing
|
||||
// optimisation, it is a silent data loss. The coverage set below is therefore exact, and a
|
||||
// drain that reaches outside it is Fatal rather than a re-read of whatever happens to be there.
|
||||
//
|
||||
// WHY IT IS A HEADER AND NOT A BLOCK INSIDE Managers.cpp. Two reasons, and the second is the
|
||||
// one that matters. Managers.h is package b1's, so v1's R-11 edit may not add a member to
|
||||
// GLESBufferResource and the storage has to live beside it rather than in it. And a block
|
||||
// inside Managers.cpp could only ever be exercised by a test that also has a GL context, a
|
||||
// resource twin and a live session - which is exactly how a rule ends up with no check that
|
||||
// can fail for its own reason (R-16). Here, CopiesIntoServerStorage is a parameter rather than
|
||||
// a read of MG_Config::Transport, so a unit case builds one store of each kind and asserts the
|
||||
// DIFFERENCE between them.
|
||||
|
||||
#pragma once
|
||||
#include <Includes.h>
|
||||
|
||||
#include <MG_Util/Debug/Log.h>
|
||||
#include <MG_Util/Math/VectorTypes.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <mutex>
|
||||
|
||||
namespace MobileGL::MG_Remote::Server {
|
||||
|
||||
// Keyed by the resource twin's ADDRESS, which is stable: the twins are heap-allocated and
|
||||
// held by SharedPtr in the backend slot table, and every event that ends a base's life -
|
||||
// an orphaning respecify, a successful map_persistent, destroy, context death - already has
|
||||
// a call site in Managers.cpp to drop it from.
|
||||
class StagedShadowStore {
|
||||
public:
|
||||
// `copies` is "this process is really split". False reproduces the monolith expression
|
||||
// character for character (`raw - offset`), which is what keeps every push and verify
|
||||
// lane byte-identical to what it was before R-11.
|
||||
explicit StagedShadowStore(Bool copies) : m_copies(copies) {}
|
||||
|
||||
Bool CopiesIntoServerStorage() const { return m_copies; }
|
||||
|
||||
// Copies [offset, offset+size) of the record's staged bytes into server-owned storage
|
||||
// and returns the SERVER base (offset 0 of the resource). Under monolith it returns the
|
||||
// client base unchanged and allocates nothing.
|
||||
const Uint8* Adopt(const void* key, SizeT width, const void* bytes, SizeT offset, SizeT size) {
|
||||
const auto* raw = static_cast<const Uint8*>(bytes);
|
||||
if (!m_copies) return raw - offset;
|
||||
const std::lock_guard<std::mutex> lock(m_mutex);
|
||||
Shadow& shadow = m_shadows[key];
|
||||
const SizeT needed = std::max<SizeT>(width, offset + size);
|
||||
if (shadow.Bytes.size() < needed) shadow.Bytes.resize(needed, 0);
|
||||
if (size != 0 && raw != nullptr) {
|
||||
std::memcpy(shadow.Bytes.data() + offset, raw, size);
|
||||
CoverageAdd(shadow.Covered, offset, offset + size);
|
||||
}
|
||||
m_any.store(true, std::memory_order_release);
|
||||
// Growing REALLOCATES, so every caller assigns the returned base to hostBytes on
|
||||
// the same call. No other resource's base moves: each Shadow owns its own vector,
|
||||
// and a rehash of the map MOVES that vector, which preserves its data pointer.
|
||||
return shadow.Bytes.data();
|
||||
}
|
||||
|
||||
void Drop(const void* key) {
|
||||
if (!m_any.load(std::memory_order_acquire)) return;
|
||||
const std::lock_guard<std::mutex> lock(m_mutex);
|
||||
m_shadows.erase(key);
|
||||
}
|
||||
|
||||
void DropAll() {
|
||||
if (!m_any.load(std::memory_order_acquire)) return;
|
||||
const std::lock_guard<std::mutex> lock(m_mutex);
|
||||
m_shadows.clear();
|
||||
}
|
||||
|
||||
// Fatal when a drain reaches bytes no record staged. It fires ONLY for a base that is
|
||||
// this key's server shadow: the legacy arm passes the frontend object's own
|
||||
// MappedData(), which is valid for the whole store and is not this rule's subject.
|
||||
void RequireCoverage(const void* key, const Uint8* hostBase, SizeT start, SizeT end,
|
||||
const char* site) const {
|
||||
if (!m_any.load(std::memory_order_acquire) || hostBase == nullptr) return;
|
||||
const std::lock_guard<std::mutex> lock(m_mutex);
|
||||
const auto it = m_shadows.find(key);
|
||||
if (it == m_shadows.end() || it->second.Bytes.data() != hostBase) return;
|
||||
if (CoverageHas(it->second.Covered, start, end)) return;
|
||||
MGLOG_F("MGPipe: Fatal{StageSnapshotTooNarrow, \"%s\"} - the server's ladder wants "
|
||||
"[%zu, %zu) of a buffer whose staged coverage does not include it. Under "
|
||||
"split the authoritative shadow is SERVER-OWNED (rule C) and "
|
||||
"resource_subdata is the only way bytes reach it, so bytes outside a staged "
|
||||
"range have never existed on this side. Re-reading them would move zeroes "
|
||||
"into the store, and an INVALIDATE_RANGE over them would declare live "
|
||||
"GPU-written bytes dead (Managers.cpp:1126-1129). This is a missing record, "
|
||||
"not a missing widening",
|
||||
site, start, end);
|
||||
std::abort();
|
||||
}
|
||||
|
||||
// Diagnostics the unit cases read, so that a check can assert WHAT HAPPENED rather than
|
||||
// that nothing blew up.
|
||||
Bool IsCovered(const void* key, SizeT start, SizeT end) const {
|
||||
const std::lock_guard<std::mutex> lock(m_mutex);
|
||||
const auto it = m_shadows.find(key);
|
||||
if (it == m_shadows.end()) return false;
|
||||
return CoverageHas(it->second.Covered, start, end);
|
||||
}
|
||||
SizeT CoveredRunCount(const void* key) const {
|
||||
const std::lock_guard<std::mutex> lock(m_mutex);
|
||||
const auto it = m_shadows.find(key);
|
||||
return it == m_shadows.end() ? 0 : it->second.Covered.size();
|
||||
}
|
||||
SizeT TrackedResources() const {
|
||||
const std::lock_guard<std::mutex> lock(m_mutex);
|
||||
return m_shadows.size();
|
||||
}
|
||||
|
||||
// Is there STILL a live shadow for this key? The m-5 discriminator: after DropAll (context
|
||||
// loss) the key is erased, so a twin's cached hostBytes names freed memory and must be
|
||||
// nulled; after an ordinary Adopt the key is present and its base is live. The
|
||||
// generation-reset block runs on a twin's FIRST ensure too (the generation starts
|
||||
// mismatched), and there the shadow a preceding subdata just staged is present - so nulling
|
||||
// must key on THIS answer, not on the generation change alone, or the reduced path drops
|
||||
// its own bytes.
|
||||
Bool HasShadow(const void* key) const {
|
||||
if (!m_any.load(std::memory_order_acquire)) return false;
|
||||
const std::lock_guard<std::mutex> lock(m_mutex);
|
||||
return m_shadows.find(key) != m_shadows.end();
|
||||
}
|
||||
|
||||
// Adjacent ranges merge - there is no gap between them, so the union really is one run.
|
||||
// Ranges with a gap do NOT merge, and that is the whole mechanism: it is what makes a
|
||||
// missing record detectable instead of papered over.
|
||||
static void CoverageAdd(Vector<Range1D>& covered, SizeT start, SizeT end) {
|
||||
if (start >= end) return;
|
||||
Vector<Range1D> merged;
|
||||
merged.reserve(covered.size() + 1);
|
||||
SizeT s = start;
|
||||
SizeT e = end;
|
||||
for (const auto& range : covered) {
|
||||
if (range.end < s || range.start > e) {
|
||||
merged.push_back(range);
|
||||
continue;
|
||||
}
|
||||
s = std::min(s, range.start);
|
||||
e = std::max(e, range.end);
|
||||
}
|
||||
merged.push_back({s, e});
|
||||
std::sort(merged.begin(), merged.end(),
|
||||
[](const Range1D& a, const Range1D& b) { return a.start < b.start; });
|
||||
covered = std::move(merged);
|
||||
}
|
||||
|
||||
static Bool CoverageHas(const Vector<Range1D>& covered, SizeT start, SizeT end) {
|
||||
if (start >= end) return true;
|
||||
for (const auto& range : covered) {
|
||||
if (range.start <= start && end <= range.end) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private:
|
||||
struct Shadow {
|
||||
Vector<Uint8> Bytes;
|
||||
// Sorted, disjoint, EXACT.
|
||||
Vector<Range1D> Covered;
|
||||
};
|
||||
|
||||
const Bool m_copies;
|
||||
mutable std::mutex m_mutex;
|
||||
ska::flat_hash_map<const void*, Shadow> m_shadows;
|
||||
// Read on every UploadRangeFrom, so the monolith cost is one acquire load of a
|
||||
// never-written flag rather than a mutex and a hash lookup.
|
||||
std::atomic<Bool> m_any{false};
|
||||
};
|
||||
|
||||
} // namespace MobileGL::MG_Remote::Server
|
||||
@@ -0,0 +1,205 @@
|
||||
// MobileGL - MobileGL/MG_Remote/Transport/EventRing.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
|
||||
|
||||
// SEG_EVENT: the server -> client reverse channel. Owner: package s1.
|
||||
//
|
||||
// WHAT P5 OWES HERE AND NOTHING MORE (BRIEF R-12, and s1's brief): it must be
|
||||
// able to CARRY OnBufferWriteback, OnGpuWritten and OnSurfaceChanged. The other
|
||||
// seven MGPipeCallbacks members are off P5's reduced path, and THE OVERFLOW
|
||||
// POLICY IS P9's - what is here is the mechanism (a full ring latches
|
||||
// eventRingFull, a lossy post that is dropped counts in eventDropped) and not a
|
||||
// policy that decides between them.
|
||||
//
|
||||
// IT IS A SECOND RingControl, NOT A THIRD CURSOR SET. RingControl carries two
|
||||
// cursor triples (SEG_CMD and SEG_STAGE) and adding a third would resize the
|
||||
// shared page that Ring.h static_asserts at exactly 4096 bytes. So SEG_EVENT
|
||||
// gets its OWN control page at its own head and drives it with the Cmd cursor
|
||||
// set - the same RingProducer/RingConsumer code, in the opposite direction. The
|
||||
// two EVENT FLAGS still live in the SEG_CMD page, because that is where Ring.h
|
||||
// declares them and where the client's own waits already look.
|
||||
//
|
||||
// THE PAYLOAD SHAPES ARE FIXED-WIDTH AND LIVE HERE, not in MG_Pipe's headers.
|
||||
// Nothing under Transport/ may reach MobileGL/Includes.h (WireLog.h:9-24, and
|
||||
// the purity gate's `wire-header` probe), so MGPipeHandle / MGPRange /
|
||||
// MGPSurfaceInfo cannot be named in this file. The wire shapes below mirror them
|
||||
// field for field and the SESSIONS assert the two agree, which is the same
|
||||
// discipline the rest of the wire is held to: a wire struct is fixed-width, and
|
||||
// the conversion happens where the frontend types are legal.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "Doorbell.h"
|
||||
#include "Ring.h"
|
||||
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
|
||||
namespace MobileGL::MG_Remote::Transport {
|
||||
|
||||
// Record kinds on SEG_EVENT. 0 is kRingPadRecordKind and can never be an
|
||||
// event, which is why the list starts at 1.
|
||||
enum EventKind : std::uint16_t {
|
||||
kEventNone = 0,
|
||||
kEventBufferWriteback = 1, // MGPipeCallbacks::OnBufferWriteback
|
||||
kEventGpuWritten = 2, // MGPipeCallbacks::OnGpuWritten
|
||||
kEventSurfaceChanged = 3, // MGPipeCallbacks::OnSurfaceChanged
|
||||
};
|
||||
|
||||
// The 8-byte {slot, gen} pair, mirrored (MGPipeHandles.h:54-65).
|
||||
struct EventHandle {
|
||||
std::uint32_t Slot;
|
||||
std::uint32_t Gen;
|
||||
};
|
||||
static_assert(sizeof(EventHandle) == 8, "the handle is the 8-byte {slot, gen} pair");
|
||||
|
||||
// MGPRange, mirrored (MGPipeTypes.h:63-67).
|
||||
struct EventRange {
|
||||
std::uint64_t Offset;
|
||||
std::uint64_t Size;
|
||||
};
|
||||
static_assert(sizeof(EventRange) == 16, "MGPRange is 16 bytes on the wire");
|
||||
|
||||
// OnBufferWriteback(res, offset, MGPBlobRef bytes). The bytes follow this
|
||||
// head INSIDE THE RECORD: the blobref the client hands the frontend names
|
||||
// SEG_EVENT and the in-segment offset of those inline bytes, which is what
|
||||
// makes "the destination is the client's shadow" (contract table 1 row 22)
|
||||
// reachable without a second segment. `Size` is therefore the record's own
|
||||
// tail length and is cross-checked against it.
|
||||
struct EventBufferWritebackHead {
|
||||
EventHandle Resource;
|
||||
std::uint64_t Offset; // destination offset inside the resource
|
||||
std::uint64_t Size; // inline byte count that follows
|
||||
};
|
||||
static_assert(sizeof(EventBufferWritebackHead) == 24, "wire shape");
|
||||
|
||||
// OnGpuWritten(res, rangeCount, ranges). EventRange[RangeCount] follows.
|
||||
struct EventGpuWrittenHead {
|
||||
EventHandle Resource;
|
||||
std::uint32_t RangeCount;
|
||||
std::uint32_t Pad0;
|
||||
};
|
||||
static_assert(sizeof(EventGpuWrittenHead) == 16, "wire shape");
|
||||
|
||||
// OnSurfaceChanged(const MGPSurfaceInfo*), mirrored (MGPipeTypes.h:1394-1401).
|
||||
struct EventSurfaceChangedHead {
|
||||
std::uint32_t Width;
|
||||
std::uint32_t Height;
|
||||
std::uint32_t InternalFormat;
|
||||
std::uint16_t Samples;
|
||||
std::uint16_t Layers;
|
||||
std::uint8_t IsDefault;
|
||||
std::uint8_t Pad0[7];
|
||||
};
|
||||
static_assert(sizeof(EventSurfaceChangedHead) == 24, "MGPSurfaceInfo is 24 bytes on the wire");
|
||||
|
||||
// The server's end. One producer: the apply thread, by construction.
|
||||
class EventRingProducer {
|
||||
public:
|
||||
EventRingProducer() = default;
|
||||
|
||||
// `eventControl` is SEG_EVENT's own control page; `cmdControl` is the
|
||||
// SEG_CMD page, because Ring.h declares eventRingFull / eventDropped
|
||||
// there and the client's waits already look at it.
|
||||
EventRingProducer(RingControl* eventControl, RingControl* cmdControl, void* base,
|
||||
std::uint64_t capacityBytes)
|
||||
: m_cmdControl(cmdControl),
|
||||
m_producer(eventControl, base, capacityBytes, RingCursorSet::Cmd) {}
|
||||
|
||||
bool Valid() const { return m_producer.Valid() && m_cmdControl != nullptr; }
|
||||
|
||||
// Reserves one event record. nullptr means the ring is full: the caller
|
||||
// decides, and the two flags are how it says which decision it took.
|
||||
// THIS FUNCTION DOES NOT DECIDE - that is P9's.
|
||||
void* Reserve(EventKind kind, std::uint64_t payloadBytes) {
|
||||
void* slot = m_producer.Reserve(static_cast<std::uint16_t>(kind), kRecNone, payloadBytes);
|
||||
if (slot == nullptr && m_cmdControl != nullptr) {
|
||||
// "SEG_EVENT full, server stopped applying" - Ring.h:123. Latched
|
||||
// here, cleared by the consumer once it has drained.
|
||||
m_cmdControl->eventRingFull.store(1, std::memory_order_release);
|
||||
}
|
||||
return slot;
|
||||
}
|
||||
|
||||
// For a LOSSY event the caller could not place. Lossless events must
|
||||
// never call this; they wait for the client to drain instead.
|
||||
void CountDrop() {
|
||||
if (m_cmdControl != nullptr) {
|
||||
m_cmdControl->eventDropped.fetch_add(1, std::memory_order_relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
// Publish, THEN ring - the same order as the forward direction, and for
|
||||
// the same reason (Doorbell.h:186-193: the fence only orders what
|
||||
// precedes it, so ringing first reopens the lost-wakeup window).
|
||||
void PublishAndNotify(Doorbell& clientBell, std::atomic<std::uint32_t>& producerParked) {
|
||||
m_producer.Publish();
|
||||
NotifyIfParked(clientBell, producerParked);
|
||||
}
|
||||
|
||||
RingProducer& Ring() { return m_producer; }
|
||||
|
||||
private:
|
||||
RingControl* m_cmdControl = nullptr;
|
||||
RingProducer m_producer;
|
||||
};
|
||||
|
||||
// The client's end. One consumer: the GL thread, which drains between verbs.
|
||||
class EventRingConsumer {
|
||||
public:
|
||||
EventRingConsumer() = default;
|
||||
|
||||
EventRingConsumer(RingControl* eventControl, RingControl* cmdControl, void* base,
|
||||
std::uint64_t capacityBytes, const void* segmentBase)
|
||||
: m_cmdControl(cmdControl),
|
||||
m_consumer(eventControl, base, capacityBytes, RingCursorSet::Cmd),
|
||||
m_segmentBase(static_cast<const std::uint8_t*>(segmentBase)) {}
|
||||
|
||||
bool Valid() const { return m_consumer.Valid() && m_cmdControl != nullptr; }
|
||||
|
||||
bool Pop(RingRecordView& out, bool* outCorrupt = nullptr) {
|
||||
return m_consumer.Pop(out, outCorrupt);
|
||||
}
|
||||
|
||||
// Release the bytes and clear the full latch. Only after the caller has
|
||||
// finished with every payload pointer it popped: a writeback's bytes live
|
||||
// in the ring itself, so retiring early is the R-11 violation one level
|
||||
// down.
|
||||
void Drained() {
|
||||
m_consumer.PublishRetired();
|
||||
if (m_cmdControl != nullptr) {
|
||||
m_cmdControl->eventRingFull.store(0, std::memory_order_release);
|
||||
}
|
||||
}
|
||||
|
||||
// Byte offset of `payload` inside SEG_EVENT, which is what an
|
||||
// OnBufferWriteback MGPBlobRef must carry (Seg = kSegEvent, Offset =
|
||||
// this, Size = the head's Size). Never a host address - R-2's rule B.
|
||||
std::uint64_t OffsetInSegment(const void* payload) const {
|
||||
return static_cast<std::uint64_t>(static_cast<const std::uint8_t*>(payload) -
|
||||
m_segmentBase);
|
||||
}
|
||||
|
||||
std::uint64_t DroppedEvents() const {
|
||||
return m_cmdControl == nullptr
|
||||
? 0
|
||||
: m_cmdControl->eventDropped.load(std::memory_order_relaxed);
|
||||
}
|
||||
bool RingIsFull() const {
|
||||
return m_cmdControl != nullptr &&
|
||||
m_cmdControl->eventRingFull.load(std::memory_order_acquire) != 0;
|
||||
}
|
||||
|
||||
RingConsumer& Ring() { return m_consumer; }
|
||||
|
||||
private:
|
||||
RingControl* m_cmdControl = nullptr;
|
||||
RingConsumer m_consumer;
|
||||
const std::uint8_t* m_segmentBase = nullptr;
|
||||
};
|
||||
|
||||
} // namespace MobileGL::MG_Remote::Transport
|
||||
@@ -0,0 +1,329 @@
|
||||
// MobileGL - MobileGL/MG_Remote/Transport/ReplySlot.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
|
||||
|
||||
// SEG_REPLY: the slot pool the server writes a kReplySlot answer into, and the
|
||||
// client reads it back out of. Owner: package s1.
|
||||
//
|
||||
// THE ID IS THE RECORD SEQUENCE NUMBER (P5 R-3). There is no second id space and
|
||||
// no allocator: the ten kReplySlot calls carry no MGPReplySlot in their payloads
|
||||
// (that is why the id has to be DERIVED rather than carried), the wire has no
|
||||
// per-record seq field (ARCHITECTURE.md:124), so the record's ordinal IS its
|
||||
// reply-slot id. The slot is addressed `seq % slotCount` and the server STAMPS
|
||||
// THE SEQ BACK INTO THE SLOT HEADER, which is what makes a wrong-slot read
|
||||
// detectable rather than merely plausible. Seq is 1-based; 0 means "no record".
|
||||
//
|
||||
// THE SLOT HEADER IS CONTRACT-P5 TABLE 0's ROW, verbatim:
|
||||
// { Uint64 Seq; Int32 Status; Uint32 Size; } // 16 bytes, then the payload
|
||||
// Status: 0 = OK, 1 = DECLINED, 2 = ERROR
|
||||
//
|
||||
// DECLINED IS A REAL ANSWER, NOT A FAILURE. It is how MapPersistent says nullptr
|
||||
// (R-6) and how the four Bool acceptance entry points - ResourceCreate,
|
||||
// ResourceRespecify, ResourceSubData, SetTextureParams - say false (R-5). A
|
||||
// client that folds DECLINED into "the call failed" re-creates ID-39's 66 lost
|
||||
// uploads from the other side, and a client that folds it into OK accepts a
|
||||
// pointer the server never handed out.
|
||||
//
|
||||
// A REPLY LARGER THAN ONE SLOT IS FATAL, NOT CHUNKED, AND THE CLIENT SAYS SO
|
||||
// FIRST (ID-47). P5's only large answer is ReadPixels, and the client knows its
|
||||
// size before it emits the record, so it refuses an oversize read BY NAME before
|
||||
// emission (RequireReadPixelsFits: Fatal{ReplyTooLarge, "ReadPixels <w>x<h>
|
||||
// <format> <bytes> > <cap>"}); Post's own refusal is the server's last line of
|
||||
// defence, and reaching it means the two sides disagree about the frame rather
|
||||
// than that the pool is too small. Chunking is a P6 debt; the pool has no knob.
|
||||
//
|
||||
// ORDERING. The client only looks at a slot after it has seen
|
||||
// RingControl::appliedSeq >= its own seq with an ACQUIRE load, and the server
|
||||
// advances appliedSeq with a RELEASE store AFTER posting the reply
|
||||
// (PipeApplier::ApplyOne's order: decode -> stamp -> apply -> post -> advance).
|
||||
// That pair is what publishes the slot's bytes; the fences below are the
|
||||
// belt-and-braces for a caller - a unit test, or P9's async pool - that reads a
|
||||
// slot without going through appliedSeq first.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "WireLog.h"
|
||||
|
||||
#include <atomic>
|
||||
#include <cstdint>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
|
||||
// P9's account, named here rather than left to be rediscovered: the seq stamp
|
||||
// catches a sequence space drifted by anything that is NOT a multiple of
|
||||
// slotCount. A drift of exactly 8, 16, ... lands on the same slot with a matching
|
||||
// stamp and reads as this call's answer. Under R-1's verb barrier the in-flight
|
||||
// depth is one and a drift cannot open at all; P9 is what removes the barrier,
|
||||
// and it is what has to widen the stamp (a generation beside the seq) or bound
|
||||
// the drift some other way.
|
||||
|
||||
namespace MobileGL::MG_Remote::Transport {
|
||||
|
||||
// CONTRACT-P5 table 0, "reply slot header".
|
||||
struct ReplySlotHeader {
|
||||
std::uint64_t Seq; // the record ordinal, stamped back for self-check
|
||||
std::int32_t Status; // ReplyStatus
|
||||
std::uint32_t Size; // payload bytes following this header
|
||||
};
|
||||
static_assert(sizeof(ReplySlotHeader) == 16, "the reply slot header is 16 bytes on the wire");
|
||||
static_assert(alignof(ReplySlotHeader) == 8, "the reply slot header must not gain padding");
|
||||
|
||||
enum ReplyStatus : std::int32_t {
|
||||
kReplyStatusOk = 0,
|
||||
// Not an error. MapPersistent's nullptr and the four Bool acceptance
|
||||
// returns' `false` both arrive as this.
|
||||
kReplyStatusDeclined = 1,
|
||||
kReplyStatusError = 2,
|
||||
};
|
||||
|
||||
// Eight slots of a 16 MiB SEG_REPLY is 2 MiB per slot, and MaxReplyBytes() is
|
||||
// 2 MiB minus the 16-byte header = 2,097,136 bytes per answer (ID-47).
|
||||
//
|
||||
// Why eight and not sixty-four: while the verb barrier holds (R-1) the client
|
||||
// blocks at every verb boundary, so the in-flight depth is exactly ONE and
|
||||
// every extra slot buys nothing but a smaller maximum answer. The trade is
|
||||
// the other way round - fewer slots, bigger replies - and P5's only large
|
||||
// answer is a blocking ReadPixels. P9, which is what makes the pool
|
||||
// asynchronous, re-chooses this geometry with real depth to size it against.
|
||||
//
|
||||
// WHY 2 MiB AND NOT 1. The first version of this file said "1 MiB covers a
|
||||
// 512x512 RGBA8 read", and it did not: 512*512*4 is exactly 1 MiB and the
|
||||
// slot header takes 16 of those bytes, so Post refused it by sixteen. Worse,
|
||||
// the E2 retrace harness's snapshot is a full-surface GL_RGBA/GL_UNSIGNED_BYTE
|
||||
// read of OpenRA's 640x480 surface = 1,228,800 bytes through the interposer,
|
||||
// 17% over the old cap - Post would have aborted on the first snapshot the
|
||||
// day the client's ReadPixels emitter landed. Contract §2 row 23 says the
|
||||
// slot is "sized from the scenario's largest read rather than guessed";
|
||||
// 2 MiB is that size for every P5 exit-gate read (E2 is the largest at
|
||||
// 640x480). A 2400x1080 RGBA8 device surface is ~10.4 MB and is a P6 debt
|
||||
// (chunked readback or a dedicated readback carrier), recorded in the
|
||||
// ROADMAP by the integrator - the geometry here is not the place it is paid.
|
||||
inline constexpr std::uint32_t kDefaultReplySlotCount = 8;
|
||||
|
||||
// Slot 0 exists and is used: seq is 1-based, so seq % slotCount hits slot 0
|
||||
// on seq == slotCount, not on "no record".
|
||||
class ReplySlotPool {
|
||||
public:
|
||||
ReplySlotPool() = default;
|
||||
|
||||
// `base`/`sizeBytes` are SEG_REPLY's mapping. `slotCount` must be a power
|
||||
// of two - the addressing is a mask, and a non-power-of-two modulus on
|
||||
// the apply thread is a division in the reply path of every blocking
|
||||
// call. Anything else leaves Valid() false rather than half-working.
|
||||
ReplySlotPool(void* base, std::uint64_t sizeBytes, std::uint32_t slotCount) {
|
||||
if (base == nullptr || slotCount == 0 || (slotCount & (slotCount - 1)) != 0) {
|
||||
WireLogError("MG_Remote reply pool: rejected, slotCount %u must be a non-zero power "
|
||||
"of two over a non-null mapping",
|
||||
static_cast<unsigned>(slotCount));
|
||||
return;
|
||||
}
|
||||
const std::uint64_t slotBytes = sizeBytes / slotCount;
|
||||
if (slotBytes <= sizeof(ReplySlotHeader)) {
|
||||
WireLogError("MG_Remote reply pool: rejected, %llu bytes over %u slots leaves no "
|
||||
"room for a payload past the %llu byte slot header",
|
||||
static_cast<unsigned long long>(sizeBytes),
|
||||
static_cast<unsigned>(slotCount),
|
||||
static_cast<unsigned long long>(sizeof(ReplySlotHeader)));
|
||||
return;
|
||||
}
|
||||
// EVERY SLOT MUST START 8-ALIGNED. The header is written by one thread
|
||||
// and read by another; the fences below order the payload against the
|
||||
// stamp, but the stamp's own 8-byte Seq has to be untorn for the
|
||||
// wrong-slot self-check to mean anything, and that is only true while
|
||||
// it is naturally aligned. A geometry whose slotBytes is not a
|
||||
// multiple of 8 puts later slots on odd boundaries, so it is refused
|
||||
// here rather than left to a future caller to discover.
|
||||
if ((slotBytes % 8) != 0 ||
|
||||
(reinterpret_cast<std::uintptr_t>(base) % alignof(ReplySlotHeader)) != 0) {
|
||||
WireLogError("MG_Remote reply pool: rejected, a %llu byte slot at base alignment "
|
||||
"%llu would put a slot header on an unaligned address, and the seq "
|
||||
"stamp the wrong-slot check reads has to be untorn",
|
||||
static_cast<unsigned long long>(slotBytes),
|
||||
static_cast<unsigned long long>(
|
||||
reinterpret_cast<std::uintptr_t>(base) % alignof(ReplySlotHeader)));
|
||||
return;
|
||||
}
|
||||
m_base = static_cast<std::uint8_t*>(base);
|
||||
m_slots = slotCount;
|
||||
m_mask = slotCount - 1;
|
||||
// Truncated to 32 bits deliberately: the header's Size field is
|
||||
// 32-bit, so a slot no 32-bit count could describe would let a
|
||||
// legal-looking Size name bytes past the slot.
|
||||
m_slotBytes = slotBytes > 0xFFFFFFFFull ? 0xFFFFFFFFu
|
||||
: static_cast<std::uint32_t>(slotBytes);
|
||||
}
|
||||
|
||||
bool Valid() const { return m_base != nullptr; }
|
||||
std::uint32_t SlotCount() const { return m_slots; }
|
||||
std::uint32_t SlotBytes() const { return m_slotBytes; }
|
||||
// What a single answer may carry. The client checks against this BEFORE
|
||||
// it emits a ReadPixels, which is the whole reason a fixed slot size is
|
||||
// legitimate rather than a guess.
|
||||
std::uint32_t MaxReplyBytes() const {
|
||||
return m_slotBytes == 0 ? 0u
|
||||
: m_slotBytes - static_cast<std::uint32_t>(sizeof(ReplySlotHeader));
|
||||
}
|
||||
|
||||
// ID-47: THE CLIENT'S HALF of "a reply larger than one slot is fatal". True
|
||||
// exactly when an answer of `bytes` can be posted into this pool: the pool
|
||||
// is configured and `bytes <= MaxReplyBytes()`. The boundary is inclusive
|
||||
// and SessionTest pins it from both sides.
|
||||
bool CanHold(std::uint64_t bytes) const { return m_base != nullptr && bytes <= MaxReplyBytes(); }
|
||||
|
||||
// ID-47's named refusal, AT THE CLIENT, BEFORE EMISSION. Returns when the
|
||||
// answer fits; otherwise
|
||||
// Fatal{ReplyTooLarge, "ReadPixels <w>x<h> <format> <bytes> > <cap>"}
|
||||
// and abort. Never truncated, never chunked, and never a server-side
|
||||
// abort the client cannot name: Post's own refusal below stays as the
|
||||
// last line of defence, but it fires on the apply thread with the record
|
||||
// already on the wire, where the only thing the client sees is a hang.
|
||||
//
|
||||
// `format`/`type` are the GL enums the record carries (MGPReadbackInfo::
|
||||
// Format/Type), printed as the hex pair every pipe diagnostic uses; the
|
||||
// caller passes the byte count it computed for the record's DstSize, so
|
||||
// what is refused is exactly what would have been posted. This is the one
|
||||
// call c1's OnReadPixels emitter makes before EmitAndWait; the
|
||||
// ClientSession forwards it verbatim (RequireReadPixelsReplyFits).
|
||||
void RequireReadPixelsFits(std::uint32_t width, std::uint32_t height, std::uint32_t format,
|
||||
std::uint32_t type, std::uint64_t bytes) const {
|
||||
if (CanHold(bytes)) {
|
||||
return;
|
||||
}
|
||||
WireLogFatal("MGPipe: Fatal{ReplyTooLarge, \"ReadPixels %ux%u 0x%04X/0x%04X %llu > %u\"} - "
|
||||
"the answer does not fit one SEG_REPLY slot (%u slots of %u bytes, payload "
|
||||
"cap %u; a cap of 0 means no reply pool is configured). Refused at the "
|
||||
"client before emission (ID-47): P5 neither truncates nor chunks a reply, "
|
||||
"and a read larger than the cap is a P6 debt (chunked readback), not a "
|
||||
"bigger pool",
|
||||
static_cast<unsigned>(width), static_cast<unsigned>(height),
|
||||
static_cast<unsigned>(format), static_cast<unsigned>(type),
|
||||
static_cast<unsigned long long>(bytes),
|
||||
static_cast<unsigned>(MaxReplyBytes()), static_cast<unsigned>(m_slots),
|
||||
static_cast<unsigned>(m_slotBytes), static_cast<unsigned>(MaxReplyBytes()));
|
||||
}
|
||||
|
||||
// Zeroes every header, so a stale seq from a previous session cannot be
|
||||
// mistaken for this session's answer. Called on the server side at Accept.
|
||||
void Clear() {
|
||||
if (m_base == nullptr) {
|
||||
return;
|
||||
}
|
||||
for (std::uint32_t slot = 0; slot < m_slots; ++slot) {
|
||||
ReplySlotHeader header{};
|
||||
std::memcpy(m_base + static_cast<std::uint64_t>(slot) * m_slotBytes, &header,
|
||||
sizeof(header));
|
||||
}
|
||||
}
|
||||
|
||||
// Server side. `size` bytes of `bytes` become the answer for `seq`.
|
||||
// An answer larger than one slot is FATAL, never truncated and never
|
||||
// chunked - see the file header.
|
||||
void Post(std::uint64_t seq, std::int32_t status, const void* bytes, std::uint64_t size) {
|
||||
if (m_base == nullptr) {
|
||||
WireLogFatal("MG_Remote reply pool: Fatal{ProtocolCorruption} - Post(seq=%llu) on an "
|
||||
"unconfigured pool",
|
||||
static_cast<unsigned long long>(seq));
|
||||
}
|
||||
if (seq == 0) {
|
||||
WireLogFatal("MG_Remote reply pool: Fatal{ProtocolCorruption} - seq 0 is \"no "
|
||||
"record\" and can never name a slot (R-3: seq is 1-based)");
|
||||
}
|
||||
if (size > MaxReplyBytes()) {
|
||||
// The server's LAST line of defence, not the first: the client refuses an
|
||||
// oversize ReadPixels by name before it emits (RequireReadPixelsFits, ID-47),
|
||||
// so reaching this means the two sides disagree about the frame.
|
||||
WireLogFatal("MG_Remote reply pool: Fatal{ProtocolCorruption} - a %llu byte answer "
|
||||
"for seq %llu does not fit a %u byte slot (payload cap %u). P5 does "
|
||||
"not chunk replies: the client knows an answer's size before it emits "
|
||||
"the record, so this means the two sides disagree about the frame",
|
||||
static_cast<unsigned long long>(size),
|
||||
static_cast<unsigned long long>(seq), static_cast<unsigned>(m_slotBytes),
|
||||
static_cast<unsigned>(MaxReplyBytes()));
|
||||
}
|
||||
std::uint8_t* slot = SlotAt(seq);
|
||||
if (size != 0 && bytes != nullptr) {
|
||||
std::memcpy(slot + sizeof(ReplySlotHeader), bytes, static_cast<std::size_t>(size));
|
||||
}
|
||||
ReplySlotHeader header{};
|
||||
header.Seq = seq;
|
||||
header.Status = status;
|
||||
header.Size = static_cast<std::uint32_t>(size);
|
||||
// The payload must be visible before the stamp that says it is there.
|
||||
std::atomic_thread_fence(std::memory_order_release);
|
||||
std::memcpy(slot, &header, sizeof(header));
|
||||
}
|
||||
|
||||
// Client side. Returns false when the slot does not carry THIS seq - the
|
||||
// self-check the stamp exists for. `outBytes` may be null for an answer
|
||||
// with no payload (every DECLINE, and the four Bool acceptances).
|
||||
//
|
||||
// A payload larger than the caller's buffer is a caller bug rather than a
|
||||
// wire fault (the caller sized it from the call it made), so it returns
|
||||
// false with *outSize set to what was there, the ReceiveFrame shape.
|
||||
bool Read(std::uint64_t seq, void* outBytes, std::uint64_t outCapacity,
|
||||
std::int32_t* outStatus, std::uint64_t* outSize) const {
|
||||
if (outStatus != nullptr) {
|
||||
*outStatus = kReplyStatusError;
|
||||
}
|
||||
if (outSize != nullptr) {
|
||||
*outSize = 0;
|
||||
}
|
||||
if (m_base == nullptr || seq == 0) {
|
||||
return false;
|
||||
}
|
||||
const std::uint8_t* slot = SlotAt(seq);
|
||||
ReplySlotHeader header{};
|
||||
std::memcpy(&header, slot, sizeof(header));
|
||||
std::atomic_thread_fence(std::memory_order_acquire);
|
||||
if (header.Seq != seq) {
|
||||
// Not "retry": under the verb barrier the answer is already
|
||||
// there by the time appliedSeq passed this record, so a stamp
|
||||
// that disagrees is a drifted sequence space (R-9's kRecPad
|
||||
// rule) or a wrong-slot read, and both are faults.
|
||||
WireLogError("MG_Remote reply pool: slot %llu carries seq %llu, not %llu - the two "
|
||||
"sides' sequence spaces have drifted (a counted kRecPad, R-9) or the "
|
||||
"addressing disagrees",
|
||||
static_cast<unsigned long long>(seq & m_mask),
|
||||
static_cast<unsigned long long>(header.Seq),
|
||||
static_cast<unsigned long long>(seq));
|
||||
return false;
|
||||
}
|
||||
if (header.Size > MaxReplyBytes()) {
|
||||
WireLogError("MG_Remote reply pool: slot for seq %llu declares %u payload bytes in "
|
||||
"a %u byte slot",
|
||||
static_cast<unsigned long long>(seq), header.Size,
|
||||
static_cast<unsigned>(m_slotBytes));
|
||||
return false;
|
||||
}
|
||||
if (outStatus != nullptr) {
|
||||
*outStatus = header.Status;
|
||||
}
|
||||
if (outSize != nullptr) {
|
||||
*outSize = header.Size;
|
||||
}
|
||||
if (header.Size == 0) {
|
||||
return true;
|
||||
}
|
||||
if (outBytes == nullptr || outCapacity < header.Size) {
|
||||
return false;
|
||||
}
|
||||
std::memcpy(outBytes, slot + sizeof(ReplySlotHeader), header.Size);
|
||||
return true;
|
||||
}
|
||||
|
||||
private:
|
||||
std::uint8_t* SlotAt(std::uint64_t seq) const {
|
||||
return m_base + (seq & m_mask) * static_cast<std::uint64_t>(m_slotBytes);
|
||||
}
|
||||
|
||||
std::uint8_t* m_base = nullptr;
|
||||
std::uint32_t m_slots = 0;
|
||||
std::uint32_t m_mask = 0;
|
||||
std::uint32_t m_slotBytes = 0;
|
||||
};
|
||||
|
||||
} // namespace MobileGL::MG_Remote::Transport
|
||||
@@ -8,8 +8,12 @@
|
||||
|
||||
#include "Ring.h"
|
||||
|
||||
#include "SessionRings.h"
|
||||
#include "WireLog.h"
|
||||
|
||||
#include <MG_Util/Debug/Log.h>
|
||||
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
|
||||
namespace MobileGL::MG_Remote::Transport {
|
||||
@@ -257,7 +261,16 @@ namespace MobileGL::MG_Remote::Transport {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ((header.flags & kRecPad) != 0) {
|
||||
// BOTH, not just the flag. kRecPad (1<<2) is the same bit as
|
||||
// MGPipeCallFlags::kVarTail, so an encoder that copied a call's flags
|
||||
// into this framing field verbatim would have every var-tail record
|
||||
// skipped HERE, silently, with the record lost and nothing logged on
|
||||
// either side. A genuine filler is always kind kRingPadRecordKind -
|
||||
// Reserve writes it two dozen lines above - and a call record always
|
||||
// carries a real opcode, because the catalogue starts at 1. Requiring
|
||||
// the pair costs one comparison and turns that collision from a lost
|
||||
// record into a record the decoder gets and can reject by name.
|
||||
if ((header.flags & kRecPad) != 0 && header.kind == kRingPadRecordKind) {
|
||||
m_localTail += size;
|
||||
continue;
|
||||
}
|
||||
@@ -303,4 +316,339 @@ namespace MobileGL::MG_Remote::Transport {
|
||||
}
|
||||
}
|
||||
|
||||
// =======================================================================
|
||||
// P5: the five watermarks, the two session endpoints, and the ABI mixer.
|
||||
// =======================================================================
|
||||
|
||||
std::uint64_t LargestPowerOfTwoAtMost(std::uint64_t bytes) {
|
||||
if (bytes == 0) {
|
||||
return 0;
|
||||
}
|
||||
std::uint64_t value = 1;
|
||||
while (value <= (bytes >> 1)) {
|
||||
value <<= 1;
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
std::uint64_t SegmentBytesForRing(std::uint64_t ringBytes) {
|
||||
const std::uint64_t ring = LargestPowerOfTwoAtMost(ringBytes);
|
||||
if (ring < kMinRingCapacity || ring > kMaxRingCapacity) {
|
||||
return 0;
|
||||
}
|
||||
return ring + sizeof(RingControl);
|
||||
}
|
||||
|
||||
std::uint64_t RingCapacityForSegment(std::uint64_t segmentBytes) {
|
||||
if (segmentBytes <= sizeof(RingControl)) {
|
||||
return 0;
|
||||
}
|
||||
const std::uint64_t usable = LargestPowerOfTwoAtMost(segmentBytes - sizeof(RingControl));
|
||||
return usable < kMinRingCapacity ? 0 : usable;
|
||||
}
|
||||
|
||||
namespace Watermark {
|
||||
|
||||
namespace {
|
||||
// A watermark may be published LATE but never EARLY, and it may never
|
||||
// move BACKWARDS. Backwards is the half that is mechanically
|
||||
// detectable from inside, and it is FATAL rather than logged: the
|
||||
// consumer keeps its own counter, so a shared watermark left behind
|
||||
// makes every later advance a no-op and every WaitForApplied on
|
||||
// kWaitForever - the verb barrier and every reply wait - block for
|
||||
// ever. A hang with one ERROR line in the log is strictly worse than
|
||||
// an abort at the instruction that caused it, and Ring.h:181-185
|
||||
// already rules the same way for the cursor invariants on this page.
|
||||
// "Early" can only be caught at the call site, which is why every
|
||||
// advance below has exactly one caller and a named unit case.
|
||||
void AdvanceMonotonic(std::atomic<std::uint64_t>& watermark, std::uint64_t to,
|
||||
const char* name) {
|
||||
const std::uint64_t current = watermark.load(std::memory_order_relaxed);
|
||||
if (to < current) {
|
||||
// WireLogFatal, not MGLOG_F + abort: the line has to reach stderr
|
||||
// for SessionTestDeath's control to name it (WireLog.h).
|
||||
WireLogFatal("MGPipe: Fatal{ProtocolCorruption, \"watermark\"} %s moved backwards, "
|
||||
"%llu -> %llu. A waiter that already resumed on the higher value "
|
||||
"cannot be un-resumed, and every later advance of this watermark "
|
||||
"would be a no-op, so the verb barrier and every reply wait would "
|
||||
"block for ever",
|
||||
name, static_cast<unsigned long long>(current),
|
||||
static_cast<unsigned long long>(to));
|
||||
}
|
||||
if (to == current) {
|
||||
return;
|
||||
}
|
||||
// Release: everything the advance is a statement ABOUT - the
|
||||
// record that was applied, the staged bytes that were drained,
|
||||
// the reply that was posted - must be visible to the acquiring
|
||||
// waiter before the number that says it happened.
|
||||
watermark.store(to, std::memory_order_release);
|
||||
}
|
||||
} // namespace
|
||||
|
||||
void AdvanceSubmitted(RingControl& control, std::uint64_t seq) {
|
||||
AdvanceMonotonic(control.submittedSeq, seq, "submittedSeq");
|
||||
}
|
||||
|
||||
void AdvanceApplied(RingControl& control, std::uint64_t seq) {
|
||||
AdvanceMonotonic(control.appliedSeq, seq, "appliedSeq");
|
||||
}
|
||||
|
||||
void AdvanceRetired(RingControl& control, std::uint64_t seq) {
|
||||
// retiredSeq may never overtake appliedSeq: the staging allocator
|
||||
// reclaims behind it, so a retire ahead of the apply hands live bytes
|
||||
// back to the producer. Clamped rather than refused, because a
|
||||
// caller that retires "everything applied" is the normal shape.
|
||||
const std::uint64_t applied = control.appliedSeq.load(std::memory_order_acquire);
|
||||
AdvanceMonotonic(control.retiredSeq, seq > applied ? applied : seq, "retiredSeq");
|
||||
}
|
||||
|
||||
void AdvanceCompletedFrame(RingControl& control, std::uint64_t serial) {
|
||||
AdvanceMonotonic(control.completedFrameSerial, serial, "completedFrameSerial");
|
||||
}
|
||||
|
||||
void AdvancePresentAck(RingControl& control, std::uint64_t serial) {
|
||||
AdvanceMonotonic(control.presentAckSerial, serial, "presentAckSerial");
|
||||
}
|
||||
|
||||
} // namespace Watermark
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// SessionProducer
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
void SessionProducer::Attach(RingControl* control, RingProducer* cmd, Doorbell* peerBell,
|
||||
Doorbell* selfBell, std::uint32_t spinUs) {
|
||||
m_control = control;
|
||||
m_cmd = cmd;
|
||||
m_peerBell = peerBell;
|
||||
m_selfBell = selfBell;
|
||||
m_spinUs = spinUs;
|
||||
}
|
||||
|
||||
void SessionProducer::Detach() {
|
||||
m_control = nullptr;
|
||||
m_cmd = nullptr;
|
||||
m_peerBell = nullptr;
|
||||
m_selfBell = nullptr;
|
||||
m_lastPublishedSeq = 0;
|
||||
}
|
||||
|
||||
void SessionProducer::PublishAndNotify(std::uint64_t submittedSeq) {
|
||||
if (!Valid()) {
|
||||
return;
|
||||
}
|
||||
// 1. the records themselves. ONLY SEG_CMD: SEG_STAGE is not a ring and
|
||||
// RingCursorSet::Stage is driven by nobody (Ring.h's stage triple).
|
||||
m_cmd->Publish();
|
||||
// Kept locally as well as on the shared page: the shared watermark is
|
||||
// allowed to lag (Ring.h:72-77), and teardown's drain must not.
|
||||
//
|
||||
// Clamped UP, not passed through. A caller that republishes an older
|
||||
// bound - teardown does exactly that, and so does any batched publisher
|
||||
// that lost track - is publishing LATE, which R-9 permits; it is not the
|
||||
// same thing as a watermark moving backwards, which is Fatal. Doing the
|
||||
// clamp here keeps that distinction at the one boundary where a stale
|
||||
// argument is legitimate.
|
||||
if (submittedSeq > m_lastPublishedSeq) {
|
||||
m_lastPublishedSeq = submittedSeq;
|
||||
}
|
||||
// 2. the diagnostic watermark, after the bytes it describes.
|
||||
Watermark::AdvanceSubmitted(*m_control, m_lastPublishedSeq);
|
||||
// 3. and only now the bell. Publish-then-ring, never ring-then-publish.
|
||||
if (m_peerBell != nullptr) {
|
||||
NotifyIfParked(*m_peerBell, m_control->consumerParked);
|
||||
}
|
||||
}
|
||||
|
||||
template <class Ready>
|
||||
SessionWait SessionProducer::Park(Ready&& ready, std::uint32_t timeoutMs) {
|
||||
if (!Valid() || m_selfBell == nullptr) {
|
||||
return SessionWait::TimedOut;
|
||||
}
|
||||
if (m_selfBell->Wait(m_control->producerParked, ready, m_spinUs, timeoutMs)) {
|
||||
return SessionWait::Reached;
|
||||
}
|
||||
// Wait == false && Dead() is "the session was shut down", and it is the
|
||||
// only thing that returns from a kWaitForever park. Anything else is the
|
||||
// deadline.
|
||||
return m_selfBell->Dead() ? SessionWait::ShutDown : SessionWait::TimedOut;
|
||||
}
|
||||
|
||||
SessionWait SessionProducer::WaitForApplied(std::uint64_t seq, std::uint32_t timeoutMs) {
|
||||
if (!Valid()) {
|
||||
return SessionWait::TimedOut;
|
||||
}
|
||||
RingControl* control = m_control;
|
||||
return Park([control, seq] { return Watermark::Reached(control->appliedSeq, seq); },
|
||||
timeoutMs);
|
||||
}
|
||||
|
||||
SessionWait SessionProducer::WaitForPresentAck(std::uint64_t serial, std::uint32_t timeoutMs) {
|
||||
if (!Valid()) {
|
||||
return SessionWait::TimedOut;
|
||||
}
|
||||
RingControl* control = m_control;
|
||||
return Park([control, serial] { return Watermark::Reached(control->presentAckSerial, serial); },
|
||||
timeoutMs);
|
||||
}
|
||||
|
||||
SessionWait SessionProducer::WaitForCmdSpace(std::uint64_t bytes, std::uint32_t timeoutMs) {
|
||||
if (!Valid()) {
|
||||
return SessionWait::TimedOut;
|
||||
}
|
||||
RingProducer* cmd = m_cmd;
|
||||
return Park([cmd, bytes] { return cmd->FreeBytes() >= bytes; }, timeoutMs);
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// SessionConsumer
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
void SessionConsumer::Attach(RingControl* control, RingConsumer* cmd, Doorbell* peerBell,
|
||||
Doorbell* selfBell, std::uint32_t spinUs) {
|
||||
m_control = control;
|
||||
m_cmd = cmd;
|
||||
m_peerBell = peerBell;
|
||||
m_selfBell = selfBell;
|
||||
m_spinUs = spinUs;
|
||||
m_appliedSeq = control == nullptr ? 0 : control->appliedSeq.load(std::memory_order_acquire);
|
||||
m_retirableCursor = cmd == nullptr ? 0 : cmd->LocalTail();
|
||||
m_borrowHeld = false;
|
||||
}
|
||||
|
||||
void SessionConsumer::Detach() {
|
||||
m_control = nullptr;
|
||||
m_cmd = nullptr;
|
||||
m_peerBell = nullptr;
|
||||
m_selfBell = nullptr;
|
||||
m_retirableCursor = 0;
|
||||
m_borrowHeld = false;
|
||||
}
|
||||
|
||||
SessionWait SessionConsumer::WaitForWork(std::uint32_t timeoutMs) {
|
||||
if (!Valid() || m_selfBell == nullptr) {
|
||||
return SessionWait::TimedOut;
|
||||
}
|
||||
RingControl* control = m_control;
|
||||
RingConsumer* cmd = m_cmd;
|
||||
const bool woke = m_selfBell->Wait(
|
||||
control->consumerParked,
|
||||
[control, cmd] {
|
||||
return control->cmdHead.load(std::memory_order_acquire) != cmd->LocalTail();
|
||||
},
|
||||
m_spinUs, timeoutMs);
|
||||
if (woke) {
|
||||
return SessionWait::Reached;
|
||||
}
|
||||
return m_selfBell->Dead() ? SessionWait::ShutDown : SessionWait::TimedOut;
|
||||
}
|
||||
|
||||
void SessionConsumer::RetireThrough(std::uint64_t seq) {
|
||||
if (!Valid()) {
|
||||
return;
|
||||
}
|
||||
Watermark::AdvanceRetired(*m_control, seq);
|
||||
// PublishRetiredUpTo, NOT PublishRetired: the latter stores m_localTail
|
||||
// into BOTH tails, i.e. it hands back every byte the consumer has popped
|
||||
// whether or not a record among them was borrowed into the GPU timeline.
|
||||
// That would defeat the whole reason the ring carries two tails
|
||||
// (Ring.h:24-27) and would let the producer overwrite a slot the GPU is
|
||||
// still reading. m_retirableCursor stops at the first borrowed record.
|
||||
m_cmd->PublishApplied();
|
||||
m_cmd->PublishRetiredUpTo(m_retirableCursor);
|
||||
NotifyClient();
|
||||
}
|
||||
|
||||
void SessionConsumer::NoteBorrowedRecord(std::uint16_t kind, std::uint16_t flags) {
|
||||
++m_borrowedSeen;
|
||||
if (m_borrowedSeen == 1) {
|
||||
MGLOG_E("MG_Remote ring: record kind %u carries kRecBorrowSlot (flags=0x%04X). P5 "
|
||||
"implements NO borrowed slots, and that bit is also MGPipeCallFlags::"
|
||||
"kHostSpan, which P5's reduced path is ruled to produce none of either. "
|
||||
"Nothing past this record will be reclaimed until RetireBorrowedUpTo "
|
||||
"releases it, so a producer that then wedges on a full ring is THIS line's "
|
||||
"fault and not the ring's",
|
||||
static_cast<unsigned>(kind), static_cast<unsigned>(flags));
|
||||
}
|
||||
}
|
||||
|
||||
void SessionConsumer::RetireBorrowedUpTo(std::uint64_t cursor) {
|
||||
if (!Valid()) {
|
||||
return;
|
||||
}
|
||||
if (cursor > m_retirableCursor) {
|
||||
m_retirableCursor = cursor;
|
||||
// A release that reaches everything popped so far clears the latch;
|
||||
// anything still unreleased keeps it set, so a second borrow behind
|
||||
// the first is not skipped.
|
||||
m_borrowHeld = cursor < m_cmd->LocalTail();
|
||||
}
|
||||
m_cmd->PublishRetiredUpTo(m_retirableCursor);
|
||||
NotifyClient();
|
||||
}
|
||||
|
||||
void SessionConsumer::CompleteFrame(std::uint64_t serial) {
|
||||
if (!Valid()) {
|
||||
return;
|
||||
}
|
||||
Watermark::AdvanceCompletedFrame(*m_control, serial);
|
||||
NotifyClient();
|
||||
}
|
||||
|
||||
void SessionConsumer::ReturnPresentCredit(std::uint64_t serial) {
|
||||
if (!Valid()) {
|
||||
return;
|
||||
}
|
||||
Watermark::AdvancePresentAck(*m_control, serial);
|
||||
NotifyClient();
|
||||
}
|
||||
|
||||
void SessionConsumer::NotifyClient() {
|
||||
if (m_control != nullptr && m_peerBell != nullptr) {
|
||||
NotifyIfParked(*m_peerBell, m_control->producerParked);
|
||||
}
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// The ABI fingerprint's mixer
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
std::uint64_t MixAbiFingerprint(const AbiFingerprintInputs& inputs) {
|
||||
// FNV-1a over every field, in declaration order, then the stamp. Not a
|
||||
// hash with any security property and not meant to be one: it has to
|
||||
// (a) change when ANY input changes and (b) be computable identically in
|
||||
// two processes built from one source tree, which rules out anything
|
||||
// seeded at runtime.
|
||||
std::uint64_t hash = 1469598103934665603ull;
|
||||
const auto mix = [&hash](std::uint64_t value) {
|
||||
for (int byte = 0; byte < 8; ++byte) {
|
||||
hash ^= static_cast<std::uint64_t>((value >> (byte * 8)) & 0xFF);
|
||||
hash *= 1099511628211ull;
|
||||
}
|
||||
};
|
||||
mix(inputs.DynamicParamsSize);
|
||||
mix(inputs.CapsSize);
|
||||
mix(inputs.FunctionTableSize);
|
||||
mix(inputs.FormatCapabilityTargets);
|
||||
mix(inputs.FormatCapabilityFormats);
|
||||
mix(inputs.FormatCapabilitiesCodecVersion);
|
||||
mix(inputs.RendererInfoCodecVersion);
|
||||
mix(inputs.OpCount);
|
||||
mix(inputs.AbiVersion);
|
||||
// A presence marker before the bytes, so that "no stamp" (nullptr) and
|
||||
// "an empty stamp" ("") are different inputs rather than the same
|
||||
// absence of bytes.
|
||||
mix(inputs.BuildStamp != nullptr ? 1u : 0u);
|
||||
if (inputs.BuildStamp != nullptr) {
|
||||
for (const char* c = inputs.BuildStamp; *c != '\0'; ++c) {
|
||||
hash ^= static_cast<std::uint64_t>(static_cast<unsigned char>(*c));
|
||||
hash *= 1099511628211ull;
|
||||
}
|
||||
}
|
||||
// 0 is reserved for "not stated": a peer that forgot to fill the field
|
||||
// must not accidentally agree with one that did.
|
||||
return hash == 0 ? 1ull : hash;
|
||||
}
|
||||
|
||||
} // namespace MobileGL::MG_Remote::Transport
|
||||
|
||||
@@ -103,7 +103,30 @@ namespace MobileGL::MG_Remote::Transport {
|
||||
alignas(64) std::atomic<std::uint64_t> cmdAppliedTail; // consumer: bytes decoded/copied out
|
||||
std::atomic<std::uint64_t> cmdRetiredTail; // consumer: borrowed slots released
|
||||
|
||||
// ---- SEG_STAGE cursors ----------------------------------------------
|
||||
// ---- SEG_STAGE cursors ------------------------------------------------
|
||||
//
|
||||
// DEAD IN P5, DELIBERATELY, AND NOBODY MAY WIRE THEM UP HALFWAY.
|
||||
//
|
||||
// SEG_STAGE is NOT a ring any more. Package w1's encoder owns staging as
|
||||
// an ENCODER-LOCAL LINEAR ALLOCATOR: a staged byte run carries no
|
||||
// RingRecordHeader, there is no consumer walking SEG_STAGE, and the
|
||||
// allocator reclaims on `retiredSeq` - the sequence watermark below -
|
||||
// rather than on these three cursors. So all three stay ZERO for the
|
||||
// whole of P5, `RingCursorSet::Stage` has no producer and no consumer,
|
||||
// and `SessionTest.TheStageCursorTripleStaysDeadAcrossAWholeSession`
|
||||
// pins that rather than leaving it to be noticed.
|
||||
//
|
||||
// They are kept rather than deleted because RingCursorSet, the three
|
||||
// cursor accessors in Ring.cpp and RingTest's fixture are all written
|
||||
// against a two-triple page, and P8/P11's shadow and adopt segments are
|
||||
// the ring-shaped users this triple was reserved for. What is NOT
|
||||
// acceptable is the middle state: a producer publishing `stageHead` with
|
||||
// nothing advancing the two tails makes FreeBytes() fall to zero the
|
||||
// first time the head laps the capacity and never recover, which is a
|
||||
// guaranteed hang rather than a slow path. Five watermarks already spent
|
||||
// a whole phase declared-and-written-by-nobody; this is the sixth, and
|
||||
// it is declared-and-written-by-nobody ON PURPOSE, which is only
|
||||
// different if it is written down.
|
||||
alignas(64) std::atomic<std::uint64_t> stageHead;
|
||||
alignas(64) std::atomic<std::uint64_t> stageAppliedTail;
|
||||
std::atomic<std::uint64_t> stageRetiredTail;
|
||||
@@ -140,6 +163,33 @@ namespace MobileGL::MG_Remote::Transport {
|
||||
};
|
||||
static_assert(sizeof(RingRecordHeader) == 8, "RecHeader is 8 bytes on the wire");
|
||||
|
||||
// THESE ARE RING FLAGS AND THEY ARE NOT MGPipeCallFlags, AND THREE OF THE
|
||||
// BITS COLLIDE WITH A DIFFERENT MEANING. `MGPipeCallFlags` (MG_Pipe/MGPipe.h:
|
||||
// 42-54) is a SEPARATE SPACE that happens to overlap this one, and an encoder
|
||||
// that copies `MGPipeCallFlagsFor(op)` into RingRecordHeader::flags without
|
||||
// translating puts a call's bits into a framing field:
|
||||
//
|
||||
// bit 0 kNeedsAck == kRecNeedsAck same meaning, harmless
|
||||
// bit 1 kHasBlob == kRecHasBlob same meaning, harmless
|
||||
// bit 2 kVarTail == kRecPad WORST: a var-tail record would read
|
||||
// as a WRAP FILLER and be skipped
|
||||
// silently by Pop, losing the record
|
||||
// with nothing logged anywhere
|
||||
// bit 3 kHostSpan == kRecBorrowSlot a host-span record would read as
|
||||
// borrowed into the GPU timeline, and
|
||||
// the consumer would stop reclaiming
|
||||
// ring bytes behind it for ever
|
||||
// bit 4 kReplySlot == kRecVarTail a blocking call would read as having
|
||||
// a tail it does not have
|
||||
// bit 5 kOptional == (unused here)
|
||||
//
|
||||
// Translating is the ENCODER's job. Two things on this side make the first
|
||||
// two of those survivable anyway rather than trusting it: `Pop` requires a
|
||||
// filler to carry BOTH kRecPad AND kind == kRingPadRecordKind, so a real
|
||||
// record with bit 2 set is delivered rather than eaten (a call record always
|
||||
// has a real opcode kind, the catalogue starts at 1); and SessionConsumer
|
||||
// counts and NAMES every kRecBorrowSlot it sees, because P5 produces no
|
||||
// borrowed slots at all and the bit arriving means the collision did.
|
||||
enum RingRecordFlags : std::uint16_t {
|
||||
kRecNone = 0,
|
||||
kRecNeedsAck = 1u << 0,
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
// MobileGL - MobileGL/MG_Remote/Transport/RoleMemory.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
|
||||
|
||||
// Peak-RSS accounting for the two roles. Owner: package s1; CONSUMER: package t1,
|
||||
// which puts the numbers in MEASUREMENTS.
|
||||
//
|
||||
// WHY BOTH HALVES ARE NEEDED, AND WHY NEITHER ALONE IS THE ANSWER.
|
||||
//
|
||||
// VmHWM is the kernel's own high-water mark of resident set size, in
|
||||
// /proc/self/status. It is the only number that cannot be argued with - it
|
||||
// counts what the process actually touched, including the pages the allocator
|
||||
// never gave back. But under `inproc` BOTH ROLES ARE ONE PROCESS, so a single
|
||||
// VmHWM cannot be split between them and reporting it as "the client's" would
|
||||
// be a lie that only becomes visible in P6.
|
||||
//
|
||||
// The segment ledger is the other half: every ShmSegment this process mapped,
|
||||
// by kind and by role. It is exact, it IS separable by role, and under `spawn`
|
||||
// it is the part that appears in both processes at once (one mapping, two
|
||||
// address spaces, one set of physical pages) - which is precisely the number a
|
||||
// naive "sum the two VmHWMs" double-counts.
|
||||
//
|
||||
// So the pair is the measurement: VmHWM for what the process really cost, the
|
||||
// ledger for how much of it is shared mapping that a second process will not pay
|
||||
// for again. t1 reports both, per role, and the split's memory claim is
|
||||
// (client VmHWM + server VmHWM - shared ledger), never either half on its own.
|
||||
//
|
||||
// A SAMPLE IS A SYSCALL AND A PARSE. Take it at phase boundaries - after the
|
||||
// handshake, after the first frame, at teardown - never per record.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <atomic>
|
||||
#include <cstdint>
|
||||
|
||||
namespace MobileGL::MG_Remote::Transport {
|
||||
|
||||
enum class MemoryRole : std::uint32_t {
|
||||
Client = 0,
|
||||
Server = 1,
|
||||
kMemoryRoleCount = 2,
|
||||
};
|
||||
|
||||
// Resident-set high-water mark of THIS PROCESS in bytes, from
|
||||
// /proc/self/status's VmHWM line. 0 when the platform has no such file
|
||||
// (Windows, and Android's /proc is readable but the caller should still
|
||||
// treat 0 as "not measured" rather than "measured zero").
|
||||
std::uint64_t ProcessPeakRssBytes();
|
||||
|
||||
// Current resident set (VmRSS), same source and same 0 convention. Sampled
|
||||
// beside the peak so a phase that never grew the peak is distinguishable
|
||||
// from one that was not sampled.
|
||||
std::uint64_t ProcessCurrentRssBytes();
|
||||
|
||||
// BOTH, FROM ONE PASS OVER /proc/self/status. The kernel does not keep
|
||||
// hiwater_rss up to date on growth - it stores it only when RSS is about to
|
||||
// DROP, and task_mem() reports max(stored hiwater, rss-at-this-read) - so
|
||||
// two separate reads are not comparable: the fopen of the second read can
|
||||
// itself grow RSS past the VmHWM the first read reported. That is exactly
|
||||
// what GitHub run 35079459114 caught (VmHWM 4,784,128 < VmRSS 4,849,664 on
|
||||
// ubuntu-24.04) and what ~/w7/p5-s1-probe reproduced locally: two reads
|
||||
// disagree by 128 KiB with nothing allocated between them, one read never
|
||||
// does (0/1000 with 64 KiB of growth per iteration). One pass is therefore
|
||||
// the only way to read a pair, and even then the pair is a snapshot, not a
|
||||
// bound - see SampleRoleMemoryInto.
|
||||
void ProcessRssBytes(std::uint64_t* outPeakBytes, std::uint64_t* outCurrentBytes);
|
||||
|
||||
// The ledger. ShmSegment does NOT update it itself: a segment is also created
|
||||
// by tests and by P6's adopt path, and a ledger that counted those would stop
|
||||
// meaning "this session's footprint". The SESSION books its own segments.
|
||||
void LedgerAddSegment(MemoryRole role, std::uint64_t bytes);
|
||||
void LedgerRemoveSegment(MemoryRole role, std::uint64_t bytes);
|
||||
std::uint64_t LedgerMappedBytes(MemoryRole role);
|
||||
// Every role's mapped bytes. Under inproc the two roles map THE SAME pages,
|
||||
// so this over-counts on purpose: the two per-role numbers are what t1
|
||||
// subtracts with, and a single total that silently deduplicated them would
|
||||
// hide exactly the spawn-vs-inproc difference the measurement is for.
|
||||
std::uint64_t LedgerMappedBytesAllRoles();
|
||||
|
||||
// One sample, both halves, for one role.
|
||||
//
|
||||
// PeakRssBytes IS THE LEDGER'S OWN RUNNING MAXIMUM, not the kernel's VmHWM.
|
||||
// It is the largest of every kernel peak and every kernel current this
|
||||
// process has folded in through SampleRoleMemoryInto, so it is >= this
|
||||
// sample's CurrentRssBytes BY CONSTRUCTION and never decreases. The kernel's
|
||||
// VmHWM feeds it (it is a lower bound on the true peak that this process's
|
||||
// own samples may have missed) but is never reported on its own: as
|
||||
// ProcessRssBytes explains, the kernel's peak is not a monotone bound on the
|
||||
// kernel's current at read time, so a sample that reported VmHWM verbatim
|
||||
// could show a peak below its own current - which is a number t1 cannot put
|
||||
// in MEASUREMENTS and a test cannot assert against. GitHub run 35079459114.
|
||||
struct RoleMemorySample {
|
||||
std::uint64_t PeakRssBytes = 0;
|
||||
std::uint64_t CurrentRssBytes = 0;
|
||||
std::uint64_t MappedSegmentBytes = 0; // this role's ledger
|
||||
MemoryRole Role = MemoryRole::Client;
|
||||
};
|
||||
|
||||
// One pass over /proc/self/status folded into the PROCESS's running peak.
|
||||
RoleMemorySample SampleRoleMemory(MemoryRole role);
|
||||
|
||||
// The fold itself, over a running peak the CALLER owns: `runningPeak`
|
||||
// becomes max(runningPeak, kernelPeakRssBytes, kernelCurrentRssBytes) and
|
||||
// the sample reports that as PeakRssBytes beside `kernelCurrentRssBytes`.
|
||||
// SampleRoleMemory calls this with the process-wide running peak and the
|
||||
// numbers it just read; SessionTest calls it with a running peak of its own
|
||||
// and a stubbed reader whose current EXCEEDS its peak, which must not fail
|
||||
// (R-16's control on this rule: revert PeakRssBytes to the kernel's peak and
|
||||
// it does).
|
||||
RoleMemorySample SampleRoleMemoryInto(std::atomic<std::uint64_t>& runningPeak, MemoryRole role,
|
||||
std::uint64_t kernelPeakRssBytes,
|
||||
std::uint64_t kernelCurrentRssBytes);
|
||||
|
||||
// Emits one line at INFO level, which is what every P5 lane builds at, so
|
||||
// t1's harness can grep it out of a lane log without a new log sink. Not
|
||||
// DEBUG, which the INFO build compiles out; not ERROR, which this is not.
|
||||
// The grep tag is `MG_Remote memory[`.
|
||||
// `phase` is a short tag: "handshake", "first-frame", "teardown".
|
||||
void LogRoleMemory(const char* phase, const RoleMemorySample& sample);
|
||||
|
||||
} // namespace MobileGL::MG_Remote::Transport
|
||||
@@ -0,0 +1,526 @@
|
||||
// MobileGL - MobileGL/MG_Remote/Transport/SessionRings.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
|
||||
|
||||
// The ring-owning half of a session: the four segments, the two ring endpoints,
|
||||
// and the five watermarks. Owner: package s1.
|
||||
//
|
||||
// This is the object the P5 gate is really about. ROADMAP.md:21 asks that
|
||||
// `inproc` run THE SAME G3 codec as `spawn`, and InProcessTransport cannot
|
||||
// deliver that no matter how it is edited: it is two deque<vector<uint8_t>> plus
|
||||
// two condvar doorbells (InProcessTransport.cpp:38-97), it owns THE BELLS BUT
|
||||
// NOT THE RING, and it runs no codec at all. So the rings live here, above
|
||||
// ITransport, in one implementation both delivery modes use - and the transport
|
||||
// supplies the control plane and the two bells, which is exactly what its own
|
||||
// header says it is for (ITransport.h:16-20: "everything on the hot path
|
||||
// bypasses this interface entirely").
|
||||
//
|
||||
// INPROC USES ShmSegment TOO, NOT new[]. In one address space a heap allocation
|
||||
// would work and would be faster to write. It is refused deliberately: it is half
|
||||
// of what makes "the same code path" true rather than nominal. A `new` here means
|
||||
// the mapping, the alignment, the size rounding, the read-only peer view and the
|
||||
// lifetime are all exercised for the first time in P6, on the day the second
|
||||
// process appears - which is the shape of every "it was green in CI" failure this
|
||||
// phase is trying not to repeat.
|
||||
//
|
||||
// ---------------------------------------------------------------------------
|
||||
// THE KNOB NAMES THE RING; THE SEGMENT IS THE RING PLUS ONE CONTROL PAGE.
|
||||
//
|
||||
// Ring.h:11-13 puts RingControl at the HEAD of SEG_CMD and RingProducer requires
|
||||
// a POWER-OF-TWO capacity (Ring.cpp:89-103 - the mask IS the indexing). Those two
|
||||
// facts together mean a segment and its ring cannot both be 8 MiB, and one of the
|
||||
// two numbers has to give.
|
||||
//
|
||||
// The one that gives is the SEGMENT: SEG_CMD is `MOBILEGL_IPC_RING_MB` MiB PLUS
|
||||
// 4096, so the ring inside it is exactly MOBILEGL_IPC_RING_MB MiB and
|
||||
// RingProducer::MaxRecordBytes() is exactly half of that. CONTRACT-P5 §5 and
|
||||
// Config.h's MOBILEGL_IPC_RING_MB comment - "A RECORD MAY BE AT MOST HALF OF
|
||||
// THIS, so 8 MiB caps one record at 4 MiB" - are then TRUE AS WRITTEN, which
|
||||
// matters because that sentence is what every other package sizes against.
|
||||
//
|
||||
// The first version of this file did the opposite: an 8 MiB segment with a 4 MiB
|
||||
// ring and a 2 MiB record cap, on the grounds that ProtocolSmokeTest.cpp:72 pinned
|
||||
// the four announced sizes. That was wrong on the facts - that test builds four
|
||||
// SegmentRefs from its own literals and round-trips them through the schema; it
|
||||
// says nothing about what a session announces, and it never mentions
|
||||
// SessionSegments at all. So the alternative was available at no cost, and the
|
||||
// version that made two live documents false and left half of SEG_CMD mapped and
|
||||
// unreachable was the worse of the two.
|
||||
//
|
||||
// SegmentRef.sizeBytes therefore announces the MAPPING size (ring + page), which
|
||||
// is what a spawn peer must mmap. The four numbers a reader recognises - 8 MiB /
|
||||
// 32 MiB / 16 MiB / 256 KiB (ID-47) - are the RING sizes, which is what the
|
||||
// knobs name.
|
||||
//
|
||||
// SEG_STAGE has no control page of its own: RingControl carries TWO cursor
|
||||
// triples (Ring.h:101-109) and the stage triple is the second. So SEG_STAGE is
|
||||
// exactly its ring, and 32 MiB is already a power of two. SEG_REPLY is not a ring
|
||||
// at all.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "Doorbell.h"
|
||||
#include "EventRing.h"
|
||||
#include "ReplySlot.h"
|
||||
#include "Ring.h"
|
||||
#include "RoleMemory.h"
|
||||
#include "ShmSegment.h"
|
||||
|
||||
#include <atomic>
|
||||
#include <cstdint>
|
||||
|
||||
namespace MobileGL::MG_Remote::Transport {
|
||||
|
||||
// RING sizes, not segment sizes - see the header block. The four defaults are
|
||||
// CONTRACT-P5's; MOBILEGL_IPC_RING_MB / MOBILEGL_IPC_STAGE_MB move the first
|
||||
// two, and ServerSession applies them unless SetSegmentSizes overrode them.
|
||||
struct SessionSegmentSizes {
|
||||
std::uint64_t CmdRingBytes = 8ull * 1024 * 1024; // + one control page
|
||||
// SEG_STAGE IS NOT A RING. Package w1's encoder owns it as an
|
||||
// encoder-local LINEAR ALLOCATOR that reclaims on retiredSeq, so this is
|
||||
// a plain byte count: no control page, and no rounding down to a power of
|
||||
// two either. Rounding was a ring requirement and keeping it would have
|
||||
// silently turned an operator's MOBILEGL_IPC_STAGE_MB=24 into 16.
|
||||
std::uint64_t StageBytes = 32ull * 1024 * 1024;
|
||||
// SEG_REPLY: a slot pool, not a ring, and NO KNOB MOVES IT (contract §5 has
|
||||
// none). ID-47: 16 MiB = eight slots of 2 MiB, sized from the largest P5
|
||||
// read - the E2 retrace's full-surface 640x480 RGBA8 snapshot, 1,228,800
|
||||
// bytes - which the previous 8 MiB / 1 MiB-per-slot pool could not hold
|
||||
// (ReplySlot.h says how it was found). ProtocolSmokeTest pins the number.
|
||||
std::uint64_t ReplyBytes = 16ull * 1024 * 1024;
|
||||
std::uint64_t EventRingBytes = 256ull * 1024; // + one control page
|
||||
std::uint32_t ReplySlotCount = kDefaultReplySlotCount;
|
||||
};
|
||||
|
||||
// Largest power of two <= `bytes`, or 0 when there is none. The ring's
|
||||
// indexing is a mask, so this is what a ring capacity has to be rounded to.
|
||||
std::uint64_t LargestPowerOfTwoAtMost(std::uint64_t bytes);
|
||||
|
||||
// How big a segment has to be to hold `ringBytes` of ring behind its control
|
||||
// page. `ringBytes` is rounded DOWN to a power of two first, so an operator
|
||||
// who asks for 6 MiB gets a 4 MiB ring in a 4 MiB + 4096 segment rather than
|
||||
// a segment whose tail can never be addressed.
|
||||
std::uint64_t SegmentBytesForRing(std::uint64_t ringBytes);
|
||||
|
||||
// The usable ring inside a segment that carries a RingControl page at its
|
||||
// head. The inverse of SegmentBytesForRing for any size it produced.
|
||||
std::uint64_t RingCapacityForSegment(std::uint64_t segmentBytes);
|
||||
|
||||
enum class SessionSegmentSlot : std::uint32_t {
|
||||
Cmd = 0,
|
||||
Stage = 1,
|
||||
Reply = 2,
|
||||
Event = 3,
|
||||
kSessionSegmentCount = 4,
|
||||
};
|
||||
|
||||
// The four ShmSegments of one session, created and mapped read/write.
|
||||
//
|
||||
// WHO CREATES THEM: the SERVER, because Welcome announces all four
|
||||
// (protocol.fbs's Welcome table) and Welcome is server -> client. "Client
|
||||
// owned" in the schema's comments is about who WRITES a segment, not who
|
||||
// allocates it. Under `inproc` the client then attaches to the same mapping
|
||||
// (AttachInProcess); under `spawn` it will adopt the fds the server passed by
|
||||
// SCM_RIGHTS, which is P6's and is why Adopt is on ShmSegment already.
|
||||
class SessionSegments {
|
||||
public:
|
||||
SessionSegments() = default;
|
||||
~SessionSegments();
|
||||
|
||||
SessionSegments(const SessionSegments&) = delete;
|
||||
SessionSegments& operator=(const SessionSegments&) = delete;
|
||||
|
||||
// Creates and maps all four, initialises BOTH control pages (SEG_CMD's
|
||||
// and SEG_EVENT's), and books the mapping in `role`'s ledger.
|
||||
MobileGLResult Create(const SessionSegmentSizes& sizes, MemoryRole role);
|
||||
|
||||
// The inproc peer's view of the owner's four segments, booked under the
|
||||
// OTHER role. It does NOT re-init the control pages - there is one shared
|
||||
// page per ring and re-initialising it would zero the owner's cursors out
|
||||
// from under whoever is already using them.
|
||||
//
|
||||
// ON POSIX THIS IS A REAL SECOND MAPPING, NOT AN ALIAS: each descriptor is
|
||||
// dup()ed and adopted through ShmSegment::Adopt + Map, so the peer gets
|
||||
// its own virtual addresses over the same memfd. That is the same reason
|
||||
// inproc uses ShmSegment at all (see the header block): the ATTACH half is
|
||||
// the half P6 replaces with an SCM_RIGHTS Adopt, and aliasing the owner's
|
||||
// ShmSegment objects would leave it first exercised on the day the second
|
||||
// process appears - which is exactly the criticism this file levels at
|
||||
// new[]. It also removes a raw lifetime coupling: an aliased view holds
|
||||
// pointers into the owner's members with no ownership, so the two Closes
|
||||
// have to be ordered by hand.
|
||||
//
|
||||
// Windows has no Adopt (ShmSegment::Adopt is POSIX-only; the section name
|
||||
// travels in SegmentRef instead), so there it still aliases and says so.
|
||||
MobileGLResult AttachInProcess(SessionSegments& owner, MemoryRole role);
|
||||
|
||||
void Close();
|
||||
bool Valid() const { return m_valid; }
|
||||
|
||||
RingControl* CmdControl() const { return m_cmdControl; }
|
||||
void* CmdRingBase() const { return m_cmdRingBase; }
|
||||
std::uint64_t CmdRingCapacity() const { return m_cmdRingCapacity; }
|
||||
|
||||
// The whole SEG_STAGE mapping, for w1's linear allocator and for the
|
||||
// SegmentTable view the decoder resolves blobrefs against. There is no
|
||||
// stage RING and no RingProducer/RingConsumer over RingCursorSet::Stage.
|
||||
void* StageBase() const { return m_stageBase; }
|
||||
std::uint64_t StageBytes() const { return m_stageBytes; }
|
||||
|
||||
void* ReplyBase() const { return m_replyBase; }
|
||||
std::uint64_t ReplyBytes() const { return m_replyBytes; }
|
||||
std::uint32_t ReplySlotCount() const { return m_replySlotCount; }
|
||||
|
||||
RingControl* EventControl() const { return m_eventControl; }
|
||||
void* EventSegmentBase() const { return m_eventSegmentBase; }
|
||||
void* EventRingBase() const { return m_eventRingBase; }
|
||||
std::uint64_t EventRingCapacity() const { return m_eventRingCapacity; }
|
||||
|
||||
// For Welcome's four SegmentRefs. The announced size is the MAPPING size,
|
||||
// which is what a peer must map - not the ring capacity inside it.
|
||||
std::uint64_t AnnouncedSize(SessionSegmentSlot slot) const;
|
||||
const char* AnnouncedName(SessionSegmentSlot slot) const;
|
||||
int DescriptorFor(SessionSegmentSlot slot) const; // POSIX; -1 elsewhere
|
||||
|
||||
std::uint64_t MappedBytes() const { return m_mappedBytes; }
|
||||
|
||||
private:
|
||||
void DeriveViews();
|
||||
|
||||
ShmSegment m_owned[4]; // empty on an attached (peer) view
|
||||
ShmSegment* m_segments[4] = {nullptr, nullptr, nullptr, nullptr};
|
||||
|
||||
RingControl* m_cmdControl = nullptr;
|
||||
void* m_cmdRingBase = nullptr;
|
||||
std::uint64_t m_cmdRingCapacity = 0;
|
||||
void* m_stageBase = nullptr;
|
||||
std::uint64_t m_stageBytes = 0;
|
||||
void* m_replyBase = nullptr;
|
||||
std::uint64_t m_replyBytes = 0;
|
||||
std::uint32_t m_replySlotCount = kDefaultReplySlotCount;
|
||||
RingControl* m_eventControl = nullptr;
|
||||
void* m_eventSegmentBase = nullptr;
|
||||
void* m_eventRingBase = nullptr;
|
||||
std::uint64_t m_eventRingCapacity = 0;
|
||||
|
||||
std::uint64_t m_mappedBytes = 0;
|
||||
MemoryRole m_role = MemoryRole::Client;
|
||||
bool m_valid = false;
|
||||
bool m_owns = false;
|
||||
bool m_booked = false;
|
||||
};
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// The five watermarks (R-9). Every write and every wait goes through here,
|
||||
// so the rules in Ring.h's header have exactly one implementation.
|
||||
// -----------------------------------------------------------------------
|
||||
//
|
||||
// THE ONE RULE THAT MATTERS: a watermark may be published LATE but NEVER
|
||||
// EARLY. Late costs a waiter some latency; early makes every waiter a silent
|
||||
// use of work that has not happened, and there is no checksum anywhere on
|
||||
// this ring that would catch it. The callers are responsible for never
|
||||
// calling an advance before the work is done - that is the half only a
|
||||
// call-site review and R-9's unit cases can enforce.
|
||||
//
|
||||
// THE HALF THAT IS MECHANICALLY DETECTABLE - a watermark moving BACKWARDS -
|
||||
// IS FATAL, not logged-and-ignored. Logging it and returning was the first
|
||||
// version of this file and it was worse than useless: SessionConsumer keeps
|
||||
// its own counter, so once the shared appliedSeq is behind, every later
|
||||
// advance is a no-op for ever and every WaitForApplied(seq, kWaitForever) -
|
||||
// the verb barrier and every reply wait - blocks permanently. The user sees a
|
||||
// hang and the only evidence is one ERROR line. This is the same class as
|
||||
// RingCursorsValid returning false, and Ring.h:181-185 already calls that "a
|
||||
// Fatal{ProtocolCorruption}, never a retry".
|
||||
namespace Watermark {
|
||||
|
||||
// Producer, after Publish. Nobody waits on it - it is the answer to "how
|
||||
// far ahead of the server is the client right now".
|
||||
void AdvanceSubmitted(RingControl& control, std::uint64_t seq);
|
||||
// Consumer, ONCE PER APPLIED RECORD. P5 forbids the 64-record batching
|
||||
// this ring was designed for: the verb barrier and every reply wait read
|
||||
// it. kRecPad does not count - RingConsumer::Pop skips fillers, so the
|
||||
// rule is kept by counting Pops rather than bytes.
|
||||
void AdvanceApplied(RingControl& control, std::uint64_t seq);
|
||||
// Consumer, once the SEG_STAGE bytes a record referenced are finished
|
||||
// with. The staging allocator reclaims behind it and nothing else may.
|
||||
void AdvanceRetired(RingControl& control, std::uint64_t seq);
|
||||
// Server, when a present completes. Trails appliedSeq by the GPU's own
|
||||
// depth; never conflate the two.
|
||||
void AdvanceCompletedFrame(RingControl& control, std::uint64_t serial);
|
||||
// Server, when it returns a present credit. The only back-pressure that
|
||||
// bounds latency rather than bytes.
|
||||
void AdvancePresentAck(RingControl& control, std::uint64_t serial);
|
||||
|
||||
// Every wait is >=, never ==: both sides advance in jumps, and an
|
||||
// equality waiter misses its wakeup and hangs until the next coincidence.
|
||||
inline bool Reached(const std::atomic<std::uint64_t>& watermark, std::uint64_t target) {
|
||||
return watermark.load(std::memory_order_acquire) >= target;
|
||||
}
|
||||
|
||||
} // namespace Watermark
|
||||
|
||||
enum class SessionWait : std::uint32_t {
|
||||
Reached = 0,
|
||||
// The doorbell died: the peer shut the session down. The ONLY thing that
|
||||
// can un-park a waiter on kWaitForever (Doorbell.h:211-221), and the
|
||||
// reason a bounded join is possible at all.
|
||||
ShutDown = 1,
|
||||
TimedOut = 2,
|
||||
};
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// The client's end of the rings.
|
||||
//
|
||||
// THE TWO DOORBELL ACCESSORS LIVE ON THE SESSION, NOT ON ITransport
|
||||
// (contract §3.9, the ruling s1 is asked to make now rather than let P6
|
||||
// discover). The session takes the two references InProcessTransport hands
|
||||
// out and is the only thing that knows which is which; ITransport stays the
|
||||
// dumb control-plane interface its header claims to be, and P6's
|
||||
// SocketTransport does not grow two accessors it has no natural home for.
|
||||
// -----------------------------------------------------------------------
|
||||
class SessionProducer {
|
||||
public:
|
||||
SessionProducer() = default;
|
||||
|
||||
// `peerBell` is the bell the SERVER parks on and this side rings;
|
||||
// `selfBell` is this side's own. InProcessTransport::PeerDoorbell() and
|
||||
// SelfDoorbell() are exactly that pair, from the client endpoint.
|
||||
// NO STAGE RING. SEG_STAGE is w1's encoder-local linear allocator and
|
||||
// RingCursorSet::Stage has no producer and no consumer in P5 - see
|
||||
// RingControl's stage triple in Ring.h. A producer here would publish
|
||||
// stageHead with nothing advancing the two tails, so FreeBytes() would
|
||||
// fall to zero the first time the head lapped the capacity and never
|
||||
// recover: a guaranteed hang, not a slow path.
|
||||
void Attach(RingControl* control, RingProducer* cmd, Doorbell* peerBell, Doorbell* selfBell,
|
||||
std::uint32_t spinUs);
|
||||
void Detach();
|
||||
bool Valid() const { return m_control != nullptr && m_cmd != nullptr; }
|
||||
|
||||
// Publish the command ring's head, record submittedSeq, THEN ring - in
|
||||
// that order and never any other. Doorbell.h:186-193: the fence only
|
||||
// orders what precedes it, so ringing before publishing reopens the very
|
||||
// lost-wakeup window the fences exist to close. RingTest.cpp:446 pins the
|
||||
// call order; this is the one place production code performs it.
|
||||
void PublishAndNotify(std::uint64_t submittedSeq);
|
||||
|
||||
// The last seq THIS producer published, kept locally rather than read back
|
||||
// out of RingControl::submittedSeq. Teardown's drain needs it: Ring.h:72-77
|
||||
// explicitly permits submittedSeq to be published LAZILY and Ring.h:243
|
||||
// encourages batching the publish, so the shared watermark may lag the
|
||||
// emitter - and a drain that waits for `appliedSeq >= submittedSeq` would
|
||||
// then under-wait and free an emitter's var-tail while a record still
|
||||
// names it. With the verb barrier armed the two are equal; with
|
||||
// MOBILEGL_IPC_VERB_BARRIER=0, R-1's negative control which the phase has
|
||||
// to run once, they are not.
|
||||
std::uint64_t LastPublishedSeq() const { return m_lastPublishedSeq; }
|
||||
|
||||
// The verb barrier's wait, AND the reply's wait: they are the same wait
|
||||
// (R-3/R-5), which is why a blocking ReadPixels, MapPersistent's decline
|
||||
// and the four Bool acceptances cost ZERO extra round trips.
|
||||
SessionWait WaitForApplied(std::uint64_t seq, std::uint32_t timeoutMs);
|
||||
// Present throttle.
|
||||
SessionWait WaitForPresentAck(std::uint64_t serial, std::uint32_t timeoutMs);
|
||||
// Back-pressure when Reserve returned nullptr. NEVER call this when
|
||||
// FreeBytes() is already >= the record: Ring.h:226-233 - a nullptr with
|
||||
// enough free bytes can only mean "too big, chunk", and waiting on it
|
||||
// stalls forever.
|
||||
SessionWait WaitForCmdSpace(std::uint64_t bytes, std::uint32_t timeoutMs);
|
||||
|
||||
RingControl* Control() const { return m_control; }
|
||||
RingProducer* Cmd() const { return m_cmd; }
|
||||
Doorbell* PeerDoorbell() const { return m_peerBell; }
|
||||
Doorbell* SelfDoorbell() const { return m_selfBell; }
|
||||
std::uint32_t SpinUs() const { return m_spinUs; }
|
||||
|
||||
private:
|
||||
template <class Ready>
|
||||
SessionWait Park(Ready&& ready, std::uint32_t timeoutMs);
|
||||
|
||||
RingControl* m_control = nullptr;
|
||||
RingProducer* m_cmd = nullptr;
|
||||
Doorbell* m_peerBell = nullptr;
|
||||
Doorbell* m_selfBell = nullptr;
|
||||
std::uint32_t m_spinUs = kDefaultSpinUs;
|
||||
std::uint64_t m_lastPublishedSeq = 0;
|
||||
};
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// The server's end of the rings: the apply thread's loop, minus the applier.
|
||||
// -----------------------------------------------------------------------
|
||||
class SessionConsumer {
|
||||
public:
|
||||
SessionConsumer() = default;
|
||||
|
||||
void Attach(RingControl* control, RingConsumer* cmd, Doorbell* peerBell, Doorbell* selfBell,
|
||||
std::uint32_t spinUs);
|
||||
void Detach();
|
||||
bool Valid() const { return m_control != nullptr && m_cmd != nullptr; }
|
||||
|
||||
// Park until a record is waiting, the session is shut down, or the
|
||||
// deadline passes. Pass kWaitForever for the steady state; a dead bell is
|
||||
// what ends it, which is why Doorbell::Kill() is load-bearing for the
|
||||
// join (InProcessTransportTest.cpp:344 pins the shape).
|
||||
SessionWait WaitForWork(std::uint32_t timeoutMs);
|
||||
|
||||
// Pop ONE record and hand it to `apply`. Returns false when the ring is
|
||||
// empty. On a corrupt header it returns false and sets *outCorrupt, which
|
||||
// the CALLER escalates to Fatal{ProtocolCorruption} rather than retrying.
|
||||
//
|
||||
// This is the only place appliedSeq is advanced, and it advances it by
|
||||
// EXACTLY ONE per record - never a batch (R-9). kRecPad cannot reach
|
||||
// `apply`: RingConsumer::Pop skips fillers before returning, so a filler
|
||||
// is never counted here and the two sides' sequence spaces cannot drift.
|
||||
// Order: apply -> appliedSeq -> PublishApplied -> ring the client.
|
||||
template <class Apply>
|
||||
bool ApplyOne(Apply&& apply, bool* outCorrupt = nullptr) {
|
||||
if (outCorrupt != nullptr) {
|
||||
*outCorrupt = false;
|
||||
}
|
||||
if (!Valid()) {
|
||||
return false;
|
||||
}
|
||||
RingRecordView view{};
|
||||
if (!m_cmd->Pop(view, outCorrupt)) {
|
||||
return false;
|
||||
}
|
||||
apply(view);
|
||||
++m_appliedSeq;
|
||||
Watermark::AdvanceApplied(*m_control, m_appliedSeq);
|
||||
m_cmd->PublishApplied();
|
||||
// THE BYTE CURSOR RetireThrough MAY RECLAIM TO, which is NOT simply
|
||||
// "everything popped". A record carrying kRecBorrowSlot has been lent
|
||||
// into the GPU timeline and its slot can only be recycled after
|
||||
// completedFrameSerial (Ring.h:24-27), so the reclaimable cursor stops
|
||||
// AT the first borrowed record and does not move again until
|
||||
// RetireBorrowedUpTo releases it. Nothing sets kRecBorrowSlot yet;
|
||||
// this is here so that the day something does, the producer does not
|
||||
// overwrite a slot the GPU is still reading.
|
||||
if ((view.flags & kRecBorrowSlot) == 0 && !m_borrowHeld) {
|
||||
m_retirableCursor = view.cursor + sizeof(RingRecordHeader) + view.payloadSize;
|
||||
} else {
|
||||
if ((view.flags & kRecBorrowSlot) != 0) {
|
||||
// P5 PRODUCES NO BORROWED SLOTS AT ALL, so this bit arriving
|
||||
// is either a borrow nobody implemented or MGPipeCallFlags::
|
||||
// kHostSpan wearing kRecBorrowSlot's bit (Ring.h's collision
|
||||
// table) - and P5's reduced path is ruled to produce zero
|
||||
// host spans too. Either way the conservative arm is taken
|
||||
// (nothing past it is reclaimed) and the sighting is NAMED,
|
||||
// because the alternative is a producer that wedges on the
|
||||
// first full ring with no line anywhere saying why.
|
||||
NoteBorrowedRecord(view.kind, view.flags);
|
||||
}
|
||||
m_borrowHeld = true;
|
||||
}
|
||||
NotifyClient();
|
||||
return true;
|
||||
}
|
||||
|
||||
// Publish the retire watermark and hand back every byte up to the first
|
||||
// still-borrowed record.
|
||||
//
|
||||
// IT IS MANDATORY, NOT OPTIONAL. RingProducer::FreeBytes() reclaims against
|
||||
// retiredTail ONLY (Ring.cpp:110-115) and nothing else in this class
|
||||
// publishes it, so an apply loop that calls ApplyOne and never this wedges
|
||||
// the producer on the first full ring. Call it once per drain batch.
|
||||
void RetireThrough(std::uint64_t seq);
|
||||
|
||||
// Release borrowed slots up to `cursor` once completedFrameSerial has
|
||||
// passed them. `cursor` is a RingRecordView::cursor the apply loop kept.
|
||||
// This is the only thing that moves the reclaim point past a borrowed
|
||||
// record - see ApplyOne.
|
||||
void RetireBorrowedUpTo(std::uint64_t cursor);
|
||||
|
||||
// The byte cursor RetireThrough would reclaim to right now. Diagnostic;
|
||||
// a borrow that is never released shows up as this number standing still.
|
||||
std::uint64_t RetirableCursor() const { return m_retirableCursor; }
|
||||
|
||||
// completedFrameSerial and presentAckSerial, advanced AND rung. The free
|
||||
// functions in namespace Watermark advance only: a v1 caller that used one
|
||||
// directly would leave a client parked in WaitForPresentAck(kWaitForever)
|
||||
// with nothing to wake it, because the advance and the doorbell are two
|
||||
// separate stores and only the pair is a wakeup.
|
||||
void CompleteFrame(std::uint64_t serial);
|
||||
void ReturnPresentCredit(std::uint64_t serial);
|
||||
|
||||
// Ring the client's bell, but only when it said it is parked: a store to
|
||||
// a shared cache line otherwise burns a big core for a whole frame on a
|
||||
// phone (Doorbell.h:13-22).
|
||||
void NotifyClient();
|
||||
|
||||
std::uint64_t AppliedSeq() const { return m_appliedSeq; }
|
||||
// How many kRecBorrowSlot records this consumer has seen. Non-zero in P5
|
||||
// is a finding, not a statistic.
|
||||
std::uint64_t BorrowedRecordsSeen() const { return m_borrowedSeen; }
|
||||
RingControl* Control() const { return m_control; }
|
||||
RingConsumer* Cmd() const { return m_cmd; }
|
||||
Doorbell* PeerDoorbell() const { return m_peerBell; }
|
||||
Doorbell* SelfDoorbell() const { return m_selfBell; }
|
||||
std::uint32_t SpinUs() const { return m_spinUs; }
|
||||
|
||||
private:
|
||||
RingControl* m_control = nullptr;
|
||||
RingConsumer* m_cmd = nullptr;
|
||||
Doorbell* m_peerBell = nullptr;
|
||||
Doorbell* m_selfBell = nullptr;
|
||||
std::uint32_t m_spinUs = kDefaultSpinUs;
|
||||
std::uint64_t m_appliedSeq = 0;
|
||||
std::uint64_t m_retirableCursor = 0;
|
||||
std::uint64_t m_borrowedSeen = 0;
|
||||
bool m_borrowHeld = false;
|
||||
|
||||
// Out of line so ApplyOne, which is a template in a header this layer
|
||||
// keeps free of MobileGL/Includes.h, can still log.
|
||||
void NoteBorrowedRecord(std::uint16_t kind, std::uint16_t flags);
|
||||
};
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// The ABI fingerprint's mixer - THE ONE IMPLEMENTATION.
|
||||
//
|
||||
// CapsCodec.cpp's CapsAbiFingerprint(), the value both handshakes compare,
|
||||
// is exactly MixAbiFingerprint(CapsAbiFingerprintInputs()). It lives under
|
||||
// Transport/ so that it can be tested without the GL frontend's umbrella
|
||||
// header, and it takes its inputs as a struct so that the SAME function the
|
||||
// handshake calls can be driven with one field perturbed at a time.
|
||||
//
|
||||
// The wave-1 review (ID-46 finding 6) found the previous shape - a
|
||||
// five-argument mixer here and a SEPARATE hand-rolled FNV loop in
|
||||
// CapsCodec.cpp - had exactly one caller of this function: the sensitivity
|
||||
// test. Production never called it, so replacing CapsAbiFingerprint() with
|
||||
// `return 1;` left every fingerprint test green and both peers agreeing on
|
||||
// nothing. Now there is one mixer, the sensitivity case starts from the
|
||||
// production entry point, and that perturbation turns it red.
|
||||
// -----------------------------------------------------------------------
|
||||
struct AbiFingerprintInputs {
|
||||
// The three struct shapes table 0's ABI-agreement row names.
|
||||
std::uint64_t DynamicParamsSize = 0;
|
||||
std::uint64_t CapsSize = 0;
|
||||
std::uint64_t FunctionTableSize = 0;
|
||||
// The caps blob's own geometry and the two blob codecs' versions: the
|
||||
// format-capability table's extents and the codec version stamps.
|
||||
std::uint64_t FormatCapabilityTargets = 0;
|
||||
std::uint64_t FormatCapabilityFormats = 0;
|
||||
std::uint64_t FormatCapabilitiesCodecVersion = 0;
|
||||
std::uint64_t RendererInfoCodecVersion = 0;
|
||||
// The catalogue's length (ID-33): a peer with one more opcode is a
|
||||
// different wire even if every struct kept its size.
|
||||
std::uint64_t OpCount = 0;
|
||||
// MOBILEGL_ABI_VERSION(major, minor): a protocol change that left every
|
||||
// struct the same size, which nothing above can see.
|
||||
std::uint32_t AbiVersion = 0;
|
||||
// GIT_COMMIT_HASH_SHORT: two builds of the same sizes can still disagree
|
||||
// about a FIELD ORDER, which no sizeof can see. nullptr and "" are
|
||||
// distinct inputs and neither equals a real stamp.
|
||||
const char* BuildStamp = nullptr;
|
||||
};
|
||||
|
||||
// FNV-1a over every field above, in declaration order. Never 0: that value is
|
||||
// reserved for "not stated", so a peer that forgot to fill the field cannot
|
||||
// accidentally agree with one that did.
|
||||
std::uint64_t MixAbiFingerprint(const AbiFingerprintInputs& inputs);
|
||||
|
||||
} // namespace MobileGL::MG_Remote::Transport
|
||||
@@ -8,12 +8,27 @@
|
||||
|
||||
// Platform-independent half of ShmSegment. The create/map/close bodies live in
|
||||
// ShmSegmentPosix.cpp and ShmSegmentWin32.cpp.
|
||||
//
|
||||
// P5 adds two things that are about a SET of segments rather than about one:
|
||||
// SessionSegments (the four a session owns, and the ring geometry derived from
|
||||
// them) and the role memory ledger that t1 reports against.
|
||||
|
||||
#include "ShmSegment.h"
|
||||
|
||||
#include "RoleMemory.h"
|
||||
#include "SessionRings.h"
|
||||
|
||||
#include <MG_Util/Debug/Log.h>
|
||||
|
||||
#include <atomic>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <utility>
|
||||
|
||||
#if !defined(_WIN32)
|
||||
#include <unistd.h>
|
||||
#endif
|
||||
|
||||
namespace MobileGL::MG_Remote::Transport {
|
||||
|
||||
ShmSegment::~ShmSegment() { Close(); }
|
||||
@@ -46,4 +61,413 @@ namespace MobileGL::MG_Remote::Transport {
|
||||
|
||||
bool ShmSegment::Valid() const { return m_size != 0 && (m_fd >= 0 || m_nativeHandle != nullptr); }
|
||||
|
||||
// =======================================================================
|
||||
// P5: the role memory ledger and the VmHWM sample
|
||||
// =======================================================================
|
||||
|
||||
namespace {
|
||||
constexpr std::size_t kMemoryRoleCount = static_cast<std::size_t>(MemoryRole::kMemoryRoleCount);
|
||||
|
||||
std::atomic<std::uint64_t>& LedgerSlot(MemoryRole role) {
|
||||
static std::atomic<std::uint64_t> ledger[kMemoryRoleCount];
|
||||
const std::size_t index = static_cast<std::size_t>(role);
|
||||
return ledger[index < kMemoryRoleCount ? index : 0];
|
||||
}
|
||||
|
||||
const char* RoleName(MemoryRole role) {
|
||||
return role == MemoryRole::Server ? "server" : "client";
|
||||
}
|
||||
|
||||
// "<key>:\t <number> kB" -> bytes. The unit suffix is part of the
|
||||
// line, so it is parsed rather than assumed; anything else is a kernel
|
||||
// this code has not seen, and 0 ("not measured") is the honest answer.
|
||||
bool ParseKilobyteLine(const char* line, const char* key, std::uint64_t* outBytes) {
|
||||
const std::size_t keyLength = std::strlen(key);
|
||||
if (std::strncmp(line, key, keyLength) != 0) {
|
||||
return false;
|
||||
}
|
||||
unsigned long long kilobytes = 0;
|
||||
if (std::sscanf(line + keyLength, ": %llu kB", &kilobytes) == 1) {
|
||||
*outBytes = static_cast<std::uint64_t>(kilobytes) * 1024ull;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// The process-wide running peak SampleRoleMemory folds into. One per
|
||||
// process, like VmHWM itself; under inproc both roles share it and the
|
||||
// log line says so.
|
||||
std::atomic<std::uint64_t>& ProcessRunningPeak() {
|
||||
static std::atomic<std::uint64_t> peak{0};
|
||||
return peak;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
// ONE PASS FOR BOTH KEYS - see RoleMemory.h. A pass per key was the wave-1
|
||||
// shape and it is what GitHub run 35079459114 caught: the second fopen grew
|
||||
// RSS past the VmHWM the first pass had reported, because the kernel only
|
||||
// stores hiwater_rss when RSS is about to drop and reports max(stored, now)
|
||||
// otherwise, so the two reads were snapshots of different "now"s.
|
||||
void ProcessRssBytes(std::uint64_t* outPeakBytes, std::uint64_t* outCurrentBytes) {
|
||||
std::uint64_t peak = 0;
|
||||
std::uint64_t current = 0;
|
||||
#if defined(__linux__) || defined(__ANDROID__)
|
||||
std::FILE* file = std::fopen("/proc/self/status", "re");
|
||||
if (file != nullptr) {
|
||||
char line[256];
|
||||
bool sawPeak = false;
|
||||
bool sawCurrent = false;
|
||||
while ((!sawPeak || !sawCurrent) && std::fgets(line, sizeof(line), file) != nullptr) {
|
||||
if (!sawPeak && ParseKilobyteLine(line, "VmHWM", &peak)) {
|
||||
sawPeak = true;
|
||||
} else if (!sawCurrent && ParseKilobyteLine(line, "VmRSS", ¤t)) {
|
||||
sawCurrent = true;
|
||||
}
|
||||
}
|
||||
std::fclose(file);
|
||||
}
|
||||
#endif
|
||||
if (outPeakBytes != nullptr) {
|
||||
*outPeakBytes = peak;
|
||||
}
|
||||
if (outCurrentBytes != nullptr) {
|
||||
*outCurrentBytes = current;
|
||||
}
|
||||
}
|
||||
|
||||
std::uint64_t ProcessPeakRssBytes() {
|
||||
std::uint64_t peak = 0;
|
||||
ProcessRssBytes(&peak, nullptr);
|
||||
return peak;
|
||||
}
|
||||
|
||||
std::uint64_t ProcessCurrentRssBytes() {
|
||||
std::uint64_t current = 0;
|
||||
ProcessRssBytes(nullptr, ¤t);
|
||||
return current;
|
||||
}
|
||||
|
||||
void LedgerAddSegment(MemoryRole role, std::uint64_t bytes) {
|
||||
LedgerSlot(role).fetch_add(bytes, std::memory_order_relaxed);
|
||||
}
|
||||
|
||||
void LedgerRemoveSegment(MemoryRole role, std::uint64_t bytes) {
|
||||
std::atomic<std::uint64_t>& slot = LedgerSlot(role);
|
||||
const std::uint64_t current = slot.load(std::memory_order_relaxed);
|
||||
// Clamped rather than wrapped: a double-unbook would otherwise report a
|
||||
// role holding sixteen exabytes, which is a number nobody reads as a bug.
|
||||
slot.store(bytes > current ? 0 : current - bytes, std::memory_order_relaxed);
|
||||
}
|
||||
|
||||
std::uint64_t LedgerMappedBytes(MemoryRole role) {
|
||||
return LedgerSlot(role).load(std::memory_order_relaxed);
|
||||
}
|
||||
|
||||
std::uint64_t LedgerMappedBytesAllRoles() {
|
||||
std::uint64_t total = 0;
|
||||
for (std::size_t index = 0; index < kMemoryRoleCount; ++index) {
|
||||
total += LedgerSlot(static_cast<MemoryRole>(index)).load(std::memory_order_relaxed);
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
RoleMemorySample SampleRoleMemoryInto(std::atomic<std::uint64_t>& runningPeak, MemoryRole role,
|
||||
std::uint64_t kernelPeakRssBytes,
|
||||
std::uint64_t kernelCurrentRssBytes) {
|
||||
// max(running, kernel peak, kernel current), as a CAS loop: two threads
|
||||
// sampling at once (the GL thread and the apply thread both log memory
|
||||
// at phase boundaries) must not let a lower value overwrite a higher.
|
||||
const std::uint64_t observed =
|
||||
kernelPeakRssBytes > kernelCurrentRssBytes ? kernelPeakRssBytes : kernelCurrentRssBytes;
|
||||
std::uint64_t peak = runningPeak.load(std::memory_order_relaxed);
|
||||
while (observed > peak &&
|
||||
!runningPeak.compare_exchange_weak(peak, observed, std::memory_order_relaxed)) {
|
||||
}
|
||||
RoleMemorySample sample;
|
||||
sample.Role = role;
|
||||
// THE RUNNING MAXIMUM, never the kernel's peak verbatim - RoleMemory.h
|
||||
// says why, and SessionTest's stubbed-reader control is the gate on it.
|
||||
sample.PeakRssBytes = observed > peak ? observed : peak;
|
||||
sample.CurrentRssBytes = kernelCurrentRssBytes;
|
||||
sample.MappedSegmentBytes = LedgerMappedBytes(role);
|
||||
return sample;
|
||||
}
|
||||
|
||||
RoleMemorySample SampleRoleMemory(MemoryRole role) {
|
||||
std::uint64_t kernelPeak = 0;
|
||||
std::uint64_t kernelCurrent = 0;
|
||||
ProcessRssBytes(&kernelPeak, &kernelCurrent);
|
||||
return SampleRoleMemoryInto(ProcessRunningPeak(), role, kernelPeak, kernelCurrent);
|
||||
}
|
||||
|
||||
void LogRoleMemory(const char* phase, const RoleMemorySample& sample) {
|
||||
// INFO, not DEBUG: t1 greps this out of a lane log and MGLOG_D is compiled out at the
|
||||
// INFO level every P5 lane builds at. It is a handful of lines per session - the
|
||||
// handshake, the first frame and teardown - so it is not per-frame noise either.
|
||||
//
|
||||
// VmHWM is the PROCESS's, so under inproc both roles report the same
|
||||
// number and only the ledger differs. The line says so rather than
|
||||
// leaving a reader to work out why two roles have one peak.
|
||||
MGLOG_I("MG_Remote memory[%s/%s]: peakRss=%llu currentRss=%llu roleMapped=%llu "
|
||||
"allRolesMapped=%llu (peakRss is the PROCESS's; under inproc both roles share it)",
|
||||
phase == nullptr ? "?" : phase, RoleName(sample.Role),
|
||||
static_cast<unsigned long long>(sample.PeakRssBytes),
|
||||
static_cast<unsigned long long>(sample.CurrentRssBytes),
|
||||
static_cast<unsigned long long>(sample.MappedSegmentBytes),
|
||||
static_cast<unsigned long long>(LedgerMappedBytesAllRoles()));
|
||||
}
|
||||
|
||||
// =======================================================================
|
||||
// P5: SessionSegments
|
||||
// =======================================================================
|
||||
|
||||
namespace {
|
||||
constexpr std::size_t kSlotCount =
|
||||
static_cast<std::size_t>(SessionSegmentSlot::kSessionSegmentCount);
|
||||
|
||||
std::size_t SlotIndex(SessionSegmentSlot slot) {
|
||||
const std::size_t index = static_cast<std::size_t>(slot);
|
||||
return index < kSlotCount ? index : 0;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
SessionSegments::~SessionSegments() { Close(); }
|
||||
|
||||
MobileGLResult SessionSegments::Create(const SessionSegmentSizes& sizes, MemoryRole role) {
|
||||
Close();
|
||||
// Set BEFORE the loop, so that Close() on a failure INSIDE it really
|
||||
// closes what has already been created: Close only walks m_owned when
|
||||
// m_owns is true, and setting it afterwards left a failure at segment 3
|
||||
// holding segments 0-2's descriptors and mappings open with Valid()
|
||||
// false, against ShmSegment.h:66's "unmaps and releases the descriptor".
|
||||
m_owns = true;
|
||||
|
||||
struct Spec {
|
||||
const char* name;
|
||||
std::uint64_t bytes;
|
||||
};
|
||||
// The sizes are RING sizes; a segment that carries a control page at its
|
||||
// head is that much bigger. SEG_STAGE drives the SECOND cursor triple of
|
||||
// SEG_CMD's page and SEG_REPLY is not a ring at all, so neither of those
|
||||
// two grows.
|
||||
const Spec specs[kSlotCount] = {
|
||||
{"mgl-cmd", SegmentBytesForRing(sizes.CmdRingBytes)},
|
||||
{"mgl-stage", sizes.StageBytes},
|
||||
{"mgl-reply", sizes.ReplyBytes},
|
||||
{"mgl-event", SegmentBytesForRing(sizes.EventRingBytes)},
|
||||
};
|
||||
for (std::size_t index = 0; index < kSlotCount; ++index) {
|
||||
if (specs[index].bytes == 0) {
|
||||
MGLOG_E("MG_Remote session: segment %s was asked for a ring size that cannot be "
|
||||
"made into one (a ring is a power of two between %llu and %llu bytes)",
|
||||
specs[index].name, static_cast<unsigned long long>(kMinRingCapacity),
|
||||
static_cast<unsigned long long>(kMaxRingCapacity));
|
||||
Close();
|
||||
return MOBILEGL_ERR_INVALID_ARGUMENT;
|
||||
}
|
||||
}
|
||||
|
||||
for (std::size_t index = 0; index < kSlotCount; ++index) {
|
||||
const MobileGLResult created =
|
||||
ShmSegment::Create(specs[index].name, specs[index].bytes, m_owned[index]);
|
||||
if (created != MOBILEGL_OK) {
|
||||
MGLOG_E("MG_Remote session: could not create segment %s of %llu bytes (rc=%d)",
|
||||
specs[index].name, static_cast<unsigned long long>(specs[index].bytes),
|
||||
static_cast<int>(created));
|
||||
Close();
|
||||
return created;
|
||||
}
|
||||
// Read/write on both roles under inproc: they are the same mapping.
|
||||
// P6's read-only peer view is a property of the ADOPT path, not of
|
||||
// this one, and pretending otherwise here would give the inproc lane
|
||||
// a protection the spawn lane does not reproduce.
|
||||
const MobileGLResult mapped = m_owned[index].Map(false);
|
||||
if (mapped != MOBILEGL_OK) {
|
||||
MGLOG_E("MG_Remote session: could not map segment %s (rc=%d)", specs[index].name,
|
||||
static_cast<int>(mapped));
|
||||
Close();
|
||||
return mapped;
|
||||
}
|
||||
}
|
||||
|
||||
m_replySlotCount = sizes.ReplySlotCount;
|
||||
DeriveViews();
|
||||
if (!m_valid) {
|
||||
Close();
|
||||
return MOBILEGL_ERR_INVALID_ARGUMENT;
|
||||
}
|
||||
|
||||
// Both control pages, zeroed with their generations at 1. The owner does
|
||||
// this exactly once; the inproc peer must NOT, or it would zero the
|
||||
// cursors out from under whoever is already using them.
|
||||
InitRingControl(*m_cmdControl);
|
||||
InitRingControl(*m_eventControl);
|
||||
|
||||
m_role = role;
|
||||
LedgerAddSegment(role, m_mappedBytes);
|
||||
m_booked = true;
|
||||
return MOBILEGL_OK;
|
||||
}
|
||||
|
||||
MobileGLResult SessionSegments::AttachInProcess(SessionSegments& owner, MemoryRole role) {
|
||||
Close();
|
||||
if (!owner.Valid()) {
|
||||
return MOBILEGL_ERR_NOT_INITIALIZED;
|
||||
}
|
||||
#if !defined(_WIN32)
|
||||
// A REAL SECOND MAPPING, not an alias. dup + Adopt + Map is byte for byte
|
||||
// the call sequence P6's SCM_RIGHTS client runs, so mapping, the fstat
|
||||
// size check inside Adopt (ShmSegmentPosix.cpp:119-141), alignment and the
|
||||
// peer's own lifetime are all exercised now rather than on the day the
|
||||
// second process appears. Aliasing the owner's ShmSegment objects would
|
||||
// leave the attach half untested for exactly the reason this file refuses
|
||||
// to allocate the rings with new[].
|
||||
m_owns = true;
|
||||
for (std::size_t index = 0; index < kSlotCount; ++index) {
|
||||
const ShmSegment* theirs = owner.m_segments[index];
|
||||
const int duplicate = theirs == nullptr ? -1 : ::dup(theirs->Fd());
|
||||
if (duplicate < 0) {
|
||||
MGLOG_E("MG_Remote session: could not dup the owner's descriptor for segment %zu",
|
||||
index);
|
||||
Close();
|
||||
return MOBILEGL_ERR_INVALID_ARGUMENT;
|
||||
}
|
||||
// Adopt takes ownership of `duplicate` on success only.
|
||||
const MobileGLResult adopted =
|
||||
ShmSegment::Adopt(duplicate, theirs->Size(), m_owned[index]);
|
||||
if (adopted != MOBILEGL_OK) {
|
||||
::close(duplicate);
|
||||
Close();
|
||||
return adopted;
|
||||
}
|
||||
// Read/write: under inproc the client writes SEG_CMD and SEG_STAGE and
|
||||
// reads SEG_REPLY and SEG_EVENT, and one ShmSegment maps the whole
|
||||
// thing one way. The per-segment read-only peer view is P6's, where
|
||||
// the roles are separable.
|
||||
const MobileGLResult mapped = m_owned[index].Map(false);
|
||||
if (mapped != MOBILEGL_OK) {
|
||||
Close();
|
||||
return mapped;
|
||||
}
|
||||
}
|
||||
#else
|
||||
// Windows has no Adopt (ShmSegment::Adopt is POSIX-only; a Windows peer
|
||||
// resolves the section by the name carried in SegmentRef). Alias, and say
|
||||
// so: this arm does not exercise the attach path P6 replaces.
|
||||
for (std::size_t index = 0; index < kSlotCount; ++index) {
|
||||
m_segments[index] = owner.m_segments[index];
|
||||
}
|
||||
m_owns = false;
|
||||
#endif
|
||||
m_replySlotCount = owner.m_replySlotCount;
|
||||
DeriveViews();
|
||||
if (!m_valid) {
|
||||
Close();
|
||||
return MOBILEGL_ERR_INVALID_ARGUMENT;
|
||||
}
|
||||
m_role = role;
|
||||
// Booked under this role as well, and that double-counting is the point:
|
||||
// the pages are shared under inproc and are NOT shared under spawn, so
|
||||
// the per-role numbers are what t1 subtracts with.
|
||||
LedgerAddSegment(role, m_mappedBytes);
|
||||
m_booked = true;
|
||||
return MOBILEGL_OK;
|
||||
}
|
||||
|
||||
void SessionSegments::DeriveViews() {
|
||||
m_valid = false;
|
||||
if (m_owns) {
|
||||
for (std::size_t index = 0; index < kSlotCount; ++index) {
|
||||
m_segments[index] = &m_owned[index];
|
||||
}
|
||||
}
|
||||
for (std::size_t index = 0; index < kSlotCount; ++index) {
|
||||
if (m_segments[index] == nullptr || m_segments[index]->Data() == nullptr) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
auto* cmdBase = static_cast<std::uint8_t*>(m_segments[0]->Data());
|
||||
m_cmdControl = reinterpret_cast<RingControl*>(cmdBase);
|
||||
m_cmdRingBase = cmdBase + sizeof(RingControl);
|
||||
m_cmdRingCapacity = RingCapacityForSegment(m_segments[0]->Size());
|
||||
|
||||
// SEG_STAGE IS NOT A RING: no control page, no cursor triple, no power-of-
|
||||
// two rounding. Package w1's encoder owns it as a linear allocator that
|
||||
// reclaims on retiredSeq, so the whole mapping is usable bytes.
|
||||
m_stageBase = m_segments[1]->Data();
|
||||
m_stageBytes = m_segments[1]->Size();
|
||||
|
||||
m_replyBase = m_segments[2]->Data();
|
||||
m_replyBytes = m_segments[2]->Size();
|
||||
|
||||
auto* eventBase = static_cast<std::uint8_t*>(m_segments[3]->Data());
|
||||
m_eventSegmentBase = eventBase;
|
||||
m_eventControl = reinterpret_cast<RingControl*>(eventBase);
|
||||
m_eventRingBase = eventBase + sizeof(RingControl);
|
||||
m_eventRingCapacity = RingCapacityForSegment(m_segments[3]->Size());
|
||||
|
||||
m_mappedBytes = 0;
|
||||
for (std::size_t index = 0; index < kSlotCount; ++index) {
|
||||
m_mappedBytes += m_segments[index]->Size();
|
||||
}
|
||||
|
||||
if (m_cmdRingCapacity == 0 || m_stageBytes == 0 || m_eventRingCapacity == 0 ||
|
||||
m_replyBytes == 0) {
|
||||
MGLOG_E("MG_Remote session: segment sizes leave no usable ring (cmd cap=%llu stage "
|
||||
"cap=%llu event cap=%llu reply=%llu). A ring is the largest POWER OF TWO that "
|
||||
"fits after the 4096 byte control page, so a segment must be strictly larger "
|
||||
"than one page plus the smallest ring",
|
||||
static_cast<unsigned long long>(m_cmdRingCapacity),
|
||||
static_cast<unsigned long long>(m_stageBytes),
|
||||
static_cast<unsigned long long>(m_eventRingCapacity),
|
||||
static_cast<unsigned long long>(m_replyBytes));
|
||||
return;
|
||||
}
|
||||
m_valid = true;
|
||||
}
|
||||
|
||||
void SessionSegments::Close() {
|
||||
if (m_booked) {
|
||||
LedgerRemoveSegment(m_role, m_mappedBytes);
|
||||
m_booked = false;
|
||||
}
|
||||
if (m_owns) {
|
||||
for (ShmSegment& segment : m_owned) {
|
||||
segment.Close();
|
||||
}
|
||||
}
|
||||
for (std::size_t index = 0; index < kSlotCount; ++index) {
|
||||
m_segments[index] = nullptr;
|
||||
}
|
||||
m_cmdControl = nullptr;
|
||||
m_cmdRingBase = nullptr;
|
||||
m_cmdRingCapacity = 0;
|
||||
m_stageBase = nullptr;
|
||||
m_stageBytes = 0;
|
||||
m_replyBase = nullptr;
|
||||
m_replyBytes = 0;
|
||||
m_eventControl = nullptr;
|
||||
m_eventSegmentBase = nullptr;
|
||||
m_eventRingBase = nullptr;
|
||||
m_eventRingCapacity = 0;
|
||||
m_mappedBytes = 0;
|
||||
m_owns = false;
|
||||
m_valid = false;
|
||||
}
|
||||
|
||||
std::uint64_t SessionSegments::AnnouncedSize(SessionSegmentSlot slot) const {
|
||||
const ShmSegment* segment = m_segments[SlotIndex(slot)];
|
||||
return segment == nullptr ? 0 : segment->Size();
|
||||
}
|
||||
|
||||
const char* SessionSegments::AnnouncedName(SessionSegmentSlot slot) const {
|
||||
const ShmSegment* segment = m_segments[SlotIndex(slot)];
|
||||
return segment == nullptr ? "" : segment->Name();
|
||||
}
|
||||
|
||||
int SessionSegments::DescriptorFor(SessionSegmentSlot slot) const {
|
||||
const ShmSegment* segment = m_segments[SlotIndex(slot)];
|
||||
return segment == nullptr ? -1 : segment->Fd();
|
||||
}
|
||||
|
||||
} // namespace MobileGL::MG_Remote::Transport
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
|
||||
#include <cstdarg>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
|
||||
namespace MobileGL::MG_Remote::Transport {
|
||||
|
||||
@@ -30,4 +31,23 @@ namespace MobileGL::MG_Remote::Transport {
|
||||
MGLOG_E("%s", line);
|
||||
}
|
||||
|
||||
void WireLogFatal(const char* format, ...) {
|
||||
char line[512];
|
||||
va_list args;
|
||||
va_start(args, format);
|
||||
const int written = std::vsnprintf(line, sizeof(line), format, args);
|
||||
va_end(args);
|
||||
if (written < 0) {
|
||||
std::snprintf(line, sizeof(line),
|
||||
"MG_Remote wire: unformattable Fatal diagnostic (format=%s)", format);
|
||||
}
|
||||
MGLOG_F("%s", line);
|
||||
// The stderr echo is the half a death test can see (WireLog.h). Unbuffered
|
||||
// by default and flushed anyway: abort() does not flush stdio.
|
||||
std::fputs(line, stderr);
|
||||
std::fputc('\n', stderr);
|
||||
std::fflush(stderr);
|
||||
std::abort();
|
||||
}
|
||||
|
||||
} // namespace MobileGL::MG_Remote::Transport
|
||||
|
||||
@@ -19,9 +19,9 @@
|
||||
// the one header under Transport/ that broke the rule; it now calls this
|
||||
// instead, and the umbrella stays inside WireLog.cpp.
|
||||
//
|
||||
// ERROR only, deliberately. Everything routed here is a latched protocol
|
||||
// violation, never per-frame noise; non-critical wire lines use MGLOG_D from a
|
||||
// .cpp, where the INFO build compiles them out entirely.
|
||||
// ERROR and FATAL only, deliberately. Everything routed here is a latched
|
||||
// protocol violation, never per-frame noise; non-critical wire lines use
|
||||
// MGLOG_D from a .cpp, where the INFO build compiles them out entirely.
|
||||
|
||||
#pragma once
|
||||
|
||||
@@ -35,4 +35,25 @@ namespace MobileGL::MG_Remote::Transport {
|
||||
void
|
||||
WireLogError(const char* format, ...);
|
||||
|
||||
// Formats one line, emits it at FATAL level (MGLOG_F), ECHOES IT TO STDERR,
|
||||
// and aborts. Every `Fatal{...}` this layer raises goes through here.
|
||||
//
|
||||
// WHY STDERR AS WELL. Defines.h builds the logger with the console sink OFF
|
||||
// and the file sink ON, so an MGLOG line reaches exactly one place: the log
|
||||
// file. A Fatal is the last thing the process says, and three readers need
|
||||
// it somewhere other than a file whose path they may not know: a terminal,
|
||||
// a CI job log, and a gtest death test - which matches its regex against
|
||||
// the CHILD'S STDERR and nothing else. The wave-1 review (ID-46 finding 10)
|
||||
// found both SessionTestDeath controls written with an empty regex for
|
||||
// precisely that reason: with the diagnostic reachable only through the
|
||||
// file sink there was nothing on stderr to name, so a bare std::abort() or
|
||||
// a segfault satisfied them. The echo is what lets a death control name
|
||||
// its diagnostic (R-16: a negative control asserts its own failure reason).
|
||||
[[noreturn]]
|
||||
#if defined(__GNUC__) || defined(__clang__)
|
||||
__attribute__((format(printf, 1, 2)))
|
||||
#endif
|
||||
void
|
||||
WireLogFatal(const char* format, ...);
|
||||
|
||||
} // namespace MobileGL::MG_Remote::Transport
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -111,12 +111,89 @@ namespace MobileGL::MG_Remote::Wire {
|
||||
|
||||
// R-2.3 arms 1-4 over one record's blobref. Split only; a monolith emission is exempt by
|
||||
// construction because it never reaches this layer.
|
||||
//
|
||||
// ARMS 3 AND 4 ONLY, PLUS ONE THIS FUNCTION HAD TO INVENT. A blobref is honest when it is
|
||||
// EITHER fully declared - a real Seg, a non-zero Size and an Offset+Size inside that
|
||||
// segment - OR fully absent, which is all three fields zero. The third shape, a Seg or an
|
||||
// Offset with Size == 0, is neither, and it is the shape a monolith emitter produces
|
||||
// today (Seg = None, Offset = a host address, Size = 0), so under split it has to be
|
||||
// Fatal rather than "absent": a decoder that read it as absent would silently drop the
|
||||
// bytes of every record an unconverted emitter sent.
|
||||
//
|
||||
// ARM 2 - "Blob.Size == 0 on a CONTENT record" - is NOT here and cannot be: whether a
|
||||
// record carries content is a property of the record's OTHER fields (ChunkMask, the
|
||||
// destination range, GlobalUboSize, the stage mask), which this signature does not see.
|
||||
// RequireDeclaredBlob below is arm 2, and the decoder's per-op arm calls it exactly where
|
||||
// the payload says content is implied.
|
||||
void CheckBlobIsHonest(MG_Pipe::MGPWireOp op, const MG_Pipe::MGPBlobRef& blob,
|
||||
const SegmentTable& segments);
|
||||
// R-2.3 arm for MGHostSpan. P5's reduced path should produce ZERO host spans
|
||||
// R-2.3 arm 2: the record's other fields say it carries content, so the blob must be
|
||||
// declared. Fatal on an absent blob, then CheckBlobIsHonest on a present one.
|
||||
void RequireDeclaredBlob(MG_Pipe::MGPWireOp op, const MG_Pipe::MGPBlobRef& blob,
|
||||
const SegmentTable& segments);
|
||||
// R-2.3 arms 1 and 3 for MGHostSpan. P5's reduced path should produce ZERO host spans
|
||||
// (kCapNeedsHostIndexBytes / kCapNeedsHostUboBytes are both 0 in P5, table 0), so this
|
||||
// firing at all is a finding, not just a corruption check.
|
||||
//
|
||||
// IT CANNOT DO ARM 4 - it has no segment table - so a span that names a real segment and a
|
||||
// run PAST THE END OF IT passes this function. Use the overload below on any path that has
|
||||
// a table; this one exists because c0 shipped the signature and other packages compile
|
||||
// against it.
|
||||
void CheckHostSpanIsHonest(const MG_Pipe::MGHostSpan& span);
|
||||
// All four arms. Arm 4 is the one the signature above cannot express: a span is only
|
||||
// honest if its Offset+Size actually lies inside the segment it names, and the promise
|
||||
// WireVerbSink's header makes - that OnDrawVbo is handed a VALIDATED argument list - is
|
||||
// false without it. Latent in P5 (nothing emits a span) and armed at P8, which is exactly
|
||||
// when nobody will be reading this file.
|
||||
void CheckHostSpanIsHonest(const MG_Pipe::MGHostSpan& span, const SegmentTable& segments);
|
||||
|
||||
// ---- one record's shape, computed ONCE and read by both sides ----------------------
|
||||
//
|
||||
// THE TAIL CROSS-CHECK LIVES HERE AND NOWHERE ELSE (BRIEF §5 w1, contract table 1 group
|
||||
// B). MGP_WIRE_CHECK_BOUNDS only proves `size >= sizeof(MGPWireRec_X)` - IT CANNOT SEE
|
||||
// THE TAIL - so a record declaring Count = 4000 while carrying 8 bytes passes it. The
|
||||
// encoder computes this layout from the payload it is about to write and REFUSES a caller
|
||||
// whose tails disagree; the decoder computes the same layout from the payload it just
|
||||
// received and REFUSES a record whose MGPWireRecHeader::Size disagrees. Two readers, one
|
||||
// arithmetic, so the two sides cannot drift.
|
||||
//
|
||||
// EVERY TAIL STARTS 8-BYTE ALIGNED WITHIN THE RECORD, and the encoder zero-fills the gap.
|
||||
// Eight of the nine kVarTail rows are already aligned by construction (their payload and
|
||||
// element sizes are multiples of 8); DrawVbo is not - MGPDrawRange is TWELVE bytes, so an
|
||||
// odd NumDraws leaves the conditional MGHostSpan on a 4-byte boundary, and MGHostSpan
|
||||
// holds a pointer and two Uint64s. P5 emits no host span at all, so this rule costs
|
||||
// nothing now and is stated now because the phase that arms kDrawHasUserIndices would
|
||||
// otherwise have to discover it as a misaligned load on a device.
|
||||
struct WireRecordLayout {
|
||||
Uint64 PayloadBytes = 0; // sizeof the op's payload struct
|
||||
Uint64 TailOffset[2] = {0, 0}; // from the START of the record, header included
|
||||
Uint64 TailBytes[2] = {0, 0};
|
||||
Uint32 TailCount = 0;
|
||||
Uint64 TotalBytes = 0; // header + payload + gaps + tails, rounded up to 8
|
||||
// P5b: WHAT THE SECOND TAIL IS. SetShaderBuffers' second tail is MGHostSpan[HostSpanCount]
|
||||
// and DrawVbo's is EITHER the user-index MGHostSpan (kDrawHasUserIndices) OR one
|
||||
// MGPDrawIndirect (kDrawIsIndirect, CONTRACT-P5B.md d1). The encoder's host-span
|
||||
// honesty pass reads this rather than "tail 2 exists", because a 40-byte indirect
|
||||
// block read as spans is one span and a quarter of garbage.
|
||||
Bool SecondTailIsHostSpans = false;
|
||||
};
|
||||
|
||||
// `payload` must already be known to hold at least the op's payload struct - that is what
|
||||
// MGP_WIRE_CHECK_BOUNDS proves, and this function is only ever called after it. Returns
|
||||
// false for an opcode outside the catalogue; a count past its own GL bound is Fatal,
|
||||
// because a decoder holding such a record has nothing safe left to do with it.
|
||||
Bool MGPipeWireRecordLayout(MG_Pipe::MGPWireOp op, const void* payload, WireRecordLayout& out);
|
||||
|
||||
// The catalogue's own spelling of an opcode, for a Fatal line. Out of range is "<opcode>".
|
||||
const char* WireOpName(MG_Pipe::MGPWireOp op);
|
||||
|
||||
// One tail array. Two of the 71 rows carry two (SetShaderBuffers, SetStreamOutputTargets)
|
||||
// and DrawVbo carries a conditional second one, which is why EncodeRecord's one-tail form
|
||||
// could not stay the only one.
|
||||
struct WireTail {
|
||||
const void* Bytes = nullptr;
|
||||
Uint64 Size = 0;
|
||||
};
|
||||
|
||||
// ---- encoder -----------------------------------------------------------------------
|
||||
//
|
||||
@@ -150,6 +227,50 @@ namespace MobileGL::MG_Remote::Wire {
|
||||
Uint64 EncodeRecord(MG_Pipe::MGPWireOp op, const void* payload, Uint64 payloadBytes,
|
||||
const void* varTail = nullptr, Uint64 varTailBytes = 0);
|
||||
|
||||
// The same call for the three rows that carry TWO tails. The one-tail form above is
|
||||
// this one with tailCount <= 1; nothing is duplicated between them.
|
||||
//
|
||||
// The tails a caller hands over are CROSS-CHECKED against the layout the payload
|
||||
// itself declares (MGPipeWireRecordLayout): a caller whose Count says 4000 while its
|
||||
// tail holds 8 bytes is Fatal HERE, on the producing side, rather than on a peer that
|
||||
// can only report a corrupt stream. That is the same arithmetic the decoder runs, so
|
||||
// the check is real rather than a restatement of the caller's own belief.
|
||||
Uint64 EncodeRecord(MG_Pipe::MGPWireOp op, const void* payload, Uint64 payloadBytes,
|
||||
const WireTail* tails, Uint32 tailCount);
|
||||
|
||||
// Releases every SEG_STAGE run named by a record the apply side has RETIRED
|
||||
// (RingControl::retiredSeq, R-9, which this class only ever READS). Called from
|
||||
// Publish() and whenever StageBytes runs short, so nothing outside this package has to
|
||||
// remember to; the allocator reclaims behind retiredSeq and nothing else may
|
||||
// (table 1's "retires" column, R-11).
|
||||
//
|
||||
// THE MARK IS HELD ON THIS SIDE, NOT ON THE WIRE. A record does not carry where its
|
||||
// staged bytes end, so the encoder remembers {seq, stage cursor} per record and
|
||||
// reclaims to the newest mark whose seq the server has retired. That is exact, needs
|
||||
// no wire field, and does not depend on the verb barrier - so it keeps working when
|
||||
// R-1's barrier retires family by family.
|
||||
//
|
||||
// SEG_STAGE'S CURSOR TRIPLE IN RingControl IS NOT USED BY EITHER SIDE IN P5, and this
|
||||
// is the reason. Ring.h makes stageAppliedTail / stageRetiredTail CONSUMER-owned, the
|
||||
// server never Pops the stage ring (the decoder resolves by offset), and a producer
|
||||
// that wrote those cursors would be the very shape R-9 forbids one segment over. So
|
||||
// the allocator below is entirely encoder-local and the triple is left at its
|
||||
// InitRingControl values. **s1 must not attach a RingConsumer to
|
||||
// RingCursorSet::Stage**: its m_localTail would never move, and PublishApplied /
|
||||
// PublishRetired would then walk both cursors BACKWARDS under this allocator.
|
||||
void ReclaimStagedBytes();
|
||||
// Staged bytes not yet reclaimed. The number MOBILEGL_IPC_STAGE_MB has to cover.
|
||||
Uint64 StagedBytesInFlight() const;
|
||||
// The {seq, cursor} marks the queue is STILL STORING, consumed ones included - not the
|
||||
// number in flight. Bounded by twice the records in flight, and exposed so a case can
|
||||
// assert that bound rather than trust the comment, because an unbounded queue here is
|
||||
// a steady-state leak no SSIM comparison and no two-scenario lane would ever see.
|
||||
//
|
||||
// It reports the storage deliberately: the in-flight count stays at one or two while
|
||||
// the container behind it grows for ever, so a control written against that number
|
||||
// goes green through exactly the leak it exists to catch.
|
||||
SizeT StageMarksHeld() const;
|
||||
|
||||
// Release-stores the head cursor, then rings the consumer doorbell IF PARKED. The
|
||||
// order is pinned by RingTest.cpp:446 and must not be swapped: notify-then-publish
|
||||
// loses the wakeup.
|
||||
@@ -163,12 +284,41 @@ namespace MobileGL::MG_Remote::Wire {
|
||||
Uint64 MaxRecordBytesSeen() const;
|
||||
|
||||
private:
|
||||
// {the record's seq, the SEG_STAGE cursor just past everything that record named}.
|
||||
struct StageMark {
|
||||
Uint64 Seq = 0;
|
||||
Uint64 StageCursor = 0;
|
||||
};
|
||||
|
||||
// The SEG_STAGE linear allocator (BRIEF §5 w1's own wording). Monotonic byte counters
|
||||
// over the segment; the in-segment offset is `cursor % capacity` and a run that would
|
||||
// straddle the end skips to the boundary, exactly as a ring does, but WITHOUT touching
|
||||
// RingControl - see ReclaimStagedBytes above.
|
||||
Uint8* StageAllocate(Uint64 size);
|
||||
|
||||
// AN EMPTY STAGE STARTS OVER AT ZERO, so that the wrap skip is only ever charged
|
||||
// against bytes that are really still in flight. Head and tail are monotonic, so once
|
||||
// everything has retired they are EQUAL BUT NOT ZERO, and `head % capacity` is
|
||||
// wherever the last run happened to end - a wrap skip charged against that offset
|
||||
// costs the suffix a second time and refused a blob the whole segment could hold, with
|
||||
// a message that reported zero bytes in flight while it did so. Rebasing also rewrites
|
||||
// the marks still held: a mark stores an ABSOLUTE head cursor and a later reclaim
|
||||
// assigns it to m_stageTail, so leaving a stale one behind would drive the tail past
|
||||
// the head and underflow StagedBytesInFlight().
|
||||
void RebaseEmptyStage();
|
||||
|
||||
Transport::RingControl* m_control = nullptr;
|
||||
Transport::RingProducer* m_cmd = nullptr;
|
||||
Transport::RingProducer* m_stage = nullptr;
|
||||
SegmentTable* m_segments = nullptr;
|
||||
Uint64 m_emitSeq = kInvalidSeq;
|
||||
Uint64 m_maxRecordBytes = 0;
|
||||
Vector<StageMark> m_stageMarks;
|
||||
SizeT m_stageMarkFront = 0;
|
||||
Uint8* m_stageBase = nullptr;
|
||||
Uint64 m_stageCapacity = 0;
|
||||
Uint64 m_stageHead = 0; // monotonic bytes allocated
|
||||
Uint64 m_stageTail = 0; // monotonic bytes reclaimed
|
||||
};
|
||||
|
||||
// ---- decoder -----------------------------------------------------------------------
|
||||
@@ -189,6 +339,139 @@ namespace MobileGL::MG_Remote::Wire {
|
||||
virtual void PostReply(Uint64 seq, Int32 status, const void* bytes, Uint64 size) = 0;
|
||||
};
|
||||
|
||||
// ---- the verb sink: the five rows with no MGPipeApply* to delegate to ---------------
|
||||
//
|
||||
// The decoder owns NO semantics, so every arm ends in an existing MGPipeApply* free
|
||||
// function - except five, and they are exactly contract §7's class B: Clear (57), Blit
|
||||
// (56), ReadPixels (58), DrawVbo (59) and Present (67). Those are GLFunctionsTable VERBS.
|
||||
// MG_Pipe has no applier for any of them (the 37 MGPipeApply* entry points are the object
|
||||
// and state families), so for these five P5 writes the first consumer as well as the first
|
||||
// producer - and the consumer is the SERVER'S backend call, which is v1's, not the codec's.
|
||||
//
|
||||
// So the codec does what it can prove and stops there: it bounds-checks, cross-checks the
|
||||
// tail, resolves the segments and hands over a DECODED, VALIDATED argument list. With no
|
||||
// sink installed those five arms return false ("this build does not implement it"), which
|
||||
// is the same answer the other unimplemented rows give.
|
||||
//
|
||||
// SetShaderBuffers (38) and SetStreamOutputTargets (39) also have no applier entry point,
|
||||
// and they deliberately get NO sink method: both are off P5's reduced path (BRIEF §4's
|
||||
// exclusion list), so inventing a consumer for them would be building a semantics nobody
|
||||
// can test this phase. Their arms validate both tails - which is the part a later phase
|
||||
// must not have to re-derive - and return false.
|
||||
class WireVerbSink {
|
||||
public:
|
||||
virtual ~WireVerbSink() = default;
|
||||
virtual Bool OnClear(const MG_Pipe::MGPClear& clear) {
|
||||
(void)clear;
|
||||
return false;
|
||||
}
|
||||
virtual Bool OnBlit(const MG_Pipe::MGPBlit& blit) {
|
||||
(void)blit;
|
||||
return false;
|
||||
}
|
||||
virtual Bool OnPresent(const MG_Pipe::MGPPresent& present) {
|
||||
(void)present;
|
||||
return false;
|
||||
}
|
||||
// The pixels go back in the reply slot (contract table 1 row 23: the destination is
|
||||
// ALWAYS SEG_REPLY in P5, which is why MGPReadbackInfo gains no Seg field), so the
|
||||
// sink is handed the seq and the sink it must answer into.
|
||||
virtual Bool OnReadPixels(const MG_Pipe::MGPReadbackInfo& info, Uint64 seq, ReplySink* replies) {
|
||||
(void)info;
|
||||
(void)seq;
|
||||
(void)replies;
|
||||
return false;
|
||||
}
|
||||
// `ranges` is info.NumDraws entries. `userIndices` is null unless the record set
|
||||
// kDrawHasUserIndices; `indirect` is null unless it set kDrawIsIndirect (P5b d1,
|
||||
// CONTRACT-P5B.md). The layout refuses a record that sets both, so at most one of the
|
||||
// two is non-null. The span is VALIDATED (all four R-2 arms, the segment-range one
|
||||
// included) and names a SEG_STAGE run the client staged; the sink resolves it through
|
||||
// MG_Pipe::MGPipeHostBytes and never holds the pointer past its return (rule C).
|
||||
virtual Bool OnDrawVbo(const MG_Pipe::MGPDrawInfo& info, const MG_Pipe::MGPDrawRange* ranges,
|
||||
const MG_Pipe::MGHostSpan* userIndices,
|
||||
const MG_Pipe::MGPDrawIndirect* indirect) {
|
||||
(void)info;
|
||||
(void)ranges;
|
||||
(void)userIndices;
|
||||
(void)indirect;
|
||||
return false;
|
||||
}
|
||||
|
||||
// ---- P5b (MG_Remote/CONTRACT-P5B.md): the rows the four migration packages consume.
|
||||
//
|
||||
// Every one below is a GLFunctionsTable verb with NO MGPipeApply* entry point - the
|
||||
// census's correction - so, exactly like the five above, the codec validates and hands
|
||||
// over and the SERVER'S sink (Server/PipeApplier.cpp's ServerVerbSink) makes the
|
||||
// backend call. The default bodies return false ("this build does not implement it");
|
||||
// ServerVerbSink's stubs die Fatal{UnmigratedVerb, "<GL slot>"} by name until the owning
|
||||
// package lands the real body, so a client that flips a slot ahead of its server half
|
||||
// aborts with the same line the census greps rather than rendering nothing.
|
||||
//
|
||||
// i1 OnLaunchGrid, OnMemoryBarrier, OnResourceCopyRegion, OnBindShaderImage,
|
||||
// OnSetStorageBlockBinding
|
||||
// t2 OnBeginStreamOutput, OnEndStreamOutput, OnPauseStreamOutput,
|
||||
// OnResumeStreamOutput, OnBindStreamOutput, OnPatchParameter
|
||||
// f1 OnGenerateMipmap, OnCopyFramebufferToTexture (and OnClear's non-Whole kinds)
|
||||
// d1 OnDrawVbo's indirect tail and user-index span (above)
|
||||
virtual Bool OnLaunchGrid(const MG_Pipe::MGPGridInfo& grid) {
|
||||
(void)grid;
|
||||
return false;
|
||||
}
|
||||
virtual Bool OnMemoryBarrier(const MG_Pipe::MGPMemoryBarrier& barrier) {
|
||||
(void)barrier;
|
||||
return false;
|
||||
}
|
||||
virtual Bool OnResourceCopyRegion(const MG_Pipe::MGPCopyRegion& copy) {
|
||||
(void)copy;
|
||||
return false;
|
||||
}
|
||||
virtual Bool OnBindShaderImage(const MG_Pipe::MGPImageBind& bind) {
|
||||
(void)bind;
|
||||
return false;
|
||||
}
|
||||
// `name` is the NUL-terminated block name the decoder copied out of the record's
|
||||
// SEG_STAGE blob; valid for the call only.
|
||||
virtual Bool OnSetStorageBlockBinding(const MG_Pipe::MGPStorageBlockBinding& binding,
|
||||
const char* name) {
|
||||
(void)binding;
|
||||
(void)name;
|
||||
return false;
|
||||
}
|
||||
virtual Bool OnBeginStreamOutput(const MG_Pipe::MGPStreamOutputBegin& begin) {
|
||||
(void)begin;
|
||||
return false;
|
||||
}
|
||||
virtual Bool OnEndStreamOutput(const MG_Pipe::MGPXfbAccounting& accounting) {
|
||||
(void)accounting;
|
||||
return false;
|
||||
}
|
||||
virtual Bool OnPauseStreamOutput(const MG_Pipe::MGPStreamOutputControl& control) {
|
||||
(void)control;
|
||||
return false;
|
||||
}
|
||||
virtual Bool OnResumeStreamOutput(const MG_Pipe::MGPStreamOutputControl& control) {
|
||||
(void)control;
|
||||
return false;
|
||||
}
|
||||
virtual Bool OnBindStreamOutput(const MG_Pipe::MGPStreamOutputBind& bind) {
|
||||
(void)bind;
|
||||
return false;
|
||||
}
|
||||
virtual Bool OnPatchParameter(const MG_Pipe::MGPPatchParameter& patch) {
|
||||
(void)patch;
|
||||
return false;
|
||||
}
|
||||
virtual Bool OnGenerateMipmap(const MG_Pipe::MGPMipPlan& plan) {
|
||||
(void)plan;
|
||||
return false;
|
||||
}
|
||||
virtual Bool OnCopyFramebufferToTexture(const MG_Pipe::MGPCopyFromFramebuffer& copy) {
|
||||
(void)copy;
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
// Not thread safe: one decoder on the apply thread, by construction.
|
||||
class PipeWireDecoder {
|
||||
public:
|
||||
@@ -215,16 +498,106 @@ namespace MobileGL::MG_Remote::Wire {
|
||||
// here Fatals, because a pad that reached the decoder has already been counted.
|
||||
Bool DecodeAndApply(const Transport::RingRecordView& record);
|
||||
|
||||
// Advanced by exactly one per applied non-pad record. P5 FORBIDS BATCHING IT (R-9):
|
||||
// the verb barrier's waiter reads it, and a batched watermark makes the client wait
|
||||
// for records the server has not run.
|
||||
// THE DECODER'S OWN TALLY, NOT THE SHARED WATERMARK. Advanced by exactly one per
|
||||
// applied non-pad record.
|
||||
//
|
||||
// RingControl::appliedSeq has exactly ONE writer - s1's SessionConsumer::ApplyOne, +1
|
||||
// per record, pads never counted - and this class writes NO RingControl field at all.
|
||||
// That is deliberate rather than a division of labour: two writers of a watermark is
|
||||
// how a waiter resumes on a record the server has not run, which is what R-9's "never
|
||||
// publish a watermark early" forbids, and there is no checksum on this ring that would
|
||||
// catch it.
|
||||
//
|
||||
// Keeping a private count beside the session's is what makes the batching ban
|
||||
// CHECKABLE instead of merely stated: after every record the two numbers must agree,
|
||||
// and a single counter could not tell a batched publish from an honest one.
|
||||
Uint64 AppliedSeq() const;
|
||||
|
||||
// v1 installs the backend bridge for contract §7's five class-B verbs. Null - the
|
||||
// default - makes those five arms return false rather than invent a semantics.
|
||||
void SetVerbSink(WireVerbSink* sink);
|
||||
WireVerbSink* VerbSink() const;
|
||||
|
||||
// R-2.5 / rule C's mechanical control: with MOBILEGL_IPC_AUDIT=1 every SEG_STAGE byte
|
||||
// this decoder resolved for a record is overwritten with 0xDD once the applier has
|
||||
// RETURNED, so an applier that kept the pointer reads 0xDD on the next frame instead
|
||||
// of bytes that happen to still be there. Off by default; the run is exact - the
|
||||
// decoder poisons what it resolved, not a conservative window.
|
||||
void SetAuditPoison(Bool enabled);
|
||||
Bool AuditPoison() const;
|
||||
// How many staged bytes this decoder has poisoned. Zero with the audit off, and the
|
||||
// number a t1 lane asserts is non-zero with it on: an instrumentation that cannot be
|
||||
// observed to have run is decoration.
|
||||
//
|
||||
// WHAT IT ACTUALLY COVERS is "the blob runs the arm resolved", which today is AT MOST
|
||||
// ONE per record: tails live in SEG_CMD and are never noted, and CreateShaderState's
|
||||
// six per-stage runs are Fatal rather than resolved, so the one archive is the only
|
||||
// multi-kilobyte run in the catalogue that reaches it. The array is eight deep so a
|
||||
// later phase that declares more can fill it without a code change - and overflowing
|
||||
// it is Fatal rather than a silent drop, because a poison that quietly stopped
|
||||
// covering a run is the same failure as no poison at all.
|
||||
Uint64 PoisonedStageBytes() const;
|
||||
|
||||
// R-5's acceptance answer for the four Bool-returning appliers - ResourceCreate,
|
||||
// ResourceRespecify, ResourceSubData, SetTextureParams.
|
||||
//
|
||||
// IT DOES NOT RIDE A REPLY SLOT, and that is a contract conflict this package could
|
||||
// not settle on its own. CONTRACT-P5.md table 0's reply-slot-header row says DECLINED
|
||||
// "is how the four Bool acceptance entry points say false (R-5)", but PipeCalls.def
|
||||
// gives none of those four `kReplySlot` - and table 0 ALSO says kMGPipeCallFlags is
|
||||
// what "every package" reads, so s1 will size ReplyPool from it. Writing
|
||||
// SEG_REPLY[seq % slots] for a record the pool never reserved a slot for overwrites a
|
||||
// waiter's answer, and because the slot header stamps the writer's seq for self-check,
|
||||
// the waiter's check then fails FOR EVER and the barrier hangs rather than returning
|
||||
// something wrong. So the decoder posts a reply only for rows whose flags say
|
||||
// kReplySlot (PostReply itself Fatals otherwise) and exposes the acceptance here
|
||||
// instead. The integrator rules on which half of the contract moves.
|
||||
Bool LastAcceptanceKnown() const;
|
||||
Bool LastAcceptance() const;
|
||||
Uint64 AcceptedRecords() const;
|
||||
Uint64 DeclinedRecords() const;
|
||||
|
||||
// Points MG_Pipe::gMGPipeWireRecordApply at this layer's thunk. Called once from the
|
||||
// constructor and modelled on SegmentTable::InstallProcessResolver, which is the same
|
||||
// shape for the same reason; Uninstall belongs beside that one at teardown. The thunk
|
||||
// is inert without a decoder on the calling thread, so installing it early changes
|
||||
// nothing for a monolith caller of MGPipeApplyWireRecord.
|
||||
static void InstallApplyHook();
|
||||
static void UninstallApplyHook();
|
||||
|
||||
private:
|
||||
Bool ApplyChecked(MG_Pipe::MGPWireOp op, const void* record, Uint64 size);
|
||||
const void* ResolveOrFatal(MG_Pipe::MGPWireOp op, const MG_Pipe::MGPBlobRef& blob);
|
||||
void NoteResolvedRun(MG_Pipe::MGPWireOp op, const MG_Pipe::MGPBlobRef& blob);
|
||||
void PoisonResolvedRuns();
|
||||
// The ONLY way this class answers a record. Fatals if `op` carries no kReplySlot -
|
||||
// see LastAcceptanceKnown() for why that is a Fatal and not a log line.
|
||||
void PostReply(MG_Pipe::MGPWireOp op, Uint64 seq, Int32 status, const void* bytes,
|
||||
Uint64 size);
|
||||
|
||||
friend Bool MGPipeWireRecordApplyThunk(MG_Pipe::MGPWireOp, const void*, Uint64, Uint64);
|
||||
|
||||
Transport::RingControl* m_control = nullptr;
|
||||
SegmentTable* m_segments = nullptr;
|
||||
ReplySink* m_replies = nullptr;
|
||||
WireVerbSink* m_verbs = nullptr;
|
||||
Uint64 m_applySeq = kInvalidSeq;
|
||||
Bool m_auditPoison = false;
|
||||
Uint64 m_poisonedBytes = 0;
|
||||
Bool m_lastAcceptanceKnown = false;
|
||||
Bool m_lastAcceptance = false;
|
||||
Uint64 m_accepted = 0;
|
||||
Uint64 m_declined = 0;
|
||||
// The SEG_STAGE runs the record being applied resolved, for the 0xDD fill. Eight deep
|
||||
// so CreateShaderState's seven blob members plus a tail would fit if a later phase
|
||||
// declares them; today at most one run is ever noted (see PoisonedStageBytes).
|
||||
MG_Pipe::MGPBlobRef m_resolved[8];
|
||||
Uint32 m_resolvedCount = 0;
|
||||
};
|
||||
|
||||
// The hook MGPipeApplyWireRecord dispatches to once its generated per-opcode bounds gate
|
||||
// has passed. Inert unless a decoder is active on the calling thread.
|
||||
Bool MGPipeWireRecordApplyThunk(MG_Pipe::MGPWireOp op, const void* record, Uint64 size,
|
||||
Uint64 remaining);
|
||||
|
||||
} // namespace MobileGL::MG_Remote::Wire
|
||||
|
||||
@@ -12,6 +12,14 @@
|
||||
|
||||
#include <atomic>
|
||||
#include <MG_Pipe/PipeMutation.h>
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
// The client role's persistent-map tracker. MG_State reaching into MG_Remote/Client is the
|
||||
// layering ARCHITECTURE.md:575 names - the CLIENT role IS MG_State plus MG_Impl - and the
|
||||
// edge exists only in a build that has the transport at all.
|
||||
#include <MG_Remote/Client/GpuWritePending.h>
|
||||
#include <MG_Remote/Client/PersistentMapTracker.h>
|
||||
#include <MG_Util/Metrics/PipeStats.h>
|
||||
#endif
|
||||
|
||||
namespace MobileGL::MG_State::GLState {
|
||||
namespace {
|
||||
@@ -47,6 +55,13 @@ namespace MobileGL::MG_State::GLState {
|
||||
}
|
||||
|
||||
BufferObject::~BufferObject() {
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
// Unconditional, not behind PushIsArmed(): the transport mode cannot change, but the
|
||||
// tracker is a leaked singleton whose entries are raw pointers, and an entry that
|
||||
// outlives its object is the one failure this set must not have. Forget is a no-op
|
||||
// for a buffer that was never a member.
|
||||
MG_Remote::Client::PersistentMapTracker::Instance().Forget(*this);
|
||||
#endif
|
||||
#if MOBILEGL_PIPE_PUSH
|
||||
// P3a D-L: the buffer's death crosses as resource_destroy, which is the catalogue
|
||||
// call for it - no seventh NotifyStateObjectDestroyed raiser is added, because that
|
||||
@@ -166,6 +181,12 @@ namespace MobileGL::MG_State::GLState {
|
||||
}
|
||||
m_size = size;
|
||||
m_resource.ResizeShadow(size);
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
// The store this buffer's membership was about no longer exists, and ResizeShadow is
|
||||
// reserve+resize - a grow past the reserve reallocates - so a pushed block's source
|
||||
// base has moved too. Both are the same event to the tracker: re-read the predicate.
|
||||
NotePersistentMapStateChanged();
|
||||
#endif
|
||||
}
|
||||
|
||||
void BufferObject::Respecify(SizeT size, const void* data) {
|
||||
@@ -238,6 +259,14 @@ namespace MobileGL::MG_State::GLState {
|
||||
if (void* base = MG_Pipe::MGPipeEmitMapPersistent(*this)) m_resource.AdoptPersistentMap(base);
|
||||
return;
|
||||
}
|
||||
#endif
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
// R-6 IS "ALWAYS", AND THIS IS ITS SECOND DOOR. MGPipeApplyMapPersistent declines
|
||||
// every acquisition under split - but a split build whose backend registered no
|
||||
// MGPipe resource ops falls through to the LEGACY hook below, which would mint a real
|
||||
// pointer and adopt it. A donated address is meaningless across a process, and an
|
||||
// inproc lane that adopted would be green for a reason spawn cannot reproduce.
|
||||
if (MG_Config::Transport != MG_Config::TransportMode::Monolith) return;
|
||||
#endif
|
||||
if (g_bufferBackendOps == nullptr || g_bufferBackendOps->AcquirePersistentMap == nullptr) return;
|
||||
if (void* base = g_bufferBackendOps->AcquirePersistentMap(*this)) {
|
||||
@@ -303,6 +332,12 @@ namespace MobileGL::MG_State::GLState {
|
||||
m_mappedRange = {0, 0};
|
||||
m_stagingBias = 0;
|
||||
m_ownsStagingData = false;
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
// AFTER the reset, so the predicate reads the post-unmap state, and after the landing
|
||||
// above, so the last bytes of a write map are already on the wire when the record
|
||||
// that says "no live writer" goes out behind them.
|
||||
NotePersistentMapStateChanged();
|
||||
#endif
|
||||
}
|
||||
|
||||
void BufferObject::FlushMemoryRange(SizeT offset, SizeT length) {
|
||||
@@ -339,6 +374,22 @@ namespace MobileGL::MG_State::GLState {
|
||||
}
|
||||
|
||||
void BufferObject::SyncPersistentMappedRange() {
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
// SPLIT: the same span, cut into MOBILEGL_IPC_PERSISTENT_BLOCK_KB blocks, and the
|
||||
// membership test is this function's own early-out chain read by the tracker rather
|
||||
// than re-derived there. The 21 sites that call this (CONTRACT-P5.md section 3: 9
|
||||
// Espryt + 12 Magma) therefore keep pushing at exactly the points monolith pushes
|
||||
// at, which is what makes the split arm comparable to the monolith one at all; they
|
||||
// retire into MG_Remote::Client::PushPersistentMapsBeforeVerb at P8.
|
||||
//
|
||||
// A block size of 0 disables the push (E3(a)'s negative control) and this is where
|
||||
// that is felt: the bytes the application wrote through the pointer never leave, the
|
||||
// frame draws the last uploaded ones, and PersistentCoherentMapScenario goes red.
|
||||
if (MG_Remote::Client::PersistentMapTracker::PushIsArmed()) {
|
||||
MG_Remote::Client::PersistentMapTracker::Instance().PushBlocksFor(*this);
|
||||
return;
|
||||
}
|
||||
#endif
|
||||
if (!m_isMapped) return;
|
||||
// GPU-resident: the app already wrote directly into coherent GPU memory. This is
|
||||
// the whole point of the persistent-map path - the per-draw whole-buffer re-upload
|
||||
@@ -352,6 +403,83 @@ namespace MobileGL::MG_State::GLState {
|
||||
NotifySubData(m_mappedRange.start, m_mappedRange.end - m_mappedRange.start);
|
||||
}
|
||||
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
void BufferObject::PushMappedSpanBlock(SizeT offset, SizeT size) {
|
||||
// NotifySubData and not MGPipeEmitResourceSubData directly: the serial bump, the
|
||||
// defined-content promotion and the legacy-ops fallback are what the monolith span
|
||||
// push does, and a second route to the same record is a second thing to keep in step.
|
||||
if (size == 0) return;
|
||||
NotifySubData(offset, size);
|
||||
if (MG_Util::PipeStats::Enabled()) {
|
||||
// THE persistent-map-push SITE: the bytes an application wrote through a map with
|
||||
// no API call, which a split build therefore has to ship.
|
||||
//
|
||||
// THESE BYTES ARE ALSO COUNTED AS stage-buffer, and that overlap is stated in the
|
||||
// inventory rather than avoided. At tier T2 a pushed block IS an ordinary
|
||||
// resource_subdata, so it reaches Ops_H_SubData, is queued into pendingRanges and
|
||||
// is staged like any other write. Subtracting it at the staging site would make
|
||||
// stage-buffer under-report what the BACKEND actually moves, which is the question
|
||||
// that class exists to answer; the two counters are different questions about the
|
||||
// same bytes and PipeStats.cpp:33-35 now says so.
|
||||
MG_Util::PipeStats::AddBytes(MG_Util::PipeStats::ByteClass::PersistentMapPush,
|
||||
static_cast<Uint64>(size));
|
||||
}
|
||||
}
|
||||
|
||||
void BufferObject::NotePersistentMapStateChanged() {
|
||||
if (!MG_Remote::Client::PersistentMapTracker::PushIsArmed()) return;
|
||||
MG_Remote::Client::PersistentMapTracker::Instance().NoteMapStateChanged(*this);
|
||||
|
||||
// THE LIVE-HOST-WRITES BIT (ARCHITECTURE.md 12, CONTRACT-P5.md section 3). A live
|
||||
// WRITE map - persistent or not - mutates the shadow with no call, no serial and no
|
||||
// epoch, which is exactly why IsBufferDrawCleanByHandle had to ask the frontend object
|
||||
// whether it was mapped. Under a spawn there is no object on that side, so the fact
|
||||
// has to cross; it rides MGPSubData's pad (see MGPipeTypes.h, and b1-v1.md 3.1 for
|
||||
// why not MGPResourceDesc's).
|
||||
//
|
||||
// BOTH EDGES EMIT A RECORD, AND THE RISING ONE IS NOT OPTIONAL. An earlier cut let the
|
||||
// rising edge emit nothing on the grounds that "the next content record carries the
|
||||
// bit anyway" - and for the single idiom this feature exists to serve, a persistently
|
||||
// mapped streaming arena behind a static VAO, there IS no next content record. The
|
||||
// only one is the block push, the push for a vertex/uniform/SSBO map runs inside
|
||||
// EnsureBufferResourceForHandle, and a draw-clean answer SKIPS that ensure
|
||||
// (DirectGLES.cpp:691) and then LATCHES it (:697, vboCleanEpoch - and a coherent
|
||||
// persistent map bumps no mutation epoch, which is its whole point). So: draw 1
|
||||
// pushes, draw 2 probes clean, draw 3 onward never probes again, and the frame draws
|
||||
// frame 1's bytes for ever with no diagnostic. That is Managers.cpp:2650-2655's
|
||||
// regression one layer down, and the rising-edge record is what breaks the cycle: the
|
||||
// server learns a host writer is live BEFORE the first probe, answers dirty while the
|
||||
// map lives, and the ensure - and with it the push - runs every draw.
|
||||
const Bool live = m_isMapped && (m_mappingAccess & BufferMappingAccessBit::Write) &&
|
||||
!m_resource.IsGpuResident();
|
||||
if (live == m_publishedLiveHostWrites) return;
|
||||
m_publishedLiveHostWrites = live;
|
||||
|
||||
// ONE BLOCK, NOT THE SPAN. On the falling edge the span's bytes have already shipped
|
||||
// on this same path (ReleaseMemory lands the staged writes and calls
|
||||
// NotifyFlushMappedRange before this runs); on the rising edge the span has not been
|
||||
// written yet. Either way the record exists to carry the STATE, and the bytes it
|
||||
// carries are real, current and the cheapest honest ones there are. A zero-length
|
||||
// record would have been the alternative and it is illegal by contract rule A.
|
||||
if (m_size == 0) return;
|
||||
const Uint64 blockBytes = MG_Remote::Client::PersistentMapTracker::BlockBytes();
|
||||
// MOBILEGL_IPC_PERSISTENT_BLOCK_KB=0 TURNS THE WHOLE MECHANISM OFF, STATE RECORD
|
||||
// INCLUDED (E3(a)). An earlier cut skipped the blocks and still shipped a whole buffer
|
||||
// here, which meant an unmap delivered the bytes the control exists to withhold - and
|
||||
// a negative control that still delivers them is not a control. With the knob at 0
|
||||
// nothing is published and nothing is pushed, so the probe answers clean, the frame
|
||||
// draws the last uploaded bytes, and PersistentCoherentMapScenario goes red.
|
||||
if (blockBytes == 0) return;
|
||||
const SizeT length = blockBytes >= static_cast<Uint64>(m_size) ? m_size
|
||||
: static_cast<SizeT>(blockBytes);
|
||||
NotifySubData(0, length);
|
||||
}
|
||||
|
||||
Bool BufferObject::HasLiveHostWritesForWire() const {
|
||||
return m_publishedLiveHostWrites;
|
||||
}
|
||||
#endif
|
||||
|
||||
void BufferObject::WritebackFromBackend(DataPtr data, SizeT atOffset) {
|
||||
MOBILEGL_ASSERT(atOffset + data.size <= m_size,
|
||||
"WritebackFromBackend out of bounds: atOffset (%zu) + data.size (%zu) > m_size (%zu)", atOffset,
|
||||
@@ -359,6 +487,19 @@ namespace MobileGL::MG_State::GLState {
|
||||
Memcpy(m_resource.Bytes() + atOffset, data.data, data.size);
|
||||
++m_changeSerial;
|
||||
MGP_NOTE_AGGREGATE(BufferChange);
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
// THE THIRD STATE'S ONLY EXIT. In a split build SyncGpuWrites does NOT clear the
|
||||
// flag before emitting, because between the emission and the answer the shadow is
|
||||
// stale and the object has no way to say so; the answer landing here is what makes it
|
||||
// current, so the answer is what clears. Gated: in monolith SyncGpuWrites has already
|
||||
// cleared by the time the applier calls back, and a second clear here would also
|
||||
// retire a GPU write announced by something other than a readback - a ReadPixels into
|
||||
// a pack PBO writes back through this same function.
|
||||
if (MG_Config::Transport != MG_Config::TransportMode::Monolith &&
|
||||
atOffset == 0 && data.size >= m_size) {
|
||||
m_gpuWritePending = false;
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
void BufferObject::MarkGpuWritten() {
|
||||
@@ -368,6 +509,44 @@ namespace MobileGL::MG_State::GLState {
|
||||
|
||||
void BufferObject::SyncGpuWrites() {
|
||||
if (!m_gpuWritePending) return;
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
// THE THIRD STATE (CONTRACT-P5.md section 3, ARCHITECTURE.md:509). This function has
|
||||
// only ever been able to say "pending" or "not pending", and clearing first is safe
|
||||
// in monolith because the readback is synchronous INSIDE the applier: the caller sees
|
||||
// the reconciled shadow on return. Under a transport there is a third state - the
|
||||
// readback was emitted and the answer has not arrived - which the flag cannot express,
|
||||
// and clearing optimistically leaves the shadow silently stale for the object's life.
|
||||
//
|
||||
// So: emit, then BLOCK until OnBufferWriteback lands, and let the writeback do the
|
||||
// clearing. ARCHITECTURE.md:509 lists "the first CPU read of a GPU-write-pending
|
||||
// buffer" among the UNAVOIDABLE blocking points, because monolith already glFinish()es
|
||||
// here; under R-1's verb barrier the block is nearly free, since the client is already
|
||||
// waiting for appliedSeq to reach the record it just emitted.
|
||||
//
|
||||
// NO NARROWING (ResourceTracker.h:587-592's rangeCount == 1 assertion stays): this
|
||||
// phase only gives the client a conservative set, and a zero-range announcement stays
|
||||
// illegal until P8/P9 make it mean "fully narrowed - nothing is dirty".
|
||||
if (MG_Config::Transport != MG_Config::TransportMode::Monolith) {
|
||||
#if MOBILEGL_PIPE_PUSH
|
||||
if (m_size != 0 && MG_Pipe::MGPipeResourceSubsystemEnabled()) {
|
||||
MG_Pipe::MGPipeEmitResourceReadback(*this);
|
||||
// The wait is the barrier's wait: the reply slot id IS the record's seq, so
|
||||
// "my answer is back" and "appliedSeq reached me" are one condition. With no
|
||||
// session (a build-split lane running monolith, and every unit case) the
|
||||
// emission was synchronous and the writeback has already cleared the flag.
|
||||
MG_Remote::Client::AwaitBufferWriteback(*this);
|
||||
}
|
||||
#endif
|
||||
// A buffer with no readback route - no size, or a backend that registered no
|
||||
// resource ops - can never catch up, and retrying on every subsequent read would
|
||||
// only repeat the same no-op. That is the ONE case the monolith clear covers that
|
||||
// the writeback cannot, so it is spelled out here rather than inherited.
|
||||
if (m_gpuWritePending && !MG_Remote::Client::BufferWritebackIsReachable(*this)) {
|
||||
m_gpuWritePending = false;
|
||||
}
|
||||
return;
|
||||
}
|
||||
#endif
|
||||
// Cleared unconditionally: without a readback op the shadow can never catch up,
|
||||
// and retrying on every subsequent read would only repeat the same no-op.
|
||||
m_gpuWritePending = false;
|
||||
@@ -564,6 +743,12 @@ namespace MobileGL::MG_State::GLState {
|
||||
m_mappingAccess = (read ? BufferMappingAccessBit::Read : BufferMappingAccessBit::Null) |
|
||||
(write ? BufferMappingAccessBit::Write : BufferMappingAccessBit::Null);
|
||||
m_mappedRange = {0, m_size};
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
// glMapBuffer never takes the Persistent bit, so this buffer can never join the
|
||||
// push set - but a WRITE map still mutates the shadow with no call, which is the
|
||||
// half of the live-host-writes bit that is not about the push at all.
|
||||
NotePersistentMapStateChanged();
|
||||
#endif
|
||||
|
||||
if (m_mappingAccess & BufferMappingAccessBit::Write) {
|
||||
// glMapBuffer maps from offset 0, so no bias: the allocation's own
|
||||
@@ -605,6 +790,10 @@ namespace MobileGL::MG_State::GLState {
|
||||
m_resource.AdoptPersistentMap(pushedBase);
|
||||
return true;
|
||||
}
|
||||
#endif
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
// R-6's second door, as in TryAdoptLargeStorage above.
|
||||
if (MG_Config::Transport != MG_Config::TransportMode::Monolith) return false;
|
||||
#endif
|
||||
if (m_size == 0 || g_bufferBackendOps == nullptr || g_bufferBackendOps->AcquirePersistentMap == nullptr) {
|
||||
return false;
|
||||
@@ -641,6 +830,15 @@ namespace MobileGL::MG_State::GLState {
|
||||
m_isMapped = true;
|
||||
m_mappingAccess = access;
|
||||
m_mappedRange = range;
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
// BEFORE the adoption attempt below, deliberately. Under R-6 the acquisition always
|
||||
// declines, so the predicate this publishes is already final; if a later phase ever
|
||||
// mints one, the adoption path notes the change itself (it does now - the call is
|
||||
// beside AdoptPersistentMap) and the entry is withdrawn there rather than never
|
||||
// having been made, which is the order that keeps the set conservative under both
|
||||
// answers.
|
||||
NotePersistentMapStateChanged();
|
||||
#endif
|
||||
|
||||
if (access & BufferMappingAccessBit::Persistent) {
|
||||
m_ownsStagingData = false;
|
||||
@@ -656,13 +854,27 @@ namespace MobileGL::MG_State::GLState {
|
||||
MG_Pipe::MGPipeResourceSubsystemEnabled()) {
|
||||
if (void* pushedBase = MG_Pipe::MGPipeEmitMapPersistent(*this)) {
|
||||
m_resource.AdoptPersistentMap(pushedBase);
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
// An adoption takes the buffer OUT of the push set and out of the
|
||||
// live-host-writes state: the application now writes coherent GPU memory
|
||||
// and there is nothing to ship. Under R-6 this is unreachable; it is here
|
||||
// because the comment below used to claim the adoption path withdrew the
|
||||
// entry and nothing did, which would have left the published bit true
|
||||
// across an adoption until unmap (latent for P11).
|
||||
NotePersistentMapStateChanged();
|
||||
#endif
|
||||
}
|
||||
return m_resource.Bytes() + range.start;
|
||||
}
|
||||
#endif
|
||||
if (!m_resource.IsGpuResident() && (access & BufferMappingAccessBit::Write) &&
|
||||
!(access & BufferMappingAccessBit::FlushExplicit) && g_bufferBackendOps &&
|
||||
g_bufferBackendOps->AcquirePersistentMap) {
|
||||
!(access & BufferMappingAccessBit::FlushExplicit) &&
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
// R-6's second door, as in TryAdoptLargeStorage: no legacy mint under a
|
||||
// transport, whatever the backend registered.
|
||||
MG_Config::Transport == MG_Config::TransportMode::Monolith &&
|
||||
#endif
|
||||
g_bufferBackendOps && g_bufferBackendOps->AcquirePersistentMap) {
|
||||
if (void* base = g_bufferBackendOps->AcquirePersistentMap(*this)) {
|
||||
m_resource.AdoptPersistentMap(base);
|
||||
}
|
||||
|
||||
@@ -187,6 +187,49 @@ namespace MobileGL {
|
||||
// from every path that reads the shadow on the app's behalf.
|
||||
void SyncGpuWrites();
|
||||
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
// ---- P5 b1: the two things a split build has to do that a monolith does not ---
|
||||
//
|
||||
// Everything here is behind the build option AND behind
|
||||
// `MG_Config::Transport != Monolith` at the call site, because an extra
|
||||
// resource_subdata record or an extra respecify on the monolith path is new
|
||||
// behaviour and D-J forbids it. The pull build compiles none of it, which is also
|
||||
// how G1 holds over a file this central.
|
||||
|
||||
// ONE MOBILEGL_IPC_PERSISTENT_BLOCK_KB BLOCK of the mapped span, emitted through
|
||||
// the private NotifySubData - the same serial, the same defined-content flag, the
|
||||
// same record - so the split arm and the monolith arm differ in HOW the span is
|
||||
// cut and in nothing else. Called only by
|
||||
// MG_Remote::Client::PersistentMapTracker, which owns the cutting.
|
||||
void PushMappedSpanBlock(SizeT offset, SizeT size);
|
||||
|
||||
// Called on every event that can move the tracker's membership predicate: map,
|
||||
// unmap, respecify, adoption, destruction. It is one call rather than an
|
||||
// insert/erase pair on purpose - the predicate is read from this object, so a
|
||||
// caller that had to decide which of the two to call could decide differently
|
||||
// from IsLivePersistentMap and the set would drift from the thing it models.
|
||||
//
|
||||
// It also PUBLISHES the live-host-writes bit when it changes: the server must
|
||||
// know that a write map is live, because such a map mutates the shadow with no
|
||||
// call, no serial and no epoch, and the applier's IsBufferDrawCleanByHandle can
|
||||
// no longer ask this object (there is no object on that side of a spawn).
|
||||
void NotePersistentMapStateChanged();
|
||||
|
||||
// What MGPipeEmitResourceSubData and MGPipeEmitBufferSubDataResident write into
|
||||
// MGPSubData::HasLiveHostWrites. The PUBLISHED value, not the live predicate: the
|
||||
// two are the same by the time any content record is built, and reading the
|
||||
// published one is what makes a record and the edge that announced it agree by
|
||||
// construction.
|
||||
Bool HasLiveHostWritesForWire() const;
|
||||
|
||||
// Is a GPU write still unreconciled? Under split this is the THIRD STATE made
|
||||
// readable: SyncGpuWrites no longer clears optimistically, so between the readback
|
||||
// emission and OnBufferWriteback landing this stays true, and nothing else in the
|
||||
// object can express that. Split-only so the pull build's layout and inlining do
|
||||
// not move (G1).
|
||||
Bool HasOutstandingGpuWrite() const { return m_gpuWritePending; }
|
||||
#endif
|
||||
|
||||
Bool IsMapped() const;
|
||||
Bool IsImmutableStorage() const;
|
||||
SizeT GetSize() const;
|
||||
@@ -264,8 +307,16 @@ namespace MobileGL {
|
||||
Uint64 m_changeSerial = 0;
|
||||
// See HasDefinedContent().
|
||||
Bool m_hasDefinedContent = true;
|
||||
// Set by MarkGpuWritten, cleared by SyncGpuWrites once the shadow is refreshed.
|
||||
// Set by MarkGpuWritten, cleared by SyncGpuWrites once the shadow is refreshed -
|
||||
// and, in a split build, cleared by WritebackFromBackend instead, because there
|
||||
// the answer arrives later than the request. See SyncGpuWrites' definition.
|
||||
Bool m_gpuWritePending = false;
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
// The last value of MGPResourceDesc::HasLiveHostWrites this object published.
|
||||
// Behind the option so the pull build's layout - and therefore every inlined
|
||||
// constructor and accessor in it - does not move (G1).
|
||||
Bool m_publishedLiveHostWrites = false;
|
||||
#endif
|
||||
Range1D m_mappedRange;
|
||||
// The write-map staging store. MapAlignedData because the application is handed a
|
||||
// pointer into it, and biased by m_stagingBias because ARB_map_buffer_alignment
|
||||
|
||||
@@ -23,5 +23,33 @@ if (MSVC)
|
||||
target_compile_options(BufferTest PRIVATE /Zc:preprocessor)
|
||||
endif()
|
||||
|
||||
# P5 b1: the split buffer side - the client GPU-write set, the persistent-map block push and
|
||||
# tier 1 of the flush ladder. Built in EVERY configuration on purpose; the cases that need
|
||||
# MOBILEGL_BUILD_DISAGGREGATED skip elsewhere rather than disappearing, so the ctest name set
|
||||
# is the same in the pull and the push lanes (G2) and build-split removes none of them (G14).
|
||||
add_executable(
|
||||
SplitBufferTest
|
||||
SplitBufferTest.cpp
|
||||
)
|
||||
|
||||
target_include_directories(SplitBufferTest PRIVATE
|
||||
${MGL_ROOT}/include
|
||||
${MGL_ROOT}/MobileGL
|
||||
${MGL_ROOT}/3rdparty/xxHash
|
||||
${MGL_ROOT}/3rdparty/Vulkan-Headers/include
|
||||
${MGL_ROOT}/3rdparty/SPIRV-Reflect
|
||||
)
|
||||
|
||||
target_link_libraries(
|
||||
SplitBufferTest PRIVATE
|
||||
GTest::gtest_main
|
||||
${LINK_LIBRARIES}
|
||||
)
|
||||
|
||||
if (MSVC)
|
||||
target_compile_options(SplitBufferTest PRIVATE /Zc:preprocessor)
|
||||
endif()
|
||||
|
||||
include(GoogleTest)
|
||||
gtest_discover_tests(BufferTest DISCOVERY_TIMEOUT 30 PROPERTIES LABELS unit)
|
||||
gtest_discover_tests(SplitBufferTest DISCOVERY_TIMEOUT 30 PROPERTIES LABELS unit)
|
||||
|
||||
@@ -0,0 +1,603 @@
|
||||
// MobileGL - MobileGL/MG_Test/Buffer/SplitBufferTest.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
|
||||
|
||||
// P5 (b1): the buffer side of the split - the client-side conservative GPU-write set, the
|
||||
// block-granularity persistent-map push, and tier 1 of the flush ladder.
|
||||
//
|
||||
// EVERY CASE IS COMPILED IN ALL FOUR BUILDS AND SKIPS OUTSIDE build-split, deliberately. The
|
||||
// names then exist identically in the pull and the push lane (G2 stays at 0 diff lines) and
|
||||
// build-split adds none of its own (G14 stays at 0 removed), while a lane that cannot run a
|
||||
// case says so instead of quietly not having it.
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include <Config.h>
|
||||
#include <MG_State/GLState/BufferState/BufferObject.h>
|
||||
#include <MG_State/GLState/Core.h>
|
||||
#include <MG_State/GLState/TextureState/TextureObjectBuffer.h>
|
||||
#include <MG_State/GLState/TextureState/TextureState.h>
|
||||
#include <MG_Util/Metrics/PipeStats.h>
|
||||
|
||||
#if MOBILEGL_PIPE_PUSH
|
||||
#include <MG_Backend/DirectGLES/Managers.h>
|
||||
#endif
|
||||
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
#include <MG_Remote/Client/GpuWritePending.h>
|
||||
#include <MG_Remote/Client/PersistentMapTracker.h>
|
||||
#endif
|
||||
|
||||
using namespace MobileGL;
|
||||
|
||||
namespace {
|
||||
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
using MG_State::GLState::BufferObject;
|
||||
using MG_Remote::Client::GpuWriteProducer;
|
||||
using MG_Remote::Client::PersistentMapTracker;
|
||||
|
||||
// A backend that MINTS a persistent mapping, for the one case that needs the adopted arm
|
||||
// (TheAdoptedArmIsNotAMemberAndItIsTheChainRowThatSaysSo). Only AcquirePersistentMap is
|
||||
// filled in: the frontend null-checks every op individually, and a table with one live
|
||||
// member is the smallest thing that makes AcquireMemoryRange's legacy adoption arm fire.
|
||||
// The storage is the CASE's, not this table's - AdoptPersistentMap keeps the pointer and
|
||||
// never owns it - so the base travels through a file-scope variable the case sets and
|
||||
// clears around the one acquisition it wants minted.
|
||||
void* g_mintedPersistentBase = nullptr;
|
||||
void* MintPersistentMap(BufferObject&) { return g_mintedPersistentBase; }
|
||||
const MG_State::GLState::BufferBackendOps g_mintingBufferOps = [] {
|
||||
MG_State::GLState::BufferBackendOps ops{};
|
||||
ops.AcquirePersistentMap = &MintPersistentMap;
|
||||
return ops;
|
||||
}();
|
||||
|
||||
// Everything in this package is gated on `Transport != Monolith`, so every case has to
|
||||
// put the process into a split configuration and put it back. A fixture rather than a
|
||||
// lambda because the tracker is a process-wide singleton and a case that left an entry in
|
||||
// it would poison the next one through a raw pointer to a destroyed buffer - which is
|
||||
// exactly the failure mode the tracker's own Forget() exists to prevent.
|
||||
class SplitBufferSet : public ::testing::Test {
|
||||
protected:
|
||||
void SetUp() override {
|
||||
m_transport = MG_Config::Transport;
|
||||
m_blockKb = MG_Config::Ipc.PersistentBlockKb;
|
||||
m_adoptTier = MG_Config::Ipc.AdoptTier;
|
||||
m_pipeStats = MG_Config::Features.PipeStats;
|
||||
m_context = Move(MG_State::pGLContext);
|
||||
MG_State::pGLContext = MakeUnique<MG_State::GLState::GLContext>();
|
||||
MG_Config::Transport = MG_Config::TransportMode::InProcess;
|
||||
MG_Config::Ipc.PersistentBlockKb = 64;
|
||||
MG_Config::Ipc.AdoptTier = 2;
|
||||
MG_Config::Features.PipeStats = true;
|
||||
MG_Util::PipeStats::Init();
|
||||
PersistentMapTracker::Instance().ClearForTest();
|
||||
MG_Remote::Client::ResetProducerMarkCountsForTest();
|
||||
}
|
||||
void TearDown() override {
|
||||
// Belt and braces for the one case that installs a minting backend: a table left
|
||||
// behind would make the NEXT case's acquisition land in the adopted arm, and every
|
||||
// membership assertion in this file would then be about a different code path.
|
||||
MG_State::GLState::SetBufferBackendOps(nullptr);
|
||||
g_mintedPersistentBase = nullptr;
|
||||
PersistentMapTracker::Instance().ClearForTest();
|
||||
MG_State::pGLContext = Move(m_context);
|
||||
MG_Config::Transport = m_transport;
|
||||
MG_Config::Ipc.PersistentBlockKb = m_blockKb;
|
||||
MG_Config::Ipc.AdoptTier = m_adoptTier;
|
||||
MG_Config::Features.PipeStats = m_pipeStats;
|
||||
MG_Util::PipeStats::Init();
|
||||
}
|
||||
|
||||
static SharedPtr<BufferObject> MakeBuffer(Uint index, SizeT size) {
|
||||
auto buffer = MakeShared<BufferObject>(index);
|
||||
buffer->Respecify(size, nullptr);
|
||||
return buffer;
|
||||
}
|
||||
|
||||
MG_Config::TransportMode m_transport = MG_Config::TransportMode::Monolith;
|
||||
Uint32 m_blockKb = 64;
|
||||
Uint32 m_adoptTier = 2;
|
||||
Bool m_pipeStats = false;
|
||||
UniquePtr<MG_State::GLState::GLContext> m_context;
|
||||
};
|
||||
#endif
|
||||
|
||||
#define MGL_SPLIT_ONLY_OR_SKIP() \
|
||||
do { \
|
||||
GTEST_SKIP() << "the client-side GPU-write set and the persistent-map push exist only in " \
|
||||
"a MOBILEGL_BUILD_DISAGGREGATED build"; \
|
||||
} while (0)
|
||||
|
||||
} // namespace
|
||||
|
||||
// =====================================================================================
|
||||
// The GPU-write set: one case per row of CONTRACT-P5.md section 3's first table.
|
||||
// =====================================================================================
|
||||
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
|
||||
// Row 0 - DirectGLES.cpp:570 / UniformManager.cpp:1231.
|
||||
TEST_F(SplitBufferSet, Row0EverySsboBindingPointIsMarkedByADraw) {
|
||||
auto ssbo = MakeBuffer(11u, 256);
|
||||
MG_State::pGLContext->GetBufferBindingPoint(BufferTarget::ShaderStorage, 0).Bind(ssbo);
|
||||
MG_State::pGLContext->TouchBufferBindingPoint(BufferTarget::ShaderStorage, 0);
|
||||
|
||||
MG_Remote::Client::MarkGpuWritesForDraw();
|
||||
|
||||
EXPECT_EQ(MG_Remote::Client::ProducerMarkCount(GpuWriteProducer::ShaderStorageBinding), 1u)
|
||||
<< "a draw with an SSBO bound must mark it: the shader writes into the driver's buffer, "
|
||||
"behind the shadow glMapBuffer and glGetBufferSubData read";
|
||||
}
|
||||
|
||||
// Row 1 - DirectGLES.cpp:618. The point of a counter is that the shader increments it.
|
||||
TEST_F(SplitBufferSet, Row1EveryBoundAtomicCounterIsMarkedByADraw) {
|
||||
auto counter = MakeBuffer(12u, 64);
|
||||
MG_State::pGLContext->GetBufferBindingPoint(BufferTarget::AtomicCounter, 0).Bind(counter);
|
||||
MG_State::pGLContext->TouchBufferBindingPoint(BufferTarget::AtomicCounter, 0);
|
||||
|
||||
MG_Remote::Client::MarkGpuWritesForDraw();
|
||||
|
||||
EXPECT_EQ(MG_Remote::Client::ProducerMarkCount(GpuWriteProducer::AtomicCounterBinding), 1u);
|
||||
}
|
||||
|
||||
// Row 2's DISCRIMINATOR - DirectGLES.cpp:2354-2357. This is the one row whose backend twin is
|
||||
// narrow on purpose, so the narrowness is what the case is about: a GL_READ_ONLY image binding
|
||||
// must NOT be marked, or the next map waits on and re-reads a dispatch that cannot have changed
|
||||
// a byte of it.
|
||||
TEST_F(SplitBufferSet, Row2OnlyAWritableImageBufferTextureCounts) {
|
||||
MG_State::GLState::ImageTextureBinding empty{};
|
||||
EXPECT_FALSE(MG_Remote::Client::ImageUnitIsAWritableBufferTexture(empty))
|
||||
<< "an unbound image unit is not a GPU write";
|
||||
|
||||
auto texture = MakeShared<MG_State::GLState::TextureObjectBuffer>(7u);
|
||||
auto backing = MakeBuffer(13u, 128);
|
||||
texture->GetBufferBindingSlot().Bind(backing);
|
||||
|
||||
MG_State::GLState::ImageTextureBinding readOnly{};
|
||||
readOnly.Texture = texture;
|
||||
readOnly.Access = GL_READ_ONLY;
|
||||
EXPECT_FALSE(MG_Remote::Client::ImageUnitIsAWritableBufferTexture(readOnly))
|
||||
<< "a GL_READ_ONLY image binding is left alone by the backend twin and must be left "
|
||||
"alone here";
|
||||
|
||||
MG_State::GLState::ImageTextureBinding writable = readOnly;
|
||||
writable.Access = GL_READ_WRITE;
|
||||
EXPECT_TRUE(MG_Remote::Client::ImageUnitIsAWritableBufferTexture(writable));
|
||||
}
|
||||
|
||||
// Row 2's WALK, through the image unit the context actually holds.
|
||||
TEST_F(SplitBufferSet, Row2AWritableImageBufferTextureIsMarkedByADraw) {
|
||||
auto texture = MakeShared<MG_State::GLState::TextureObjectBuffer>(8u);
|
||||
auto backing = MakeBuffer(14u, 128);
|
||||
texture->GetBufferBindingSlot().Bind(backing);
|
||||
auto& binding = MG_State::pGLContext->GetImageTextureBinding(0);
|
||||
binding.Texture = texture;
|
||||
binding.Access = GL_WRITE_ONLY;
|
||||
|
||||
MG_Remote::Client::MarkGpuWritesForDraw();
|
||||
|
||||
EXPECT_EQ(MG_Remote::Client::ProducerMarkCount(GpuWriteProducer::WritableImageBufferTexture), 1u);
|
||||
|
||||
binding = MG_State::GLState::ImageTextureBinding{};
|
||||
}
|
||||
|
||||
// Row 3 - VulkanRenderer.cpp:11618. With no capture active there is nothing to mark, and that
|
||||
// gate is the half worth pinning: a mark taken with no active capture would mark whatever the
|
||||
// binding points happened to hold from a previous one.
|
||||
TEST_F(SplitBufferSet, Row3TransformFeedbackTargetsAreOnlyMarkedWhileACaptureIsActive) {
|
||||
auto target = MakeBuffer(15u, 256);
|
||||
MG_State::pGLContext->GetBufferBindingPoint(BufferTarget::TransformFeedback, 0).Bind(target);
|
||||
MG_State::pGLContext->TouchBufferBindingPoint(BufferTarget::TransformFeedback, 0);
|
||||
|
||||
ASSERT_FALSE(MG_State::pGLContext->IsTransformFeedbackActive());
|
||||
MG_Remote::Client::MarkGpuWritesForDraw();
|
||||
EXPECT_EQ(MG_Remote::Client::ProducerMarkCount(GpuWriteProducer::TransformFeedbackCapture), 0u);
|
||||
|
||||
// The marking itself, driven at the row rather than through the capture state machine.
|
||||
MG_Remote::Client::MarkBufferForProducer(target, GpuWriteProducer::TransformFeedbackCapture);
|
||||
EXPECT_EQ(MG_Remote::Client::ProducerMarkCount(GpuWriteProducer::TransformFeedbackCapture), 1u);
|
||||
}
|
||||
|
||||
// Row 4 - P5's own: glReadPixels into a bound GL_PIXEL_PACK_BUFFER.
|
||||
TEST_F(SplitBufferSet, Row4AReadPixelsIntoAPackPboMarksThePbo) {
|
||||
MG_Remote::Client::MarkReadPixelsPackBuffer();
|
||||
EXPECT_EQ(MG_Remote::Client::ProducerMarkCount(GpuWriteProducer::ReadPixelsPackBuffer), 0u)
|
||||
<< "a read into client memory binds no PBO and must mark nothing";
|
||||
|
||||
auto pbo = MakeBuffer(16u, 1024);
|
||||
MG_State::pGLContext->GetBufferBindingSlot(BufferTarget::PixelPack).Bind(pbo);
|
||||
MG_Remote::Client::MarkReadPixelsPackBuffer();
|
||||
EXPECT_EQ(MG_Remote::Client::ProducerMarkCount(GpuWriteProducer::ReadPixelsPackBuffer), 1u);
|
||||
}
|
||||
|
||||
// Row 5 - P5's own: glEndTransformFeedback, in place of the unbounded ClientWaitSync.
|
||||
TEST_F(SplitBufferSet, Row5EndTransformFeedbackMarksTheCaptureTargets) {
|
||||
auto target = MakeBuffer(17u, 256);
|
||||
ASSERT_FALSE(MG_State::pGLContext->IsTransformFeedbackActive());
|
||||
MG_Remote::Client::MarkEndTransformFeedbackCaptureTargets();
|
||||
EXPECT_EQ(MG_Remote::Client::ProducerMarkCount(GpuWriteProducer::EndTransformFeedbackCapture), 0u);
|
||||
|
||||
MG_Remote::Client::MarkBufferForProducer(target, GpuWriteProducer::EndTransformFeedbackCapture);
|
||||
EXPECT_EQ(MG_Remote::Client::ProducerMarkCount(GpuWriteProducer::EndTransformFeedbackCapture), 1u);
|
||||
}
|
||||
|
||||
// THE GATE ITSELF. On the monolith path the six backend sites are still the only producers and
|
||||
// a second marker would be new behaviour (D-J) - and rows 4 and 5 would remove a stall that
|
||||
// monolith is entitled to keep.
|
||||
TEST_F(SplitBufferSet, TheWholeSetIsInertOnTheMonolithPath) {
|
||||
MG_Config::Transport = MG_Config::TransportMode::Monolith;
|
||||
auto ssbo = MakeBuffer(18u, 256);
|
||||
MG_State::pGLContext->GetBufferBindingPoint(BufferTarget::ShaderStorage, 0).Bind(ssbo);
|
||||
MG_State::pGLContext->TouchBufferBindingPoint(BufferTarget::ShaderStorage, 0);
|
||||
|
||||
MG_Remote::Client::MarkGpuWritesForDraw();
|
||||
MG_Remote::Client::MarkGpuWritesForDispatch();
|
||||
MG_Remote::Client::MarkReadPixelsPackBuffer();
|
||||
MG_Remote::Client::MarkEndTransformFeedbackCaptureTargets();
|
||||
|
||||
for (SizeT row = 0; row < static_cast<SizeT>(GpuWriteProducer::Count); ++row) {
|
||||
EXPECT_EQ(MG_Remote::Client::ProducerMarkCount(static_cast<GpuWriteProducer>(row)), 0u)
|
||||
<< "row " << row << " fired with Transport == Monolith";
|
||||
}
|
||||
}
|
||||
|
||||
// =====================================================================================
|
||||
// The persistent-map push
|
||||
// =====================================================================================
|
||||
|
||||
// The membership predicate IS SyncPersistentMappedRange's early-out chain, and the two must
|
||||
// answer the same thing about the same buffer. A re-derived predicate that drifted would push
|
||||
// a buffer monolith stopped pushing, and no other test could see it.
|
||||
TEST_F(SplitBufferSet, MembershipIsSyncPersistentMappedRangesOwnEarlyOutChain) {
|
||||
auto buffer = MakeBuffer(20u, 4096);
|
||||
EXPECT_FALSE(PersistentMapTracker::IsLivePersistentMap(*buffer)) << "not mapped";
|
||||
|
||||
buffer->AcquireMemoryRange(Range1D{0, 4096},
|
||||
BufferMappingAccessBit::Write | BufferMappingAccessBit::Persistent);
|
||||
ASSERT_FALSE(buffer->IsBackendPersistentMapped())
|
||||
<< "the acquisition was minted, so this is the adopted arm and not the one under test";
|
||||
EXPECT_TRUE(PersistentMapTracker::IsLivePersistentMap(*buffer));
|
||||
EXPECT_EQ(PersistentMapTracker::Instance().MemberCount(), 1u);
|
||||
|
||||
buffer->ReleaseMemory(false);
|
||||
EXPECT_FALSE(PersistentMapTracker::IsLivePersistentMap(*buffer));
|
||||
EXPECT_EQ(PersistentMapTracker::Instance().MemberCount(), 0u);
|
||||
|
||||
// FLUSH_EXPLICIT is the early-out that is easiest to lose: the application announces its
|
||||
// own writes with glFlushMappedBufferRange, which already crosses as resource_flush_range.
|
||||
buffer->AcquireMemoryRange(Range1D{0, 4096}, BufferMappingAccessBit::Write |
|
||||
BufferMappingAccessBit::Persistent |
|
||||
BufferMappingAccessBit::FlushExplicit);
|
||||
EXPECT_FALSE(PersistentMapTracker::IsLivePersistentMap(*buffer));
|
||||
EXPECT_EQ(PersistentMapTracker::Instance().MemberCount(), 0u);
|
||||
buffer->ReleaseMemory(false);
|
||||
}
|
||||
|
||||
// THE ADOPTED ARM IS NOT A MEMBER, AND IT IS THE CHAIN THAT SAYS SO - NOT THE TIER (ID-42).
|
||||
//
|
||||
// IsLivePersistentMap's second row is `if (buffer.IsBackendPersistentMapped()) return false;`,
|
||||
// and its comment promises that the row answers for ITSELF: at tier T2 the arm is unreachable
|
||||
// because MapPersistent declines, but a build that reaches T0/T1 later must get the same answer
|
||||
// out of the same row. Nothing drove that promise. The case above only ever sees the declined
|
||||
// arm, and PersistentCoherentMapScenario's membership assertion cannot pin it either - an
|
||||
// integration entry sees whichever arm its driver and transport hand it, which is exactly how
|
||||
// that assertion came to state the emulated arm's property as if it were universal and go red on
|
||||
// seven split-monolith entries the first time it ran.
|
||||
//
|
||||
// So the statement is pinned HERE, where both answers can be produced on demand. The adoption is
|
||||
// made by the PRODUCTION path - AcquireMemoryRange dispatching to the backend's
|
||||
// AcquirePersistentMap and calling PipeResource::AdoptPersistentMap - and not by the case
|
||||
// reaching into the buffer, because a hand-set flag would still be "true" with the production
|
||||
// adoption deleted (R-16). The transport is Monolith for exactly that call, because R-6's decline
|
||||
// is ANDed with `Transport != Monolith` and there is no other way to reach a mint in this build;
|
||||
// the PREDICATE is then asked with the tier back at T2/InProcess, which is the whole point: the
|
||||
// tier says "emulated, always" and the chain still says "not a member".
|
||||
TEST_F(SplitBufferSet, TheAdoptedArmIsNotAMemberAndItIsTheChainRowThatSaysSo) {
|
||||
constexpr SizeT kSize = 4096;
|
||||
// The storage the backend "mints". Declared first so it outlives the buffer: AdoptPersistentMap
|
||||
// stores the pointer and releases the shadow, and it never owns what it was handed.
|
||||
Vector<Uint8> minted(kSize, static_cast<Uint8>(0));
|
||||
g_mintedPersistentBase = minted.data();
|
||||
|
||||
auto adopted = MakeBuffer(27u, kSize);
|
||||
auto declined = MakeBuffer(28u, kSize);
|
||||
|
||||
// The declined twin first, with no backend ops at all: same flags, same size, same call.
|
||||
declined->AcquireMemoryRange(Range1D{0, kSize},
|
||||
BufferMappingAccessBit::Write | BufferMappingAccessBit::Persistent);
|
||||
ASSERT_FALSE(declined->IsBackendPersistentMapped());
|
||||
ASSERT_TRUE(PersistentMapTracker::IsLivePersistentMap(*declined))
|
||||
<< "the emulated arm IS a member - if this fails the two halves are not comparable and the "
|
||||
"assertion below proves nothing";
|
||||
|
||||
{
|
||||
MG_State::GLState::SetBufferBackendOps(&g_mintingBufferOps);
|
||||
MG_Config::Transport = MG_Config::TransportMode::Monolith;
|
||||
adopted->AcquireMemoryRange(Range1D{0, kSize},
|
||||
BufferMappingAccessBit::Write | BufferMappingAccessBit::Persistent);
|
||||
MG_Config::Transport = MG_Config::TransportMode::InProcess;
|
||||
MG_State::GLState::SetBufferBackendOps(nullptr);
|
||||
}
|
||||
ASSERT_TRUE(adopted->IsBackendPersistentMapped())
|
||||
<< "the backend declined the mint, so there is no adopted arm here to ask about";
|
||||
|
||||
// THE TIER SAYS EMULATED. The chain must still say "not a member".
|
||||
ASSERT_TRUE(MG_Remote::Client::AdoptTierIsEmulate());
|
||||
ASSERT_NE(MG_Config::Transport, MG_Config::TransportMode::Monolith);
|
||||
EXPECT_FALSE(PersistentMapTracker::IsLivePersistentMap(*adopted))
|
||||
<< "an adopted store's bytes are already in host-visible coherent GPU memory and there is "
|
||||
"nothing for the push to ship, so IsBackendPersistentMapped() takes it out of the set. "
|
||||
"This answer must come from that ROW and not from the adopt tier: the tier is T2 and the "
|
||||
"transport is InProcess right now, which is the configuration in which R-6 says every "
|
||||
"acquisition declines - and the store in front of the predicate is adopted anyway, "
|
||||
"because a later phase's T0/T1 will mint one. A predicate that read the tier would call "
|
||||
"it a member and the push would read an adopted store's Bytes() as if it were the "
|
||||
"shadow.";
|
||||
|
||||
// The SET agrees with the predicate, asked through the production entry point rather than by
|
||||
// reading a member: NoteMapStateChanged is what every one of the five maintenance events
|
||||
// calls, and it must refuse to enrol an adopted store.
|
||||
PersistentMapTracker::Instance().NoteMapStateChanged(*adopted);
|
||||
EXPECT_EQ(PersistentMapTracker::Instance().MemberCount(), 1u)
|
||||
<< "only the declined twin: enrolling an adopted store would make the push read its "
|
||||
"Bytes() - which is the GPU map, not the shadow - as if it were bytes to ship";
|
||||
|
||||
// ...and the consequence, which is the one that would actually corrupt something.
|
||||
const Uint64 before = MG_Util::PipeStats::TotalBytes(MG_Util::PipeStats::ByteClass::PersistentMapPush);
|
||||
MG_Remote::Client::PushPersistentMapsBeforeVerb();
|
||||
EXPECT_EQ(MG_Util::PipeStats::TotalBytes(MG_Util::PipeStats::ByteClass::PersistentMapPush) - before,
|
||||
static_cast<Uint64>(kSize))
|
||||
<< "the declined twin's 4096 bytes and nothing else: the adopted buffer must contribute no "
|
||||
"pushed bytes at all";
|
||||
|
||||
declined->ReleaseMemory(false);
|
||||
// The adopted one is NOT released through ReleaseMemory: ReleasePersistentMap is for a store
|
||||
// being redefined, and a persistent map the application holds outlives every unmap by
|
||||
// definition (PipeResource.h:121-127). It is dropped here with the mapping still adopted,
|
||||
// which is also the shape ~BufferObject has to survive.
|
||||
adopted.reset();
|
||||
g_mintedPersistentBase = nullptr;
|
||||
}
|
||||
|
||||
// pmap is non-zero, and it is non-zero in BLOCKS.
|
||||
TEST_F(SplitBufferSet, ThePushCutsTheMappedSpanIntoBlocksAndMovesPmap) {
|
||||
constexpr SizeT kSize = 4u * 64u * 1024u; // exactly four 64 KiB blocks
|
||||
auto buffer = MakeBuffer(21u, kSize);
|
||||
buffer->AcquireMemoryRange(Range1D{0, kSize},
|
||||
BufferMappingAccessBit::Write | BufferMappingAccessBit::Persistent);
|
||||
ASSERT_TRUE(PersistentMapTracker::IsLivePersistentMap(*buffer));
|
||||
|
||||
const Uint64 before = MG_Util::PipeStats::TotalBytes(MG_Util::PipeStats::ByteClass::PersistentMapPush);
|
||||
MG_Remote::Client::PushPersistentMapsBeforeVerb();
|
||||
|
||||
EXPECT_EQ(PersistentMapTracker::Instance().BlocksPushed(), 4u)
|
||||
<< "a 256 KiB span at a 64 KiB block size is four records, not one";
|
||||
EXPECT_EQ(PersistentMapTracker::Instance().BytesPushed(), static_cast<Uint64>(kSize));
|
||||
EXPECT_EQ(MG_Util::PipeStats::TotalBytes(MG_Util::PipeStats::ByteClass::PersistentMapPush) - before,
|
||||
static_cast<Uint64>(kSize))
|
||||
<< "persistent-map-push is wired and counts the bytes the client had to ship because "
|
||||
"MapPersistent declined";
|
||||
|
||||
buffer->ReleaseMemory(false);
|
||||
}
|
||||
|
||||
// A span that is not a whole number of blocks keeps its tail.
|
||||
TEST_F(SplitBufferSet, TheLastBlockIsTheRemainderAndNotAWholeBlock) {
|
||||
constexpr SizeT kSize = 64u * 1024u + 7u;
|
||||
auto buffer = MakeBuffer(22u, kSize);
|
||||
buffer->AcquireMemoryRange(Range1D{0, kSize},
|
||||
BufferMappingAccessBit::Write | BufferMappingAccessBit::Persistent);
|
||||
MG_Remote::Client::PushPersistentMapsBeforeVerb();
|
||||
EXPECT_EQ(PersistentMapTracker::Instance().BlocksPushed(), 2u);
|
||||
EXPECT_EQ(PersistentMapTracker::Instance().BytesPushed(), static_cast<Uint64>(kSize));
|
||||
buffer->ReleaseMemory(false);
|
||||
}
|
||||
|
||||
// THE STATE RECORD ON BOTH EDGES (B-1). The rising edge is what breaks the cycle the probe
|
||||
// would otherwise latch: a coherent persistent map behind a static VAO emits NO content record
|
||||
// of its own until the push runs, the push runs inside the ensure path, and a draw-clean answer
|
||||
// skips that ensure and then latches it. So the map itself has to publish, and the unmap has to
|
||||
// publish the retraction - one block each, observable here as exactly one serial bump each.
|
||||
TEST_F(SplitBufferSet, BothEdgesOfAWriteMapPublishOneStateRecord) {
|
||||
constexpr SizeT kSize = 4096;
|
||||
auto buffer = MakeBuffer(26u, kSize);
|
||||
EXPECT_FALSE(buffer->HasLiveHostWritesForWire());
|
||||
|
||||
const Uint64 beforeMap = buffer->GetChangeSerial();
|
||||
buffer->AcquireMemoryRange(Range1D{0, kSize},
|
||||
BufferMappingAccessBit::Write | BufferMappingAccessBit::Persistent);
|
||||
EXPECT_TRUE(buffer->HasLiveHostWritesForWire());
|
||||
EXPECT_EQ(buffer->GetChangeSerial(), beforeMap + 1)
|
||||
<< "the rising edge published nothing, so the server cannot know a host writer is live "
|
||||
"until a content record it may never emit";
|
||||
|
||||
const Uint64 beforeUnmap = buffer->GetChangeSerial();
|
||||
buffer->ReleaseMemory(/*landStagedWrites=*/true);
|
||||
EXPECT_FALSE(buffer->HasLiveHostWritesForWire());
|
||||
EXPECT_EQ(buffer->GetChangeSerial(), beforeUnmap + 2)
|
||||
<< "the unmap's own NotifyFlushMappedRange plus the falling-edge state record: without "
|
||||
"the second the record stays dirty for the buffer's life";
|
||||
}
|
||||
|
||||
// E3(a)'s NEGATIVE CONTROL: 0 disables the push, it does not mean "one unlimited block" - and
|
||||
// it disables the STATE RECORDS with it. An earlier cut skipped the blocks and still shipped a
|
||||
// whole buffer at unmap, so a scenario that unmapped before reading back went green and the
|
||||
// control was dead.
|
||||
TEST_F(SplitBufferSet, AZeroBlockSizeTurnsThePushOffRatherThanMakingItUnlimited) {
|
||||
MG_Config::Ipc.PersistentBlockKb = 0;
|
||||
constexpr SizeT kSize = 128u * 1024u;
|
||||
auto buffer = MakeBuffer(23u, kSize);
|
||||
|
||||
const Uint64 beforeMap = buffer->GetChangeSerial();
|
||||
buffer->AcquireMemoryRange(Range1D{0, kSize},
|
||||
BufferMappingAccessBit::Write | BufferMappingAccessBit::Persistent);
|
||||
ASSERT_TRUE(PersistentMapTracker::IsLivePersistentMap(*buffer));
|
||||
EXPECT_EQ(buffer->GetChangeSerial(), beforeMap)
|
||||
<< "the rising-edge state record went out with the push disabled";
|
||||
|
||||
const Uint64 before = MG_Util::PipeStats::TotalBytes(MG_Util::PipeStats::ByteClass::PersistentMapPush);
|
||||
MG_Remote::Client::PushPersistentMapsBeforeVerb();
|
||||
EXPECT_EQ(PersistentMapTracker::Instance().BlocksPushed(), 0u);
|
||||
EXPECT_EQ(MG_Util::PipeStats::TotalBytes(MG_Util::PipeStats::ByteClass::PersistentMapPush), before)
|
||||
<< "MOBILEGL_IPC_PERSISTENT_BLOCK_KB=0 must ship nothing, so that "
|
||||
"PersistentCoherentMapScenario goes red under it";
|
||||
|
||||
const Uint64 beforeUnmap = buffer->GetChangeSerial();
|
||||
buffer->ReleaseMemory(/*landStagedWrites=*/true);
|
||||
EXPECT_EQ(buffer->GetChangeSerial(), beforeUnmap + 1)
|
||||
<< "with the push off the unmap must emit only its own NotifyFlushMappedRange - a "
|
||||
"falling-edge record here delivers a whole buffer the control exists to withhold, "
|
||||
"and a negative control that still delivers the bytes is not a control";
|
||||
}
|
||||
|
||||
// The set does not keep a pointer to a dead buffer.
|
||||
TEST_F(SplitBufferSet, ADestroyedBufferLeavesTheSet) {
|
||||
{
|
||||
auto buffer = MakeBuffer(24u, 4096);
|
||||
buffer->AcquireMemoryRange(Range1D{0, 4096},
|
||||
BufferMappingAccessBit::Write | BufferMappingAccessBit::Persistent);
|
||||
ASSERT_EQ(PersistentMapTracker::Instance().MemberCount(), 1u);
|
||||
}
|
||||
EXPECT_EQ(PersistentMapTracker::Instance().MemberCount(), 0u)
|
||||
<< "~BufferObject must Forget() itself: the set holds raw pointers keyed on the "
|
||||
"lifetime id, and an entry that outlives its object is the one failure it cannot have";
|
||||
}
|
||||
|
||||
// SyncGpuWrites' THIRD STATE. Monolith clears the flag before it emits, which is safe only
|
||||
// because the readback runs synchronously inside the applier; under a transport that clear
|
||||
// leaves the shadow silently stale for the object's life, so the WRITEBACK clears it instead.
|
||||
TEST_F(SplitBufferSet, UnderSplitTheWritebackClearsThePendingFlagAndNotTheRequest) {
|
||||
auto buffer = MakeBuffer(25u, 256);
|
||||
buffer->MarkGpuWritten();
|
||||
ASSERT_TRUE(buffer->HasOutstandingGpuWrite());
|
||||
|
||||
Vector<Uint8> bytes(256, static_cast<Uint8>(0x5A));
|
||||
buffer->WritebackFromBackend(DataPtr{bytes.data(), bytes.size()}, 0);
|
||||
EXPECT_FALSE(buffer->HasOutstandingGpuWrite())
|
||||
<< "the answer landing is what makes the shadow current, so the answer is what clears";
|
||||
|
||||
// A PARTIAL writeback is not an answer to a whole-buffer readback and must not clear:
|
||||
// GL_Drawing's transform-feedback strip fixup writes back three vertices at a time.
|
||||
buffer->MarkGpuWritten();
|
||||
buffer->WritebackFromBackend(DataPtr{bytes.data(), 16}, 0);
|
||||
EXPECT_TRUE(buffer->HasOutstandingGpuWrite());
|
||||
|
||||
// And with no readback route at all - no size, or a backend that registered no resource
|
||||
// ops - SyncGpuWrites must clear rather than block for ever. That is the ONE case
|
||||
// monolith's unconditional clear covers that a writeback cannot.
|
||||
EXPECT_FALSE(MG_Remote::Client::BufferWritebackIsReachable(*buffer));
|
||||
buffer->SyncGpuWrites();
|
||||
EXPECT_FALSE(buffer->HasOutstandingGpuWrite());
|
||||
}
|
||||
|
||||
// R-6's tier gate. T2 is the only tier P5 implements; the other two are a NAMED refusal and
|
||||
// their spelling exists now so the P11 negative control has one.
|
||||
TEST_F(SplitBufferSet, OnlyAdoptTierTwoIsImplemented) {
|
||||
EXPECT_TRUE(MG_Remote::Client::AdoptTierIsEmulate());
|
||||
MG_Config::Ipc.AdoptTier = 0;
|
||||
EXPECT_DEATH(MG_Remote::Client::AdoptTierIsEmulate(), "");
|
||||
MG_Config::Ipc.AdoptTier = 1;
|
||||
EXPECT_DEATH(MG_Remote::Client::AdoptTierIsEmulate(), "");
|
||||
MG_Config::Ipc.AdoptTier = 2;
|
||||
}
|
||||
|
||||
#else
|
||||
|
||||
// THE SAME SIXTEEN NAMES, SO THE ctest NAME SET DOES NOT MOVE BETWEEN LANES. G2 compares the
|
||||
// pull and push name lists line for line and G14 allows build-split to ADD names but never to
|
||||
// remove one, so a case that exists only where it can run would break both gates for a reason
|
||||
// that has nothing to do with what it tests. It skips instead, and says why.
|
||||
TEST(SplitBufferSet, Row0EverySsboBindingPointIsMarkedByADraw) { MGL_SPLIT_ONLY_OR_SKIP(); }
|
||||
TEST(SplitBufferSet, Row1EveryBoundAtomicCounterIsMarkedByADraw) { MGL_SPLIT_ONLY_OR_SKIP(); }
|
||||
TEST(SplitBufferSet, Row2OnlyAWritableImageBufferTextureCounts) { MGL_SPLIT_ONLY_OR_SKIP(); }
|
||||
TEST(SplitBufferSet, Row2AWritableImageBufferTextureIsMarkedByADraw) { MGL_SPLIT_ONLY_OR_SKIP(); }
|
||||
TEST(SplitBufferSet, Row3TransformFeedbackTargetsAreOnlyMarkedWhileACaptureIsActive) {
|
||||
MGL_SPLIT_ONLY_OR_SKIP();
|
||||
}
|
||||
TEST(SplitBufferSet, Row4AReadPixelsIntoAPackPboMarksThePbo) { MGL_SPLIT_ONLY_OR_SKIP(); }
|
||||
TEST(SplitBufferSet, Row5EndTransformFeedbackMarksTheCaptureTargets) { MGL_SPLIT_ONLY_OR_SKIP(); }
|
||||
TEST(SplitBufferSet, TheWholeSetIsInertOnTheMonolithPath) { MGL_SPLIT_ONLY_OR_SKIP(); }
|
||||
TEST(SplitBufferSet, MembershipIsSyncPersistentMappedRangesOwnEarlyOutChain) { MGL_SPLIT_ONLY_OR_SKIP(); }
|
||||
TEST(SplitBufferSet, TheAdoptedArmIsNotAMemberAndItIsTheChainRowThatSaysSo) { MGL_SPLIT_ONLY_OR_SKIP(); }
|
||||
TEST(SplitBufferSet, ThePushCutsTheMappedSpanIntoBlocksAndMovesPmap) { MGL_SPLIT_ONLY_OR_SKIP(); }
|
||||
TEST(SplitBufferSet, TheLastBlockIsTheRemainderAndNotAWholeBlock) { MGL_SPLIT_ONLY_OR_SKIP(); }
|
||||
TEST(SplitBufferSet, BothEdgesOfAWriteMapPublishOneStateRecord) { MGL_SPLIT_ONLY_OR_SKIP(); }
|
||||
TEST(SplitBufferSet, AZeroBlockSizeTurnsThePushOffRatherThanMakingItUnlimited) { MGL_SPLIT_ONLY_OR_SKIP(); }
|
||||
TEST(SplitBufferSet, ADestroyedBufferLeavesTheSet) { MGL_SPLIT_ONLY_OR_SKIP(); }
|
||||
TEST(SplitBufferSet, UnderSplitTheWritebackClearsThePendingFlagAndNotTheRequest) { MGL_SPLIT_ONLY_OR_SKIP(); }
|
||||
TEST(SplitBufferSet, OnlyAdoptTierTwoIsImplemented) { MGL_SPLIT_ONLY_OR_SKIP(); }
|
||||
|
||||
#endif // MOBILEGL_BUILD_DISAGGREGATED
|
||||
|
||||
// =====================================================================================
|
||||
// Tier 1 of the three-tier flush ladder - the INVALIDATE_RANGE edge.
|
||||
//
|
||||
// It is a PUSH-build case and not a split-build one: the widening hazard is real in every
|
||||
// build that compiles FlushPendingRangesFrom, and under split it simply gains a second cause
|
||||
// (a SEG_STAGE snapshot that no longer matches the queued range).
|
||||
// =====================================================================================
|
||||
|
||||
#if MOBILEGL_PIPE_PUSH
|
||||
namespace {
|
||||
using MobileGL::MG_Backend::DirectGLES::BufferImpl::InvalidateFlushAccessFor;
|
||||
using MobileGL::MG_Backend::DirectGLES::BufferImpl::kEsprytInvalidateRangeMinBytes;
|
||||
constexpr SizeT kStore = 1024u * 1024u;
|
||||
} // namespace
|
||||
|
||||
TEST(EsprytFlushLadder, AWholeBufferRangeOrphansTheStore) {
|
||||
EXPECT_EQ(InvalidateFlushAccessFor(0, kStore, 0, kStore, kStore, kStore),
|
||||
static_cast<GLbitfield>(GL_MAP_WRITE_BIT | GL_MAP_INVALIDATE_BUFFER_BIT));
|
||||
}
|
||||
|
||||
TEST(EsprytFlushLadder, ALargePartialRangeInvalidatesExactlyThatRange) {
|
||||
const SizeT start = 4096;
|
||||
const SizeT end = start + kEsprytInvalidateRangeMinBytes;
|
||||
EXPECT_EQ(InvalidateFlushAccessFor(start, end, start, end, kStore, kStore),
|
||||
static_cast<GLbitfield>(GL_MAP_WRITE_BIT | GL_MAP_INVALIDATE_RANGE_BIT));
|
||||
}
|
||||
|
||||
TEST(EsprytFlushLadder, ASmallPartialRangeFallsThroughToTheStagingRing) {
|
||||
EXPECT_EQ(InvalidateFlushAccessFor(4096, 4096 + 64, 4096, 4096 + 64, kStore, kStore), 0u)
|
||||
<< "below the threshold the map WAITS out the WAR hazard on the CPU instead of "
|
||||
"substituting pages, which is the whole reason tier 2 exists";
|
||||
}
|
||||
|
||||
// THE EDGE THAT HAS ALREADY DRAWN BLOOD (Managers.cpp:1125-1128): widening the map past the
|
||||
// queued range clobbered GPU-written data - an SSBO counter beside the app's SubData - with
|
||||
// the stale shadow, SILENTLY. Under split the same shape arrives with a different cause: the
|
||||
// server may hold no pointer into the client's shadow (R-11), so `hostBase` becomes a
|
||||
// SEG_STAGE snapshot, and a snapshot that does not cover exactly the queued range is the same
|
||||
// lie told by a thread boundary instead of by a page alignment.
|
||||
TEST(EsprytFlushLadder, AMapWiderThanTheQueuedRangeRefusesTierOne) {
|
||||
const SizeT queuedStart = 4096;
|
||||
const SizeT queuedEnd = queuedStart + kEsprytInvalidateRangeMinBytes;
|
||||
// Page-aligned outward, the exact widening the in-tree note records.
|
||||
EXPECT_EQ(InvalidateFlushAccessFor(queuedStart, queuedEnd, 0, queuedEnd + 4096, kStore, kStore), 0u)
|
||||
<< "a widened INVALIDATE_RANGE declares bytes dead that the shadow is not about to "
|
||||
"rewrite, and overwrites whatever the GPU put there";
|
||||
// And narrower, which is the same corruption read the other way round: bytes left
|
||||
// unwritten inside a range that has just been declared dead.
|
||||
EXPECT_EQ(InvalidateFlushAccessFor(queuedStart, queuedEnd, queuedStart, queuedEnd - 8, kStore, kStore), 0u);
|
||||
}
|
||||
|
||||
TEST(EsprytFlushLadder, AnEmptyRangeIsNeverTierOne) {
|
||||
EXPECT_EQ(InvalidateFlushAccessFor(4096, 4096, 4096, 4096, kStore, kStore), 0u);
|
||||
}
|
||||
#else
|
||||
// The same five names in a pull build, for the G2/G14 reason above: the ladder's push arm
|
||||
// (FlushPendingRangesFrom) is the only one that carries this decision as a function - the pull
|
||||
// arm's FlushPendingRangesNow is byte-frozen against 5cb826b0 (ID-15) and may not grow one.
|
||||
#define MGL_PUSH_ONLY_OR_SKIP() \
|
||||
GTEST_SKIP() << "the three-tier ladder's push arm (FlushPendingRangesFrom) is what carries " \
|
||||
"InvalidateFlushAccessFor; a pull build compiles the frozen arm instead"
|
||||
TEST(EsprytFlushLadder, AWholeBufferRangeOrphansTheStore) { MGL_PUSH_ONLY_OR_SKIP(); }
|
||||
TEST(EsprytFlushLadder, ALargePartialRangeInvalidatesExactlyThatRange) { MGL_PUSH_ONLY_OR_SKIP(); }
|
||||
TEST(EsprytFlushLadder, ASmallPartialRangeFallsThroughToTheStagingRing) { MGL_PUSH_ONLY_OR_SKIP(); }
|
||||
TEST(EsprytFlushLadder, AMapWiderThanTheQueuedRangeRefusesTierOne) { MGL_PUSH_ONLY_OR_SKIP(); }
|
||||
TEST(EsprytFlushLadder, AnEmptyRangeIsNeverTierOne) { MGL_PUSH_ONLY_OR_SKIP(); }
|
||||
#endif // MOBILEGL_PIPE_PUSH
|
||||
@@ -175,8 +175,41 @@ foreach(pipeTest ResourceEmitTest VertexInputEmitTest
|
||||
endif()
|
||||
endforeach()
|
||||
|
||||
# P5 package p1: table 2 (PipeInputs field ownership) at runtime. Registered in EVERY
|
||||
# configuration rather than behind `if (MOBILEGL_BUILD_DISAGGREGATED)` like the Wire suite,
|
||||
# because half of it is arithmetic over the generated table that a push or verify build can
|
||||
# check just as well - and a suite that only exists in one configuration is a suite three
|
||||
# configurations cannot notice breaking. Its split-only cases compile away there.
|
||||
#
|
||||
# Links gtest rather than gtest_main and carries its own main(), like PipeInputsTest and
|
||||
# RenderStateSpansTest: its abort cases read the Fatal line back out of a log file the process
|
||||
# names before anything logs.
|
||||
add_executable(
|
||||
FieldOwnershipTest
|
||||
FieldOwnershipTest.cpp
|
||||
)
|
||||
|
||||
target_include_directories(FieldOwnershipTest PRIVATE
|
||||
${MGL_ROOT}/include
|
||||
${MGL_ROOT}/MobileGL
|
||||
${MGL_ROOT}/MobileGL/MG_Pipe
|
||||
${MGL_ROOT}/3rdparty/xxHash
|
||||
${MGL_ROOT}/3rdparty/Vulkan-Headers/include
|
||||
${MGL_ROOT}/3rdparty/SPIRV-Reflect
|
||||
)
|
||||
|
||||
target_link_libraries(FieldOwnershipTest PRIVATE
|
||||
GTest::gtest
|
||||
${LINK_LIBRARIES}
|
||||
)
|
||||
|
||||
if (MSVC)
|
||||
target_compile_options(FieldOwnershipTest PRIVATE /Zc:preprocessor)
|
||||
endif()
|
||||
|
||||
include(GoogleTest)
|
||||
gtest_discover_tests(PipeCatalogueTest DISCOVERY_TIMEOUT 30 PROPERTIES LABELS unit)
|
||||
gtest_discover_tests(FieldOwnershipTest DISCOVERY_TIMEOUT 30 PROPERTIES LABELS unit)
|
||||
foreach(pipeTest ResourceEmitTest VertexInputEmitTest
|
||||
FramebufferEmitTest TextureEmitTest SamplerEmitTest ImageEmitTest
|
||||
ProgramEmitTest CompositeResolverTest)
|
||||
|
||||
@@ -0,0 +1,603 @@
|
||||
// MobileGL - MobileGL/MG_Test/Pipe/FieldOwnershipTest.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
|
||||
|
||||
// TABLE 2 at runtime (CONTRACT-P5.md section 3, BRIEF-P5 R-7, exit gate E4). Package p1.
|
||||
//
|
||||
// The generated table is checked two ways here, and they answer different questions:
|
||||
//
|
||||
// the ARITHMETIC cases run in any push build and say the table PARTITIONS the field set -
|
||||
// 70 rows, four classes, every BARRIER-PULLED row naming the phase that retires it;
|
||||
//
|
||||
// the BEHAVIOUR cases run only in a split build and say the table is LOAD-BEARING - that a
|
||||
// server verb stamp makes the record-supplied fields readable and withdraws the rest, that a
|
||||
// BARRIER-PULLED read is counted rather than fatal, that MOBILEGL_IPC_STRICT_ERRORS=1 turns
|
||||
// it into a named abort, and that the seven sticky forwards' poison exemption is cancelled.
|
||||
//
|
||||
// E4's negative control is ARecordSuppliedFieldIsReadableAfterAServerStamp: move one field
|
||||
// from RECORD-SUPPLIED to FATAL in MG_Pipe/FieldOwnership.def and that case goes red by name.
|
||||
// The generator's own controls are `gen_pipe_field_ownership.py --self-test`.
|
||||
//
|
||||
// Links gtest rather than gtest_main and carries its own main(), like PipeInputsTest: the
|
||||
// abort cases read the Fatal line back out of a log file this process names before anything
|
||||
// logs.
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
|
||||
#include "Includes.h"
|
||||
#include <MG_Pipe/MGPipe.h>
|
||||
|
||||
#if MOBILEGL_PIPE_PUSH
|
||||
#include <Config.h>
|
||||
#include <MG_Backend/MGPipe/PipeInputs.h>
|
||||
#include <MG_Impl/Pipe/PipeFill.h>
|
||||
#include <MG_Pipe/PipeApply.h>
|
||||
#include <MG_State/GLState/Core.h>
|
||||
#include <MG_Util/Metrics/PipeStats.h>
|
||||
#endif
|
||||
|
||||
#if !defined(_WIN32)
|
||||
#include <csignal>
|
||||
#include <sys/wait.h>
|
||||
#include <unistd.h>
|
||||
#define MGTEST_HAVE_FORK 1
|
||||
#else
|
||||
#include <process.h>
|
||||
#define MGTEST_HAVE_FORK 0
|
||||
#endif
|
||||
|
||||
using namespace MobileGL;
|
||||
using namespace MobileGL::MG_Pipe;
|
||||
|
||||
namespace {
|
||||
std::string g_logPath;
|
||||
|
||||
std::string ReadLog() {
|
||||
std::ifstream in(g_logPath, std::ios::binary);
|
||||
std::ostringstream ss;
|
||||
ss << in.rdbuf();
|
||||
return ss.str();
|
||||
}
|
||||
|
||||
long ProcessId() {
|
||||
#if defined(_WIN32)
|
||||
return static_cast<long>(::_getpid());
|
||||
#else
|
||||
return static_cast<long>(::getpid());
|
||||
#endif
|
||||
}
|
||||
|
||||
#if MOBILEGL_PIPE_PUSH
|
||||
using GLContext = MG_State::GLState::GLContext;
|
||||
|
||||
// A live frontend context, restored on the way out so the cases stay independent - the
|
||||
// sticky forwards reach for one and the stamp cases must not depend on whether they found
|
||||
// it (PipeInputsTest's idiom).
|
||||
class FieldOwnershipTest : public ::testing::Test {
|
||||
protected:
|
||||
void SetUp() override {
|
||||
m_previous = Move(MG_State::pGLContext);
|
||||
MG_State::pGLContext = MakeUnique<GLContext>();
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
MG_Config::Ipc.StrictErrors = false;
|
||||
MGPipeServerClearVerbBoundary();
|
||||
MGPipeResetResidualPullCountForTesting();
|
||||
#endif
|
||||
}
|
||||
void TearDown() override {
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
MGPipeServerClearVerbBoundary();
|
||||
MG_Config::Ipc.StrictErrors = false;
|
||||
#endif
|
||||
MG_State::pGLContext = Move(m_previous);
|
||||
}
|
||||
UniquePtr<GLContext> m_previous;
|
||||
};
|
||||
|
||||
SizeT Index(MGPipeInputField field) { return static_cast<SizeT>(field); }
|
||||
|
||||
#if MGTEST_HAVE_FORK
|
||||
struct ChildResult {
|
||||
int Status = -1;
|
||||
std::string Log;
|
||||
};
|
||||
|
||||
// Runs `body` in a forked child and returns its wait status and log delta. The child must
|
||||
// not use gtest assertions; it _exit(0)s when `body` returns, so a body expected to die is
|
||||
// asserted dead by the parent rather than assumed dead.
|
||||
template <class Body>
|
||||
ChildResult RunInChild(Body body) {
|
||||
ChildResult result;
|
||||
const std::string before = ReadLog();
|
||||
std::fflush(nullptr);
|
||||
const pid_t pid = ::fork();
|
||||
if (pid < 0) return result;
|
||||
if (pid == 0) {
|
||||
body();
|
||||
::_exit(0);
|
||||
}
|
||||
int status = 0;
|
||||
if (::waitpid(pid, &status, 0) != pid) return result;
|
||||
result.Status = status;
|
||||
result.Log = ReadLog().substr(before.size());
|
||||
return result;
|
||||
}
|
||||
|
||||
Bool DiedOfAbort(const ChildResult& r) { return WIFSIGNALED(r.Status) && WTERMSIG(r.Status) == SIGABRT; }
|
||||
Bool ExitedWith(const ChildResult& r, int code) { return WIFEXITED(r.Status) && WEXITSTATUS(r.Status) == code; }
|
||||
std::string DescribeStatus(const ChildResult& r) {
|
||||
if (r.Status < 0) return "fork/waitpid failed";
|
||||
if (WIFEXITED(r.Status)) return "exited " + std::to_string(WEXITSTATUS(r.Status));
|
||||
if (WIFSIGNALED(r.Status)) return "signal " + std::to_string(WTERMSIG(r.Status));
|
||||
return "status " + std::to_string(r.Status);
|
||||
}
|
||||
#endif // MGTEST_HAVE_FORK
|
||||
#endif // MOBILEGL_PIPE_PUSH
|
||||
} // namespace
|
||||
|
||||
#if !MOBILEGL_PIPE_PUSH
|
||||
|
||||
TEST(FieldOwnershipTest, EveryFieldAndForwardIsInExactlyOneClass) {
|
||||
GTEST_SKIP() << "push not compiled in (MOBILEGL_PIPE_PUSH=OFF)";
|
||||
}
|
||||
TEST(FieldOwnershipTest, TheClassSizesPartitionTheFieldSet) {
|
||||
GTEST_SKIP() << "push not compiled in (MOBILEGL_PIPE_PUSH=OFF)";
|
||||
}
|
||||
TEST(FieldOwnershipTest, EveryBarrierPulledRowNamesTheRetiringPhase) {
|
||||
GTEST_SKIP() << "push not compiled in (MOBILEGL_PIPE_PUSH=OFF)";
|
||||
}
|
||||
TEST(FieldOwnershipTest, TheReducedPathsUnmigratedFieldsAreAllAccountedFor) {
|
||||
GTEST_SKIP() << "push not compiled in (MOBILEGL_PIPE_PUSH=OFF)";
|
||||
}
|
||||
TEST(FieldOwnershipTest, TheSevenStickyForwardsAgreeWithTheirFieldRows) {
|
||||
GTEST_SKIP() << "push not compiled in (MOBILEGL_PIPE_PUSH=OFF)";
|
||||
}
|
||||
TEST(FieldOwnershipTest, VerbBoundaryOpsCoverEveryVerbShapedCall) {
|
||||
GTEST_SKIP() << "push not compiled in (MOBILEGL_PIPE_PUSH=OFF)";
|
||||
}
|
||||
|
||||
#else // MOBILEGL_PIPE_PUSH
|
||||
|
||||
// ---------------------------------------------------------------------------------------
|
||||
// The arithmetic: the table partitions the field set. Runs in push, verify and split.
|
||||
// ---------------------------------------------------------------------------------------
|
||||
|
||||
TEST_F(FieldOwnershipTest, EveryFieldAndForwardIsInExactlyOneClass) {
|
||||
for (SizeT i = 0; i < kMGPipeInputFieldCount; ++i) {
|
||||
EXPECT_NE(kMGPipeFieldOwnership[i], MGPipeFieldOwnership::kUnclassified)
|
||||
<< kMGPipeInputFieldNames[i] << " is in none of the four ownership classes";
|
||||
}
|
||||
for (SizeT i = 0; i < kMGPipeFieldOwnershipForwardCount; ++i) {
|
||||
EXPECT_NE(kMGPipeFieldOwnershipForward[i], MGPipeFieldOwnership::kUnclassified)
|
||||
<< "sticky forward " << i << " is in none of the four ownership classes";
|
||||
}
|
||||
EXPECT_EQ(kMGPipeFieldOwnershipRowCount, SizeT{70});
|
||||
}
|
||||
|
||||
TEST_F(FieldOwnershipTest, TheClassSizesPartitionTheFieldSet) {
|
||||
SizeT counted[5] = {};
|
||||
for (SizeT i = 0; i < kMGPipeInputFieldCount; ++i) {
|
||||
++counted[static_cast<SizeT>(kMGPipeFieldOwnership[i])];
|
||||
}
|
||||
EXPECT_EQ(counted[static_cast<SizeT>(MGPipeFieldOwnership::kRecordSupplied)],
|
||||
kMGPipeRecordSuppliedFieldCount);
|
||||
EXPECT_EQ(counted[static_cast<SizeT>(MGPipeFieldOwnership::kApplierDerived)],
|
||||
kMGPipeApplierDerivedFieldCount);
|
||||
EXPECT_EQ(counted[static_cast<SizeT>(MGPipeFieldOwnership::kBarrierPulled)],
|
||||
kMGPipeBarrierPulledFieldCount);
|
||||
EXPECT_EQ(counted[static_cast<SizeT>(MGPipeFieldOwnership::kFatal)], kMGPipeFatalFieldCount);
|
||||
// The census's own arithmetic (scout-unmigrated-census section 2.1): 31 of the 63 fields
|
||||
// are served by NO pushed record - 24 non-sticky plus the seven sticky - so 32 are.
|
||||
EXPECT_EQ(kMGPipeRecordSuppliedFieldCount, SizeT{32});
|
||||
EXPECT_EQ(kMGPipeApplierDerivedFieldCount + kMGPipeBarrierPulledFieldCount + kMGPipeFatalFieldCount,
|
||||
SizeT{31});
|
||||
}
|
||||
|
||||
TEST_F(FieldOwnershipTest, EveryBarrierPulledRowNamesTheRetiringPhase) {
|
||||
SizeT pulled = 0;
|
||||
for (SizeT i = 0; i < kMGPipeInputFieldCount; ++i) {
|
||||
const Bool isPulled = kMGPipeFieldOwnership[i] == MGPipeFieldOwnership::kBarrierPulled;
|
||||
const Bool named = std::string(kMGPipeFieldRetiringPhase[i]) != "-";
|
||||
EXPECT_EQ(isPulled, named) << kMGPipeInputFieldNames[i]
|
||||
<< ": only a BARRIER-PULLED row has a retiring phase, and it must have one";
|
||||
pulled += isPulled ? 1 : 0;
|
||||
}
|
||||
EXPECT_EQ(pulled, kMGPipeBarrierPulledFieldCount);
|
||||
}
|
||||
|
||||
// The 21 the reduced path actually reads (scout-unmigrated-census section 3: the union of
|
||||
// kClear's 7, kDraw's 19 and kReadback's 12). Twenty of them are BARRIER-PULLED; the
|
||||
// twenty-first is GetPixelStoreParameters, whose PACK half the applier writes and whose UNPACK
|
||||
// half has no carrier and no backend reader at all.
|
||||
TEST_F(FieldOwnershipTest, TheReducedPathsUnmigratedFieldsAreAllAccountedFor) {
|
||||
const MGPipeInputField pulled[] = {
|
||||
MGPipeInputField::GetActiveTextureUnit,
|
||||
MGPipeInputField::GetBoundVertexArray,
|
||||
MGPipeInputField::GetBufferBindingSlot,
|
||||
MGPipeInputField::GetBufferBindingPoint,
|
||||
MGPipeInputField::GetTouchedBufferBindingPointCount,
|
||||
MGPipeInputField::GetCurrentVertexAttribute,
|
||||
MGPipeInputField::GetFramebufferBindingSlot,
|
||||
MGPipeInputField::GetImageTextureBinding,
|
||||
MGPipeInputField::GetMaxTouchedTextureUnit,
|
||||
MGPipeInputField::GetProgramForDraw,
|
||||
MGPipeInputField::GetSamplingResolutionGeneration,
|
||||
MGPipeInputField::GetTextureBindGeneration,
|
||||
MGPipeInputField::GetTextureContextId,
|
||||
MGPipeInputField::GetTextureUnitObject,
|
||||
MGPipeInputField::GetTransformFeedbackCapturedVertices,
|
||||
MGPipeInputField::GetTransformFeedbackGeneration,
|
||||
MGPipeInputField::GetTransformFeedbackProgram,
|
||||
MGPipeInputField::GetBoundTransformFeedbackLifetimeId,
|
||||
MGPipeInputField::IsTransformFeedbackActive,
|
||||
MGPipeInputField::IsTransformFeedbackPaused,
|
||||
};
|
||||
for (const auto field : pulled) {
|
||||
EXPECT_EQ(MGPipeFieldOwnershipOf(field), MGPipeFieldOwnership::kBarrierPulled)
|
||||
<< kMGPipeInputFieldNames[Index(field)] << " left the reduced path's debt";
|
||||
}
|
||||
EXPECT_EQ(MGPipeFieldOwnershipOf(MGPipeInputField::GetPixelStoreParameters),
|
||||
MGPipeFieldOwnership::kApplierDerived);
|
||||
EXPECT_EQ(MGPipeFieldOwnershipOf(MGPipeInputField::GetPixelStoreParameters, 0u),
|
||||
MGPipeFieldOwnership::kApplierDerived);
|
||||
EXPECT_EQ(MGPipeFieldOwnershipOf(MGPipeInputField::GetPixelStoreParameters, 1u),
|
||||
MGPipeFieldOwnership::kFatal);
|
||||
|
||||
// The three off the reduced path, each for its own checkable reason.
|
||||
EXPECT_EQ(MGPipeFieldOwnershipOf(MGPipeInputField::GetBoundTransformFeedbackName),
|
||||
MGPipeFieldOwnership::kFatal);
|
||||
EXPECT_EQ(MGPipeFieldOwnershipOf(MGPipeInputField::GetTransformFeedbackPausedPrimitiveCounter),
|
||||
MGPipeFieldOwnership::kFatal);
|
||||
EXPECT_EQ(MGPipeFieldOwnershipOf(MGPipeInputField::GetProgramForDispatch),
|
||||
MGPipeFieldOwnership::kFatal);
|
||||
}
|
||||
|
||||
TEST_F(FieldOwnershipTest, TheSevenStickyForwardsAgreeWithTheirFieldRows) {
|
||||
ASSERT_EQ(kMGPipeFieldOwnershipForwardCount, kMGPipeInputStickyFieldCount);
|
||||
for (SizeT i = 0; i < kMGPipeFieldOwnershipForwardCount; ++i) {
|
||||
const MGPipeInputField field = kMGPipeFieldOwnershipForwardField[i];
|
||||
EXPECT_TRUE(kMGPipeInputFieldSticky[Index(field)])
|
||||
<< kMGPipeInputFieldNames[Index(field)] << " has a forward row but is not sticky";
|
||||
EXPECT_EQ(kMGPipeFieldOwnershipForward[i], MGPipeFieldOwnershipOf(field));
|
||||
EXPECT_STRNE(kMGPipeFieldOwnershipForwardMechanism[i], "");
|
||||
}
|
||||
}
|
||||
|
||||
// The stamp map, in both directions: the four P5 class-B boundaries, the eight mapped ahead of
|
||||
// the phase that will emit them, and the three verb-shaped calls that are exempt by name.
|
||||
TEST_F(FieldOwnershipTest, VerbBoundaryOpsCoverEveryVerbShapedCall) {
|
||||
// CONTRACT §7 class B minus Present - the only four that can arrive in P5.
|
||||
EXPECT_EQ(MGPipeVerbForWireOp(MGPWireOp::Clear), MGPipeVerb::Clear);
|
||||
EXPECT_EQ(MGPipeVerbForWireOp(MGPWireOp::DrawVbo), MGPipeVerb::DrawArrays);
|
||||
EXPECT_EQ(MGPipeVerbForWireOp(MGPWireOp::ReadPixels), MGPipeVerb::ReadPixels);
|
||||
EXPECT_EQ(MGPipeVerbForWireOp(MGPWireOp::Blit), MGPipeVerb::BlitFramebuffer);
|
||||
// Class C today, mapped anyway: an OMITTED stamp row is silent, because the record would
|
||||
// apply under the previous verb's serial, mask and name.
|
||||
EXPECT_EQ(MGPipeVerbForWireOp(MGPWireOp::LaunchGrid), MGPipeVerb::DispatchCompute);
|
||||
EXPECT_EQ(MGPipeVerbForWireOp(MGPWireOp::MemoryBarrier), MGPipeVerb::MemoryBarrier);
|
||||
EXPECT_EQ(MGPipeVerbForWireOp(MGPWireOp::BeginStreamOutput), MGPipeVerb::BeginTransformFeedback);
|
||||
EXPECT_EQ(MGPipeVerbForWireOp(MGPWireOp::EndStreamOutput), MGPipeVerb::EndTransformFeedback);
|
||||
EXPECT_EQ(MGPipeVerbForWireOp(MGPWireOp::PauseStreamOutput), MGPipeVerb::PauseTransformFeedback);
|
||||
EXPECT_EQ(MGPipeVerbForWireOp(MGPWireOp::ResumeStreamOutput), MGPipeVerb::ResumeTransformFeedback);
|
||||
EXPECT_EQ(MGPipeVerbForWireOp(MGPWireOp::GenerateMipmap), MGPipeVerb::GenerateMipmap);
|
||||
EXPECT_EQ(MGPipeVerbForWireOp(MGPWireOp::GetTextureImage), MGPipeVerb::GetTextureImage);
|
||||
// P5b (MG_Remote/CONTRACT-P5B.md): the renamed boundary the file left to "the phase that
|
||||
// emits it" - resource_copy_region is glCopyImageSubData only - and the five appended verbs,
|
||||
// each stamped as the GLFunctionsTable verb it reproduces. copy_framebuffer_to_texture also
|
||||
// carries glCopyTexSubImage2D and stamps CopyTexImage2D for both: one kBlitOrCopy mask.
|
||||
EXPECT_EQ(MGPipeVerbForWireOp(MGPWireOp::ResourceCopyRegion), MGPipeVerb::CopyImageSubData);
|
||||
EXPECT_EQ(MGPipeVerbForWireOp(MGPWireOp::BindShaderImage), MGPipeVerb::BindImageTexture);
|
||||
EXPECT_EQ(MGPipeVerbForWireOp(MGPWireOp::PatchParameter), MGPipeVerb::PatchParameteri);
|
||||
EXPECT_EQ(MGPipeVerbForWireOp(MGPWireOp::BindStreamOutput), MGPipeVerb::BindTransformFeedback);
|
||||
EXPECT_EQ(MGPipeVerbForWireOp(MGPWireOp::SetStorageBlockBinding),
|
||||
MGPipeVerb::ShaderStorageBlockBinding);
|
||||
EXPECT_EQ(MGPipeVerbForWireOp(MGPWireOp::CopyFramebufferToTexture), MGPipeVerb::CopyTexImage2D);
|
||||
EXPECT_EQ(kMGPipeVerbBoundaryOpCount, SizeT{18});
|
||||
EXPECT_EQ(kMGPipeVerbBoundaryExemptCount, SizeT{3});
|
||||
|
||||
// Present is class B (it is emitted in P5) and is STILL not a verb boundary:
|
||||
// FillPoints.def:21 - "Present and SetSwapInterval go through BackendObject virtuals and
|
||||
// read no frontend state, so they are not verbs here". Stamping there would retire the
|
||||
// previous verb's answers with nothing to put in their place.
|
||||
EXPECT_EQ(MGPipeVerbForWireOp(MGPWireOp::Present), MGPipeVerb::kVerbCount);
|
||||
EXPECT_EQ(MGPipeVerbForWireOp(MGPWireOp::SetSwapInterval), MGPipeVerb::kVerbCount);
|
||||
EXPECT_EQ(MGPipeVerbForWireOp(MGPWireOp::Flush), MGPipeVerb::kVerbCount);
|
||||
// ... and a record that is part of a verb rather than a boundary of one.
|
||||
EXPECT_EQ(MGPipeVerbForWireOp(MGPWireOp::SetDynamicState), MGPipeVerb::kVerbCount);
|
||||
EXPECT_EQ(MGPipeVerbForWireOp(MGPWireOp::GetCaps), MGPipeVerb::kVerbCount);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------
|
||||
// The behaviour: the table is load-bearing. Split builds only - it is the server verb stamp
|
||||
// that arms all of it, and nothing in a monolith lane stamps.
|
||||
// ---------------------------------------------------------------------------------------
|
||||
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
|
||||
TEST_F(FieldOwnershipTest, AServerStampMakesRecordSuppliedFieldsFreshAndWithdrawsTheRest) {
|
||||
MGPipeServerStampVerbBoundary(MGPipeVerb::Clear);
|
||||
EXPECT_TRUE(gPipeInputs.ServerStampedVerb());
|
||||
EXPECT_EQ(gPipeInputs.CurrentVerb(), MGPipeVerb::Clear);
|
||||
const MGPipeFieldMask& mask = kMGPipeClassFieldMask[static_cast<SizeT>(
|
||||
kMGPipeVerbClass[static_cast<SizeT>(MGPipeVerb::Clear)])];
|
||||
SizeT stamped = 0;
|
||||
for (SizeT i = 0; i < kMGPipeInputFieldCount; ++i) {
|
||||
const auto field = static_cast<MGPipeInputField>(i);
|
||||
const Bool fresh = MGPipeInputFieldIsFresh(gPipeInputs.FilledState(), field);
|
||||
// The stamp respects the verb's own may-read table for the client fill's reason: a
|
||||
// field outside the class was never copied for this verb, so answering it would hand
|
||||
// the server the previous verb's value.
|
||||
const Bool answerable = MGPipeFieldMaskHas(mask, field) &&
|
||||
(kMGPipeFieldOwnership[i] == MGPipeFieldOwnership::kRecordSupplied ||
|
||||
kMGPipeFieldOwnership[i] == MGPipeFieldOwnership::kApplierDerived);
|
||||
EXPECT_EQ(fresh, answerable)
|
||||
<< kMGPipeInputFieldNames[i] << " is " << MGPipeFieldOwnershipName(kMGPipeFieldOwnership[i])
|
||||
<< " and the stamp answered " << (fresh ? "fresh" : "stale");
|
||||
stamped += fresh ? 1 : 0;
|
||||
}
|
||||
// Not vacuous: kClear really does have record-supplied fields to stamp.
|
||||
EXPECT_GT(stamped, SizeT{0});
|
||||
|
||||
// AND FOUR NAMED FIELDS, NOT DERIVED FROM THE ARRAY UNDER TEST. The loop above recomputes
|
||||
// `answerable` out of kMGPipeFieldOwnership, so it can only catch a stamp that disagrees
|
||||
// with the table - never a table that is wrong. These four say what the stamp must do for
|
||||
// four fields whose class is an argument of this package rather than a lookup.
|
||||
const MGPipeFilledState& filled = gPipeInputs.FilledState();
|
||||
EXPECT_TRUE(MGPipeInputFieldIsFresh(filled, MGPipeInputField::GetClearColor)); // supplied
|
||||
EXPECT_TRUE(MGPipeInputFieldIsFresh(filled, MGPipeInputField::GetRenderStateParameters));
|
||||
EXPECT_FALSE(MGPipeInputFieldIsFresh(filled, MGPipeInputField::GetFramebufferBindingSlot)); // pulled
|
||||
EXPECT_FALSE(MGPipeInputFieldIsFresh(filled, MGPipeInputField::RecordError)); // sticky
|
||||
}
|
||||
|
||||
// THE STICKY EXEMPTION, CANCELLED. generated/PipeFilled.inc answers "fresh" for a sticky field
|
||||
// whatever the serial says - but it tests "never filled" FIRST, so the stamp's withdrawal
|
||||
// (FilledGen = 0) wins over kMGPipeInputFieldSticky without a line of the generated file
|
||||
// changing. Before this, the seven most dangerous fields were exempt by construction.
|
||||
TEST_F(FieldOwnershipTest, TheStickyExemptionIsCancelledByTheServerStamp) {
|
||||
MGPipeValidateForVerb(MGPipeVerb::Clear); // the CLIENT fills and stamps all 63, sticky included
|
||||
EXPECT_TRUE(MGPipeInputFieldIsFresh(gPipeInputs.FilledState(), MGPipeInputField::RecordError));
|
||||
MGPipeServerStampVerbBoundary(MGPipeVerb::Clear);
|
||||
for (SizeT i = 0; i < kMGPipeFieldOwnershipForwardCount; ++i) {
|
||||
const MGPipeInputField field = kMGPipeFieldOwnershipForwardField[i];
|
||||
EXPECT_FALSE(MGPipeInputFieldIsFresh(gPipeInputs.FilledState(), field))
|
||||
<< kMGPipeInputFieldNames[Index(field)] << " is still exempt under split";
|
||||
}
|
||||
}
|
||||
|
||||
// E4's NEGATIVE CONTROL. Move one field from RECORD-SUPPLIED to FATAL in FieldOwnership.def
|
||||
// and this case goes red by name: the read below aborts instead of completing.
|
||||
TEST_F(FieldOwnershipTest, ARecordSuppliedFieldIsReadableAfterAServerStamp) {
|
||||
ASSERT_EQ(MGPipeFieldOwnershipOf(MGPipeInputField::GetClearColor),
|
||||
MGPipeFieldOwnership::kRecordSupplied);
|
||||
MGPipeServerStampVerbBoundary(MGPipeVerb::Clear);
|
||||
(void)gPipeInputs.GetClearColor();
|
||||
(void)gPipeInputs.GetRenderStateParameters();
|
||||
EXPECT_EQ(MGPipeResidualPullCount(), Uint64{0});
|
||||
// The pixel store is in kReadback's class, not kClear's, so its readable half is exercised
|
||||
// under the verb that actually reads it.
|
||||
MGPipeServerStampVerbBoundary(MGPipeVerb::ReadPixels);
|
||||
(void)gPipeInputs.GetPixelStoreParameters(false); // the half that has a carrier
|
||||
EXPECT_EQ(MGPipeResidualPullCount(), Uint64{0});
|
||||
}
|
||||
|
||||
TEST_F(FieldOwnershipTest, ABarrierPulledReadAfterAServerStampIsCountedNotFatal) {
|
||||
MGPipeServerStampVerbBoundary(MGPipeVerb::ReadPixels);
|
||||
ASSERT_EQ(MGPipeResidualPullCount(), Uint64{0});
|
||||
(void)gPipeInputs.GetActiveTextureUnit();
|
||||
EXPECT_EQ(MGPipeResidualPullCount(), Uint64{1});
|
||||
(void)gPipeInputs.GetTextureContextId();
|
||||
(void)gPipeInputs.GetMaxTouchedTextureUnit();
|
||||
EXPECT_EQ(MGPipeResidualPullCount(), Uint64{3});
|
||||
}
|
||||
|
||||
// The seven carry no MGP_INPUT_CHECK, so freshness can never reach them; this is the only
|
||||
// thing that puts them in `rsp`.
|
||||
TEST_F(FieldOwnershipTest, AStickyForwardIsCountedAsAResidualPull) {
|
||||
MGPipeServerStampVerbBoundary(MGPipeVerb::Clear);
|
||||
ASSERT_EQ(MGPipeResidualPullCount(), Uint64{0});
|
||||
(void)gPipeInputs.ValidateProgramName(1u);
|
||||
(void)gPipeInputs.GetProgramObject(1u);
|
||||
EXPECT_EQ(MGPipeResidualPullCount(), Uint64{2});
|
||||
}
|
||||
|
||||
// ... and outside a server-stamped verb they are ordinary monolith calls, which is what keeps
|
||||
// InvalidateCompileEnv reachable from backend initialisation - the case the exemption exists
|
||||
// for - and what keeps build-split's monolith lanes behaving as a verify build's do.
|
||||
TEST_F(FieldOwnershipTest, NothingIsCountedOutsideAServerStampedVerb) {
|
||||
MGPipeValidateForVerb(MGPipeVerb::ReadPixels);
|
||||
(void)gPipeInputs.ValidateProgramName(1u);
|
||||
gPipeInputs.InvalidateCompileEnv();
|
||||
(void)gPipeInputs.GetActiveTextureUnit();
|
||||
EXPECT_EQ(MGPipeResidualPullCount(), Uint64{0});
|
||||
EXPECT_FALSE(gPipeInputs.ServerStampedVerb());
|
||||
}
|
||||
|
||||
// THE APPLIER'S OWN CLEAR, reached directly rather than through the client's fill. In a spawned
|
||||
// server MG_Impl is not in the process, so MGPipeValidateForVerb/MGPipeLeaveVerb never run and
|
||||
// MGPipeServerClearVerbBoundary is the ONLY thing that can disarm the flag; without it the
|
||||
// server latches TRUE after its first stamp and the sticky exemption - the one
|
||||
// InvalidateCompileEnv is reached from backend initialisation under - is gone for good.
|
||||
TEST_F(FieldOwnershipTest, TheAppliersOwnClearDisarmsTheStampWithoutTheClientsFill) {
|
||||
MGPipeServerStampVerbBoundary(MGPipeVerb::ReadPixels);
|
||||
ASSERT_TRUE(gPipeInputs.ServerStampedVerb());
|
||||
(void)gPipeInputs.ValidateProgramName(1u);
|
||||
ASSERT_EQ(MGPipeResidualPullCount(), Uint64{1});
|
||||
|
||||
MGPipeServerClearVerbBoundary(); // what PipeApplier must call on leaving the applier
|
||||
EXPECT_FALSE(gPipeInputs.ServerStampedVerb());
|
||||
(void)gPipeInputs.ValidateProgramName(1u);
|
||||
gPipeInputs.InvalidateCompileEnv();
|
||||
EXPECT_EQ(MGPipeResidualPullCount(), Uint64{1}) << "a forward outside a stamped verb was counted";
|
||||
}
|
||||
|
||||
// The verb's own may-read table still holds on the server: kClear does not read
|
||||
// GetActiveTextureUnit, so reading it there is a stale answer rather than a residual pull,
|
||||
// and it stays Fatal. Counting it would trade a loud staleness for a quiet one.
|
||||
TEST_F(FieldOwnershipTest, ABarrierPulledFieldOutsideTheVerbsClassIsStillFatal) {
|
||||
#if MGTEST_HAVE_FORK
|
||||
const ChildResult r = RunInChild([] {
|
||||
MGPipeServerStampVerbBoundary(MGPipeVerb::Clear);
|
||||
(void)gPipeInputs.GetActiveTextureUnit(); // BARRIER-PULLED, but not in kClear's class
|
||||
});
|
||||
ASSERT_TRUE(DiedOfAbort(r)) << DescribeStatus(r) << "\n" << r.Log;
|
||||
EXPECT_NE(r.Log.find("Fatal{UnmigratedPipeInput, \"GetActiveTextureUnit@Clear\"}"), std::string::npos)
|
||||
<< r.Log;
|
||||
EXPECT_EQ(r.Log.find("BARRIER-PULLED"), std::string::npos) << r.Log;
|
||||
#else
|
||||
GTEST_SKIP() << "needs fork";
|
||||
#endif
|
||||
}
|
||||
|
||||
TEST_F(FieldOwnershipTest, ResidualPullsReachThePublishedPerFrameCounter) {
|
||||
namespace PS = MG_Util::PipeStats;
|
||||
PS::SetEnabledForTesting(true);
|
||||
PS::ResetForTesting();
|
||||
MGPipeServerStampVerbBoundary(MGPipeVerb::ReadPixels);
|
||||
(void)gPipeInputs.GetActiveTextureUnit();
|
||||
EXPECT_EQ(PS::FrameCalls(PS::CallClass::ResidualPulls), Uint64{1});
|
||||
EXPECT_NE(PS::FormatWindowLine().find("rsp="), std::string::npos) << PS::FormatWindowLine();
|
||||
PS::ResetForTesting();
|
||||
PS::SetEnabledForTesting(false);
|
||||
}
|
||||
|
||||
#if MGTEST_HAVE_FORK
|
||||
|
||||
// R-7.3's proof that the instrumentation can go red. An instrumentation that cannot is
|
||||
// decoration, and the set it counts is not empty.
|
||||
TEST_F(FieldOwnershipTest, StrictErrorsTurnsABarrierPulledReadIntoANamedAbort) {
|
||||
const ChildResult r = RunInChild([] {
|
||||
MG_Config::Ipc.StrictErrors = true;
|
||||
MGPipeServerStampVerbBoundary(MGPipeVerb::ReadPixels);
|
||||
(void)gPipeInputs.GetActiveTextureUnit();
|
||||
});
|
||||
ASSERT_TRUE(DiedOfAbort(r)) << DescribeStatus(r) << "\n" << r.Log;
|
||||
EXPECT_NE(r.Log.find("Fatal{UnmigratedPipeInput, \"GetActiveTextureUnit@ReadPixels\"}"),
|
||||
std::string::npos)
|
||||
<< r.Log;
|
||||
EXPECT_NE(r.Log.find("BARRIER-PULLED"), std::string::npos) << r.Log;
|
||||
EXPECT_NE(r.Log.find("MOBILEGL_IPC_STRICT_ERRORS=1"), std::string::npos) << r.Log;
|
||||
// The strict line names the phase that owes the answer; a strict abort that did not would
|
||||
// leave the reader exactly where the gate found them.
|
||||
EXPECT_NE(r.Log.find("retires in P3b/P4b"), std::string::npos) << r.Log;
|
||||
}
|
||||
|
||||
TEST_F(FieldOwnershipTest, TheSameReadWithoutStrictErrorsSurvivesAndIsCounted) {
|
||||
const ChildResult r = RunInChild([] {
|
||||
MGPipeServerStampVerbBoundary(MGPipeVerb::ReadPixels);
|
||||
(void)gPipeInputs.GetActiveTextureUnit();
|
||||
if (MGPipeResidualPullCount() != 1) ::_exit(7);
|
||||
});
|
||||
ASSERT_TRUE(ExitedWith(r, 0)) << DescribeStatus(r) << "\n" << r.Log;
|
||||
EXPECT_EQ(r.Log.find("Fatal{"), std::string::npos) << r.Log;
|
||||
}
|
||||
|
||||
TEST_F(FieldOwnershipTest, StrictErrorsAlsoPromotesTheStickyForwards) {
|
||||
const ChildResult r = RunInChild([] {
|
||||
MG_Config::Ipc.StrictErrors = true;
|
||||
MGPipeServerStampVerbBoundary(MGPipeVerb::DrawArrays);
|
||||
(void)gPipeInputs.ValidateProgramName(1u);
|
||||
});
|
||||
ASSERT_TRUE(DiedOfAbort(r)) << DescribeStatus(r) << "\n" << r.Log;
|
||||
EXPECT_NE(r.Log.find("Fatal{UnmigratedPipeInput, \"ValidateProgramName@DrawArrays\"}"),
|
||||
std::string::npos)
|
||||
<< r.Log;
|
||||
}
|
||||
|
||||
// A FATAL-class read aborts whatever the knob says: no carrier, and the reduced path never
|
||||
// reads it, so it is a real defect rather than a debt.
|
||||
TEST_F(FieldOwnershipTest, AFatalClassReadAbortsEvenWithoutStrictErrors) {
|
||||
const ChildResult r = RunInChild([] {
|
||||
MGPipeServerStampVerbBoundary(MGPipeVerb::DrawArrays);
|
||||
(void)gPipeInputs.GetProgramForDispatch();
|
||||
});
|
||||
ASSERT_TRUE(DiedOfAbort(r)) << DescribeStatus(r) << "\n" << r.Log;
|
||||
EXPECT_NE(r.Log.find("Fatal{UnmigratedPipeInput, \"GetProgramForDispatch@DrawArrays\"}"),
|
||||
std::string::npos)
|
||||
<< r.Log;
|
||||
}
|
||||
|
||||
// The argument-keyed row: the pack half is answerable and the unpack half is not, and the
|
||||
// difference is the accessor's own argument rather than a second field id. Splitting the field
|
||||
// into two ids would have made the unpack half BARRIER-PULLED - silently served - which is
|
||||
// weaker than this.
|
||||
TEST_F(FieldOwnershipTest, TheUnpackHalfOfThePixelStoreAbortsWhileThePackHalfDoesNot) {
|
||||
const ChildResult fatal = RunInChild([] {
|
||||
MGPipeServerStampVerbBoundary(MGPipeVerb::ReadPixels);
|
||||
(void)gPipeInputs.GetPixelStoreParameters(true);
|
||||
});
|
||||
ASSERT_TRUE(DiedOfAbort(fatal)) << DescribeStatus(fatal) << "\n" << fatal.Log;
|
||||
EXPECT_NE(fatal.Log.find("Fatal{UnmigratedPipeInput, \"GetPixelStoreParameters@ReadPixels\"}"),
|
||||
std::string::npos)
|
||||
<< fatal.Log;
|
||||
// The line must say WHICH HALF. Without this the message is byte-identical to what a
|
||||
// genuinely stale read of the pack half would print, and the whole case for narrowing by
|
||||
// argument instead of by a second field id is that the reader is told which half they
|
||||
// asked for.
|
||||
EXPECT_NE(fatal.Log.find("argument 0 = 1 is FATAL while the field is APPLIER-DERIVED"),
|
||||
std::string::npos)
|
||||
<< fatal.Log;
|
||||
|
||||
const ChildResult ok = RunInChild([] {
|
||||
MGPipeServerStampVerbBoundary(MGPipeVerb::ReadPixels);
|
||||
(void)gPipeInputs.GetPixelStoreParameters(false);
|
||||
if (MGPipeResidualPullCount() != 0) ::_exit(7);
|
||||
});
|
||||
ASSERT_TRUE(ExitedWith(ok, 0)) << DescribeStatus(ok) << "\n" << ok.Log;
|
||||
EXPECT_EQ(ok.Log.find("Fatal{"), std::string::npos) << ok.Log;
|
||||
}
|
||||
|
||||
// One function edit, five call sites (Managers.cpp:5334, DirectGLES.cpp:8051, :8702, :8997,
|
||||
// :10623). The arm is the TRANSPORT, not the build: build-split's own lanes run monolith and
|
||||
// several of the five are on ordinary monolith paths they exercise.
|
||||
TEST_F(FieldOwnershipTest, AnUnmigratedEmulationIsFatalUnderARealTransportAndInertUnderMonolith) {
|
||||
const ChildResult monolith = RunInChild([] {
|
||||
MG_Config::Transport = MG_Config::TransportMode::Monolith;
|
||||
MGPipeUnmigratedEmulation("get-tex-image-shadow");
|
||||
});
|
||||
ASSERT_TRUE(ExitedWith(monolith, 0)) << DescribeStatus(monolith) << "\n" << monolith.Log;
|
||||
EXPECT_EQ(monolith.Log.find("Fatal{"), std::string::npos) << monolith.Log;
|
||||
|
||||
const ChildResult split = RunInChild([] {
|
||||
MG_Config::Transport = MG_Config::TransportMode::InProcess;
|
||||
MGPipeUnmigratedEmulation("get-tex-image-shadow");
|
||||
});
|
||||
ASSERT_TRUE(DiedOfAbort(split)) << DescribeStatus(split) << "\n" << split.Log;
|
||||
EXPECT_NE(split.Log.find("Fatal{UnmigratedEmulation, \"get-tex-image-shadow\"}"), std::string::npos)
|
||||
<< split.Log;
|
||||
}
|
||||
|
||||
#endif // MGTEST_HAVE_FORK
|
||||
#endif // MOBILEGL_BUILD_DISAGGREGATED
|
||||
#endif // MOBILEGL_PIPE_PUSH
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
// Before anything logs: MG_Util::Debug::InitFile() reads the variable once, on the first
|
||||
// write, and caches the FILE*. PipeInputsTest's idiom, and for its reason - the abort cases
|
||||
// read their Fatal line back out of this file.
|
||||
namespace fs = std::filesystem;
|
||||
const fs::path path =
|
||||
fs::temp_directory_path() / ("mobilegl-fieldownership-test-" + std::to_string(ProcessId()) + ".log");
|
||||
std::error_code ec;
|
||||
fs::remove(path, ec);
|
||||
g_logPath = path.string();
|
||||
#if defined(_WIN32)
|
||||
_putenv_s("MOBILEGL_LOG_FILE_PATH", g_logPath.c_str());
|
||||
#else
|
||||
setenv("MOBILEGL_LOG_FILE_PATH", g_logPath.c_str(), 1);
|
||||
#endif
|
||||
::testing::InitGoogleTest(&argc, argv);
|
||||
const int rc = RUN_ALL_TESTS();
|
||||
fs::remove(path, ec);
|
||||
return rc;
|
||||
}
|
||||
@@ -13,6 +13,10 @@
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include <cstring>
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <regex>
|
||||
#include <sstream>
|
||||
#include <iterator>
|
||||
#include <limits>
|
||||
#include <type_traits>
|
||||
@@ -25,11 +29,39 @@
|
||||
#if MOBILEGL_PIPE_PUSH
|
||||
#include <MG_Impl/Pipe/SlotAllocator.h>
|
||||
#include <MG_Pipe/PipeApply.h>
|
||||
// P5 R-17: the routing that INSTALLS the two tables. Included here so that the installation
|
||||
// case below states the partition deterministically rather than depending on whether some
|
||||
// other object in this particular test binary happened to drag the installer in.
|
||||
#include <MG_Pipe/PipeRoute.h>
|
||||
#endif
|
||||
|
||||
using namespace MobileGL;
|
||||
using namespace MobileGL::MG_Pipe;
|
||||
|
||||
TEST(PipeCatalogue, FrontendNeverTakesAnApplierAddress) {
|
||||
namespace fs = std::filesystem;
|
||||
auto base = fs::current_path();
|
||||
while (!fs::is_directory(base / "MobileGL/MG_Impl") && base != base.root_path())
|
||||
base = base.parent_path();
|
||||
const auto root = base / "MobileGL/MG_Impl";
|
||||
ASSERT_TRUE(fs::is_directory(root)) << "frontend source unavailable: " << root;
|
||||
const std::regex comments(R"(/\*[\s\S]*?\*/|//[^\n]*)");
|
||||
const std::regex address(R"(&\s*MGPipeApply[A-Za-z_0-9]*)");
|
||||
for (const auto& entry : fs::recursive_directory_iterator(root)) {
|
||||
if (!entry.is_regular_file()) continue;
|
||||
const auto ext = entry.path().extension();
|
||||
if (ext != ".cpp" && ext != ".h" && ext != ".inc") continue;
|
||||
std::ifstream input(entry.path());
|
||||
ASSERT_TRUE(input.good()) << entry.path();
|
||||
std::ostringstream bytes;
|
||||
bytes << input.rdbuf();
|
||||
const auto code = std::regex_replace(bytes.str(), comments, "");
|
||||
EXPECT_FALSE(std::regex_search(code, address))
|
||||
<< "FrontendApplierAddress: " << entry.path()
|
||||
<< " must take the route address; routing tables live outside MG_Impl";
|
||||
}
|
||||
}
|
||||
|
||||
namespace {
|
||||
// Counting expansions of the catalogue. The Class parameter is a real enumerator, so a
|
||||
// per-class count is a constant expression too.
|
||||
@@ -98,20 +130,117 @@ TEST(PipeCatalogue, GeneratedTablesHoldTheWholeCatalogue) {
|
||||
EXPECT_EQ(ClassCount<kCtxCso>(), 13u);
|
||||
EXPECT_EQ(ClassCount<kCtxState>(), 17u);
|
||||
EXPECT_EQ(ClassCount<kCtxObject>(), 9u);
|
||||
EXPECT_EQ(ClassCount<kCtxVerb>(), 13u);
|
||||
// 13 + the five P5b-appended verbs (MG_Remote/CONTRACT-P5B.md): bind_shader_image,
|
||||
// patch_parameter, bind_stream_output, set_storage_block_binding,
|
||||
// copy_framebuffer_to_texture.
|
||||
EXPECT_EQ(ClassCount<kCtxVerb>(), 18u);
|
||||
}
|
||||
|
||||
// An uninstalled pipe is every entry null - which is exactly what "this subsystem has not
|
||||
// been migrated, keep pulling" means (plan B section 4.1).
|
||||
// A row nobody has migrated is null - which is exactly what "this subsystem has not been
|
||||
// migrated, keep pulling" means (plan B section 4.1).
|
||||
//
|
||||
// UNTIL P5 R-17 THAT WAS EVERY ROW, and this case said so. It is now EXACTLY THE 34 ROWS WITH
|
||||
// NO MGPipeApply* ENTRY POINT: the other 37 have an applier, R-17 installs adapters over them,
|
||||
// and a null there would no longer mean "keep pulling" - `MG_Impl/Pipe`'s call sites go through
|
||||
// the thunks, so a null would mean "call through a null pointer". The number is asserted rather
|
||||
// than the emptiness, because "37 installed" and "34 still null" are the two halves of a
|
||||
// partition and a case that checked only one of them would pass an installer that had
|
||||
// overwritten rows it does not own.
|
||||
// THE NAME IS KEPT, AND SO IS THE STATEMENT IT MAKES - only the ROWS it makes it about have
|
||||
// narrowed. G2/G14 compare ctest names against a pre-P5 baseline and require ZERO removed, so
|
||||
// renaming a case is a removal even when the new name is better: it is indistinguishable, from
|
||||
// the gate's side, from a case that was deleted. So this case stays, asserting the half that is
|
||||
// still true, and the new half below is an ADDED name.
|
||||
TEST(PipeCatalogue, UninstalledTablesAreAllNull) {
|
||||
const void* const* screen = reinterpret_cast<const void* const*>(&gMGPipeScreen);
|
||||
for (SizeT i = 0; i < kMGPipeScreenCallCount; ++i) {
|
||||
EXPECT_EQ(screen[i], nullptr) << "screen entry " << i;
|
||||
}
|
||||
const void* const* context = reinterpret_cast<const void* const*>(&gMGPipeContext);
|
||||
for (SizeT i = 0; i < kMGPipeContextCallCount; ++i) {
|
||||
EXPECT_EQ(context[i], nullptr) << "context entry " << i;
|
||||
#if MOBILEGL_PIPE_PUSH
|
||||
MGPipeInstallMonolithTables();
|
||||
// The 34 rows with no MGPipeApply* entry point are still null, and null still means "this
|
||||
// subsystem has not been migrated, keep pulling". Named rather than counted, because the
|
||||
// count is the other case's job and two cases asserting the same number would both go red
|
||||
// for one change.
|
||||
EXPECT_EQ(gMGPipeContext.SetShaderBuffers, nullptr);
|
||||
EXPECT_EQ(gMGPipeContext.SetStreamOutputTargets, nullptr);
|
||||
EXPECT_EQ(gMGPipeContext.DrawVbo, nullptr);
|
||||
EXPECT_EQ(gMGPipeContext.Present, nullptr);
|
||||
EXPECT_EQ(gMGPipeContext.SetSwapInterval, nullptr);
|
||||
EXPECT_EQ(gMGPipeScreen.GetCaps, nullptr);
|
||||
EXPECT_EQ(gMGPipeContext.QueryCreate, nullptr);
|
||||
EXPECT_EQ(gMGPipeScreen.FenceCreate, nullptr);
|
||||
#else
|
||||
// A pull build compiles no applier and no routing, so the pre-migration statement is the
|
||||
// whole truth there and this case is the one that says so.
|
||||
for (SizeT i = 0; i < kMGPipeScreenCallCount; ++i) EXPECT_EQ(screen[i], nullptr) << i;
|
||||
for (SizeT i = 0; i < kMGPipeContextCallCount; ++i) EXPECT_EQ(context[i], nullptr) << i;
|
||||
#endif
|
||||
(void)screen;
|
||||
(void)context;
|
||||
}
|
||||
|
||||
TEST(PipeCatalogue, ExactlyTheRoutedRowsAreInstalledAndTheRestAreStillNull) {
|
||||
const void* const* screen = reinterpret_cast<const void* const*>(&gMGPipeScreen);
|
||||
const void* const* context = reinterpret_cast<const void* const*>(&gMGPipeContext);
|
||||
SizeT installed = 0;
|
||||
SizeT nulls = 0;
|
||||
|
||||
#if MOBILEGL_PIPE_PUSH
|
||||
// IDEMPOTENT, and called here on purpose: what this case observes is WHICH rows the
|
||||
// installer fills, not whether an installer ran somewhere in this binary. Leaving that to
|
||||
// ambient linkage is what made the same assertion pass in one build directory and fail in
|
||||
// another - the object file carrying a static initialiser was dropped by the linker in the
|
||||
// binaries that did not name a symbol in it.
|
||||
MGPipeInstallMonolithTables();
|
||||
#endif
|
||||
|
||||
for (SizeT i = 0; i < kMGPipeScreenCallCount; ++i) {
|
||||
if (screen[i] != nullptr) ++installed; else ++nulls;
|
||||
}
|
||||
for (SizeT i = 0; i < kMGPipeContextCallCount; ++i) {
|
||||
if (context[i] != nullptr) ++installed; else ++nulls;
|
||||
}
|
||||
EXPECT_EQ(installed + nulls, static_cast<SizeT>(kMGPipeCallCount));
|
||||
|
||||
#if MOBILEGL_PIPE_PUSH
|
||||
// 33 + 4 = 37, and the split is the honest shape of R-17 rather than an implementation
|
||||
// detail: 37 is the number of MGPipeApply* entry points PipeApply.h declares, 33 of them
|
||||
// fit a GENERATED row and go in the two tables, and FOUR cannot be expressed by any
|
||||
// generated signature and go in the hand-written escape table beside them
|
||||
// (ResourceRespecify's uncarried initialBytes, ResourceFlushRange's likewise,
|
||||
// MapPersistent's size + seedBytes + void* return, CreateShaderState's seven blobrefs and
|
||||
// two typed pointers - each one a CONTRACT-P5 ruling, see MG_Pipe/PipeRoute.h).
|
||||
//
|
||||
// BOTH NUMBERS ARE ASSERTED. If the escape table were left out of this case, moving a row
|
||||
// out of the generated tables and forgetting to install its escape would read as a smaller
|
||||
// "installed" count and nothing else - and the call site would take a null.
|
||||
EXPECT_EQ(installed, 33u) << "the routed rows and the applier's entry points disagree";
|
||||
EXPECT_EQ(nulls, static_cast<SizeT>(kMGPipeCallCount) - 33u);
|
||||
const void* const* escapes = reinterpret_cast<const void* const*>(&gMGPipeRouteEscapes);
|
||||
SizeT escapesInstalled = 0;
|
||||
for (SizeT i = 0; i < sizeof(MGPipeRouteEscapes) / sizeof(void*); ++i) {
|
||||
if (escapes[i] != nullptr) ++escapesInstalled;
|
||||
}
|
||||
EXPECT_EQ(escapesInstalled, 4u) << "an escape row is null; its call site would take a null "
|
||||
"pointer rather than fall back to anything";
|
||||
EXPECT_EQ(installed + escapesInstalled, 37u)
|
||||
<< "the two tables plus the escapes must be exactly PipeApply.h's entry points";
|
||||
|
||||
// And the rows that MUST still be null, named rather than counted: these are calls with no
|
||||
// applier at all (CONTRACT-P5 table 1 rows 13, 14: "no applier entry point exists"), plus
|
||||
// the two verbs the census measured as having zero MG_Impl call sites. An installer that
|
||||
// filled one of these would be claiming an implementation that does not exist.
|
||||
EXPECT_EQ(gMGPipeContext.SetShaderBuffers, nullptr);
|
||||
EXPECT_EQ(gMGPipeContext.SetStreamOutputTargets, nullptr);
|
||||
EXPECT_EQ(gMGPipeContext.DrawVbo, nullptr);
|
||||
EXPECT_EQ(gMGPipeContext.Present, nullptr);
|
||||
EXPECT_EQ(gMGPipeContext.SetSwapInterval, nullptr);
|
||||
EXPECT_EQ(gMGPipeScreen.GetCaps, nullptr);
|
||||
#else
|
||||
// A pull build compiles no applier and no routing, so the pre-migration statement is still
|
||||
// the whole truth there.
|
||||
EXPECT_EQ(installed, 0u);
|
||||
EXPECT_EQ(nulls, static_cast<SizeT>(kMGPipeCallCount));
|
||||
#endif
|
||||
}
|
||||
|
||||
// The retirement ratchet of the migration carrier (section 6.3): the constant and the
|
||||
@@ -419,7 +548,41 @@ TEST(PipeCatalogue, LateArrivalsAreAppendedWithoutRenumbering) {
|
||||
EXPECT_EQ(static_cast<Uint16>(MGPWireOp::QueryTimestamp), 69);
|
||||
EXPECT_EQ(static_cast<Uint16>(MGPWireOp::QueryCounter), 70);
|
||||
EXPECT_EQ(static_cast<Uint16>(MGPWireOp::FenceWaitServer), 71);
|
||||
EXPECT_EQ(static_cast<Uint16>(MGPWireOp::kOpCount), 72);
|
||||
// P5b (MG_Remote/CONTRACT-P5B.md) appended five verbs AFTER P0's three late arrivals, by
|
||||
// the same rule: opcodes 72..76, and nothing before them moved. The five are pinned by
|
||||
// VALUE, because the pin is the protocol - a row inserted ahead of one would silently
|
||||
// re-point every record a P5b package emits at the wrong arm.
|
||||
EXPECT_EQ(static_cast<Uint16>(MGPWireOp::BindShaderImage), 72);
|
||||
EXPECT_EQ(static_cast<Uint16>(MGPWireOp::PatchParameter), 73);
|
||||
EXPECT_EQ(static_cast<Uint16>(MGPWireOp::BindStreamOutput), 74);
|
||||
EXPECT_EQ(static_cast<Uint16>(MGPWireOp::SetStorageBlockBinding), 75);
|
||||
EXPECT_EQ(static_cast<Uint16>(MGPWireOp::CopyFramebufferToTexture), 76);
|
||||
EXPECT_EQ(static_cast<Uint16>(MGPWireOp::kOpCount), 77);
|
||||
// And the P5b rows carry what their contract says: one blob (the block name) and nothing
|
||||
// else, and the extended draw row keeps its two flags.
|
||||
EXPECT_EQ(MGPipeCallFlagsFor(MGPWireOp::SetStorageBlockBinding), static_cast<Uint32>(kHasBlob));
|
||||
EXPECT_EQ(MGPipeCallFlagsFor(MGPWireOp::BindShaderImage), static_cast<Uint32>(kNone));
|
||||
EXPECT_EQ(MGPipeCallFlagsFor(MGPWireOp::PatchParameter), static_cast<Uint32>(kNone));
|
||||
EXPECT_EQ(MGPipeCallFlagsFor(MGPWireOp::BindStreamOutput), static_cast<Uint32>(kNone));
|
||||
EXPECT_EQ(MGPipeCallFlagsFor(MGPWireOp::CopyFramebufferToTexture), static_cast<Uint32>(kNone));
|
||||
EXPECT_EQ(MGPipeCallFlagsFor(MGPWireOp::DrawVbo), static_cast<Uint32>(kHostSpan | kVarTail));
|
||||
// The P5b payload sizes, pinned like every other MGP_ASSERT_POD at runtime so the numbers
|
||||
// show up in ctest output; MGPCopyRegion grew 64 -> 72 for its two GL names (i1).
|
||||
EXPECT_EQ(sizeof(MGPImageBind), 40u);
|
||||
EXPECT_EQ(sizeof(MGPPatchParameter), 8u);
|
||||
EXPECT_EQ(sizeof(MGPStreamOutputBind), 16u);
|
||||
EXPECT_EQ(sizeof(MGPStorageBlockBinding), 40u);
|
||||
EXPECT_EQ(sizeof(MGPCopyFromFramebuffer), 48u);
|
||||
EXPECT_EQ(sizeof(MGPCopyRegion), 72u);
|
||||
EXPECT_EQ(sizeof(MGPDrawIndirect), 40u);
|
||||
// The two draw-flag bits P5b's d1 arms are exclusive by contract and distinct by value.
|
||||
EXPECT_EQ(static_cast<Uint32>(kDrawIsIndirect), 1u << 5);
|
||||
EXPECT_EQ(static_cast<Uint32>(kDrawHasUserIndices) & static_cast<Uint32>(kDrawIsIndirect), 0u);
|
||||
// The clear discriminants have ONE spelling now, and Whole is 0 so a zeroed record is a
|
||||
// whole-framebuffer clear.
|
||||
EXPECT_EQ(kMGPipeClearKindWhole, 0u);
|
||||
EXPECT_EQ(kMGPipeClearKindDepthStencil + 1, kMGPipeClearKindCount);
|
||||
EXPECT_EQ(kMGPipeClearValueClassUint + 1, kMGPipeClearValueClassCount);
|
||||
}
|
||||
|
||||
// A well-formed record passes the applier's bounds gate. P0 has no applier, so "accepted"
|
||||
@@ -606,7 +769,10 @@ TEST(PipeCatalogue, FloatVectorsCompareBitwise) {
|
||||
// a cache that read the padding would mint a fresh CSO per call and the verify lane would
|
||||
// abort at random.
|
||||
TEST(PipeCatalogue, SixValueStructsHaveFieldLists) {
|
||||
EXPECT_EQ(kMGPipeVerifiedPayloadCount, 72u);
|
||||
// 72 through P5; P5b appended five call payloads (MG_Remote/CONTRACT-P5B.md: MGPImageBind,
|
||||
// MGPPatchParameter, MGPStreamOutputBind, MGPStorageBlockBinding, MGPCopyFromFramebuffer),
|
||||
// each with its own field list, so the comparator sees every one of them: 77.
|
||||
EXPECT_EQ(kMGPipeVerifiedPayloadCount, 77u);
|
||||
static_assert(MGPipeHasFieldVerifier<RenderStateParameters>::value);
|
||||
static_assert(MGPipeHasFieldVerifier<PixelStoreParameters>::value);
|
||||
static_assert(MGPipeHasFieldVerifier<PerBufferBlendState>::value);
|
||||
@@ -850,6 +1016,36 @@ TEST(PipeCatalogue, ResourceRespecifyAcksOnlyImmutableStorage) {
|
||||
#undef MGP_COUNT_ACKING_CALLS
|
||||
EXPECT_EQ(ackingCalls, 1u);
|
||||
|
||||
// P5 R-16: the same shape over kReplySlot, which had no count pin at all until the flag
|
||||
// became load-bearing. It is what sizes the reply pool and what the decoder posts against,
|
||||
// so the number is now a protocol quantity rather than a documentation one.
|
||||
//
|
||||
// FOURTEEN. Ten answers that were always declared - get_caps, map_persistent, the two fence
|
||||
// reads, the three query reads, the two readbacks and read_pixels - plus the FOUR ACCEPTANCE
|
||||
// ROWS, whose applier entry points return a Bool the client acts on destructively and which
|
||||
// carried no flag because in monolith that answer is a direct call's return value.
|
||||
Uint32 replySlotCalls = 0;
|
||||
#define MGP_COUNT_REPLY_SLOT_CALLS(Name, Payload, Class, Flags) \
|
||||
if ((static_cast<Uint32>(Flags) & static_cast<Uint32>(kReplySlot)) != 0) ++replySlotCalls;
|
||||
MGP_CALL_LIST(MGP_COUNT_REPLY_SLOT_CALLS)
|
||||
#undef MGP_COUNT_REPLY_SLOT_CALLS
|
||||
EXPECT_EQ(replySlotCalls, 14u);
|
||||
|
||||
// And the four by name, because a count alone would let a row lose the flag while another
|
||||
// gained one. These are exactly the MGPipeApply* entry points that return Bool
|
||||
// (PipeApply.h:820, :868, :897, :1023); map_persistent's void* is the fifth answer and was
|
||||
// already declared.
|
||||
Uint32 acceptanceWithSlot = 0;
|
||||
#define MGP_COUNT_ACCEPTANCE_ROWS(Name, Payload, Class, Flags) \
|
||||
if ((std::strcmp(#Name, "ResourceCreate") == 0 || std::strcmp(#Name, "ResourceRespecify") == 0 || \
|
||||
std::strcmp(#Name, "ResourceSubData") == 0 || std::strcmp(#Name, "SetTextureParams") == 0) && \
|
||||
(static_cast<Uint32>(Flags) & static_cast<Uint32>(kReplySlot)) != 0) { \
|
||||
++acceptanceWithSlot; \
|
||||
}
|
||||
MGP_CALL_LIST(MGP_COUNT_ACCEPTANCE_ROWS)
|
||||
#undef MGP_COUNT_ACCEPTANCE_ROWS
|
||||
EXPECT_EQ(acceptanceWithSlot, 4u);
|
||||
|
||||
// glBufferStorage: an immutable store, and the one entry point allowed a synchronous ack.
|
||||
MGPResourceDesc immutable{};
|
||||
immutable.Immutable = 1;
|
||||
|
||||
@@ -1260,6 +1260,18 @@ namespace {
|
||||
// until now by POISON being invisible in this TU at all (see the include at the top).
|
||||
#elif !MOBILEGL_PIPE_VERIFY
|
||||
GTEST_SKIP() << "Fatal{PipeLiveHostWrites} is a MOBILEGL_PIPE_VERIFY wire and is compiled out here";
|
||||
// P5 b1: AND IT IS RETIRED IN A SPLIT BUILD, because this is the phase the wire was
|
||||
// waiting for. "HasLiveHostWrites is always false and is written by nobody" cannot
|
||||
// survive the producer it exists to announce - MGPSubData::HasLiveHostWrites, set by
|
||||
// MGPipeEmitResourceSubData - so under MOBILEGL_BUILD_DISAGGREGATED the always-false
|
||||
// pin is gone and two other things carry the invariant instead:
|
||||
// PinLiveHostWritesNamesABuffer (the bit is buffer-family only, and that IS still
|
||||
// always true) and the production-path probe pair in MG_Test/SanityTest.cpp and
|
||||
// MG_Test/Buffer/SplitBufferTest.cpp, both of which go red when the producer is
|
||||
// deleted. This skip is what the build-verify-split lane exists to make visible.
|
||||
#elif MOBILEGL_BUILD_DISAGGREGATED
|
||||
GTEST_SKIP() << "P5 gave HasLiveHostWrites a producer, so the always-false wire is retired "
|
||||
"in a split build; PinLiveHostWritesNamesABuffer replaces it";
|
||||
#elif !MGTEST_HAVE_FORK
|
||||
GTEST_SKIP() << "no fork on this platform; the wire's verdict is std::abort()";
|
||||
#else
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user