Compare commits

...
17 Commits
Author SHA1 Message Date
swung0x48 7cdc8d775e [Docs] (Disaggregated): refresh the P5c close-out status lines - README and ARCHITECTURE section 17.6 were still describing P5c as planned, and the code head is the triage head b88e8487 everywhere 2026-09-17 18:57:14 -04:00
swung0x48 36176b9dbc [Docs, MG_Remote] (Disaggregated): close out P5c - the inproc split's direct cross-role access is zeroed
ROADMAP marks P5c closed at the triage head and P6 next; CURRENT_STAGE_PROGRESS carries
the current-head gate table (unit 2187/2187, integration-split 111/111, the census
classification with every newly-red entry evidenced by its Fatal name, the three named G1
resizes, the 0xDD audit, the per-frame rsp measurements, and the two items deliberately
not done locally: the Redmi retest and the 79-trace census); MEASUREMENTS gains section 8
with the per-gate evidence. CONTRACT-P5C takes the amendments ratified at gt's landing
and at the regression triage: per-level extent is retired at the sites rather than
guarded on the accessor, the strict CI lane is two-sided (unit green gate plus
expected-red scenario lane with the marker asserted), the drain points are two classes
(the EGL RPC returns beside EmitAndWait), and oversized writebacks are client-sliced at a
quarter of the event ring.
2026-09-17 13:15:57 -04:00
swung0x48 b88e848761 [MG_Remote, MG_State, MG_Impl, MG_Backend, MG_IntegrationTest] (Disaggregated): P5c census triage - the three real regressions the merge owed
The broad inproc census against a same-machine 11ac3de6 baseline found 183 newly-failing;
172 are the design-red the contract rules (the legacy-arm refusal under transport: the
subsystem-off and legacy control lanes, and Magma's P7 surface - every one carries its
Fatal name in ~/p5c-fatal-map.tsv), and the other eleven were three REAL regressions,
fixed here:

1. The surface-changed event drained at the first verb's EmitAndWait, but a pre-verb
   glGetFramebufferAttachmentParameteriv on the default framebuffer was answered from the
   placeholder attachments, and buffers allocated from that answer are blit-incompatible
   with the real surface (DepthStencilReadbackAttachmentShapeScenario). The event ring
   gains its SECOND drain-point class: the blocking EGL lifecycle RPC returns
   (BackendObject_Remote's surface create/resize and make-current) - the same known-idle
   premise as EmitAndWait's post-barrier point. CONTRACT-P5C section 4.1 amended.
2. A whole-buffer writeback larger than the event ring could never fit one record
   (capacity/2), aborting the server with Fatal{EventRingOverflow} on the large-arena
   readbacks. The client now slices the request at a quarter of the ring (header and
   co-posted small events ride along), each slice round-tripping its own barrier + drain;
   the whole-buffer flag is cleared by hand after the last slice lands, which is exactly
   what WritebackFromBackend's clear says. CONTRACT-P5C section 4.4 amended.
3. ScatterCapturedRecords / ReadbackCapturedRanges read the capture buffers through the
   frontend MappedData() (a layer-1 surface since gt) and wrote back by direct call. The
   XFB capture path now reads the server's staged shadow (RequireStagedCoverage asserted,
   syncedChangeSerial bumped so no later draw overwrites the capture with stale shadow)
   and writes back through OnBufferWriteback, the Ops_H_Readback order.

CtWireScenario's two death cases skip on DirectVulkan by name: object_death's producer is
the Espryt-side death-notice ops and Magma installs none until P7.

Evidence: unit 2187/2187; integration-split 111/111; the three families' named cases green
again; census newly-failing reduced to the evidenced design-red set.
2026-09-17 13:13:41 -04:00
swung0x48 39d1a5d38c Merge branch 'p5c-gt' into feat/disaggregated (P5c gt: role guards, InBarrierWait wired, rsp measured) 2026-09-17 11:21:39 -04:00
swung0x48 ab9250281b [Docs, MG_Backend] (Disaggregated): P5c housekeeping - the death-switch scope comment describes the landed ct shape (the NoSession arm only), and the README counts 79 calls after ct/rv 2026-09-17 11:21:39 -04:00
swung0x48 a0865b00f4 [MG_State, MG_Backend, MG_Remote, MG_Impl, CI] (Disaggregated): P5c gt - the role guards close the phase
Layer 1 arms the texture object surfaces at MipmapStorage (the one point every concrete
texture class and view forwards through): AllocateStorage, TruncateMipmapLevels,
UpdateMipmapSubData, MapMipmapData, MarkStorageDirty(Region), IsStorageDirty,
GetStorageDirtyRegion(s) take Fatal{RoleViolation, texture-legacy-arm} from the apply
thread with an active transport. What the lane then exposed is fixed, not exempted: the
completeness gate answers from the staged store's defined-ness, the two logging reads go
through the descriptor macro, and the remint replay loop keeps its named
Fatal{UnmigratedEmulation} ahead of the guard. Magma's texture sync read path is the one
named exemption (MGPipeTextureLegacyArmScope, P7). Layer 2 wires InBarrierWait as the
client half of the gPipeInputs single-writer rule (RefusePipeInputsTouchWhileApplierOwnsIt:
applier owns it AND this thread not in a barrier wait => Fatal{RoleViolation,
gPipeInputs}; the barrier-off negative control is deferred to its own Fatal), and stale
reads of RECORD-SUPPLIED / APPLIER-DERIVED fields under a server stamp now report
RoleViolation with the field named. The RemoteGuards suite pins all nine texture surfaces
plus HasDefinedContent by name, and a negative control for the fill window. CI gains the
integration-split-strict job: unit lane as the hard gate under MOBILEGL_IPC_STRICT_ERRORS=1,
the scenario lane expected-red with the marker asserted (rewritable to plain green once P7
retires the object-class rows). rsp is per-frame in the stats line and measured on the
locally available traces (bsl in-world 948.5/frame avg over 123 frames, complementary
1591.9, iterationrp 286 until its named remint-pull Fatal); value-class pulls are zero by
rv's pinned list, what remains is the object-class fifteen.

Evidence: unit 2187/2187 (also under STRICT_ERRORS=1); integration-split 111/111; red-once
per layer (the texture guard and the gPipeInputs guard each turned their named death test
red and restored green). CONTRACT-P5C sections 5.4, 6.
2026-09-17 11:20:44 -04:00
swung0x48 c74de6b506 Merge branch 'p5c-rv' into feat/disaggregated (P5c rv: residual-value record, value-class pulls retired) 2026-09-17 09:27:47 -04:00
swung0x48 82b1f743a7 [MG_Pipe, MG_Impl, MG_Remote, MG_Backend] (Disaggregated): P5c rv - set_context_values retires the value-class BARRIER_PULLED rows
set_context_values (opcode 79, MGPContextValues 96B, kCtxState) carries the active texture
unit, the max touched unit, the fifteen touched-binding-point counts and the five value-class
XFB rows, emitted at validate under the subsystem bit and hash-suppressed as a whole; the
emit gate and the residual-skip gate read the same answer so they can never disagree.
MGPipeApplySetContextValues writes gPipeInputs (the PackState shape). MGPAttribValue grows
24->56B to carry the frontend's converted three views, and MGPipeApplySetVertexAttribDefaults
finally writes them (the 'ignores MGPAttribValue::ValueClass' warning dies), so
GetCurrentVertexAttribute leaves the refusal set. The three texture shutters answer the
applier's own serials under a server-stamped verb (APPLIER_DERIVED), storage answer kept
verbatim elsewhere. FieldOwnership.def: nine value-class rows become derived RECORD_SUPPLIED,
the three shutters APPLIER_DERIVED, the nine object-class rows keep their phases;
FieldOwnershipTest pins that the remaining pulls are exactly the object-class list.
gen_pipe.py gains SCAN_EXEMPT_ACCESSORS with per-name reasons and retiring phases (it repairs
the --check gate the hd merge's two G6 probes had left red).

Evidence: unit 2175/2175; integration-split 111/111; both generators' --check and
--self-test green; rsp on the Xfb capture scenario 36 -> 22; red-once - gating the emission
off turns seven named scenarios red, restoring returns 111/111. CONTRACT-P5C section 5.3.
2026-09-17 09:27:36 -04:00
swung0x48 04650ca35e Merge branch 'p5c-ct' into feat/disaggregated (P5c ct: applier_reset / object_death control records)
# Conflicts:
#	MobileGL/MG_Backend/DirectGLES/Managers.h
2026-09-17 06:58:45 -04:00
swung0x48 63f8bb1f8f [Docs, MG_Pipe] (Disaggregated): CONTRACT-P5C amendments ratified at the tx/ev/hd landing
Table 0 gains the MGPSurfaceInfo zero-extent semantics row (ev). section 2.1 is amended
to the handle-keyed store with whole-run coverage and defined-ness tracking (tx's three
in-field rulings: a twin-address key would force glGenTextures at adopt time; region-
precise coverage false-Fatals the legal texStorage-then-small-box flow; Levels=N says
nothing about a sparse chain). section 2.3 records Espryt's driver-side mip generation
as a final shape beside Magma's store marking. section 3.1 gains the two named scoped
exemptions (the un-emitted binding records family, P4b/P7; the G6 frontend-keyed
registry family, P3b/P4b) and section 3.3/3.6 take hd's in-field shapes (the verb-handle
workspace with the state note; HasDefinedContent OR staged coverage, because the
streaming idiom defines content through subdata with no new descriptor). section 5.2
takes ct's documented NoSession server-only-fixture arm. FieldOwnership.def moves
InvalidateCompileEnv (field and forward rows) to FATAL with the deletion as mechanism
(P5c ev), regenerated .inc checked in; --check and --self-test green.
2026-09-17 06:57:38 -04:00
swung0x48 b45bf68101 Merge branch 'p5c-hd' into feat/disaggregated (P5c hd: handle-keyed resolution)
Conflict: VulkanRenderer.cpp's disaggregated include block took both halves.

Merge coordination (integrator, with the evidence inline):

- hd's Fatal{RoleViolation, MGPipeSlots} guard as landed was kind-blind: it fired on the
  G6 frontend-keyed twin registry (texture/VAO/program/sampler resolver probes - P3b/P4b's
  to rekey) and on the families whose handle-carrying records the client does not emit
  until P4b (the buffer binding-point ensures, the GPU-written announcement). Integration-
  split went 104/107 red at the first Clear. Two NAMED, scoped exemptions keep the guard's
  teeth for every other caller (SlotAllocator.{h,cpp}): MGPipeReverseAnnouncementScope
  (buffer ensure + announcement family, P4b/P7) and MGPipeFrontendKeyedRegistryScope
  (the G6 registry family, P3b/P4b; also the mailbox death switch until ct's object_death
  record retires it). ~30 resolver sites wrapped, each naming its debt in the comment.
- ScopedRestartIndexSubstitution needed NO exemption: the EBO resolves from the record's
  IndexBuffer.Res and the bytes read from the server staged shadow - CONTRACT-P5B d1's
  own sentence, implemented.
- Magma's named blit takes a G6 consume arm (frontend FBOs resolved by lifetime id inside
  the scope, VerbBlitNamedConsumed set, loud refusal kept for a failed resolution), so the
  two DirectVulkan.Split.NamedBlit correctness cases stay green; Magma's hidden blit and
  depth-mipmap resources' teardown probes are wrapped and named (P7: give them non-frontend
  storage).
- MG_State gains GLContext::FindFramebufferObjectByLifetimeId (behaviour-neutral accessor
  for the arm above).

Gates on the merged tree: unit 2166/2166; integration-split 107/107 (2 design skips);
hd's RemoteGuards death tests still abort the unwrapped paths by name; PrimitiveRestart
7/7; the two Magma named-blit cases render. CONTRACT-P5C sections 3, 5.4.
2026-09-17 06:57:16 -04:00
swung0x48 a7e55ee62a [MG_Pipe, MG_Remote, MG_Backend, MG_Impl, MG_IntegrationTest] (Disaggregated): P5c ct - the applier_reset and object_death control records
Two appended wire records replace the two cross-role control bypasses:
applier_reset (opcode 77, MGPApplierReset{Uint64 ContextSerial}, kScreen) is emitted by
the GL thread at the FreshlyPrimed make-current edge, before the client-side resets, so
the record's barrier orders the server's MGPipeApplierReset against every verb that
follows; a direct MGPipeApplierReset() from a non-apply thread with a live session is
Fatal{RoleViolation, "g_applier"} (MGPipeApply.cpp carries the layer-2 guard; the
apply-thread and no-session bring-up shapes keep the direct call verbatim).
object_death (opcode 78, reuses MGPipeHandleOnly, kCtxObject) is the framebuffer
family's first wire delete opcode: the client thread resolves the dying object's handle
in its OWN allocator, emits nothing for a handle the server never saw, and EmitAndWaits
otherwise - the wait preserving the death's ordering against in-flight records that
name the handle, the only property the blocking mailbox hop provided. The sink releases
per-kind twins through a handle-keyed ReleaseTwinByHandle (seven kinds, SamplerViewCso's
idempotent second path kept); a null arriving handle is
Fatal{ProtocolCorruption, "ObjectDeath.Handle"}. A documented NoSession fallback arm
delivers a death to a server-only fixture's loop; monolith keeps the mailbox hop and
the FreshlyPrimed direct call character for character.

Evidence: gen_pipe --check/--self-test and gen_pipe_field_ownership --check/--self-test
green; unit 2155/2155; integration-split 111/111 (107 plus four new CtWireScenario
entries, all genuinely run, each with its own log path and an EXPECT_EXIT death case);
red-once - shorting the emission to the direct call turns the four Ct cases red with
Fatal{RoleViolation, "g_applier"} by name, then restores green verbatim.
CONTRACT-P5C sections 1, 5.1-5.2, 7.
2026-09-17 06:08:54 -04:00
swung0x48 7f5bdd3aa5 [MG_Backend, MG_Remote, MG_Impl, MG_State] (Disaggregated): P5c hd - sinks and twins resolve by the handle the record carried
A split-only verb-handle workspace in MGPipeApplierState (written by the sinks before
dispatch, read by the backend within the same verb) carries the record's handles to the
backend entries whose shared function-table signatures cannot grow them without moving
G1. OnBlit resolves ReadFbo/DrawFbo through the FBO twin table by handle (the named arm
of BlitFramebuffer, a loud refusal when the backend does not consume it) and the split
path's ScopedBlitBindings rebinding is deleted; CopyTex resolves MGPCopyFromFramebuffer::Dst;
the mip descriptor check resolves MGPMipPlan::Res; the indirect families resolve their
buffer handles from the records and read the bytes from the server staged shadow with
RequireStagedCoverage. EnsureBufferResourceForHandle answers HasDefinedContent from
Desc.HasDefinedContent OR the staged coverage set (the streaming idiom defines content
through subdata with no new descriptor). The minting GetOrCreate(StatePtr), HandleOf and
the death switch's lifetime-id arms take Fatal{RoleViolation, MGPipeSlots} from the apply
thread, as do the three MGPipeSlots() entry points; the frontend BufferObject legacy
accessors take Fatal{RoleViolation, buffer-legacy-arm}; Magma's four caps reads go to the
server's own backend and the client-mirror fallback arm is a named refusal.

Evidence: unit 2156/2156 (incl. 9 new RemoteF1 + 10 new RemoteGuards death tests pinning
the four Fatal names); monolith smoke green; six production mutations each turned their
named test red and were restored; c1f_redcheck M5 RED then RESTORED GREEN. The mip
descriptor check overlaps tx and is coordinated at the merge (tx's sync rekey wins the
sync body, this handle resolution wins the identity check). CONTRACT-P5C section 3.
2026-09-17 04:55:50 -04:00
swung0x48 1eeb4740ca Merge branch 'p5c-ev' into feat/disaggregated (P5c ev: SEG_EVENT reverse channel) 2026-09-17 03:55:46 -04:00
swung0x48 930ad0193f [MG_Remote, MG_Impl, MG_Backend] (Disaggregated): P5c ev - SEG_EVENT is the only reverse channel
The three reverse MGPipeCallbacks entries become the SERVER session's producer callbacks
(Reserve + fill the head + copy the payload inline + PublishEvents; the host pointer never
reaches the wire), installed at Accept and uninstalled at Close, a second installation
over a claimed entry being Fatal{RoleViolation, callback-double-install}. Producers wired:
buffer writeback (the mapped bytes are copied into the record's inline tail instead of a
raw pointer in MGPBlobRef::Offset), GPU-written (Magma's three direct MarkGpuWritten
bypasses are routed through the callback), surface-changed (the backend posts
MGPSurfaceInfo; the client consumer replays the allocate/format writes against
pDefaultFramebufferInfo on the GL thread, where R3's ownership always was), and
kEventGlError = 4 for PipeInputs::RecordError (ordering stays P9's).
PipeInputs::InvalidateCompileEnv's forward is deleted with an active transport - R-12's
caps re-publication already does its job. The consumer's monolith guard is replaced by
the three segment arms (kSegEvent resolves through the session's SegmentTable;
kMGHostSpanSegNone is monolith-only and Fatal{ProtocolCorruption} on the wire; anything
else the same), and DrainEventRing calls the client consumers BY NAME, never through the
global table. Overflow is Fatal{EventRingOverflow} - P5c's events are lossless, P9 owns
the drop policy. Monolith arms keep the pre-P5c expressions character for character.

Evidence: unit 2139/2139 (incl. the new kEventGlError round-trip), integration-split
107/107, monolith GPU subset 24/24; negative control executed - a writeback blobref
reverted to the raw-pointer shape turns DirectGLES.Split.AtomicCounterScenario.
SubDataAfterDispatchSurvivesAnImmediateReadback red with Fatal{ProtocolCorruption,
OnBufferWriteback.Seg}. CONTRACT-P5C sections 1, 4.
2026-09-17 03:55:30 -04:00
swung0x48 4b54a6f902 [MG_Remote, MG_Backend] (Disaggregated): P5c tx - the server's texture staged shadow
StagedTextureStore (MG_Remote/Server/StagedTextureStore.h), the texture twin of R-11's
StagedShadowStore: keyed by the wire handle (a twin-address key would force glGenTextures
at adopt time), coverage = the whole staged run per (uploadTarget, level), defined-ness
tracked from the respecify hook so sparse chains keep their holes. ApplyTextureUpload
adopts the staged bytes at the last instant they are alive (rule C) through three new
disaggregated-only MGPipeResourceOps members; SyncMipmapsToBackend's four arms read the
store and the descriptor instead of the client's MipmapStorage (texels, extent, target,
defined-ness, dirty); Magma's GenerateMipmap marks the server shadow Defined+GpuDirty
instead of writing the client's level storage (T5). Monolith arms reproduce the pre-tx
expressions character for character behind the same macro discipline as P4a.

Evidence: unit 2147/2147 incl. two named-Fatal death tests and the copies/no-copies
difference suite; DirectGLES.Split 104/104 on WSL GPU; red-once - reverting the adoption
to pointer-dropping turns exactly StagedTextureProductionTest red; the two monolith lane
failures reproduce on the base commit (DirectVulkan.IterationRPProgram203Scenario,
DirectVulkan.F1WireScenario.GenerateMipmapPackedFloatPixels). CONTRACT-P5C section 2.
2026-09-17 03:55:13 -04:00
swung0x48 851bc70c1d [MG_Remote] (Disaggregated): CONTRACT-P5C - the wire contract for zeroing the inproc split's 59 direct cross-role memory accesses (P5c package c0c)
Texture staged shadow ownership and exact per-level coverage (tx); SEG_EVENT blobref convention with Seg = kSegEvent plus the kEventGlError kind, producer ownership and the consumer segment arm that replaces the monolith guard (ev); handle-keyed sink and twin resolution with MGPipeSlots() ruled a client-only surface (hd); the applier_reset (77) and object_death (78) control records (ct); set_context_values (79) and the residual-value field table retiring every value-class BARRIER_PULLED row (rv); the two Fatal{RoleViolation} guard layers with InBarrierWait wired rather than deleted (gt); FieldOwnership.def and Table 3 amendments; the six E-P5c exit gates.
2026-09-17 01:34:17 -04:00
82 changed files with 6920 additions and 632 deletions
+116 -1
View File
@@ -1,4 +1,4 @@
name: Test
name: Test
on:
push:
@@ -1116,6 +1116,121 @@ jobs:
path: /tmp/core.*
if-no-files-found: ignore
# P5c gt (CONTRACT-P5C §6): the strict twin of integration-split. The role guards (the two
# layers of Fatal{RoleViolation, ...}) are COMPILED into every split build - there is no
# knob to arm them - so "guards armed" below means MOBILEGL_IPC_STRICT_ERRORS=1, the knob
# that promotes a BARRIER-PULLED residual read from counted debt to a named abort.
#
# TWO ASSERTIONS, NOT ONE, because the two halves of "strict is armed" are different
# statements:
#
# * the unit label must stay GREEN under it. A unit case that newly aborts under strict
# is a value-class read that crept back in (P5c rv's exit line is value-class = 0), and
# this step is what says so. FieldOwnershipTest owns the strict arms' behaviour cases;
#
# * the integration-split scenarios must all ABORT under it, BY DESIGN: the remaining
# residual pulls are the pinned object-class rows (GetFramebufferBindingSlot & co.,
# P3b/P4b/P7's), every drawing scenario reads one, and strict turns the first read into
# Fatal{UnmigratedPipeInput, ...} [BARRIER-PULLED, MOBILEGL_IPC_STRICT_ERRORS=1, ...].
# A lane that "passed" a scenario here would mean strict never armed - the same
# two-state shape as the E1/E3(a) negative controls, so the step asserts the abort AND
# greps the entry's private split-log for the strict marker. This half flips meaning
# when the object-class rows retire (P7): the scenarios then PASS under strict and the
# step is rewritten as an ordinary green lane.
integration-split-strict:
runs-on: ubuntu-latest
timeout-minutes: 60
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 green half: no unit case may pull harder under strict. This includes the
# RemoteGuards suite (the layer-1/layer-2 Fatal drives) and FieldOwnershipTest's strict
# arms, so the guards are provably armed in the lane that gates on them.
- name: Unit tests on the split runtime under MOBILEGL_IPC_STRICT_ERRORS=1
working-directory: build-split
env:
MOBILEGL_ITEST_REQUIRE_GPU: "1"
MOBILEGL_IPC_STRICT_ERRORS: "1"
run: ctest --output-on-failure -L unit --no-tests=error -j "$(nproc)"
# The expected-red half: every integration-split entry aborts on its first BARRIER-PULLED
# read under strict. The run is EXPECTED to fail; what the step gates on is that the
# failure is the strict Fatal and nothing else. A scenario that PASSED would mean strict
# never armed, and one whose private log lacks the marker failed for another reason.
- name: Integration-split aborts under strict with the strict marker
working-directory: build-split
env:
MOBILEGL_ITEST_REQUIRE_GPU: "1"
MOBILEGL_IPC_STRICT_ERRORS: "1"
MOBILEGL_TRANSPORT: "inproc"
run: |
ulimit -c unlimited
rc=0
ctest -L integration-split --no-tests=error -j 4 > "${RUNNER_TEMP}/strict-split.txt" 2>&1 || rc=$?
cat "${RUNNER_TEMP}/strict-split.txt" | tail -5
if [ "${rc}" -eq 0 ]; then
echo "::error::integration-split under MOBILEGL_IPC_STRICT_ERRORS=1 went GREEN - the object-class residual pulls (P3b/P4b/P7) are still pinned, so strict must abort every drawing scenario. If the object-class rows have just retired, rewrite this step as the green lane it then becomes."
exit 1
fi
failed=$(grep -cE '^ *[0-9]+ - .* \(.*(Failed|Subprocess aborted).*\)' "${RUNNER_TEMP}/strict-split.txt" || true)
# Every entry that RAN (did not skip) must have failed; entries skipped by a missing
# GPU or an unmet pre-flight are reported, not counted.
ran=$(grep -cE 'tests passed, [0-9]+ tests failed out of [0-9]+' "${RUNNER_TEMP}/strict-split.txt" || true)
echo "strict run: rc=${rc}"
# The strict marker, from the split entries' own private logs: the run's red must be
# the strict Fatal and not a bring-up defect.
marker='BARRIER-PULLED, MOBILEGL_IPC_STRICT_ERRORS=1'
hits=$(grep -rl "${marker}" MobileGL/MG_IntegrationTest/split-logs/ 2>/dev/null | wc -l)
if [ "${hits}" -lt 1 ]; then
echo "::error::no split entry's private log carries the strict marker '${marker}' - the lane went red without the strict Fatal firing, which is a defect, not the control"
exit 1
fi
echo "integration-split under strict is red by design; ${hits} private log(s) carry the strict marker"
- name: Upload strict lane logs
if: always()
uses: actions/upload-artifact@v7
with:
name: integration-split-strict-logs
path: |
build-split/MobileGL/MG_IntegrationTest/*.log*
build-split/MobileGL/MG_IntegrationTest/split-logs/*.log
if-no-files-found: warn
# 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
File diff suppressed because it is too large Load Diff
+591 -51
View File
@@ -20,7 +20,12 @@
// 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>
#include <MG_Remote/Server/StagedTextureStore.h>
#include <MG_Remote/Server/ServerLoop.h>
// P5c (ct): object_death's producer (CONTRACT-P5C.md §5.2) - the death notice's split arm
// emits the record through the client's emit helper instead of hopping a stack struct to the
// apply thread.
#include <MG_Remote/Client/WireTables.h>
#endif
#include "Utils.h"
@@ -206,10 +211,34 @@ namespace MobileGL::MG_Backend::DirectGLES {
void OnFrontendStateObjectDestroyed(MG_Pipe::MGPipeKind kind, Uint64 lifetimeId) {
if (InProcessTeardown()) return;
#if MOBILEGL_BUILD_DISAGGREGATED
// Death notices have no framebuffer wire opcode. Keep the lifetime/slot valid
// until the context owner has destroyed its twin and updated its binding cache.
// P5c (ct), CONTRACT-P5C.md §5.2: with an active transport the death crosses AS A
// RECORD - object_death, the framebuffer family's first wire delete opcode. The GL
// thread resolves the dying object's handle in its OWN allocator inside
// EmitObjectDeathRecord: no handle means the server never saw the object and
// NOTHING crosses (which replaces the mailbox's unconditional delivery), and a
// handle means the record's EmitAndWait orders the death against in-flight verbs
// that name it - the one property the blocking RunOnApplyThread hop provided and
// the only one P5c keeps. The sink (ServerVerbSink::OnObjectDeath) releases the
// kind's twin table by handle on the apply thread, so neither a lifetime-id probe
// nor the client's allocator is touched from there any more.
if (MG_Config::Transport != MG_Config::TransportMode::Monolith &&
!MG_Remote::Server::ServerLoop::OnApplyThread()) {
if (MG_Remote::Client::EmitObjectDeathRecord(kind, lifetimeId) !=
MG_Remote::Client::ObjectDeathEmit::NoSession) {
return;
}
// NoSession is the ONE shape the record cannot carry: a transport configured
// with no client session at all - a ServerLoop fixture driving a server role
// with no client, never a real split (there a session exists whenever the
// server does). The server loop IS there, so the death takes the delivery
// that predates the record, kept VERBATIM for exactly this arm: a stack
// struct hopped to the apply thread, which runs the switch below. NoHandle
// does NOT land here - a handle that never existed has no twin to kill (§5.2)
// - and a loop that is not RUNNING (teardown, pre-Start) has no thread to hop
// to; the twin dies with the server either way.
if (!MG_Remote::Server::ServerLoopInstance().Running()) {
return;
}
struct Death { MG_Pipe::MGPipeKind kind; Uint64 lifetimeId; } death{kind, lifetimeId};
MG_Remote::Server::ServerLoopInstance().RunOnApplyThread(
+[](void* user) -> MobileGLResult {
@@ -219,6 +248,12 @@ namespace MobileGL::MG_Backend::DirectGLES {
}, &death);
return;
}
// P5c merge coordination: the record arm above carries every death a real split
// sees; what still lands HERE through the mailbox is the NoSession server-only
// fixture arm, whose DestroyByLifetimeId probes the client allocator from the
// apply thread. Those probes ride inside the G6 scope (CONTRACT-P5C §5.2, the
// amended ruling) - named debt that dies with the mailbox hop.
const MG_Pipe::MGPipeFrontendKeyedRegistryScope frontendKeyedRegistry;
#endif
switch (kind) {
case MG_Pipe::MGPipeKind::Texture:
@@ -289,6 +324,43 @@ namespace MobileGL::MG_Backend::DirectGLES {
};
} // namespace
#if MOBILEGL_BUILD_DISAGGREGATED
Bool ReleaseTwinsForWireObjectDeath(MG_Pipe::MGPipeHandle handle, MG_Pipe::MGPipeKind kind) {
// The handle-keyed twin of the notice switch above, and deliberately NOT that switch:
// the record carried the handle, so no lifetime id is probed and the client's
// allocator - a client-only surface under a transport (CONTRACT-P5C.md §3.1) - is
// never touched from the apply thread. Each arm names its kind's registry GLOBAL for
// the same spelling reason as the notice arms: ReleaseByHandle /
// ReleaseTwinByHandle is static and is answered by every table of the kind that
// exists, this global's own and any by-value copy a fixture or a context reset holds.
switch (kind) {
case MG_Pipe::MGPipeKind::Texture:
return TextureImpl::g_backendTextureObjects.ReleaseByHandle(handle);
case MG_Pipe::MGPipeKind::Framebuffer:
return FramebufferImpl::g_backendFramebufferObjects.ReleaseByHandle(handle);
case MG_Pipe::MGPipeKind::Renderbuffer:
return RenderbufferImpl::g_backendRenderbufferObjects.ReleaseByHandle(handle);
case MG_Pipe::MGPipeKind::SamplerCso:
return SamplerImpl::g_backendSamplerObjects.ReleaseByHandle(handle);
case MG_Pipe::MGPipeKind::ShaderCso:
return PrgramImpl::g_backendProgramObjects.ReleaseByHandle(handle);
case MG_Pipe::MGPipeKind::SamplerViewCso:
// The notice arm's REDUNDANT SECOND PATH, keyed by the view's handle the same
// way (CONTRACT-P5C.md §5.2): the client's delete_sampler_view may already have
// released the twin, in which case the generation check inside fails and this
// answers false. A false here is idempotency, never a leak - the view twin owns
// no driver id of its own.
return SamplerViewImpl::BackendSamplerViewTable::ReleaseTwinByHandle(handle);
case MG_Pipe::MGPipeKind::VertexElementsCso:
return VertexArrayImpl::g_backendVertexArrayObjects.ReleaseByHandle(handle);
default:
// Buffer's death crosses as resource_destroy (P3a), exactly as the notice
// switch's default arm rules; every other kind has no twin table here.
return false;
}
}
#endif
// The one sentence that decides the arm, written once so that a test can drive every
// combination of the two knobs and so that bring-up and first-use cannot disagree.
EsprytSlotArmVerdict ClassifyEsprytSlotArm(Bool subsystemBitSet, Bool legacyMemosEnabled) {
@@ -2508,6 +2580,139 @@ namespace MobileGL::MG_Backend::DirectGLES {
return result;
}
#if MOBILEGL_BUILD_DISAGGREGATED
// ---- P5c (tx): the TEXTURE half of the resource family, staged server-side --------
//
// The buffer half's R-11 pattern (ServerStaged() above), for texture levels: the
// staged bytes of resource_subdata's texture half are adopted into the server's
// StagedTextureStore AT APPLY TIME, because `bytes` names SEG_STAGE and is dead the
// moment the record retires (rule C). The store, its ownership and its coverage
// rules are documented in MG_Remote/Server/StagedTextureStore.h; these are only the
// three hook bodies. All three are no-ops in monolith (CopiesIntoServerStorage()
// false), which is what keeps the monolith expression character for character.
//
// NOTHING here mints or reads a texture twin: the store is keyed by the wire handle
// the record carried (StagedTextureStore.h explains why not the twin address), so
// adoption needs no GL call and no frontend object.
// GetUploadTargets() answered from the descriptor's Target: one static list per
// target, matching the frontend classes' own lists member for member
// (TextureObject*.h / TextureObjectStubs.h: a cube is six faces, a cube array is
// the single CubeMapArray target, everything else its own one).
const Vector<TextureUploadTarget>& StagedUploadTargetsForPipeTarget(Uint8 pipeResourceTarget) {
static const Vector<TextureUploadTarget> kUnknown{};
static const Vector<TextureUploadTarget> kTex1D{TextureUploadTarget::Texture1D};
static const Vector<TextureUploadTarget> kTex2D{TextureUploadTarget::Texture2D};
static const Vector<TextureUploadTarget> kTex3D{TextureUploadTarget::Texture3D};
static const Vector<TextureUploadTarget> kTex1DArray{TextureUploadTarget::Texture1DArray};
static const Vector<TextureUploadTarget> kTex2DArray{TextureUploadTarget::Texture2DArray};
static const Vector<TextureUploadTarget> kTexCube{
TextureUploadTarget::CubeMapPositiveX, TextureUploadTarget::CubeMapNegativeX,
TextureUploadTarget::CubeMapPositiveY, TextureUploadTarget::CubeMapNegativeY,
TextureUploadTarget::CubeMapPositiveZ, TextureUploadTarget::CubeMapNegativeZ};
static const Vector<TextureUploadTarget> kTexCubeArray{TextureUploadTarget::CubeMapArray};
static const Vector<TextureUploadTarget> kTex2DMS{TextureUploadTarget::Texture2DMultisample};
static const Vector<TextureUploadTarget> kTex2DMSArray{TextureUploadTarget::Texture2DMultisampleArray};
static const Vector<TextureUploadTarget> kTexRect{TextureUploadTarget::TextureRectangle};
static const Vector<TextureUploadTarget> kTexBuffer{TextureUploadTarget::TextureBuffer};
switch (static_cast<MG_Pipe::MGPipeResourceTarget>(pipeResourceTarget)) {
case MG_Pipe::MGPipeResourceTarget::Tex1D: return kTex1D;
case MG_Pipe::MGPipeResourceTarget::Tex2D: return kTex2D;
case MG_Pipe::MGPipeResourceTarget::Tex3D: return kTex3D;
case MG_Pipe::MGPipeResourceTarget::Tex1DArray: return kTex1DArray;
case MG_Pipe::MGPipeResourceTarget::Tex2DArray: return kTex2DArray;
case MG_Pipe::MGPipeResourceTarget::TexCube: return kTexCube;
case MG_Pipe::MGPipeResourceTarget::TexCubeArray: return kTexCubeArray;
case MG_Pipe::MGPipeResourceTarget::Tex2DMS: return kTex2DMS;
case MG_Pipe::MGPipeResourceTarget::Tex2DMSArray: return kTex2DMSArray;
case MG_Pipe::MGPipeResourceTarget::TexRect: return kTexRect;
case MG_Pipe::MGPipeResourceTarget::TexBuffer: return kTexBuffer;
default: return kUnknown;
}
}
// The inverse of MG_Pipe::MGPipeResourceTargetForTextureTarget, for the sync's
// target reads (ConvertTextureTargetToBackendGLEnum and MapToBackendTextureTarget
// both want the frontend enum).
TextureTarget StagedTextureTargetForPipeTarget(Uint8 pipeResourceTarget) {
switch (static_cast<MG_Pipe::MGPipeResourceTarget>(pipeResourceTarget)) {
case MG_Pipe::MGPipeResourceTarget::Tex1D: return TextureTarget::Texture1D;
case MG_Pipe::MGPipeResourceTarget::Tex2D: return TextureTarget::Texture2D;
case MG_Pipe::MGPipeResourceTarget::Tex3D: return TextureTarget::Texture3D;
case MG_Pipe::MGPipeResourceTarget::Tex1DArray: return TextureTarget::Texture1DArray;
case MG_Pipe::MGPipeResourceTarget::Tex2DArray: return TextureTarget::Texture2DArray;
case MG_Pipe::MGPipeResourceTarget::TexCube: return TextureTarget::TextureCubeMap;
case MG_Pipe::MGPipeResourceTarget::TexCubeArray: return TextureTarget::TextureCubeMapArray;
case MG_Pipe::MGPipeResourceTarget::Tex2DMS: return TextureTarget::Texture2DMultisample;
case MG_Pipe::MGPipeResourceTarget::Tex2DMSArray: return TextureTarget::Texture2DMultisampleArray;
case MG_Pipe::MGPipeResourceTarget::TexRect: return TextureTarget::TextureRectangle;
case MG_Pipe::MGPipeResourceTarget::TexBuffer: return TextureTarget::TextureBuffer;
default: return TextureTarget::Unknown;
}
}
void Ops_H_TextureSubData(MG_Pipe::MGPipeHandle res, const MG_Pipe::MGPSubData& record,
const void* bytes, const MG_Pipe::MGPSubRegion* regions) {
// The region set is the upload planner's shape and stays in the applier's
// pending set; the store's coverage is the staged run itself
// (StagedTextureStore.h's coverage ruling).
(void)regions;
auto& store = MG_Remote::Server::ServerStagedTexture();
if (!store.CopiesIntoServerStorage()) return;
// The applier's gate has already faulted every shape that reaches here without
// bytes, and under split the codec declared the run's length (Blob.Size) -
// TextureEmit.h:1285's "the bytes this record declares ARE the level shadow".
if (bytes == nullptr || record.Blob.Size == 0) return;
const auto* stored = PipeTextureRecordForHandle(res);
if (stored == nullptr) return;
const IntVec3 extent = MG_Remote::Server::StagedTextureMipExtent(
stored->Desc.Target, stored->Desc.Width, stored->Desc.Height, stored->Desc.Depth,
static_cast<Uint32>(record.Level));
store.Adopt(MG_Remote::Server::StagedTextureStore::KeyForHandle(res),
MG_Pipe::MGPipeSubDataUploadTargetOf(record.Target), record.Level, extent,
bytes, static_cast<SizeT>(record.Blob.Size));
}
void Ops_H_TextureRespecify(MG_Pipe::MGPipeHandle res, const MG_Pipe::MGPResourceDesc& desc,
const MG_Pipe::MGPRespecifiedLevel* level) {
auto& store = MG_Remote::Server::ServerStagedTexture();
if (!store.CopiesIntoServerStorage()) return;
const Uint64 key = MG_Remote::Server::StagedTextureStore::KeyForHandle(res);
if (level != nullptr) {
// ONE glTexImage*D redefined one level: it exists from here on, at the
// derived extent (§1). NoteLevelDefined keeps a same-extent level's bytes.
store.NoteLevelDefined(
key, MG_Pipe::MGPipeSubDataUploadTargetOf(level->UploadTarget), level->Level,
MG_Remote::Server::StagedTextureMipExtent(desc.Target, desc.Width, desc.Height,
desc.Depth, level->Level));
return;
}
// A whole-resource redefinition: every level's old coordinate system is gone.
// glTexStorage* then defines the WHOLE chain at once (GL 4.6 core 8.19 - all six
// cube faces included), so an immutable descriptor re-marks every level of every
// upload target; a mutable whole-resource respecify (a texture view) defines
// nothing here and the store simply forgets the old levels.
store.ResetLevels(key);
if (desc.Immutable == 0 || desc.Levels == 0) return;
for (const auto& uploadTarget : StagedUploadTargetsForPipeTarget(desc.Target)) {
for (Uint32 levelIndex = 0; levelIndex < desc.Levels; ++levelIndex) {
store.NoteLevelDefined(
key, static_cast<Uint16>(uploadTarget), static_cast<Uint16>(levelIndex),
MG_Remote::Server::StagedTextureMipExtent(desc.Target, desc.Width, desc.Height,
desc.Depth, levelIndex));
}
}
}
void Ops_H_TextureDestroy(MG_Pipe::MGPipeHandle res) {
// Deliberately NOT gated on CopiesIntoServerStorage(): Drop's own m_any gate
// makes the monolith call one acquire load, and an unconditional drop cannot
// strand a key the latch state was misread for.
MG_Remote::Server::ServerStagedTexture().Drop(
MG_Remote::Server::StagedTextureStore::KeyForHandle(res));
}
#endif // MOBILEGL_BUILD_DISAGGREGATED
const MG_Pipe::MGPipeResourceOps g_glesResourceOps = {
.Create = Ops_H_Create,
.Respecify = Ops_H_RespecifyTracked,
@@ -2518,6 +2723,11 @@ namespace MobileGL::MG_Backend::DirectGLES {
.Destroy = Ops_H_DestroyTracked,
.MapPersistent = Ops_H_MapPersistentTracked,
.UnmapPersistent = Ops_H_UnmapPersistent,
#if MOBILEGL_BUILD_DISAGGREGATED
.TextureSubData = Ops_H_TextureSubData,
.TextureRespecify = Ops_H_TextureRespecify,
.TextureDestroy = Ops_H_TextureDestroy,
#endif
};
#endif // MOBILEGL_PIPE_PUSH
@@ -2702,6 +2912,13 @@ namespace MobileGL::MG_Backend::DirectGLES {
return twin ? twin->get() : nullptr;
}
#if MOBILEGL_BUILD_DISAGGREGATED
void RequireStagedCoverage(GLESBufferResource& resource, const Uint8* hostBase, SizeT start,
SizeT end, const char* site) {
ServerStaged().RequireCoverage(&resource, hostBase, start, end, site);
}
#endif
MG_Pipe::MGPipeHandle HandleOfBuffer(const MG_State::GLState::BufferObject* bufferObject) {
if (bufferObject == nullptr) return MG_Pipe::kMGPipeNullHandle;
// Through the table's own single-entry front memo rather than straight into
@@ -2712,6 +2929,14 @@ namespace MobileGL::MG_Backend::DirectGLES {
// allocator probe on a miss - and remembers the answer, which the minting overload
// was previously the only writer of. A null answer is deliberately never memoised
// (see the comment at HandleOf).
#if MOBILEGL_BUILD_DISAGGREGATED
// P5c merge coordination (CONTRACT-P5C §3.1's named exemption): every caller of
// this function is a site whose handle-carrying records (set_shader_buffers /
// set_stream_output_targets) the client does not emit until P4b, so the probe
// below runs inside the scoped exemption. The scope, not a silent guard removal,
// is what keeps the debt named and greppable.
const MG_Pipe::MGPipeReverseAnnouncementScope reverseAnnouncement;
#endif
return g_backendBufferResources.HandleOf(bufferObject);
}
@@ -2812,6 +3037,12 @@ namespace MobileGL::MG_Backend::DirectGLES {
// 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();
#if MOBILEGL_BUILD_DISAGGREGATED
// tx's texture shadows die for the same reason, keyed by handle rather than address
// but with the same recycled-identity failure mode: a new context's allocator may
// hand out a {slot, gen} the old one's store still answers for.
MG_Remote::Server::ServerStagedTexture().DropAll();
#endif
#endif
}
@@ -3100,7 +3331,17 @@ namespace MobileGL::MG_Backend::DirectGLES {
// D-N keeps this call here for P3a. It can queue ranges and move the record, so
// everything below is read AFTER it.
#if MOBILEGL_BUILD_DISAGGREGATED
// P5c (hd, CONTRACT-P5C §3.8): under an active transport the frontend accessor is a
// layer-1 surface ("buffer-legacy-arm") and the client's own pre-verb
// persistent-map push is the only producer; the call is skipped outright. Under
// monolith D-N's placement stands.
if (bufferObject && MG_Config::Transport == MG_Config::TransportMode::Monolith) {
bufferObject->SyncPersistentMappedRange();
}
#else
if (bufferObject) bufferObject->SyncPersistentMappedRange();
#endif
const auto* record = ResourceRecordOf(res);
const SizeT size = record != nullptr ? static_cast<SizeT>(record->Desc.Width) : 0;
@@ -3128,24 +3369,28 @@ namespace MobileGL::MG_Backend::DirectGLES {
// and its bytes are read through persistentPtr.
if (hostBase != nullptr) resource->hostBytes = hostBase;
// "DOES THE SHADOW THIS PATH IS ABOUT TO UPLOAD HOLD MEANINGFUL BYTES?" - and it has
// to be asked of the SAME thing the bytes come from, which is why it is not
// record->Desc.HasDefinedContent. The descriptor states what was true at the last
// resource_respecify and NOTHING refreshes it afterwards: resource_subdata,
// resource_flush_range, buffer_subdata_resident and OnGpuWritten all define content
// (BufferObject.cpp:85, :101, :127, :365, :441) without re-emitting a descriptor,
// and re-emitting one per glBufferSubData would be new wire traffic D-J forbids. So
// after the ordinary glBufferData(NULL) + glBufferSubData idiom the descriptor still
// says "undefined", this full re-upload passed nullptr, RespecifyStorageWith
// CLEARED the queued ranges and stamped syncedChangeSerial - i.e. an empty store
// declared current, with the application's bytes dropped and nothing saying so.
// The legacy arm pairs bufferObject.MappedData() with bufferObject.HasDefinedContent()
// (RespecifyStorageNow) and this arm pairs the same two, so the source of the bytes
// and the statement about them can never disagree. Declared, like C-1's IsMapped():
// it is a frontend read this function keeps for P3a and it retires the moment the
// client publishes a live content flag beside the descriptor (P5/P8). With no
// frontend object (the handle-only drains) the descriptor is all there is.
// to be asked of the SAME thing the bytes come from. The legacy arm pairs
// bufferObject.MappedData() with bufferObject.HasDefinedContent() (RespecifyStorageNow)
// and this arm pairs the same two, so the source of the bytes and the statement about
// them can never disagree.
//
// P5c (hd, CONTRACT-P5C §3.6 / B1): with an active transport the answer is the
// DESCRIPTOR's bit - which the client publishes on ResourceCreate/Respecify - OR the
// staged coverage the content records behind it delivered. The coverage half is what
// keeps the answer equal to the frontend flag's in the one case the descriptor alone
// cannot see: an ORPHANING respecify (descriptor clear) followed by glBufferSubData,
// which defines content without a new descriptor - the bytes crossed as
// resource_subdata and the staged store's coverage is exactly "content defined since
// the last orphan". With no coverage and a clear bit the store is undefined by the
// application's own declaration and the upload stays a pure NULL reallocation.
const Bool shadowHasContent =
bufferObject ? bufferObject->HasDefinedContent() : (record->Desc.HasDefinedContent != 0);
#if MOBILEGL_BUILD_DISAGGREGATED
MG_Config::Transport != MG_Config::TransportMode::Monolith
? (record->Desc.HasDefinedContent != 0 ||
ServerStaged().CoveredRunCount(resource) != 0)
:
#endif
(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
@@ -4293,6 +4538,11 @@ namespace MobileGL::MG_Backend::DirectGLES {
// MGPipeSlots().FindByLifetimeId, which is a hash lookup. HandleOf answers
// identically - the same allocator probe on a miss - and remembers the answer; a
// null answer is deliberately never memoised (SlotTables.h, at HandleOf).
#if MOBILEGL_BUILD_DISAGGREGATED
// P5c (G6, CONTRACT-P5C §5.4): frontend-keyed twin resolution, named debt inside
// the scope - P3b/P4b rekeys the sampler-view registry onto handles.
const MG_Pipe::MGPipeFrontendKeyedRegistryScope frontendKeyedRegistry;
#endif
return g_backendSamplerViews.HandleOf(textureObject);
}
} // namespace SamplerViewImpl
@@ -5624,8 +5874,16 @@ namespace MobileGL::MG_Backend::DirectGLES {
// because that is what this arm consumes.
Bool markedRemintPull = false;
const MG_Pipe::MGPipeHandle rearmRes =
TextureResourceSubsystemEnabled() ? g_backendTextureObjects.HandleOf(stateTextureObject.get())
: MG_Pipe::kMGPipeNullHandle;
TextureResourceSubsystemEnabled()
? [&]() {
#if MOBILEGL_BUILD_DISAGGREGATED
// P5c (G6, CONTRACT-P5C §5.4): frontend-keyed resolution, named
// debt inside the scope - P3b/P4b rekeys the registry.
const MG_Pipe::MGPipeFrontendKeyedRegistryScope frontendKeyedRegistry;
#endif
return g_backendTextureObjects.HandleOf(stateTextureObject.get());
}()
: MG_Pipe::kMGPipeNullHandle;
const Uint32 rearmResourceTarget =
MG_Pipe::MGPipeResourceTargetForTextureTarget(stateTextureObject->GetTarget());
if (TextureResourceSubsystemEnabled() && MG_Pipe::MGPipeHandleIsNull(rearmRes)) {
@@ -5634,6 +5892,41 @@ namespace MobileGL::MG_Backend::DirectGLES {
"pending set - they would be allocated empty",
stateTextureObject->GetExternalIndex());
}
#endif
#if MOBILEGL_BUILD_DISAGGREGATED
// P5c (gt): under an active transport the replay loop below reaches the layer-1
// texture guard (MarkStorageDirty on a frontend object is Fatal{RoleViolation,
// "texture-legacy-arm"}) BEFORE the N-4 marker it owns - so the marker is hoisted
// here, ahead of the first guarded contact, with its semantics unchanged: raised
// only when a level would actually be replayed. The predicate is answered by the
// server's own staged-texture store rather than the frontend's extent walk: a
// Defined level has a non-zero extent and bytes on the frontend (the two conditions
// the loop tests), and an undefined one reads {0,0,0} and is skipped. A texture with
// no applier record (rearmRes null, the MGLOG_E_ONCE arm above) falls through to the
// guard, which names the same violation one level down.
if (MG_Config::Transport != MG_Config::TransportMode::Monolith &&
!MG_Pipe::MGPipeHandleIsNull(rearmRes)) {
const auto* rearmRecord = PipeTextureRecordForHandle(rearmRes);
if (rearmRecord != nullptr) {
auto& rearmStore = MG_Remote::Server::ServerStagedTexture();
const Uint64 rearmKey = MG_Remote::Server::StagedTextureStore::KeyForHandle(rearmRes);
Bool anyLevelWouldReplay = false;
for (const auto& uploadTarget :
BufferImpl::StagedUploadTargetsForPipeTarget(rearmRecord->Desc.Target)) {
for (Uint32 level = 0; level < rearmRecord->Desc.Levels; ++level) {
if (rearmStore.IsLevelDefined(rearmKey, static_cast<Uint16>(uploadTarget),
static_cast<Uint16>(level))) {
anyLevelWouldReplay = true;
break;
}
}
if (anyLevelWouldReplay) break;
}
if (anyLevelWouldReplay) {
MG_Pipe::MGPipeUnmigratedEmulation("texture-remint-pull");
}
}
}
#endif
if (auto* mipmapObject = MG_State::GLState::AsMipmapTexture(stateTextureObject.get())) {
const auto levelCount = mipmapObject->GetMipmapLevelCount();
@@ -6586,7 +6879,91 @@ namespace MobileGL::MG_Backend::DirectGLES {
// pre-P4a expression exactly when MOBILEGL_PIPE_PUSH is off, so the pull build's
// preprocessed text, and therefore its object code, is unchanged. Both are #undef'd
// immediately after the function.
#if MOBILEGL_PIPE_PUSH
#if MOBILEGL_BUILD_DISAGGREGATED
// P5c (tx): THE READS THE FOUR UPLOAD ARMS MAKE, re-sourced. With an active transport the
// apply thread may not name the client's TextureObjectMipmap at all (rule E), so on the
// handle arm:
//
// * the level TEXELS come from the server's staged-texture store, adopted at apply time
// (MGB_LEVEL_TEXELS - Fatal{StageSnapshotTooNarrow} when no record covered the level,
// which is the data-correctness refusal of the texture half);
// * the per-level EXTENT and DEFINED-NESS come from the same store (fed by the sub-data
// adoption and the respecify hook; {0,0,0} for a level nothing defined, which is exactly
// GetMipmapTexelSize's answer for one);
// * the level BYTE SIZE is the adopted run's length;
// * the texture TARGET and the UPLOAD-TARGET list come from the descriptor.
//
// Every macro keeps the P4a discipline: the non-disaggregated expansion is the original
// frontend read, character for character modulo one pair of parentheses, so the pull and
// push builds compile exactly what they compiled before tx, and every disaggregated arm
// falls back to the frontend read when there is no active transport (the legacy arm, and
// monolith). MGB_STAGED_TEXTURE_LIVE is the runtime discriminator; pushedStorage/pushedRes
// are the function's own locals. All are #undef'd with the rest after the function.
#define MGB_STAGED_TEXTURE_LIVE \
(pushedStorage != nullptr && MG_Remote::Server::ServerStagedTexture().CopiesIntoServerStorage())
#define MGB_TEXTURE_TARGET(obj) \
(MGB_STAGED_TEXTURE_LIVE ? BufferImpl::StagedTextureTargetForPipeTarget(pushedStorage->Desc.Target) \
: (obj)->GetTarget())
#define MGB_UPLOAD_TARGETS(obj) \
(MGB_STAGED_TEXTURE_LIVE ? BufferImpl::StagedUploadTargetsForPipeTarget(pushedStorage->Desc.Target) \
: (obj)->GetUploadTargets())
#define MGB_LEVEL_TEXEL_SIZE(obj, tgt, lvl) \
(MGB_STAGED_TEXTURE_LIVE \
? MG_Remote::Server::ServerStagedTexture().LevelExtentOrUndefined( \
MG_Remote::Server::StagedTextureStore::KeyForHandle(pushedRes), static_cast<Uint16>(tgt), \
static_cast<Uint16>(lvl)) \
: (obj)->GetMipmapTexelSize(tgt, lvl))
#define MGB_LEVEL_BYTE_SIZE(obj, tgt, lvl) \
(MGB_STAGED_TEXTURE_LIVE \
? MG_Remote::Server::ServerStagedTexture().LevelByteSize( \
MG_Remote::Server::StagedTextureStore::KeyForHandle(pushedRes), static_cast<Uint16>(tgt), \
static_cast<Uint16>(lvl)) \
: (obj)->GetMipmapByteSize(tgt, lvl))
#define MGB_LEVEL_TEXELS(obj, tgt, lvl, site) \
(MGB_STAGED_TEXTURE_LIVE \
? MG_Remote::Server::ServerStagedTexture().RequireLevelBytes( \
MG_Remote::Server::StagedTextureStore::KeyForHandle(pushedRes), static_cast<Uint16>(tgt), \
static_cast<Uint16>(lvl), site) \
: (obj)->MapMipmapData(tgt, lvl))
#else
#define MGB_TEXTURE_TARGET(obj) ((obj)->GetTarget())
#define MGB_UPLOAD_TARGETS(obj) ((obj)->GetUploadTargets())
#define MGB_LEVEL_TEXEL_SIZE(obj, tgt, lvl) ((obj)->GetMipmapTexelSize(tgt, lvl))
#define MGB_LEVEL_BYTE_SIZE(obj, tgt, lvl) ((obj)->GetMipmapByteSize(tgt, lvl))
#define MGB_LEVEL_TEXELS(obj, tgt, lvl, site) ((obj)->MapMipmapData(tgt, lvl))
#endif
#if MOBILEGL_BUILD_DISAGGREGATED
// P5c (tx): the disaggregated pair adds ONE term and ONE clear to the P4a shapes - the
// staged-texture store's GPU-dirty mark (T5: a level the GPU generated dirties the SERVER's
// shadow, and the pending set cannot see it). The mark is never set on Espryt today - its
// GenerateMipmap fills the levels on the driver - so the term is inert here and is the
// contract-shaped answer (§2.2's last row) rather than a hot-path cost: one m_any acquire
// load when the store is empty.
#define MGB_LEVEL_NEEDS_UPLOAD(obj, tgt, lvl) \
(pushedStorage != nullptr \
? (FindPipeTextureUpload(*pushedStorage, static_cast<Uint16>(tgt), static_cast<Uint16>(lvl)) != nullptr || \
MG_Remote::Server::ServerStagedTexture().IsLevelGpuDirty( \
MG_Remote::Server::StagedTextureStore::KeyForHandle(pushedRes), static_cast<Uint16>(tgt), \
static_cast<Uint16>(lvl))) \
: (obj)->IsStorageDirty(tgt, lvl))
// Re-resolves the record itself, so it is safe after any amount of driver work - and it
// invalidates any PendingUpload* taken earlier for THIS texture, which is why every such pointer
// is used and dropped inside one level's iteration.
#define MGB_LEVEL_UPLOAD_DONE(obj, tgt, lvl) \
do { \
if (pushedStorage != nullptr) { \
ConsumePipeTextureUpload(pushedRes, static_cast<Uint16>(tgt), static_cast<Uint16>(lvl)); \
if (MGB_STAGED_TEXTURE_LIVE) { \
MG_Remote::Server::ServerStagedTexture().MarkLevelGpuDirty( \
MG_Remote::Server::StagedTextureStore::KeyForHandle(pushedRes), static_cast<Uint16>(tgt), \
static_cast<Uint16>(lvl), false); \
} \
} else { \
(obj)->MarkStorageDirty(tgt, lvl, false); \
} \
} while (0)
#elif MOBILEGL_PIPE_PUSH
#define MGB_LEVEL_NEEDS_UPLOAD(obj, tgt, lvl) \
(pushedStorage != nullptr \
? FindPipeTextureUpload(*pushedStorage, static_cast<Uint16>(tgt), static_cast<Uint16>(lvl)) != nullptr \
@@ -6703,6 +7080,12 @@ namespace MobileGL::MG_Backend::DirectGLES {
const MG_Pipe::MGPipeResourceRecord* pushedStorage = nullptr;
MG_Pipe::MGPipeHandle pushedRes = MG_Pipe::kMGPipeNullHandle;
if (TextureResourceSubsystemEnabled()) {
#if MOBILEGL_BUILD_DISAGGREGATED
// P5c (G6, CONTRACT-P5C §5.4): the sync arrives holding the frontend object
// (the object-class rows) and resolves its handle by frontend identity -
// named debt inside the scope, P3b/P4b rekeys the registry onto handles.
const MG_Pipe::MGPipeFrontendKeyedRegistryScope frontendKeyedRegistry;
#endif
pushedRes = g_backendTextureObjects.HandleOf(stateTextureObject.get());
pushedStorage = PipeTextureRecordForHandle(pushedRes);
if (pushedStorage == nullptr) {
@@ -6783,8 +7166,8 @@ namespace MobileGL::MG_Backend::DirectGLES {
MGLOG_D("Syncing texture mipmaps with backend ID %u to backend for state ID %u", m_backendTextureId,
stateTextureObject->GetExternalIndex());
GLenum target = ConvertTextureTargetToBackendGLEnum(stateTextureObject->GetTarget());
auto targetInternal = stateTextureObject->GetTarget();
GLenum target = ConvertTextureTargetToBackendGLEnum(MGB_TEXTURE_TARGET(stateTextureObject));
auto targetInternal = MGB_TEXTURE_TARGET(stateTextureObject);
MGLOG_D(" Texture target for syncing is %s",
MG_Util::ConvertTextureTargetToString(targetInternal).c_str());
if (!IsSupportedTextureTarget(targetInternal)) {
@@ -6805,6 +7188,48 @@ namespace MobileGL::MG_Backend::DirectGLES {
// left the backend name with no levels whatsoever, so the level that WAS defined could
// never be sampled or read back. Sync whenever some level holds an image; the per-level
// loops below skip the degenerate ones individually.
#if MOBILEGL_BUILD_DISAGGREGATED
// P5c (gt, CONTRACT-P5C §6 layer 1): on the staged arm the same question is answered
// out of the SERVER's staged-texture store, never out of the frontend object - the
// store's Defined-ness (fed by the respecify hook and the sub-data adoption) IS "some
// level holds an image", and IsComplete()'s sampling half is redundant with it: a
// complete mipmap chain has a defined level 0, and the gate's whole job is to let an
// incomplete-but-partly-defined chain through. The one divergence is deliberate and
// stated: a chain whose EVERY level is 0x0 is complete-by-quirk on the frontend (the
// "0x0 in last level" relaxation, TextureObject.cpp) and undefined here - and syncing
// it would upload nothing either way, because every per-level loop below skips a
// {0,0,0} level individually. A BUFFER texture never has staged levels, so its gate
// is the descriptor's format - exactly what TextureObjectBase::IsComplete() reduces
// to for that storage kind.
if (MGB_STAGED_TEXTURE_LIVE) {
const auto& stagedDesc = pushedStorage->Desc;
Bool anyDefined = false;
if (static_cast<TextureStorageType>(stagedDesc.StorageKind) == TextureStorageType::Buffer) {
// A buffer texture has no staged levels; its gate is the descriptor's
// format, which is what TextureObjectBase::IsComplete() reduces to here.
anyDefined = static_cast<TextureInternalFormat>(stagedDesc.InternalFormat) !=
TextureInternalFormat::Unknown;
} else {
auto& stagedStore = MG_Remote::Server::ServerStagedTexture();
const Uint64 stagedKey = MG_Remote::Server::StagedTextureStore::KeyForHandle(pushedRes);
for (const auto& uploadTarget : BufferImpl::StagedUploadTargetsForPipeTarget(stagedDesc.Target)) {
for (Uint32 level = 0; level < stagedDesc.Levels; ++level) {
if (stagedStore.IsLevelDefined(stagedKey, static_cast<Uint16>(uploadTarget),
static_cast<Uint16>(level))) {
anyDefined = true;
break;
}
}
if (anyDefined) break;
}
}
if (!anyDefined) {
MGLOG_D("Texture object with ID: %u has no defined image level, skipping sync.",
stateTextureObject->GetExternalIndex());
return;
}
} else
#endif
if (!stateTextureObject->IsComplete() && !HasAnyDefinedMipmapLevel(stateTextureObject.get())) {
MGLOG_D("Texture object with ID: %u has no defined image level, skipping sync.",
stateTextureObject->GetExternalIndex());
@@ -6921,11 +7346,11 @@ namespace MobileGL::MG_Backend::DirectGLES {
TextureImpl::GenerateTextureFormatInfo(MGB_STORAGE_FORMAT(textureMipmapObject), &glInternalFormat,
&glFormat, &glType, targetInternal);
const auto& uploadTargets = textureMipmapObject->GetUploadTargets();
const auto& uploadTargets = MGB_UPLOAD_TARGETS(textureMipmapObject);
ScopedDefaultUnpackState unpackState;
for (auto& uploadTarget : uploadTargets) {
for (SizeT level = m_prevTextureInfo.mipmapLevels; level < mipmapCount; ++level) {
auto levelTexelSize = textureMipmapObject->GetMipmapTexelSize(uploadTarget, level);
auto levelTexelSize = MGB_LEVEL_TEXEL_SIZE(textureMipmapObject, uploadTarget, level);
// A level the application never defined reads back as {0, 0, 0}; now that a
// sparse chain is synced rather than skipped whole, leave those undefined on
// the driver instead of giving the name a 0x0 image at that index.
@@ -6933,11 +7358,12 @@ namespace MobileGL::MG_Backend::DirectGLES {
MGB_LEVEL_UPLOAD_DONE(textureMipmapObject, uploadTarget, level);
continue;
}
auto levelByteSize = textureMipmapObject->GetMipmapByteSize(uploadTarget, level);
auto levelByteSize = MGB_LEVEL_BYTE_SIZE(textureMipmapObject, uploadTarget, level);
bool levelDirty = MGB_LEVEL_NEEDS_UPLOAD(textureMipmapObject, uploadTarget, level);
auto glUploadTarget = ConvertTextureUploadTargetToBackendGLEnum(uploadTarget);
auto* pData = (levelDirty && levelByteSize != 0)
? textureMipmapObject->MapMipmapData(uploadTarget, level)
? MGB_LEVEL_TEXELS(textureMipmapObject, uploadTarget, level,
"append-mips")
: nullptr;
Vector<Float> convertedUploadData;
Vector<Uint8> widenedUploadData;
@@ -6951,8 +7377,8 @@ namespace MobileGL::MG_Backend::DirectGLES {
DebugImpl::ErrorLopper::Clear();
BufferImpl::BindPixelUnpackBufferId(0); // no-op once the resting 0 state is pinned
const IntVec3 uploadSize =
GetBackendUploadSize(stateTextureObject->GetTarget(), levelTexelSize);
switch (MapToBackendTextureTarget(stateTextureObject->GetTarget())) {
GetBackendUploadSize(MGB_TEXTURE_TARGET(stateTextureObject), levelTexelSize);
switch (MapToBackendTextureTarget(MGB_TEXTURE_TARGET(stateTextureObject))) {
case TextureTarget::Texture2D:
case TextureTarget::TextureCubeMap:
g_GLESFuncs.glTexImage2D(
@@ -6972,7 +7398,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
break;
default:
MGLOG_E_ONCE("Unhandled texture target %s",
MG_Util::ConvertTextureTargetToString(stateTextureObject->GetTarget()).c_str());
MG_Util::ConvertTextureTargetToString(MGB_TEXTURE_TARGET(stateTextureObject)).c_str());
break;
}
DebugImpl::ErrorLopper::Loop([file = __FILE__, line = __LINE__, func = __func__,
@@ -7022,7 +7448,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
&glFormat, &glType, targetInternal);
ApplyImageBindableStorageWidening(imageWidening, &glInternalFormat, &glFormat, &glType);
const auto& uploadTargets = textureMipmapObject->GetUploadTargets();
const auto& uploadTargets = MGB_UPLOAD_TARGETS(textureMipmapObject);
if (TextureImpl::IsMultisampleTextureTarget(targetInternal)) {
DebugImpl::ErrorLopper::Clear();
BufferImpl::BindPixelUnpackBufferId(0); // no-op once the resting 0 state is pinned
@@ -7120,13 +7546,14 @@ namespace MobileGL::MG_Backend::DirectGLES {
ScopedDefaultUnpackState unpackState;
for (auto& uploadTarget : uploadTargets) {
for (SizeT level = 0; level < mipmapCount; ++level) {
auto levelByteSize = textureMipmapObject->GetMipmapByteSize(uploadTarget, level);
auto levelByteSize = MGB_LEVEL_BYTE_SIZE(textureMipmapObject, uploadTarget, level);
const bool levelDirty = MGB_LEVEL_NEEDS_UPLOAD(textureMipmapObject, uploadTarget, level);
if (levelDirty && levelByteSize != 0) {
auto levelTexelSize =
textureMipmapObject->GetMipmapTexelSize(uploadTarget, level);
MGB_LEVEL_TEXEL_SIZE(textureMipmapObject, uploadTarget, level);
auto glUploadTarget = ConvertTextureUploadTargetToBackendGLEnum(uploadTarget);
auto* pData = textureMipmapObject->MapMipmapData(uploadTarget, level);
auto* pData = MGB_LEVEL_TEXELS(textureMipmapObject, uploadTarget, level,
"immutable-regen");
Vector<Float> convertedUploadData;
Vector<Uint8> widenedUploadData;
const void* uploadData = PrepareFallbackUpload(
@@ -7183,7 +7610,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
ScopedDefaultUnpackState unpackState;
for (auto& uploadTarget : uploadTargets) {
for (SizeT level = 0; level < mipmapCount; ++level) {
auto levelTexelSize = textureMipmapObject->GetMipmapTexelSize(uploadTarget, level);
auto levelTexelSize = MGB_LEVEL_TEXEL_SIZE(textureMipmapObject, uploadTarget, level);
// See the append-mips loop: an undefined level stays undefined on the
// driver rather than becoming a 0x0 image.
if (levelTexelSize.x() <= 0 || levelTexelSize.y() <= 0 ||
@@ -7191,11 +7618,12 @@ namespace MobileGL::MG_Backend::DirectGLES {
MGB_LEVEL_UPLOAD_DONE(textureMipmapObject, uploadTarget, level);
continue;
}
auto levelByteSize = textureMipmapObject->GetMipmapByteSize(uploadTarget, level);
auto levelByteSize = MGB_LEVEL_BYTE_SIZE(textureMipmapObject, uploadTarget, level);
bool levelDirty = MGB_LEVEL_NEEDS_UPLOAD(textureMipmapObject, uploadTarget, level);
auto glUploadTarget = ConvertTextureUploadTargetToBackendGLEnum(uploadTarget);
auto* pData = (levelDirty && levelByteSize != 0)
? textureMipmapObject->MapMipmapData(uploadTarget, level)
? MGB_LEVEL_TEXELS(textureMipmapObject, uploadTarget, level,
"mutable-regen")
: nullptr;
Vector<Float> convertedUploadData;
Vector<Uint8> widenedUploadData;
@@ -7214,7 +7642,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
DebugImpl::ErrorLopper::Clear();
BufferImpl::BindPixelUnpackBufferId(0); // no-op once the resting 0 state is pinned
auto textureTarget = stateTextureObject->GetTarget();
auto textureTarget = MGB_TEXTURE_TARGET(stateTextureObject);
const IntVec3 uploadSize = GetBackendUploadSize(textureTarget, levelTexelSize);
switch (MapToBackendTextureTarget(textureTarget)) {
case TextureTarget::Texture2D:
@@ -7263,7 +7691,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
{ // Update all dirty mipmap levels
if (TextureImpl::IsMultisampleTextureTarget(targetInternal)) {
const auto& uploadTargets = textureMipmapObject->GetUploadTargets();
const auto& uploadTargets = MGB_UPLOAD_TARGETS(textureMipmapObject);
for (const auto& uploadTarget : uploadTargets) {
for (SizeT level = 0; level < mipmapCount; ++level) {
if (MGB_LEVEL_NEEDS_UPLOAD(textureMipmapObject, uploadTarget, level)) {
@@ -7283,7 +7711,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
// requires glTexSubImage's `format` to match the storage's base internal
// format, so a GL_RG upload into a GL_RGBA32F image is GL_INVALID_OPERATION.
ApplyImageBindableStorageWidening(imageWidening, &glInternalFormat, &glFormat, &glType);
const auto& uploadTargets = textureMipmapObject->GetUploadTargets();
const auto& uploadTargets = MGB_UPLOAD_TARGETS(textureMipmapObject);
ScopedDefaultUnpackState unpackState;
for (auto& uploadTarget : uploadTargets) {
for (SizeT level = 0; level < mipmapCount; ++level) {
@@ -7291,7 +7719,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
continue;
}
auto byteSize = textureMipmapObject->GetMipmapByteSize(uploadTarget, level);
auto byteSize = MGB_LEVEL_BYTE_SIZE(textureMipmapObject, uploadTarget, level);
if (byteSize == 0) {
MGLOG_D("Mipmap level %d has no data, skipping update.", level);
continue;
@@ -7301,8 +7729,8 @@ namespace MobileGL::MG_Backend::DirectGLES {
MGLOG_D("%s: Updating dirty mip %d for texture ID %u, size: %dx%d, "
"byteSize: %d",
__func__, level, m_backendTextureId,
textureMipmapObject->GetMipmapTexelSize(uploadTarget, level).x(),
textureMipmapObject->GetMipmapTexelSize(uploadTarget, level).y(), byteSize);
MGB_LEVEL_TEXEL_SIZE(textureMipmapObject, uploadTarget, level).x(),
MGB_LEVEL_TEXEL_SIZE(textureMipmapObject, uploadTarget, level).y(), byteSize);
auto glUploadTarget = ConvertTextureUploadTargetToBackendGLEnum(uploadTarget);
BufferImpl::BindPixelUnpackBufferId(0); // no-op once the resting 0 state is pinned
@@ -7311,8 +7739,9 @@ namespace MobileGL::MG_Backend::DirectGLES {
MGLOG_D("%s(%s:%d) ES error: %s", func, file, line,
MG_Util::ConvertGLEnumToString(err).c_str());
});
auto texelSize = textureMipmapObject->GetMipmapTexelSize(uploadTarget, level);
const void* mipData = textureMipmapObject->MapMipmapData(uploadTarget, level);
auto texelSize = MGB_LEVEL_TEXEL_SIZE(textureMipmapObject, uploadTarget, level);
const void* mipData = MGB_LEVEL_TEXELS(textureMipmapObject, uploadTarget, level,
"dirty-level");
Vector<Float> convertedUploadData;
Vector<Uint8> widenedUploadData;
const void* uploadData = PrepareFallbackUpload(
@@ -7329,7 +7758,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
uploadData = PrepareImageWidenedUpload(imageWidening, texelSize, uploadData, byteSize,
imageWidenedUploadData);
const IntVec3 uploadSize =
GetBackendUploadSize(stateTextureObject->GetTarget(), texelSize);
GetBackendUploadSize(MGB_TEXTURE_TARGET(stateTextureObject), texelSize);
// Sub-rect upload: when only a region of the level changed (a
// 16x16 sprite in a 1024x512 atlas, the per-frame lightmap) and
// the shadow bytes go to the driver unconverted, upload just that
@@ -7357,6 +7786,20 @@ namespace MobileGL::MG_Backend::DirectGLES {
: nullptr;
const auto dirtyRegion = [&]() -> MG_State::GLState::MipmapDirtyRegion {
if (pendingUpload == nullptr) {
#if MOBILEGL_BUILD_DISAGGREGATED
// P5c (tx): a level this arm owes with NO pending upload behind it
// was dirtied by the GPU (T5), and the dirty answer is the
// server's own mark on the staged shadow - the whole level,
// because a generation touches all of it. The client is never
// asked (§2.2's last row).
if (MGB_STAGED_TEXTURE_LIVE) {
const IntVec3 gpuExtent =
MG_Remote::Server::ServerStagedTexture().LevelExtentOrUndefined(
MG_Remote::Server::StagedTextureStore::KeyForHandle(pushedRes),
static_cast<Uint16>(uploadTarget), static_cast<Uint16>(level));
return MG_State::GLState::MipmapDirtyRegion{IntVec3{0, 0, 0}, gpuExtent};
}
#endif
return textureMipmapObject->GetStorageDirtyRegion(uploadTarget, level);
}
// MGPBox is {origin, extent}; MipmapDirtyRegion is {lo, hi}. The
@@ -7507,6 +7950,13 @@ namespace MobileGL::MG_Backend::DirectGLES {
region.Z + static_cast<Int32>(region.D)}};
}
} else
#endif
#if MOBILEGL_BUILD_DISAGGREGATED
// tx: with an active transport the rect list is the record's (the
// pendingUpload arm above) or nothing - the server's GPU-dirty mark
// is whole-level and has no scatter refinement to hand out, and the
// frontend's rect model is not this side's to read.
if (!MGB_STAGED_TEXTURE_LIVE)
#endif
dirtyRectCount = textureMipmapObject->GetStorageDirtyRects(
uploadTarget, level, dirtyRects,
@@ -7661,7 +8111,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
MG_Util::PipeStats::AddCalls(MG_Util::PipeStats::CallClass::TextureUploadJobs,
rectShape ? static_cast<Uint64>(dirtyRectCount) : 1u);
}
switch (MapToBackendTextureTarget(stateTextureObject->GetTarget())) {
switch (MapToBackendTextureTarget(MGB_TEXTURE_TARGET(stateTextureObject))) {
case TextureTarget::Texture2D:
case TextureTarget::TextureCubeMap:
if (subRectEligible && dirtyRectCount >= 2) {
@@ -7754,7 +8204,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
break;
default:
MGLOG_E_ONCE("Unhandled texture target %s",
MG_Util::ConvertTextureTargetToString(stateTextureObject->GetTarget()).c_str());
MG_Util::ConvertTextureTargetToString(MGB_TEXTURE_TARGET(stateTextureObject)).c_str());
break;
}
if (ringStaged) {
@@ -8009,6 +8459,14 @@ namespace MobileGL::MG_Backend::DirectGLES {
#undef MGB_STORAGE_FIXED_SAMPLE_LOCATIONS
#undef MGB_STORAGE_IMMUTABLE
#undef MGB_STORAGE_KIND
#undef MGB_TEXTURE_TARGET
#undef MGB_UPLOAD_TARGETS
#undef MGB_LEVEL_TEXEL_SIZE
#undef MGB_LEVEL_BYTE_SIZE
#undef MGB_LEVEL_TEXELS
#if MOBILEGL_BUILD_DISAGGREGATED
#undef MGB_STAGED_TEXTURE_LIVE
#endif
#if MOBILEGL_PIPE_PUSH
const SamplerParameters* BackendTextureObject::ResolvePushedBuiltinSampler(
@@ -8017,6 +8475,11 @@ namespace MobileGL::MG_Backend::DirectGLES {
// object this backend still arrives holding. Under a real split the handle rides in
// the payload; the client mints it off this object's lifetime id, so the allocator
// resolves it here through the table's own single-entry front memo.
#if MOBILEGL_BUILD_DISAGGREGATED
// P5c (G6, CONTRACT-P5C §5.4): frontend-keyed resolution, named debt inside the
// scope - P3b/P4b rekeys the registry onto handles.
const MG_Pipe::MGPipeFrontendKeyedRegistryScope frontendKeyedRegistry;
#endif
const MG_Pipe::MGPipeHandle res = g_backendTextureObjects.HandleOf(stateTextureObject.get());
const auto* record = PipeTextureRecordForHandle(res);
if (record == nullptr) {
@@ -8248,6 +8711,11 @@ namespace MobileGL::MG_Backend::DirectGLES {
#if MOBILEGL_PIPE_PUSH
const MG_Pipe::MGPipeResourceRecord* BackendTextureObject::ResolvePushedTextureParams(
const SharedPtr<MG_State::GLState::ITextureObject>& stateTextureObject) {
#if MOBILEGL_BUILD_DISAGGREGATED
// P5c (G6, CONTRACT-P5C §5.4): frontend-keyed resolution, named debt inside the
// scope - P3b/P4b rekeys the registry onto handles.
const MG_Pipe::MGPipeFrontendKeyedRegistryScope frontendKeyedRegistry;
#endif
const MG_Pipe::MGPipeHandle res = g_backendTextureObjects.HandleOf(stateTextureObject.get());
const auto* record = PipeTextureRecordForHandle(res);
if (record == nullptr) {
@@ -8782,6 +9250,11 @@ namespace MobileGL::MG_Backend::DirectGLES {
if (attachmentObject.IsTexture()) {
const auto& textureObject = attachmentObject.GetTexture();
SharedPtr<TextureImpl::BackendTextureObject> backendTextureObject;
#if MOBILEGL_BUILD_DISAGGREGATED
// P5c (G6, CONTRACT-P5C §5.4): frontend-keyed twin resolution (and the mint on
// a first attach), named debt inside the scope - P3b/P4b rekeys the registry.
const MG_Pipe::MGPipeFrontendKeyedRegistryScope frontendKeyedRegistry;
#endif
if (auto* backendTextureSlot = TextureImpl::g_backendTextureObjects.Find(textureObject.get())) {
backendTextureObject = *backendTextureSlot;
} else {
@@ -8831,6 +9304,11 @@ namespace MobileGL::MG_Backend::DirectGLES {
}
} else if (attachmentObject.IsRenderbuffer()) {
const auto& renderbufferObject = attachmentObject.GetRenderbuffer();
#if MOBILEGL_BUILD_DISAGGREGATED
// P5c (G6, CONTRACT-P5C §5.4): frontend-keyed twin resolution (and the mint on
// a first attach), named debt inside the scope - P3b/P4b rekeys the registry.
const MG_Pipe::MGPipeFrontendKeyedRegistryScope frontendKeyedRegistry;
#endif
SharedPtr<RenderbufferImpl::BackendRenderbufferObject> backendRenderbufferObject;
if (auto* backendRenderbufferSlot =
RenderbufferImpl::g_backendRenderbufferObjects.Find(renderbufferObject.get())) {
@@ -9143,7 +9621,16 @@ namespace MobileGL::MG_Backend::DirectGLES {
surface.Res.Slot, surface.Res.Gen);
return false;
}
#if MOBILEGL_BUILD_DISAGGREGATED
// P5c (hd): the corroborating cross-check against the frontend object's handle
// is a client-allocator probe (T2). Under an active transport the record is the
// ONLY statement of identity (rule E) and the check does not run; monolith
// keeps it verbatim. The record's own handle was already validated above (N-3).
if (MG_Config::Transport == MG_Config::TransportMode::Monolith &&
!(TextureImpl::g_backendTextureObjects.HandleOf(textureObject.get()) == surface.Res)) {
#else
if (!(TextureImpl::g_backendTextureObjects.HandleOf(textureObject.get()) == surface.Res)) {
#endif
MGLOG_E_ONCE("MGPipe: attachment record names texture {%u, %u} but the frontend "
"attachment's texture %u is handle {%u, %u} - refusing rather than "
"attaching one of them",
@@ -9215,6 +9702,12 @@ namespace MobileGL::MG_Backend::DirectGLES {
surface.Res.Slot, surface.Res.Gen);
return false;
}
#if MOBILEGL_BUILD_DISAGGREGATED
// P5c (G6, CONTRACT-P5C §5.4): the corroborating cross-check below resolves the
// frontend renderbuffer's handle by frontend identity - named debt inside the
// scope - P3b/P4b rekeys the registry onto handles.
const MG_Pipe::MGPipeFrontendKeyedRegistryScope frontendKeyedRegistry;
#endif
if (!(RenderbufferImpl::g_backendRenderbufferObjects.HandleOf(renderbufferObject.get()) ==
surface.Res)) {
MGLOG_E_ONCE("MGPipe: attachment record names renderbuffer {%u, %u} but the frontend "
@@ -9358,7 +9851,15 @@ namespace MobileGL::MG_Backend::DirectGLES {
// FramebufferAttachmentType::None, i.e. GL_NONE. A surface that matches no colour
// point cannot be a legal read buffer and is refused rather than guessed.
if (FramebufferSubsystemEnabled()) {
const MG_Pipe::MGPipeHandle fbo = g_backendFramebufferObjects.HandleOf(stateFBOObject.get());
// P5c (hd): with an active transport the handle is the caller's
// (m_pushedSyncHandle), never the client allocator's - see SyncToBackend.
const MG_Pipe::MGPipeHandle fbo =
#if MOBILEGL_BUILD_DISAGGREGATED
MG_Config::Transport != MG_Config::TransportMode::Monolith
? m_pushedSyncHandle
:
#endif
g_backendFramebufferObjects.HandleOf(stateFBOObject.get());
// ID-19: the OBJECT's record, not "the record of whatever is bound to READ". A
// framebuffer whose read buffer is being pushed need not be the read binding at
// all - glNamedFramebufferReadBuffer and the DSA clears reach here by name - and
@@ -9586,7 +10087,18 @@ namespace MobileGL::MG_Backend::DirectGLES {
// there is no framebuffer create or destroy in the catalogue and none is invented
// - so the handle exists purely to key set_framebuffer_state, which is exactly
// what it is used for here.
const MG_Pipe::MGPipeHandle fbo = g_backendFramebufferObjects.HandleOf(stateFBOObject.get());
//
// P5c (hd): with an active transport the handle is the one the caller is applying
// (m_pushedSyncHandle - the record-driven sync set it), and the client allocator
// is never probed (T2). A null there means a caller reached this arm without a
// record, which the null-record refusal below names.
const MG_Pipe::MGPipeHandle fbo =
#if MOBILEGL_BUILD_DISAGGREGATED
MG_Config::Transport != MG_Config::TransportMode::Monolith
? m_pushedSyncHandle
:
#endif
g_backendFramebufferObjects.HandleOf(stateFBOObject.get());
pushedRecord = PushedFramebufferRecord(fbo);
if (pushedRecord == nullptr) {
MGLOG_E_ONCE("MGPipe: framebuffer %u has no applier record on the handle arm, so it "
@@ -9864,6 +10376,11 @@ namespace MobileGL::MG_Backend::DirectGLES {
// Verify that the backend object's name and parameters match the frontend attachment state
if (attachmentObject.IsTexture()) {
const auto& textureObject = attachmentObject.GetTexture();
#if MOBILEGL_BUILD_DISAGGREGATED
// P5c (G6, CONTRACT-P5C §5.4): frontend-keyed twin resolution, named
// debt inside the scope - P3b/P4b rekeys the registry.
const MG_Pipe::MGPipeFrontendKeyedRegistryScope frontendKeyedRegistry;
#endif
auto* backendTextureSlot = TextureImpl::g_backendTextureObjects.Find(textureObject.get());
MOBILEGL_ASSERT(backendTextureSlot != nullptr && *backendTextureSlot != nullptr,
"No backend texture found while framebuffer reports texture attachment.");
@@ -9880,6 +10397,11 @@ namespace MobileGL::MG_Backend::DirectGLES {
"Attachment texture level mismatch between GLES and state object.");
} else if (attachmentObject.IsRenderbuffer()) {
const auto& renderbufferObject = attachmentObject.GetRenderbuffer();
#if MOBILEGL_BUILD_DISAGGREGATED
// P5c (G6, CONTRACT-P5C §5.4): frontend-keyed twin resolution, named
// debt inside the scope - P3b/P4b rekeys the registry.
const MG_Pipe::MGPipeFrontendKeyedRegistryScope frontendKeyedRegistry;
#endif
auto* backendRboSlot =
RenderbufferImpl::g_backendRenderbufferObjects.Find(renderbufferObject.get());
MOBILEGL_ASSERT(
@@ -12420,6 +12942,12 @@ namespace MobileGL::MG_Backend::DirectGLES {
// stateProgramObject. The verify build is where the codec is exercised, by
// serialising, deserialising and field-comparing before storing.
if (ProgramSubsystemEnabled()) {
#if MOBILEGL_BUILD_DISAGGREGATED
// P5c (G6, CONTRACT-P5C §5.4): the program's ShaderCso handle is resolved by
// frontend identity below - frontend-keyed twin resolution, named debt inside
// the scope - P3b/P4b rekeys the registry onto handles.
const MG_Pipe::MGPipeFrontendKeyedRegistryScope frontendKeyedRegistry;
#endif
// MONOLITH GLUE: the ShaderCso handle of a program this backend still arrives
// holding. The reader hides the composite band, so a program-pipeline composite
// - which the server must never learn is one - resolves through the same call.
@@ -12738,6 +13266,12 @@ namespace MobileGL::MG_Backend::DirectGLES {
// the values are taken from the object, which in monolith are the very
// values the client content-addressed, so the picture stays right while
// the gap is visible rather than silent.
#if MOBILEGL_BUILD_DISAGGREGATED
// P5c (G6, CONTRACT-P5C §5.4): the registration probe below resolves the
// sampler's handle by frontend identity - frontend-keyed twin resolution,
// named debt inside the scope - P3b/P4b rekeys the registry onto handles.
const MG_Pipe::MGPipeFrontendKeyedRegistryScope frontendKeyedRegistry;
#endif
if (!MG_Pipe::MGPipeHandleIsNull(
g_backendSamplerObjects.HandleOf(stateSamplerObject.get()))) {
MGLOG_E_ONCE("MGPipe: sampler %u was synced without its unit's SamplerCso handle, so "
@@ -13029,6 +13563,12 @@ namespace MobileGL::MG_Backend::DirectGLES {
#if MOBILEGL_PIPE_PUSH
const MG_Pipe::MGPipeResourceRecord* pushedRecord = nullptr;
if (TextureResourceSubsystemEnabled()) {
#if MOBILEGL_BUILD_DISAGGREGATED
// P5c (G6, CONTRACT-P5C §5.4): the renderbuffer's handle is resolved by
// frontend identity below - frontend-keyed twin resolution, named debt inside
// the scope - P3b/P4b rekeys the registry onto handles.
const MG_Pipe::MGPipeFrontendKeyedRegistryScope frontendKeyedRegistry;
#endif
// MONOLITH GLUE, named as such: the Renderbuffer handle of an object this
// backend still arrives holding. Under a real split it rides in the payload.
const MG_Pipe::MGPipeHandle res = g_backendRenderbufferObjects.HandleOf(stateRBOObject.get());
+69 -10
View File
@@ -467,17 +467,47 @@ namespace MobileGL::MG_Backend::DirectGLES {
return m_slotTable.LiveGenAt(slot);
}
// NO ReleaseByHandle HERE, AND THAT IS A DECISION (review M-4). The death half of
// GetOrCreateByHandle exists for a kind whose announcement is its own destroy CALL
// rather than the shared death notice - which is the BUFFER family
#if MOBILEGL_BUILD_DISAGGREGATED
// P5c (hd): the two halves of SlotTables.h's state note, forwarded. A caller holding
// both the record's handle and the frontend object (the record-driven sync) notes the
// object so a later handle-only resolution can reach it without the client allocator.
void NoteStateForHandle(MG_Pipe::MGPipeHandle handle, const StatePtr& stateObj) {
if (EsprytSlotTablesEnabled()) {
m_slotTable.NoteStateForHandle(handle, stateObj);
}
}
StatePtr StateForHandle(MG_Pipe::MGPipeHandle handle) const {
if (EsprytSlotTablesEnabled()) {
return m_slotTable.StateForHandle(handle);
}
return nullptr;
}
#endif
// NO ReleaseByHandle HERE THROUGH P5, AND THAT WAS A DECISION (review M-4). The death
// half of GetOrCreateByHandle existed only for a kind whose announcement is its own
// destroy CALL rather than the shared death notice - which was the BUFFER family
// (BackendBufferResourceTable::ReleaseByHandle, SlotTables.h, called from
// resource_destroy) and none of the five kinds this registry serves: every one of them
// dies through DestroyByLifetimeId below, because P4a adds no server-side destroy arm
// for a texture, a renderbuffer, a framebuffer, a sampler CSO or a shader CSO. v1
// declared one here anyway and it had no caller on either arm, which made its bound and
// its wording things nobody would exercise until P5. The one-line wrapper comes back in
// the commit that gives it a caller; SlotTable::ReleaseByHandle underneath is untouched
// and is what SanityTest drives directly.
// resource_destroy) and none of the five kinds this registry serves: every one of
// them died through DestroyByLifetimeId below, because P4a added no server-side
// destroy arm for a texture, a renderbuffer, a framebuffer, a sampler CSO or a shader
// CSO. P5c (ct) is the commit that gives the wrapper its caller: object_death carries
// the dead object's HANDLE on the wire (CONTRACT-P5C.md §5.2), and the static
// ReleaseByHandle below is what the sink's per-kind dispatch calls.
// P5c (ct), CONTRACT-P5C.md §5.2: the wrapper M-4 below deferred, given its caller by
// object_death. The record carried the handle, so the release is keyed by it and the
// client's allocator is never asked from this side (rule E); every holder of the kind
// lets go, exactly as DestroyByLifetimeId walks them. What this does NOT do is the
// allocator Free the notice arm performs - the slot's owner is the client, which
// already returned it after the record went out. STATIC for the same reason
// DestroyByLifetimeId is: a death is about an object, not a table instance.
static Bool ReleaseByHandle(MG_Pipe::MGPipeHandle handle) {
if (EsprytSlotTablesEnabled()) {
return SlotTable::ReleaseTwinByHandle(handle);
}
return false;
}
// P2 step e2. STATIC, because a death notice is about an object and not about a
// registry instance: it is answered by EVERY table of this kind that exists - this
@@ -892,6 +922,14 @@ namespace MobileGL::MG_Backend::DirectGLES {
GLESBufferResource* GetOrCreateBufferResourceForHandle(MG_Pipe::MGPipeHandle res);
GLESBufferResource* FindBufferResourceForHandle(MG_Pipe::MGPipeHandle res);
#if MOBILEGL_BUILD_DISAGGREGATED
// P5c (hd): the staged-coverage assertion (StagedShadowStore::RequireCoverage) for a
// read of the server shadow outside the upload ladders - the indirect command-byte
// resolver. A no-op for a base that is not this resource's server shadow.
void RequireStagedCoverage(GLESBufferResource& resource, const Uint8* hostBase, SizeT start,
SizeT end, const char* site);
#endif
// MONOLITH GLUE, and named as such: the handle of a resource this backend is looking
// at through a frontend object, resolved through the client allocator's lifetime-id
// index. Every caller is a site P3a deliberately does NOT migrate - the SSBO / UBO /
@@ -1810,6 +1848,14 @@ namespace MobileGL::MG_Backend::DirectGLES {
// still run when SyncCurrentFBO skips the READ-target sync because the same GL FBO is
// bound as both draw and read (otherwise glReadBuffer changes would be silently dropped).
void SyncReadBufferToBackend(const SharedPtr<MG_State::GLState::FramebufferObject>& stateFBOObject);
#if MOBILEGL_BUILD_DISAGGREGATED
// P5c (hd, CONTRACT-P5C §3.2): the framebuffer handle the CURRENT sync is keyed on.
// A caller applying a record sets it before SyncToBackend / SyncReadBufferToBackend,
// which then read the applier's record for THAT handle instead of probing the
// client's slot allocator for the frontend object's lifetime id (T2). Read only
// with an active transport; monolith resolves through HandleOf as it always did.
MG_Pipe::MGPipeHandle m_pushedSyncHandle = MG_Pipe::kMGPipeNullHandle;
#endif
void InvalidateSyncedState();
Uint GetBackendFramebufferId() const { return m_backendFBOId; }
void Bind(FramebufferTarget target) const;
@@ -2773,4 +2819,17 @@ namespace MobileGL::MG_Backend::DirectGLES {
extern TwinRegistry<MG_State::GLState::RenderbufferObject, BackendRenderbufferObject, MG_Pipe::MGPipeKind::Renderbuffer>
g_backendRenderbufferObjects;
} // namespace RenderbufferImpl
#if MOBILEGL_BUILD_DISAGGREGATED
// P5c (ct), CONTRACT-P5C.md §5.2: object_death's per-kind release, one entry point for all
// seven kinds for the same reason the notice switch is one - the answer is the same for
// all of them: every holder of the kind's twin table lets go of the twin at this handle.
// Called from ServerVerbSink::OnObjectDeath ON THE APPLY THREAD, with the handle the
// record carried; the client's allocator is never consulted (rule E). Returns whether any
// table released a twin - false for a kind this backend does not twin (Buffer: its death
// crosses as resource_destroy) and for a handle no holder holds, which the kind's own
// delete opcode may already have released (the idempotent-second-path shape the notice
// arms document).
Bool ReleaseTwinsForWireObjectDeath(MG_Pipe::MGPipeHandle handle, MG_Pipe::MGPipeKind kind);
#endif
} // namespace MobileGL::MG_Backend::DirectGLES
@@ -75,6 +75,12 @@
// belong on the client, and the backend should receive the handle in the verb payload. It is
// NOT part of "Track H done" and check_include_closure.py does not probe MG_Backend headers,
// so nothing catches it automatically.
//
// P5c (hd, CONTRACT-P5C §3.1) is what gives the debt teeth: with an active transport the
// minting GetOrCreate, HandleOf and OnFrontendObjectDestroyed raise
// Fatal{RoleViolation, "MGPipeSlots"} when reached from the apply thread (the same check the
// allocator's own three entries carry, repeated here so the refusal names this surface), and
// the split paths resolve through GetOrCreate(handle) / ReleaseByHandle instead.
namespace MobileGL::MG_Backend::DirectGLES {
#if MOBILEGL_PIPE_PUSH
@@ -228,6 +234,16 @@ namespace MobileGL::MG_Backend::DirectGLES {
// arm StateBackendObjectRegistry::GetOrCreate arms it itself.
EnsureProcessTeardownSentinel();
#if MOBILEGL_BUILD_DISAGGREGATED
// P5c (hd, CONTRACT-P5C §3.1): this overload MINTS - it is monolith glue, and with
// an active transport a call from the apply thread is Fatal{RoleViolation,
// "MGPipeSlots"} before the allocator is touched. Split paths call the handle
// overload below. (The check also lives at the allocator's own three entries; it
// is repeated at this entry so the refusal names this surface even if the entry
// set changes.)
MG_Pipe::MGPipeRefuseAllocatorFromApplyThread("GetOrCreate(StatePtr)");
#endif
const MG_Pipe::MGPipeHandle handle =
MG_Pipe::MGPipeSlots().Acquire(kKind, stateObj->GetLifetimeId());
MOBILEGL_ASSERT(!MG_Pipe::MGPipeHandleIsNull(handle),
@@ -334,6 +350,34 @@ namespace MobileGL::MG_Backend::DirectGLES {
return entry.Live ? entry.Gen : 0;
}
#if MOBILEGL_BUILD_DISAGGREGATED
// P5c (hd): remember the frontend object a HANDLE-keyed twin was synced from. The
// minting overload sets stateRef itself; the handle overload cannot (no object
// crosses), so a caller that legitimately holds the object - the record-driven sync,
// which arrived holding it through the object-class barrier-pulled rows - notes it
// here. It is what lets a later handle-only resolution (P5c's named blit) reach the
// frontend object the twin's sync body still walks, without probing the client's slot
// allocator (T2). Same liveness rules as the minted stateRef: never an identity test,
// never read to decide the slot is dead.
void NoteStateForHandle(MG_Pipe::MGPipeHandle handle, const StatePtr& stateObj) {
if (MG_Pipe::MGPipeHandleIsNull(handle) || handle.Slot >= m_slots.size()) return;
Entry& entry = m_slots[handle.Slot];
if (!entry.Live || entry.Gen != handle.Gen) return;
entry.stateRef = stateObj;
}
// The frontend object noted for this handle, or null. The handle answers identity;
// this answers only "which object was this twin last synced from".
StatePtr StateForHandle(MG_Pipe::MGPipeHandle handle) const {
if (MG_Pipe::MGPipeHandleIsNull(handle) || handle.Slot >= m_slots.size()) {
return nullptr;
}
const Entry& entry = m_slots[handle.Slot];
if (!entry.Live || entry.Gen != handle.Gen) return nullptr;
return entry.stateRef.lock();
}
#endif
// P3a: the death half of the overload above, for a kind whose announcement is its own
// destroy CALL rather than the shared death notice (D-L). Hands the twin OUT rather
// than destroying it in place, because the caller may still have to decide what
@@ -391,6 +435,11 @@ namespace MobileGL::MG_Backend::DirectGLES {
// allocator probe it always cost; a hit is refreshed the moment anyone acquires.
MG_Pipe::MGPipeHandle HandleOf(const StateObject* stateObj) const {
if (stateObj == nullptr) return MG_Pipe::kMGPipeNullHandle;
#if MOBILEGL_BUILD_DISAGGREGATED
// P5c (hd): same guard as the minting overload - a lifetime-id probe from the
// apply thread is Fatal{RoleViolation, "MGPipeSlots"} with an active transport.
MG_Pipe::MGPipeRefuseAllocatorFromApplyThread("HandleOf");
#endif
const Uint64 lifetimeId = stateObj->GetLifetimeId();
if (lifetimeId == m_memoLifetimeId) return m_memoHandle;
const MG_Pipe::MGPipeHandle handle =
@@ -414,6 +463,12 @@ namespace MobileGL::MG_Backend::DirectGLES {
// Returns whether the object had a slot of this kind, i.e. whether anything was freed;
// a second call for the same id answers false because the allocator no longer maps it.
static Bool OnFrontendObjectDestroyed(Uint64 lifetimeId) {
#if MOBILEGL_BUILD_DISAGGREGATED
// P5c (hd): the Find/Free pair below is monolith-only with an active transport -
// a frontend death is announced to the server by the object_death record (ct),
// and a direct call from the apply thread is Fatal{RoleViolation, "MGPipeSlots"}.
MG_Pipe::MGPipeRefuseAllocatorFromApplyThread("OnFrontendObjectDestroyed");
#endif
const MG_Pipe::MGPipeHandle handle =
MG_Pipe::MGPipeSlots().FindByLifetimeId(kKind, lifetimeId);
if (MG_Pipe::MGPipeHandleIsNull(handle)) return false;
@@ -429,6 +484,28 @@ namespace MobileGL::MG_Backend::DirectGLES {
return true;
}
// P5c (ct), CONTRACT-P5C.md §5.2: the handle-keyed half of the above, for a death that
// arrived AS A WIRE RECORD (object_death) rather than as the shared notice. The
// handle IS the resolution - it crossed in the record's payload - so the client's
// allocator is never asked: under an active transport MGPipeSlots() is a client-only
// surface (rule E, §3.1) and this function runs on the apply thread. Every holder
// lets go exactly as the notice arm does, in the same successor-first order. What
// does NOT happen here is the allocator Free: the slot's owner - the client -
// returned it itself after the record went out (PipeFill.cpp's NotifyAndFree), and a
// double Free would be refused by generation anyway. Idempotent against the kind's
// own delete opcode, exactly as the notice arm is: a twin the delete already released
// fails ReleaseTwinAt's generation check and the walk moves on.
static Bool ReleaseTwinByHandle(MG_Pipe::MGPipeHandle handle) {
if (MG_Pipe::MGPipeHandleIsNull(handle)) return false;
Bool released = false;
for (BackendSlotTable* holder = s_firstHolder; holder != nullptr;) {
BackendSlotTable* const next = holder->m_nextHolder;
released = holder->ReleaseTwinAt(handle) || released;
holder = next;
}
return released;
}
// How many tables of this type exist right now. For the tests that pin the holder
// list; nothing on a shipping path asks.
static Uint32 HolderCount() {
+10
View File
@@ -31,6 +31,7 @@
#include <algorithm>
#include <cmath>
#include <cctype>
#include <cstdlib>
#include <cstring>
#include <format>
#include <regex>
@@ -46,6 +47,15 @@ namespace MobileGL::MG_Backend::DirectGLES {
if (MG_Backend::BackendObject* server = MG_Remote::Server::ServerLoopInstance().Backend()) {
return &server->GetFormatCapabilities();
}
// P5c (hd, CONTRACT-P5C §3.7): the mirror fallback is REFUSED with an active
// transport. The server's backend exists whenever the session does, so reaching
// here is a bring-up ordering defect, and a silent read of the client caps mirror
// (pActiveBackendObject is client memory, rule E) would hide it.
MGLOG_F("MGPipe: Fatal{RoleViolation, \"caps-mirror\"} - the format-capability "
"fallback to the client caps mirror was reached with an active transport "
"but no server backend; the server's own backend is the only legal source "
"on the apply thread");
std::abort();
}
return pActiveBackendObject ? &pActiveBackendObject->GetFormatCapabilities() : nullptr;
}
@@ -1,4 +1,4 @@
// MobileGL - MobileGL/MG_Backend/DirectVulkan/DirectVulkan.cpp
// MobileGL - MobileGL/MG_Backend/DirectVulkan/DirectVulkan.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
@@ -17,6 +17,10 @@
#include "MG_Util/Metrics/PipeStats.h"
#include "MG_Util/Metrics/TextureMetrics.h"
#include "MG_Util/Miscellany/IndexGenerator.h"
#if MOBILEGL_BUILD_DISAGGREGATED
#include <Config.h>
#include <MG_Remote/Server/ServerLoop.h>
#endif
#include <atomic>
#include <bit>
#include <cstring>
@@ -710,9 +714,23 @@ namespace MobileGL::MG_Backend::DirectVulkan {
void ShaderStorageBlockBinding(GLuint program, const GLchar* storageBlockName, GLuint storageBlockBinding) {
auto* programObject = TryGetDirectVulkanProgram(program);
if (!programObject || storageBlockName == nullptr) return;
const Int maxBindings = pActiveBackendObject
? pActiveBackendObject->GetDynamicParameters().MaxShaderStorageBufferBindings
: 0;
const Int maxBindings =
#if MOBILEGL_BUILD_DISAGGREGATED
// P5c (hd, CONTRACT-P5C §3.7): with an active transport the dynamic parameters are
// the SERVER's own backend's - the client caps mirror (pActiveBackendObject) is
// client memory the apply thread may not name (rule E). Monolith reads the mirror
// as it always did.
MG_Config::Transport != MG_Config::TransportMode::Monolith
? (MG_Remote::Server::ServerLoopInstance().Backend() != nullptr
? static_cast<Int>(MG_Remote::Server::ServerLoopInstance().Backend()
->GetDynamicParameters()
.MaxShaderStorageBufferBindings)
: 0)
:
#endif
pActiveBackendObject
? pActiveBackendObject->GetDynamicParameters().MaxShaderStorageBufferBindings
: 0;
if (storageBlockBinding >= static_cast<GLuint>(maxBindings)) {
MGB_CTX->RecordError(
ErrorCode::InvalidValue,
@@ -11,6 +11,11 @@
#include "MG_Impl/GLImpl/Framebuffer/GL_Framebuffer.h"
#include "MG_State/GLState/TextureState/TextureObject2D.h"
#if MOBILEGL_PIPE_PUSH
// P5c ev: the surface-changed event's producer callback, installed by the server session.
#include <MG_Pipe/MGPipeCallbacks.h>
#endif
#if defined(__has_include)
#if __has_include(<vulkan/vk_enum_string_helper.h>)
#include <vulkan/vk_enum_string_helper.h>
@@ -280,11 +285,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
static_cast<SizeT>(defaultFramebufferExtent.width) *
static_cast<SizeT>(defaultFramebufferExtent.height) * 4;
auto* colorTex = static_cast<MG_State::GLState::TextureObject2D*>(defaultFBOInfo->colorAttachment.get());
colorTex->AllocateStorage(
TextureUploadTarget::Texture2D, 0, {
{extentWidth, extentHeight, 1},
defaultAttachmentByteSize}); // TODO: 4 is format size
TextureInternalFormat depthFormat = TextureInternalFormat::Depth24Stencil8;
switch (m_depthStencilFormat) {
case VK_FORMAT_D24_UNORM_S8_UINT:
@@ -300,11 +300,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
depthFormat = TextureInternalFormat::Depth24Stencil8;
break;
}
auto* depthTex = static_cast<MG_State::GLState::TextureObject2D*>(defaultFBOInfo->depthAttachment.get());
depthTex->SetInternalFormat(depthFormat);
depthTex->AllocateStorage(TextureUploadTarget::Texture2D, 0, {
{extentWidth, extentHeight, 1},
defaultAttachmentByteSize}); // TODO: 4 is format size
// The default FBO's stencil attachment must track the swapchain extent:
// FramebufferObject::CheckCompleteness requires every valid attachment
@@ -324,11 +319,44 @@ namespace MobileGL::MG_Backend::DirectVulkan {
stencilFormat = depthFormat;
break;
}
auto* stencilTex = static_cast<MG_State::GLState::TextureObject2D*>(defaultFBOInfo->stencilAttachment.get());
stencilTex->SetInternalFormat(stencilFormat);
stencilTex->AllocateStorage(TextureUploadTarget::Texture2D, 0, {
{extentWidth, extentHeight, 1},
defaultAttachmentByteSize}); // TODO: 4 is format size
#if MOBILEGL_PIPE_PUSH
if (MG_Pipe::gMGPipeCallbacks.OnSurfaceChanged != nullptr) {
// P5c ev (CONTRACT-P5C §4.2): with an active transport the default FBO's
// attachments are CLIENT memory and this thread may not write them - the backend
// fills MGPSurfaceInfo and posts, and the client's consumer replays exactly the
// allocate/format writes of the monolith arm below on the GL thread. The two
// formats are always equal by the switches above, so one InternalFormat carries
// both. The callback's presence IS the transport probe - the server session
// installs it at Accept, and under monolith nobody ever does.
MG_Pipe::MGPSurfaceInfo info{};
info.Width = defaultFramebufferExtent.width;
info.Height = defaultFramebufferExtent.height;
info.InternalFormat = static_cast<Uint32>(depthFormat);
info.Samples = 1;
info.Layers = 1;
info.IsDefault = 1;
MG_Pipe::gMGPipeCallbacks.OnSurfaceChanged(&info);
} else
#endif
{
auto* colorTex = static_cast<MG_State::GLState::TextureObject2D*>(defaultFBOInfo->colorAttachment.get());
colorTex->AllocateStorage(
TextureUploadTarget::Texture2D, 0, {
{extentWidth, extentHeight, 1},
defaultAttachmentByteSize}); // TODO: 4 is format size
auto* depthTex = static_cast<MG_State::GLState::TextureObject2D*>(defaultFBOInfo->depthAttachment.get());
depthTex->SetInternalFormat(depthFormat);
depthTex->AllocateStorage(TextureUploadTarget::Texture2D, 0, {
{extentWidth, extentHeight, 1},
defaultAttachmentByteSize}); // TODO: 4 is format size
auto* stencilTex = static_cast<MG_State::GLState::TextureObject2D*>(defaultFBOInfo->stencilAttachment.get());
stencilTex->SetInternalFormat(stencilFormat);
stencilTex->AllocateStorage(TextureUploadTarget::Texture2D, 0, {
{extentWidth, extentHeight, 1},
defaultAttachmentByteSize}); // TODO: 4 is format size
}
}
@@ -11,6 +11,10 @@
#include "MG_Backend/DirectVulkan/DirectVulkanResourceState.h"
#include "MG_State/GLState/Core.h"
#include <MG_Pipe/PipeInputsSwitch.h>
#if MOBILEGL_PIPE_PUSH
// P5c ev: the GPU-write announcement routes through the reverse channel (R2).
#include <MG_Impl/Pipe/ResourceTracker.h>
#endif
#include "MG_State/GLState/ProgramState/ProgramObject.h"
#include "MG_State/GLState/TextureState/TextureObject1D.h"
#include "MG_State/GLState/TextureState/TextureObject2D.h"
@@ -1072,7 +1076,13 @@ namespace MobileGL::MG_Backend::DirectVulkan {
// changed a byte of it.
bufferObject->EnsureGpuResidentStorage();
if (imageBinding.Access != GL_READ_ONLY) {
#if MOBILEGL_PIPE_PUSH
// P5c ev (R2, CONTRACT-P5C §4.2): the announcement goes through the reverse
// channel - the apply thread may not poke the client object directly.
MG_Pipe::MGPipeAnnounceBufferGpuWritten(bufferObject);
#else
bufferObject->MarkGpuWritten();
#endif
}
BufferSlice slice{};
@@ -1228,7 +1238,13 @@ namespace MobileGL::MG_Backend::DirectVulkan {
// results are visible without a readback path, exactly as for a capture buffer.
bufferObject->EnsureGpuResidentStorage();
// ... and the read that follows has to wait for this draw or dispatch to retire.
#if MOBILEGL_PIPE_PUSH
// P5c ev (R2, CONTRACT-P5C §4.2): through the reverse channel, not a direct poke of
// the client object from the apply thread.
MG_Pipe::MGPipeAnnounceBufferGpuWritten(bufferObject);
#else
bufferObject->MarkGpuWritten();
#endif
BufferSlice slice{};
if (!m_bufferManager->AcquireResidentSlice(BufferKind::ShaderStorage, bufferObject, slice) || !slice.IsValid()) {
@@ -10,6 +10,10 @@
#include "MagmaPipeArms.h"
#include "MG_Util/Converters/MGToStr/DataTypeConverter.h"
#include <MG_Backend/BackendObjects.h>
#if MOBILEGL_BUILD_DISAGGREGATED
#include <Config.h>
#include <MG_Remote/Server/ServerLoop.h>
#endif
#include <utility>
namespace MobileGL::MG_Backend::DirectVulkan {
@@ -246,6 +250,16 @@ namespace MobileGL::MG_Backend::DirectVulkan {
// set, a dvec3/dvec4 would be declined by ToVkVertexFormat AND left 64-bit in the
// module, so a float32 stream would be fed to a Float64 input.
const Bool narrowFloat64Arrays =
#if MOBILEGL_BUILD_DISAGGREGATED
// P5c (hd, CONTRACT-P5C §3.7): with an active transport the answer is the
// SERVER's own backend's - the client caps mirror is client memory (rule E).
MG_Config::Transport != MG_Config::TransportMode::Monolith
? (MG_Remote::Server::ServerLoopInstance().Backend() == nullptr ||
!MG_Remote::Server::ServerLoopInstance().Backend()
->GetDynamicParameters()
.SupportsFloat64VertexAttributes)
:
#endif
MG_Backend::pActiveBackendObject == nullptr ||
!MG_Backend::pActiveBackendObject->GetDynamicParameters().SupportsFloat64VertexAttributes;
if (sourceVkFormat == VK_FORMAT_UNDEFINED && attr.Type == DataType::Float64 && narrowFloat64Arrays) {
@@ -499,7 +513,17 @@ namespace MobileGL::MG_Backend::DirectVulkan {
// demoted `vec` input - the same thing DirectGLES does for the same state. The
// frontend RECORDS the format either way, so this gate is the only thing standing
// between a legal glVertexAttribLFormat and a mismatched pipeline.
if (MG_Backend::pActiveBackendObject == nullptr ||
if (
#if MOBILEGL_BUILD_DISAGGREGATED
// P5c (hd, CONTRACT-P5C §3.7): see the narrowFloat64Arrays site above.
MG_Config::Transport != MG_Config::TransportMode::Monolith
? (MG_Remote::Server::ServerLoopInstance().Backend() == nullptr ||
!MG_Remote::Server::ServerLoopInstance().Backend()
->GetDynamicParameters()
.SupportsFloat64VertexAttributes)
:
#endif
MG_Backend::pActiveBackendObject == nullptr ||
!MG_Backend::pActiveBackendObject->GetDynamicParameters().SupportsFloat64VertexAttributes) {
return VK_FORMAT_UNDEFINED;
}
@@ -1744,6 +1744,16 @@ namespace MobileGL::MG_Backend::DirectVulkan {
Bool VkTextureManager::SyncTexture(MG_State::GLState::ITextureObject &texture,
TextureResource &outResource) {
#if MOBILEGL_BUILD_DISAGGREGATED
// P5c (gt): Magma's texture sync still reads - and clears - the CLIENT's mip shadow:
// the dirty scan below, and UploadDirtyMipLevels' texel reads / region reads /
// MarkStorageDirty(false) clears. CONTRACT-P5C §2 migrated Espryt's sync and Magma's
// T5 writes, and left THIS path on the legacy arm; under the verb barrier and one
// address space the reads answer correctly, and the migration is P7's server-side
// sync. The scope is the debt's greppable form (MipmapStorage.h); outside it the
// layer-1 guard still aborts.
const MG_State::GLState::MGPipeTextureLegacyArmScope textureLegacyArm;
#endif
// Cross-draw fast path: if the resource is already built and neither the texture's
// pixel content (bumped in MarkStorageDirty), its SHAPE (bumped in BumpShapeVersion)
// nor its params changed since the last sync, there is nothing to re-check or
@@ -15,6 +15,10 @@
#include "MG_State/GLState/Core.h"
#include <MG_Pipe/PipeInputsSwitch.h>
#if MOBILEGL_PIPE_PUSH
// P5c ev: the GPU-write announcement routes through the reverse channel (R2).
#include <MG_Impl/Pipe/ResourceTracker.h>
#endif
#include "MG_State/GLState/ProgramState/ProgramObject.h"
#include "MG_State/GLState/ProgramState/ShaderObject.h"
#include "MG_State/GLState/SamplerState/SamplerObject.h"
@@ -33,6 +37,13 @@
#include "MG_Util/SelfTest/PrimitivesGeneratedNoXfbProbe.h"
#include "MG_Util/Texture/PixelStoreProcessor.h"
#include <Config.h>
#if MOBILEGL_BUILD_DISAGGREGATED
// P5c (T5 / tx): the server's staged-texture shadow GenerateMipmap defines its chain on.
#include <MG_Remote/Server/StagedTextureStore.h>
#include <MG_Remote/Server/ServerLoop.h>
// P5c (G6): the named-blit arm's endpoint resolution runs inside the frontend-keyed scope.
#include <MG_Impl/Pipe/SlotAllocator.h>
#endif
#include <algorithm>
#include <bit>
#include <cstdlib>
@@ -664,6 +675,23 @@ namespace MobileGL::MG_Backend::DirectVulkan {
static void ApplyLineWidthState(VkCommandBuffer commandBuffer) {
Float lineWidth = MGB_CTX->GetLineWidth();
#if MOBILEGL_BUILD_DISAGGREGATED
// P5c (hd, CONTRACT-P5C §3.7): with an active transport the dynamic parameters are the
// SERVER's own backend's - the client caps mirror is client memory (rule E). Monolith
// reads the mirror as it always did.
if (MG_Config::Transport != MG_Config::TransportMode::Monolith) {
if (MG_Backend::BackendObject* server = MG_Remote::Server::ServerLoopInstance().Backend()) {
const auto& dynamicParameters = server->GetDynamicParameters();
const Float minLineWidth = dynamicParameters.AliasedLineWidthRangeMin;
const Float maxLineWidth = dynamicParameters.AliasedLineWidthRangeMax;
if (lineWidth < minLineWidth) {
lineWidth = minLineWidth;
} else if (lineWidth > maxLineWidth) {
lineWidth = maxLineWidth;
}
}
} else
#endif
if (MG_Backend::pActiveBackendObject != nullptr) {
const auto& dynamicParameters = MG_Backend::pActiveBackendObject->GetDynamicParameters();
const Float minLineWidth = dynamicParameters.AliasedLineWidthRangeMin;
@@ -1608,6 +1636,52 @@ void main() {
return true;
}
#if MOBILEGL_BUILD_DISAGGREGATED
// P5c (T5 / tx): the split arm of EnsureGenerateMipmapStorageAllocated. Under an active
// transport the apply thread may not WRITE the client's level storage - AllocateStorage
// and MarkStorageDirty on a frontend TextureObjectMipmap are §6 layer-1 surfaces
// (CONTRACT-P5C §2.3) - so the generated chain is defined on the SERVER's staged-texture
// shadow instead, keyed by this renderer's own texture twin (the TextureResource,
// node-stable in VkTextureManager's map). Same levels, same extents - derived from the
// Vulkan-space base extent, whose depth is already 1 for every array target (layers
// live in arrayLayers there, so the fixed-component split the GL-space derivation
// needs is unnecessary here; these shadow extents answer in Vulkan space, which every
// consumer of a Magma-keyed entry shares) - and every generated level is marked
// dirty-in-shadow, because its texels are generated on the GPU and no byte answer
// exists on this side. The client's chain is left stale, which §2.3 rules CORRECT: the
// two readers that could observe the staleness are both named refusals under split.
// The upload-target list still comes from the frontend object - a shape READ, the P7
// registry's residual, not one of the writes this arm exists to remove.
static Bool EnsureGenerateMipmapShadowAllocated(const VkTextureManager::TextureResource& resource,
Uint32 baseMipLevel,
const Vector<TextureUploadTarget>& uploadTargets) {
if (resource.mipLevels <= baseMipLevel || uploadTargets.empty()) {
return false;
}
const IntVec3 storageBaseTexelSize = {static_cast<Int>(resource.extent.width),
static_cast<Int>(resource.extent.height),
static_cast<Int>(resource.depth)};
const IntVec3 baseTexelSize = ComputeMipTexelSize(storageBaseTexelSize, baseMipLevel);
if (baseTexelSize.x() <= 0 || baseTexelSize.y() <= 0 || baseTexelSize.z() <= 0) {
return false;
}
const Uint32 requiredMipLevelCount = baseMipLevel + ComputeFullMipLevelCount(baseTexelSize);
auto& store = MG_Remote::Server::ServerStagedTexture();
const Uint64 key = MG_Remote::Server::StagedTextureStore::KeyForTwinAddress(&resource);
for (const auto uploadTarget : uploadTargets) {
for (Uint32 level = baseMipLevel + 1; level < requiredMipLevelCount; ++level) {
// A level the shadow already tracks (an adopted base chain) keeps its bytes;
// the generation made the GPU newer than either, which the mark says.
store.NoteLevelDefined(key, static_cast<Uint16>(uploadTarget), static_cast<Uint16>(level),
ComputeMipTexelSize(storageBaseTexelSize, level));
store.MarkLevelGpuDirty(key, static_cast<Uint16>(uploadTarget), static_cast<Uint16>(level),
true);
}
}
return true;
}
#endif
static VkImageLayout ResolveGenerateMipmapFinalLayout(VkImageAspectFlags aspectMask) {
return (aspectMask & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT)) != 0
? VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL
@@ -4468,6 +4542,17 @@ void main() {
}
void VulkanRenderer::ShutdownBlitResources() {
#if MOBILEGL_BUILD_DISAGGREGATED
// P5c (G6, CONTRACT-P5C §3.1's named exemption): the hidden blit program and samplers
// are FRONTEND objects the server backend created on the apply thread, and under an
// active transport they die here on that same thread. Their destructors run the client
// death helper, whose lifetime-id probe is the frontend-keyed registry family - it
// resolves to nothing (no handle was ever minted for these objects) and routes no
// delete, so the scope admits the probe as named debt rather than letting the guard
// Fatal at server teardown. P7 gives these resources storage that is not a frontend
// object.
const MG_Pipe::MGPipeFrontendKeyedRegistryScope frontendKeyedRegistry;
#endif
m_blitResources = {};
}
@@ -4542,6 +4627,12 @@ void main() {
}
void VulkanRenderer::ShutdownDepthMipmapResources() {
#if MOBILEGL_BUILD_DISAGGREGATED
// Same shape as ShutdownBlitResources above: the hidden depth-mipmap program is a
// frontend object created and destroyed by the server backend on the apply thread, and
// its destructor's lifetime-id probe is admitted here as named debt.
const MG_Pipe::MGPipeFrontendKeyedRegistryScope frontendKeyedRegistry;
#endif
m_depthMipmapResources = {};
}
@@ -8874,6 +8965,53 @@ void main() {
void VulkanRenderer::BlitFramebuffer(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1,
GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1,
GLbitfield mask, GLenum filter) {
#if MOBILEGL_BUILD_DISAGGREGATED
// P5c (G6, CONTRACT-P5C §3.3/§5.4): MAGMA'S NAMED ARM. A blit record whose
// ReadFbo/DrawFbo are non-null is a glBlitNamedFramebuffer: both framebuffers resolve
// from the record's handles, and the sink is told the pair was consumed - a backend
// that leaves the flag clear has no named arm and the verb declines there, loudly.
// Magma has no FBO twin registry (it reads the frontend object wherever it syncs), so
// the resolution here is frontend-keyed - the handle was minted over the frontend
// object's lifetime id, and the two probes below (the client allocator's slot entry
// and the frontend context's framebuffer pool) are named debt inside the scope, the
// same shape as Espryt's StateForHandle arm: P3b/P4b retire it by carrying the object
// identity in the record.
if (MG_Config::Transport != MG_Config::TransportMode::Monolith) {
auto& applierState = MG_Pipe::MGPipeApplier();
const MG_Pipe::MGPipeHandle readHandle = applierState.VerbBlitReadFbo;
const MG_Pipe::MGPipeHandle drawHandle = applierState.VerbBlitDrawFbo;
if (!MG_Pipe::MGPipeHandleIsNull(readHandle) || !MG_Pipe::MGPipeHandleIsNull(drawHandle)) {
const auto resolveEndpoint = [](MG_Pipe::MGPipeHandle handle)
-> SharedPtr<MG_State::GLState::FramebufferObject> {
const MG_Pipe::MGPipeFrontendKeyedRegistryScope frontendKeyedRegistry;
if (handle == MG_Pipe::kMGPipeDefaultFramebuffer) {
return MG_State::pGLContext ? MG_State::pGLContext->GetFramebufferObject(0) : nullptr;
}
if (!MG_Pipe::MGPipeSlots().IsLive(MG_Pipe::MGPipeKind::Framebuffer, handle)) {
return nullptr;
}
const Uint64 lifetimeId =
MG_Pipe::MGPipeSlots().LifetimeIdOfSlot(MG_Pipe::MGPipeKind::Framebuffer, handle.Slot);
if (lifetimeId == 0 || MG_State::pGLContext == nullptr) return nullptr;
return MG_State::pGLContext->FindFramebufferObjectByLifetimeId(lifetimeId);
};
auto readFbo = resolveEndpoint(readHandle);
auto drawFbo = resolveEndpoint(drawHandle);
if (!readFbo || !drawFbo) {
// Leave the pair UNCONSUMED: the sink's decline is the loud answer a
// missing endpoint deserves, not a silent blit of whatever is bound.
MGLOG_E_ONCE("MGPipe: Magma's named blit could not resolve an endpoint (read {%u, %u}, draw "
"{%u, %u}) to a frontend framebuffer; the verb declines at the sink",
readHandle.Slot, readHandle.Gen, drawHandle.Slot, drawHandle.Gen);
return;
}
applierState.VerbBlitNamedConsumed = true;
BlitNamedFramebuffer(readFbo, drawFbo, srcX0, srcY0, srcX1, srcY1, dstX0, dstY0,
dstX1, dstY1, mask, filter);
return;
}
}
#endif
auto readFbo = MGB_CTX->GetFramebufferBindingSlot(FramebufferTarget::Read).GetBoundObject();
auto drawFbo = MGB_CTX->GetFramebufferBindingSlot(FramebufferTarget::Draw).GetBoundObject();
BlitNamedFramebuffer(readFbo, drawFbo, srcX0, srcY0, srcX1, srcY1, dstX0, dstY0, dstX1, dstY1, mask, filter);
@@ -11314,7 +11452,17 @@ void main() {
"GenerateMipmap: depth-stencil mipmap generation is not supported yet.");
}
#if MOBILEGL_BUILD_DISAGGREGATED
// P5c (T5 / tx): under an active transport the generated chain is defined on the
// server's staged shadow (keyed by the synced TextureResource above) and the client's
// level storage is never written; in monolith the client-object path runs unchanged.
const Bool allocatedMipmapStorage =
MG_Config::Transport != MG_Config::TransportMode::Monolith
? EnsureGenerateMipmapShadowAllocated(*resource, baseMipLevel, texture->GetUploadTargets())
: EnsureGenerateMipmapStorageAllocated(*mipmapTexture, baseMipLevel);
#else
const Bool allocatedMipmapStorage = EnsureGenerateMipmapStorageAllocated(*mipmapTexture, baseMipLevel);
#endif
MOBILEGL_ASSERT(allocatedMipmapStorage, "GenerateMipmap could not allocate a full mip chain for this texture.");
resource = m_textureManager->SyncTextureAndGetDescriptor(*texture);
@@ -11615,7 +11763,13 @@ void main() {
// have happened, so the buffer is also flagged for the wait that a later CPU
// read has to perform - the capture is a GPU write like any shader's.
bufferObject->EnsureGpuResidentStorage();
#if MOBILEGL_PIPE_PUSH
// P5c ev (R2, CONTRACT-P5C §4.2): through the reverse channel, not a direct poke
// of the client object from the apply thread.
MG_Pipe::MGPipeAnnounceBufferGpuWritten(bufferObject);
#else
bufferObject->MarkGpuWritten();
#endif
BufferSlice slice{};
if (!m_bufferManager.AcquireResidentSlice(BufferKind::Vertex, bufferObject, slice)) {
MGLOG_E_ONCE("BeginXfbCaptureForDraw: failed to acquire capture buffer %zu", i);
+17
View File
@@ -147,6 +147,23 @@ namespace MobileGL::MG_Pipe {
if (!serverStamped ||
kMGPipeFieldOwnership[static_cast<SizeT>(field)] != MGPipeFieldOwnership::kBarrierPulled ||
!FieldIsInVerbClass(field, verb)) {
// P5c (gt, CONTRACT-P5C §6 layer 1): under a server stamp, a stale read of a field
// whose row is RECORD-SUPPLIED or APPLIER-DERIVED - i.e. a value a pushed record
// DOES carry, read where this verb's stamp does not cover it - is a role violation
// named by its surface, not a generic unmigrated read: the wire already owns the
// answer, so reaching past it into the residual fill is rule E's shape. A
// BARRIER-PULLED field outside the verb's class and a FATAL field keep the poison
// Fatal - those are the stamp table's own verdicts, not a role's overreach.
const MGPipeFieldOwnership ownership = kMGPipeFieldOwnership[static_cast<SizeT>(field)];
if (serverStamped && (ownership == MGPipeFieldOwnership::kRecordSupplied ||
ownership == MGPipeFieldOwnership::kApplierDerived)) {
MGLOG_F("MGPipe: Fatal{RoleViolation, \"%s\"} - the server read this field stale "
"at %s, but a pushed record carries it (the row is %s): the read reached "
"the client's residual fill for a value the wire already owns",
kMGPipeInputFieldNames[static_cast<SizeT>(field)], MGPipeVerbName(verb),
MGPipeFieldOwnershipName(ownership));
std::abort();
}
MGPipeInputPoisonFatalForVerb(field, verb);
}
CountBarrierPull(field, verb);
+29
View File
@@ -13,6 +13,15 @@
// the live context happens on the client side, in MG_Impl/Pipe/PipeFill.cpp.
#include <MG_State/GLState/Core.h>
#if MOBILEGL_BUILD_DISAGGREGATED
// P5c (rv, CONTRACT-P5C.md §5.3): the three texture shutters' server-side answer lives in the
// applier - MGPipeApplierTextureShutterSerial() / MGPipeApplierContextSerial(), declared here
// so the accessors below can answer with them under a server-stamped verb. MG_Pipe is below
// MG_Backend, so this direction is the layering's, and PipeApply.h forward-declares
// PipeInputs rather than including this header, so there is no cycle.
#include <MG_Pipe/PipeApply.h>
#endif
// MOBILEGL_PIPE_POISON: the per-verb generation stamps and the read-side
// Fatal{UnmigratedPipeInput} check. Derived here, once. The repository's debug gate is
// MOBILEGL_LOG_ACTIVE_LEVEL <= MOBILEGL_LOG_LEVEL_DEBUG (Defines.h); the verify CI build is
@@ -471,9 +480,19 @@ namespace MobileGL::MG_Pipe {
MGP_INPUT_VERIFY_READ(MGPipeInputField::GetRenderStateParameters, 0, 0);
return m_renderState;
}
// THE THREE TEXTURE SHUTTERS (P5c rv, CONTRACT-P5C.md §5.3). Their FieldOwnership rows
// have said "a shutter, not a value: the server answers from its own Serial" since P5;
// rv is the edit that makes the accessor DO it. Under a SERVER-STAMPED verb the answer
// is the applier's own serial (APPLIER_DERIVED): server-owned, monotone, moved by every
// applied record that can move what the frontend generation guarded. Everywhere else -
// monolith, a split build on monolith transport, any read outside a stamped verb - the
// storage answer is kept, byte for byte (G1).
Uint64 GetSamplingResolutionGeneration() const {
MGP_INPUT_CHECK(MGPipeInputField::GetSamplingResolutionGeneration);
MGP_INPUT_VERIFY_READ(MGPipeInputField::GetSamplingResolutionGeneration, 0, 0);
#if MOBILEGL_BUILD_DISAGGREGATED
if (m_serverStampedVerb) return MGPipeApplierTextureShutterSerial();
#endif
return m_samplingResolutionGeneration;
}
const IntVec4& GetScissorBox() const {
@@ -489,11 +508,21 @@ namespace MobileGL::MG_Pipe {
Uint64 GetTextureBindGeneration() const {
MGP_INPUT_CHECK(MGPipeInputField::GetTextureBindGeneration);
MGP_INPUT_VERIFY_READ(MGPipeInputField::GetTextureBindGeneration, 0, 0);
#if MOBILEGL_BUILD_DISAGGREGATED
// See GetSamplingResolutionGeneration: the server answers from its own Serial.
if (m_serverStampedVerb) return MGPipeApplierTextureShutterSerial();
#endif
return m_textureBindGeneration;
}
Uint64 GetTextureContextId() const {
MGP_INPUT_CHECK(MGPipeInputField::GetTextureContextId);
MGP_INPUT_VERIFY_READ(MGPipeInputField::GetTextureContextId, 0, 0);
#if MOBILEGL_BUILD_DISAGGREGATED
// A context IDENTITY rather than a generation: stable within the served context,
// moved by every MGPipeApplierReset - which is all the backends' per-context memo
// keys ask of it.
if (m_serverStampedVerb) return MGPipeApplierContextSerial();
#endif
return m_textureContextId;
}
Uint64 GetTransformFeedbackCapturedVertices() const {
+240 -41
View File
@@ -48,6 +48,12 @@
// lanes must keep answering exactly what they answered before.
#include <MG_Remote/Client/CapsMirror.h>
#include <MG_Remote/Client/WireTables.h>
// P5c gt (CONTRACT-P5C §6 layer 2, audit A1): the client-side gPipeInputs check consults
// InBarrierWait() and ApplyThreadIsInsideApplier() - both live here.
#include <MG_Remote/Client/ClientSession.h>
// P5c ev (CONTRACT-P5C §4.2): RecordError's transport arm posts kEventGlError through the
// server session, and InvalidateCompileEnv's forward is deleted with an active transport.
#include <MG_Remote/Server/ServerSession.h>
#endif
#include <atomic>
@@ -529,6 +535,12 @@ namespace MobileGL::MG_Pipe {
// an unrelated frontend write.
void MGPipeNoteFrontendMutation(MGPipeInputField field) {
PipeInputs& inputs = gPipeInputs;
#if MOBILEGL_BUILD_DISAGGREGATED
// P5c (gt, layer 2): the single-field refresh is a client write into gPipeInputs too -
// same gate as the fill.
MG_Remote::Client::ClientSession::RefusePipeInputsTouchWhileApplierOwnsIt(
"MGPipeNoteFrontendMutation");
#endif
auto* ctx = LiveContext();
if (ctx == nullptr) return;
const auto verb = inputs.CurrentVerb();
@@ -662,7 +674,18 @@ namespace MobileGL::MG_Pipe {
// the resource subsystem bit would make the vertex-input subsystem emit null handles
// in exactly the A/B arm that exists to isolate the two. It costs one free-list pop
// and one map insert per buffer object and emits nothing.
//
// The client resource callbacks are MONOLITH-ONLY (CONTRACT-P5C §4.1): with an
// active transport the server session installs its producer callbacks at Accept and
// the client's consumers are invoked by name from DrainEventRing, so installing
// them here would be the double installation the check now aborts on.
#if MOBILEGL_BUILD_DISAGGREGATED
if (MG_Config::Transport == MG_Config::TransportMode::Monolith) {
MGPipeInstallClientResourceCallbacks();
}
#else
MGPipeInstallClientResourceCallbacks();
#endif
MGPipeResourceTrackerInstance().Acquire(buffer);
}
@@ -882,14 +905,20 @@ namespace MobileGL::MG_Pipe {
}
void MGPipeEmitResourceReadback(BufferObject& buffer) {
// Whole-buffer by contract (BufferObject.h: the op pulls the backend's current
// contents for the WHOLE buffer into the shadow). The split arm's slicing lives in
// the CALLER (BufferObject::SyncGpuWrites): what "whole" costs is decided by the
// event ring's capacity, which this layer does not read.
MGPipeEmitResourceReadbackRange(buffer, 0, buffer.GetSize());
}
void MGPipeEmitResourceReadbackRange(BufferObject& buffer, SizeT offset, SizeT size) {
const MGPipeHandle handle = ContentHandleFor(buffer, "resource_readback");
if (MGPipeHandleIsNull(handle)) return;
MGPReadback record{};
record.Res = handle;
// Whole-buffer by contract (BufferObject.h: the op pulls the backend's current
// contents for the WHOLE buffer into the shadow).
record.Offset = 0;
record.Size = buffer.GetSize();
record.Offset = offset;
record.Size = size;
// The answer travels back through MGPipeClientOnBufferWriteback, and the server's
// epoch bump happens AFTER that writeback, never before.
MGPipeRouteResourceReadback(record);
@@ -1752,6 +1781,16 @@ namespace MobileGL::MG_Pipe {
void PipeInputs::InvalidateCompileEnv() {
MGP_STICKY_FORWARD_PULL(InvalidateCompileEnv);
#if MOBILEGL_BUILD_DISAGGREGATED
if (MG_Config::Transport != MG_Config::TransportMode::Monolith) {
// DELETED with an active transport (CONTRACT-P5C §4.2): R-12's caps
// re-publication already invalidates the CLIENT's compile environment when the
// second snapshot arrives (CapsMirror.cpp:78-80), and this forward is a write
// into the frontend with no wire shape. A caller that still needs it under a
// transport is a defect to fix, not a pull to serve.
return;
}
#endif
if (auto* ctx = LiveContext()) ctx->InvalidateCompileEnv();
}
@@ -1763,6 +1802,20 @@ namespace MobileGL::MG_Pipe {
void PipeInputs::RecordError(ErrorCode code, UniquePtr<ErrorInfo> info) {
MGP_STICKY_FORWARD_PULL(RecordError);
#if MOBILEGL_BUILD_DISAGGREGATED
if (MG_Config::Transport != MG_Config::TransportMode::Monolith) {
// The error queue is CLIENT state and the apply thread may not write it (R4).
// kEventGlError carries the code and the message; the client records it into its
// own queue at the next drain point. ORDERING IS P9's (CONTRACT-P5C §4.2): the
// event is observed at the next EmitAndWait drain, which preserves per-thread
// program order of error-then-read but not cross-verb interleaving - the
// accepted P5c shape, stated in the contract rather than discovered in P6.
const String message = info != nullptr ? info->toString() : String{};
MG_Remote::Server::ServerSessionInstance().PostGlError(static_cast<Uint32>(code),
message.c_str());
return;
}
#endif
auto* ctx = LiveContext();
if (ctx == nullptr) {
MGLOG_E_ONCE("PipeInputs::RecordError: no live context, dropping error %d", static_cast<int>(code));
@@ -1789,6 +1842,11 @@ namespace MobileGL::MG_Pipe {
void MGPipeLeaveVerb() {
PipeInputs& inputs = gPipeInputs;
#if MOBILEGL_BUILD_DISAGGREGATED
// Same layer-2 gate as the fill: the serial bump and the verb reset below are writes
// into gPipeInputs (gt).
MG_Remote::Client::ClientSession::RefusePipeInputsTouchWhileApplierOwnsIt("MGPipeLeaveVerb");
#endif
#if MOBILEGL_PIPE_POISON
// 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.
@@ -1848,6 +1906,11 @@ namespace MobileGL::MG_Pipe {
case MGPipeFieldEmitter::SetDrawProgram:
case MGPipeFieldEmitter::SetDispatchProgram:
return kMGPipeSubsystemPrograms;
// P5c rv (CONTRACT-P5C.md §5.3): the residual-value record rides the residual
// subsystem - the one family with no dirty bit of its own, which is why its
// emission gate is the subsystem bit plus the whole-record hash and nothing else.
case MGPipeFieldEmitter::SetContextValues:
return kMGPipeSubsystemResidualValues;
case MGPipeFieldEmitter::kNone:
break;
}
@@ -2024,10 +2087,15 @@ namespace MobileGL::MG_Pipe {
// commit, not at the merge, and no file is touched twice.
//
// The sampler bit covers SamplerEmit.h AND ImageEmit.h: one family, one A/B.
// P5c rv: the residual subsystem joins the wired mask for set_context_values - the
// record's emission is NOT gated on a dirty bit (there is none for the family,
// NoDirtyBitOwnsTheResidualSubsystem says so), so this bit is what the residual-fill
// skip consults for the eight fields the record supplies.
constexpr Uint64 kMGPipeWiredSubsystems = kMGPipeSubsystemRenderState |
kMGPipeSubsystemPixelPack |
kMGPipeSubsystemPatchState |
kMGPipeSubsystemVertexAttribDefaults |
kMGPipeSubsystemResidualValues |
kMGPipeSubsystemResources |
kMGPipeSubsystemVertexInput |
kMGPipeWiredFramebufferSubsystem |
@@ -2059,17 +2127,6 @@ namespace MobileGL::MG_Pipe {
// (ARCHITECTURE.md 4.6 D5, MGPipeTypes.h). The unpack half has no carrier at all,
// so the field keeps being pulled and the verify comparator keeps proving it.
//
// GetCurrentVertexAttribute's three views are NOT bit-identical: GLContext
// CONVERTS between them (SetCurrentVertexAttributeFloat writes (Int32)value into
// intValue), while MGPipeApplySetVertexAttribDefaults (package A's) memcpys one
// Data[4] into all three views and ignores MGPAttribValue::ValueClass. The CLIENT
// half of that is fixed - the call now carries the class the frontend actually
// wrote and that class's own bytes - but the APPLIER still cannot reproduce the
// conversion, so this row stays SHAPE-ONLY: the field keeps being pulled, and
// retiring that pull is blocked on A teaching the applier to switch on
// ValueClass. EmitVertexAttribDefaults checks rather than trusts, and repairs the
// mirror when the applier's write does not reproduce the value.
//
// GetBoundVertexArray is P3a's row, and Coverage.def asks for the decision to be
// taken HERE, deliberately, rather than inherited from the row's presence. THE
// ANSWER IS NO, and it is not a matter of degree: the field's storage is a
@@ -2099,25 +2156,21 @@ namespace MobileGL::MG_Pipe {
// null on every draw of every push build. What retires them is not a better
// applier, it is the phase where the backend stops reading a frontend object.
//
// GetMaxTouchedTextureUnit is the sixth and its argument is different, which is
// why it is written out: it is a plain Int, and set_sampler_views' Count IS that
// value plus one. But the set is SUPPRESSED on an unchanged content hash and is
// emitted only when NEW_SAMPLER_VIEWS fires, and that bit's shutter -
// Mix(textureContent, GetTextureBindGeneration()) - does NOT move on a redundant
// re-bind of the object a unit already holds, while the high-water mark DOES. So
// the applier's Count can lag the frontend's mark by exactly the case the
// suppressor exists to swallow, and the field keeps being pulled.
// GetMaxTouchedTextureUnit was the sixth and its argument was different - a plain
// Int whose carrier (set_sampler_views' Count) is hash-suppressed while the
// high-water mark still moves on a redundant re-bind. P5c rv RETIRED it from this
// list (CONTRACT-P5C.md §5.3): set_context_values carries the mark as a VALUE of
// its own, whole-record suppressed, so the lag the suppressor could introduce is
// gone and the derivation's RECORD_SUPPLIED answer is honest.
constexpr Bool EmittedCallSuppliesTheWholeField(MGPipeInputField field) {
switch (field) {
case MGPipeInputField::GetPixelStoreParameters:
case MGPipeInputField::GetCurrentVertexAttribute:
case MGPipeInputField::GetBoundVertexArray:
case MGPipeInputField::GetFramebufferBindingSlot:
case MGPipeInputField::GetImageTextureBinding:
case MGPipeInputField::GetTextureUnitObject:
case MGPipeInputField::GetProgramForDraw:
case MGPipeInputField::GetProgramForDispatch:
case MGPipeInputField::GetMaxTouchedTextureUnit:
return false;
default:
return true;
@@ -2137,6 +2190,16 @@ namespace MobileGL::MG_Pipe {
case MGPipeInputField::GetPatchDefaultOuterLevel:
case MGPipeInputField::GetPatchDefaultInnerLevel:
case MGPipeInputField::GetCurrentVertexAttribute:
// P5c rv's eight: MGPipeApplySetContextValues writes them out of the record,
// field for field, through MGPipeApplyAccess::SetContextValues.
case MGPipeInputField::GetActiveTextureUnit:
case MGPipeInputField::GetMaxTouchedTextureUnit:
case MGPipeInputField::GetTouchedBufferBindingPointCount:
case MGPipeInputField::IsTransformFeedbackActive:
case MGPipeInputField::IsTransformFeedbackPaused:
case MGPipeInputField::GetTransformFeedbackGeneration:
case MGPipeInputField::GetBoundTransformFeedbackLifetimeId:
case MGPipeInputField::GetTransformFeedbackCapturedVertices:
return true;
default:
return false;
@@ -2218,15 +2281,18 @@ namespace MobileGL::MG_Pipe {
// when the hash has not moved. That is coalescing rule 4, and this is its one wired
// consumer in P2.
//
// THE PAYLOAD AND ITS ONE MISSING HALF. A CurrentVertexAttributeValue is one value in
// three views, and GLContext CONVERTS between them numerically, so "the bytes of one
// view" is not the value: glVertexAttrib4f(loc, 1.5f, ...) leaves 1 in intValue and
// 0x3FC00000 in floatValue, and every glVertexAttribI4i/ui is a different pair again.
// MGPAttribValue carries ValueClass for exactly this reason, so the client sends the
// class the frontend actually wrote (GLContext::GetCurrentVertexAttributeClass) and
// THAT class's own four words. What is still missing is the other half:
// MGPipeApplySetVertexAttribDefaults (package A's file) memcpys the four words into
// all three views regardless of ValueClass, which cannot reproduce the conversion.
// THE PAYLOAD, SINCE P5c rv (CONTRACT-P5C.md §5.3). A CurrentVertexAttributeValue is
// one value in three views, and GLContext CONVERTS between them numerically, so "the
// bytes of one view" is not the value: glVertexAttrib4f(loc, 1.5f, ...) leaves 1 in
// intValue and 0x3FC00000 in floatValue, and every glVertexAttribI4i/ui is a different
// pair again. MGPAttribValue now carries all three views VERBATIM
// (FloatView/IntView/UintView) plus the class the frontend actually wrote
// (GLContext::GetCurrentVertexAttributeClass), and MGPipeApplySetVertexAttribDefaults
// writes each view from its own array - the cross-view conversion's authoritative
// answer is the client's, and the applier no longer reconverts anything. The pre-rv
// shape (one Data[4] memcpied into all three views, ValueClass ignored) is exactly
// what kept this row EMITTED-AND-STILL-PULLED in EmittedCallSuppliesTheWholeField;
// with the applier fixed, the field is RECORD_SUPPLIED outright.
//
// The suppressing memcmp below is over the three VIEWS only, and that is not an
// oversight: the class decides how the views are REBUILT, so two writes that leave
@@ -2239,8 +2305,9 @@ namespace MobileGL::MG_Pipe {
// and says so once. That is what keeps the block correct in the window this call used
// to corrupt - a glVertexAttrib4f followed by a non-kDraw verb, where the residual
// fill does not run for this field and nothing else would have put the value back.
// The day the applier honours ValueClass the compare stops failing and the repair
// stops happening, with no edit here.
// Since rv the applier writes all three views verbatim, so the compare below is
// expected to pass on every emission; it stays armed because it is the one observable
// of that write being verbatim in a window no other gate looks at.
Uint64 g_attribDefaultRepairs = 0;
// The header of the last set_vertex_attrib_defaults that actually went out. Count == 0
@@ -2311,14 +2378,73 @@ namespace MobileGL::MG_Pipe {
}
if (!reproduced) {
++g_attribDefaultRepairs;
MGLOG_W_ONCE("MGPipe: MGPipeApplySetVertexAttribDefaults does not reproduce the "
"carried value on this build (it ignores MGPAttribValue::ValueClass) "
"- the client is keeping m_currentVertexAttribute authoritative");
MGLOG_W_ONCE("MGPipe: MGPipeApplySetVertexAttribDefaults did not reproduce the "
"carried three views on this build - the client is keeping "
"m_currentVertexAttribute authoritative");
MGPipeFillAccess::CopyField(gPipeInputs, ctx, MGPipeInputField::GetCurrentVertexAttribute);
}
return sizeof(MGPVertexAttribDefaults) + header.Count * sizeof(MGPAttribValue);
}
#if MOBILEGL_BUILD_DISAGGREGATED
// set_context_values (P5c rv, CONTRACT-P5C.md §5.3): the residual-value record. One
// POD carrying every value-class field no other set_* supplies - the two texture-unit
// counters, the 15 per-target touched-buffer-binding counts and the five XFB values -
// emitted at validate WHEN ANY COVERED VALUE MOVED, which the whole-record hash says:
// there is deliberately no dirty bit for the family (the tracker's value-class dirty
// accounting is untouched - "零新增记账", ARCHITECTURE.md 5.2) and no dirty mask in the
// payload, so a suppressed record means "nothing moved", never "field invalid" (§1).
//
// THE PRODUCER IS TRANSPORT-GATED, and the residual-fill skip for the same eight fields
// is gated on the same answer (MGPipeValidateForVerb's contextValuesWireLive): under
// monolith - or with a transport configured but no live session (the bring-up window, a
// server-role-only fixture) - nothing is emitted and the fields keep being pulled, byte
// for byte as before (G1).
Uint64 EmitContextValues(GLContext& ctx) {
MGPContextValues values{};
values.ActiveTextureUnit = static_cast<Uint32>(ctx.GetActiveTextureUnit());
values.MaxTouchedTextureUnit = static_cast<Uint32>(ctx.GetMaxTouchedTextureUnit());
// The array is indexed by BufferTarget value, all 15 of them (MGPipeTypes.h);
// targets with no binding points answer 0 (BufferState::GetTouchedBindPointCount).
static_assert(
std::extent_v<decltype(MGPContextValues::TouchedBufferBindingPointCount)> ==
static_cast<SizeT>(BufferTarget::BufferTargetCount),
"MGPContextValues' per-target array and BufferTargetCount have drifted");
for (Uint32 t = 0; t < static_cast<Uint32>(BufferTarget::BufferTargetCount); ++t) {
values.TouchedBufferBindingPointCount[t] =
static_cast<Uint32>(ctx.GetTouchedBufferBindingPointCount(static_cast<BufferTarget>(t)));
}
values.IsTransformFeedbackActive = ctx.IsTransformFeedbackActive() ? 1 : 0;
values.IsTransformFeedbackPaused = ctx.IsTransformFeedbackPaused() ? 1 : 0;
values.TransformFeedbackGeneration = ctx.GetTransformFeedbackGeneration();
values.BoundTransformFeedbackLifetimeId = ctx.GetBoundTransformFeedbackLifetimeId();
values.TransformFeedbackCapturedVertices = ctx.GetTransformFeedbackCapturedVertices();
// The whole record is the hash input, padding included - `values{}` zeroes it, so
// the pad bytes are defined and the hash is stable.
const Uint64 contentHash = XXH64(&values, sizeof(values), 0);
if (!MGPipeSetHashSuppressorInstance().ShouldEmit(MGPipeSuppressorSlot::SetContextValues,
contentHash)) {
return 0;
}
MGPipeRouteSetContextValues(values);
return sizeof(MGPContextValues);
}
// The fields set_context_values supplies. A validate whose verb class reads NONE of
// them skips the record build entirely - the record exists so a verb's reads are
// answered, and a verb that never reads them needs no publication.
constexpr Bool VerbMaskReadsContextValues(const MGPipeFieldMask& mask) {
return MGPipeFieldMaskHas(mask, MGPipeInputField::GetActiveTextureUnit) ||
MGPipeFieldMaskHas(mask, MGPipeInputField::GetMaxTouchedTextureUnit) ||
MGPipeFieldMaskHas(mask, MGPipeInputField::GetTouchedBufferBindingPointCount) ||
MGPipeFieldMaskHas(mask, MGPipeInputField::IsTransformFeedbackActive) ||
MGPipeFieldMaskHas(mask, MGPipeInputField::IsTransformFeedbackPaused) ||
MGPipeFieldMaskHas(mask, MGPipeInputField::GetTransformFeedbackGeneration) ||
MGPipeFieldMaskHas(mask, MGPipeInputField::GetBoundTransformFeedbackLifetimeId) ||
MGPipeFieldMaskHas(mask, MGPipeInputField::GetTransformFeedbackCapturedVertices);
}
#endif
// set_residual_value_state (P2 brief D9, ARCHITECTURE.md 9.4).
//
@@ -2551,6 +2677,15 @@ namespace MobileGL::MG_Pipe {
// ---- the validate point (P2 brief D1) ----
void MGPipeValidateForVerb(MGPipeVerb verb) {
PipeInputs& inputs = gPipeInputs;
#if MOBILEGL_BUILD_DISAGGREGATED
// P5c (gt, CONTRACT-P5C §6 layer 2): the residual fill is THE client-side write into
// gPipeInputs, and it is legal only because it runs before the record is published -
// under an armed barrier the apply thread's in-applier flag is provably down here. If
// that ever stops being true this is the check that says so, rather than the applier
// reading a half-written fill.
MG_Remote::Client::ClientSession::RefusePipeInputsTouchWhileApplierOwnsIt(
"MGPipeValidateForVerb");
#endif
ParsePoisonOmissionKnob();
#if MOBILEGL_PIPE_VERIFY
ArmVerify();
@@ -2631,6 +2766,19 @@ namespace MobileGL::MG_Pipe {
// emission the server refuses is an emission whose acceptance already cleared a frontend
// dirty flag the legacy arm still owed. Same table, same four families, one place.
const Uint64 pushMask = MG_Config::Features.PipePush;
#if MOBILEGL_BUILD_DISAGGREGATED
// P5c rv (CONTRACT-P5C.md §5.3): set_context_values is the carrier for the eight
// value-class fields ONLY with a live wire. ONE answer gates both halves - the emission
// below and the residual-fill skip in step 4 - so they can never disagree about who
// supplies a field: with no live session (a monolith transport, the bring-up window, a
// server-role-only fixture) nothing is emitted and the fields keep being pulled, byte
// for byte as before (G1).
const Bool contextValuesWireLive =
MG_Config::Transport != MG_Config::TransportMode::Monolith &&
MG_Remote::Client::ContextValuesWireLive();
#else
constexpr Bool contextValuesWireLive = false;
#endif
const auto wants = [&](MGPipeDirty bit) {
const Uint64 subsystem = MGPipeSubsystemForDirty(bit);
return subsystem != 0 && (pushMask & subsystem) != 0 &&
@@ -2652,8 +2800,38 @@ namespace MobileGL::MG_Pipe {
// - what the server has is no longer what any suppressor slot last emitted;
// - and the residual block owes a fresh publication whatever else moved.
if (tracker.FreshlyPrimed()) {
#if MOBILEGL_BUILD_DISAGGREGATED
// P5c (ct), CONTRACT-P5C.md §5.1: with an active transport the server's reset
// crosses AS A RECORD, ahead of every reset below - the client-side ones (the CSO
// cache, the hash suppressor, the vertex-input emitter) and the emitters' latches
// - because the record's barrier is what orders the server's MGPipeApplierReset()
// against every verb that follows. The GL-thread direct call it replaces is
// Fatal{RoleViolation, "g_applier"} inside MGPipeApplierReset itself (§6 layer 2),
// so reverting this arm to the direct call goes red by name rather than rendering
// stale. Monolith keeps the direct call, byte for byte (G1).
//
// THE APPLY THREAD IS EXCLUDED (M5's rule): a validate running on the server's own
// thread produces no client record - EmitAndWait there would wait on the thread
// that has to apply the record - and the direct call is exactly what the apply
// thread is allowed to make (the sink's own path runs it there).
//
// AND A CONFIGURED-BUT-WIRELESS TRANSPORT TAKES THE DIRECT CALL TOO:
// EmitApplierResetRecord answers false when no live session could carry the
// record (the pre-Start bring-up window, a ServerLoop fixture with no client at
// all), and in that shape this process IS the only place the reset can run.
const Bool transportActive =
MG_Config::Transport != MG_Config::TransportMode::Monolith &&
!MG_Remote::Client::RunsAsTheServerRole();
Bool resetCrossed = false;
if (transportActive) {
resetCrossed = MG_Remote::Client::EmitApplierResetRecord();
}
#endif
MGPipeCsoCacheInstance().Reset();
MGPipeApplierReset();
#if MOBILEGL_BUILD_DISAGGREGATED
if (!resetCrossed)
#endif
MGPipeApplierReset();
MGPipeSetHashSuppressorInstance().InvalidateAll();
// P3a: and the vertex-input emitter's latches. NOT because the applier dropped
// its vertex-elements records - it does not, they are share-group object state
@@ -2740,6 +2918,19 @@ namespace MobileGL::MG_Pipe {
payloadBytes += EmitVertexAttribDefaults(*ctx, tracker.FreshlyPrimed());
}
#if MOBILEGL_BUILD_DISAGGREGATED
// P5c rv (CONTRACT-P5C.md §5.3): the residual-value record, emitted when any covered
// value moved. THE GATE IS THE SUBSYSTEM BIT PLUS THE WIRE BEING LIVE - the family has
// no dirty bit (NoDirtyBitOwnsTheResidualSubsystem) and no P4a consumer predicate (it
// is not one of the four families), and the "did anything move" question is the
// whole-record hash inside EmitContextValues. The class-mask test skips the build for
// verbs that read none of the eight fields.
if (contextValuesWireLive && (pushMask & kMGPipeSubsystemResidualValues) != 0 &&
VerbMaskReadsContextValues(mask)) {
payloadBytes += EmitContextValues(*ctx);
}
#endif
// P3a's vertex segment, in the order the design fixes: vertex elements, then the
// vertex buffers that fill them, then the index binding. All three are LIVE now (m1):
// bits 5 / 9 / 10 map onto kMGPipeSubsystemVertexInput in Tracker.h:145-148 and all
@@ -2789,12 +2980,20 @@ namespace MobileGL::MG_Pipe {
// FIELD, and on a backend with no consumer - or at a mask that leaves one of the
// family's D-K2 dependency bits clear - no P4a call went out at all, so withholding
// the pull here would leave the field unfilled at the very verb that reads it.
//
// AND THE LAST CONJUNCT IS P5c rv's (CONTRACT-P5C.md §5.3): set_context_values has
// NO PRODUCER without a live wire (its emission is transport-gated, above), so its
// eight fields keep being pulled under monolith - G1's byte-for-byte rule - and are
// skipped only when the record really crosses. The two sides read the ONE answer
// computed at the top of this function, so they cannot disagree.
const Bool supplied = subsystem != 0 && (subsystem & kMGPipeWiredSubsystems) != 0 &&
(pushMask & subsystem) != 0 &&
P4aFamilyHasItsConsumer(subsystem) &&
P4aFamilyDependenciesAreSet(subsystem, pushMask) &&
EmittedCallSuppliesTheWholeField(field) &&
(applierDerives || AppliedWithoutDerivation(field));
(applierDerives || AppliedWithoutDerivation(field)) &&
(emitter != MGPipeFieldEmitter::SetContextValues ||
contextValuesWireLive);
if (!supplied) MGPipeFillAccess::CopyField(inputs, *ctx, field);
#if MOBILEGL_PIPE_POISON
// The value is copied either way; only the stamp is withheld for the omitted pair.
+4 -2
View File
@@ -113,8 +113,10 @@ namespace MobileGL::MG_Pipe {
// (EmitVertexAttribDefaults). It is the ONE observable of that repair: the window it
// covers is a verb whose class does not read m_currentVertexAttribute, where reading the
// storage to check it would be the poison violation the fill table exists to forbid. So
// TrackerShippedEmitter asserts on this counter instead, and the day package A's applier
// switches on MGPAttribValue::ValueClass the counter stops moving.
// TrackerShippedEmitter asserts on this counter instead. Since P5c rv the record carries
// all three views verbatim (CONTRACT-P5C.md §5.3) and the applier writes each from its own
// array, so the counter is expected to stay at 0 - the check that increments it is the
// trip wire that remains.
//
// Not hot-path instrumentation: it is incremented only inside the repair branch, which
// runs only when the call actually went out, which is only when an attribute default
+141 -16
View File
@@ -49,7 +49,16 @@
#include <Config.h>
#if MOBILEGL_BUILD_DISAGGREGATED
// P5c ev (CONTRACT-P5C §4.3): the writeback consumer's SEG_EVENT arm resolves the blobref
// through the client session's own SegmentTable, and the transport check below is the same
// MG_Config::Transport probe PipeFill.cpp uses. Behind the build option for G1's reason -
// nothing under MG_Remote may be reachable from a pull build.
#include <MG_Remote/Client/ClientSession.h>
#endif
#include <cstdint>
#include <cstdlib>
namespace MobileGL::MG_Pipe {
@@ -550,6 +559,19 @@ namespace MobileGL::MG_Pipe {
// The client resolves the handle to its own object and writes the shadow; the epoch bump
// stays SERVER-side and happens AFTER this returns, never before (ARCHITECTURE.md 7.4:
// the reverse channel needs the same ordering guarantee as the forward one).
//
// THE BLOBREF'S THREE ARMS (CONTRACT-P5C §4.3, replacing the P3a monolith guard that
// rejected every Seg != kMGHostSpanSegNone and would have dropped every writeback EVENT
// on arrival):
// Seg == kSegEvent -> the wire shape (CONTRACT-P5C §1's reverse-channel row):
// Offset is the byte offset of the inline payload inside
// SEG_EVENT, resolved through the client session's OWN
// SegmentTable, bounds-checked against the announced size;
// Seg == kMGHostSpanSegNone -> monolith only: Offset IS the backend's mapped address
// (MGPipeTypes.h says so in as many words). With an active
// transport this is rule B in the reverse direction and is
// Fatal{ProtocolCorruption, "OnBufferWriteback.Seg"};
// anything else -> the same Fatal.
inline void MGPipeClientOnBufferWriteback(MGPipeHandle res, Uint64 offset, MGPBlobRef bytes) {
auto* buffer = MGPipeResourceTrackerInstance().Resolve(res);
if (buffer == nullptr) {
@@ -557,18 +579,62 @@ namespace MobileGL::MG_Pipe {
res.Slot, res.Gen);
return;
}
if (bytes.Seg != kMGHostSpanSegNone) {
MGLOG_E_ONCE("MGPipe: OnBufferWriteback carried a transport segment (%u); P3a is monolith only",
void* bytePtr = nullptr;
if (bytes.Seg == kMGHostSpanSegNone) {
#if MOBILEGL_BUILD_DISAGGREGATED
if (MG_Config::Transport != MG_Config::TransportMode::Monolith) {
MGLOG_F("MGPipe: Fatal{ProtocolCorruption, \"OnBufferWriteback.Seg\"} - a "
"writeback blobref carried Seg = kMGHostSpanSegNone (a raw host "
"address) with an active transport. Rule B binds the reverse "
"direction exactly as it binds MGHostSpan: on the wire the blobref "
"names SEG_EVENT and an in-segment offset, never a host address");
std::abort();
}
#endif
bytePtr = reinterpret_cast<void*>(static_cast<std::uintptr_t>(bytes.Offset));
}
#if MOBILEGL_BUILD_DISAGGREGATED
else if (bytes.Seg == MG_Remote::Wire::kSegEvent) {
// Size == 0 with a live resource is legal - a zero-length writeback
// (CONTRACT-P5C §1) - and SegmentTable::Resolve answers nullptr for a zero size,
// so only a non-empty run goes through the bounds-checked resolve.
if (bytes.Size != 0) {
auto* session = MG_Remote::Client::ClientSession::Active();
const void* resolved =
session == nullptr
? nullptr
: session->Segments().Resolve(MG_Remote::Wire::kSegEvent, bytes.Offset,
bytes.Size);
if (resolved == nullptr) {
MGLOG_F("MGPipe: Fatal{ProtocolCorruption, \"OnBufferWriteback.Offset\"} - "
"the writeback blobref's {%llu + %llu} does not resolve inside the "
"session's SEG_EVENT segment",
static_cast<unsigned long long>(bytes.Offset),
static_cast<unsigned long long>(bytes.Size));
std::abort();
}
bytePtr = const_cast<void*>(resolved);
}
} else {
MGLOG_F("MGPipe: Fatal{ProtocolCorruption, \"OnBufferWriteback.Seg\"} - a writeback "
"blobref carried Seg %u, which is neither kMGHostSpanSegNone (monolith) nor "
"kSegEvent (the wire shape)",
bytes.Seg);
std::abort();
}
#else
else {
// The pre-P5c guard's monolith spelling, kept for builds with no transport layer:
// a segment tag cannot legitimately arrive here and the write must not be made
// from a null pointer.
MGLOG_E_ONCE("MGPipe: OnBufferWriteback carried a transport segment (%u) in a build "
"with no transport; the writeback is dropped",
bytes.Seg);
return;
}
// Monolith: Seg is kMGHostSpanSegNone and Offset IS the address of the backend's
// mapped bytes (MGPipeTypes.h says so in as many words). Under a transport the
// segment resolves first, and that is the phase's edit, not this one's.
buffer->WritebackFromBackend(
DataPtr{reinterpret_cast<void*>(static_cast<std::uintptr_t>(bytes.Offset)),
static_cast<SizeT>(bytes.Size)},
static_cast<SizeT>(offset));
#endif
buffer->WritebackFromBackend(DataPtr{bytePtr, static_cast<SizeT>(bytes.Size)},
static_cast<SizeT>(offset));
}
// A draw or dispatch wrote these ranges. ARCHITECTURE.md 7.1 calls this a NARROWING
@@ -600,16 +666,75 @@ namespace MobileGL::MG_Pipe {
buffer->MarkGpuWritten();
}
// Installed once, and never over an entry a backend already claimed: these two are the
// CLIENT's implementations of a backend -> frontend callback, so the backend installs
// the rest of the table and these two answer for it.
// MONOLITH ONLY (CONTRACT-P5C §4.1): with an active transport the three reverse entries
// of gMGPipeCallbacks are the SERVER session's producer callbacks and the client
// consumers are invoked BY NAME from DrainEventRing - the global table is a
// producer-side surface under split. The caller (MGPipeMintResourceHandle) gates on the
// resolved transport, exactly as PipeFill.cpp's other transport arms do.
//
// Installed over only an EMPTY or OUR OWN entry: writing over one somebody else claimed
// is Fatal{RoleViolation, "callback-double-install"} - the "never over an entry a
// backend already claimed" comment, made a check. Finding our own function is the
// idempotent repeat this helper runs once per buffer mint, not a second installation.
inline void MGPipeInstallClientResourceCallbacks() {
if (gMGPipeCallbacks.OnBufferWriteback == nullptr) {
gMGPipeCallbacks.OnBufferWriteback = &MGPipeClientOnBufferWriteback;
}
const auto install = [](auto& entry, auto* fn, const char* name) {
if (entry != nullptr && entry != fn) {
MGLOG_F("MGPipe: Fatal{RoleViolation, \"callback-double-install\"} - %s is "
"already claimed by a different function. With an active transport "
"the reverse entries are the server session's producers; the client "
"installs them under monolith only",
name);
std::abort();
}
entry = fn;
};
install(gMGPipeCallbacks.OnBufferWriteback, &MGPipeClientOnBufferWriteback,
"OnBufferWriteback");
install(gMGPipeCallbacks.OnGpuWritten, &MGPipeClientOnGpuWritten, "OnGpuWritten");
}
// The GPU-write announcement for a buffer the backend holds only a FRONTEND POINTER to -
// Magma's barrier-pulled binding-point reads (UniformManager / VulkanRenderer), whose
// direct bufferObject->MarkGpuWritten() was the apply thread poking client memory (R2).
// Routed through the reverse channel exactly as DirectGLES' MarkBufferGpuWritten routes
// its own sites: ONE whole-buffer range, stated rather than implied (zero ranges is the
// shape a fully narrowed announcement will legitimately have at P8/P9, and the two must
// not be the same record). The handle comes from the client allocator's lifetime-id
// probe - the mint is unconditional at the BufferObject constructor
// (MGPipeMintResourceHandle), so a live buffer always has one.
//
// The fallback is the monolith shape, preserved byte for byte: no reverse channel
// installed (a pull-arm build, or a process with no session) pokes the object directly,
// which is exactly what these sites did before. A MISSING HANDLE with a live channel is
// loud rather than a silent drop, the same choice MarkBufferGpuWritten makes.
inline void MGPipeAnnounceBufferGpuWritten(
const SharedPtr<MG_State::GLState::BufferObject>& bufferObject) {
if (bufferObject == nullptr) return;
if (gMGPipeCallbacks.OnGpuWritten == nullptr) {
gMGPipeCallbacks.OnGpuWritten = &MGPipeClientOnGpuWritten;
bufferObject->MarkGpuWritten();
return;
}
const MGPipeHandle res = [&]() {
#if MOBILEGL_BUILD_DISAGGREGATED
// CONTRACT-P5C §3.1's named exemption, Magma's half: the binding records that
// would carry this buffer's handle are P4b's to emit and Magma's server-side
// binding table is P7's, so until then the probe runs inside the scope - the
// debt's named, greppable form rather than a silent guard removal.
const MGPipeReverseAnnouncementScope reverseAnnouncement;
#endif
return MGPipeSlots().FindByLifetimeId(MGPipeKind::Buffer, bufferObject->GetLifetimeId());
}();
if (MGPipeHandleIsNull(res)) {
MGLOG_E_ONCE("MGPipe: no handle for the GPU-write announcement of buffer %u - the "
"reverse channel is installed but the mint is missing, so the mark "
"would be dropped at the consumer; poking the object directly rather "
"than losing it",
bufferObject->GetExternalIndex());
bufferObject->MarkGpuWritten();
return;
}
const MGPRange whole{0, kMGPipeWholeBuffer};
gMGPipeCallbacks.OnGpuWritten(res, 1, &whole);
}
} // namespace MobileGL::MG_Pipe
#endif // MOBILEGL_PIPE_PUSH
+9 -1
View File
@@ -45,7 +45,9 @@ namespace MobileGL::MG_Pipe {
// One slot per kVarTail set_* (ARCHITECTURE.md 5.1's call list), PLUS
// SetFramebufferState, which is not kVarTail at all: MGPFramebufferState carries a
// ContentHash for TWO jobs - the server's render-pass memo key and the client's emission
// suppressor - and the second one needs a slot here like any other. The enum is
// suppressor - and the second one needs a slot here like any other, PLUS
// SetContextValues (P5c rv), also not kVarTail: one fixed-width POD whose whole-record
// hash is the "did any covered value move" answer. The enum is
// CLIENT-ONLY and is not a wire opcode, so appending before Count is safe.
enum class MGPipeSuppressorSlot : Uint32 {
SetVertexBuffers = 0, // P3a - wired, and its hash includes BaseInstance
@@ -64,6 +66,12 @@ namespace MobileGL::MG_Pipe {
SetStreamOutputTargets, // P4b
SetVertexAttribDefaults, // P2 - the one consumer that is wired
SetFramebufferState, // P4a - wired
// P5c rv (CONTRACT-P5C.md §5.3). NOT kVarTail either - the same shape as
// SetFramebufferState's note: MGPContextValues is one fixed-width POD, and the
// whole-record hash IS its "did any covered value move" answer (there is deliberately
// no dirty mask in the payload - a suppressed record means "nothing moved", never
// "field invalid").
SetContextValues, // P5c rv - wired, split+transport only (PipeFill.cpp gates)
Count,
};
+69
View File
@@ -9,7 +9,67 @@
// SlotAllocator.h. Compiled only under MOBILEGL_PIPE_PUSH.
#include <MG_Impl/Pipe/SlotAllocator.h>
#if MOBILEGL_BUILD_DISAGGREGATED
#include <Config.h>
#include <MG_Remote/Server/ServerLoop.h>
#include <MG_Util/Debug/Log.h>
#include <cstdlib>
#endif
namespace MobileGL::MG_Pipe {
#if MOBILEGL_BUILD_DISAGGREGATED
void MGPipeRefuseAllocatorFromApplyThread(const char* entry) {
if (MG_Config::Transport == MG_Config::TransportMode::Monolith) return;
if (!MG_Remote::Server::ServerLoop::OnApplyThread()) return;
// The named exemption of CONTRACT-P5C §3.1: the sites whose handle-carrying records
// are not emitted yet (P4b/P7) probe read-only inside the scope. The G6
// frontend-keyed registry family (P3b/P4b) does the same inside its own scope.
if (MGPipeReverseAnnouncementScope::Active()) return;
if (MGPipeFrontendKeyedRegistryScope::Active()) return;
MGLOG_F("MGPipe: Fatal{RoleViolation, \"MGPipeSlots\"} - the apply thread called "
"MGPipeSlots().%s. With an active transport the client slot allocator is "
"client-only memory (CONTRACT-P5C §3.1, rule E): a handle arrives already "
"minted in a record, and a server that resolves or mints one off a frontend "
"object's lifetime id is reading memory that will not exist on its side of a "
"real split",
entry);
std::abort();
}
namespace {
thread_local Uint32 g_reverseAnnouncementScopeDepth = 0;
}
MGPipeReverseAnnouncementScope::MGPipeReverseAnnouncementScope() {
++g_reverseAnnouncementScopeDepth;
}
MGPipeReverseAnnouncementScope::~MGPipeReverseAnnouncementScope() {
--g_reverseAnnouncementScopeDepth;
}
Bool MGPipeReverseAnnouncementScope::Active() {
return g_reverseAnnouncementScopeDepth != 0;
}
namespace {
thread_local Uint32 g_frontendKeyedRegistryScopeDepth = 0;
}
MGPipeFrontendKeyedRegistryScope::MGPipeFrontendKeyedRegistryScope() {
++g_frontendKeyedRegistryScopeDepth;
}
MGPipeFrontendKeyedRegistryScope::~MGPipeFrontendKeyedRegistryScope() {
--g_frontendKeyedRegistryScopeDepth;
}
Bool MGPipeFrontendKeyedRegistryScope::Active() {
return g_frontendKeyedRegistryScopeDepth != 0;
}
#endif
namespace {
// The ShaderCso band the ordinary allocator must never enter: the top 1/16 of the
// ShaderCso slot space is reserved for PROGRAM PIPELINE COMPOSITES, which are minted
@@ -166,6 +226,9 @@ namespace MobileGL::MG_Pipe {
}
MGPipeHandle MGPipeSlotAllocator::FindByLifetimeId(MGPipeKind kind, Uint64 lifetimeId) const {
#if MOBILEGL_BUILD_DISAGGREGATED
MGPipeRefuseAllocatorFromApplyThread("FindByLifetimeId");
#endif
if (lifetimeId == 0) return kMGPipeNullHandle;
const KindState& state = StateOf(kind);
const auto it = state.ByLifetimeId.find(lifetimeId);
@@ -176,12 +239,18 @@ namespace MobileGL::MG_Pipe {
}
MGPipeHandle MGPipeSlotAllocator::Acquire(MGPipeKind kind, Uint64 lifetimeId) {
#if MOBILEGL_BUILD_DISAGGREGATED
MGPipeRefuseAllocatorFromApplyThread("Acquire");
#endif
const MGPipeHandle existing = FindByLifetimeId(kind, lifetimeId);
if (!MGPipeHandleIsNull(existing)) return existing;
return AllocateFor(kind, lifetimeId);
}
void MGPipeSlotAllocator::Free(MGPipeKind kind, MGPipeHandle handle) {
#if MOBILEGL_BUILD_DISAGGREGATED
MGPipeRefuseAllocatorFromApplyThread("Free");
#endif
KindState& state = StateOf(kind);
SlotState* entry = EntryOf(state, kind, handle.Slot);
if (entry == nullptr) return;
+43
View File
@@ -163,4 +163,47 @@ namespace MobileGL::MG_Pipe {
// The monolith's one client allocator. Under split there is one per client context.
MGPipeSlotAllocator& MGPipeSlots();
#if MOBILEGL_BUILD_DISAGGREGATED
// P5c (hd, CONTRACT-P5C §3.1 / §6 layer 1): with an active transport this allocator is a
// CLIENT-only surface. Acquire, FindByLifetimeId and Free called from the apply thread -
// i.e. a server that resolves or mints handles off a frontend object's lifetime id (T2),
// which is memory that will not exist on its side of a real split - are
// Fatal{RoleViolation, "MGPipeSlots"}. Compiled out entirely outside split builds, so the
// pull build's bytes do not move (G1).
void MGPipeRefuseAllocatorFromApplyThread(const char* entry);
// The NAMED EXEMPTION to the rule above (CONTRACT-P5C §3.1): the family of sites whose
// handle-carrying records the client does not EMIT yet. set_shader_buffers and
// set_stream_output_targets exist in the catalogue but are P4b's to emit
// (SetHashSuppressor.h says so), so the buffer binding-point ensures and the GPU-written
// announcement they feed have no record handle to resolve from today. Inside this scope
// ONE read-only lifetime-id probe stays legal; the scope is the debt's measurable,
// greppable form, and it retires with P4b's emission (Espryt) and P7's server-side
// binding table (Magma). Every other apply-thread allocator access stays Fatal.
class MGPipeReverseAnnouncementScope {
public:
MGPipeReverseAnnouncementScope();
~MGPipeReverseAnnouncementScope();
MGPipeReverseAnnouncementScope(const MGPipeReverseAnnouncementScope&) = delete;
MGPipeReverseAnnouncementScope& operator=(const MGPipeReverseAnnouncementScope&) = delete;
static Bool Active();
};
// The SECOND named exemption family (CONTRACT-P5C §5.4): the frontend-keyed twin
// registry (audit row G6). The texture / sampler-view / FBO-legacy HandleOf probes are
// how the server answers "which twin is this frontend object" while the registry is
// keyed by frontend identity - server-PRIVATE state whose rekey onto handles is
// P3b/P4b's, not P5c's. A probe inside this scope stays a read-only, barrier-held debt;
// wrapping a NEW site in it is the greppable act of naming that debt, and an unwrapped
// probe from the apply thread is still Fatal{RoleViolation, "MGPipeSlots"}.
class MGPipeFrontendKeyedRegistryScope {
public:
MGPipeFrontendKeyedRegistryScope();
~MGPipeFrontendKeyedRegistryScope();
MGPipeFrontendKeyedRegistryScope(const MGPipeFrontendKeyedRegistryScope&) = delete;
MGPipeFrontendKeyedRegistryScope& operator=(const MGPipeFrontendKeyedRegistryScope&) = delete;
static Bool Active();
};
#endif
} // namespace MobileGL::MG_Pipe
+18 -19
View File
@@ -821,31 +821,30 @@ namespace MobileGL::MG_Pipe {
Uint64 m_walks[kMGPipeVerbClassCount]{};
};
// ONE attribute default, flattened onto the wire (P2 brief D10). A named function rather
// than four lines inside the emitter because this flattening is the whole correctness
// question of set_vertex_attrib_defaults: a CurrentVertexAttributeValue is one value in
// three views and GLContext converts NUMERICALLY between them, so four words alone are
// not the value - glVertexAttrib4f(loc, 1.5f, ...) leaves 1 in intValue and 0x3FC00000 in
// floatValue. MGPAttribValue::ValueClass is what makes the four words readable again, and
// TrackerAttribPayload pins that here instead of leaving it to the emitter's shape.
// ONE attribute default, flattened onto the wire (P2 brief D10, AMENDED at P5c rv). A
// named function rather than four lines inside the emitter because this flattening is the
// whole correctness question of set_vertex_attrib_defaults: a CurrentVertexAttributeValue
// is one value in three views and GLContext converts NUMERICALLY between them, so four
// words alone are not the value - glVertexAttrib4f(loc, 1.5f, ...) leaves 1 in intValue
// and 0x3FC00000 in floatValue. Since rv the record carries ALL THREE VIEWS VERBATIM
// (MGPAttribValue::FloatView/IntView/UintView, CONTRACT-P5C.md §5.3) and the applier writes
// each view from its own array; ValueClass is the record of which view the application
// wrote directly, kept for the comparator and for readers - the applier no longer needs
// it to rebuild anything.
inline void MGPipeFillAttribValue(Uint32 location,
const MG_State::GLState::CurrentVertexAttributeValue& value,
Uint32 writtenClass, MGPAttribValue& out) {
out = MGPAttribValue{};
out.Location = location;
out.ValueClass = static_cast<Uint8>(writtenClass);
static_assert(sizeof(out.Data) == sizeof(value.floatValue), "MGPAttribValue::Data is four words");
switch (writtenClass) {
case MG_State::GLState::kVertexAttribValueClassInt:
std::memcpy(out.Data, value.intValue.data(), sizeof(out.Data));
break;
case MG_State::GLState::kVertexAttribValueClassUint:
std::memcpy(out.Data, value.uintValue.data(), sizeof(out.Data));
break;
default:
std::memcpy(out.Data, value.floatValue.data(), sizeof(out.Data));
break;
}
static_assert(sizeof(out.FloatView) == sizeof(value.floatValue),
"MGPAttribValue's views are four words each");
static_assert(sizeof(out.IntView) == sizeof(value.intValue) &&
sizeof(out.UintView) == sizeof(value.uintValue),
"MGPAttribValue's views are four words each");
std::memcpy(out.FloatView, value.floatValue.data(), sizeof(out.FloatView));
std::memcpy(out.IntView, value.intValue.data(), sizeof(out.IntView));
std::memcpy(out.UintView, value.uintValue.data(), sizeof(out.UintView));
}
// The monolith's one tracker. Under split there is one per client context; the context
@@ -2172,6 +2172,29 @@ if (MOBILEGL_BUILD_DISAGGREGATED)
endforeach()
endif()
# P5c ct (MG_Remote/CONTRACT-P5C.md §5): the two control records, split-only source for the
# same reason as f1's - the scenario reads the SERVER sink's tallies, which a monolith build
# has no symbol for. One block per case with a LOG PATH OF ITS OWN, the F1 pattern:
# SplitLogPaths.PrivateAndDistinct fails a lane whose cases share one file, and the death
# case's child truncates whatever path it inherits.
if (MOBILEGL_BUILD_DISAGGREGATED)
target_sources(MobileGLIntegrationTest PRIVATE Scenarios/CtWireScenario.cpp)
foreach(ctCase ApplierResetCrossesAtThePrimedEdgeInSerialOrder
TextureDeathCrossesAndTheRecycledSlotAnswersTheNewObject
FramebufferDeathCrossesAndTheRecycledSlotAnswersTheNewObject
TheDirectApplierResetCallOnTheGLThreadIsRoleViolation)
gtest_discover_tests(MobileGLIntegrationTest
TEST_PREFIX "DirectGLES.Split.Ct."
TEST_FILTER "CtWireScenario.${ctCase}"
DISCOVERY_TIMEOUT 30
PROPERTIES
LABELS "integration-gpu\;integration-split"
TIMEOUT ${MGL_ITEST_TIMEOUT}
ENVIRONMENT "${MGL_ITEST_GLES_SPLIT_ENVIRONMENT}\;MOBILEGL_LOG_FILE_PATH=${CMAKE_CURRENT_BINARY_DIR}/p5c-ct-${ctCase}.log"
)
endforeach()
endif()
# P5b measured named-blit blockers, exercising both backend bound-form lowerings.
if (MOBILEGL_BUILD_DISAGGREGATED)
foreach(namedBlitBackend DirectGLES DirectVulkan)
@@ -0,0 +1,257 @@
// MobileGL - MobileGL/MG_IntegrationTest/Scenarios/CtWireScenario.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
// P5c ct (MG_Remote/CONTRACT-P5C.md §5): the two control records, end to end over inproc.
//
// applier_reset (§5.1): this process's first validate primes the pipe tracker, and the
// FreshlyPrimed edge is the record's producer (MG_Impl/Pipe/PipeFill.cpp). What the scenario
// asserts is the SERVER sink's own counters - moved by nobody else - plus the pixels, so a
// reset that never crossed is red by the tally and a client that fell through to the driver
// is red by ScenarioFixture's emit-ordinal rule.
//
// object_death (§5.2): a texture and a framebuffer die, the deaths cross, and the slots
// recycle. The picture after recycling is the behavioural half: a stale twin answering for
// the recycled object renders the DEAD object's content (or errors), which is the exact
// shape LiveGenAt's generation check exists to refuse.
//
// RED ONCE for the reset (executed, recorded in the package report): reverting PipeFill's
// FreshlyPrimed arm to the GL-thread direct MGPipeApplierReset() call aborts this whole lane
// with Fatal{RoleViolation, "g_applier"} out of the applier's layer-2 guard. The automated
// half of that control is TheDirectApplierResetCallOnTheGLThreadIsRoleViolation below, and
// the guard's two non-Fatal arms are pinned in PipeWireCodecTest's CtWireFatals suite.
#include "../Harness/ScenarioFixture.h"
#include "../Harness/SplitRuntimePeek.h"
#include <MG_Pipe/PipeApply.h>
#include <MG_Remote/Server/ServerSession.h>
#if !defined(_WIN32)
#include <csignal>
#include <cstdlib>
#include <fstream>
#include <sstream>
#endif
#ifdef GLAPI
#undef GLAPI
#endif
#define GL_GLEXT_PROTOTYPES
#include <GL/gl.h>
#include <GL/glcorearb.h>
#undef GL_GLEXT_PROTOTYPES
namespace MGITest {
namespace {
MobileGL::MG_Remote::Server::ServerVerbSink& ServerVerbs() {
return MobileGL::MG_Remote::Server::ServerSessionInstance().Applier().Verbs();
}
class CtWireScenario : public ScenarioTest {
protected:
void SetUp() override {
ScenarioTest::SetUp();
if (!Ready()) return;
const auto why = SplitRuntimeSkipReason();
if (!why.empty()) GTEST_SKIP() << why;
}
// One 4x4 RGBA8 texture whose every texel is `rgba`, uploaded so the object crosses
// (no handle, no record - CONTRACT-P5C.md §5.2: an object that never crossed emits
// nothing at death, and this case needs a real death).
GLuint MakeSolidTexture(const GLubyte rgba[4]) {
GLuint texture = 0;
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, 4, 4, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr);
GLubyte texels[4 * 4 * 4];
for (int i = 0; i < 4 * 4; ++i) {
for (int c = 0; c < 4; ++c) texels[i * 4 + c] = rgba[c];
}
glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 4, 4, GL_RGBA, GL_UNSIGNED_BYTE, texels);
return texture;
}
// The texture's level-0 content, read back through a throwaway FBO, as four bytes.
// The FBO is bound AND deleted here, so it never leaks a framebuffer death into the
// tally a case is watching.
void ReadTextureLevel(GLuint texture, GLubyte out[4]) {
GLuint fbo = 0;
glGenFramebuffers(1, &fbo);
glBindFramebuffer(GL_FRAMEBUFFER, fbo);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture, 0);
glReadPixels(1, 1, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, out);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glDeleteFramebuffers(1, &fbo);
}
};
TEST_F(CtWireScenario, ApplierResetCrossesAtThePrimedEdgeInSerialOrder) {
if (!Ready()) return;
// The first verb of the process primes the tracker; the edge is the producer. The
// clear also gives the case its pixels, so a lane that emitted nothing is red twice
// (here and in the fixture's emit-ordinal rule).
glClearColor(0.2f, 0.4f, 0.6f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
EXPECT_GE(ServerVerbs().ApplierResets(), 1u)
<< "the FreshlyPrimed edge emitted no applier_reset; the server's g_applier was "
"never reset for this session";
// The serial sequence is the session's own count (§1: asserted, never dispatched
// on): every record the sink accepted carried the serial it expected, or the counter
// and the accepted tally would disagree.
EXPECT_EQ(ServerVerbs().ExpectedApplierResetSerial(), ServerVerbs().ApplierResets())
<< "an applier_reset record was dropped or replayed on the wire";
GLubyte pixel[4]{};
glReadPixels(1, 1, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, pixel);
ASSERT_EQ(FirstGLError(), GLenum(GL_NO_ERROR)) << "Ct.ApplierReset.error";
const int expected[4] = {51, 102, 153, 255};
for (int i = 0; i < 4; ++i) EXPECT_NEAR(pixel[i], expected[i], 1) << "Ct.ApplierReset.pixels";
}
TEST_F(CtWireScenario, TextureDeathCrossesAndTheRecycledSlotAnswersTheNewObject) {
if (!Ready()) return;
// The object_death producer is Espryt-side (OnFrontendStateObjectDestroyed,
// CONTRACT-P5C.md §5.2); Magma installs no StateObjectDeathOps (P7), so under
// DirectVulkan there is no death record to watch and the case has nothing to prove.
if (HeadlessGL::Get().BackendName() != "DirectGLES") {
GTEST_SKIP() << "object_death is produced by the DirectGLES death-notice ops; "
"DirectVulkan has none until P7";
}
const GLubyte red[4] = {255, 0, 0, 255};
const GLubyte green[4] = {0, 255, 0, 255};
// A texture lives and crosses (the upload emits its records). It is also READ BACK
// once before it dies: the read forces the server-side sync that creates the twin -
// and, one level down, resolves the Espryt slot arm that INSTALLS the death-notice
// ops, which no process has before its first twin lookup. The red picture is the
// pre-death control the recycle below is read against.
GLuint texture = MakeSolidTexture(red);
GLubyte before[4]{};
ReadTextureLevel(texture, before);
const int redExpected[4] = {255, 0, 0, 255};
for (int i = 0; i < 4; ++i) ASSERT_NEAR(before[i], redExpected[i], 1) << "Ct.TextureDeath.before";
// The object dies unbound so the destructor - and the death record - fire at the
// delete, and the tally is read AFTER the EmitAndWait the delete blocked on.
glBindTexture(GL_TEXTURE_2D, 0);
const MobileGL::Uint64 deathsBefore = ServerVerbs().ObjectDeaths();
glDeleteTextures(1, &texture);
EXPECT_GT(ServerVerbs().ObjectDeaths(), deathsBefore)
<< "the texture's death produced no object_death record; the server's twin was "
"never told to let go";
// The slot recycles forward: a new texture (the frontend hands the same GL name back
// more often than not, which is exactly the ABA shape) must answer with ITS content,
// not the dead twin's. Red then green, read back as pixels: a stale twin is red.
texture = MakeSolidTexture(green);
GLubyte pixel[4]{};
ReadTextureLevel(texture, pixel);
glBindTexture(GL_TEXTURE_2D, 0);
glDeleteTextures(1, &texture);
ASSERT_EQ(FirstGLError(), GLenum(GL_NO_ERROR)) << "Ct.TextureDeath.error";
const int expected[4] = {0, 255, 0, 255};
for (int i = 0; i < 4; ++i) EXPECT_NEAR(pixel[i], expected[i], 1)
<< "Ct.TextureDeath.pixels - the recycled texture read back the dead twin's content";
}
TEST_F(CtWireScenario, FramebufferDeathCrossesAndTheRecycledSlotAnswersTheNewObject) {
if (!Ready()) return;
// Same producer reason as the texture case above: object_death is emitted by the
// DirectGLES death-notice ops; DirectVulkan has none until P7.
if (HeadlessGL::Get().BackendName() != "DirectGLES") {
GTEST_SKIP() << "object_death is produced by the DirectGLES death-notice ops; "
"DirectVulkan has none until P7";
}
// Framebuffer is the kind object_death EXISTS for: it has no other wire delete
// opcode (CONTRACT-P5C.md §5.2). The renderbuffer goes along so the FBO has storage.
GLuint fbo = 0, renderbuffer = 0;
glGenFramebuffers(1, &fbo);
glGenRenderbuffers(1, &renderbuffer);
glBindRenderbuffer(GL_RENDERBUFFER, renderbuffer);
glRenderbufferStorage(GL_RENDERBUFFER, GL_RGBA8, 4, 4);
glBindFramebuffer(GL_FRAMEBUFFER, fbo);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, renderbuffer);
ASSERT_EQ(glCheckFramebufferStatus(GL_FRAMEBUFFER), GLenum(GL_FRAMEBUFFER_COMPLETE))
<< "Ct.FramebufferDeath.setup";
glClearColor(0.0f, 0.0f, 1.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
GLubyte pixel[4]{};
glReadPixels(1, 1, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, pixel);
const int blue[4] = {0, 0, 255, 255};
for (int i = 0; i < 4; ++i) ASSERT_NEAR(pixel[i], blue[i], 1) << "Ct.FramebufferDeath.first";
// Die unbound, framebuffer first so the attachment's own death is a separate record.
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glBindRenderbuffer(GL_RENDERBUFFER, 0);
const MobileGL::Uint64 deathsBefore = ServerVerbs().ObjectDeaths();
glDeleteFramebuffers(1, &fbo);
EXPECT_GT(ServerVerbs().ObjectDeaths(), deathsBefore)
<< "the framebuffer's death produced no object_death record - and no other "
"opcode can carry it";
glDeleteRenderbuffers(1, &renderbuffer);
// Recycle: a new FBO and a new backing store, cleared to a different colour. A stale
// twin answering for the recycled framebuffer renders the blue of the dead one.
glGenFramebuffers(1, &fbo);
glGenRenderbuffers(1, &renderbuffer);
glBindRenderbuffer(GL_RENDERBUFFER, renderbuffer);
glRenderbufferStorage(GL_RENDERBUFFER, GL_RGBA8, 4, 4);
glBindFramebuffer(GL_FRAMEBUFFER, fbo);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, renderbuffer);
ASSERT_EQ(glCheckFramebufferStatus(GL_FRAMEBUFFER), GLenum(GL_FRAMEBUFFER_COMPLETE))
<< "Ct.FramebufferDeath.recycle";
glClearColor(1.0f, 1.0f, 0.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
glReadPixels(1, 1, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, pixel);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glBindRenderbuffer(GL_RENDERBUFFER, 0);
glDeleteFramebuffers(1, &fbo);
glDeleteRenderbuffers(1, &renderbuffer);
ASSERT_EQ(FirstGLError(), GLenum(GL_NO_ERROR)) << "Ct.FramebufferDeath.error";
const int yellow[4] = {255, 255, 0, 255};
for (int i = 0; i < 4; ++i) EXPECT_NEAR(pixel[i], yellow[i], 1)
<< "Ct.FramebufferDeath.pixels - the recycled framebuffer read back the dead twin's content";
}
#if !defined(_WIN32)
TEST_F(CtWireScenario, TheDirectApplierResetCallOnTheGLThreadIsRoleViolation) {
if (!Ready()) return;
// A verb in the PARENT, so the fixture's emit-ordinal rule has something to see: the
// death statement below runs only in the child, and a parent that emitted nothing
// is the shape that rule exists to fail.
glClearColor(0.1f, 0.1f, 0.1f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
// THE RED-ONCE FOR §5.1, AUTOMATED. This process has a LIVE inproc session, and the
// GL-thread direct call the applier_reset record replaced is a named Fatal there
// (CONTRACT-P5C.md §5.1 / §6 layer 2) - which is exactly the shape reverting
// PipeFill's FreshlyPrimed arm would take, so the guard is what turns that revert
// red. EXPECT_EXIT re-runs the case in a child process: the child brings up its own
// session (its SetUp is this same fixture's) and aborts at the statement. The two
// NON-Fatal arms - monolith, and a transport with no client session - are the unit
// suite's CtWireFatals.TheDirectApplierResetCallSurvivesMonolithAndAWirelessTransport.
//
// The regex is ".*" because the library's Fatal line goes to its log file, not to
// the stderr a death test matches (ServerLoopEglTest's own EXPECT_EXIT does the
// same); the NAME is asserted from the log below, which the child truncated and
// wrote before it died.
EXPECT_EXIT(MobileGL::MG_Pipe::MGPipeApplierReset(), ::testing::KilledBySignal(SIGABRT), ".*");
if (const char* logPath = std::getenv("MOBILEGL_LOG_FILE_PATH"); logPath != nullptr) {
std::ifstream in(logPath, std::ios::binary);
std::ostringstream log;
log << in.rdbuf();
EXPECT_NE(log.str().find("Fatal{RoleViolation, \"g_applier\"}"), std::string::npos)
<< "the child aborted, but not with the layer-2 guard's own line:\n"
<< log.str();
}
}
#endif
} // namespace
} // namespace MGITest
+29 -21
View File
@@ -212,33 +212,36 @@
// mirrors null on every draw of every push build. What retires those pulls is not a better
// applier, it is the phase where the backend stops reading a frontend object at all.
//
// THE SIXTH IS A DIFFERENT ARGUMENT AND IT IS WORTH WRITING DOWN, because it looks like the
// easy one. GetMaxTouchedTextureUnit is a plain Int, and set_sampler_views' Count IS that
// value plus one (the second merge rule: a high-water mark is directly the count argument).
// But the set is SUPPRESSED on an unchanged content hash and is emitted only when bit 12 fires,
// and bit 12's shutter is Mix(textureContent, GetTextureBindGeneration()) - which does NOT
// move on a redundant re-bind of the object a unit already holds, while the high-water mark
// DOES (see NoteUnitTouched in DirtySurface.def). So the applier's Count can lag the frontend's
// high-water mark by exactly the case the suppressor exists to swallow, and the field keeps
// being pulled. Narrowing that is P3b/P4b's, with the backend debounce it takes over.
// THE SIXTH left that arm at P5c rv: GetMaxTouchedTextureUnit is a plain Int whose problem was
// never shape, it was the CARRIER - set_sampler_views' Count is the set's window, and the set
// is suppressed on an unchanged content hash while the high-water mark still moves on a
// redundant re-bind. set_context_values (CONTRACT-P5C.md §5.3) carries the mark as a VALUE of
// its own, whole-record suppressed, so the mark rides an unsuppressed field and the row is
// RECORD_SUPPLIED outright.
//
// FOUR ACCESSORS THAT MAP TO A P4a CALL ARE DELIBERATELY NOT HERE, for GetPixelStoreParameters'
// reason - a row here says "this field is supplied", and for these it would be a half-truth:
// GetActiveTextureUnit - glActiveTexture's selector. set_sampler_views carries the RESOLVED
// per-unit set and no active-unit selector at all; nothing on the wire carries it.
// GetTextureContextId - a context identity the backend keys its own tables on. No call
// carries it and none should: it is the server's question about the client, not state.
// GetTextureBindGeneration / GetSamplingResolutionGeneration - frontend SHUTTERS. What
// replaces them server-side is the applier's own Serial, which is a different value with a
// different owner; claiming the sets supply the generations would make the fill loop skip
// two counters no record carries.
// P5c rv ADDS EIGHT ROWS, and they are the whole of the value-class debt that was left
// (CONTRACT-P5C.md §5.3): seven residual values no set_* call carried - the two texture-unit
// counters, the 15-target touched-count array and the five transform-feedback values - plus
// GetMaxTouchedTextureUnit re-homed from SetSamplerViews. All eight name SetContextValues, one
// POD emitted at validate when any covered value moved, hash-suppressed whole. The OBJECT rows
// (GetTextureUnitObject and its four P4a siblings above) stay BARRIER_PULLED with their
// retiring phases; the three texture shutters (below) take no row here either - they carry no
// wire value at all, the accessors answer the applier's own Serial.
//
// GetTextureContextId / GetTextureBindGeneration / GetSamplingResolutionGeneration stay out
// DELIBERATELY, and the reason is ownership rather than coverage: they are frontend SHUTTERS,
// and what replaces them server-side is the applier's own Serial - a different value with a
// different owner. A row here would claim the sets supply the generations, and the fill loop
// would skip two counters no record carries.
// And GetTextureObject / GetProgramObject are STICKY (see MGP_COVERAGE_STICKY_LIST): they are
// keyed by GL name, they are object lookups rather than verb state, and a forwarded field has
// no storage for an emitted call to supply.
#define MGP_COVERAGE_EMITTED_LIST(X) \
X(GetActiveTextureUnit, SetContextValues) \
X(GetBlendColor, SetDynamicState) \
X(GetBlendEquationIndexed, CreateRenderState) \
X(GetBlendFuncIndexed, CreateRenderState) \
X(GetBoundTransformFeedbackLifetimeId, SetContextValues) \
X(GetBoundVertexArray, BindVertexElements) \
X(GetClampReadColor, SetDynamicState) \
X(GetClearColor, SetDynamicState) \
@@ -254,7 +257,7 @@
X(GetImageTextureBinding, SetShaderImages) \
X(GetLineWidth, SetDynamicState) \
X(GetLogicOp, CreateRenderState) \
X(GetMaxTouchedTextureUnit, SetSamplerViews) \
X(GetMaxTouchedTextureUnit, SetContextValues) \
X(GetMinSampleShadingValue, CreateRenderState) \
X(GetPatchDefaultInnerLevel, SetPatchState) \
X(GetPatchDefaultOuterLevel, SetPatchState) \
@@ -272,9 +275,14 @@
X(GetScissorBox, SetDynamicState) \
X(GetStencilState, CreateRenderState) \
X(GetTextureUnitObject, SetSamplerViews) \
X(GetTouchedBufferBindingPointCount, SetContextValues) \
X(GetTransformFeedbackCapturedVertices, SetContextValues) \
X(GetTransformFeedbackGeneration, SetContextValues) \
X(GetViewport, SetDynamicState) \
X(GetViewportIndexed, SetDynamicState) \
X(IsCapabilityEnabled, CreateRenderState) \
X(IsCapabilityEnabledIndexed, CreateRenderState)
X(IsCapabilityEnabledIndexed, CreateRenderState) \
X(IsTransformFeedbackActive, SetContextValues) \
X(IsTransformFeedbackPaused, SetContextValues)
// clang-format on
+41 -46
View File
@@ -18,7 +18,8 @@
// 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
// (MG_Impl/Pipe/PipeFill.cpp). 41 fields since P5c rv (32 before it). 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.
@@ -50,14 +51,20 @@
// 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 ---- */ \
/* ---- BARRIER_PULLED: the 9 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") \
/* 17). That union was 21 fields at P5; P5c rv (CONTRACT-P5C.md §5.3) retired NINE of them */ \
/* to RECORD_SUPPLIED through set_context_values (the two texture-unit counters, the */ \
/* touched-count array, the five XFB values) plus GetCurrentVertexAttribute (the amended */ \
/* set_vertex_attrib_defaults payload), and moved the three texture SHUTTERS to */ \
/* APPLIER_DERIVED (their own rows said it since P5: "a shutter, not a value: the server */ \
/* answers from its own Serial" - rv made the accessor DO it). GetPixelStoreParameters is */ \
/* the 21st of the census and it is APPLIER_DERIVED below, for the reason written there. */ \
/* WHAT IS LEFT IS EXACTLY THE OBJECT CLASS: nine fields whose storage is a frontend heap */ \
/* reference no record can carry, each with the phase that retires it, and */ \
/* FieldOwnershipTest pins this list as ALL the remaining non-sticky rows. OpenRA adds no */ \
/* field to this set - it widens the SITE set, not the field set. */ \
/* 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 */ \
@@ -72,14 +79,6 @@
"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. */ \
@@ -87,19 +86,6 @@
"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. */ \
@@ -113,24 +99,15 @@
/* phases. Overturned by: nothing in P5b; P7/P8 retire both rows together. */ \
X(GetProgramForDispatch, BARRIER_PULLED, "P7 (Magma), P8 (Espryt)", \
"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") \
/* The XFB family's one OBJECT row. XFB itself is off the reduced path, but kDraw's */ \
/* may-read mask carries it and the draw walk reads it regardless - which is exactly the */ \
/* case a field census taken from "what the scenario does" rather than from the mask would */ \
/* miss. The family's five VALUE rows rode set_context_values out of this list at P5c rv. */ \
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 */ \
/* THE FIRST 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 */ \
@@ -139,6 +116,19 @@
/* half of it). */ \
X(GetPixelStoreParameters, APPLIER_DERIVED, "-", \
"set_pixel_pack_state; the applier writes m_pixelStore[0] (PipeApply.cpp:1373)") \
/* THE THREE TEXTURE SHUTTERS (P5c rv, CONTRACT-P5C.md §5.3). No call carries them and none */ \
/* should (Coverage.def's emitted-list header): what replaces them server-side is the */ \
/* applier's own Serial - a different value with a different owner. rv is the edit that */ \
/* makes the accessor DO it: under a server-stamped verb the PipeInputs accessor answers */ \
/* MGPipeApplierTextureShutterSerial() / MGPipeApplierContextSerial() (PipeApply.cpp) */ \
/* instead of the client's residual-fill copy, and the class flips from BARRIER_PULLED to */ \
/* here. Under monolith the storage answer is kept, byte for byte (G1). */ \
X(GetSamplingResolutionGeneration, APPLIER_DERIVED, "-", \
"a shutter, not a value: the server answers from its own Serial") \
X(GetTextureBindGeneration, APPLIER_DERIVED, "-", \
"a shutter, not a value: the server answers from its own Serial") \
X(GetTextureContextId, APPLIER_DERIVED, "-", \
"a shutter, not a value: the server answers from its own Serial") \
\
/* ---- FATAL: two non-sticky fields, each off the reduced path for a checkable reason ----- */ \
/* Three until P5b: GetProgramForDispatch moved up to BARRIER_PULLED when package i1 put */ \
@@ -164,8 +154,13 @@
"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") \
/* P5c ev DELETED the forward under an active transport (CONTRACT-P5C section 4.2): */ \
/* R-12's caps re-publication (CapsMirror.cpp:78-80) already invalidates the compile */ \
/* environment on the client, so a read or call under split is a real defect and */ \
/* aborts, never a pull. The class is unconditional because FieldOwnership only ever */ \
/* describes the split server's reads - under monolith there is no server to read. */ \
X(InvalidateCompileEnv, FATAL, "-", \
"DELETED under split by P5c ev; R-12's caps re-publication replaced it") \
X(RecordError, BARRIER_PULLED, "P9", \
"a WRITE INTO THE FRONTEND; R-12's OnGlError, whose ordering is P9's")
@@ -191,8 +186,8 @@
"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(InvalidateCompileEnv, FATAL, "-", \
"DELETED under split by P5c ev; 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")
+74 -3
View File
@@ -936,14 +936,29 @@ namespace MobileGL::MG_Pipe {
};
MGP_ASSERT_POD(MGPGlobalConstants, 40);
// The float/int/uint view is resolved on the CLIENT by ClassifyVertexAttribType.
// One attribute default, resolved on the CLIENT. P5c (rv, CONTRACT-P5C.md §5.3) AMENDED
// the shape: a CurrentVertexAttributeValue is one value in THREE views and GLContext
// converts between them NUMERICALLY (SetCurrentVertexAttributeFloat writes (Int32)value
// into intValue), so the four words of the written class alone were never the value -
// glVertexAttrib4f(loc, 1.5f, ...) leaves 1 in intValue and 0x3FC00000 in floatValue. The
// record now carries all three views VERBATIM, as the frontend computed them, and the
// applier writes each view from its own array; ValueClass stays as the record of which
// view the application wrote directly (the verify comparator covers it, and the
// emission-side suppressor compares the three views, not it). This is the catalogue's
// second payload-size amendment after P5b's MGPCopyRegion 64 -> 72 (CONTRACT-P5C.md §7.6):
// 24 -> 56 bytes, and PipeCatalogueTest pins the new size.
struct MGPAttribValue {
Uint32 Location;
Uint8 ValueClass; // Float | Int | Uint | Double
Uint8 Pad0[3];
Uint32 Data[4];
// The frontend's three views, VERBATIM - floatValue / intValue / uintValue of the
// CurrentVertexAttributeValue, converted between each other by the CLIENT. The
// applier writes each view from its own array and never reconverts.
Uint32 FloatView[4];
Uint32 IntView[4];
Uint32 UintView[4];
};
MGP_ASSERT_POD(MGPAttribValue, 24);
MGP_ASSERT_POD(MGPAttribValue, 56);
// Var-tail header: MGPAttribValue[popcount(Mask)] follows.
struct MGPVertexAttribDefaults {
@@ -1633,6 +1648,62 @@ namespace MobileGL::MG_Pipe {
};
MGP_ASSERT_POD(MGPCopyFromFramebuffer, 48);
// ---------------------------------------------------------------------------------
// P5c: the three appended rows (MG_Remote/CONTRACT-P5C.md §5). APPENDED, never inserted:
// applier_reset is opcode 77, object_death opcode 78, and set_context_values (rv, §5.3)
// opcode 79 - and no earlier opcode moved.
//
// THE TWO CONTROL RECORDS have no MGPipeApply* entry point and never gain one. Both reach
// MG_Remote::Wire::WireVerbSink like the five P5b verbs, and under monolith neither has a
// producer - the reset is the GL thread's direct MGPipeApplierReset() call and the death
// notice's mailbox hop, byte for byte as today (G1/G2). set_context_values is the ordinary
// shape instead: a routed set_* row with an MGPipeApply* entry point, emitted at validate
// with an active transport and never produced under monolith (G1).
// ---------------------------------------------------------------------------------
// applier_reset = tracker.FreshlyPrimed()'s server half (P5c §5.1). The one field is the
// client-side context's make-current serial at the edge that primed it: 0 is the first
// make-current. P5c has exactly one context per session, so the sink ASSERTS the value
// against the session's own count rather than dispatching on it; P6's multi-context shape
// is what reads it for real.
struct MGPApplierReset {
Uint64 ContextSerial;
};
MGP_ASSERT_POD(MGPApplierReset, 8);
// object_death carries no payload of its own: MGPHandleOnly (:93-98) IS the payload
// (CONTRACT-P5C.md §1) - Handle the dead frontend object's handle, Kind its MGPipeKind
// widened, one row for all seven kinds the death switch handles. A null handle never
// crosses: the client emits nothing when its own allocator cannot resolve the dying
// object (§5.2), so a null handle arriving is Fatal{ProtocolCorruption,
// "ObjectDeath.Handle"} at the sink.
// set_context_values = opcode 79, P5c rv (CONTRACT-P5C.md §5.3): the rv field table as
// ONE fixed-width POD. It carries every value-class field that no set_* call supplies -
// the two texture-unit counters, the per-target touched-buffer-binding high-water marks
// (indexed by BufferTarget, all 15, the four bind-point targets today and the rest
// zero), and the five transform-feedback values - and it retires their BARRIER_PULLED
// rows to RECORD_SUPPLIED. There is NO dirty mask in the payload: the record is
// whole-record hash-suppressed like every other set_* call, and a suppressed record
// means "nothing moved", never "field invalid" (§1). The three texture SHUTTERS
// (GetSamplingResolutionGeneration / GetTextureBindGeneration / GetTextureContextId)
// deliberately carry NO field here: they are APPLIER_DERIVED, answered by the accessor
// from the applier's own Serial (MG_Backend/MGPipe/PipeInputs.h).
struct MGPContextValues {
Uint32 ActiveTextureUnit; // feeds GetActiveTextureUnit
Uint32 MaxTouchedTextureUnit; // feeds GetMaxTouchedTextureUnit
// 15 = BufferTarget::BufferTargetCount (BufferObject.h:15-33). MG_Pipe may not include
// MG_State, so the pairing is asserted where both sides are visible (PipeFill.cpp).
Uint32 TouchedBufferBindingPointCount[15];
Uint8 IsTransformFeedbackActive;
Uint8 IsTransformFeedbackPaused;
Uint8 Pad0[2];
Uint64 TransformFeedbackGeneration;
Uint64 BoundTransformFeedbackLifetimeId;
Uint64 TransformFeedbackCapturedVertices;
};
MGP_ASSERT_POD(MGPContextValues, 96);
// ---------------------------------------------------------------------------------
// Reverse channel payloads (section 7.1)
// ---------------------------------------------------------------------------------
+142 -10
View File
@@ -37,6 +37,13 @@
// 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>
// P5c (ct), CONTRACT-P5C.md §6 layer 2: MGPipeApplierReset's role guard asks
// ServerLoop::OnApplyThread() - the one predicate that tells the GL thread from the thread
// that owns g_applier under an active transport - and ClientSession::Active(), which is what
// tells a live wire from a configured-but-wireless one (the bring-up window and the
// server-role-only fixture: there the direct call is the only reset that exists).
#include <MG_Remote/Client/ClientSession.h>
#include <MG_Remote/Server/ServerLoop.h>
#endif
#include <algorithm>
@@ -206,6 +213,23 @@ namespace MobileGL::MG_Pipe {
inputs.m_patchDefaultOuterLevel = outer;
inputs.m_patchDefaultInnerLevel = inner;
}
// P5c (rv, CONTRACT-P5C.md §5.3): set_context_values' write, one field per payload
// member, on the server side of the wire. Like PackState it is a plain store - the
// stamp is the filler/verb boundary's statement, not the applier's (see the struct's
// header comment).
static void SetContextValues(PipeInputs& inputs, const MGPContextValues& values) {
inputs.m_activeTextureUnit = static_cast<Int>(values.ActiveTextureUnit);
inputs.m_maxTouchedTextureUnit = static_cast<Int>(values.MaxTouchedTextureUnit);
for (SizeT i = 0; i < PipeInputs::kBufferTargetCount; ++i) {
inputs.m_touchedBindingPointCount[i] =
static_cast<SizeT>(values.TouchedBufferBindingPointCount[i]);
}
inputs.m_transformFeedbackActive = values.IsTransformFeedbackActive != 0;
inputs.m_transformFeedbackPaused = values.IsTransformFeedbackPaused != 0;
inputs.m_transformFeedbackGeneration = values.TransformFeedbackGeneration;
inputs.m_boundTransformFeedbackLifetimeId = values.BoundTransformFeedbackLifetimeId;
inputs.m_transformFeedbackCapturedVertices = values.TransformFeedbackCapturedVertices;
}
// ----------------------------------------------------------------------------
// D5: the 29 PipeInputs fields that are PURE FUNCTIONS of RenderStateParameters.
@@ -986,11 +1010,13 @@ namespace MobileGL::MG_Pipe {
return true;
}
// The texture half of resource_subdata, and it DISPATCHES TO NOBODY. Nothing in this
// family reaches the backend at GL-call time today: a texture write marks a level dirty
// and Espryt uploads it at its own sync point, out of the accumulated set below. So the
// whole of this function is the gate, the accumulation and the serial - which is also
// why MGPipeResourceOps did not have to grow a member for it.
// The texture half of resource_subdata, and it DISPATCHES TO NOBODY at GL-call time:
// a texture write marks a level dirty and Espryt uploads it at its own sync point, out
// of the accumulated set below. So the whole of this function is the gate, the
// accumulation, the serial and - P5c (tx), disaggregated builds only - the adoption
// hook that moves the staged bytes into the server's staged-texture store while they
// are still alive. MGPipeResourceOps grew its three texture members for exactly that
// hook; the monolith shape of everything above them is unchanged.
Bool ApplyTextureUpload(const MGPSubData& record, const void* bytes, const MGPSubRegion* regions) {
MGPipeResourceRecord* stored =
ResolveResourceIn(g_applier.TextureResources, "resource_subdata", record.Res);
@@ -1032,6 +1058,16 @@ namespace MobileGL::MG_Pipe {
// record was accumulated, so the texels are the server's now, and that is the true
// this returns.
++stored->Serial;
#if MOBILEGL_BUILD_DISAGGREGATED
// P5c (tx): THE STAGED BYTES ARE ADOPTED HERE, at the last instant `bytes` is known
// alive (rule C: SEG_STAGE retires when this record does, and PendingUpload
// deliberately holds no byte pointer). The hook copies the run into the server's
// staged-texture store keyed by this record's own handle; it is a no-op in
// monolith, so the monolith shape keeps P5's pointer-dropping expression exactly.
if (g_resourceOps != nullptr && g_resourceOps->TextureSubData != nullptr) {
g_resourceOps->TextureSubData(record.Res, record, bytes, regions);
}
#endif
return true;
}
@@ -1170,6 +1206,12 @@ namespace MobileGL::MG_Pipe {
MGPipeApplierState& MGPipeApplier() { return g_applier; }
// P5c (rv, CONTRACT-P5C.md §5.3): the three texture shutters' server-side answers. See
// MGPipeApplierState::TextureShutterSerial / ContextSerial for the bump rule.
Uint64 MGPipeApplierTextureShutterSerial() { return g_applier.TextureShutterSerial; }
Uint64 MGPipeApplierContextSerial() { return g_applier.ContextSerial; }
void MGPipeApplierNoteTextureStateMoved() { ++g_applier.TextureShutterSerial; }
void MGPipeSetResourceOps(const MGPipeResourceOps* ops) { g_resourceOps = ops; }
const MGPipeResourceOps* MGPipeGetResourceOps() { return g_resourceOps; }
@@ -1200,6 +1242,28 @@ namespace MobileGL::MG_Pipe {
} // namespace
void MGPipeApplierReset() {
#if MOBILEGL_BUILD_DISAGGREGATED
// P5c (ct), CONTRACT-P5C.md §5.1 / §6 layer 2. With an active transport g_applier is
// SERVER-PRIVATE and the GL thread's reset crosses as the applier_reset RECORD
// (PipeFill.cpp's FreshlyPrimed arm emits it; ServerVerbSink::OnApplierReset runs this
// function ON the apply thread). Reaching here from any other thread WITH A LIVE WIRE
// is the direct call the record replaced - a write into server memory with no wire
// shape, and exactly the revert the red-once gate must catch - so it is a named Fatal
// rather than a silent reset of state another role owns. The window the Fatal
// deliberately does NOT cover is a configured-but-wireless transport: before
// ClientSession::Start() there is no wire for a record to cross (§6 layer 2's
// documented bring-up exception), and a ServerLoop fixture with no client at all has
// none either - there this call is the only reset that exists. Monolith keeps the
// direct call, byte for byte (G1); in a pull build none of this is compiled at all.
if (MG_Config::Transport != MG_Config::TransportMode::Monolith &&
MG_Remote::Client::ClientSession::Active() != nullptr &&
!MG_Remote::Server::ServerLoop::OnApplyThread()) {
MGLOG_F("MGPipe: Fatal{RoleViolation, \"g_applier\"} - MGPipeApplierReset() called "
"off the apply thread with an active transport; under split the reset "
"crosses as the applier_reset record (CONTRACT-P5C.md §5.1)");
std::abort();
}
#endif
g_applier.RenderStateCsos.clear();
g_applier.BoundRenderStateCso = kMGPipeNullHandle;
g_applier.Residual = ResidualValueBlock{};
@@ -1265,6 +1329,13 @@ namespace MobileGL::MG_Pipe {
// the first compare after the switch is a mismatch, which is the safe direction.
++g_applier.VertexBuffersSerial;
++g_applier.IndexBufferSerial;
// P5c (rv): a make-current is a fresh server, and the two shutter serials are what the
// PipeInputs texture-shutter accessors answer with - so both ADVANCE here, for the
// serials' own reason: a counter that restarts walks back through values already
// stamped into a memo that outlived the switch. ContextSerial's move is also
// GetTextureContextId's whole job (the backends key their per-context memos on it).
++g_applier.TextureShutterSerial;
++g_applier.ContextSerial;
// ---- P4a's working state, cleared for the same reason and with the same serial rule
// (D-J4). The OBJECT records - texture and renderbuffer resources, sampler CSOs,
@@ -1310,6 +1381,10 @@ namespace MobileGL::MG_Pipe {
g_applier.BoundVertexElements = kMGPipeNullHandle;
++g_applier.VertexBuffersSerial;
++g_applier.IndexBufferSerial;
// P5c (rv): same rule for the shutter serials - the served context is going away, and
// a memo that outlives it must not match a value these have already answered with.
++g_applier.TextureShutterSerial;
++g_applier.ContextSerial;
// P4a's five object tables go with them, and the working handles they could name go
// too - a bound shader CSO whose record has just been dropped must not survive as a
// handle the next call resolves against.
@@ -1452,6 +1527,18 @@ namespace MobileGL::MG_Pipe {
MGPipeApplyAccess::PackState(gPipeInputs) = pack.Pack;
}
// set_context_values (P5c rv, CONTRACT-P5C.md §5.3): the residual-value record's server
// half. A plain store of the whole POD - there is no dirty mask and no field-level gate,
// because the record crosses only when one of its source values moved (the client's
// whole-record hash suppression) and a suppressed record means "nothing moved", never
// "field invalid" (§1).
void MGPipeApplySetContextValues(const MGPContextValues& values) {
static_assert(std::extent_v<decltype(MGPContextValues::TouchedBufferBindingPointCount)> ==
PipeInputs::kBufferTargetCount,
"the record's per-target array and PipeInputs' have drifted");
MGPipeApplyAccess::SetContextValues(gPipeInputs, values);
}
void MGPipeApplySetPatchState(const MGPPatchState& patch) {
PipeInputs& inputs = gPipeInputs;
RenderStateParameters& working = MGPipeApplyAccess::RenderState(inputs);
@@ -1540,11 +1627,16 @@ namespace MobileGL::MG_Pipe {
continue;
}
PipeInputs::CurrentVertexAttributeValue& slot = slots[location];
// The three views are always populated; which one a shader input consumes is
// ClassifyVertexAttribType's answer, not the carrier's, so all three cross.
std::memcpy(slot.floatValue.data(), value.Data, sizeof(slot.floatValue));
std::memcpy(slot.intValue.data(), value.Data, sizeof(slot.intValue));
std::memcpy(slot.uintValue.data(), value.Data, sizeof(slot.uintValue));
// P5c (rv, CONTRACT-P5C.md §5.3): the record carries ALL THREE VIEWS VERBATIM, as
// the frontend computed them, and the applier writes each view from its own array.
// The pre-rv shape - one Data[4] memcpied into all three views - could not
// reproduce the frontend's NUMERIC cross-view conversion (glVertexAttrib4f(loc,
// 1.5f, ...) leaves 1 in intValue and 0x3FC00000 in floatValue), which is exactly
// why the field stayed EMITTED-AND-STILL-PULLED until rv. ValueClass rides along
// for the comparator; the applier no longer needs it to rebuild anything.
std::memcpy(slot.floatValue.data(), value.FloatView, sizeof(slot.floatValue));
std::memcpy(slot.intValue.data(), value.IntView, sizeof(slot.intValue));
std::memcpy(slot.uintValue.data(), value.UintView, sizeof(slot.uintValue));
}
if (fault == nullptr && consumed != hdr.Count) {
fault = "Count does not match the attributes Mask names";
@@ -1726,6 +1818,9 @@ namespace MobileGL::MG_Pipe {
// the twin re-derives its storage flags from the new mask at its next sync and decides
// for itself whether the backend needs a recreate.
++record->Serial;
// P5c (rv): a respecify can move a texture's shape, which is exactly what the
// sampling-resolution shutter guarded - the server-side answer moves with it.
MGPipeApplierNoteTextureStateMoved();
// A RESPECIFY REDEFINES A STORE, SO THE PENDING UPLOADS AGAINST THE STORE IT REPLACES
// GO WITH IT - AND ONLY THOSE. They are boxes and rects in a level's coordinate system
@@ -1782,6 +1877,22 @@ namespace MobileGL::MG_Pipe {
record->PendingUploads.clear();
}
#if MOBILEGL_BUILD_DISAGGREGATED
// P5c (tx): the staged-texture store's defined-ness and drop bookkeeping rides THE SAME
// scope rules as the pending-set drops above - a named level redefines that one
// (uploadTarget, level), a whole-resource respecify drops every level, and a metadata
// update replaces no storage and is not delivered. Without this the store could not say
// whether a level exists at all (a null-data glTexImage*D carries no sub-data), and a
// whole-resource respecify would leave levels keyed against a replaced coordinate
// system. Textures only: a buffer's storage is the ops table's own Respecify hook, and
// a renderbuffer has no levels.
if (desc.Target != kMGPipeResourceTargetBuffer &&
desc.Target != static_cast<Uint8>(MGPipeResourceTarget::Renderbuffer) && !metadataOnly &&
g_resourceOps != nullptr && g_resourceOps->TextureRespecify != nullptr) {
g_resourceOps->TextureRespecify(desc.Resource, desc, level);
}
#endif
// resource_respecify is the catalogue's only kNeedsAck call, and the per-record half
// of that flag is MGPipeResourceRespecifyNeedsAck(desc): glBufferStorage is a real
// synchronous allocation and the only entry point allowed a synchronous ack, while
@@ -1968,6 +2079,10 @@ namespace MobileGL::MG_Pipe {
const Uint32 gen = record->Gen;
*record = MGPipeResourceRecord{};
record->Gen = gen;
// P5c (rv): a destroyed object may still be BOUND somewhere the texture shutters guard;
// the server's answer for them moves with the death rather than waiting for the next
// unit-set record to say so.
MGPipeApplierNoteTextureStateMoved();
// The applier's own state is consistent before the backend hears the news, so a hook
// that looked back at this applier could not see a resource that is already gone. The
@@ -1978,6 +2093,15 @@ namespace MobileGL::MG_Pipe {
// AND ONLY A BUFFER IS HANDED ON, for resource_create's reason: the op table is the
// buffer family's, its Destroy takes a handle whose kind that backend registered for,
// and a texture's death is read out of the record at the sync that would have used it.
#if MOBILEGL_BUILD_DISAGGREGATED
// P5c (tx): with ONE exception - the staged-texture store is keyed by the handle, so
// the death must reach it or a recycled slot's stale levels would answer for the
// successor. This does not hand the texture to the buffer family's Destroy.
if (static_cast<MGPipeKind>(handle.Kind) == MGPipeKind::Texture &&
g_resourceOps != nullptr && g_resourceOps->TextureDestroy != nullptr) {
g_resourceOps->TextureDestroy(handle.Handle);
}
#endif
if (static_cast<MGPipeKind>(handle.Kind) != MGPipeKind::Buffer) return;
if (g_resourceOps != nullptr && g_resourceOps->Destroy != nullptr) {
g_resourceOps->Destroy(handle.Handle);
@@ -2634,6 +2758,8 @@ namespace MobileGL::MG_Pipe {
// bytes are CARRIED, never cleared here: the server ORs them into its own flags and
// clears its own copy, and the client never clears a server flag.
++record->ParamsSerial;
// P5c (rv): a parameter change is what the sampling-resolution shutter guarded.
MGPipeApplierNoteTextureStateMoved();
return true;
}
@@ -2663,6 +2789,8 @@ namespace MobileGL::MG_Pipe {
return;
}
++g_applier.SamplerViewsSerial;
// P5c (rv): a texture bind is what the bind-generation shutter guarded.
MGPipeApplierNoteTextureStateMoved();
}
void MGPipeApplyBindSamplerStates(const MGPSamplerStates& hdr, const MGPipeHandle* tail) {
@@ -2673,6 +2801,8 @@ namespace MobileGL::MG_Pipe {
return;
}
++g_applier.SamplerStatesSerial;
// P5c (rv): a sampler bind or parameter change is what the shutters guarded.
MGPipeApplierNoteTextureStateMoved();
}
void MGPipeApplySetShaderImages(const MGPShaderImages& hdr, const MGPImageView* tail) {
@@ -2688,6 +2818,8 @@ namespace MobileGL::MG_Pipe {
return;
}
++g_applier.ShaderImagesSerial;
// P5c (rv): an image bind moves the texture bind generation's guarded set too.
MGPipeApplierNoteTextureStateMoved();
}
// ================================================================================
+105
View File
@@ -41,6 +41,9 @@ namespace MobileGL::MG_State::GLState {
namespace MobileGL::MG_Pipe {
struct PipeInputs;
// P5c (tx): MGPipeResourceOps::TextureRespecify names it; the definition is beside the
// applier entry point that produces one (below, with MGPipeApplyResourceRespecify).
struct MGPRespecifiedLevel;
// ---------------------------------------------------------------------------------
// The CSO store
@@ -94,6 +97,26 @@ namespace MobileGL::MG_Pipe {
void (*Destroy)(MGPipeHandle res);
void* (*MapPersistent)(MGPipeHandle res, Uint64 size, const void* seedBytes);
void (*UnmapPersistent)(MGPipeHandle res);
#if MOBILEGL_BUILD_DISAGGREGATED
// P5c (tx): the TEXTURE half of the resource family, appended so every positional
// initialiser of the nine P3a members keeps its meaning. TextureSubData is called
// from ApplyTextureUpload AFTER the gate, the accumulation and the serial, while
// `bytes` still names the staged run (SEG_STAGE retires when the record does, so an
// adoption anywhere later would read dead bytes - rule C); the backend copies the
// run into the server's staged-texture store (MG_Remote/Server/StagedTextureStore.h)
// and does nothing in monolith. TextureRespecify is the defined-ness/drop channel:
// it rides MGPipeApplyResourceRespecify's own scope rules (a named level redefines
// that level, a whole-resource respecify drops them all, a metadata update is not
// delivered). TextureDestroy is resource_destroy's texture arm - the applier hands
// only a buffer to Destroy, and a store keyed by the handle needs the death to drop
// its key. All three may be null together: a backend that has not adopted the staged
// shadow leaves them null and keeps the pre-tx shape.
void (*TextureSubData)(MGPipeHandle res, const MGPSubData& record, const void* bytes,
const MGPSubRegion* regions);
void (*TextureRespecify)(MGPipeHandle res, const MGPResourceDesc& desc,
const MGPRespecifiedLevel* level);
void (*TextureDestroy)(MGPipeHandle res);
#endif
};
// Install / read the table. A null argument uninstalls, which is what a backend does at
@@ -670,6 +693,71 @@ namespace MobileGL::MG_Pipe {
MGPipeHandle BoundShaderCso = kMGPipeNullHandle;
Uint64 ProgramBindingSerial = 0;
// ---- P5c (rv, CONTRACT-P5C.md §5.3): the server-side answer for the three texture
// SHUTTERS. FieldOwnership.def moves GetSamplingResolutionGeneration /
// GetTextureBindGeneration / GetTextureContextId to APPLIER_DERIVED - "a shutter, not
// a value: the server answers from its own Serial", which their rows have said since
// P5 - and THESE are the serials, read by the PipeInputs accessors under a
// server-stamped verb instead of the client's residual-fill copy.
//
// TextureShutterSerial answers the two GENERATIONS. It is an MGGen like its seven
// siblings above: server-owned, monotone, ++ on every applied record that can move
// what the frontend's bind / sampling-resolution generations guard - the three unit
// sets, set_texture_params, a respecify or destroy of any resource, a bind_shader_image
// verb (the sink bumps it, PipeApplier.cpp) - and ADVANCED, never zeroed, by
// MGPipeApplierReset / MGPipeApplierReleaseObjectRecords. Over-firing is the safe
// direction for a memo key: a moved serial costs a re-sync, a stuck one renders stale.
//
// ContextSerial answers GetTextureContextId: stable within the served context, moved
// by every MGPipeApplierReset (a make-current is a fresh server, §5.1), which is all
// the backends' per-context memo keys need.
Uint64 TextureShutterSerial = 0;
Uint64 ContextSerial = 0;
#if MOBILEGL_BUILD_DISAGGREGATED
// ---- P5c (hd, CONTRACT-P5C §3.2): THE CURRENT VERB'S OWN HANDLES. ----------------
//
// Server state, written by ServerVerbSink at the top of a verb's dispatch and read by
// the backend DURING THAT SAME VERB, so the apply thread resolves the verb's objects
// from the handles the record carried instead of probing the client's slot allocator
// for a frontend object's lifetime id (T2). It is per-verb WORKING state, not object
// state: every writer overwrites the whole set for its verb (null included), so a
// value is only ever read between its verb's write and that verb's return, and there
// is nothing to clear at a reset.
//
// Blit: both null = the bound-form blit (the bindings answer, as before). A non-null
// pair names the read/draw framebuffers of a NAMED blit (MGPBlit::ReadFbo/DrawFbo);
// the backend must then run its named-blit arm and raise VerbBlitNamedConsumed - the
// sink reads that flag back so a backend with no named arm is a loud decline rather
// than a silent blit of whatever is bound.
MGPipeHandle VerbBlitReadFbo = kMGPipeNullHandle;
MGPipeHandle VerbBlitDrawFbo = kMGPipeNullHandle;
Bool VerbBlitNamedConsumed = false;
// copy_framebuffer_to_texture's destination texture (MGPCopyFromFramebuffer::Dst).
MGPipeHandle VerbCopyTexDst = kMGPipeNullHandle;
// generate_mipmap's texture (MGPMipPlan::Res).
MGPipeHandle VerbMipRes = kMGPipeNullHandle;
// The current indirect draw's command buffer and (for the *Count forms) parameter
// buffer (MGPDrawIndirect::Buffer / ParameterBuffer).
MGPipeHandle VerbIndirectBuffer = kMGPipeNullHandle;
MGPipeHandle VerbIndirectParameterBuffer = kMGPipeNullHandle;
// dispatch_indirect's command buffer (MGPGridInfo::IndirectBuffer).
MGPipeHandle VerbDispatchIndirectBuffer = kMGPipeNullHandle;
// Every verb's writer calls this FIRST and then sets its own fields, so no field ever
// outlives the verb that wrote it and a reader can treat non-null as "this verb's".
void ClearVerbHandles() {
VerbBlitReadFbo = kMGPipeNullHandle;
VerbBlitDrawFbo = kMGPipeNullHandle;
VerbBlitNamedConsumed = false;
VerbCopyTexDst = kMGPipeNullHandle;
VerbMipRes = kMGPipeNullHandle;
VerbIndirectBuffer = kMGPipeNullHandle;
VerbIndirectParameterBuffer = kMGPipeNullHandle;
VerbDispatchIndirectBuffer = kMGPipeNullHandle;
}
#endif
// ---- THE THREE FRAMEBUFFER ACCESSORS (ID-19(b)/(d)). They are functions rather than
// members because the storage moved under them and their callers must not have to know
// it did: `DrawFramebuffer()` / `ReadFramebuffer()` answer the question the two members
@@ -694,6 +782,17 @@ namespace MobileGL::MG_Pipe {
// The monolith's single applier. Under split there is one per served context.
MGPipeApplierState& MGPipeApplier();
// P5c (rv): the two serials the PipeInputs texture-shutter accessors answer with under a
// server-stamped verb (FieldOwnership.def, APPLIER_DERIVED). Free functions rather than
// member reads so PipeInputs.h needs this header's DECLARATIONS only... and because the
// bump rule - advance, never zero - is stated once, beside the state.
Uint64 MGPipeApplierTextureShutterSerial();
Uint64 MGPipeApplierContextSerial();
// The one writer-side helper: every applier entry point that can move what the frontend's
// texture bind / sampling-resolution generations guard bumps the shutter serial through
// this, so the bump rule lives in exactly one place.
void MGPipeApplierNoteTextureStateMoved();
// A MAKE-CURRENT, NOT A TEARDOWN - and the distinction is the whole of this function's
// contract. It runs on every change of the current GLContext (MGPipeTracker::Update resets
// the tracker whenever the context pointer moves, and the emitter calls this from the
@@ -762,6 +861,12 @@ namespace MobileGL::MG_Pipe {
// set_patch_state. The trio also travels in pipeline chunk P0, and the applier asserts
// under verify that the two carriers agree - the redundancy is a trip wire, not waste.
void MGPipeApplySetPatchState(const MGPPatchState& patch);
// set_context_values (P5c rv, CONTRACT-P5C.md §5.3): the residual-value record. Writes
// every field it carries into gPipeInputs through MGPipeApplyAccess - the server-owned
// write that retires the eight value-class BARRIER_PULLED rows. Emitted only with an
// active transport; under monolith there is no producer and the fields keep coming
// through the residual fill (G1).
void MGPipeApplySetContextValues(const MGPContextValues& values);
// set_vertex_attrib_defaults: `tail` is hdr.Count MGPAttribValues for the attributes
// named by hdr.Mask, in ascending location order.
void MGPipeApplySetVertexAttribDefaults(const MGPVertexAttribDefaults& hdr, const MGPAttribValue* tail);
+47 -7
View File
@@ -41,17 +41,19 @@
// that the expansion, the two generated tables and this number agree.
//
// class entries group (as the plan tabulates it)
// kScreen 11 screen: caps 1 + resource 3 + persistent map 2 + fence 4, plus the
// appended server-side fence wait 1
// kScreen 12 screen: caps 1 + resource 3 + persistent map 2 + fence 4, plus the
// appended server-side fence wait 1 and P5c's applier_reset 1
// kCtxQuery 8 query object namespace 6, plus the appended timestamp pair 2
// 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
// kCtxState 18 16 of the 18 set_* calls + the temporary set_residual_value_state
// + P5c rv's set_context_values
// kCtxObject 10 set_texture_params (the 17th set_*) + 8 object-scoped transfers, plus
// P5c's object_death 1
// 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
// total 79
//
// 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:
@@ -88,9 +90,20 @@
// 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.
// - P5c (MG_Remote/CONTRACT-P5C.md §5.1/§5.2) appended TWO more after those (opcodes 77..78),
// same rule: applier_reset, the make-current edge's server-side reset that used to be a
// GL-thread direct call into server memory, and object_death, the framebuffer family's
// FIRST wire delete opcode and the handle-keyed replacement for the death-notice mailbox.
// Neither has an MGPipeApply* entry point and neither gains one; both reach WireVerbSink.
// - P5c rv (§5.3) appended ONE more (opcode 79): set_context_values, the residual-value
// record that retires the value-class BARRIER_PULLED rows. Unlike the two control records
// it IS an ordinary set_* row: MGPipeApplySetContextValues writes gPipeInputs, the row is
// routed through gMGPipeContext like its seventeen siblings, and under monolith it has no
// producer at all - the fields keep coming through the residual fill, byte for byte as
// before (G1). 79 unique records.
// ---------------------------------------------------------------------------------------
#define MGP_CALL_LIST_DOCUMENTED_COUNT 76
#define MGP_CALL_LIST_DOCUMENTED_COUNT 79
// clang-format off
#define MGP_CALL_LIST(X) \
@@ -230,7 +243,34 @@
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)
X(CopyFramebufferToTexture, MGPCopyFromFramebuffer, kCtxVerb, kNone) \
/* ---- APPENDED BY P5c (MG_Remote/CONTRACT-P5C.md §5): the two control records. Opcodes ---- */ \
/* ---- 77..78. Neither has an MGPipeApply* entry point and neither gains one: both reach ---- */ \
/* ---- WireVerbSink, and under monolith neither has a producer - the reset is a direct ---- */ \
/* ---- MGPipeApplierReset() call and the death notice's mailbox hop, byte for byte as ---- */ \
/* ---- today (G1/G2). ---- */ \
/* tracker.FreshlyPrimed() - a make-current is a fresh server. Under a transport the GL */ \
/* thread may not reset the server's g_applier itself (rule E), so the reset crosses AS */ \
/* THE CALL, ahead of the block's client-side resets; the record's barrier orders it */ \
/* against every verb that follows. ContextSerial is the client context's make-current */ \
/* serial at the edge - ASSERTED against the session's, never dispatched on (P5c: one */ \
/* context per session). */ \
X(ApplierReset, MGPApplierReset, kScreen, kNone) \
/* A frontend state object died. The record carries the HANDLE (and kind) the client's own */ \
/* allocator resolves for it - nothing is emitted for an object that never crossed (the */ \
/* server never saw it, so there is no twin to kill) - and the sink releases the kind's */ \
/* twin table by handle. The framebuffer family's FIRST wire delete opcode: its death used */ \
/* to hop to the apply thread through a stack-struct mailbox and a lifetime-id probe of */ \
/* the client's allocator, both rule-E surfaces. */ \
X(ObjectDeath, MGPHandleOnly, kCtxObject, kNone) \
/* ---- P5c rv (CONTRACT-P5C.md §5.3), opcode 79: the residual-value record. One POD that ---- */ \
/* ---- carries every value-class BARRIER_PULLED field left after the set_* catalogue: the ---- */ \
/* ---- two texture-unit counters, the 15 per-target touched-buffer-binding counts and the ---- */ \
/* ---- five transform-feedback values. Emitted at validate when any covered value moved ---- */ \
/* ---- (whole-record hash suppression, D11's shape), ACTIVE ONLY with an active transport ---- */ \
/* ---- (PipeFill.cpp gates both the emission and the residual-fill skip on it): under ---- */ \
/* ---- monolith there is no producer and the fields keep being pulled, byte for byte (G1). ---- */ \
X(SetContextValues, MGPContextValues, kCtxState, kNone)
// clang-format on
// Explicitly NOT migrated (plan 4.4.6 / appendix A "explicit deletions"):
+16 -1
View File
@@ -149,7 +149,7 @@
F(ShaderCso) F(Version) F(Blob)
#define MGP_FIELDS_MGPAttribValue(F) \
F(Location) F(ValueClass) F(Data)
F(Location) F(ValueClass) F(FloatView) F(IntView) F(UintView)
#define MGP_FIELDS_MGPVertexAttribDefaults(F) \
F(Mask) F(Count)
@@ -262,6 +262,20 @@
F(Dst) F(Target) F(Level) F(InternalFormat) F(X) F(Y) F(Width) F(Height) F(XOffset) F(YOffset) \
F(SubImage)
// ---- P5c's two appended rows (MG_Remote/CONTRACT-P5C.md §5). object_death's payload IS
// MGPHandleOnly, whose list already exists above; applier_reset's is one field.
#define MGP_FIELDS_MGPApplierReset(F) \
F(ContextSerial)
// P5c rv (CONTRACT-P5C.md §5.3): set_context_values' POD, one row per member. The 15-entry
// array is one field, exactly as MGPFramebufferState's Color[8] is one.
#define MGP_FIELDS_MGPContextValues(F) \
F(ActiveTextureUnit) F(MaxTouchedTextureUnit) F(TouchedBufferBindingPointCount) \
F(IsTransformFeedbackActive) F(IsTransformFeedbackPaused) \
F(TransformFeedbackGeneration) F(BoundTransformFeedbackLifetimeId) \
F(TransformFeedbackCapturedVertices)
// ---- 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
@@ -379,6 +393,7 @@
P(MGPSurfaceInfo) \
P(MGPImageBind) P(MGPPatchParameter) P(MGPStreamOutputBind) P(MGPStorageBlockBinding) \
P(MGPCopyFromFramebuffer) \
P(MGPApplierReset) P(MGPContextValues) \
P(RenderStateParameters) P(PixelStoreParameters) P(SamplerParameters) P(PerBufferBlendState) \
P(StencilFaceState) \
P(DynamicBackendParameters) P(MGHostSpan) \
+5
View File
@@ -221,6 +221,11 @@ namespace MobileGL::MG_Pipe {
void MGPipeEmitResourceFlushRange(MG_State::GLState::BufferObject& buffer, SizeT offset, SizeT size,
Uint32 accessFlags);
void MGPipeEmitResourceReadback(MG_State::GLState::BufferObject& buffer);
// The ranged form, for the split arm's sliced whole-buffer readback: the writeback's
// bytes travel INLINE in a SEG_EVENT record, so a buffer larger than the ring can hold
// is read back as [offset, offset+size) slices, each its own record. Monolith never
// calls it - the direct callback carries a pointer, not a copy.
void MGPipeEmitResourceReadbackRange(MG_State::GLState::BufferObject& buffer, SizeT offset, SizeT size);
// Returns the coherent host pointer the resource owner donated, or null for a DECLINE -
// which is a real answer. Every call, mint or decline, is one map-persistent roundtrip.
void* MGPipeEmitMapPersistent(MG_State::GLState::BufferObject& buffer);
+9 -3
View File
@@ -6,7 +6,7 @@
// 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
// The MONOLITH arm of R-17's routing: thirty-eight 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.
//
@@ -164,11 +164,11 @@ namespace MobileGL::MG_Pipe {
Bool MGPipeTablesAreInstalled() { return g_arm != MGPipeRouteArm::kNone; }
// ---------------------------------------------------------------------------------
// The thirty-seven monolith adapters
// The thirty-eight 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
// reading thirty-eight 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.
@@ -207,6 +207,11 @@ namespace MobileGL::MG_Pipe {
MGP_MONO_PLAIN(SetIndexBuffer, MGPIndexBuffer)
MGP_MONO_PLAIN(SetPixelPackState, MGPPixelPackState)
MGP_MONO_PLAIN(SetPatchState, MGPPatchState)
// P5c (rv): dormant under monolith - PipeFill.cpp's producer is transport-gated, so
// nothing routes here without a live wire. It exists because the row has an
// MGPipeApply* entry point (unlike the two control records) and because the wire
// emitter's server-role arm forwards to this table (WireTables.cpp).
MGP_MONO_PLAIN(SetContextValues, MGPContextValues)
// -- context, blob companion --------------------------------------------------
MGP_MONO_BLOB(CreateRenderState, MGPRenderStateDesc)
@@ -341,6 +346,7 @@ namespace MobileGL::MG_Pipe {
gMGPipeContext.SetVertexAttribDefaults = &Mono_SetVertexAttribDefaults;
gMGPipeContext.SetPixelPackState = &Mono_SetPixelPackState;
gMGPipeContext.SetPatchState = &Mono_SetPatchState;
gMGPipeContext.SetContextValues = &Mono_SetContextValues;
gMGPipeContext.SetResidualValueState = &Mono_SetResidualValueState;
gMGPipeContext.SetTextureParams = &Mono_SetTextureParams;
gMGPipeContext.ResourceSubData = &Mono_ResourceSubData;
+11 -2
View File
@@ -6,7 +6,8 @@
// 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).
// THE CLIENT -> WIRE ROUTING OF THE 38 MGPipeApply* ENTRY POINTS (P5, integrator ruling R-17;
// 38 since P5c rv added set_context_values, CONTRACT-P5C.md section 5.3).
// Owner: package c1.
//
// WHAT WAS MISSING. `gMGPipeWireRecordApply` is the DECODE hook and it has existed since w1:
@@ -218,7 +219,7 @@ namespace MobileGL::MG_Pipe {
void MGPipeNoteInstalledArm(MGPipeRouteArm arm);
// ---------------------------------------------------------------------------------
// The call-site names: MGPipeRoute<Name> for each of the thirty-seven
// The call-site names: MGPipeRoute<Name> for each of the thirty-eight
// ---------------------------------------------------------------------------------
//
// EVERY ONE TAKES THE APPLIER'S OWN SIGNATURE, so converting a call site is a rename and
@@ -307,6 +308,14 @@ namespace MobileGL::MG_Pipe {
MGP_SetPixelPackState(&pack);
}
inline void MGPipeRouteSetPatchState(const MGPPatchState& patch) { MGP_SetPatchState(&patch); }
// P5c (rv, CONTRACT-P5C.md §5.3): emitted ONLY with an active transport (PipeFill.cpp
// gates on it); under monolith the row is never produced and the fields keep coming
// through the residual fill (G1). The row IS an ordinary routed set_* otherwise - the
// monolith adapter exists so the wire emitter's server-role arm has something defined to
// forward to, and the catalogue's null-row accounting (PipeCatalogueTest) counts it.
inline void MGPipeRouteSetContextValues(const MGPContextValues& values) {
MGP_SetContextValues(&values);
}
inline void MGPipeRouteSetVertexAttribDefaults(const MGPVertexAttribDefaults& hdr,
const MGPAttribValue* tail) {
MGP_SetVertexAttribDefaults(&hdr, tail, hdr.Count);
@@ -34,7 +34,7 @@ inline constexpr const char* kMGPipeFieldOwnershipNames[] = {
};
inline constexpr MGPipeFieldOwnership kMGPipeFieldOwnership[kMGPipeInputFieldCount] = {
MGPipeFieldOwnership::kBarrierPulled, // GetActiveTextureUnit
MGPipeFieldOwnership::kRecordSupplied, // GetActiveTextureUnit
MGPipeFieldOwnership::kRecordSupplied, // GetBlendColor
MGPipeFieldOwnership::kRecordSupplied, // GetBlendEquationIndexed
MGPipeFieldOwnership::kRecordSupplied, // GetBlendFuncIndexed
@@ -43,14 +43,14 @@ inline constexpr MGPipeFieldOwnership kMGPipeFieldOwnership[kMGPipeInputFieldCou
MGPipeFieldOwnership::kBarrierPulled, // GetBufferBindingSlot
MGPipeFieldOwnership::kBarrierPulled, // GetBufferBindingPoint
MGPipeFieldOwnership::kBarrierPulled, // GetBufferBindingPointCount
MGPipeFieldOwnership::kBarrierPulled, // GetTouchedBufferBindingPointCount
MGPipeFieldOwnership::kRecordSupplied, // GetTouchedBufferBindingPointCount
MGPipeFieldOwnership::kRecordSupplied, // GetClampReadColor
MGPipeFieldOwnership::kRecordSupplied, // GetClearColor
MGPipeFieldOwnership::kRecordSupplied, // GetClearDepth
MGPipeFieldOwnership::kRecordSupplied, // GetClearStencil
MGPipeFieldOwnership::kRecordSupplied, // GetColorMaskIndexed
MGPipeFieldOwnership::kRecordSupplied, // GetCullFaceMode
MGPipeFieldOwnership::kBarrierPulled, // GetCurrentVertexAttribute
MGPipeFieldOwnership::kRecordSupplied, // GetCurrentVertexAttribute
MGPipeFieldOwnership::kRecordSupplied, // GetDepthFunc
MGPipeFieldOwnership::kRecordSupplied, // GetDepthMask
MGPipeFieldOwnership::kRecordSupplied, // GetDepthRangeIndexed
@@ -58,7 +58,7 @@ inline constexpr MGPipeFieldOwnership kMGPipeFieldOwnership[kMGPipeInputFieldCou
MGPipeFieldOwnership::kBarrierPulled, // GetImageTextureBinding
MGPipeFieldOwnership::kRecordSupplied, // GetLineWidth
MGPipeFieldOwnership::kRecordSupplied, // GetLogicOp
MGPipeFieldOwnership::kBarrierPulled, // GetMaxTouchedTextureUnit
MGPipeFieldOwnership::kRecordSupplied, // GetMaxTouchedTextureUnit
MGPipeFieldOwnership::kRecordSupplied, // GetMinSampleShadingValue
MGPipeFieldOwnership::kRecordSupplied, // GetPatchDefaultInnerLevel
MGPipeFieldOwnership::kRecordSupplied, // GetPatchDefaultOuterLevel
@@ -75,33 +75,33 @@ inline constexpr MGPipeFieldOwnership kMGPipeFieldOwnership[kMGPipeInputFieldCou
MGPipeFieldOwnership::kRecordSupplied, // GetProvokingVertexMode
MGPipeFieldOwnership::kRecordSupplied, // GetRenderStateParameters
MGPipeFieldOwnership::kRecordSupplied, // GetRenderStateParametersVersion
MGPipeFieldOwnership::kBarrierPulled, // GetSamplingResolutionGeneration
MGPipeFieldOwnership::kApplierDerived, // GetSamplingResolutionGeneration
MGPipeFieldOwnership::kRecordSupplied, // GetScissorBox
MGPipeFieldOwnership::kRecordSupplied, // GetStencilState
MGPipeFieldOwnership::kBarrierPulled, // GetTextureBindGeneration
MGPipeFieldOwnership::kBarrierPulled, // GetTextureContextId
MGPipeFieldOwnership::kApplierDerived, // GetTextureBindGeneration
MGPipeFieldOwnership::kApplierDerived, // GetTextureContextId
MGPipeFieldOwnership::kBarrierPulled, // GetTextureObject
MGPipeFieldOwnership::kBarrierPulled, // GetTextureUnitObject
MGPipeFieldOwnership::kBarrierPulled, // GetTransformFeedbackCapturedVertices
MGPipeFieldOwnership::kBarrierPulled, // GetTransformFeedbackGeneration
MGPipeFieldOwnership::kRecordSupplied, // GetTransformFeedbackCapturedVertices
MGPipeFieldOwnership::kRecordSupplied, // 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::kRecordSupplied, // IsTransformFeedbackActive
MGPipeFieldOwnership::kRecordSupplied, // IsTransformFeedbackPaused
MGPipeFieldOwnership::kFatal, // InvalidateCompileEnv
MGPipeFieldOwnership::kBarrierPulled, // ValidateProgramName
MGPipeFieldOwnership::kBarrierPulled, // RecordError
MGPipeFieldOwnership::kBarrierPulled, // GetBoundTransformFeedbackLifetimeId
MGPipeFieldOwnership::kRecordSupplied, // 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
"-", // GetActiveTextureUnit
"-", // GetBlendColor
"-", // GetBlendEquationIndexed
"-", // GetBlendFuncIndexed
@@ -110,14 +110,14 @@ inline constexpr const char* kMGPipeFieldRetiringPhase[kMGPipeInputFieldCount] =
"P8 (indirect), P9 (readback), P13 (transfer)", // GetBufferBindingSlot
"P3b/P4b, P7", // GetBufferBindingPoint
"P7/P13", // GetBufferBindingPointCount
"P3b/P4b", // GetTouchedBufferBindingPointCount
"-", // GetTouchedBufferBindingPointCount
"-", // GetClampReadColor
"-", // GetClearColor
"-", // GetClearDepth
"-", // GetClearStencil
"-", // GetColorMaskIndexed
"-", // GetCullFaceMode
"P3b/P4b", // GetCurrentVertexAttribute
"-", // GetCurrentVertexAttribute
"-", // GetDepthFunc
"-", // GetDepthMask
"-", // GetDepthRangeIndexed
@@ -125,7 +125,7 @@ inline constexpr const char* kMGPipeFieldRetiringPhase[kMGPipeInputFieldCount] =
"P3b/P4b, P7", // GetImageTextureBinding
"-", // GetLineWidth
"-", // GetLogicOp
"P3b/P4b", // GetMaxTouchedTextureUnit
"-", // GetMaxTouchedTextureUnit
"-", // GetMinSampleShadingValue
"-", // GetPatchDefaultInnerLevel
"-", // GetPatchDefaultOuterLevel
@@ -142,27 +142,27 @@ inline constexpr const char* kMGPipeFieldRetiringPhase[kMGPipeInputFieldCount] =
"-", // GetProvokingVertexMode
"-", // GetRenderStateParameters
"-", // GetRenderStateParametersVersion
"P3b/P4b", // GetSamplingResolutionGeneration
"-", // GetSamplingResolutionGeneration
"-", // GetScissorBox
"-", // GetStencilState
"P3b/P4b", // GetTextureBindGeneration
"P3b/P4b", // GetTextureContextId
"-", // GetTextureBindGeneration
"-", // GetTextureContextId
"P7", // GetTextureObject
"P3b/P4b, P7", // GetTextureUnitObject
"P3b/P4b (Espryt), P7 (Magma)", // GetTransformFeedbackCapturedVertices
"P3b/P4b (Espryt), P7 (Magma)", // GetTransformFeedbackGeneration
"-", // GetTransformFeedbackCapturedVertices
"-", // 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
"-", // IsTransformFeedbackActive
"-", // IsTransformFeedbackPaused
"-", // InvalidateCompileEnv
"P9", // ValidateProgramName
"P9", // RecordError
"P3b/P4b (Espryt), P7 (Magma)", // GetBoundTransformFeedbackLifetimeId
"-", // GetBoundTransformFeedbackLifetimeId
"P7/P9", // HasOpenTransformFeedbackSpan
};
@@ -187,7 +187,7 @@ inline constexpr MGPipeFieldOwnership kMGPipeFieldOwnershipForward[kMGPipeFieldO
MGPipeFieldOwnership::kBarrierPulled, // GetTextureObject
MGPipeFieldOwnership::kBarrierPulled, // HasOpenTransformFeedbackSpan
MGPipeFieldOwnership::kBarrierPulled, // ValidateProgramName
MGPipeFieldOwnership::kBarrierPulled, // InvalidateCompileEnv
MGPipeFieldOwnership::kFatal, // InvalidateCompileEnv
MGPipeFieldOwnership::kBarrierPulled, // RecordError
};
inline constexpr const char* kMGPipeFieldOwnershipForwardMechanism[kMGPipeFieldOwnershipForwardCount] = {
@@ -196,7 +196,7 @@ inline constexpr const char* kMGPipeFieldOwnershipForwardMechanism[kMGPipeFieldO
"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
"DELETED under split by P5c ev; the re-arriving caps snapshot IS the invalidation (R-12)", // InvalidateCompileEnv, retires in -
"OnGlError, the ordered reverse-channel error post (R-12); its ordering is P9's", // RecordError, retires in P9
};
@@ -301,8 +301,8 @@ inline constexpr SizeT kMGPipeVerbBoundaryOpCount = 23;
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 = 28;
inline constexpr SizeT kMGPipeFatalFieldCount = 2;
inline constexpr SizeT kMGPipeRecordSuppliedFieldCount = 41;
inline constexpr SizeT kMGPipeApplierDerivedFieldCount = 4;
inline constexpr SizeT kMGPipeBarrierPulledFieldCount = 15;
inline constexpr SizeT kMGPipeFatalFieldCount = 3;
static_assert(kMGPipeRecordSuppliedFieldCount + kMGPipeApplierDerivedFieldCount + kMGPipeBarrierPulledFieldCount + kMGPipeFatalFieldCount == kMGPipeInputFieldCount, "the four class sizes do not partition the field set");
+11 -9
View File
@@ -308,6 +308,7 @@ enum class MGPipeFieldEmitter : Uint8 {
BindRenderState,
BindVertexElements,
CreateRenderState,
SetContextValues,
SetDispatchProgram,
SetDrawProgram,
SetDynamicState,
@@ -323,6 +324,7 @@ inline constexpr const char* kMGPipeFieldEmitterNames[] = {
"BindRenderState",
"BindVertexElements",
"CreateRenderState",
"SetContextValues",
"SetDispatchProgram",
"SetDrawProgram",
"SetDynamicState",
@@ -334,7 +336,7 @@ inline constexpr const char* kMGPipeFieldEmitterNames[] = {
};
inline constexpr MGPipeFieldEmitter kMGPipeFieldEmittedBy[kMGPipeInputFieldCount] = {
MGPipeFieldEmitter::kNone, // GetActiveTextureUnit
MGPipeFieldEmitter::SetContextValues, // GetActiveTextureUnit
MGPipeFieldEmitter::SetDynamicState, // GetBlendColor
MGPipeFieldEmitter::CreateRenderState, // GetBlendEquationIndexed
MGPipeFieldEmitter::CreateRenderState, // GetBlendFuncIndexed
@@ -343,7 +345,7 @@ inline constexpr MGPipeFieldEmitter kMGPipeFieldEmittedBy[kMGPipeInputFieldCount
MGPipeFieldEmitter::kNone, // GetBufferBindingSlot
MGPipeFieldEmitter::kNone, // GetBufferBindingPoint
MGPipeFieldEmitter::kNone, // GetBufferBindingPointCount
MGPipeFieldEmitter::kNone, // GetTouchedBufferBindingPointCount
MGPipeFieldEmitter::SetContextValues, // GetTouchedBufferBindingPointCount
MGPipeFieldEmitter::SetDynamicState, // GetClampReadColor
MGPipeFieldEmitter::SetDynamicState, // GetClearColor
MGPipeFieldEmitter::SetDynamicState, // GetClearDepth
@@ -358,7 +360,7 @@ inline constexpr MGPipeFieldEmitter kMGPipeFieldEmittedBy[kMGPipeInputFieldCount
MGPipeFieldEmitter::SetShaderImages, // GetImageTextureBinding
MGPipeFieldEmitter::SetDynamicState, // GetLineWidth
MGPipeFieldEmitter::CreateRenderState, // GetLogicOp
MGPipeFieldEmitter::SetSamplerViews, // GetMaxTouchedTextureUnit
MGPipeFieldEmitter::SetContextValues, // GetMaxTouchedTextureUnit
MGPipeFieldEmitter::CreateRenderState, // GetMinSampleShadingValue
MGPipeFieldEmitter::SetPatchState, // GetPatchDefaultInnerLevel
MGPipeFieldEmitter::SetPatchState, // GetPatchDefaultOuterLevel
@@ -382,23 +384,23 @@ inline constexpr MGPipeFieldEmitter kMGPipeFieldEmittedBy[kMGPipeInputFieldCount
MGPipeFieldEmitter::kNone, // GetTextureContextId
MGPipeFieldEmitter::kNone, // GetTextureObject
MGPipeFieldEmitter::SetSamplerViews, // GetTextureUnitObject
MGPipeFieldEmitter::kNone, // GetTransformFeedbackCapturedVertices
MGPipeFieldEmitter::kNone, // GetTransformFeedbackGeneration
MGPipeFieldEmitter::SetContextValues, // GetTransformFeedbackCapturedVertices
MGPipeFieldEmitter::SetContextValues, // GetTransformFeedbackGeneration
MGPipeFieldEmitter::kNone, // GetTransformFeedbackPausedPrimitiveCounter
MGPipeFieldEmitter::kNone, // GetTransformFeedbackProgram
MGPipeFieldEmitter::SetDynamicState, // GetViewport
MGPipeFieldEmitter::SetDynamicState, // GetViewportIndexed
MGPipeFieldEmitter::CreateRenderState, // IsCapabilityEnabled
MGPipeFieldEmitter::CreateRenderState, // IsCapabilityEnabledIndexed
MGPipeFieldEmitter::kNone, // IsTransformFeedbackActive
MGPipeFieldEmitter::kNone, // IsTransformFeedbackPaused
MGPipeFieldEmitter::SetContextValues, // IsTransformFeedbackActive
MGPipeFieldEmitter::SetContextValues, // IsTransformFeedbackPaused
MGPipeFieldEmitter::kNone, // InvalidateCompileEnv
MGPipeFieldEmitter::kNone, // ValidateProgramName
MGPipeFieldEmitter::kNone, // RecordError
MGPipeFieldEmitter::kNone, // GetBoundTransformFeedbackLifetimeId
MGPipeFieldEmitter::SetContextValues, // GetBoundTransformFeedbackLifetimeId
MGPipeFieldEmitter::kNone, // HasOpenTransformFeedbackSpan
};
inline constexpr SizeT kMGPipeEmittedFieldCount = 40;
inline constexpr SizeT kMGPipeEmittedFieldCount = 47;
struct MGPipeFilledState {
Uint64 CurrentVerbSerial;
+8 -5
View File
@@ -12,7 +12,7 @@
// Regenerate with `python3 scripts/gen_pipe.py`; CI runs it and diffs the result.
// This file is included from MG_Pipe/MGPipe.h inside namespace MobileGL::MG_Pipe.
// share group: 11 calls. A null entry means the backend does not implement this
// share group: 12 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, const void* blobBytes, Uint64 blobByteCount, MGPReplySlot* reply);
@@ -26,9 +26,10 @@ struct MGPipeScreen {
void (*FenceWait)(const MGPFenceWait* payload, MGPReplySlot* reply);
void (*FenceDestroy)(const MGPHandleOnly* payload);
void (*FenceWaitServer)(const MGPFenceWait* payload);
void (*ApplierReset)(const MGPApplierReset* payload);
};
// context: 65 calls. A null entry means the backend does not implement this
// context: 67 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);
@@ -96,11 +97,13 @@ struct MGPipeContext {
void (*BindStreamOutput)(const MGPStreamOutputBind* payload);
void (*SetStorageBlockBinding)(const MGPStorageBlockBinding* payload, const void* blobBytes, Uint64 blobByteCount);
void (*CopyFramebufferToTexture)(const MGPCopyFromFramebuffer* payload);
void (*ObjectDeath)(const MGPHandleOnly* payload);
void (*SetContextValues)(const MGPContextValues* payload);
};
inline constexpr SizeT kMGPipeScreenCallCount = 11;
inline constexpr SizeT kMGPipeContextCallCount = 65;
inline constexpr SizeT kMGPipeCallCount = 76;
inline constexpr SizeT kMGPipeScreenCallCount = 12;
inline constexpr SizeT kMGPipeContextCallCount = 67;
inline constexpr SizeT kMGPipeCallCount = 79;
// A table that is not exactly its call count of function pointers has grown a
// member that no generator knows about.
+12
View File
@@ -320,3 +320,15 @@ inline void MGP_SetStorageBlockBinding(const MGPStorageBlockBinding* payload, co
inline void MGP_CopyFramebufferToTexture(const MGPCopyFromFramebuffer* payload) {
gMGPipeContext.CopyFramebufferToTexture(payload);
}
inline void MGP_ApplierReset(const MGPApplierReset* payload) {
gMGPipeScreen.ApplierReset(payload);
}
inline void MGP_ObjectDeath(const MGPHandleOnly* payload) {
gMGPipeContext.ObjectDeath(payload);
}
inline void MGP_SetContextValues(const MGPContextValues* payload) {
gMGPipeContext.SetContextValues(payload);
}
+17 -1
View File
@@ -112,6 +112,8 @@ inline Bool MGPipeVerify(const MGPPatchParameter& a, const MGPPatchParameter& b,
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 MGPApplierReset& a, const MGPApplierReset& b, const char** outField);
inline Bool MGPipeVerify(const MGPContextValues& a, const MGPContextValues& 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);
@@ -259,6 +261,10 @@ struct MGPipeHasFieldVerifier<MGPStorageBlockBinding> : std::true_type {};
template <>
struct MGPipeHasFieldVerifier<MGPCopyFromFramebuffer> : std::true_type {};
template <>
struct MGPipeHasFieldVerifier<MGPApplierReset> : std::true_type {};
template <>
struct MGPipeHasFieldVerifier<MGPContextValues> : std::true_type {};
template <>
struct MGPipeHasFieldVerifier<RenderStateParameters> : std::true_type {};
template <>
struct MGPipeHasFieldVerifier<PixelStoreParameters> : std::true_type {};
@@ -662,6 +668,16 @@ inline Bool MGPipeVerify(const MGPCopyFromFramebuffer& a, const MGPCopyFromFrame
return true;
}
inline Bool MGPipeVerify(const MGPApplierReset& a, const MGPApplierReset& b, const char** outField) {
MGP_FIELDS_MGPApplierReset(MGP_VERIFY_FIELD)
return true;
}
inline Bool MGPipeVerify(const MGPContextValues& a, const MGPContextValues& b, const char** outField) {
MGP_FIELDS_MGPContextValues(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;
@@ -709,4 +725,4 @@ inline Bool MGPipeVerify(const MGPVertexBindingPointWire& a, const MGPVertexBind
#undef MGP_VERIFY_FIELD
inline constexpr SizeT kMGPipeVerifiedPayloadCount = 77;
inline constexpr SizeT kMGPipeVerifiedPayloadCount = 79;
+40 -1
View File
@@ -146,7 +146,10 @@ enum class MGPWireOp : Uint16 {
BindStreamOutput = 74,
SetStorageBlockBinding = 75,
CopyFramebufferToTexture = 76,
kOpCount = 77,
ApplierReset = 77,
ObjectDeath = 78,
SetContextValues = 79,
kOpCount = 80,
};
// THE FLAGS, EXPORTED ONCE, INDEXED BY OPCODE (P5 R-13.4). MGPWireRecHeader::Flags is
@@ -244,6 +247,9 @@ inline constexpr Uint32 kMGPipeCallFlags[static_cast<SizeT>(MGPWireOp::kOpCount)
/* 74 BindStreamOutput */ static_cast<Uint32>(kNone),
/* 75 SetStorageBlockBinding */ static_cast<Uint32>(kHasBlob),
/* 76 CopyFramebufferToTexture*/ static_cast<Uint32>(kNone),
/* 77 ApplierReset */ static_cast<Uint32>(kNone),
/* 78 ObjectDeath */ static_cast<Uint32>(kNone),
/* 79 SetContextValues */ static_cast<Uint32>(kNone),
};
static_assert(sizeof(kMGPipeCallFlags) / sizeof(kMGPipeCallFlags[0]) ==
static_cast<SizeT>(MGPWireOp::kOpCount),
@@ -905,6 +911,30 @@ static_assert(sizeof(MGPWireRec_CopyFramebufferToTexture) ==
((sizeof(MGPWireRecHeader) + sizeof(MGPCopyFromFramebuffer) + 7u) & ~SizeT(7u)),
"MGPWireRec_CopyFramebufferToTexture gained padding; the wire format moved");
struct alignas(8) MGPWireRec_ApplierReset {
MGPWireRecHeader Header;
MGPApplierReset Payload;
};
static_assert(sizeof(MGPWireRec_ApplierReset) ==
((sizeof(MGPWireRecHeader) + sizeof(MGPApplierReset) + 7u) & ~SizeT(7u)),
"MGPWireRec_ApplierReset gained padding; the wire format moved");
struct alignas(8) MGPWireRec_ObjectDeath {
MGPWireRecHeader Header;
MGPHandleOnly Payload;
};
static_assert(sizeof(MGPWireRec_ObjectDeath) ==
((sizeof(MGPWireRecHeader) + sizeof(MGPHandleOnly) + 7u) & ~SizeT(7u)),
"MGPWireRec_ObjectDeath gained padding; the wire format moved");
struct alignas(8) MGPWireRec_SetContextValues {
MGPWireRecHeader Header;
MGPContextValues Payload;
};
static_assert(sizeof(MGPWireRec_SetContextValues) ==
((sizeof(MGPWireRecHeader) + sizeof(MGPContextValues) + 7u) & ~SizeT(7u)),
"MGPWireRec_SetContextValues 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));
@@ -1182,6 +1212,15 @@ inline Bool MGPipeApplyWireRecord(MGPWireOp op, const void* record, Uint64 size,
case MGPWireOp::CopyFramebufferToTexture:
MGP_WIRE_CHECK_BOUNDS(MGPWireRec_CopyFramebufferToTexture, "CopyFramebufferToTexture");
break;
case MGPWireOp::ApplierReset:
MGP_WIRE_CHECK_BOUNDS(MGPWireRec_ApplierReset, "ApplierReset");
break;
case MGPWireOp::ObjectDeath:
MGP_WIRE_CHECK_BOUNDS(MGPWireRec_ObjectDeath, "ObjectDeath");
break;
case MGPWireOp::SetContextValues:
MGP_WIRE_CHECK_BOUNDS(MGPWireRec_SetContextValues, "SetContextValues");
break;
case MGPWireOp::kInvalid:
case MGPWireOp::kOpCount:
default:
+539
View File
@@ -0,0 +1,539 @@
# CONTRACT-P5C — the wire contract for zeroing the inproc split's direct cross-role memory access
Authority: this file, beside `CONTRACT-P5.md` (table 0's encodings, the byte carriers, field
ownership, role/thread ownership, the knobs, R-1…R-17) and `CONTRACT-P5B.md` (the 25 migrated
class-C slots). Where it disagrees with either, this file is newer and wins, and §7 lists
every such place.
**How to change it.** Package c0c's file, edited by the integrator first. A P5c package (tx /
ev / hd / ct / rv / gt) 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 @ 11ac3de6` (the P5c plan commit; code-identical to the audit head
`a79a0af6`). Every `file:line` below was read at that commit. The audit this contract
discharges is `~/w7/notes/p5c/p5c-audit-v1.md` (59 sites); ROADMAP.md "P5c 计划" tabulates
them as T1–T5, B1–B4, R1–R5, C1, G1–G6, A1.
---
## §0 What P5c is, and the one rule above every row
P5/P5b put verb records, `SEG_STAGE` blobs, replies and caps snapshots on the wire. The audit
proved the two roles still read and write each other's memory directly at 59 sites, correct
only because the verb barrier and the shared address space happen to hold. P6 replaces how
the rings are delivered; it cannot replace a read of memory that does not exist in the other
process. **P5c makes `inproc` honest: between the two roles, nothing crosses except
`SEG_CMD` / `SEG_STAGE` / `SEG_REPLY` / `SEG_EVENT` / the caps snapshot / control frames —
so that P6 is a transport swap and nothing else.**
Rules A (a content record declares its bytes), B (no host pointer crosses) and C (an applier
entry point may not hold a pointer past its return) are CONTRACT-P5 §0's and bind every row
here unchanged. Rule D (a verb crosses AS THE CALL) is CONTRACT-P5B §0's and is NOT relaxed:
P5c changes WHERE the sink resolves the call's objects from (the record's handles, §3), not
what the record carries. P5c adds one rule:
**Rule E — a role may not name the other role's memory.** With an active transport, the
apply thread resolves every object from a handle the record carried (`§3`), every byte from
`SEG_STAGE` adopted into server-owned storage (`§2`), and every reverse notification is a
`SEG_EVENT` record (`§4`); the GL thread reaches server state only through replies, events
and the caps snapshot. A violation is `Fatal{RoleViolation, "<surface>"}` and the two guard
layers that raise it are §6's. "The barrier held" and "same address space" are no longer
accepted as mechanisms anywhere in this file.
Refusal vocabulary is CONTRACT-P5B's, unchanged: `Fatal{ProtocolCorruption, "<row>.<field>"}`
for a record the codec cannot prove, `Fatal{UnmigratedVerb, "<GL slot>[+<QUALIFIER>]"}` for a
shape no sink implements, a null backend slot DECLINES (`return false`). P5c adds one family:
`Fatal{RoleViolation, "<surface>"}` (§6) and `Fatal{EventRingOverflow}` (§4.4).
---
## §1 Table 0 additions — encodings the P5c rows introduce
| field | the ruling | zero means | who reads it |
|---|---|---|---|
| **reverse-channel `MGPBlobRef`** | An `OnBufferWriteback` blobref on the wire names **SEG_EVENT**: `Seg = Wire::kSegEvent` (4, `PipeWireCodec.h:62`), `Offset` = the byte offset of the inline payload inside the SEG_EVENT mapping (`EventRingConsumer::OffsetInSegment`, `EventRing.h:182-185`), `Size` = the head's `Size`, cross-checked against the record's tail. **Never a host address** — rule B binds the reverse direction exactly as it binds `MGHostSpan` (R-2). Under monolith the blobref keeps its P3a shape (`Seg = kMGHostSpanSegNone`, `Offset` IS the mapped address); the two shapes are distinguished by `Seg`, not by the transport knob. | `Size == 0` with a live resource is legal (a zero-length writeback) | the client consumer (`ResourceTracker.h`, §4.3) |
| **`MGPObjectDeath` reuses `MGPHandleOnly`** | `{Handle, Kind, Pad0}` (16 B, `MGPipeTypes.h:93-98`). `Kind` is the `MGPipeKind` of the dead frontend object, widened to `Uint32` exactly as the existing rows widen it. One payload for all seven kinds the death switch handles (`Managers.cpp:224-257`): Texture, Framebuffer, Renderbuffer, SamplerCso, ShaderCso, SamplerViewCso, VertexElementsCso. | `Handle` null = "the object never crossed" — the client emits NOTHING in that case (§5.2), so a null handle arriving is `Fatal{ProtocolCorruption, "ObjectDeath.Handle"}` | `ServerVerbSink::OnObjectDeath` |
| **`MGPApplierReset::ContextSerial`** | `Uint64`. The client-side context's make-current serial at the edge that primed it. P5c has exactly one context per session, so the value is ASSERTED equal to the session's, not dispatched on; P6's multi-context shape reads it for real. | 0 = the first make-current | `ServerVerbSink::OnApplierReset` |
| **`MGPContextValues`** | The rv field table (§5.3), one fixed-width POD, `MGP_ASSERT_POD`-pinned. Whole-record hash-suppressed like every other `set_*` call: it crosses only when one of its source values moved since the last emission. There is no dirty mask in the payload — a suppressed record means "nothing moved", never "field invalid". | — | `MGPipeApplySetContextValues`, the server accessors it feeds |
| **texture per-level extent, server-side** | `max(1, base_extent >> level)` computed from the descriptor's `Width/Height/Depth` and `Levels` (`MGPResourceDesc`, `MGPipeTypes.h:295-360`). The client does NOT emit per-level extents; the derivation is the mip chain's definition and two honest ends compute the same number. | — | tx's `SyncMipmapsToBackend` (§2.2) |
| **`EventKind` = 4: `kEventGlError`** | `EventRing.h`'s enum gains `kEventGlError = 4` beside the existing three (:46-51). Head `EventGlErrorHead { Uint32 Code; Uint32 MessageBytes; }` (8 B) followed by the NUL-terminated message inline, `MessageBytes = strlen + 1`, **capped at 1024** (a longer message is truncated at the producer; the cap is a static_assert, not a check). `Code` is the frontend `ErrorCode`, widened. | `MessageBytes == 0` is `Fatal{ProtocolCorruption, "kEventGlError"}` (the NUL travels, rule A's twin) | `ClientSession::DrainEventRing` |
| **`MGPSurfaceInfo` zero-extent semantics** | `Width == 0 && Height == 0` is the FORMAT-ONLY publication (the DirectGLES shape: the placeholder's extent is deliberately left alone, only the depth/stencil `InternalFormat` moves); a non-zero extent is the SWAPCHAIN shape (storage at the extent, then format). `Samples`/`Layers` are informational only (1/1 from Vulkan, 0/0 from GLES; the placeholder attachment model has no MSAA) and the consumer ignores them. | see left | the surface-changed consumer |
---
## §2 tx — the server's texture staged shadow
The texture half of `resource_subdata` stages the level bytes into `SEG_STAGE` today and
`ApplyTextureUpload` drops the pointer (`PipeApply.cpp:989-1036`: the gate, the accumulation
and the serial — the `bytes` parameter is used only by the non-null gate at :1006-1008).
Espryt then re-reads the client's `MipmapStorage` at sync time (Managers.cpp:6940, :7129,
:7198, :7315), reads per-level shape from the client object (:7314, :7332,
`DirectGLES.cpp:8502-8507`, :8528-8529), and falls back to the client for dirty regions with
no pending upload (Managers.cpp:7360, :7371). Magma WRITES the client's level storage
(`VulkanRenderer.cpp:1562-1609`: `AllocateStorage` + `MarkStorageDirty(..., false)`).
**tx ends all of it: the staged bytes are adopted, and the server's sync reads nothing but
its own shadow and the descriptor.**
### 2.1 `StagedTextureStore` — ownership and coverage
`MobileGL/MG_Remote/Server/StagedTextureStore.h`, the texture twin of `StagedShadow.h`
(R-11), and held to its four rulings:
1. **Keyed by the wire handle the record carried** (`KeyForHandle` = `{slot, gen}` under a
tag bit) — AMENDED from "the twin's address" at tx's landing, for two reasons that
together left no honest alternative: constructing a texture twin calls `glGenTextures`
(Managers.cpp:5496), so a twin-address key either forces twin minting at adopt time (a
driver name burnt for a texture that may never draw, and a GL context required in the
R-16 unit case — buffer twins mint no GL and can be created lazily) or strands levels
adopted before the first sync; and the handle is rule E's cross-role identity anyway,
`{slot, gen}`-exact across a slot recycle. Magma's T5 path, which has no wire handle in
its identity tables, keys by twin address under a SECOND tag bit, so the two key spaces
can never collide. Every event that ends a key's life — respecify, destroy
(`resource_destroy`'s texture arm, delivered precisely because the store is
handle-keyed), context death — has a call site to drop it from.
2. **Coverage is the WHOLE STAGED RUN per (uploadTarget, level)** — AMENDED from "the
region set" at tx's landing: a texture `resource_subdata` always stages the entire
level shadow (`Blob.Size` IS the declared byte count), so the run is the honest unit;
the region set stays what it always was — the dirty SHAPE the pending set carries.
Region-precise coverage would `Fatal` on the legal
texStorage→small-box `glTexSubImage`→conversion-fallback flow, whose sync reads the
whole level. A sync that reaches a level no record covered is
`Fatal{StageSnapshotTooNarrow, "<site>"}` — the same words as the buffer half, and for the
same reason (`StagedShadow.h:96-116`: moving zeroes into the store is silent data loss,
not a missing optimisation).
3. **`copies` is a constructor parameter**, false reproducing the monolith expression
character for character (the client shadow answers, nothing is allocated). G1's pull-build
byte-identity is preserved the same way R-11 preserved it.
4. **A header with diagnostics**, not a block inside Managers.cpp, so a unit case builds one
store of each kind and asserts the difference (R-16 — `ServerLoopTest.cpp:616-760` is the
shape the tests copy).
`PendingUpload` (`PipeApply.h:289-295`) gains NO byte pointer: the record's bytes move to the
store at apply time, and the pending set keeps its job of naming which (target, level, box)
is dirty-by-record. The store, not the pending set, is the byte owner; a pending upload with
no store coverage is the `Fatal{StageSnapshotTooNarrow}` case, not a silent re-read.
### 2.2 What the sync path reads after tx
| the read today | after tx |
|---|---|
| level texels from client `MipmapStorage` (`MapMipmapData`) | the store's adopted bytes |
| per-level extent from the client object | §1's derivation from the descriptor |
| texture target / levels count from the client object | the descriptor (`Target`, `Levels`; the `MGB_STORAGE_LEVELS` handle arm already reads `pushedStorage->Desc.Levels`, Managers.cpp:6651-6652) |
| dirty region, level HAS a pending upload | the record's regions (unchanged — already record-supplied, Managers.cpp:7358-7369) |
| dirty region, level has NO pending upload (GPU-generated mips, re-derivation) | **the server's own dirty mark on the shadow** (§2.3) — the client is never asked |
| level EXISTS at all (`Levels = N` says nothing about a sparse chain) | the store's DEFINED-NESS, fed by the respecify hook: a named level redefines that one, an immutable whole-resource respecify defines the whole chain (all six cube faces included, GL 4.6 core 8.19), a mutable whole-resource respecify defines nothing. Without this the §1 derivation would define `{0,0,0}`-extent holes into existence and change FBO/sampling completeness — added at tx's landing, the contract's own omission |
### 2.3 GPU-generated mips (T5) — who owns "dirty" now
A GPU-side generation (Magma's `GenerateMipmap`, Espryt's re-derivation arms) dirties the
SERVER's shadow, not the client's. The two backends land this in their own shapes, both
final: **Magma**'s `EnsureGenerateMipmapStorageAllocated` is replaced by a store operation
that marks the level Defined at the §1 extent and GpuDirty-in-shadow (the store answers
"exists" and "needs upload" for it; the client object is never touched). **Espryt**
generates the levels ON THE DRIVER, so no server shadow allocation is needed at all — the
levels are already where a sync would put them, and the shadow's staleness is the correct
state ruled below. Either way the client's `TextureObjectMipmap` is not touched from the
apply thread — `AllocateStorage` and `MarkStorageDirty` on it are §6 layer-1 surfaces.
The client shadow for such levels is stale and that is CORRECT: the two readers that could
observe the staleness are both named refusals under split — `glGetTexImage` served from the
client shadow (class C, P9) and `texture-remint-pull` (`Fatal{UnmigratedEmulation}`). This is
i1's copy-image-shadow-mirror ruling (CONTRACT-P5B §2) applied to the mip chain, and tx
reports which scenarios reach either Fatal.
### 2.4 The audit gate (E-P5c #2)
`MOBILEGL_IPC_AUDIT=1` fills retired staging with `0xDD` (R-11). After tx the texture bytes
are adopted before retire, so the `0xDD` fill covers them: **reverting the adoption to
pointer-dropping MUST turn one named texture scenario red on the four A/B traces.** That
revert is tx's red-once (R-16), and it is the gate that makes "the server consumes the staged
bytes" a checked fact rather than a design intention.
---
## §3 hd — sinks and twins resolve by the handle the record carried
The handle-keyed `GetOrCreate(MGPipeHandle)` (`SlotTables.h:278-326`) exists since P3a and
has deliberately no caller at the contract commit (:275-277). **P5c is its first caller.**
The rules:
1. **With an active transport, `MGPipeSlots()` is a client-only surface.** `Acquire`,
`FindByLifetimeId`, `Free` called from the apply thread are `Fatal{RoleViolation,
"MGPipeSlots"}` (§6 layer 1). The minting `GetOrCreate(const StatePtr&)`
(`SlotTables.h:209-252`) and the death switch's `DestroyByLifetimeId` arms are
monolith-only; split paths call the handle forms (`GetOrCreate(handle)`,
`ReleaseByHandle`, :350-361).
**THE NAMED EXEMPTION, ruled at the tx/ev/hd merge:** the sites whose handle-carrying
records the client does not EMIT yet. `set_shader_buffers` and
`set_stream_output_targets` sit in the catalogue but are P4b's to emit
(`SetHashSuppressor.h` says so), so the buffer binding-point ensures they would feed
(`EnsureBufferResource`→`HandleOfBuffer`, Managers.cpp:3199, and its SSBO/UBO/atomic/
XFB/PBO callers) and the GPU-written announcement (`MarkBufferGpuWritten`'s handle
answer, `MGPipeAnnounceBufferGpuWritten` for Magma) have no record handle to resolve
from in P5c. Those probes run inside `MGPipeReverseAnnouncementScope`
(`SlotAllocator.h`) — one read-only lifetime-id read, scoped, named and greppable,
retired by P4b's emission (Espryt) and P7's server-side binding table (Magma). Every
other apply-thread allocator access (`Acquire`, `Free`, and `FindByLifetimeId` outside
the scope) stays Fatal with no exemption. The audit's B2 row is correspondingly
re-scoped: what hd retires is every site a record DOES name; the rest is this scope.
**THE SECOND NAMED EXEMPTION, ruled the same day:** the G6 frontend-keyed twin registry
— every `HandleOf`/`Find`/`GetOrCreate(const StatePtr&)` probe the texture / sampler /
sampler-view / VAO / program resolvers make, and the mailbox-delivered death switch
until ct's record replaces the hop (ct keeps a documented NoSession server-only-fixture
arm, and that arm is inside the scope too). These run inside
`MGPipeFrontendKeyedRegistryScope` (`SlotAllocator.h`), the executable form of §5.4's
pinned object-surface list: wrapping a site names the debt in code, an unwrapped probe
still aborts, and the guard's death tests pin exactly that. Retires with the G6 row's
own phases (P3b/P4b rekeys; the death switch's scope dies when the mailbox hop does).
2. **The records already carry the handles.** `MGPBlit::ReadFbo/DrawFbo`, `MGPMipPlan::Res`,
`MGPCopyFromFramebuffer::Dst`, `MGPDrawIndirect::Buffer` / `ParameterBuffer`,
`MGPGridInfo::IndirectBuffer` — hd's edit is to USE them, not to add fields. A site that
needs an object no record names is a missing handle and stops at the integrator, not a
quietly-added lifetime-id probe.
3. **Named blit.** `ServerVerbSink::OnBlit` resolves `ReadFbo`/`DrawFbo` through the FBO
twin table by handle — AMENDED in shape at hd's landing: the named backend ENTRY's
signature takes frontend `SharedPtr<FramebufferObject>` and the shared function table
cannot grow a handle parameter without moving G1, so the record's handles reach the
backend through a split-only verb-handle workspace in `MGPipeApplierState` (the sink
writes it before dispatch, the backend reads it within the same verb), and
`BlitFramebuffer` takes its named arm when the workspace names a pair: twins resolved
by `GetOrCreateByHandle`, frontend objects reached through the twin table's state note
(`NoteStateForHandle`/`StateForHandle` — a server-side note seeded by the record-driven
sync, object-class, P3b/P4b retires it with the twin tables). A backend that does not
consume the workspace declines LOUDLY (Magma until P7) — a blit that silently landed on
the bound FBO would be a wrong picture, not a missing feature. The client's
`ScopedBlitBindings` (`EmitTables.cpp:741-762`) is deleted from the split path — it exists
only to stage values for the server's binding-slot read, and the read is gone. The
record's `MGPBlit` payload is unchanged.
4. **CopyTex** (`DirectGLES.cpp:8560-8563`, :8655-8658) resolves the destination from
`MGPCopyFromFramebuffer::Dst`; the `GetTextureUnitObject` unit-slot read is a layer-1
surface at these two sites.
5. **Indirect buffers.** Draw-indirect / parameter / dispatch-indirect buffer objects come
from the record's handle fields (CONTRACT-P5B §2 d1/i1 already put them there); the
`GetBufferBindingSlot(DrawIndirect)` read at `DirectGLES.cpp:6702-6703` and its dispatch
twin are layer-1 surfaces at those sites.
6. **`HasDefinedContent` is the descriptor's bit OR the staged coverage set** — AMENDED at
hd's landing, because this contract's premise was wrong: the bit does NOT move only at a
storage-defining call. The streaming idiom (`glBufferData(size, NULL)` then
`glBufferSubData`) defines content through subdata with NO new descriptor
(Managers.cpp:3130-3146 says so, `ServerLoopTest`'s streaming cases pin it), and a pure
descriptor read would orphan live bytes at the next respecify. The answer is
`Desc.HasDefinedContent || the staged coverage set is non-empty` — the coverage set IS
"content records delivered since the last orphan", pointwise equivalent to the
frontend's flag and purely server-side. `bufferObject->HasDefinedContent()`
is a layer-1 surface.
7. **caps.** Magma's four reads of the client mirror (`DirectVulkan.cpp:713-715`,
`VulkanRenderer.cpp:667-676`, `VertexInputStateFactory.cpp:249-250`, :502-503) read
`ServerLoopInstance().Backend()->GetDynamicParameters()` — the server's own backend, the
same source Espryt's `ActiveBackendFormatCaps` already prefers (`Utils.cpp:45-48`).
`Utils.cpp:50`'s fallback arm to `pActiveBackendObject` is **refused** with an active
transport (`Fatal{RoleViolation, "caps-mirror"}`): the server's backend exists whenever
the session does, and a silent read of the mirror would hide a bring-up ordering defect.
8. **The legacy buffer arm is a named refusal under transport** (B3). `MappedData()` /
`IsMapped()` / `GetChangeSerial()` / `SyncPersistentMappedRange()` on the frontend
`BufferObject` (Managers.cpp:1012-1022, :1119-1121, :2944-2949, :3281-3327) take
`Fatal{RoleViolation, "buffer-legacy-arm"}` from the apply thread — the same shape as
`Fatal{PipeLegacyMemosDisabled}`, closing the arm that a cleared subsystem bit 7 currently
leaves reachable with one `MGLOG_D`.
---
## §4 ev — SEG_EVENT is the only reverse channel
The segment, the ring, the three event heads and the full consumer exist
(`EventRing.h`, `ClientSession.cpp:176-267`); production has **zero producers**
(`ServerSession::PublishEvents`, :484-492, has no caller). ev wires the three producers and
retires every direct call into the client. The ten `MGPipeCallbacks` members stay ten; P5c
arms three and a half (writeback, gpu-written, surface-changed, and gl-error as the fourth
kind) — the remaining six keep CONTRACT-P5's P9 phase.
### 4.1 Producer ownership (Table 3 amendment)
With an active transport, the three reverse entries of `gMGPipeCallbacks` are installed by
the SERVER session (producer callbacks that Reserve + Publish into SEG_EVENT), never by the
client; `MGPipeInstallClientResourceCallbacks` (`ResourceTracker.h:606-613`) is
monolith-only. A second installation over a live entry is `Fatal{RoleViolation,
"callback-double-install"}` — the "never over an entry a backend already claimed" comment
becomes a check. The apply thread calling a client-installed callback (the R1/R2 shape) is a
layer-1 violation; the GL thread calling a server-installed producer is layer 2.
`DrainEventRing` calls the client consumers BY NAME (`MGPipeClientOnBufferWriteback` /
`MGPipeClientOnGpuWritten`, `ResourceTracker.h:553-601`), not through `gMGPipeCallbacks` —
the global table is a producer-side surface under split. **The drain points are TWO classes**
(AMENDED at the regression triage): inside `EmitAndWait` after the barrier
(`ClientSession.cpp:836`), AND at the return of the blocking EGL lifecycle RPCs
(`BackendObject_Remote`'s surface creation / resize / make-current). Both satisfy the same
safety premise — the apply thread is known idle because the work it was doing (the verb, the
RPC) has completed and this thread has published nothing since. The second class exists
because a surface-changed event posted during bring-up must be applied BEFORE the first
frontend query of the default framebuffer's attachments: waiting for the first verb's drain
answered the placeholder format to `glGetFramebufferAttachmentParameteriv`, and every buffer
allocated from that answer was blit-incompatible with the real surface.
### 4.2 The three (+1) producers
| event | producer site (today's direct call) | payload |
|---|---|---|
| `kEventBufferWriteback` | `Ops_H_Readback`'s writeback (Managers.cpp:2339-2343): the server copies the mapped bytes INTO the event record's inline tail instead of casting the pointer into `MGPBlobRef::Offset` | `EventBufferWritebackHead` + inline bytes |
| `kEventGpuWritten` | `MarkBufferGpuWritten` (Managers.cpp:2722-2753) and Magma's three bypasses (`UniformManager.cpp:1075`, :1231, `VulkanRenderer.cpp:11618`) — Magma's direct `bufferObject->MarkGpuWritten()` calls are ROUTED THROUGH the callback, the bypass is deleted | `EventGpuWrittenHead` + `EventRange[RangeCount]` |
| `kEventSurfaceChanged` | `PublishDefaultFramebufferDepthStencilFormat` (`DirectGLES.cpp:11519-11610`) and the swapchain twin (`SwapchainObject.cpp:276-333`): the backend fills `MGPSurfaceInfo` and posts; it no longer calls `AllocateStorage`/`SetInternalFormat` on `pDefaultFramebufferInfo` | `EventSurfaceChangedHead` |
| `kEventGlError` | `PipeInputs::RecordError` (`PipeFill.cpp:1764-1772`) posts with `ErrorCode` + message (§1). **Ordering is P9's** (CONTRACT-P5 table 2 row `RecordError`): the event is observed at the next drain point, which preserves per-thread program order of error-then-read but not cross-verb interleaving; that is the accepted P5c shape and the contract says so rather than discovering it in P6. | `EventGlErrorHead` + inline message |
`PipeInputs::InvalidateCompileEnv` (`PipeFill.cpp:1753-1756`) is DELETED with an active
transport: R-12's caps re-publication (`CapsMirror.cpp:78-80`) already invalidates the
compile environment on the client, and the forward is a write into the frontend with no wire
shape. Its FieldOwnership.def row moves to FATAL under split (§5.4).
### 4.3 The consumer's segment arm (and the guard that has to die first)
`MGPipeClientOnBufferWriteback`'s monolith guard (`ResourceTracker.h:560-564`) currently
REJECTS any `Seg != kMGHostSpanSegNone` with `MGLOG_E_ONCE` — wiring a producer without
removing it would drop every writeback event on arrival. The replacement arm:
```
Seg == kSegEvent -> resolve via the session's SegmentTable entry for kSegEvent
(installed at session start, ServerSession.cpp:333-335 and its
client twin); bounds-checked against the announced segment size
Seg == kMGHostSpanSegNone -> monolith only; with an active transport it is
Fatal{ProtocolCorruption, "OnBufferWriteback.Seg"} (rule B,
reverse direction)
anything else -> Fatal{ProtocolCorruption, "OnBufferWriteback.Seg"}
```
The surface-changed consumer (stub at `ClientSession.cpp:240-256` today) APPLIES the
`MGPSurfaceInfo` to the client-owned `pDefaultFramebufferInfo` — the allocate/format writes
happen on the GL thread against client memory, which is where R3's ownership always was.
### 4.4 Overflow (P5c's ruling, P9 owns the policy)
All four events are **lossless** in P5c. `Reserve` returning nullptr is
`Fatal{EventRingOverflow}`, not a drop: the ring is 256 KiB, events are drained at every verb
barrier, and a full ring under lockstep means a producer burst no measured workload has.
`CountDrop` and the `eventRingFull` latch stay built and stay unused-by-policy, exactly as
`EventRing.h:14-16` rules — P9 decides between waiting and dropping; P5c makes overflow a
defect instead. The exit gate `eventDropped == 0` at drain points (E-P5c #3) is what checks
this row.
**AMENDED at the regression triage — the ring is sized for events, not buffers.** A
whole-buffer writeback larger than the ring can NEVER fit (one record is capped at
capacity/2), so the CLIENT slices the request (`BufferWritebackSliceBytes`: a quarter of the
ring, floored at 4 KiB — a quarter, not the half, because the record carries its header
beside the payload and the ring may still hold small events from the same verb). Each slice
round-trips its own barrier + drain, so the ring holds at most one slice's bytes, and the
in-order channel makes the last slice's landing imply every earlier one. This is a
client-side ruling about request SHAPE, not a drop policy; the Fatal stays for a producer
burst of real events.
### 4.5 Round-trip red-once
Each of the three P5 events gets a unit round-trip beside `SessionTest.cpp:747-823` (the
fixture already drives one producer and one consumer over real segments), and ONE integration
scenario where reverting a producer to the raw-pointer shape turns the run red (E-P5c #3).
`kEventGlError` gets the unit round-trip only; its ordered-error sibling is P9's.
---
## §5 ct + rv — the two control records and the residual-value record
### 5.1 `applier_reset` — opcode 77, appended
`X(ApplierReset, MGPApplierReset, kScreen, kNone)`, appended after
`CopyFramebufferToTexture` (PipeCalls.def:233; opcode = position = 77).
`struct MGPApplierReset { Uint64 ContextSerial; };`, `MGP_ASSERT_POD(MGPApplierReset, 8)`.
- **Producer:** the GL thread, at the `tracker.FreshlyPrimed()` edge
(`PipeFill.cpp:2654-2667`), with an active transport ONLY. The emit happens BEFORE the
block's client-side resets (CsoCache, hash suppressor, vertex-input emitter — all client
surfaces, they stay); the record's barrier is what orders the server's reset against every
verb that follows.
- **Sink:** `ServerVerbSink::OnApplierReset(const MGPApplierReset&)` →
`MGPipeApplierReset()` (`PipeApply.cpp:1202-1300`) after asserting `ContextSerial` against
the session's. `g_applier` stays server-private (`PipeApply.cpp:409`).
- **The GL thread calling `MGPipeApplierReset()` directly with an active transport is
`Fatal{RoleViolation, "g_applier"}`** (G2, layer 2). Monolith keeps the direct call —
G1's byte-identity is untouched because the emit table exists only under split.
### 5.2 `object_death` — opcode 78, appended
`X(ObjectDeath, MGPHandleOnly, kCtxObject, kNone)` — the framebuffer family's FIRST wire
delete opcode (G3). Emitted by the GL thread from
`OnFrontendStateObjectDestroyed` (Managers.cpp:206-256) with an active transport:
1. Look the dying object's handle up in the CLIENT's own allocator
(`MGPipeSlots().FindByLifetimeId` — legal: client surface, client thread).
2. **No handle → emit nothing.** The server never saw the object, so there is no twin to
kill; this replaces the mailbox's unconditional delivery.
3. Handle → `EmitAndWait(ObjectDeath, {handle, kind})`. The wait keeps the death's
ordering against in-flight verbs that name the handle, which is the only property the
blocking `RunOnApplyThread` provided and the only one P5c keeps.
Sink: `ServerVerbSink::OnObjectDeath(const MGPHandleOnly&)` → the per-kind release
(`ReleaseByHandle`, `SlotTables.h:350-361`; the SamplerViewCso arm's idempotent
secondary path, Managers.cpp:239-256, is keyed by the view's handle the same way). The
mailbox hop (Managers.cpp:208-222) is deleted under split; it stays for monolith, where it
never fired anyway (the guard at :208 is transport-gated). **AMENDED at ct's landing:** a
documented NoSession fallback arm delivers a death to a server-only fixture's loop (a
transport configured with no client session is not a real split); with the §3.1
exemption, that arm's `DestroyByLifetimeId` probes ride inside the registry scope.
### 5.3 `set_context_values` — opcode 79, the rv field table
`X(SetContextValues, MGPContextValues, kCtxState, kNone)`. One POD, emitted at validate when
any covered value moved (the tracker's value-class dirty accounting already watches all of
them — "值类零新增记账", ARCHITECTURE §5.2), hash-suppressed as a whole. The fields and what
each retires:
| payload field | PipeInputs accessor it feeds | retires (FieldOwnership.def row) |
|---|---|---|
| `Uint32 ActiveTextureUnit` | `GetActiveTextureUnit` | BARRIER_PULLED "P3b/P4b" → RECORD_SUPPLIED |
| `Uint32 MaxTouchedTextureUnit` | `GetMaxTouchedTextureUnit` | BARRIER_PULLED "P3b/P4b" → RECORD_SUPPLIED (the hash-suppressed set's high-water mark rides THIS record's unsuppressed value) |
| `Uint32 TouchedBufferBindingPointCount[15]` (indexed by BufferTarget, the Coverage.def 15) | `GetTouchedBufferBindingPointCount(target)` | BARRIER_PULLED "P3b/P4b" → RECORD_SUPPLIED |
| `Uint8 IsTransformFeedbackActive`, `Uint8 IsTransformFeedbackPaused` | the two accessors | BARRIER_PULLED "P3b/P4b (Espryt), P7 (Magma)" → RECORD_SUPPLIED |
| `Uint64 TransformFeedbackGeneration`, `Uint64 BoundTransformFeedbackLifetimeId`, `Uint64 TransformFeedbackCapturedVertices` | the three accessors | BARRIER_PULLED → RECORD_SUPPLIED |
- **`GetCurrentVertexAttribute` does NOT ride this record.** Its problem is the applier's
cross-view conversion (FieldOwnership.def:77-82), so `MGPVertexAttribDefaults` grows to
carry the frontend's CONVERTED value (all three views as the frontend computed them), the
same amendment shape as P5b's `MGPCopyRegion` 64 → 72 B (CONTRACT-P5B §2 i1). The row
becomes RECORD_SUPPLIED; `set_vertex_attrib_defaults` keeps its opcode.
- **The three shutters** (`GetSamplingResolutionGeneration`, `GetTextureBindGeneration`,
`GetTextureContextId`) carry NO wire field: they move to APPLIER_DERIVED, answered from the
applier's own Serial — which is what their rows have said since P5 ("a shutter, not a
value", FieldOwnership.def:94-102). rv's edit makes the accessor DO it.
- **`GetTransformFeedbackProgram` stays BARRIER_PULLED** (object-class:
`SharedPtr<ProgramObject>`; the twin tables are P3b/P4b/P7's). rv's exit line "值类行为 0"
(E-P5c #4) is checked against the value-class list pinned in `FieldOwnershipTest`, and the
object-class rows are re-annotated with their retiring phase in the same edit so the test
can pin that they are ALL the remaining rows.
### 5.4 FieldOwnership.def amendments (one list, made by c0c)
The generator's four classes are unchanged. c0c edits rows; rv/tx/hd land the code:
- The §5.3 value rows → RECORD_SUPPLIED (derived, via Coverage.def's emitted list gaining
`SetContextValues` rows; the derivation's contradiction rule is what proves the edit
landed).
- The three shutters → APPLIER_DERIVED ("the applier's Serial").
- `GetCurrentVertexAttribute` → RECORD_SUPPLIED (the amended payload).
- `InvalidateCompileEnv` (field + forward rows) → FATAL with mechanism "DELETED under split
by P5c ev; R-12's caps re-publication replaced it" — the class is stated unconditionally
because the table only ever describes the split server's reads (under monolith there is no
server to read), so "under split" would be noise in a column that means it everywhere;
- **The texture family is NOT a set of new field rows** — a ruling, because the texel /
per-level extent / dirty reads are reads of frontend OBJECT internals reached through
`GetTextureUnitObject` / the `GetTextureObject` sticky forward, not `MGPipeInputField`
enum values, and a row naming a non-field stops the generator by design. What pins them
instead: (a) `GetTextureUnitObject`'s existing row is re-annotated — the tx-retired reads
leave its site list, what remains is the unit-object POINTER reads (P3b/P4b/P7); (b) the
object-surface list (texel bytes, dirty region, `HasDefinedContent`,
`MappedData`/`IsMapped`/`GetChangeSerial`) is pinned verbatim in `FieldOwnershipTest` as
the layer-1 surface set, and the §6 guard is what enforces it. **AMENDED at gt's
landing:** "per-level extent" leaves the guard list — the pinned object-class rows'
per-frame binding walk legally depends on `GetMipmapTexelSize`, so extent is retired AT
THE SITES (tx's sync reads the store) rather than guarded on the accessor. This is the
honest form of ROADMAP's "把纹理家族补进 FieldOwnership.def": the .def's mechanism covers
fields, and the family's object reads get a pinned list plus a guard that can go red.
---
## §6 gt — the role guards (semantics, two layers)
With an active transport, in a split build only (`MOBILEGL_BUILD_DISAGGREGATED`; the pull
build's bytes do not move, G1):
**Layer 1 — apply thread may not touch frontend surfaces.** `Fatal{RoleViolation,
"<surface>"}` raised inside: `MGPipeSlots()` (all three entry points); the frontend
`BufferObject` legacy accessors (§3.8); the frontend `TextureObjectMipmap` /
`MipmapStorage` mutators and maps (`AllocateStorage`, `MarkStorageDirty`, `MapMipmapData`
and the storage-dirty queries); `pDefaultFramebufferInfo`'s attachment writes; the
client-caps-mirror fallback (`Utils.cpp:50`); any BARRIER-PULLED accessor whose row is no
longer BARRIER_PULLED after §5 (the stamp mechanism's `MGPipeInputUnfreshRead` already
aborts these — gt's edit is that it aborts as RoleViolation with the surface named, and the
VALUE-class set is empty at exit). Implementation surface: `ServerLoop::OnApplyThread()`
gated checks at the named entries; compiled out entirely in pull builds.
**Layer 2 — GL thread may not touch server surfaces.** `Fatal{RoleViolation, "<surface>"}`
raised on: direct `MGPipeApplierReset()` (§5.1); `ServerLoop::Backend()` /
`MGPipeGetResourceOps()` reads AFTER session start (the bring-up window before
`ClientSessionInstance().Start()`, `MG_Backend/Init.cpp:100-247`, is the documented exception — it is
single-threaded and pre-dates the roles); a write into `gPipeInputs` outside the residual
fill, and any client-side read of a server-stamped field outside a barrier wait.
**A1 is ruled: `InBarrierWait()` is WIRED, not deleted.** CONTRACT-P5 table 3's sentence —
"the client checks it when it touches `gPipeInputs` outside a barrier (`InBarrierWait` /
`ApplyThreadIsInsideApplier`)" — is currently half-true: `ApplyThreadIsInsideApplier` fires
at emit (`ClientSession.cpp:748`), `InBarrierWait` (`:880`) has zero readers. gt makes the
sentence true: the layer-2 `gPipeInputs` check consults `InBarrierWait()` exactly as the
contract describes. Deleting the sentence instead was considered and rejected: the check is
the only client-side half of the gPipeInputs single-writer rule, and P6 needs it armed, not
forgotten.
**Red-once (R-16), per layer, mandatory:** each layer is switched off in one named
integration scenario and the run MUST go red with the layer's Fatal — this is E-P5c #1's
"关掉任一层守卫必须能在一条具名用例上变红", and it is what makes the guard a gate rather
than a comment. **CI lane, AMENDED at gt's landing:** a scenario-green
`MOBILEGL_IPC_STRICT_ERRORS=1` lane is impossible while the object-class rows live (the
first Clear pulls `GetFramebufferBindingSlot@Clear` and aborts by design), so the lane is
two-sided: the unit lane under strict is the hard green gate (the RemoteGuards and
FieldOwnershipTest strict arms live there), and the integration-split scenario lane is
EXPECTED-RED with the `BARRIER-PULLED, MOBILEGL_IPC_STRICT_ERRORS=1` marker asserted in
each entry's private log — the shape `split_negative_controls.sh` already drives. It
becomes a plain green lane once P7 retires the object-class rows.
**`rsp` at exit.** `ResidualPulls` enters the per-frame stats line and is MEASURED on the
four A/B traces; the remaining reads are exactly the object-class rows pinned by
`FieldOwnershipTest` (§5.3), value rows = 0. **AMENDED at gt's landing:** the sticky-forward
blind spot this paragraph assigned to gt was already closed (`MGPipeStickyForwardPull` has
counted into `ResidualPulls` since `d709ef3e`; `FieldOwnershipTest` pins it). What the
measurement actually found on the locally available traces: bsl in-world 948.5 rsp/frame
(38.7/draw, 123 frames), iris-complementary 1591.9, iris-iterationrp 286.2 up to its
pre-existing `Fatal{UnmigratedEmulation, "texture-remint-pull"}` — all object-class, zero
value-class. The residual known blind spot is narrower than planned: a record applied
OUTSIDE a verb boundary withdraws the stamp (`PipeApplier.cpp` notes it), and a sticky pull
inside one escapes the count; no measured workload produces one.
---
## §7 Amendments to CONTRACT-P5 / P5B (the complete list)
1. **Table 0** gains §1's six rows (reverse-channel blobref, ObjectDeath's payload reuse,
ApplierReset::ContextSerial, MGPContextValues, server-side level extent, kEventGlError).
2. **Table 1** gains three rows: `applier_reset` (77), `object_death` (78),
`set_context_values` (79) — all appended, opcode = position, never inserted.
3. **Table 2** (FieldOwnership.def): the §5.4 amendments; BARRIER_PULLED's value-class
membership goes to zero and `FieldOwnershipTest` pins the remainder.
4. **Table 3**: the three reverse `MGPipeCallbacks` entries move from "client installs" to
§4.1's producer ruling; `g_applier` gains "reset only via `applier_reset` under
transport"; the `InBarrierWait` sentence becomes true (§6); the bring-up window is named
as the one legal cross-role read.
5. **CONTRACT-P5B §2 f1's named blit**: "降为现有 bound backend 调用" is superseded by
§3.3 — the sink resolves `ReadFbo`/`DrawFbo` from the record and calls the named entry;
`ScopedBlitBindings` is deleted from the split path. P5b's "P5b 留下的 inproc 依赖"
list loses that row.
6. **`MGPVertexAttribDefaults` grows** (§5.3) — the second payload-size amendment after
P5b's `MGPCopyRegion`; the ABI fingerprint (`SessionRings.h:498-524`) is what catches a
desync, and `PipeCatalogueTest` pins the new size.
7. **`EventKind` gains `kEventGlError = 4`** — the first event-kind addition; the kind
space is append-only for the same reason the opcode space is.
## §8 Exit gates this contract serves (E-P5c, restated for the packages)
1. Guards armed: `integration-split` (107 at plan time; 111 as landed — ct added four
`CtWireScenario` entries) green, broad inproc census with zero regressions
vs `348d22a4`, 79 traces with no new first blocker; each guard layer red-once (§6).
2. `MOBILEGL_IPC_AUDIT=1`'s `0xDD` covers texture staged bytes on the four A/B traces;
reverting adoption goes red (§2.4).
3. Three events round-trip; `eventDropped == 0` at drain points; producer→raw-pointer
revert goes red (§4.5).
4. `rsp` measured per frame on the four A/B traces; remaining pulls are exactly the pinned
object-class rows (§5.3, §6).
5. Redmi four-arm retest recorded (barrier tax re-measured after writeback / gpu-written
move to events) — recorded, not gated.
6. G1 0/0/0/0, G2, G14, G5 as usual.
Explicitly NOT P5c (ROADMAP "留给后续阶段的"): object-class BARRIER_PULLED rows and the
frontend-keyed twin registry (P3b/P4b, P7); XFB scatter / `OnXfbScatterReady` /
`OnTexturePullRequest` / ordered `OnGlError` (P9); the EGL forwarders' control plane (P6);
copy-image shadow mirror and CopyTex texel writeback (P8/P9); `s_synced` /
`g_syncedRenderStateParameters` context-generation resets (P6).
@@ -190,16 +190,30 @@ namespace MobileGL::MG_Remote::Client {
// a surface for, and ServerSetWindowHandle is the only way to tell it.
Server::ServerSetWindowHandle(handle);
if (!Server::ServerCreateEGLWindowSurface(surface, handle)) return false;
// The server's surface init published the default framebuffer's shape as a
// surface-changed EVENT (P5c ev): DirectGLES' depth/stencil format, Magma's
// swapchain extent. Apply it NOW - the RPC's return is a moment the apply thread
// is known idle - because the first verb's drain would otherwise let every pre-verb
// query answer from the placeholder attachments (GL_DEPTH32F_STENCIL8 for a
// depth24+stencil8 surface, and every buffer allocated from that answer is
// blit-incompatible with the real thing).
if (ClientSession* session = ClientSession::Active()) session->DrainPublishedEvents();
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;
// A resize re-creates the server's swapchain, which re-posts the surface-changed
// event - same drain, same reason as CreateEGLWindowSurface.
if (ClientSession* session = ClientSession::Active()) session->DrainPublishedEvents();
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;
// Same drain as the window surface: InitPbufferSurface publishes the default
// framebuffer's depth/stencil format on SEG_EVENT from inside this very RPC.
if (ClientSession* session = ClientSession::Active()) session->DrainPublishedEvents();
return MG_Backend::BackendObject::CreateEGLPbufferSurface(surface, width, height);
}
@@ -225,6 +239,10 @@ namespace MobileGL::MG_Remote::Client {
if (draw != EGL_NO_SURFACE && ctx != EGL_NO_CONTEXT) {
if (ClientSession* session = ClientSession::Active()) {
session->PumpControlPlane();
// The event ring beside the caps channel: a make-current can follow a
// surface (re)creation that posted a surface-changed event, and this is
// the same known-idle instant the RPC returns at.
session->DrainPublishedEvents();
RefreshFormatCapabilities();
}
}
+155 -37
View File
@@ -19,7 +19,12 @@
#include "WireTables.h"
#include <MGGitHash.h>
#include <MG_Impl/GLImpl/Framebuffer/GL_Framebuffer.h>
#include <MG_Impl/Pipe/ResourceTracker.h>
#include <MG_Pipe/MGPipeCallbacks.h>
#include <MG_State/GLState/Core.h>
#include <MG_State/GLState/ErrorState/ErrorInfo.h>
#include <MG_State/GLState/TextureState/TextureObject2D.h>
#include <MG_Util/Debug/Log.h>
#include <atomic>
@@ -173,6 +178,58 @@ namespace MobileGL::MG_Remote::Client {
// 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).
//
// THE CONSUMERS ARE CALLED BY NAME, NEVER THROUGH gMGPipeCallbacks (CONTRACT-P5C
// §4.1): with an active transport the global table's reverse entries are the SERVER
// session's producer callbacks, so routing the drain through it would call the
// producer back from the GL thread - the layer-2 violation the contract names.
//
// THE SURFACE-CHANGED CONSUMER IS WHERE R3's OWNERSHIP ALWAYS WAS: the backend
// posts the MGPSurfaceInfo, and the allocate/format writes against
// pDefaultFramebufferInfo happen HERE, on the GL thread, against client memory.
void ApplySurfaceChangedToClient(const MG_Pipe::MGPSurfaceInfo& info) {
auto& defaultFBOInfo = MG_Impl::GLImpl::FramebufferImpl::pDefaultFramebufferInfo;
if (!defaultFBOInfo) return;
const auto format = static_cast<TextureInternalFormat>(info.InternalFormat);
auto* colorTex =
static_cast<MG_State::GLState::TextureObject2D*>(defaultFBOInfo->colorAttachment.get());
auto* depthTex =
static_cast<MG_State::GLState::TextureObject2D*>(defaultFBOInfo->depthAttachment.get());
auto* stencilTex =
static_cast<MG_State::GLState::TextureObject2D*>(defaultFBOInfo->stencilAttachment.get());
if (info.Width != 0 && info.Height != 0) {
// The SWAPCHAIN's publication shape: an extent-carrying event. Reproduces
// SwapchainObject's monolith writes statement for statement - colour storage
// at the extent, depth/stencil format then storage - because
// FramebufferObject::CheckCompleteness requires every attachment to agree.
const Int extentWidth = static_cast<Int>(info.Width);
const Int extentHeight = static_cast<Int>(info.Height);
const SizeT attachmentByteSize =
static_cast<SizeT>(info.Width) * static_cast<SizeT>(info.Height) * 4;
if (colorTex != nullptr) {
colorTex->AllocateStorage(TextureUploadTarget::Texture2D, 0,
{{extentWidth, extentHeight, 1}, attachmentByteSize});
}
if (depthTex != nullptr) {
depthTex->SetInternalFormat(format);
depthTex->AllocateStorage(TextureUploadTarget::Texture2D, 0,
{{extentWidth, extentHeight, 1}, attachmentByteSize});
}
if (stencilTex != nullptr) {
stencilTex->SetInternalFormat(format);
stencilTex->AllocateStorage(TextureUploadTarget::Texture2D, 0,
{{extentWidth, extentHeight, 1}, attachmentByteSize});
}
} else {
// The DirectGLES publication shape: FORMAT ONLY, Width/Height == 0. The
// placeholder's 512x512 extent is deliberately left alone - all three
// attachments share it, and resizing depth/stencil without colour would
// report the default framebuffer incomplete.
if (depthTex != nullptr) depthTex->SetInternalFormat(format);
if (stencilTex != nullptr) stencilTex->SetInternalFormat(format);
}
}
Uint32 DrainEventRing(Transport::EventRingConsumer& events) {
if (!events.Valid()) return 0;
Uint32 delivered = 0;
@@ -197,19 +254,18 @@ namespace MobileGL::MG_Remote::Client {
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;
}
// 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. The consumer's
// kSegEvent arm resolves it through this session's own SegmentTable.
MG_Pipe::MGPBlobRef blob{};
blob.Seg = Wire::kSegEvent;
blob.Offset = events.OffsetInSegment(bytes);
blob.Size = head->Size;
MG_Pipe::MGPipeClientOnBufferWriteback(
MG_Pipe::MGPipeHandle{head->Resource.Slot, head->Resource.Gen},
head->Offset, blob);
++delivered;
break;
}
case Transport::kEventGpuWritten: {
@@ -224,39 +280,71 @@ namespace MobileGL::MG_Remote::Client {
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;
}
// 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::MGPipeClientOnGpuWritten(
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;
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;
ApplySurfaceChangedToClient(info);
++delivered;
break;
}
case Transport::kEventGlError: {
if (view.payloadSize < sizeof(Transport::EventGlErrorHead)) break;
const auto* head =
static_cast<const Transport::EventGlErrorHead*>(view.payload);
const char* message =
reinterpret_cast<const char*>(static_cast<const Uint8*>(view.payload) +
sizeof(*head));
const Uint64 tail = view.payloadSize - sizeof(*head);
// MessageBytes == 0 is the corrupt shape, never "no message": the NUL
// travels (CONTRACT-P5C §1, rule A's twin), so a legal record carries at
// least one byte and that byte terminates the string.
if (head->MessageBytes == 0 || tail < head->MessageBytes ||
message[head->MessageBytes - 1] != '\0') {
MGLOG_F("MGPipe: Fatal{ProtocolCorruption, \"kEventGlError\"} - "
"MessageBytes %u against a %llu-byte tail, or the terminating "
"NUL is missing",
static_cast<unsigned>(head->MessageBytes),
static_cast<unsigned long long>(tail));
std::abort();
}
// The error queue is CLIENT state, written here on the GL thread. The
// observation point is the next drain after the post - P9 owns the
// ordering (CONTRACT-P5C §4.2).
if (MG_State::pGLContext != nullptr) {
MG_State::pGLContext->RecordError(
static_cast<ErrorCode>(head->Code),
MakeUnique<GenericErrorInfo>(
String(message, static_cast<SizeT>(head->MessageBytes - 1))));
} else {
MGLOG_E_ONCE("MG_Remote client: a kEventGlError (code %u) arrived with "
"no live context and is dropped",
static_cast<unsigned>(head->Code));
}
++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)",
"P5c (four of the ten callbacks are armed; the rest are P9's)",
static_cast<unsigned>(view.kind));
break;
}
@@ -881,6 +969,25 @@ namespace MobileGL::MG_Remote::Client {
Bool ClientSession::ApplyThreadIsInsideApplier() {
return g_applyThreadInsideApplier.load(std::memory_order_acquire);
}
void ClientSession::RefusePipeInputsTouchWhileApplierOwnsIt(const char* surface) {
if (Server::ServerLoop::OnApplyThread()) return; // the applier owns the block inside a verb
if (MG_Config::Transport == MG_Config::TransportMode::Monolith) return;
if (!ClientSessionInstance().Started()) return; // the bring-up window pre-dates the roles
// MOBILEGL_IPC_VERB_BARRIER=0 is R-1's NEGATIVE CONTROL: the single-writer rule is off
// by the operator's own hand there, and EmitAndWait's Fatal{BarrierViolation} owns the
// red. Firing here instead would pre-empt the control's evidence line.
if (!ClientSessionInstance().BarrierArmed()) return;
if (!ApplyThreadIsInsideApplier()) return;
if (InBarrierWait()) return;
MGLOG_F("MGPipe: Fatal{RoleViolation, \"gPipeInputs\"} - the GL thread touched gPipeInputs "
"(%s) while the apply thread was inside the applier and this thread was not in a "
"barrier wait. R-1's barrier is the only thing that makes one process-wide "
"gPipeInputs legal (CONTRACT-P5 table 3); a touch in this window races the "
"applier's own reads of it",
surface);
std::abort();
}
void ClientSession::NoteApplyThreadEnteredApplier() {
g_applyThreadInsideApplier.store(true, std::memory_order_release);
}
@@ -944,6 +1051,17 @@ namespace MobileGL::MG_Remote::Client {
Transport::EventRingConsumer& ClientSession::Events() { return m_events; }
Uint32 ClientSession::DrainPublishedEvents() {
// Not gated on m_started on purpose: PumpControlPlane's own pre-start call during
// Start() has its ring-consumer twin here, and DrainEventRing's Valid() check is
// the whole guard either case needs.
return DrainEventRing(m_events);
}
Uint64 ClientSession::EventRingCapacityBytes() const { return m_shm.EventRingCapacity(); }
Wire::SegmentTable& ClientSession::Segments() { return m_segments; }
Transport::RingControl* ClientSession::Control() { return m_shm.CmdControl(); }
Transport::SessionSegments& ClientSession::Shm() { return m_shm; }
+36
View File
@@ -128,6 +128,20 @@ namespace MobileGL::MG_Remote::Client {
static Bool InBarrierWait();
static Bool ApplyThreadIsInsideApplier();
// P5c (gt, CONTRACT-P5C §6 layer 2 / audit A1): the sentence above's second half,
// wired. A GL-thread touch of gPipeInputs while the apply thread is inside the
// applier and THIS thread is not in a barrier wait is Fatal{RoleViolation,
// "gPipeInputs"} - the barrier is the only thing that makes one process-wide
// gPipeInputs legal (CONTRACT-P5 table 3), and a touch in that window races the
// applier's own reads of it. The residual fill and the verify harness are legal by
// timing, not by exemption: they run before the record is published, which under an
// armed barrier is a moment the flag is provably down (the applier drops it before
// appliedSeq advances past the record the client last waited on). No-op when no armed
// split session is live, when the caller IS the apply thread, and when the barrier is
// disarmed - MOBILEGL_IPC_VERB_BARRIER=0 is R-1's negative control and its red belongs
// to Fatal{BarrierViolation}, not to this check.
static void RefusePipeInputsTouchWhileApplierOwnsIt(const char* surface);
// ---- c1's additions ---------------------------------------------------------------
// The apply thread's half of R-1's invariant. v1's apply loop brackets its
@@ -202,6 +216,28 @@ namespace MobileGL::MG_Remote::Client {
// OnSurfaceChanged. Drained by the GL thread between verbs.
Transport::EventRingConsumer& Events();
// The event ring's SECOND drain point, for the blocking EGL lifecycle RPCs
// (BackendObject_Remote's surface creation and make-current). Their return is the
// same kind of instant as EmitAndWait's post-barrier one - the apply thread is
// known idle because the RPC it was serving has completed and this thread has
// published nothing since - so the consumers' frontend writes are as legal here as
// there. A surface-changed event posted during bring-up must be applied BEFORE the
// first frontend query of the default framebuffer's depth/stencil format: waiting
// for the first verb's drain answered GL_DEPTH32F_STENCIL8 (the placeholder) for a
// depth24+stencil8 surface, and every buffer allocated from that answer was
// blit-incompatible with the real thing.
Uint32 DrainPublishedEvents();
// SEG_EVENT's ring capacity, exposed so the readback path can slice a writeback
// request into records that always fit (RingProducer::MaxRecordBytes ==
// capacity/2, Ring.h:288).
Uint64 EventRingCapacityBytes() const;
// The CLIENT's own segment table (P5c ev, CONTRACT-P5C §4.3): the writeback
// consumer resolves a SEG_EVENT blobref through it. Never the process resolver -
// table 3 installs that one on the server role only.
Wire::SegmentTable& Segments();
Transport::RingControl* Control();
Transport::SessionSegments& Shm();
Transport::ITransport* Control_Plane();
+7 -30
View File
@@ -734,42 +734,19 @@ namespace MobileGL::MG_Remote::Client {
nullptr, 0, nullptr);
}
// DSA blits use the existing bound-form backend while the verb barrier holds.
// Only client shadow bindings change here; no driver call or frontend pointer crosses
// the wire. Bind() bumps their versions on entry and restore, so the next ordinary
// verb republishes the application's original bindings even if no GL bind intervenes.
class ScopedBlitBindings {
public:
using Fbo = MG_State::GLState::FramebufferObject;
ScopedBlitBindings(const SharedPtr<Fbo>& read, const SharedPtr<Fbo>& draw)
: m_read(MG_State::pGLContext->GetFramebufferBindingSlot(FramebufferTarget::Read)),
m_draw(MG_State::pGLContext->GetFramebufferBindingSlot(FramebufferTarget::Draw)),
m_savedRead(m_read.GetBoundObject()), m_savedDraw(m_draw.GetBoundObject()) {
m_read.Bind(read);
m_draw.Bind(draw);
}
~ScopedBlitBindings() {
m_read.Bind(m_savedRead);
m_draw.Bind(m_savedDraw);
}
ScopedBlitBindings(const ScopedBlitBindings&) = delete;
ScopedBlitBindings& operator=(const ScopedBlitBindings&) = delete;
private:
BindingSlot<Fbo>& m_read;
BindingSlot<Fbo>& m_draw;
SharedPtr<Fbo> m_savedRead;
SharedPtr<Fbo> m_savedDraw;
};
void EmitBlitNamedFramebuffer(
const SharedPtr<MG_State::GLState::FramebufferObject>& read,
const SharedPtr<MG_State::GLState::FramebufferObject>& draw,
GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0,
GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter) {
ClientSession& session = RequireSession("BlitNamedFramebuffer");
const ScopedBlitBindings bindings(read, draw);
// The frontend's first validate preceded this temporary lowering. Refresh both
// emitted framebuffer state and the existing BARRIER-PULLED binding fields now.
// P5c (hd, CONTRACT-P5C §3.3): the scoped rebind of the client's own read/draw
// binding slots is DELETED. It existed only to stage values for the server's
// binding-slot read, and that read is gone: the sink resolves both framebuffers
// from the record's handles. The validate still refreshes both framebuffers'
// emitted state (their Named set_framebuffer_state records), which is now the
// only description the server syncs from. No driver call or binding change
// happens on the client.
MG_Pipe::MGPipeValidateForVerb(MG_Pipe::MGPipeVerb::BlitNamedFramebuffer);
BeforeReadOnlyVerb();
MG_Pipe::MGPBlit record{};
@@ -169,6 +169,21 @@ namespace MobileGL::MG_Remote::Client {
#endif
}
SizeT BufferWritebackSliceBytes() {
ClientSession* session = ClientSession::Active();
if (session == nullptr) return 0;
// A quarter of the ring, not the MaxRecordBytes half: the record carries its own
// header and the 24-byte EventBufferWritebackHead beside the payload, and the ring
// may still hold a few small events (gpu-written, gl-error) posted earlier in the
// same verb's apply. Each slice round-trips with its own barrier + drain, so the
// ring never holds more than one slice's bytes.
const Uint64 slice = session->EventRingCapacityBytes() / 4;
// A floor so a pathologically small operator-supplied ring cannot make the slicing
// loop in SyncGpuWrites spin at zero width; such a ring is broken anyway, and the
// producer's Fatal{EventRingOverflow} names it on the first post.
return static_cast<SizeT>(slice < 4096 ? 4096 : slice);
}
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
@@ -149,4 +149,12 @@ namespace MobileGL::MG_Remote::Client {
// ever. It is the ONE case monolith's unconditional clear covers that a writeback cannot.
Bool BufferWritebackIsReachable(const MG_State::GLState::BufferObject& buffer);
// The slice a whole-buffer readback is cut into so one writeback event always fits
// SEG_EVENT. The writeback's bytes travel INLINE in the event record (P5c ev, CONTRACT-P5C
// §4.2), one record must fit the ring (RingProducer::MaxRecordBytes == capacity/2,
// Ring.h:288), and a 24 MiB arena's single shot cannot (measured: Fatal{EventRingOverflow}
// on LargeArenaAdoptionScenario.GpuWriteIntoTheArenaIsReadBack). 0 when no session is
// active - the synchronous arm never slices.
SizeT BufferWritebackSliceBytes();
} // namespace MobileGL::MG_Remote::Client
+99 -3
View File
@@ -6,12 +6,12 @@
// 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
// The ENCODE TWIN of gMGPipeWireRecordApply: thirty-eight 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:
// thirty-eight rows against PipeTables.inc in one pass instead of reading thirty-eight 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;
@@ -22,7 +22,7 @@
// 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
// NOT called from these thirty-eight. 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
@@ -38,6 +38,10 @@
#include <MG_Pipe/MGPipe.h>
#include <MG_Pipe/PipeRoute.h>
// P5c (ct): EmitObjectDeathRecord resolves the dying object's handle in the CLIENT's own
// allocator - a client surface, asked on the client thread, which is the one place the lookup
// is legal under rule E (CONTRACT-P5C.md §5.2).
#include <MG_Impl/Pipe/SlotAllocator.h>
#include <MG_State/GLState/ProgramState/ProgramArtifactsCodec.h>
#include <MG_Util/Debug/Log.h>
@@ -192,6 +196,11 @@ namespace MobileGL::MG_Remote::Client {
MGP_WIRE_PLAIN(SetIndexBuffer, MGPIndexBuffer, Context)
MGP_WIRE_PLAIN(SetPixelPackState, MGPPixelPackState, Context)
MGP_WIRE_PLAIN(SetPatchState, MGPPatchState, Context)
// P5c (rv), CONTRACT-P5C.md §5.3: the residual-value record is an ordinary routed
// set_* row - a fixed POD, no blob, no tail, no reply. The PRODUCER is transport-gated
// (PipeFill.cpp's EmitContextValues), so under monolith this wrapper is never reached;
// the server-role arm forwards to the monolith adapter exactly like its siblings.
MGP_WIRE_PLAIN(SetContextValues, MGPContextValues, Context)
// -- context, mandatory blob --------------------------------------------------
MGP_WIRE_BLOB(CreateRenderState, MGPRenderStateDesc, Blob)
@@ -503,6 +512,92 @@ namespace MobileGL::MG_Remote::Client {
} // namespace
// =====================================================================================
// P5c (ct), CONTRACT-P5C.md §5: the two control records' producers
// =====================================================================================
namespace {
// The ContextSerial of the NEXT applier_reset record. NOWHERE IN THE FRONTEND NUMBERS
// A MAKE-CURRENT: the tracker knows the EDGE (FreshlyPrimed) and no session or context
// carries a serial for it (checked at the contract commit), so the serial is this
// client's own count of applier_reset emissions - 0 for the first make-current, one
// more per primed edge. That is the only value the server can hold the client to in a
// one-context session: the sink keeps the same count and ASSERTS equality
// (CONTRACT-P5C.md §1: the value is asserted, never dispatched on; P6's multi-context
// shape is what will read it for real). GL-thread only, like every emitter here.
Uint64 g_applierResetContextSerial = 0;
} // namespace
Bool EmitApplierResetRecord() {
// NO SESSION, NO RECORD - and false rather than the RequireSession Fatal, because a
// validate can legitimately prime with a transport CONFIGURED but no live session:
// the bring-up window before ClientSession::Start() (§6 layer 2's documented
// exception), and the server-role-only shape a ServerLoop fixture drives with
// Transport=InProcess and no client at all. In both this process has no wire for the
// reset to cross, and the caller answers with the direct call the record replaced.
ClientSession* session = ClientSession::Active();
if (session == nullptr || !session->Started()) return false;
if (g_clientTablesUninstalled.load(std::memory_order_acquire)) return false;
MG_Pipe::MGPApplierReset record{};
record.ContextSerial = g_applierResetContextSerial++;
session->EmitAndWait(MGPWireOp::ApplierReset, &record, sizeof(record), nullptr, 0, nullptr,
0, nullptr);
++g_emitted;
return true;
}
// P5c (rv), CONTRACT-P5C.md §5.3. Whether set_context_values can cross RIGHT NOW: a live,
// started session whose tables are not being torn down. PipeFill.cpp gates BOTH halves of
// the row on this - the emission and the residual-fill skip - so a configured-but-wireless
// transport (the bring-up window, a server-role-only fixture) keeps the pull, and the two
// can never disagree about who supplies the eight fields.
Bool ContextValuesWireLive() {
ClientSession* session = ClientSession::Active();
return session != nullptr && session->Started() &&
!g_clientTablesUninstalled.load(std::memory_order_acquire);
}
ObjectDeathEmit EmitObjectDeathRecord(MG_Pipe::MGPipeKind kind, Uint64 lifetimeId) {
using MG_Pipe::MGPipeHandle;
// NO SESSION, NO RECORD - and that is NOT the RequireSession shape on purpose. A death
// notice can outlive the session by construction: frontend objects die at context
// teardown and at process exit, after Stop has joined the apply thread and freed the
// rings, and the twins this record would kill died with the server. Emitting into that
// window is a use-after-free; Fatal-ing on it is an abort at exit() for a legal death.
// NoSession is its own answer (not folded into NoHandle) because the caller's fallback
// for "no wire exists" is delivery to the server loop this process still has, while
// "no handle" means there is nothing to deliver at all.
ClientSession* session = ClientSession::Active();
if (session == nullptr || !session->Started()) return ObjectDeathEmit::NoSession;
// The same window, one step earlier: Stop has raised the teardown refusal but not yet
// joined the apply thread. A death landing here is destructor-driven, not an app bug,
// and the twin it would kill dies with the backend Stop is destroying - so it is
// skipped, where a routed call in the same window is Fatal{ClientTablesUninstalled}.
if (g_clientTablesUninstalled.load(std::memory_order_acquire)) {
return ObjectDeathEmit::NoSession;
}
// THE CLIENT'S OWN ALLOCATOR, ON THE CLIENT'S OWN THREAD (§5.2 step 1). A lifetime id
// the allocator cannot resolve names an object that never crossed - no create record
// ever carried its handle, so the server has no twin to kill and NOTHING is emitted.
// This replaces the mailbox's unconditional delivery, which hopped every death to the
// apply thread whether or not the server had ever seen the object.
const MGPipeHandle handle = MG_Pipe::MGPipeSlots().FindByLifetimeId(kind, lifetimeId);
if (MG_Pipe::MGPipeHandleIsNull(handle)) return ObjectDeathEmit::NoHandle;
MG_Pipe::MGPHandleOnly record{};
record.Handle = handle;
record.Kind = static_cast<Uint32>(kind);
// The WAIT is the only property the blocking mailbox hop provided and the only one P5c
// keeps (§5.2 step 3): it orders the death against in-flight verbs that name the
// handle, so the server's twin cannot be released underneath a verb that is using it.
session->EmitAndWait(MGPWireOp::ObjectDeath, &record, sizeof(record), nullptr, 0, nullptr,
0, nullptr);
++g_emitted;
return ObjectDeathEmit::Emitted;
}
void RequireClientTablesInstalled(const char* row) {
if (g_clientTablesUninstalled.load(std::memory_order_acquire)) {
MGLOG_F("MGPipe: Fatal{ClientTablesUninstalled, \"%s\"} - the client tables are "
@@ -549,6 +644,7 @@ namespace MobileGL::MG_Remote::Client {
gMGPipeContext.SetVertexAttribDefaults = &Wire_SetVertexAttribDefaults;
gMGPipeContext.SetPixelPackState = &Wire_SetPixelPackState;
gMGPipeContext.SetPatchState = &Wire_SetPatchState;
gMGPipeContext.SetContextValues = &Wire_SetContextValues;
gMGPipeContext.SetResidualValueState = &Wire_SetResidualValueState;
gMGPipeContext.SetTextureParams = &Wire_SetTextureParams;
gMGPipeContext.ResourceSubData = &Wire_ResourceSubData;
+38 -3
View File
@@ -8,7 +8,7 @@
// 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
// Thirty-eight 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.
@@ -35,11 +35,13 @@
#pragma once
#include <Includes.h>
#include <MG_Pipe/MGPipeHandles.h>
#if MOBILEGL_BUILD_DISAGGREGATED
namespace MobileGL::MG_Remote::Client {
// Installs the thirty-seven wire emitters over gMGPipeScreen / gMGPipeContext /
// Installs the thirty-eight wire emitters over gMGPipeScreen / gMGPipeContext /
// gMGPipeRouteEscapes and records the arm. Idempotent.
void InstallClientWireTables();
@@ -57,7 +59,7 @@ namespace MobileGL::MG_Remote::Client {
// 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
// How many records the thirty-eight 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".
@@ -86,6 +88,39 @@ namespace MobileGL::MG_Remote::Client {
// server otherwise). Declared here so PipeFill does not have to include a server header.
Bool RunsAsTheServerRole();
// ---- P5c (ct), CONTRACT-P5C.md §5: the two control records' client halves --------------
//
// NOT ROUTED ROWS - the two are appended to PipeCalls.def with no MGPipeApply* entry point
// and no table slot at all, so their producers call these directly. PipeFill.cpp's
// FreshlyPrimed arm calls the first; DirectGLES' OnFrontendStateObjectDestroyed calls the
// second.
// applier_reset (§5.1). Emitted on the GL thread at the tracker.FreshlyPrimed() edge,
// BEFORE the block's client-side resets, so the record's barrier orders the server's
// MGPipeApplierReset() against every verb that follows. ContextSerial is the client's own
// count of applier_reset emissions (0 = the first make-current): nothing in the frontend
// numbers a make-current today, and the sink asserts the value against its own count of
// the same records rather than dispatching on it (P5c: one context per session; P6 reads
// it for real). Returns false - nothing emitted - when no live session could carry the
// record (the bring-up window before Start, a server-role-only fixture, teardown); the
// caller then makes the direct call the record replaced.
Bool EmitApplierResetRecord();
// P5c (rv), CONTRACT-P5C.md §5.3: whether set_context_values can cross right now (a live,
// started session, tables not being torn down). PipeFill.cpp gates the record's emission
// AND the residual-fill skip for its eight fields on this one answer, so the two halves
// can never disagree about who supplies them.
Bool ContextValuesWireLive();
// The three answers a death notice can produce (§5.2): the record crossed; the client's
// own allocator cannot resolve the dying object (the server never saw it, so there is no
// twin to kill and NOTHING crossed); or no live session could carry the record. The
// third is NOT folded into the second: a server role with no wire at all - a ServerLoop
// fixture's shape, never a real split's - still has a server loop the caller delivers to,
// where a handle that never existed has nothing to deliver.
enum class ObjectDeathEmit : Uint8 { Emitted, NoHandle, NoSession };
ObjectDeathEmit EmitObjectDeathRecord(MG_Pipe::MGPipeKind kind, Uint64 lifetimeId);
} // namespace MobileGL::MG_Remote::Client
#endif // MOBILEGL_BUILD_DISAGGREGATED
+129 -6
View File
@@ -14,6 +14,10 @@
#include <Config.h>
#include <MG_Backend/MGPipe/PipeInputs.h>
// P5c ct: object_death's per-kind release names the Espryt twin tables (CONTRACT-P5C.md
// §5.2). The same dependency ServerLoop.cpp already takes for CreateBackend; a server built
// on Magma simply holds no twins in these tables and every release resolves to nothing.
#include <MG_Backend/DirectGLES/Managers.h>
#include <MG_Remote/Client/ClientSession.h>
#include <MG_Pipe/PipeApply.h>
#include <MG_Util/Converters/GLToMG/TextureEnumConverter.h>
@@ -229,16 +233,35 @@ namespace MobileGL::MG_Remote::Server {
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. For the named form the
// client temporarily binds the two named objects and validates before emitting; its
// existing BARRIER-PULLED fields stay fixed until this call returns. ReadFbo/DrawFbo
// retain the original identities for the later handle-only endpoint (CONTRACT-P5B §6).
#if MOBILEGL_BUILD_DISAGGREGATED
// P5c (hd, CONTRACT-P5C §3.3): the record's handles cross to the backend as the verb's
// own state. The bound form carries two nulls and nothing changes; the named form's
// pair is what the backend's named-blit arm resolves - the sink no longer relies on
// "the read and draw framebuffers are already bound" (the client's ScopedBlitBindings
// staging is deleted with this), and a backend that does not consume the pair has no
// named arm, which is a loud decline rather than a blit of whatever is bound.
auto& applierState = MG_Pipe::MGPipeApplier();
applierState.ClearVerbHandles();
applierState.VerbBlitReadFbo = blit.ReadFbo;
applierState.VerbBlitDrawFbo = blit.DrawFbo;
const Bool named = !MG_Pipe::MGPipeHandleIsNull(blit.ReadFbo) ||
!MG_Pipe::MGPipeHandleIsNull(blit.DrawFbo);
#endif
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));
#if MOBILEGL_BUILD_DISAGGREGATED
if (named && !applierState.VerbBlitNamedConsumed) {
MGLOG_E_ONCE("MGPipe: a named blit (read {%u, %u}, draw {%u, %u}) reached a backend "
"with no named-blit arm; the verb is DECLINED rather than applied to "
"the bound framebuffers",
blit.ReadFbo.Slot, blit.ReadFbo.Gen, blit.DrawFbo.Slot, blit.DrawFbo.Gen);
applierState.VerbBlitReadFbo = MG_Pipe::kMGPipeNullHandle;
applierState.VerbBlitDrawFbo = MG_Pipe::kMGPipeNullHandle;
return false;
}
#endif
++m_blits;
return true;
}
@@ -447,6 +470,15 @@ namespace MobileGL::MG_Remote::Server {
if (indirect != nullptr) {
// The layout already refused a record that sets both flags or declares ranges
// beside the block, so NumDraws is 0 and there is no span here.
#if MOBILEGL_BUILD_DISAGGREGATED
// P5c (hd, CONTRACT-P5C §3.5): the command/parameter buffer handles cross as the
// verb's own state; the backend's indirect arm resolves the buffer twins from
// them instead of reading the client's GL_DRAW_INDIRECT_BUFFER binding slot.
auto& applierState = MG_Pipe::MGPipeApplier();
applierState.ClearVerbHandles();
applierState.VerbIndirectBuffer = indirect->Buffer;
applierState.VerbIndirectParameterBuffer = indirect->ParameterBuffer;
#endif
const auto offset = reinterpret_cast<const void*>(static_cast<std::uintptr_t>(indirect->Offset));
const auto drawCount = static_cast<GLsizei>(indirect->DrawCount);
const auto stride = static_cast<GLsizei>(indirect->Stride);
@@ -650,6 +682,14 @@ namespace MobileGL::MG_Remote::Server {
// IndirectBuffer travels for P7's sake; the BINDING is server state, put there by
// the set_buffer_bindings record that preceded this one, exactly as OnClear's Fbo
// is not re-resolved here. glDispatchComputeIndirect takes only the offset.
#if MOBILEGL_BUILD_DISAGGREGATED
// P5c (hd, CONTRACT-P5C §3.5): the buffer handle itself is now also the verb's own
// state, so the backend's dispatch-indirect arm resolves the twin from the record
// rather than from the client's GL_DISPATCH_INDIRECT_BUFFER binding slot.
auto& applierState = MG_Pipe::MGPipeApplier();
applierState.ClearVerbHandles();
applierState.VerbDispatchIndirectBuffer = grid.IndirectBuffer;
#endif
gl.DispatchComputeIndirect(static_cast<GLintptr>(grid.IndirectOffset));
} else {
if (gl.DispatchCompute == nullptr) return false;
@@ -743,6 +783,11 @@ namespace MobileGL::MG_Remote::Server {
static_cast<GLenum>(bind.Access),
static_cast<GLenum>(bind.Format));
++m_imageBinds;
// P5c (rv): an image bind moves the frontend's texture bind generation, and this verb
// carries no set_shader_images alongside it - so the server-side shutter serial the
// accessors now answer with (CONTRACT-P5C.md §5.3) moves here, at the one place the
// event reaches the applier's side.
MG_Pipe::MGPipeApplierNoteTextureStateMoved();
return true;
}
@@ -870,6 +915,15 @@ namespace MobileGL::MG_Remote::Server {
Bool ServerVerbSink::OnGenerateMipmap(const MG_Pipe::MGPMipPlan& plan) {
const auto* table = Table("GenerateMipmap");
if (table == nullptr || table->GL.GenerateMipmap == nullptr) return false;
#if MOBILEGL_BUILD_DISAGGREGATED
// P5c (hd, CONTRACT-P5C §3.2): the texture the client resolved at Target on the active
// unit crosses as the verb's own state; the backend's mip-descriptor check resolves
// the record from it instead of probing the client allocator for the bound object's
// lifetime id (T2's mip half).
auto& applierState = MG_Pipe::MGPipeApplier();
applierState.ClearVerbHandles();
applierState.VerbMipRes = plan.Res;
#endif
table->GL.GenerateMipmap(plan.Target);
return true;
}
@@ -877,6 +931,14 @@ namespace MobileGL::MG_Remote::Server {
Bool ServerVerbSink::OnCopyFramebufferToTexture(const MG_Pipe::MGPCopyFromFramebuffer& copy) {
const auto* table = Table(copy.SubImage ? "CopyTexSubImage2D" : "CopyTexImage2D");
if (table == nullptr) return false;
#if MOBILEGL_BUILD_DISAGGREGATED
// P5c (hd, CONTRACT-P5C §3.4): the destination texture the client resolved at the
// active unit crosses as the verb's own state; the backend resolves its twin from the
// handle instead of reading the client's texture-unit binding slot (T4).
auto& applierState = MG_Pipe::MGPipeApplier();
applierState.ClearVerbHandles();
applierState.VerbCopyTexDst = copy.Dst;
#endif
if (copy.SubImage) {
if (table->GL.CopyTexSubImage2D == nullptr) return false;
table->GL.CopyTexSubImage2D(copy.Target, copy.Level, copy.XOffset, copy.YOffset,
@@ -889,6 +951,67 @@ namespace MobileGL::MG_Remote::Server {
return true;
}
// ---- P5c ct (MG_Remote/CONTRACT-P5C.md §5) ------------------------------------------
//
// TWO CONTROL RECORDS, NO BACKEND TABLE AND NO DECLINE ARM. Neither body consults
// Table(): the reset belongs to the applier this process owns, and the death release
// belongs to the twin tables - a backend that registered no slots (Magma's XFB shape)
// still has an applier to reset and still answers a death with the same generation
// check. A record that cannot be proved is Fatal, not declined: both refusals are
// ProtocolCorruption because by the time the sink runs the codec has already proved the
// record's SHAPE, and what is left to check are the contract facts about the peer (§1).
Bool ServerVerbSink::OnApplierReset(const MG_Pipe::MGPApplierReset& reset) {
// §1: the serial is ASSERTED, never dispatched on. P5c has exactly one context per
// session, so the only legal sequence is 0, 1, 2, ... and the session's own count of
// accepted resets IS the expected value; anything else means the two ends disagree
// about how many make-current edges have crossed, which no backend answer can fix.
if (reset.ContextSerial != m_applierResetSerial) {
MGLOG_F("MGPipe: Fatal{ProtocolCorruption, \"ApplierReset.ContextSerial\"} - the "
"record carries %llu and this session has accepted %llu reset(s); the "
"serial is asserted against the session's own count, not dispatched on "
"(one context per session in P5c)",
static_cast<unsigned long long>(reset.ContextSerial),
static_cast<unsigned long long>(m_applierResetSerial));
std::abort();
}
++m_applierResetSerial;
// THE WHOLE POINT OF THE RECORD: the reset runs HERE, on the apply thread, against
// the g_applier this role owns (PipeApply.cpp:409). The layer-2 guard inside
// MGPipeApplierReset passes because this IS the apply thread; the GL-thread direct
// call it replaced is the Fatal arm.
MG_Pipe::MGPipeApplierReset();
++m_applierResets;
return true;
}
Bool ServerVerbSink::OnObjectDeath(const MG_Pipe::MGPHandleOnly& death) {
// §1's zero ruling: a null handle means "the object never crossed", and the client
// emits NOTHING in that case (§5.2) - so a null handle arriving here is corruption,
// not a no-op.
if (MG_Pipe::MGPipeHandleIsNull(death.Handle)) {
MGLOG_F("MGPipe: Fatal{ProtocolCorruption, \"ObjectDeath.Handle\"} - a null "
"handle never crosses: the client emits nothing for an object its own "
"allocator cannot resolve (CONTRACT-P5C.md §5.2)");
std::abort();
}
if (death.Kind >= static_cast<Uint32>(MG_Pipe::MGPipeKind::KindCount)) {
MGLOG_F("MGPipe: Fatal{ProtocolCorruption, \"ObjectDeath.Kind\"} - %u is not an "
"MGPipeKind",
static_cast<unsigned>(death.Kind));
std::abort();
}
// The per-kind release, keyed by the handle the record carried. A false answer is
// NOT a decline: the kind's own delete opcode may already have released the twin
// (the idempotent second path every notice arm documents), and a kind this backend
// does not twin (Buffer, whose death crosses as resource_destroy) legally resolves
// to nothing.
MG_Backend::DirectGLES::ReleaseTwinsForWireObjectDeath(
death.Handle, static_cast<MG_Pipe::MGPipeKind>(death.Kind));
++m_objectDeaths;
return true;
}
// -----------------------------------------------------------------------------------
// PipeApplier
// -----------------------------------------------------------------------------------
+34
View File
@@ -150,6 +150,32 @@ namespace MobileGL::MG_Remote::Server {
Bool OnGenerateMipmap(const MG_Pipe::MGPMipPlan& plan) override;
Bool OnCopyFramebufferToTexture(const MG_Pipe::MGPCopyFromFramebuffer& copy) override;
// ---- P5c ct (MG_Remote/CONTRACT-P5C.md §5): the two control records ----------------
//
// REAL BODIES FROM THE DAY THE ROWS EXIST, not the P5b stub shape: the rows were
// appended by the same package that lands these bodies, so there is no window in
// which a client can emit ahead of its server half.
//
// OnApplierReset (§5.1): the make-current edge's server half. ContextSerial is
// ASSERTED against this session's own count of applier_reset records - one context
// per session in P5c, so the legal sequence is 0, 1, 2, ... - and only then is
// MGPipeApplierReset() run, here, on the apply thread that owns g_applier.
// OnObjectDeath (§5.2): a null handle never crosses (the client emits nothing for an
// object its allocator cannot resolve), so one arriving is
// Fatal{ProtocolCorruption, "ObjectDeath.Handle"}; otherwise the per-kind release
// runs by the record's handle (SlotTables.h's ReleaseTwinByHandle).
Bool OnApplierReset(const MG_Pipe::MGPApplierReset& reset) override;
Bool OnObjectDeath(const MG_Pipe::MGPHandleOnly& death) override;
// P5c ct's tallies, for the same reason every other row's tally exists (R-16: a probe
// may not arm against a stub). ApplierResets counts the records ACCEPTED (serial
// checked, reset run); ObjectDeaths counts every record the sink dispatched.
Uint64 ApplierResets() const { return m_applierResets; }
Uint64 ObjectDeaths() const { return m_objectDeaths; }
// The ContextSerial the NEXT applier_reset record must carry. Exposed so a case can
// assert the sequence rather than only the count.
Uint64 ExpectedApplierResetSerial() const { return m_applierResetSerial; }
// 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).
@@ -231,6 +257,14 @@ namespace MobileGL::MG_Remote::Server {
Uint64 m_streamOutputControls = 0;
Uint64 m_streamOutputBinds = 0;
Uint64 m_patchParameters = 0;
// P5c ct. m_applierResetSerial is BOTH the expected ContextSerial of the next record
// and the count of accepted resets: the two are one number because the serial is the
// session's own count of applier_reset records (CONTRACT-P5C.md §1: asserted, never
// dispatched on). m_objectDeaths counts records dispatched, released twin or not -
// the idempotent second path answering "nothing held it" is a legal record.
Uint64 m_applierResetSerial = 0;
Uint64 m_applierResets = 0;
Uint64 m_objectDeaths = 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.
+174
View File
@@ -16,9 +16,11 @@
#include <Config.h>
#include <MGGitHash.h>
#include <MG_Pipe/MGPipeCallbacks.h>
#include <MG_Util/Debug/Log.h>
#include <cstdlib>
#include <cstring>
#include <vector>
namespace MobileGL::MG_Remote::Server {
@@ -155,6 +157,120 @@ namespace MobileGL::MG_Remote::Server {
std::abort();
}
// ---- P5c ev: the reverse channel's PRODUCER callbacks (CONTRACT-P5C §4.1) --------
//
// With an active transport the three reverse entries of gMGPipeCallbacks belong to
// the SERVER session, never to the client: the backend calls them with exactly the
// arguments it always passed (a writeback blobref whose Offset IS the backend's own
// mapped pointer, a range array, a surface info), and what the callback does with
// the call is Reserve + fill the head + copy the payload + PublishEvents. The host
// pointer NEVER reaches the wire - what crosses is the inline copy inside the
// SEG_EVENT record, which is rule B binding the reverse direction exactly as it
// binds MGHostSpan (R-2).
//
// OVERFLOW IS A DEFECT, NOT A DROP (§4.4): all four events are lossless in P5c, so
// a Reserve that returns nullptr is Fatal{EventRingOverflow}. CountDrop and the
// eventRingFull latch stay built and stay unused-by-policy; P9 owns the policy.
[[noreturn]] void FatalEventRingOverflow(const char* eventName, Uint64 payloadBytes) {
MGLOG_F("MGPipe: Fatal{EventRingOverflow} - the producer of %s could not reserve "
"%llu bytes on SEG_EVENT. P5c's events are lossless and a full ring under "
"lockstep is a producer burst no measured workload has, so this is a "
"defect, not a drop (CONTRACT-P5C §4.4; the drop policy is P9's)",
eventName, static_cast<unsigned long long>(payloadBytes));
std::abort();
}
void ServerOnBufferWriteback(MG_Pipe::MGPipeHandle res, Uint64 offset,
MG_Pipe::MGPBlobRef bytes) {
if (bytes.Seg != MG_Pipe::kMGHostSpanSegNone) {
// The backend handed over a segment-tagged blobref. The ONLY legal shape at
// this boundary is the monolith one - Offset is the mapped address, valid
// for this call - because the segment copy is THIS function's own job.
MGLOG_F("MGPipe: Fatal{ProtocolCorruption, \"OnBufferWriteback.Seg\"} - the "
"writeback producer was handed Seg %u; at the backend boundary the "
"blobref names the backend's own mapped bytes (Seg = "
"kMGHostSpanSegNone) and the copy into SEG_EVENT is the producer's",
bytes.Seg);
std::abort();
}
ServerSession& session = ServerSessionInstance();
const Uint64 payloadBytes = sizeof(Transport::EventBufferWritebackHead) + bytes.Size;
void* slot = session.Events().Reserve(Transport::kEventBufferWriteback, payloadBytes);
if (slot == nullptr) {
FatalEventRingOverflow("kEventBufferWriteback", payloadBytes);
}
Transport::EventBufferWritebackHead head{};
head.Resource = Transport::EventHandle{res.Slot, res.Gen};
head.Offset = offset;
head.Size = bytes.Size;
std::memcpy(slot, &head, sizeof(head));
if (bytes.Size != 0) {
std::memcpy(static_cast<Uint8*>(slot) + sizeof(head),
reinterpret_cast<const void*>(static_cast<std::uintptr_t>(bytes.Offset)),
static_cast<SizeT>(bytes.Size));
}
session.PublishEvents();
}
void ServerOnGpuWritten(MG_Pipe::MGPipeHandle res, Uint rangeCount,
const MG_Pipe::MGPRange* ranges) {
ServerSession& session = ServerSessionInstance();
const Uint64 tailBytes = static_cast<Uint64>(rangeCount) * sizeof(Transport::EventRange);
const Uint64 payloadBytes = sizeof(Transport::EventGpuWrittenHead) + tailBytes;
void* slot = session.Events().Reserve(Transport::kEventGpuWritten, payloadBytes);
if (slot == nullptr) {
FatalEventRingOverflow("kEventGpuWritten", payloadBytes);
}
Transport::EventGpuWrittenHead head{};
head.Resource = Transport::EventHandle{res.Slot, res.Gen};
head.RangeCount = static_cast<std::uint32_t>(rangeCount);
std::memcpy(slot, &head, sizeof(head));
if (tailBytes != 0) {
// EventRange and MGPRange are the same two Uint64s (EventRing.h:61-66 asserts
// it), so the tail is a plain copy rather than a per-element conversion.
std::memcpy(static_cast<Uint8*>(slot) + sizeof(head), ranges,
static_cast<SizeT>(tailBytes));
}
session.PublishEvents();
}
void ServerOnSurfaceChanged(const MG_Pipe::MGPSurfaceInfo* info) {
ServerSession& session = ServerSessionInstance();
constexpr Uint64 payloadBytes = sizeof(Transport::EventSurfaceChangedHead);
void* slot = session.Events().Reserve(Transport::kEventSurfaceChanged, payloadBytes);
if (slot == nullptr) {
FatalEventRingOverflow("kEventSurfaceChanged", payloadBytes);
}
Transport::EventSurfaceChangedHead head{};
if (info != nullptr) {
head.Width = info->Width;
head.Height = info->Height;
head.InternalFormat = info->InternalFormat;
head.Samples = info->Samples;
head.Layers = info->Layers;
head.IsDefault = info->IsDefault;
}
std::memcpy(slot, &head, sizeof(head));
session.PublishEvents();
}
// One installer for both roles' tables, so the check exists in exactly one spelling:
// writing over an entry somebody else claimed is Fatal{RoleViolation,
// "callback-double-install"} - MGPipeCallbacks' "never over an entry a backend
// already claimed" comment, made a check (CONTRACT-P5C §4.1). Finding OUR OWN
// function there is the idempotent repeat, not a second installation.
template <typename Fn>
void InstallReverseCallback(Fn& entry, Fn producer) {
if (entry != nullptr && entry != producer) {
MGLOG_F("MGPipe: Fatal{RoleViolation, \"callback-double-install\"} - a reverse "
"MGPipeCallbacks entry is already claimed by a different function. With "
"an active transport the three reverse entries are the server "
"session's producers; the client installs them under monolith only");
std::abort();
}
entry = producer;
}
ServerSession* g_active = nullptr;
} // namespace
@@ -337,6 +453,19 @@ namespace MobileGL::MG_Remote::Server {
m_accepted = true;
g_active = this;
// ---- P5c ev: the three reverse-channel producers are THIS session's (CONTRACT-P5C
// §4.1), installed before the apply thread can apply a record that produces one and
// uninstalled at Close after the join. Under monolith these entries are the
// client's (MGPipeInstallClientResourceCallbacks, monolith-only now); a session is
// by definition not monolith, so finding one of them claimed here is the double
// installation the check exists to name.
InstallReverseCallback(MG_Pipe::gMGPipeCallbacks.OnBufferWriteback,
&ServerOnBufferWriteback);
InstallReverseCallback(MG_Pipe::gMGPipeCallbacks.OnGpuWritten, &ServerOnGpuWritten);
InstallReverseCallback(MG_Pipe::gMGPipeCallbacks.OnSurfaceChanged,
&ServerOnSurfaceChanged);
LogMemory("accept");
if (!CallMaskIsSet()) {
@@ -415,6 +544,17 @@ namespace MobileGL::MG_Remote::Server {
// 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();
// The reverse-channel producers go with the session that owns them - release
// only the entries that are still OURS, never one a later owner installed.
if (MG_Pipe::gMGPipeCallbacks.OnBufferWriteback == &ServerOnBufferWriteback) {
MG_Pipe::gMGPipeCallbacks.OnBufferWriteback = nullptr;
}
if (MG_Pipe::gMGPipeCallbacks.OnGpuWritten == &ServerOnGpuWritten) {
MG_Pipe::gMGPipeCallbacks.OnGpuWritten = nullptr;
}
if (MG_Pipe::gMGPipeCallbacks.OnSurfaceChanged == &ServerOnSurfaceChanged) {
MG_Pipe::gMGPipeCallbacks.OnSurfaceChanged = nullptr;
}
}
m_consumer.Detach();
m_commands = Transport::RingConsumer();
@@ -491,6 +631,40 @@ namespace MobileGL::MG_Remote::Server {
m_consumer.NotifyClient();
}
void ServerSession::PostGlError(Uint32 code, const char* message) {
if (!m_accepted) {
// The same answer PipeInputs::RecordError's own no-live-context arm gives: a
// dropped driver error is loud, never silent.
MGLOG_E_ONCE("MG_Remote server: PostGlError (code %u) before Accept - the error is "
"dropped, because there is no SEG_EVENT to carry it on",
static_cast<unsigned>(code));
return;
}
// The message rides INLINE, NUL-terminated, MessageBytes = strlen + 1 (CONTRACT-P5C
// §1), truncated to the cap at the producer - which is here, and is why the cap is a
// constant of the wire header rather than a negotiated value.
SizeT length = message == nullptr ? 0 : std::strlen(message);
if (length >= Transport::kEventGlErrorMaxMessageBytes) {
length = Transport::kEventGlErrorMaxMessageBytes - 1;
}
const Uint32 messageBytes = static_cast<Uint32>(length) + 1;
const Uint64 payloadBytes = sizeof(Transport::EventGlErrorHead) + messageBytes;
void* slot = m_events.Reserve(Transport::kEventGlError, payloadBytes);
if (slot == nullptr) {
FatalEventRingOverflow("kEventGlError", payloadBytes);
}
Transport::EventGlErrorHead head{};
head.Code = code;
head.MessageBytes = messageBytes;
std::memcpy(slot, &head, sizeof(head));
auto* tail = reinterpret_cast<char*>(static_cast<Uint8*>(slot) + sizeof(head));
if (length != 0) {
std::memcpy(tail, message, length);
}
tail[length] = '\0';
PublishEvents();
}
// 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) {
+12
View File
@@ -158,6 +158,18 @@ namespace MobileGL::MG_Remote::Server {
// caller and therefore compiles for every wrong pairing; the session is the thing
// that knows which bell belongs to the client.
void PublishEvents();
// ---- P5c ev: the reverse channel's producers (CONTRACT-P5C §4) -------------------
//
// With an active transport the three reverse MGPipeCallbacks entries are THIS
// session's producer callbacks (Accept installs them, Close uninstalls them), and
// the fourth event kind is posted through here: PipeInputs::RecordError's transport
// arm calls PostGlError with the frontend ErrorCode widened and the ErrorInfo's
// message. `message` may be null; a longer message than
// Transport::kEventGlErrorMaxMessageBytes is truncated, which is the contract's
// ruling (§1), not a check. A session that has not accepted drops the error with a
// loud line, exactly as RecordError's own no-live-context arm does.
void PostGlError(Uint32 code, const char* message);
Transport::ITransport* Control_Plane();
// completedFrameSerial / presentAckSerial: the two watermarks only the server can
@@ -0,0 +1,356 @@
// MobileGL - MobileGL/MG_Remote/Server/StagedTextureStore.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
// P5c tx - THE SERVER'S OWN COPY OF THE STAGED TEXTURE LEVELS. The texture twin of
// StagedShadow.h (R-11), held to its four rulings (CONTRACT-P5C.md §2.1).
//
// THE DEFECT THIS ENDS (T1/T5). resource_subdata's texture half stages the level bytes into
// SEG_STAGE and ApplyTextureUpload (PipeApply.cpp:989-1036) drops the pointer after the gate,
// the accumulation and the serial. Espryt then re-reads the client's MipmapStorage at sync
// time (Managers.cpp:6940, :7129, :7198, :7315), reads per-level shape off the client object
// (:6928, :6936, :7314, :7332, DirectGLES.cpp:8502-8507, :8528-8529), and Magma WRITES the
// client's level storage outright (VulkanRenderer.cpp:1562-1609: AllocateStorage +
// MarkStorageDirty). In monolith every one of those is correct - the bytes belong to a
// frontend object that outlives the call. Under split the pointer names SEG_STAGE, valid
// only until retiredSeq passes the record, and w1's MOBILEGL_IPC_AUDIT=1 fills retired
// staging with 0xDD precisely so an implementation that kept the pointer is DISTINGUISHABLE
// from one that copied. So this copies, at apply time, into server-owned storage, and the
// sync reads nothing but this store and the descriptor.
//
// WHAT A KEY IS, AND WHY IT IS NOT THE TWIN ADDRESS THE CONTRACT'S FIRST DRAFT SAID.
// CONTRACT-P5C §2.1 rules "keyed by the texture resource twin's address". The buffer half
// keys by twin address because the twin is minted at sub-data time under split
// (Managers.cpp:2139-2142) and GLESBufferResource's constructor is GL-free. The texture
// twin's constructor is NOT: BackendTextureObject() calls glGenTextures (Managers.cpp:5496),
// so minting it at sub-data time would allocate a driver name for every texture that is
// written and never drawn, and would put a GL call into a unit test that has no context
// (R-16's unit case, StagedTextureStoreTest, exercises the REAL ops table headless). The
// wire HANDLE the record carried serves the same purpose the address served - stable for
// the object's life, liveness-exact through the generation, already in every caller's hand
// (rule E: the apply thread resolves every object from a handle the record carried) - so
// KeyForHandle is the primary key. KeyForTwinAddress exists for the one caller that has a
// server-side twin and no handle: Magma's T5 shadow writes key by the TextureResource. The
// two namespaces cannot collide (handle keys carry the top bit; user-space heap addresses
// never do). Every event that ends a key's life has a call site: a named-level respecify
// re-defines the level (NoteLevelDefined), a whole-resource respecify drops every level
// (ResetLevels), resource_destroy drops the key (Ops_H_TextureDestroy), context death drops
// all (OnBackendContextDestroyed, beside MGL_SERVER_STAGED_DROP_ALL).
//
// COVERAGE IS EXACTLY THE STAGED RUN, NEVER WIDENED AND NEVER NARROWER. The texture half of
// resource_subdata ALWAYS stages the whole level shadow (TextureEmit.h:1285: "the bytes this
// record declares ARE the level shadow", Blob.Size = the level's byte count), so one Adopt
// covers its level whole. The record's region set is deliberately NOT the coverage unit: it
// declares which texels CHANGED (the upload planner's shape, which the applier's pending set
// already carries), while the full-level upload paths - every conversion fallback, and the
// immutable/mutable regeneration arms - read the whole level including texels no region
// named. Those texels crossed in the staged run; treating them as uncovered would Fatal a
// legal glTexStorage-then-small-glTexSubImage sequence whose first (and only) record names a
// small box, and moving them into the store is not the buffer half's silent-zero case
// because they are the client's own shadow bytes, delivered and declared. A sync that asks
// for a level this store has no covered run for is Fatal{StageSnapshotTooNarrow} - the same
// words as the buffer half, for the same reason: the bytes have never existed on this side,
// and inventing them is silent data loss, not a missing optimisation.
//
// DEFINED-NESS IS TRACKED, NOT DERIVED ALONE. §1's per-level extent derivation (max(1,
// base >> level), layer axes fixed) computes the extent of a level that EXISTS; it cannot
// say whether the level was ever defined, and the mutable regen arms skip undefined levels
// (a sparse chain stays sparse on the driver). The client does not emit per-level extents,
// but every storage-defining call DOES cross as a respecify, so defined-ness reaches this
// store through the ops table's TextureRespecify hook: a named level marks that (uploadTarget,
// level), an immutable whole-resource respecify (glTexStorage*) marks every level of every
// upload target. Levels the store has never heard of answer extent {0,0,0}, which is the
// exact answer the frontend's GetMipmapTexelSize gives for them - FBO completeness over a
// null-data level and the sparse-chain skip both reproduce the monolith arm.
//
// GPU-GENERATED LEVELS (T5) ARE DEFINED HERE WITH NO BYTES AND A DIRTY MARK. A GPU-side
// generation (Magma's GenerateMipmap) dirties the SERVER's shadow, not the client's: the
// level is NoteLevelDefined + MarkLevelGpuDirty(true), it holds no bytes (they were made on
// the GPU and never crossed), and the mark is the "dirty region, level has NO pending
// upload" answer of §2.2's table. A texel read of such a level is the
// Fatal{StageSnapshotTooNarrow} case above, which is correct: the two readers that could
// ask are both named refusals under split (§2.3).
//
// WHY IT IS A HEADER AND NOT A BLOCK INSIDE Managers.cpp - StagedShadow.h's reason, and it
// is the one that matters here too: 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 `copies` is
// a constructor 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; the production wiring is
// asserted separately, through the real ops table, in StagedTextureStoreTest.
#pragma once
#include <Includes.h>
#include <MG_Pipe/MGPipeTypes.h>
#include <MG_Util/Debug/Log.h>
#include <MG_Util/Math/VectorTypes.h>
#include <algorithm>
#include <cstdint>
#include <cstring>
#include <mutex>
#if MOBILEGL_BUILD_DISAGGREGATED
#include <Config.h>
#endif
namespace MobileGL::MG_Remote::Server {
// §1's server-side per-level extent (CONTRACT-P5C table 0): max(1, base_extent >> level)
// per SHRINKING axis, with an array texture's layer count fixed - it is not a dimension of
// the image (GL 4.6 core 8.14.3), and GetMipmapTexelSize parks it in the slot after the
// image's own dimensions. Texture1DArray shrinks x only; Texture2DArray and
// TextureCubeMapArray shrink x and y; every other target shrinks all three. This is the
// mip chain's definition (MG_State's IsMipmapCompleteForFilter applies the same split,
// TextureObject.cpp:705-734), so two honest ends compute the same number.
inline Int StagedTextureShrinkingAxisCount(Uint8 pipeResourceTarget) {
switch (static_cast<MG_Pipe::MGPipeResourceTarget>(pipeResourceTarget)) {
case MG_Pipe::MGPipeResourceTarget::Tex1DArray:
return 1;
case MG_Pipe::MGPipeResourceTarget::Tex2DArray:
case MG_Pipe::MGPipeResourceTarget::TexCubeArray:
return 2;
default:
return 3;
}
}
inline IntVec3 StagedTextureMipExtent(Uint8 pipeResourceTarget, Uint32 baseWidth, Uint32 baseHeight,
Uint32 baseDepth, Uint32 level) {
const Int shrinking = StagedTextureShrinkingAxisCount(pipeResourceTarget);
const Int shift = static_cast<Int>(level);
IntVec3 extent{static_cast<Int>(baseWidth), static_cast<Int>(baseHeight), static_cast<Int>(baseDepth)};
for (Int axis = 0; axis < shrinking && axis < 3; ++axis) {
extent[axis] = std::max<Int>(extent[axis] >> shift, 1);
}
return extent;
}
class StagedTextureStore {
public:
// `copies` is "this process is really split". False reproduces the monolith expression
// character for character: the client shadow answers every question (the sync's macros
// never consult this store when CopiesIntoServerStorage() is false), nothing is
// allocated, and every push and verify lane stays byte-identical to what it was
// before tx.
explicit StagedTextureStore(Bool copies) : m_copies(copies) {}
Bool CopiesIntoServerStorage() const { return m_copies; }
// The wire handle the record carried, tagged so it can never alias a twin address.
// Slot and Gen are the client allocator's identity for one live object, so a recycled
// slot's new owner keys a different entry than its predecessor's stale one.
static Uint64 KeyForHandle(MG_Pipe::MGPipeHandle handle) {
return (Uint64{1} << 63) | (static_cast<Uint64>(handle.Slot) << 32) |
static_cast<Uint64>(handle.Gen);
}
// For the caller whose server-side twin has no wire handle (Magma's TextureResource,
// T5). Node-stable by that table's own ruling (std::unordered_map nodes).
static Uint64 KeyForTwinAddress(const void* twin) {
return static_cast<Uint64>(reinterpret_cast<std::uintptr_t>(twin));
}
// THE ADOPTION. Copies the record's staged run - the whole level shadow, byteSize =
// MGPSubData::Blob.Size under split - into server-owned storage and marks the level
// covered whole (see the header comment for why the run, not the region set, is the
// coverage). REPLACES the level's entry: the run is the level's complete current
// content, so nothing of a previous run survives, and a fresh adoption is by
// definition not GPU-dirty. Returns the server-owned base; under monolith it does
// nothing and returns nullptr, and the caller (Ops_H_TextureSubData) has already
// returned before reaching here.
const Uint8* Adopt(Uint64 key, Uint16 uploadTarget, Uint16 level, const IntVec3& extent,
const void* bytes, SizeT byteSize) {
if (!m_copies) return nullptr;
const std::lock_guard<std::mutex> lock(m_mutex);
LevelShadow& shadow = m_shadows[key].Levels[PackLevel(uploadTarget, level)];
shadow.Extent = extent;
shadow.Bytes.clear();
if (bytes != nullptr && byteSize != 0) {
const auto* raw = static_cast<const Uint8*>(bytes);
shadow.Bytes.assign(raw, raw + byteSize);
}
shadow.Defined = true;
shadow.GpuDirty = false;
m_any.store(true, std::memory_order_release);
return shadow.Bytes.empty() ? nullptr : shadow.Bytes.data();
}
// A storage-defining respecify named this level: it EXISTS from here on, at this
// extent (null-data glTexImage*D, a generated level). An extent move redefines the
// level's coordinate system, so the bytes and the dirty mark of the old one go with
// it; an extent-restating one keeps them, which is the same answer the driver gives
// (a same-shape redefinition that carries no new upload leaves the old texels in
// place - undefined content is allowed to be the old content).
void NoteLevelDefined(Uint64 key, Uint16 uploadTarget, Uint16 level, const IntVec3& extent) {
if (!m_copies) return;
const std::lock_guard<std::mutex> lock(m_mutex);
LevelShadow& shadow = m_shadows[key].Levels[PackLevel(uploadTarget, level)];
if (!shadow.Defined || shadow.Extent != extent) {
shadow.Bytes.clear();
shadow.GpuDirty = false;
}
shadow.Extent = extent;
shadow.Defined = true;
m_any.store(true, std::memory_order_release);
}
// A whole-resource redefinition (glTexStorage*, a texture view): every level's old
// coordinate system is gone, so every level entry goes. The caller marks the new
// chain defined level by level afterwards where the call defines one.
void ResetLevels(Uint64 key) {
if (!m_any.load(std::memory_order_acquire)) return;
const std::lock_guard<std::mutex> lock(m_mutex);
m_shadows.erase(key);
}
// T5's dirty mark: a GPU-side generation made this level's texels newer than any
// shadow. The level typically holds NO bytes - they were generated on the GPU and
// never crossed - and the mark is what answers "dirty region, level has no pending
// upload" without asking the client (§2.2's last row).
void MarkLevelGpuDirty(Uint64 key, Uint16 uploadTarget, Uint16 level, Bool dirty) {
if (!m_copies) return;
const std::lock_guard<std::mutex> lock(m_mutex);
m_shadows[key].Levels[PackLevel(uploadTarget, level)].GpuDirty = dirty;
m_any.store(true, std::memory_order_release);
}
void Drop(Uint64 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 sync wants texels this store has no covered run for. This is THE data
// -correctness refusal of the texture half: a pending upload with no adoption behind
// it, a GPU-generated level (no bytes by construction), a level the client never
// defined, and a monolith-arm misuse all land here, because in every one of them the
// bytes have never existed on this side and re-reading the client's shadow for them
// is the cross-role access tx exists to end.
const Uint8* RequireLevelBytes(Uint64 key, Uint16 uploadTarget, Uint16 level, const char* site) const {
if (!m_copies) return nullptr;
const std::lock_guard<std::mutex> lock(m_mutex);
const LevelShadow* shadow = FindLevel(key, uploadTarget, level);
if (shadow != nullptr && shadow->Defined && !shadow->Bytes.empty()) {
return shadow->Bytes.data();
}
MGLOG_F("MGPipe: Fatal{StageSnapshotTooNarrow, \"%s\"} - the texture sync wants the "
"bytes of (uploadTarget=%u, level=%u) and the server's staged shadow has no "
"covered run for it. Under split the authoritative shadow is SERVER-OWNED "
"(rule C) and resource_subdata is the only way bytes reach it, so these "
"texels have never existed on this side: the record that should have "
"carried them is missing, or the level's texels were generated on the GPU "
"and no byte answer exists at all. Re-reading the client's shadow would be "
"the cross-role access this store exists to end",
site, static_cast<Uint32>(uploadTarget), static_cast<Uint32>(level));
std::abort();
}
// Diagnostics the sync path and the unit cases read, so that a check can assert WHAT
// HAPPENED rather than that nothing blew up.
Bool IsCovered(Uint64 key, Uint16 uploadTarget, Uint16 level) const {
const std::lock_guard<std::mutex> lock(m_mutex);
const LevelShadow* shadow = FindLevel(key, uploadTarget, level);
return shadow != nullptr && shadow->Defined && !shadow->Bytes.empty();
}
Bool IsLevelDefined(Uint64 key, Uint16 uploadTarget, Uint16 level) const {
const std::lock_guard<std::mutex> lock(m_mutex);
const LevelShadow* shadow = FindLevel(key, uploadTarget, level);
return shadow != nullptr && shadow->Defined;
}
Bool IsLevelGpuDirty(Uint64 key, Uint16 uploadTarget, Uint16 level) const {
if (!m_any.load(std::memory_order_acquire)) return false;
const std::lock_guard<std::mutex> lock(m_mutex);
const LevelShadow* shadow = FindLevel(key, uploadTarget, level);
return shadow != nullptr && shadow->GpuDirty;
}
// {0,0,0} for a level this store has never heard of - the exact answer the frontend's
// GetMipmapTexelSize gives for an undefined level, which is what keeps the regen
// arms' sparse-chain skip intact.
IntVec3 LevelExtentOrUndefined(Uint64 key, Uint16 uploadTarget, Uint16 level) const {
if (!m_any.load(std::memory_order_acquire)) return IntVec3{0, 0, 0};
const std::lock_guard<std::mutex> lock(m_mutex);
const LevelShadow* shadow = FindLevel(key, uploadTarget, level);
if (shadow == nullptr || !shadow->Defined) return IntVec3{0, 0, 0};
return shadow->Extent;
}
SizeT LevelByteSize(Uint64 key, Uint16 uploadTarget, Uint16 level) const {
if (!m_any.load(std::memory_order_acquire)) return 0;
const std::lock_guard<std::mutex> lock(m_mutex);
const LevelShadow* shadow = FindLevel(key, uploadTarget, level);
if (shadow == nullptr || !shadow->Defined) return 0;
return shadow->Bytes.size();
}
Bool HasShadow(Uint64 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();
}
SizeT TrackedResources() const {
const std::lock_guard<std::mutex> lock(m_mutex);
return m_shadows.size();
}
SizeT TrackedLevelCount(Uint64 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.Levels.size();
}
private:
static Uint32 PackLevel(Uint16 uploadTarget, Uint16 level) {
return (static_cast<Uint32>(uploadTarget) << 16) | static_cast<Uint32>(level);
}
struct LevelShadow {
IntVec3 Extent{0, 0, 0};
// The level's whole staged run. EMPTY for a defined-but-byteless level (null-data
// definition, GPU-generated) - emptiness is the coverage answer, not an error.
Vector<Uint8> Bytes;
Bool Defined = false;
Bool GpuDirty = false;
};
struct TextureShadow {
ska::flat_hash_map<Uint32, LevelShadow> Levels;
};
const LevelShadow* FindLevel(Uint64 key, Uint16 uploadTarget, Uint16 level) const {
const auto textureIt = m_shadows.find(key);
if (textureIt == m_shadows.end()) return nullptr;
const auto levelIt = textureIt->second.Levels.find(PackLevel(uploadTarget, level));
return levelIt == textureIt->second.Levels.end() ? nullptr : &levelIt->second;
}
const Bool m_copies;
mutable std::mutex m_mutex;
ska::flat_hash_map<Uint64, TextureShadow> m_shadows;
// Read on every IsLevelGpuDirty / LevelExtentOrUndefined, so the monolith cost is one
// acquire load of a never-written flag rather than a mutex and two hash lookups.
std::atomic<Bool> m_any{false};
};
#if MOBILEGL_BUILD_DISAGGREGATED
// ONE PER PROCESS, and its copying arm is decided ONCE at first use - StagedShadow's
// ServerStaged() ruling verbatim: the two arms hold the authoritative bytes in DIFFERENT
// places, so an answer that changed mid-run would strand every level already staged.
// Leaked at exit like every other MG_Remote singleton (ID-8). In a header rather than in
// Managers.cpp because TWO backends consume it: Espryt's adoption and sync
// (Managers.cpp) and Magma's T5 shadow writes (VulkanRenderer.cpp) must name the same
// store, and an inline function's one static gives them exactly that.
inline StagedTextureStore& ServerStagedTexture() {
static StagedTextureStore& store =
*new StagedTextureStore(MG_Config::Transport != MG_Config::TransportMode::Monolith);
return store;
}
#endif
} // namespace MobileGL::MG_Remote::Server
+18 -1
View File
@@ -42,12 +42,14 @@
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.
// event, which is why the list starts at 1. APPEND-ONLY, for the same reason
// the opcode space is (CONTRACT-P5C §7.7): kEventGlError is the first addition.
enum EventKind : std::uint16_t {
kEventNone = 0,
kEventBufferWriteback = 1, // MGPipeCallbacks::OnBufferWriteback
kEventGpuWritten = 2, // MGPipeCallbacks::OnGpuWritten
kEventSurfaceChanged = 3, // MGPipeCallbacks::OnSurfaceChanged
kEventGlError = 4, // PipeInputs::RecordError, posted by the server session
};
// The 8-byte {slot, gen} pair, mirrored (MGPipeHandles.h:54-65).
@@ -97,6 +99,21 @@ namespace MobileGL::MG_Remote::Transport {
};
static_assert(sizeof(EventSurfaceChangedHead) == 24, "MGPSurfaceInfo is 24 bytes on the wire");
// PipeInputs::RecordError(code, info) (CONTRACT-P5C §1). The NUL-terminated
// message follows this head INSIDE THE RECORD: MessageBytes = strlen + 1 and
// the NUL travels, so MessageBytes == 0 is the corrupt shape, never "no
// message". A longer message is TRUNCATED AT THE PRODUCER to the cap; the cap
// is a static_assert here, not a runtime check, because it is part of the
// wire's shape rather than a policy a peer may disagree about.
struct EventGlErrorHead {
std::uint32_t Code; // the frontend ErrorCode, widened
std::uint32_t MessageBytes; // strlen + 1, the NUL included
};
static_assert(sizeof(EventGlErrorHead) == 8, "wire shape");
inline constexpr std::uint32_t kEventGlErrorMaxMessageBytes = 1024;
static_assert(kEventGlErrorMaxMessageBytes == 1024,
"CONTRACT-P5C §1 caps an inline GL-error message at 1024 bytes, NUL included");
// The server's end. One producer: the apply thread, by construction.
class EventRingProducer {
public:
+29 -1
View File
@@ -239,7 +239,10 @@ namespace MobileGL::MG_Remote::Wire {
X(PatchParameter, MGPPatchParameter) \
X(BindStreamOutput, MGPStreamOutputBind) \
X(SetStorageBlockBinding, MGPStorageBlockBinding) \
X(CopyFramebufferToTexture, MGPCopyFromFramebuffer)
X(CopyFramebufferToTexture, MGPCopyFromFramebuffer) \
X(ApplierReset, MGPApplierReset) \
X(ObjectDeath, MGPHandleOnly) \
X(SetContextValues, MGPContextValues)
namespace {
@@ -2085,6 +2088,31 @@ namespace MobileGL::MG_Remote::Wire {
m_verbs->OnCopyFramebufferToTexture(
*static_cast<const MGPCopyFromFramebuffer*>(payload));
// ---- P5c's two control records, opcodes 77..78 (MG_Remote/CONTRACT-P5C.md §5) --------
//
// Fixed-size PODs the bounds gate has already proved; neither carries a blob, a tail
// or a reply, so each arm hands over and stops. ObjectDeath's null-handle refusal is
// the sink's, not the codec's: the codec proves SHAPES, and "the client emits nothing
// for an object that never crossed" (§5.2) is a contract fact about the peer.
case MGPWireOp::ApplierReset:
return m_verbs != nullptr &&
m_verbs->OnApplierReset(*static_cast<const MGPApplierReset*>(payload));
case MGPWireOp::ObjectDeath:
return m_verbs != nullptr &&
m_verbs->OnObjectDeath(*static_cast<const MGPHandleOnly*>(payload));
// ---- P5c rv (CONTRACT-P5C.md §5.3): the residual-value record, opcode 79 -------------
//
// An ordinary set_* row, unlike the two control records beside it: a fixed-width POD
// with no blob, no tail and no reply, so the bounds gate is the whole validation and
// the arm is the applier entry point - the same shape as set_pixel_pack_state beside
// it. There is no sink half and no acceptance answer: the write into gPipeInputs is
// the whole effect.
case MGPWireOp::SetContextValues:
MGPipeApplySetContextValues(*static_cast<const MGPContextValues*>(payload));
return true;
case MGPWireOp::SetSwapInterval:
// Class C, wave 3 (census-classC.md "static cross"); not a verb (FillPoints.def:21).
return false;
+19
View File
@@ -534,6 +534,25 @@ namespace MobileGL::MG_Remote::Wire {
(void)copy;
return false;
}
// ---- P5c (MG_Remote/CONTRACT-P5C.md §5): the two control records, opcodes 77..78.
//
// Same hand-over shape as the P5b rows: the codec validates the record (a fixed-size
// POD, no blob, no tail) and the SERVER'S sink does the work - OnApplierReset runs the
// server's own MGPipeApplierReset() after asserting ContextSerial against the
// session's (§5.1: ASSERTED, never dispatched on, P5c has one context per session),
// and OnObjectDeath releases the kind's twin table by the handle the record carried
// (§5.2). The default bodies return false ("this build does not implement it"), so a
// unit decoder without a server declines by the same answer every other unimplemented
// row gives.
virtual Bool OnApplierReset(const MG_Pipe::MGPApplierReset& reset) {
(void)reset;
return false;
}
virtual Bool OnObjectDeath(const MG_Pipe::MGPHandleOnly& death) {
(void)death;
return false;
}
};
// Not thread safe: one decoder on the apply thread, by construction.
@@ -29,6 +29,28 @@ namespace MobileGL::MG_State::GLState {
const BufferBackendOps* g_bufferBackendOps = nullptr;
// Starts at 1 so a zero-initialized cache slot can never carry a live buffer's id.
std::atomic<Uint64> g_nextBufferLifetimeId{1};
#if MOBILEGL_BUILD_DISAGGREGATED
// P5c (hd, CONTRACT-P5C §3.8 / §6 layer 1): the frontend BufferObject's legacy
// accessors are a layer-1 surface. With an active transport, the pre-handle buffer
// arm that reads them (Managers.cpp's RespecifyStorageNow / UploadRangeNow /
// IsBufferDrawClean / the old EnsureBufferResource body) stays compiled but may not
// run: the apply thread calling one is Fatal{RoleViolation, "buffer-legacy-arm"} -
// the same shape as Fatal{PipeLegacyMemosDisabled} - so a cleared subsystem bit 7 no
// longer leaves the arm silently readable. Client-thread callers (the GL thread's
// own state) are unaffected.
void RefuseLegacyBufferArmFromApplyThread(const char* accessor) {
if (!MG_Remote::Client::PersistentMapTracker::PushIsArmed()) return;
if (!MG_Remote::Client::PersistentMapTracker::OnServerRole()) return;
MGLOG_F("MGPipe: Fatal{RoleViolation, \"buffer-legacy-arm\"} - the apply thread "
"called BufferObject::%s on a frontend object. With an active transport "
"the server reads the applier's resource record and its own staged shadow; "
"a frontend object is client memory (rule E) and the pre-handle buffer arm "
"is monolith-only",
accessor);
std::abort();
}
#endif
}
Uint64 BufferObject::AllocateLifetimeId() {
@@ -378,6 +400,9 @@ namespace MobileGL::MG_State::GLState {
void BufferObject::SyncPersistentMappedRange() {
#if MOBILEGL_BUILD_DISAGGREGATED
// P5c (hd): the named refusal comes FIRST - the silent return below used to let a
// server-side caller slip through with one MGLOG_D's worth of evidence (B3).
RefuseLegacyBufferArmFromApplyThread("SyncPersistentMappedRange");
// Split's client pre-verb hook publishes these bytes. The retained backend sync
// sites must do nothing on the apply thread: re-entering this producer there would
// overwrite the server shadow through the monolith adapter without crossing the wire.
@@ -538,7 +563,29 @@ namespace MobileGL::MG_State::GLState {
if (MG_Config::Transport != MG_Config::TransportMode::Monolith) {
#if MOBILEGL_PIPE_PUSH
if (m_size != 0 && MG_Pipe::MGPipeResourceSubsystemEnabled()) {
MG_Pipe::MGPipeEmitResourceReadback(*this);
const SizeT sliceBytes = MG_Remote::Client::BufferWritebackSliceBytes();
if (sliceBytes != 0 && m_size > sliceBytes) {
// The writeback's bytes travel INLINE in a SEG_EVENT record (P5c ev),
// and one record must fit the ring (MaxRecordBytes == capacity/2) - a
// whole-buffer request for a buffer larger than that aborts the server
// on Fatal{EventRingOverflow}. Slice the request instead: every slice
// round-trips its own barrier + drain before the next is emitted, so
// the ring holds at most one slice's bytes at a time, and the in-order
// channel makes the last slice's landing imply every earlier one.
for (SizeT off = 0; off < m_size; off += sliceBytes) {
const SizeT left = m_size - off;
MG_Pipe::MGPipeEmitResourceReadbackRange(*this, off,
left < sliceBytes ? left : sliceBytes);
}
// No single writeback covered the whole buffer, so
// WritebackFromBackend's clear (above) never fired - but every slice
// has landed by here, which is exactly what the flag-clearing there
// says. Clearing by hand is what keeps AwaitBufferWriteback's
// third-state Fatal from misfiring on a sliced readback.
m_gpuWritePending = false;
} else {
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
@@ -914,6 +961,9 @@ namespace MobileGL::MG_State::GLState {
}
const Uint8* BufferObject::MappedData() const {
#if MOBILEGL_BUILD_DISAGGREGATED
RefuseLegacyBufferArmFromApplyThread("MappedData");
#endif
return m_resource.Bytes();
}
@@ -934,10 +984,18 @@ namespace MobileGL::MG_State::GLState {
}
Uint64 BufferObject::GetChangeSerial() const {
#if MOBILEGL_BUILD_DISAGGREGATED
RefuseLegacyBufferArmFromApplyThread("GetChangeSerial");
#endif
return m_changeSerial;
}
Bool BufferObject::HasDefinedContent() const {
#if MOBILEGL_BUILD_DISAGGREGATED
// §3.6's surface as well as §3.8's: the descriptor's bit and the staged coverage
// answer on this side; the frontend flag is client memory.
RefuseLegacyBufferArmFromApplyThread("HasDefinedContent");
#endif
return m_hasDefinedContent;
}
@@ -950,6 +1008,9 @@ namespace MobileGL::MG_State::GLState {
}
Bool BufferObject::IsMapped() const {
#if MOBILEGL_BUILD_DISAGGREGATED
RefuseLegacyBufferArmFromApplyThread("IsMapped");
#endif
return m_isMapped;
}
+6
View File
@@ -1212,6 +1212,12 @@ namespace MobileGL::MG_State {
return m_framebufferState.ValidateFramebufferObject(index);
}
#if MOBILEGL_BUILD_DISAGGREGATED
SharedPtr<FramebufferObject> GLContext::FindFramebufferObjectByLifetimeId(Uint64 lifetimeId) const {
return m_framebufferState.FindFramebufferObjectByLifetimeId(lifetimeId);
}
#endif
// Sampler
void GLContext::GenSamplerNames(Uint number, Vector<Uint>& samplers) {
m_samplerState.GenerateNames(number, samplers);
+8 -2
View File
@@ -256,8 +256,9 @@ namespace MobileGL {
// four words on a wire are not the value unless the class travels with them:
// glVertexAttrib4f(loc, 1.5f, ...) leaves 1 in intValue and 0x3FC00000 in
// floatValue. set_vertex_attrib_defaults carries this as MGPAttribValue's
// ValueClass so the applier can redo the conversion instead of memcpying one
// view into all three.
// ValueClass AND, since P5c rv (CONTRACT-P5C.md §5.3), all three views
// verbatim - the applier writes each view from its own array rather than
// redoing the conversion.
//
// It is kept BESIDE the array rather than inside CurrentVertexAttributeValue
// because that struct is mirrored into PipeInputs and compared there by a
@@ -544,6 +545,11 @@ namespace MobileGL {
// Framebuffer
void GenFramebufferNames(Uint number, Vector<Uint>& framebuffers);
const SharedPtr<FramebufferObject>& GetFramebufferObject(Uint index);
#if MOBILEGL_BUILD_DISAGGREGATED
// See FramebufferState::FindFramebufferObjectByLifetimeId - the named-blit
// consumer's handle-to-frontend resolution on a backend with no FBO twins.
SharedPtr<FramebufferObject> FindFramebufferObjectByLifetimeId(Uint64 lifetimeId) const;
#endif
BindingSlot<FramebufferObject>& GetFramebufferBindingSlot(FramebufferTarget target);
const SharedPtr<FramebufferObject>& CreateFramebufferObject(Uint index);
void MarkFramebufferObjectForDeletion(Uint index);
@@ -78,4 +78,15 @@ namespace MobileGL::MG_State::GLState {
Bool FramebufferState::ValidateFramebufferObject(Uint index) const {
return m_framebufferObjects.find(index) != m_framebufferObjects.end();
}
#if MOBILEGL_BUILD_DISAGGREGATED
SharedPtr<FramebufferObject> FramebufferState::FindFramebufferObjectByLifetimeId(Uint64 lifetimeId) const {
for (const auto& [index, framebufferObject] : m_framebufferObjects) {
if (framebufferObject && framebufferObject->GetLifetimeId() == lifetimeId) {
return framebufferObject;
}
}
return nullptr;
}
#endif
} // namespace MobileGL::MG_State::GLState
@@ -25,6 +25,16 @@ namespace MobileGL::MG_State::GLState {
Bool ValidateName(Uint index) const;
Bool ValidateFramebufferObject(Uint index) const;
#if MOBILEGL_BUILD_DISAGGREGATED
// P5c (G6, CONTRACT-P5C §3.3/§5.4): the reverse of HandleFor() for a server that holds
// only the handle - the named-blit consumer on a backend with no FBO twin registry
// (Magma) resolves the verb's ReadFbo/DrawFbo to the frontend object by the lifetime
// id the handle was minted over. Named debt, reached inside
// MGPipeFrontendKeyedRegistryScope; P3b/P4b retire it by carrying the object identity
// in the record. nullptr when no live framebuffer owns the id.
SharedPtr<FramebufferObject> FindFramebufferObjectByLifetimeId(Uint64 lifetimeId) const;
#endif
#if MOBILEGL_PIPE_PUSH
// P2 brief D4: "did the attachment set or the default geometry of ANY framebuffer
// move". It does NOT cover a BIND - a bind writes a BindingSlot, not the object - so
@@ -8,10 +8,50 @@
#include "MipmapStorage.h"
#if MOBILEGL_BUILD_DISAGGREGATED
#include <Config.h>
#include <MG_Remote/Server/ServerLoop.h>
#include <MG_Util/Debug/Log.h>
#include <cstdlib>
#endif
namespace MobileGL {
namespace MG_State {
namespace GLState {
namespace {
#if MOBILEGL_BUILD_DISAGGREGATED
// P5c (gt, CONTRACT-P5C §6 layer 1): the frontend TextureObjectMipmap's
// mutable surfaces - the maps, the storage (re)definitions and the
// storage-dirty model - are a layer-1 surface, and MipmapStorage is the one
// funnel every concrete texture class reaches them through (the cube's six
// faces included, and a view's forwards land on its owner's storage). With an
// active transport the apply thread calling one is
// Fatal{RoleViolation, "texture-legacy-arm"} - the texture twin of hd's
// BufferObject guard (BufferObject.cpp): the server reads its own staged
// texture shadow and the descriptor (tx), never this memory. Client-thread
// callers (the GL thread's own state) are unaffected, and the guard compiles
// out of every non-split build, so the pull build's bytes do not move (G1).
//
// The message names the TEXTURE-side method, not this storage's: the pinned
// surface list (MG_Test/Wire/RemoteClientTest.cpp's RemoteGuards) is written
// in TextureObjectMipmap's vocabulary.
void RefuseLegacyTextureArmFromApplyThread(const char* surface) {
if (MG_Config::Transport == MG_Config::TransportMode::Monolith) return;
if (!MG_Remote::Server::ServerLoop::OnApplyThread()) return;
// The named exemption (MipmapStorage.h): Magma's texture sync is tx's
// declared leftover and retires with P7.
if (MGPipeTextureLegacyArmScope::Active()) return;
MGLOG_F("MGPipe: Fatal{RoleViolation, \"texture-legacy-arm\"} - the apply thread "
"called TextureObjectMipmap::%s on a frontend object. With an active "
"transport the server reads the staged-texture store and the resource "
"descriptor (CONTRACT-P5C §2, rule E); a frontend texture's level "
"storage is client memory and this arm is monolith-only",
surface);
std::abort();
}
#endif
// Overlapping OR abutting ([lo, hi) intervals meeting edge-to-edge) in
// every axis: merging abutting boxes keeps scanline/tile write patterns
// as one rect instead of a picket fence.
@@ -28,11 +68,32 @@ namespace MobileGL {
}
} // namespace
#if MOBILEGL_BUILD_DISAGGREGATED
namespace {
thread_local Uint32 g_textureLegacyArmScopeDepth = 0;
}
MGPipeTextureLegacyArmScope::MGPipeTextureLegacyArmScope() {
++g_textureLegacyArmScopeDepth;
}
MGPipeTextureLegacyArmScope::~MGPipeTextureLegacyArmScope() {
--g_textureLegacyArmScopeDepth;
}
Bool MGPipeTextureLegacyArmScope::Active() {
return g_textureLegacyArmScopeDepth != 0;
}
#endif
SizeT MipmapStorage::GetLevelCount() const {
return m_data.size();
}
void MipmapStorage::AllocateLevel(Uint level, MipmapInput input) {
#if MOBILEGL_BUILD_DISAGGREGATED
RefuseLegacyTextureArmFromApplyThread("AllocateStorage");
#endif
// Grow only. GL respecifies exactly the level it is handed, so allocating level 0
// must not disturb the levels above it - but resize() shrinks as readily as it
// grows, so this used to truncate the whole chain to a single level. Callers that
@@ -125,6 +186,9 @@ namespace MobileGL {
}
void MipmapStorage::TruncateToLevelCount(SizeT levelCount) {
#if MOBILEGL_BUILD_DISAGGREGATED
RefuseLegacyTextureArmFromApplyThread("TruncateMipmapLevels");
#endif
if (levelCount >= m_data.size()) return;
m_data.resize(levelCount);
@@ -138,6 +202,9 @@ namespace MobileGL {
}
void MipmapStorage::UpdateSubData(Uint level, DataPtr input) {
#if MOBILEGL_BUILD_DISAGGREGATED
RefuseLegacyTextureArmFromApplyThread("UpdateMipmapSubData");
#endif
auto& targetData = m_data;
MOBILEGL_ASSERT(level < targetData.size(), "UpdateSubData: level out of range");
auto& levelData = targetData[level];
@@ -152,6 +219,9 @@ namespace MobileGL {
}
void* MipmapStorage::MapData(Uint level) {
#if MOBILEGL_BUILD_DISAGGREGATED
RefuseLegacyTextureArmFromApplyThread("MapMipmapData");
#endif
auto& targetData = m_data;
MOBILEGL_ASSERT(level < targetData.size(), "UpdateSubData: level out of range");
auto& levelData = targetData[level];
@@ -170,6 +240,9 @@ namespace MobileGL {
}
void MipmapStorage::MarkDirty(Uint level, bool dirty) {
#if MOBILEGL_BUILD_DISAGGREGATED
RefuseLegacyTextureArmFromApplyThread("MarkStorageDirty");
#endif
MOBILEGL_ASSERT(level < m_isDirty.size(), "MarkDirty: level out of range");
m_isDirty[level] = dirty;
if (level < m_dirtyRegions.size()) {
@@ -191,11 +264,17 @@ namespace MobileGL {
}
bool MipmapStorage::IsDirty(Uint level) const {
#if MOBILEGL_BUILD_DISAGGREGATED
RefuseLegacyTextureArmFromApplyThread("IsStorageDirty");
#endif
MOBILEGL_ASSERT(level < m_isDirty.size(), "IsDirty: level out of range");
return m_isDirty[level];
}
void MipmapStorage::MarkDirtyRegion(Uint level, IntVec3 offset, IntVec3 size) {
#if MOBILEGL_BUILD_DISAGGREGATED
RefuseLegacyTextureArmFromApplyThread("MarkStorageDirtyRegion");
#endif
MOBILEGL_ASSERT(level < m_isDirty.size(), "MarkDirtyRegion: level out of range");
const IntVec3 levelSize = level < m_texelSizes.size() ? m_texelSizes[level] : IntVec3{0, 0, 0};
MipmapDirtyRegion incoming;
@@ -280,11 +359,17 @@ namespace MobileGL {
}
MipmapDirtyRegion MipmapStorage::GetDirtyRegion(Uint level) const {
#if MOBILEGL_BUILD_DISAGGREGATED
RefuseLegacyTextureArmFromApplyThread("GetStorageDirtyRegion");
#endif
if (level >= m_dirtyRegions.size()) return {};
return m_dirtyRegions[level];
}
SizeT MipmapStorage::GetDirtyRects(Uint level, MipmapDirtyRegion* outRects, SizeT maxRects) const {
#if MOBILEGL_BUILD_DISAGGREGATED
RefuseLegacyTextureArmFromApplyThread("GetStorageDirtyRects");
#endif
if (outRects == nullptr || level >= m_dirtyRects.size() || level >= m_dirtyRegions.size()) {
return 0;
}
@@ -38,6 +38,28 @@ namespace MobileGL {
}
};
#if MOBILEGL_BUILD_DISAGGREGATED
// P5c (gt, CONTRACT-P5C §6 layer 1): the NAMED EXEMPTION to the texture legacy-arm
// guard, the texture analogue of hd's MGPipeFrontendKeyedRegistryScope
// (MG_Impl/Pipe/SlotAllocator.h). Magma's texture sync (VkTextureManager::SyncTexture
// and the UploadDirtyMipLevels it drives) still reads and clears the CLIENT's mip
// shadow - the one texture family tx did not migrate (CONTRACT-P5C §2 names Espryt's
// sync reads and Magma's T5 writes; Magma's upload read path is absent from it), and
// inproc was green on it because the barrier and the shared address space held.
// Inside this scope the guard's surfaces stay legal - read-only-or-clean, barrier-
// held, and greppable as exactly this name; retiring the scope is P7's server-side
// Magma texture sync. Every OTHER apply-thread touch of a guarded surface is still
// Fatal{RoleViolation, "texture-legacy-arm"}.
class MGPipeTextureLegacyArmScope {
public:
MGPipeTextureLegacyArmScope();
~MGPipeTextureLegacyArmScope();
MGPipeTextureLegacyArmScope(const MGPipeTextureLegacyArmScope&) = delete;
MGPipeTextureLegacyArmScope& operator=(const MGPipeTextureLegacyArmScope&) = delete;
static Bool Active();
};
#endif
class MipmapStorage {
public:
SizeT GetLevelCount() const;
+152 -37
View File
@@ -197,11 +197,15 @@ TEST_F(FieldOwnershipTest, TheClassSizesPartitionTheFieldSet) {
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});
// The census's own arithmetic (scout-unmigrated-census section 2.1), updated by P5c rv
// (CONTRACT-P5C.md §5.3): rv moved the NINE value-class rows to RECORD-SUPPLIED through
// set_context_values / the amended set_vertex_attrib_defaults and the three texture
// shutters to APPLIER-DERIVED, so 22 of the 63 fields are served by NO pushed record -
// 15 BARRIER-PULLED (the object class: nine non-sticky rows plus six of the seven sticky
// forwards), four APPLIER-DERIVED and three FATAL - and 41 are.
EXPECT_EQ(kMGPipeRecordSuppliedFieldCount, SizeT{41});
EXPECT_EQ(kMGPipeApplierDerivedFieldCount + kMGPipeBarrierPulledFieldCount + kMGPipeFatalFieldCount,
SizeT{31});
SizeT{22});
}
TEST_F(FieldOwnershipTest, EveryBarrierPulledRowNamesTheRetiringPhase) {
@@ -217,36 +221,56 @@ TEST_F(FieldOwnershipTest, EveryBarrierPulledRowNamesTheRetiringPhase) {
}
// 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.
// kClear's 7, kDraw's 19 and kReadback's 12) - AS P5c rv LEFT THEM (CONTRACT-P5C.md §5.3):
// NINE moved to RECORD-SUPPLIED through set_context_values (the two texture-unit counters,
// the touched-count array, the five XFB values) plus GetCurrentVertexAttribute through the
// amended set_vertex_attrib_defaults payload, and the three texture shutters moved to
// APPLIER-DERIVED ("a shutter, not a value: the server answers from its own Serial"). What
// remains BARRIER-PULLED is EXACTLY the object class - nine non-sticky fields whose storage
// is a frontend heap reference no record can carry - plus 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::GetProgramForDraw,
MGPipeInputField::GetProgramForDispatch,
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";
}
// rv's exit line, pinned as a SET and not only as nine rows: the non-sticky
// BARRIER-PULLED list above is ALL the non-sticky debt - value-class membership is zero
// (CONTRACT-P5C.md §7 table 2) - and the only other BARRIER-PULLED rows are six of the
// seven sticky forwards (the seventh, InvalidateCompileEnv, is FATAL since P5c ev).
const MGPipeInputField pulledSticky[] = {
MGPipeInputField::GetBufferBindingPointCount,
MGPipeInputField::GetProgramObject,
MGPipeInputField::GetTextureObject,
MGPipeInputField::HasOpenTransformFeedbackSpan,
MGPipeInputField::ValidateProgramName,
MGPipeInputField::RecordError,
};
SizeT pulledCount = 0;
for (SizeT i = 0; i < kMGPipeInputFieldCount; ++i) {
const auto field = static_cast<MGPipeInputField>(i);
if (kMGPipeFieldOwnership[i] != MGPipeFieldOwnership::kBarrierPulled) continue;
++pulledCount;
Bool named = false;
for (const auto f : pulled) named = named || field == f;
for (const auto f : pulledSticky) named = named || field == f;
EXPECT_TRUE(named) << kMGPipeInputFieldNames[i]
<< " is BARRIER-PULLED and not in the pinned object-class list";
}
EXPECT_EQ(pulledCount, 15u) << "9 non-sticky object rows + 6 sticky forwards";
EXPECT_EQ(pulledCount, kMGPipeBarrierPulledFieldCount);
EXPECT_EQ(MGPipeFieldOwnershipOf(MGPipeInputField::GetPixelStoreParameters),
MGPipeFieldOwnership::kApplierDerived);
EXPECT_EQ(MGPipeFieldOwnershipOf(MGPipeInputField::GetPixelStoreParameters, 0u),
@@ -271,6 +295,36 @@ TEST_F(FieldOwnershipTest, TheReducedPathsUnmigratedFieldsAreAllAccountedFor) {
EXPECT_EQ(MGPipeFieldOwnershipOf(MGPipeInputField::GetProgramForDispatch),
MGPipeFieldOwnershipOf(MGPipeInputField::GetProgramForDraw))
<< "GetProgramForDispatch is GetProgramForDraw's twin and must share its class";
// AND THE NINE rv RETIRED, asserted in their NEW classes rather than deleted: a row that
// quietly fell back to BARRIER-PULLED is exactly what this list is for.
const MGPipeInputField suppliedByContextValues[] = {
MGPipeInputField::GetActiveTextureUnit,
MGPipeInputField::GetMaxTouchedTextureUnit,
MGPipeInputField::GetTouchedBufferBindingPointCount,
MGPipeInputField::IsTransformFeedbackActive,
MGPipeInputField::IsTransformFeedbackPaused,
MGPipeInputField::GetTransformFeedbackGeneration,
MGPipeInputField::GetBoundTransformFeedbackLifetimeId,
MGPipeInputField::GetTransformFeedbackCapturedVertices,
};
for (const auto field : suppliedByContextValues) {
EXPECT_EQ(MGPipeFieldOwnershipOf(field), MGPipeFieldOwnership::kRecordSupplied)
<< kMGPipeInputFieldNames[Index(field)] << " no longer rides set_context_values";
}
EXPECT_EQ(MGPipeFieldOwnershipOf(MGPipeInputField::GetCurrentVertexAttribute),
MGPipeFieldOwnership::kRecordSupplied)
<< "the amended set_vertex_attrib_defaults payload carries all three views";
const MGPipeInputField shutters[] = {
MGPipeInputField::GetSamplingResolutionGeneration,
MGPipeInputField::GetTextureBindGeneration,
MGPipeInputField::GetTextureContextId,
};
for (const auto field : shutters) {
EXPECT_EQ(MGPipeFieldOwnershipOf(field), MGPipeFieldOwnership::kApplierDerived)
<< kMGPipeInputFieldNames[Index(field)]
<< " is a shutter: the server answers from its own Serial";
}
}
TEST_F(FieldOwnershipTest, TheSevenStickyForwardsAgreeWithTheirFieldRows) {
@@ -395,19 +449,76 @@ TEST_F(FieldOwnershipTest, ARecordSuppliedFieldIsReadableAfterAServerStamp) {
(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.
// under the verb that actually reads it. And P5c rv's record-supplied rows join it there:
// GetActiveTextureUnit is exactly the read that used to count into `rsp`.
MGPipeServerStampVerbBoundary(MGPipeVerb::ReadPixels);
(void)gPipeInputs.GetPixelStoreParameters(false); // the half that has a carrier
(void)gPipeInputs.GetActiveTextureUnit(); // P5c rv: set_context_values carries it
(void)gPipeInputs.GetMaxTouchedTextureUnit();
EXPECT_EQ(MGPipeResidualPullCount(), Uint64{0});
// And a shutter answers the applier's own Serial under a server stamp (APPLIER-DERIVED),
// not the client's residual-fill copy: still zero pulls, and the answer MOVES when the
// applier's texture state does.
(void)gPipeInputs.GetTextureBindGeneration();
EXPECT_EQ(MGPipeResidualPullCount(), Uint64{0});
}
// P5c rv (CONTRACT-P5C.md §5.3): the residual-value record's applier write, read back through
// the accessors a backend uses, under the stamps that publish them - and the three texture
// shutters answering the applier's own serials rather than the client's fill. kReadback's
// class carries the two texture-unit counters, kDraw's the rest.
TEST_F(FieldOwnershipTest, SetContextValuesLandsInPipeInputsAndTheShuttersAnswerTheApplier) {
MGPContextValues values{};
values.ActiveTextureUnit = 5;
values.MaxTouchedTextureUnit = 23;
values.TouchedBufferBindingPointCount[static_cast<Uint32>(BufferTarget::Uniform)] = 7;
values.IsTransformFeedbackActive = 1;
values.IsTransformFeedbackPaused = 0;
values.TransformFeedbackGeneration = 0x1112131415161718ull;
values.BoundTransformFeedbackLifetimeId = 0x2122232425262728ull;
values.TransformFeedbackCapturedVertices = 0x3132333435363738ull;
MGPipeApplySetContextValues(values);
MGPipeServerStampVerbBoundary(MGPipeVerb::ReadPixels);
EXPECT_EQ(gPipeInputs.GetActiveTextureUnit(), 5);
EXPECT_EQ(gPipeInputs.GetMaxTouchedTextureUnit(), 23);
MGPipeServerStampVerbBoundary(MGPipeVerb::DrawArrays);
EXPECT_EQ(gPipeInputs.GetTouchedBufferBindingPointCount(BufferTarget::Uniform), SizeT{7});
EXPECT_EQ(gPipeInputs.GetTouchedBufferBindingPointCount(BufferTarget::Vertex), SizeT{0});
EXPECT_TRUE(gPipeInputs.IsTransformFeedbackActive());
EXPECT_FALSE(gPipeInputs.IsTransformFeedbackPaused());
EXPECT_EQ(gPipeInputs.GetTransformFeedbackGeneration(), 0x1112131415161718ull);
EXPECT_EQ(gPipeInputs.GetBoundTransformFeedbackLifetimeId(), 0x2122232425262728ull);
EXPECT_EQ(gPipeInputs.GetTransformFeedbackCapturedVertices(), 0x3132333435363738ull);
// Eight record-supplied reads and not one residual pull.
EXPECT_EQ(MGPipeResidualPullCount(), Uint64{0});
// The three shutters answer the applier's own serials under a stamped verb. They are
// SHUTTERS - the value matters only in that it MOVES when the server's texture state does
// and never walks backwards - so the pin is the identity with the applier's counters, not
// any particular number.
EXPECT_EQ(gPipeInputs.GetTextureBindGeneration(), MGPipeApplierTextureShutterSerial());
EXPECT_EQ(gPipeInputs.GetSamplingResolutionGeneration(), MGPipeApplierTextureShutterSerial());
EXPECT_EQ(gPipeInputs.GetTextureContextId(), MGPipeApplierContextSerial());
const Uint64 before = MGPipeApplierTextureShutterSerial();
MGPipeApplierNoteTextureStateMoved();
EXPECT_EQ(gPipeInputs.GetTextureBindGeneration(), before + 1)
<< "a texture-state apply moved the serial but the shutter did not answer with it";
EXPECT_EQ(MGPipeResidualPullCount(), Uint64{0});
}
TEST_F(FieldOwnershipTest, ABarrierPulledReadAfterAServerStampIsCountedNotFatal) {
MGPipeServerStampVerbBoundary(MGPipeVerb::ReadPixels);
// P5c rv: the exemplars are OBJECT-class now - the value rows this case used to read
// (GetActiveTextureUnit / GetTextureContextId / GetMaxTouchedTextureUnit) are
// RECORD-SUPPLIED / APPLIER-DERIVED since rv, and reading them here would count nothing.
// The three below are all of kDraw's class, all SharedPtr reads, and all safe on
// never-filled storage.
MGPipeServerStampVerbBoundary(MGPipeVerb::DrawArrays);
ASSERT_EQ(MGPipeResidualPullCount(), Uint64{0});
(void)gPipeInputs.GetActiveTextureUnit();
(void)gPipeInputs.GetBoundVertexArray();
EXPECT_EQ(MGPipeResidualPullCount(), Uint64{1});
(void)gPipeInputs.GetTextureContextId();
(void)gPipeInputs.GetMaxTouchedTextureUnit();
(void)gPipeInputs.GetProgramForDraw();
(void)gPipeInputs.GetTransformFeedbackProgram();
EXPECT_EQ(MGPipeResidualPullCount(), Uint64{3});
}
@@ -452,16 +563,18 @@ TEST_F(FieldOwnershipTest, TheAppliersOwnClearDisarmsTheStampWithoutTheClientsFi
}
// 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,
// GetProgramForDraw, 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.
// (P5c rv: the exemplar moved - GetActiveTextureUnit is RECORD-SUPPLIED since rv and would
// say nothing about the pulled set here.)
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
(void)gPipeInputs.GetProgramForDraw(); // 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)
EXPECT_NE(r.Log.find("Fatal{UnmigratedPipeInput, \"GetProgramForDraw@Clear\"}"), std::string::npos)
<< r.Log;
EXPECT_EQ(r.Log.find("BARRIER-PULLED"), std::string::npos) << r.Log;
#else
@@ -473,8 +586,8 @@ TEST_F(FieldOwnershipTest, ResidualPullsReachThePublishedPerFrameCounter) {
namespace PS = MG_Util::PipeStats;
PS::SetEnabledForTesting(true);
PS::ResetForTesting();
MGPipeServerStampVerbBoundary(MGPipeVerb::ReadPixels);
(void)gPipeInputs.GetActiveTextureUnit();
MGPipeServerStampVerbBoundary(MGPipeVerb::DrawArrays);
(void)gPipeInputs.GetBoundVertexArray();
EXPECT_EQ(PS::FrameCalls(PS::CallClass::ResidualPulls), Uint64{1});
EXPECT_NE(PS::FormatWindowLine().find("rsp="), std::string::npos) << PS::FormatWindowLine();
PS::ResetForTesting();
@@ -484,28 +597,30 @@ TEST_F(FieldOwnershipTest, ResidualPullsReachThePublishedPerFrameCounter) {
#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.
// decoration, and the set it counts is not empty. (P5c rv: the exemplar is object-class now -
// the value rows this case was written against ride set_context_values and answer
// RECORD-SUPPLIED.)
TEST_F(FieldOwnershipTest, StrictErrorsTurnsABarrierPulledReadIntoANamedAbort) {
const ChildResult r = RunInChild([] {
MG_Config::Ipc.StrictErrors = true;
MGPipeServerStampVerbBoundary(MGPipeVerb::ReadPixels);
(void)gPipeInputs.GetActiveTextureUnit();
MGPipeServerStampVerbBoundary(MGPipeVerb::DrawArrays);
(void)gPipeInputs.GetBoundVertexArray();
});
ASSERT_TRUE(DiedOfAbort(r)) << DescribeStatus(r) << "\n" << r.Log;
EXPECT_NE(r.Log.find("Fatal{UnmigratedPipeInput, \"GetActiveTextureUnit@ReadPixels\"}"),
EXPECT_NE(r.Log.find("Fatal{UnmigratedPipeInput, \"GetBoundVertexArray@DrawArrays\"}"),
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;
EXPECT_NE(r.Log.find("retires in P8]"), std::string::npos) << r.Log;
}
TEST_F(FieldOwnershipTest, TheSameReadWithoutStrictErrorsSurvivesAndIsCounted) {
const ChildResult r = RunInChild([] {
MGPipeServerStampVerbBoundary(MGPipeVerb::ReadPixels);
(void)gPipeInputs.GetActiveTextureUnit();
MGPipeServerStampVerbBoundary(MGPipeVerb::DrawArrays);
(void)gPipeInputs.GetBoundVertexArray();
if (MGPipeResidualPullCount() != 1) ::_exit(7);
});
ASSERT_TRUE(ExitedWith(r, 0)) << DescribeStatus(r) << "\n" << r.Log;
+62 -16
View File
@@ -125,11 +125,14 @@ TEST(PipeCatalogue, GeneratedTablesHoldTheWholeCatalogue) {
EXPECT_EQ(kMGPipeContextCallCount, kMGPipeCallCount - ClassCount<kScreen>());
// The per-class counts PipeCalls.def documents in its header.
EXPECT_EQ(ClassCount<kScreen>(), 11u);
// kScreen is 11 + P5c's applier_reset (MG_Remote/CONTRACT-P5C.md §5.1); kCtxObject is
// 9 + P5c's object_death (§5.2), the framebuffer family's first wire delete opcode.
// kCtxState is 17 + P5c rv's set_context_values (§5.3), the residual-value record.
EXPECT_EQ(ClassCount<kScreen>(), 12u);
EXPECT_EQ(ClassCount<kCtxQuery>(), 8u);
EXPECT_EQ(ClassCount<kCtxCso>(), 13u);
EXPECT_EQ(ClassCount<kCtxState>(), 17u);
EXPECT_EQ(ClassCount<kCtxObject>(), 9u);
EXPECT_EQ(ClassCount<kCtxState>(), 18u);
EXPECT_EQ(ClassCount<kCtxObject>(), 10u);
// 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.
@@ -139,11 +142,13 @@ TEST(PipeCatalogue, GeneratedTablesHoldTheWholeCatalogue) {
// 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,
// UNTIL P5 R-17 THAT WAS EVERY ROW, and this case said so. It is now EXACTLY THE 41 ROWS WITH
// NO MGPipeApply* ENTRY POINT (79 - the 38 that have one; the number was 34 at P5, 39 after
// P5b's five sink-only verbs, and rv's set_context_values grew BOTH sides of the difference):
// the other 38 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
// than the emptiness, because "38 installed" and "41 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
@@ -156,10 +161,12 @@ TEST(PipeCatalogue, UninstalledTablesAreAllNull) {
const void* const* context = reinterpret_cast<const void* const*>(&gMGPipeContext);
#if MOBILEGL_PIPE_PUSH
MGPipeInstallMonolithTables();
// The 34 rows with no MGPipeApply* entry point are still null, and null still means "this
// The 41 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.
// for one change. P5c's two control records are among them by design (CONTRACT-P5C.md §5:
// no MGPipeApply* entry point, no monolith producer - under a transport they reach
// WireVerbSink instead).
EXPECT_EQ(gMGPipeContext.SetShaderBuffers, nullptr);
EXPECT_EQ(gMGPipeContext.SetStreamOutputTargets, nullptr);
EXPECT_EQ(gMGPipeContext.DrawVbo, nullptr);
@@ -168,6 +175,8 @@ TEST(PipeCatalogue, UninstalledTablesAreAllNull) {
EXPECT_EQ(gMGPipeScreen.GetCaps, nullptr);
EXPECT_EQ(gMGPipeContext.QueryCreate, nullptr);
EXPECT_EQ(gMGPipeScreen.FenceCreate, nullptr);
EXPECT_EQ(gMGPipeScreen.ApplierReset, nullptr);
EXPECT_EQ(gMGPipeContext.ObjectDeath, 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.
@@ -202,8 +211,9 @@ TEST(PipeCatalogue, ExactlyTheRoutedRowsAreInstalledAndTheRestAreStillNull) {
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
// 34 + 4 = 38, and the split is the honest shape of R-17 rather than an implementation
// detail: 38 is the number of MGPipeApply* entry points PipeApply.h declares (37 at P5, and
// P5c rv's set_context_values - CONTRACT-P5C.md §5.3 - is the 38th), 34 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,
@@ -213,8 +223,8 @@ TEST(PipeCatalogue, ExactlyTheRoutedRowsAreInstalledAndTheRestAreStillNull) {
// 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);
EXPECT_EQ(installed, 34u) << "the routed rows and the applier's entry points disagree";
EXPECT_EQ(nulls, static_cast<SizeT>(kMGPipeCallCount) - 34u);
const void* const* escapes = reinterpret_cast<const void* const*>(&gMGPipeRouteEscapes);
SizeT escapesInstalled = 0;
for (SizeT i = 0; i < sizeof(MGPipeRouteEscapes) / sizeof(void*); ++i) {
@@ -222,7 +232,7 @@ TEST(PipeCatalogue, ExactlyTheRoutedRowsAreInstalledAndTheRestAreStillNull) {
}
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)
EXPECT_EQ(installed + escapesInstalled, 38u)
<< "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
@@ -235,6 +245,12 @@ TEST(PipeCatalogue, ExactlyTheRoutedRowsAreInstalledAndTheRestAreStillNull) {
EXPECT_EQ(gMGPipeContext.Present, nullptr);
EXPECT_EQ(gMGPipeContext.SetSwapInterval, nullptr);
EXPECT_EQ(gMGPipeScreen.GetCaps, nullptr);
// P5c's two control records (CONTRACT-P5C.md §5) take the same answer for a different
// reason: no MGPipeApply* exists for either and none may be installed - under a transport
// they cross to WireVerbSink, under monolith the GL thread's direct call and the death
// notice's mailbox are the producers, byte for byte as before (G1/G2).
EXPECT_EQ(gMGPipeScreen.ApplierReset, nullptr);
EXPECT_EQ(gMGPipeContext.ObjectDeath, nullptr);
#else
// A pull build compiles no applier and no routing, so the pre-migration statement is still
// the whole truth there.
@@ -557,7 +573,21 @@ TEST(PipeCatalogue, LateArrivalsAreAppendedWithoutRenumbering) {
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);
// P5c (MG_Remote/CONTRACT-P5C.md §5) appended the two control records AFTER P5b's five, by
// the same rule: opcodes 77..78, and nothing before them moved. applier_reset is a kScreen
// row (a make-current is a whole-server edge, exactly as FenceWaitServer is a screen call)
// and object_death a kCtxObject one; both carry no blob, no reply and no tail.
EXPECT_EQ(static_cast<Uint16>(MGPWireOp::ApplierReset), 77);
EXPECT_EQ(static_cast<Uint16>(MGPWireOp::ObjectDeath), 78);
// P5c rv (§5.3) appended the residual-value record AFTER the two control records, by the
// same rule: opcode 79, and nothing before it moved. It is an ordinary kCtxState set_* row
// - fixed POD, no blob, no tail, no reply - with an MGPipeApply* entry point, which the two
// control records deliberately do not have.
EXPECT_EQ(static_cast<Uint16>(MGPWireOp::SetContextValues), 79);
EXPECT_EQ(static_cast<Uint16>(MGPWireOp::kOpCount), 80);
EXPECT_EQ(MGPipeCallFlagsFor(MGPWireOp::ApplierReset), static_cast<Uint32>(kNone));
EXPECT_EQ(MGPipeCallFlagsFor(MGPWireOp::ObjectDeath), static_cast<Uint32>(kNone));
EXPECT_EQ(MGPipeCallFlagsFor(MGPWireOp::SetContextValues), static_cast<Uint32>(kNone));
// 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));
@@ -575,6 +605,19 @@ TEST(PipeCatalogue, LateArrivalsAreAppendedWithoutRenumbering) {
EXPECT_EQ(sizeof(MGPCopyFromFramebuffer), 48u);
EXPECT_EQ(sizeof(MGPCopyRegion), 72u);
EXPECT_EQ(sizeof(MGPDrawIndirect), 40u);
// The P5c payload, pinned like every other MGP_ASSERT_POD at runtime: one Uint64, no
// padding. object_death REUSES MGPHandleOnly (CONTRACT-P5C.md §1), so there is no second
// struct to pin - the 16 bytes are pinned above with the handle family.
EXPECT_EQ(sizeof(MGPApplierReset), 8u);
EXPECT_EQ(sizeof(MGPHandleOnly), 16u);
// rv's two (§5.3/§7.6): the residual-value POD - 2 + 15 Uint32s, 2 Uint8s and 2 pad bytes,
// then the three Uint64s - and the AMENDED attribute carrier, which grew 24 -> 56 to carry
// all three views verbatim (the frontend's cross-view conversion is the authoritative
// answer; the applier no longer reconverts).
EXPECT_EQ(sizeof(MGPContextValues), 96u);
EXPECT_EQ(sizeof(MGPContextValues::TouchedBufferBindingPointCount), 60u);
EXPECT_EQ(sizeof(MGPAttribValue), 56u);
EXPECT_EQ(sizeof(MGPVertexAttribDefaults), 8u);
// 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);
@@ -771,8 +814,11 @@ TEST(PipeCatalogue, FloatVectorsCompareBitwise) {
TEST(PipeCatalogue, SixValueStructsHaveFieldLists) {
// 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);
// each with its own field list, so the comparator sees every one of them: 77. P5c appended
// applier_reset's MGPApplierReset (CONTRACT-P5C.md §5.1) - object_death reuses
// MGPHandleOnly, which has had a list since P0 - and rv added set_context_values'
// MGPContextValues (§5.3): 79.
EXPECT_EQ(kMGPipeVerifiedPayloadCount, 79u);
static_assert(MGPipeHasFieldVerifier<RenderStateParameters>::value);
static_assert(MGPipeHasFieldVerifier<PixelStoreParameters>::value);
static_assert(MGPipeHasFieldVerifier<PerBufferBlendState>::value);
+15 -2
View File
@@ -1304,6 +1304,9 @@ namespace {
// set_vertex_attrib_defaults: a var-tail call, and the one consumer of the set-hash
// suppressor. The tail is in ascending location order and Count matches Mask, which
// is the contract the applier now enforces in every build rather than in a debug one.
// P5c rv: each entry carries all THREE views verbatim (CONTRACT-P5C.md §5.3) and the
// applier writes each view from its own array - a float-written attribute keeps the
// frontend's converted int/uint words, which is what the pre-rv shape could not do.
{
MG_Test::ScopedPipeVerb draw(MGPipeVerb::DrawArrays);
MGPVertexAttribDefaults hdr{};
@@ -1311,16 +1314,26 @@ namespace {
hdr.Count = 2;
MGPAttribValue tail[2]{};
tail[0].Location = 2;
tail[0].ValueClass = MG_State::GLState::kVertexAttribValueClassFloat;
const float first[4] = {1.5f, 2.5f, 3.5f, 4.5f};
std::memcpy(tail[0].Data, first, sizeof(first));
std::memcpy(tail[0].FloatView, first, sizeof(first));
const Int32 firstInt[4] = {1, 2, 3, 4}; // the frontend's conversion of 1.5f & co
std::memcpy(tail[0].IntView, firstInt, sizeof(firstInt));
tail[1].Location = 9;
tail[1].ValueClass = MG_State::GLState::kVertexAttribValueClassFloat;
const float second[4] = {-1.f, 0.f, 0.5f, 1.f};
std::memcpy(tail[1].Data, second, sizeof(second));
std::memcpy(tail[1].FloatView, second, sizeof(second));
const Int32 secondInt[4] = {-1, 0, 0, 1};
std::memcpy(tail[1].IntView, secondInt, sizeof(secondInt));
MGPipeApplySetVertexAttribDefaults(hdr, tail);
EXPECT_EQ(gPipeInputs.GetCurrentVertexAttribute(2).floatValue[0], 1.5f);
EXPECT_EQ(gPipeInputs.GetCurrentVertexAttribute(2).floatValue[3], 4.5f);
EXPECT_EQ(gPipeInputs.GetCurrentVertexAttribute(9).floatValue[2], 0.5f);
// ... and the CONVERTED views are the record's, not a memcpy of the float bits:
// 1.5f's bits are 0x3FC00000, and the frontend's int view of it is 1.
EXPECT_EQ(gPipeInputs.GetCurrentVertexAttribute(2).intValue[0], 1);
EXPECT_EQ(gPipeInputs.GetCurrentVertexAttribute(9).intValue[0], -1);
}
// delete_render_state: the record stops being live and a bound handle stops being
+20 -15
View File
@@ -892,30 +892,35 @@ namespace {
const MGPAttribValue value = PayloadFor(3);
EXPECT_EQ(value.Location, 3u);
EXPECT_EQ(value.ValueClass, MG_State::GLState::kVertexAttribValueClassFloat);
EXPECT_EQ(value.Data[0], Word(1.5f));
EXPECT_EQ(value.Data[1], Word(-2.5f));
// The defect this exists to stop: 1.5f's int VIEW is 1, and a carrier that sent the
// float bits while calling them class 0 for every attribute would be sending
// 0x3FC00000 where the frontend holds 1.
EXPECT_NE(value.Data[0], static_cast<Uint32>(Ctx().GetCurrentVertexAttribute(3).intValue[0]));
EXPECT_EQ(value.FloatView[0], Word(1.5f));
EXPECT_EQ(value.FloatView[1], Word(-2.5f));
// P5c rv: the record carries ALL THREE VIEWS VERBATIM (CONTRACT-P5C.md §5.3), so the
// frontend's converted int view travels too - 1.5f's int VIEW is 1, and the carrier
// that used to send the float bits into all three views would be sending 0x3FC00000
// where the frontend holds 1.
EXPECT_EQ(value.IntView[0],
static_cast<Uint32>(Ctx().GetCurrentVertexAttribute(3).intValue[0]));
EXPECT_NE(value.FloatView[0], value.IntView[0]);
}
TEST_F(TrackerAttribPayload, AnIntWriteCarriesTheIntWordsAndNamesItsClass) {
Ctx().SetCurrentVertexAttributeInt(5, Array<Int32, 4>{7, -9, 11, 13});
const MGPAttribValue value = PayloadFor(5);
EXPECT_EQ(value.ValueClass, MG_State::GLState::kVertexAttribValueClassInt);
EXPECT_EQ(static_cast<Int32>(value.Data[0]), 7);
EXPECT_EQ(static_cast<Int32>(value.Data[1]), -9);
// and NOT the float view the frontend converted it into
EXPECT_NE(value.Data[0], Word(7.0f));
EXPECT_EQ(static_cast<Int32>(value.IntView[0]), 7);
EXPECT_EQ(static_cast<Int32>(value.IntView[1]), -9);
// and the float view is the frontend's CONVERSION of it, not the int bits
EXPECT_EQ(value.FloatView[0], Word(7.0f));
EXPECT_NE(value.IntView[0], Word(7.0f));
}
TEST_F(TrackerAttribPayload, AUintWriteCarriesTheUintWordsAndNamesItsClass) {
Ctx().SetCurrentVertexAttributeUint(6, Array<Uint32, 4>{4000000000u, 2u, 3u, 4u});
const MGPAttribValue value = PayloadFor(6);
EXPECT_EQ(value.ValueClass, MG_State::GLState::kVertexAttribValueClassUint);
EXPECT_EQ(value.Data[0], 4000000000u);
EXPECT_NE(value.Data[0], Word(4000000000.0f));
EXPECT_EQ(value.UintView[0], 4000000000u);
EXPECT_EQ(value.FloatView[0], Word(4000000000.0f));
EXPECT_NE(value.UintView[0], Word(4000000000.0f));
}
// The class is PER ATTRIBUTE and it is the last writer's, not the context's - a payload
@@ -925,9 +930,9 @@ namespace {
Ctx().SetCurrentVertexAttributeInt(2, Array<Int32, 4>{1, 2, 3, 4});
EXPECT_EQ(PayloadFor(1).ValueClass, MG_State::GLState::kVertexAttribValueClassFloat);
EXPECT_EQ(PayloadFor(2).ValueClass, MG_State::GLState::kVertexAttribValueClassInt);
// Same numbers, different classes, so the same four words mean different things:
// 1.0f is 0x3F800000 and the integer 1 is 0x00000001.
EXPECT_NE(PayloadFor(1).Data[0], PayloadFor(2).Data[0]);
// Same numbers, different classes, so the WRITTEN views differ: 1.0f is 0x3F800000
// and the integer 1 is 0x00000001.
EXPECT_NE(PayloadFor(1).FloatView[0], PayloadFor(2).IntView[0]);
// An attribute nobody wrote answers Float, which is what the GL default (0,0,0,1) is.
EXPECT_EQ(PayloadFor(7).ValueClass, MG_State::GLState::kVertexAttribValueClassFloat);
// and a later write of the other class moves the class of THAT attribute only
+11 -8
View File
@@ -73,18 +73,21 @@ gtest_discover_tests(PipeWireCodecTest DISCOVERY_TIMEOUT 30 PROPERTIES LABELS un
# main() of its own. All three also reach MG_Pipe, MG_Backend and MG_State, so all three carry
# those include paths.
#
# RemoteClientTest the 71-slot emit table, the caps mirror, R-8's liveness gates, R-17's
# routing and ID-47/ID-49's readback rules (c1)
# ServerLoopTest the apply thread, the blocking control mailbox, the verb stamp and
# R-11's server-owned staging copy (v1)
# SessionHandshakeTest the two null-union guards driven THROUGH ServerSession::Accept and
# ClientSession::StartOverTransportPair, and the ABI fingerprint's
# sensitivity case driven from CapsAbiFingerprint() (s1, ID-46 6 and 7)
# RemoteClientTest the 71-slot emit table, the caps mirror, R-8's liveness gates, R-17's
# routing and ID-47/ID-49's readback rules (c1)
# ServerLoopTest the apply thread, the blocking control mailbox, the verb stamp and
# R-11's server-owned staging copy (v1)
# SessionHandshakeTest the two null-union guards driven THROUGH ServerSession::Accept and
# ClientSession::StartOverTransportPair, and the ABI fingerprint's
# sensitivity case driven from CapsAbiFingerprint() (s1, ID-46 6 and 7)
# StagedTextureStoreTest the texture half of R-11: tx's staged-texture store, its
# Fatal{StageSnapshotTooNarrow}, and the E-P5c #2 production wiring
# through the real resource op table (P5c tx)
#
# THIS FILE IS THE PHASE'S ONE RECURRING MERGE CONFLICT, and it is the same-point-append shape
# BRIEF §5's ownership table exists to prevent: three packages, three targets, one end-of-file.
# The loop is what stops there being a fourth: a package adding a suite adds a NAME.
foreach (wiretest IN ITEMS RemoteClientTest ServerLoopTest SessionHandshakeTest)
foreach (wiretest IN ITEMS RemoteClientTest ServerLoopTest SessionHandshakeTest StagedTextureStoreTest)
add_executable(${wiretest} ${wiretest}.cpp)
target_include_directories(${wiretest} PRIVATE
+315
View File
@@ -38,6 +38,14 @@
#include <Config.h>
#include <MG_Remote/Server/PipeApplier.h>
#include <MG_Backend/DirectGLES/BackendObject_DirectGLES.h>
// P5c rv (CONTRACT-P5C.md §5.3): set_context_values' round trip reads the applied record back
// out of gPipeInputs, which needs the stamp machinery (a RECORD-SUPPLIED read outside a
// server-stamped verb is the monolith answer's business, and this fixture has no client fill).
#include <MG_Backend/MGPipe/PipeInputs.h>
// P5c ct: object_death's round trip releases REAL Espryt twin-table entries, so the suite
// drives the same registries the sink dispatches to (Managers.h). A suite that substituted a
// mock here would pin the dispatch and nothing about the release (R-16).
#include <MG_Backend/DirectGLES/Managers.h>
#include <MG_Pipe/MGPipe.h>
#include <MG_Pipe/MGPipeRenderStateSpans.h>
#include <MG_Pipe/PipeApply.h>
@@ -268,6 +276,16 @@ namespace {
FramebufferCopies.push_back(copy);
return true;
}
// ---- P5c's rows (CONTRACT-P5C.md §5): the two control records, recorded the same
// way so a round trip asserts the arm and the record intact.
Bool OnApplierReset(const MGPApplierReset& reset) override {
ApplierResets.push_back(reset);
return true;
}
Bool OnObjectDeath(const MGPHandleOnly& death) override {
ObjectDeaths.push_back(death);
return true;
}
std::vector<MGPClear> Clears;
std::vector<MGPBlit> Blits;
std::vector<MGPPresent> Presents;
@@ -293,6 +311,8 @@ namespace {
std::vector<MGPPatchParameter> Patches;
std::vector<MGPMipPlan> MipPlans;
std::vector<MGPCopyFromFramebuffer> FramebufferCopies;
std::vector<MGPApplierReset> ApplierResets;
std::vector<MGPHandleOnly> ObjectDeaths;
};
Replies& Answers() { return m_replies; }
@@ -1243,6 +1263,119 @@ TEST_F(PipeWireCodecTest, BindStreamOutputReachesTheSink) {
EXPECT_EQ(wire.Sink().StreamOutputBinds[0].LifetimeId, 0x1234567890ull);
}
// =====================================================================================
// P5c ct (MG_Remote/CONTRACT-P5C.md §5): the two control records round-trip
// =====================================================================================
//
// Same shape as the P5b rows above: encode, pump, and assert the record reached the RIGHT
// sink method intact. What a serial ASSERT or a twin release does with the record is the
// SERVER sink's layer (SessionTest drives that); here the codec proves the bytes and the
// dispatch.
TEST_F(PipeWireCodecTest, ApplierResetReachesTheSinkWithItsSerial) {
Wire2 wire;
MGPApplierReset reset{};
reset.ContextSerial = 0; // 0 = the first make-current (CONTRACT-P5C.md §1)
ASSERT_NE(wire.Encoder().EncodeRecord(MGPWireOp::ApplierReset, &reset, sizeof(reset)),
kInvalidSeq);
bool applied = false;
ASSERT_TRUE(wire.PumpOne(&applied));
EXPECT_TRUE(applied);
ASSERT_EQ(wire.Sink().ApplierResets.size(), 1u);
EXPECT_EQ(wire.Sink().ApplierResets[0].ContextSerial, 0u);
// A second edge carries the next serial, and the two records arrive in order.
reset.ContextSerial = 1;
ASSERT_NE(wire.Encoder().EncodeRecord(MGPWireOp::ApplierReset, &reset, sizeof(reset)),
kInvalidSeq);
ASSERT_TRUE(wire.PumpOne(&applied));
EXPECT_TRUE(applied);
ASSERT_EQ(wire.Sink().ApplierResets.size(), 2u);
EXPECT_EQ(wire.Sink().ApplierResets[1].ContextSerial, 1u);
EXPECT_EQ(wire.Decoder().AppliedSeq(), 2u);
}
TEST_F(PipeWireCodecTest, ObjectDeathReachesTheSinkWithItsHandleAndKind) {
Wire2 wire;
// One record per kind the death switch handles (CONTRACT-P5C.md §1: one payload for all
// seven), because the kind is what the sink dispatches on and a row that widened it
// wrong would drop every death of that kind.
const MGPipeKind kinds[] = {
MGPipeKind::Texture, MGPipeKind::Framebuffer, MGPipeKind::Renderbuffer,
MGPipeKind::SamplerCso, MGPipeKind::ShaderCso, MGPipeKind::SamplerViewCso,
MGPipeKind::VertexElementsCso,
};
Uint32 slot = 40;
for (MGPipeKind kind : kinds) {
MGPHandleOnly death = HandleOnly(slot, kind);
ASSERT_NE(wire.Encoder().EncodeRecord(MGPWireOp::ObjectDeath, &death, sizeof(death)),
kInvalidSeq)
<< static_cast<Uint32>(kind);
++slot;
}
bool applied = false;
constexpr SizeT kKindCount = sizeof(kinds) / sizeof(kinds[0]);
for (SizeT i = 0; i < kKindCount; ++i) {
ASSERT_TRUE(wire.PumpOne(&applied)) << i;
EXPECT_TRUE(applied) << i;
}
ASSERT_EQ(wire.Sink().ObjectDeaths.size(), kKindCount);
slot = 40;
for (SizeT i = 0; i < kKindCount; ++i) {
EXPECT_EQ(wire.Sink().ObjectDeaths[i].Handle.Slot, slot) << i;
EXPECT_EQ(wire.Sink().ObjectDeaths[i].Handle.Gen, 1u) << i;
EXPECT_EQ(wire.Sink().ObjectDeaths[i].Kind, static_cast<Uint32>(kinds[i])) << i;
++slot;
}
EXPECT_EQ(wire.Decoder().AppliedSeq(), static_cast<Uint64>(kKindCount));
}
// =====================================================================================
// P5c rv (MG_Remote/CONTRACT-P5C.md §5.3): the residual-value record round-trips
// =====================================================================================
//
// Not a sink row: the decoder's arm runs the REAL applier (MGPipeApplySetContextValues), so
// the round trip is read back out of gPipeInputs - under a server stamp, because a
// RECORD-SUPPLIED read outside one is the pre-stamp behaviour this build still tests
// elsewhere, and the fields' own poison would otherwise (correctly) refuse the read.
TEST_F(PipeWireCodecTest, SetContextValuesRoundTripsIntoPipeInputs) {
Wire2 wire;
MGPContextValues values{};
values.ActiveTextureUnit = 9;
values.MaxTouchedTextureUnit = 41;
for (Uint32 t = 0; t < 15; ++t) values.TouchedBufferBindingPointCount[t] = 100 + t;
values.IsTransformFeedbackActive = 1;
values.IsTransformFeedbackPaused = 1;
values.TransformFeedbackGeneration = 0xA1A2A3A4A5A6A7A8ull;
values.BoundTransformFeedbackLifetimeId = 0xB1B2B3B4B5B6B7B8ull;
values.TransformFeedbackCapturedVertices = 0xC1C2C3C4C5C6C7C8ull;
ASSERT_NE(wire.Encoder().EncodeRecord(MGPWireOp::SetContextValues, &values, sizeof(values)),
kInvalidSeq);
bool applied = false;
ASSERT_TRUE(wire.PumpOne(&applied));
EXPECT_TRUE(applied);
EXPECT_EQ(wire.Decoder().AppliedSeq(), 1u);
// kReadback's class carries the two texture-unit counters, kDraw's the rest
// (FillPoints.def) - the stamp is what publishes a RECORD-SUPPLIED field for the read.
MGPipeServerStampVerbBoundary(MGPipeVerb::ReadPixels);
EXPECT_EQ(gPipeInputs.GetActiveTextureUnit(), 9);
EXPECT_EQ(gPipeInputs.GetMaxTouchedTextureUnit(), 41);
MGPipeServerStampVerbBoundary(MGPipeVerb::DrawArrays);
for (Uint32 t = 0; t < 15; ++t) {
EXPECT_EQ(gPipeInputs.GetTouchedBufferBindingPointCount(static_cast<BufferTarget>(t)),
SizeT{100 + t})
<< "target " << t;
}
EXPECT_TRUE(gPipeInputs.IsTransformFeedbackActive());
EXPECT_TRUE(gPipeInputs.IsTransformFeedbackPaused());
EXPECT_EQ(gPipeInputs.GetTransformFeedbackGeneration(), 0xA1A2A3A4A5A6A7A8ull);
EXPECT_EQ(gPipeInputs.GetBoundTransformFeedbackLifetimeId(), 0xB1B2B3B4B5B6B7B8ull);
EXPECT_EQ(gPipeInputs.GetTransformFeedbackCapturedVertices(), 0xC1C2C3C4C5C6C7C8ull);
MGPipeServerClearVerbBoundary();
}
// =====================================================================================
// P5b t2 (MG_Remote/CONTRACT-P5B.md §2 t2). c0b's cases above round-trip each row once; these
// pin the fields t2's EMITTERS actually fill and the one ordering property the span family has.
@@ -2893,3 +3026,185 @@ TEST(FenceWireRoundTrip, MissingConsumerDeclinesWithoutInventingASignaledAnswer)
EXPECT_EQ(wire.Answers().All[0].Status, ReplySink::kStatusDeclined);
EXPECT_TRUE(wire.Answers().All[0].Bytes.empty());
}
// =====================================================================================
// P5c ct (MG_Remote/CONTRACT-P5C.md §5): the two control records, through the REAL sink
// =====================================================================================
//
// The codec cases above pin the bytes and the dispatch with a recording sink; these pin what
// the SERVER's sink does with the record: the serial assert, the applier reset that actually
// runs, the twin release that actually retires the table entry, and the layer-2 guard that
// turns the reverted GL-thread direct call red.
TEST(ApplierResetWireRoundTrip, TheSerialSequenceIsAssertedAndTheServerResetRuns) {
Wire2 wire;
Server::ServerVerbSink sink;
wire.Decoder().SetVerbSink(&sink);
auto send = [&](Uint64 serial) {
const MGPApplierReset reset{serial};
EXPECT_NE(wire.Encoder().EncodeRecord(MGPWireOp::ApplierReset, &reset, sizeof(reset)),
kInvalidSeq);
bool applied = false;
EXPECT_TRUE(wire.PumpOne(&applied));
EXPECT_TRUE(applied);
};
// The reset RUNS - asserted on the applier's own state, not on the tally (R-16: a probe
// may not arm against a stub, and a tally a stub could also move is a stub's witness).
// BoundVertexElements is one of the fields MGPipeApplierReset clears (PipeApply.cpp).
MGPipeApplier().BoundVertexElements = MakeHandle(77);
send(0); // 0 = the first make-current (CONTRACT-P5C.md §1)
EXPECT_TRUE(MGPipeHandleIsNull(MGPipeApplier().BoundVertexElements));
EXPECT_EQ(sink.ApplierResets(), 1u);
EXPECT_EQ(sink.ExpectedApplierResetSerial(), 1u);
// The second edge carries the next serial and is accepted in order.
MGPipeApplier().BoundVertexElements = MakeHandle(78);
send(1);
EXPECT_TRUE(MGPipeHandleIsNull(MGPipeApplier().BoundVertexElements));
EXPECT_EQ(sink.ApplierResets(), 2u);
EXPECT_EQ(sink.ExpectedApplierResetSerial(), 2u);
}
TEST(ObjectDeathWireRoundTrip, TheTextureAndFramebufferTwinsReleaseByHandleAndNeverByAStaleGeneration) {
Wire2 wire;
Server::ServerVerbSink sink;
wire.Decoder().SetVerbSink(&sink);
namespace gles = MG_Backend::DirectGLES;
// The handle arm answers only when kMGPipeSubsystemEsprytSlots is set, and a unit binary
// never runs ConfigLoader: Features.PipePush is 0 here, not the shipping default
// (kMGPipeSubsystemsMigratedAtP4a). Set the bit the way SanityTest's pipe fixtures do;
// the arm verdict latches on first use and this case is the first use in its process.
const Uint64 savedPush = MG_Config::Features.PipePush;
MG_Config::Features.PipePush = savedPush | kMGPipeSubsystemEsprytSlots;
struct RestorePush {
Uint64 bits;
~RestorePush() { MG_Config::Features.PipePush = bits; }
} restore{savedPush};
// Texture AND Framebuffer - the two kinds R-16 names for the death-recycle path. The
// others share the one dispatch and the one table walk, so two kinds pin the shape: one
// whose death also crosses as resource_destroy (Texture: the idempotent second path),
// and the kind whose FIRST wire delete opcode object_death is (Framebuffer).
struct KindCase {
MGPipeKind kind;
Uint32 slot;
};
const KindCase cases[] = {{MGPipeKind::Texture, 901}, {MGPipeKind::Framebuffer, 902}};
for (const KindCase& one : cases) {
const auto getOrCreate = [&](MGPipeHandle h) -> void* {
if (one.kind == MGPipeKind::Texture) {
return gles::TextureImpl::g_backendTextureObjects.GetOrCreateByHandle(h);
}
return gles::FramebufferImpl::g_backendFramebufferObjects.GetOrCreateByHandle(h);
};
const auto liveGen = [&](Uint32 slot) -> Uint32 {
if (one.kind == MGPipeKind::Texture) {
return gles::TextureImpl::g_backendTextureObjects.LiveGenAt(slot);
}
return gles::FramebufferImpl::g_backendFramebufferObjects.LiveGenAt(slot);
};
ASSERT_NE(getOrCreate(MakeHandle(one.slot, 1)), nullptr)
<< "the Espryt handle arm did not go live with kMGPipeSubsystemEsprytSlots set; "
"the verdict latched elsewhere in this process";
ASSERT_EQ(liveGen(one.slot), 1u) << static_cast<Uint32>(one.kind);
// The death crosses and the twin retires: the slot's live generation goes back to 0.
const Uint64 deathsBefore = sink.ObjectDeaths();
const MGPHandleOnly death{MakeHandle(one.slot, 1), static_cast<Uint32>(one.kind), 0};
EXPECT_NE(wire.Encoder().EncodeRecord(MGPWireOp::ObjectDeath, &death, sizeof(death)),
kInvalidSeq);
bool applied = false;
EXPECT_TRUE(wire.PumpOne(&applied));
EXPECT_TRUE(applied);
EXPECT_EQ(liveGen(one.slot), 0u) << static_cast<Uint32>(one.kind);
EXPECT_EQ(sink.ObjectDeaths(), deathsBefore + 1u);
// THE ABA HALF (LiveGenAt's semantics): the slot is recycled forward to a NEW object
// at generation 2, and the dead object's handle - replayed, as a duplicated or
// reordered record would replay it - must not answer for the new object. The record
// is still APPLIED (idempotency is legal; a generation mismatch is a no-op), but the
// new twin survives it.
ASSERT_NE(getOrCreate(MakeHandle(one.slot, 2)), nullptr);
ASSERT_EQ(liveGen(one.slot), 2u);
EXPECT_NE(wire.Encoder().EncodeRecord(MGPWireOp::ObjectDeath, &death, sizeof(death)),
kInvalidSeq);
ASSERT_TRUE(wire.PumpOne(&applied));
EXPECT_TRUE(applied);
EXPECT_EQ(liveGen(one.slot), 2u)
<< "a stale handle released the recycled slot's new twin (kind "
<< static_cast<Uint32>(one.kind) << ")";
// And the new object's own death retires it, leaving the table as the case found it.
const MGPHandleOnly newDeath{MakeHandle(one.slot, 2), static_cast<Uint32>(one.kind), 0};
EXPECT_NE(wire.Encoder().EncodeRecord(MGPWireOp::ObjectDeath, &newDeath, sizeof(newDeath)),
kInvalidSeq);
ASSERT_TRUE(wire.PumpOne(&applied));
EXPECT_TRUE(applied);
EXPECT_EQ(liveGen(one.slot), 0u);
}
}
#if MGTEST_HAVE_FORK
// The three Fatal arms, driven through the encoder and the REAL sink in a forked child (the
// file's rule: never EXPECT_DEATH here - it re-runs the whole binary and re-enters the
// applier's globals).
TEST(CtWireFatals, ASerialTheSessionCannotProveIsProtocolCorruption) {
const ChildResult r = RunInChild([] {
Wire2 wire;
Server::ServerVerbSink sink;
wire.Decoder().SetVerbSink(&sink);
// The FIRST reset a session sees must carry serial 0 (one context, the count is the
// session's own); leading with 1 is a sequence the session cannot prove.
const MGPApplierReset reset{1};
(void)wire.Encoder().EncodeRecord(MGPWireOp::ApplierReset, &reset, sizeof(reset));
bool applied = false;
(void)wire.PumpOne(&applied);
});
ASSERT_TRUE(DiedOfAbort(r)) << DescribeStatus(r) << "\n" << r.Log;
EXPECT_NE(r.Log.find("Fatal{ProtocolCorruption, \"ApplierReset.ContextSerial\"}"),
std::string::npos)
<< r.Log;
}
TEST(CtWireFatals, ANullDeathHandleIsProtocolCorruption) {
const ChildResult r = RunInChild([] {
Wire2 wire;
Server::ServerVerbSink sink;
wire.Decoder().SetVerbSink(&sink);
// §1's zero ruling: a null handle means "the object never crossed", and the client
// emits NOTHING then - so a null handle ON the wire is corruption, not a no-op.
const MGPHandleOnly death{kMGPipeNullHandle, static_cast<Uint32>(MGPipeKind::Texture), 0};
(void)wire.Encoder().EncodeRecord(MGPWireOp::ObjectDeath, &death, sizeof(death));
bool applied = false;
(void)wire.PumpOne(&applied);
});
ASSERT_TRUE(DiedOfAbort(r)) << DescribeStatus(r) << "\n" << r.Log;
EXPECT_NE(r.Log.find("Fatal{ProtocolCorruption, \"ObjectDeath.Handle\"}"), std::string::npos)
<< r.Log;
}
// THE GUARD'S TWO NON-FATAL ARMS, as unit controls. The Fatal arm itself needs a LIVE client
// session (the guard deliberately exempts the configured-but-wireless window - §6 layer 2's
// documented bring-up exception), which a unit binary has no handshake for; that arm is the
// integration lane's CtWireScenario.TheDirectApplierResetCallOnTheGLThreadIsRoleViolation,
// and the manual revert of PipeFill's FreshlyPrimed arm is the red-once beside it. What is
// pinnable here is that neither monolith nor a wireless transport is stopped.
TEST(CtWireFatals, TheDirectApplierResetCallSurvivesMonolithAndAWirelessTransport) {
const ChildResult wireless = RunInChild([] {
// Transport=InProcess with NO client session - the ServerLoop fixture's shape. The
// direct call is the only reset that exists there, so it must NOT be stopped.
MG_Config::Transport = MG_Config::TransportMode::InProcess;
MGPipeApplierReset();
});
EXPECT_FALSE(DiedOfAbort(wireless)) << DescribeStatus(wireless) << "\n" << wireless.Log;
const ChildResult monolith = RunInChild([] { MGPipeApplierReset(); });
EXPECT_FALSE(DiedOfAbort(monolith)) << DescribeStatus(monolith) << "\n" << monolith.Log;
}
#endif // MGTEST_HAVE_FORK
+16 -13
View File
@@ -419,22 +419,26 @@ TEST(RemoteClientControls, BoundPackBufferOffsetReadRefusesByName) {
}
TEST(RemoteClientControls, ServerRoleRespecifyDoesNotEmitClientInitialBytes) {
// P5c (hd): the in-process server-role drive itself is now refused by name. The emit
// path's first move is the client allocator's Acquire for the buffer's handle, and with
// an active transport that entry is Fatal{RoleViolation, "MGPipeSlots"} from the apply
// thread (CONTRACT-P5C §3.1, rule E). "No client initial bytes" therefore holds the
// strong way - there is no client-emitter path for the server role to reach at all; ev's
// SEG_EVENT producers are what replaces the mechanism this case used to drive.
const auto child = RunInChild([] {
CapsPeer backend;
Srv::ServerSessionInstance().SetBackend(&backend);
StartControlSession();
MG_Config::Features.PipePush |= kMGPipeSubsystemResources;
const auto before = ClientWireRecordsEmitted();
if (Srv::ServerLoopInstance().RunOnApplyThread([](void*) {
Srv::ServerLoopInstance().RunOnApplyThread([](void*) {
MG_State::GLState::BufferObject buffer(701);
Uint8 data[64]{};
buffer.Respecify(sizeof(data), data);
return MOBILEGL_OK;
}, nullptr) != MOBILEGL_OK) ::_exit(92);
if (ClientWireRecordsEmitted() != before) ::_exit(93);
}, nullptr);
ClientSessionInstance().Stop();
});
ExpectChildSuccess(child);
ExpectNamedAbort(child, "Fatal{RoleViolation, \"MGPipeSlots\"}");
}
TEST(RemoteClientControls, HeaderOnlyDynamicStateCrossesWithoutBlobMissing) {
@@ -451,34 +455,33 @@ TEST(RemoteClientControls, HeaderOnlyDynamicStateCrossesWithoutBlobMissing) {
}
TEST(RemoteClientControls, ServerRoleFlushDoesNotRunTheClientSubDataFollowup) {
// P5c (hd): same refusal as the respecify sibling above - a server-role flush reaching the
// client emit path is stopped at the allocator entry before any follow-up question arises
// (Fatal{RoleViolation, "MGPipeSlots"}; ev's events replace the mechanism).
const auto child = RunInChild([] {
CapsPeer backend;
Srv::ServerSessionInstance().SetBackend(&backend);
StartControlSession();
MG_Config::Features.PipePush |= kMGPipeSubsystemResources;
const auto rc = Srv::ServerLoopInstance().RunOnApplyThread([](void*) {
static int subdata = 0, flushes = 0;
Srv::ServerLoopInstance().RunOnApplyThread([](void*) {
MGPipeResourceOps ops{};
ops.Create = [](MGPipeHandle, const MGPResourceDesc&) {};
ops.Respecify = [](MGPipeHandle, const MGPResourceDesc&, const void*) {};
ops.SubData = [](MGPipeHandle, const MGPSubData&, const void*) { ++subdata; };
ops.FlushRange = [](MGPipeHandle, const MGPFlushRange&, const void*) { ++flushes; };
ops.SubData = [](MGPipeHandle, const MGPSubData&, const void*) {};
ops.FlushRange = [](MGPipeHandle, const MGPFlushRange&, const void*) {};
ops.Destroy = [](MGPipeHandle) {};
MGPipeSetResourceOps(&ops);
{
MG_State::GLState::BufferObject buffer(702);
buffer.Resize(64);
subdata = flushes = 0;
MGPipeEmitResourceFlushRange(buffer, 16, 16, 0);
if (subdata != 0 || flushes != 1) ::_exit(95);
}
MGPipeSetResourceOps(nullptr);
return MOBILEGL_OK;
}, nullptr);
if (rc != MOBILEGL_OK) ::_exit(96);
ClientSessionInstance().Stop();
});
ExpectChildSuccess(child);
ExpectNamedAbort(child, "Fatal{RoleViolation, \"MGPipeSlots\"}");
}
// Uses the shipped EGL/GL frontend and real DirectGLES driver. Invoked explicitly by the
// package gate because a native driver is not a prerequisite of the unit lane.
+422 -3
View File
@@ -47,6 +47,7 @@
#include <MG_Impl/GLImpl/Buffer/GL_Buffer.h>
#include <MG_Pipe/PipeMutation.h>
#include <MG_Pipe/PipeApply.h>
#include <MG_Impl/Pipe/PipeFill.h>
#include <Init.h>
#include <MG_Impl/EGLImpl/EGLImpl.h>
#include <MG_Impl/GLImpl/Framebuffer/GL_Framebuffer.h>
@@ -1064,7 +1065,7 @@ TEST(PipeRouting, AnErrorStatusIsNotFoldedIntoAcceptedOrRefused) {
#endif // MGTEST_HAVE_FORK
// =====================================================================================
// B3 / codex 9: the CLIENT arm's 37 rows are observed, not just the monolith install
// B3 / codex 9: the CLIENT arm's 38 rows are observed, not just the monolith install
// =====================================================================================
namespace {
@@ -1127,6 +1128,11 @@ TEST(PipeRouting, TheInstalledClientArmIsWireAndNotMonolithAndEveryRoutedRowMove
C1F_MOVED(Context, SetVertexAttribDefaults);
C1F_MOVED(Context, SetPixelPackState);
C1F_MOVED(Context, SetPatchState);
// P5c rv (CONTRACT-P5C.md §5.3): the residual-value record is the 34th routed row - an
// ordinary set_* row with an MGPipeApply* entry point, so it rides BOTH tables like its
// siblings (its producer is transport-gated in PipeFill.cpp, which is a different gate's
// business).
C1F_MOVED(Context, SetContextValues);
C1F_MOVED(Context, SetResidualValueState);
C1F_MOVED(Context, SetTextureParams);
C1F_MOVED(Context, ResourceSubData);
@@ -1140,8 +1146,9 @@ TEST(PipeRouting, TheInstalledClientArmIsWireAndNotMonolithAndEveryRoutedRowMove
C1F_ESCAPE(CreateShaderState);
#undef C1F_ESCAPE
const SizeT movedContext = CountDifferingCells(gMGPipeContext, MGPipeMonolithContext());
EXPECT_EQ(movedScreen + movedContext, 33u)
<< "exactly the 33 generated routed rows must differ from the monolith adapters; "
EXPECT_EQ(movedScreen + movedContext, 34u)
<< "exactly the 34 generated routed rows must differ from the monolith adapters "
"(33 at P5, + set_context_values at P5c rv); "
<< movedScreen + movedContext
<< " did, so a row was left on the monolith adapter (it would run the applier on the GL "
"thread under split) or an unrouted row was overwritten";
@@ -1230,10 +1237,12 @@ struct F1Peer : Codec::WireVerbSink {
MGPClear clear{};
MGPCopyFromFramebuffer copy{};
MGPMipPlan mip{};
MGPBlit blit{};
unsigned calls = 0;
Bool OnClear(const MGPClear& v) override { clear = v; ++calls; return true; }
Bool OnCopyFramebufferToTexture(const MGPCopyFromFramebuffer& v) override { copy = v; ++calls; return true; }
Bool OnGenerateMipmap(const MGPMipPlan& v) override { mip = v; ++calls; return true; }
Bool OnBlit(const MGPBlit& v) override { blit = v; ++calls; return true; }
void Install() {
if (Srv::ServerLoopInstance().RunOnApplyThread([](void* self) {
auto& decoder = Srv::ServerSessionInstance().Applier().*PeerMember(DecoderTag{});
@@ -1514,6 +1523,416 @@ TEST(RemoteF1, UnboundNamedfiRefusesByName) {
}
#endif
// =====================================================================================
// P5c (hd, CONTRACT-P5C §3): the record's handles are the server's resolution. The sink
// publishes each verb's own handles into the applier's verb stash (§3.2), the named blit's
// client emitter no longer rebinds anything (§3.3), and the layer-1 guards refuse the
// client-only surfaces from the apply thread by name (§3.1, §3.7, §3.8).
// =====================================================================================
#if MGTEST_HAVE_FORK
#include <MG_Backend/DirectGLES/SlotTables.h>
#include <MG_Backend/DirectGLES/Utils.h>
#include <MG_Impl/Pipe/SlotAllocator.h>
#include <MG_State/GLState/BufferState/BufferObject.h>
TEST(RemoteF1, BlitNamedCarriesHandlesAndLeavesTheClientBindingsAlone) {
// Red once (executed, reverted): re-bind the named arguments in the client shadow before
// emitting (the deleted ScopedBlitBindings); the two binding-slot asserts fail.
const auto child = RunInChild([] {
StartControlSession();
F1Peer peer;
peer.Install();
MG_State::pGLContext = MakeUnique<MG_State::GLState::GLContext>();
auto boundRead = MakeShared<MG_State::GLState::FramebufferObject>(11);
auto boundDraw = MakeShared<MG_State::GLState::FramebufferObject>(12);
auto namedRead = MakeShared<MG_State::GLState::FramebufferObject>(13);
auto namedDraw = MakeShared<MG_State::GLState::FramebufferObject>(14);
MG_State::pGLContext->GetFramebufferBindingSlot(MobileGL::FramebufferTarget::Read).Bind(boundRead);
MG_State::pGLContext->GetFramebufferBindingSlot(MobileGL::FramebufferTarget::Draw).Bind(boundDraw);
RemoteEmitTable().GL.BlitNamedFramebuffer(namedRead, namedDraw, 0, 0, 8, 8, 0, 0, 8, 8,
GL_COLOR_BUFFER_BIT, GL_NEAREST);
const auto& r = peer.blit;
if (peer.calls != 1 || r.ReadFbo != MGPipeFramebufferEmitter::HandleFor(*namedRead) ||
r.DrawFbo != MGPipeFramebufferEmitter::HandleFor(*namedDraw)) ::_exit(101);
// The client's own bindings are untouched: the server resolves the named pair from the
// record, not from a staged binding override (T3).
if (MG_State::pGLContext->GetFramebufferBindingSlot(MobileGL::FramebufferTarget::Read)
.GetBoundObject()
.get() != boundRead.get()) ::_exit(102);
if (MG_State::pGLContext->GetFramebufferBindingSlot(MobileGL::FramebufferTarget::Draw)
.GetBoundObject()
.get() != boundDraw.get()) ::_exit(103);
ClientSessionInstance().Stop();
});
ExpectChildSuccess(child);
}
namespace {
Bool g_stubBlitCalled = false;
MGPipeHandle g_observedBlitRead = kMGPipeNullHandle;
MGPipeHandle g_observedBlitDraw = kMGPipeNullHandle;
void StubBlitFramebuffer(GLint, GLint, GLint, GLint, GLint, GLint, GLint, GLint, GLbitfield, GLenum) {
g_stubBlitCalled = true;
const auto& st = MG_Pipe::MGPipeApplier();
g_observedBlitRead = st.VerbBlitReadFbo;
g_observedBlitDraw = st.VerbBlitDrawFbo;
}
void StubBlitFramebufferConsuming(GLint x0, GLint y0, GLint x1, GLint y1, GLint dx0, GLint dy0,
GLint dx1, GLint dy1, GLbitfield mask, GLenum filter) {
StubBlitFramebuffer(x0, y0, x1, y1, dx0, dy0, dx1, dy1, mask, filter);
MG_Pipe::MGPipeApplier().VerbBlitNamedConsumed = true;
}
MGPipeHandle g_observedCopyDst = kMGPipeNullHandle;
void StubCopyTexImage2D(GLenum, GLint, GLenum, GLint, GLint, GLsizei, GLsizei, GLint) {
g_observedCopyDst = MG_Pipe::MGPipeApplier().VerbCopyTexDst;
}
MGPipeHandle g_observedMipRes = kMGPipeNullHandle;
void StubGenerateMipmap(GLenum) { g_observedMipRes = MG_Pipe::MGPipeApplier().VerbMipRes; }
MGPipeHandle g_observedIndirect = kMGPipeNullHandle;
MGPipeHandle g_observedParameter = kMGPipeNullHandle;
void StubMultiDrawArraysIndirectCount(GLenum, const void*, GLintptr, GLsizei, GLsizei) {
const auto& st = MG_Pipe::MGPipeApplier();
g_observedIndirect = st.VerbIndirectBuffer;
g_observedParameter = st.VerbIndirectParameterBuffer;
}
MGPipeHandle g_observedDispatchIndirect = kMGPipeNullHandle;
void StubDispatchComputeIndirect(GLintptr) {
g_observedDispatchIndirect = MG_Pipe::MGPipeApplier().VerbDispatchIndirectBuffer;
}
} // namespace
TEST(RemoteF1, NamedBlitStashesHandlesAndDeclinesWhenTheBackendHasNoNamedArm) {
// Red once (executed, reverted): do not write the verb stash; the observed handles are null.
const auto child = RunInChild([] {
MG_Config::Transport = MG_Config::TransportMode::InProcess;
CapsPeer backend;
backend.table.GL.BlitFramebuffer = &StubBlitFramebuffer;
Srv::ServerVerbSink sink;
sink.SetBackend(&backend);
MGPBlit r{};
r.ReadFbo = {41, 2};
r.DrawFbo = {42, 3};
r.Mask = GL_COLOR_BUFFER_BIT;
r.Filter = GL_NEAREST;
const Bool applied = sink.OnBlit(r);
if (applied) ::_exit(101); // a named pair the backend did not consume must decline
if (!g_stubBlitCalled) ::_exit(102);
// The backend saw the record's handles as the verb's own state (CONTRACT-P5C §3.2/§3.3).
if (g_observedBlitRead != r.ReadFbo || g_observedBlitDraw != r.DrawFbo) ::_exit(103);
::_exit(0);
});
ExpectChildSuccess(child);
}
TEST(RemoteF1, NamedBlitIsAppliedWhenTheBackendConsumesThePair) {
const auto child = RunInChild([] {
MG_Config::Transport = MG_Config::TransportMode::InProcess;
CapsPeer backend;
backend.table.GL.BlitFramebuffer = &StubBlitFramebufferConsuming;
Srv::ServerVerbSink sink;
sink.SetBackend(&backend);
MGPBlit r{};
r.ReadFbo = {41, 2};
r.DrawFbo = {42, 3};
r.Mask = GL_COLOR_BUFFER_BIT;
r.Filter = GL_NEAREST;
if (!sink.OnBlit(r)) ::_exit(101);
if (g_observedBlitRead != r.ReadFbo || g_observedBlitDraw != r.DrawFbo) ::_exit(102);
::_exit(0);
});
ExpectChildSuccess(child);
}
TEST(RemoteF1, BoundBlitCarriesNoHandlesAndIsAppliedAsBefore) {
const auto child = RunInChild([] {
MG_Config::Transport = MG_Config::TransportMode::InProcess;
CapsPeer backend;
backend.table.GL.BlitFramebuffer = &StubBlitFramebuffer;
Srv::ServerVerbSink sink;
sink.SetBackend(&backend);
MGPBlit r{};
r.Mask = GL_COLOR_BUFFER_BIT;
r.Filter = GL_NEAREST;
if (!sink.OnBlit(r)) ::_exit(101);
if (!MGPipeHandleIsNull(g_observedBlitRead) || !MGPipeHandleIsNull(g_observedBlitDraw))
::_exit(102);
::_exit(0);
});
ExpectChildSuccess(child);
}
TEST(RemoteF1, CopyFramebufferToTextureStashesTheDestinationHandle) {
// Red once (executed, reverted): do not write VerbCopyTexDst; the observed handle is null.
const auto child = RunInChild([] {
MG_Config::Transport = MG_Config::TransportMode::InProcess;
CapsPeer backend;
backend.table.GL.CopyTexImage2D = &StubCopyTexImage2D;
Srv::ServerVerbSink sink;
sink.SetBackend(&backend);
MGPCopyFromFramebuffer r{};
r.Dst = {51, 4};
r.Target = GL_TEXTURE_2D;
r.Level = 1;
r.InternalFormat = GL_RGBA8;
r.Width = 8;
r.Height = 8;
if (!sink.OnCopyFramebufferToTexture(r)) ::_exit(101);
if (g_observedCopyDst != r.Dst) ::_exit(102);
::_exit(0);
});
ExpectChildSuccess(child);
}
TEST(RemoteF1, GenerateMipmapStashesTheTextureHandle) {
// Red once (executed, reverted): do not write VerbMipRes; the observed handle is null.
const auto child = RunInChild([] {
MG_Config::Transport = MG_Config::TransportMode::InProcess;
CapsPeer backend;
backend.table.GL.GenerateMipmap = &StubGenerateMipmap;
Srv::ServerVerbSink sink;
sink.SetBackend(&backend);
MGPMipPlan r{};
r.Res = {52, 5};
r.Target = GL_TEXTURE_2D;
if (!sink.OnGenerateMipmap(r)) ::_exit(101);
if (g_observedMipRes != r.Res) ::_exit(102);
::_exit(0);
});
ExpectChildSuccess(child);
}
TEST(RemoteF1, AnIndirectDrawStashesTheCommandAndParameterBuffers) {
// Red once (executed, reverted): do not write the indirect stash; the observed handles are null.
const auto child = RunInChild([] {
MG_Config::Transport = MG_Config::TransportMode::InProcess;
CapsPeer backend;
backend.table.GL.MultiDrawArraysIndirectCount = &StubMultiDrawArraysIndirectCount;
Srv::ServerVerbSink sink;
sink.SetBackend(&backend);
MGPDrawInfo info{};
info.Mode = GL_TRIANGLES;
info.IndexSize = 0;
info.NumDraws = 0;
info.InstanceCount = 1;
MGPDrawIndirect indirect{};
indirect.Buffer = {61, 1};
indirect.ParameterBuffer = {62, 1};
indirect.Offset = 64;
indirect.DrawCount = 3;
indirect.Stride = 16;
if (!sink.OnDrawVbo(info, nullptr, nullptr, &indirect)) ::_exit(101);
if (g_observedIndirect != indirect.Buffer || g_observedParameter != indirect.ParameterBuffer)
::_exit(102);
::_exit(0);
});
ExpectChildSuccess(child);
}
TEST(RemoteF1, DispatchIndirectStashesTheCommandBuffer) {
// Red once (executed, reverted): do not write VerbDispatchIndirectBuffer; the observed
// handle is null.
const auto child = RunInChild([] {
MG_Config::Transport = MG_Config::TransportMode::InProcess;
CapsPeer backend;
backend.table.GL.DispatchComputeIndirect = &StubDispatchComputeIndirect;
Srv::ServerVerbSink sink;
sink.SetBackend(&backend);
MGPGridInfo grid{};
grid.IsIndirect = 1;
grid.IndirectBuffer = {63, 1};
grid.IndirectOffset = 128;
if (!sink.OnLaunchGrid(grid)) ::_exit(101);
if (g_observedDispatchIndirect != grid.IndirectBuffer) ::_exit(102);
::_exit(0);
});
ExpectChildSuccess(child);
}
// ---- the layer-1 guards (CONTRACT-P5C §6), each verified red once by its own Fatal ---------
TEST(RemoteGuards, AllocatorAcquireFromTheApplyThreadIsFatalByName) {
const auto child = RunInChild([] {
StartControlSession();
Srv::ServerLoopInstance().RunOnApplyThread([](void*) {
MGPipeSlots().Acquire(MGPipeKind::Texture, 424242);
return MOBILEGL_OK;
}, nullptr);
ClientSessionInstance().Stop();
});
ExpectNamedAbort(child, "Fatal{RoleViolation, \"MGPipeSlots\"}");
}
TEST(RemoteGuards, AllocatorFindByLifetimeIdFromTheApplyThreadIsFatalByName) {
const auto child = RunInChild([] {
StartControlSession();
Srv::ServerLoopInstance().RunOnApplyThread([](void*) {
MGPipeSlots().FindByLifetimeId(MGPipeKind::Texture, 424242);
return MOBILEGL_OK;
}, nullptr);
ClientSessionInstance().Stop();
});
ExpectNamedAbort(child, "Fatal{RoleViolation, \"MGPipeSlots\"}");
}
TEST(RemoteGuards, AllocatorFreeFromTheApplyThreadIsFatalByName) {
const auto child = RunInChild([] {
StartControlSession();
Srv::ServerLoopInstance().RunOnApplyThread([](void*) {
MGPipeSlots().Free(MGPipeKind::Texture, {7, 1});
return MOBILEGL_OK;
}, nullptr);
ClientSessionInstance().Stop();
});
ExpectNamedAbort(child, "Fatal{RoleViolation, \"MGPipeSlots\"}");
}
namespace {
struct FakeTwin {
int marker = 0;
};
using TestTextureTable =
MG_Backend::DirectGLES::BackendSlotTable<MG_State::GLState::TextureObject2D, FakeTwin,
MGPipeKind::Texture>;
} // namespace
TEST(RemoteGuards, SlotTableHandleOfFromTheApplyThreadIsFatalByName) {
const auto child = RunInChild([] {
StartControlSession();
Srv::ServerLoopInstance().RunOnApplyThread([](void*) {
MG_State::pGLContext = MakeUnique<MG_State::GLState::GLContext>();
TestTextureTable table;
MG_State::GLState::TextureObject2D tex(44);
table.HandleOf(&tex);
return MOBILEGL_OK;
}, nullptr);
ClientSessionInstance().Stop();
});
ExpectNamedAbort(child, "Fatal{RoleViolation, \"MGPipeSlots\"}");
}
TEST(RemoteGuards, SlotTableMintingGetOrCreateFromTheApplyThreadIsFatalByName) {
const auto child = RunInChild([] {
StartControlSession();
Srv::ServerLoopInstance().RunOnApplyThread([](void*) {
MG_State::pGLContext = MakeUnique<MG_State::GLState::GLContext>();
TestTextureTable table;
auto tex = MakeShared<MG_State::GLState::TextureObject2D>(45);
table.GetOrCreate(tex);
return MOBILEGL_OK;
}, nullptr);
ClientSessionInstance().Stop();
});
ExpectNamedAbort(child, "Fatal{RoleViolation, \"MGPipeSlots\"}");
}
// The four accessor drives share one shape: the BufferObject is constructed on the CLIENT
// thread (its own resource_create publication is a legal client-side emit), and only the
// accessor runs on the apply thread, where it must die at the accessor's own guard.
#define MGL_BUFFER_GUARD_TEST(Name, Id, Call) TEST(RemoteGuards, Name) { const auto child = RunInChild([] { StartControlSession(); MG_State::GLState::BufferObject buffer(Id); Srv::ServerLoopInstance().RunOnApplyThread([](void* self) { auto& buffer = *static_cast<MG_State::GLState::BufferObject*>(self); Call; return MOBILEGL_OK; }, &buffer); ClientSessionInstance().Stop(); }); ExpectNamedAbort(child, "Fatal{RoleViolation, \"buffer-legacy-arm\"}"); }
MGL_BUFFER_GUARD_TEST(BufferMappedDataFromTheApplyThreadIsFatalByName, 703, (void)buffer.MappedData())
MGL_BUFFER_GUARD_TEST(BufferIsMappedFromTheApplyThreadIsFatalByName, 704, (void)buffer.IsMapped())
MGL_BUFFER_GUARD_TEST(BufferChangeSerialFromTheApplyThreadIsFatalByName, 705, (void)buffer.GetChangeSerial())
MGL_BUFFER_GUARD_TEST(BufferSyncPersistentMappedRangeFromTheApplyThreadIsFatalByName, 706,
buffer.SyncPersistentMappedRange())
MGL_BUFFER_GUARD_TEST(BufferHasDefinedContentFromTheApplyThreadIsFatalByName, 707, (void)buffer.HasDefinedContent())
#undef MGL_BUFFER_GUARD_TEST
TEST(RemoteGuards, CapsMirrorFallbackWithNoServerBackendIsFatalByName) {
const auto child = RunInChild([] {
MG_Config::Transport = MG_Config::TransportMode::InProcess;
// No server backend exists in this process: the format-caps fallback to the client
// mirror is refused by name (CONTRACT-P5C §3.7).
(void)MG_Backend::DirectGLES::ActiveBackendFormatCaps();
});
ExpectNamedAbort(child, "Fatal{RoleViolation, \"caps-mirror\"}");
}
// P5c (gt, CONTRACT-P5C §6 layer 1): the TEXTURE family's object-surface list, in executable
// form - this block IS the pinned list §5.4(b) asks for (the buffer family's five are the
// MGL_BUFFER_GUARD_TEST block above). Every drive shares the buffer family's shape: the texture
// is constructed on the CLIENT thread (its resource_create mint and emission are legal
// client-side), and only the probed method runs on the apply thread, where the guard fires
// BEFORE any level precondition could - the method names below are exactly the ones the guard
// (MipmapStorage.cpp's RefuseLegacyTextureArmFromApplyThread) is hung on:
//
// AllocateStorage, TruncateMipmapLevels, UpdateMipmapSubData, MapMipmapData,
// MarkStorageDirty, MarkStorageDirtyRegion, IsStorageDirty, GetStorageDirtyRegion,
// GetStorageDirtyRects
//
// Deliberately NOT in the list: the shape reads (GetMipmapTexelSize / GetMipmapByteSize /
// GetMipmapLevelCount / GetUploadTargets / GetTarget / IsComplete), which the pinned
// BARRIER-PULLED object-class rows still answer through the unit-object pointer
// (FieldOwnershipTest's list, P3b/P4b/P7) - the per-draw binding walk reads them every draw.
#define MGL_TEXTURE_GUARD_TEST(Name, Id, Call) \
TEST(RemoteGuards, Name) { \
const auto child = RunInChild([] { \
StartControlSession(); \
MG_State::GLState::TextureObject2D texture(Id); \
Srv::ServerLoopInstance().RunOnApplyThread( \
[](void* self) { \
auto& texture = *static_cast<MG_State::GLState::TextureObject2D*>(self); \
Call; \
return MOBILEGL_OK; \
}, \
&texture); \
ClientSessionInstance().Stop(); \
}); \
ExpectNamedAbort(child, "Fatal{RoleViolation, \"texture-legacy-arm\"}"); \
}
MGL_TEXTURE_GUARD_TEST(TextureAllocateStorageFromTheApplyThreadIsFatalByName, 711,
texture.AllocateStorage(TextureUploadTarget::Texture2D, 0,
{{4, 4, 1}, 64}))
MGL_TEXTURE_GUARD_TEST(TextureTruncateMipmapLevelsFromTheApplyThreadIsFatalByName, 712,
texture.TruncateMipmapLevels(TextureUploadTarget::Texture2D, 1))
MGL_TEXTURE_GUARD_TEST(TextureUpdateMipmapSubDataFromTheApplyThreadIsFatalByName, 713,
texture.UpdateMipmapSubData(TextureUploadTarget::Texture2D, 0, {}))
MGL_TEXTURE_GUARD_TEST(TextureMapMipmapDataFromTheApplyThreadIsFatalByName, 714,
(void)texture.MapMipmapData(TextureUploadTarget::Texture2D, 0))
MGL_TEXTURE_GUARD_TEST(TextureMarkStorageDirtyFromTheApplyThreadIsFatalByName, 715,
texture.MarkStorageDirty(TextureUploadTarget::Texture2D, 0, true))
MGL_TEXTURE_GUARD_TEST(TextureMarkStorageDirtyRegionFromTheApplyThreadIsFatalByName, 716,
texture.MarkStorageDirtyRegion(TextureUploadTarget::Texture2D, 0,
{0, 0, 0}, {1, 1, 1}))
MGL_TEXTURE_GUARD_TEST(TextureIsStorageDirtyFromTheApplyThreadIsFatalByName, 717,
(void)texture.IsStorageDirty(TextureUploadTarget::Texture2D, 0))
MGL_TEXTURE_GUARD_TEST(TextureGetStorageDirtyRegionFromTheApplyThreadIsFatalByName, 718,
(void)texture.GetStorageDirtyRegion(TextureUploadTarget::Texture2D, 0))
MGL_TEXTURE_GUARD_TEST(TextureGetStorageDirtyRectsFromTheApplyThreadIsFatalByName, 719,
(void)texture.GetStorageDirtyRects(TextureUploadTarget::Texture2D, 0,
nullptr, 0))
#undef MGL_TEXTURE_GUARD_TEST
// P5c (gt, CONTRACT-P5C §6 layer 2 / audit A1): the client-side half of the gPipeInputs
// single-writer rule. The apply thread is NOT actually inside the applier in this case - the
// flag is raised by hand, which is the exact overlap window the check exists to refuse: a fill
// that ran while a real apply was in flight would race the applier's reads of gPipeInputs.
TEST(RemoteGuards, ClientPipeInputsFillWhileTheApplierOwnsItIsFatalByName) {
const auto child = RunInChild([] {
StartControlSession();
ClientSession::NoteApplyThreadEnteredApplier();
MGPipeValidateForVerb(MGPipeVerb::Clear);
ClientSession::NoteApplyThreadLeftApplier();
ClientSessionInstance().Stop();
});
ExpectNamedAbort(child, "Fatal{RoleViolation, \"gPipeInputs\"}");
}
// The same fill with the flag down is the legal shape - this is the control that keeps the
// check from being "abort unconditionally".
TEST(RemoteGuards, ClientPipeInputsFillWithTheApplierIdleIsAllowed) {
const auto child = RunInChild([] {
StartControlSession();
MGPipeValidateForVerb(MGPipeVerb::Clear);
MGPipeLeaveVerb();
ClientSessionInstance().Stop();
});
ExpectChildSuccess(child);
}
#endif
int main(int argc, char** argv) {
namespace fs = std::filesystem;
const fs::path path =
+43 -38
View File
@@ -1629,44 +1629,6 @@ TEST(StagedShadowProductionTest, ATwinSurvivingContextLossDropsItsFreedShadowBas
// shows it": B is the corruption, the upload is the draw, the mapped read-back is the picture. Red
// once by restoring the MappedData() fallback in liveHostBase(): the store then holds A, the
// client's bytes, and the R-2.5 audit could never reach a draw again.
TEST(ServerLoopEglTest, FrontendFramebufferDeathDeletesOnTheContextOwner) {
MG_Config::Features.PipePush |= MG_Pipe::kMGPipeSubsystemEsprytSlots;
EglServerFixture fixture;
MGL_EGL_BRING_UP_OR_BAIL(fixture);
ASSERT_TRUE(fixture.MakeCurrent());
namespace GLES = MG_Backend::DirectGLES;
static auto nativeDelete = GLES::g_GLESFuncs.glDeleteFramebuffers;
static std::atomic<Uint32> deleted{0};
static std::atomic<Bool> wrongThread{false};
nativeDelete = GLES::g_GLESFuncs.glDeleteFramebuffers;
deleted.store(0);
wrongThread.store(false);
auto framebuffer = MakeShared<MG_State::GLState::FramebufferObject>(901u);
GLuint driverId = 0;
ASSERT_EQ(OnApply([&] {
auto& twin = GLES::FramebufferImpl::g_backendFramebufferObjects.GetOrCreate(framebuffer);
twin = MakeShared<GLES::FramebufferImpl::BackendFramebufferObject>();
driverId = twin->GetBackendFramebufferId();
twin->Bind(FramebufferTarget::Draw);
GLES::g_GLESFuncs.glDeleteFramebuffers = +[](GLsizei count, const GLuint* names) {
if (!Server::ServerLoop::OnApplyThread()) wrongThread.store(true);
deleted.fetch_add(count);
nativeDelete(count, names);
};
}), MOBILEGL_OK);
ASSERT_NE(driverId, 0u);
framebuffer.reset(); // Frontend destructor runs on this client thread.
EXPECT_EQ(deleted.load(), 1u);
EXPECT_FALSE(wrongThread.load());
ASSERT_EQ(OnApply([&] {
GLES::g_GLESFuncs.glDeleteFramebuffers = nativeDelete;
GLint bound = -1;
GLES::g_GLESFuncs.glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &bound);
EXPECT_EQ(bound, 0) << "native deletion must unbind the framebuffer in the owner context";
}), MOBILEGL_OK);
fixture.TearDown();
}
TEST(StagedShadowProductionTest, TheEnsurePathUploadsTheServerShadowNotTheClientObjectsBytes) {
EglServerFixture fixture;
MGL_EGL_BRING_UP_OR_BAIL(fixture);
@@ -1820,6 +1782,49 @@ TEST(StagedShadowProductionTest, TheStreamingIdiomThroughAPoolReuseIsUploadedNot
"whole-store refusal must key on the descriptor's HasDefinedContent); the log says: "
<< appended;
}
namespace {
// The drive below, in a FORKED CHILD that brings the server up itself (the integration
// harness's pre-flight shape), so a Fatal on the apply thread ends the child and not the
// case. Exit 8 = the child's bring-up failed; exit 0 = the apply-thread twin mint ran,
// which is the refusal this case pins having been removed.
[[noreturn]] void RunFrontendFramebufferDeathOnApplyThreadAndExit() {
EglServerFixture fixture;
if (!fixture.BringUp().empty() || !fixture.MakeCurrent()) ::_exit(8);
namespace GLES = MG_Backend::DirectGLES;
auto framebuffer = MakeShared<MG_State::GLState::FramebufferObject>(901u);
(void)OnApply([&] {
auto& twin = GLES::FramebufferImpl::g_backendFramebufferObjects.GetOrCreate(framebuffer);
twin = MakeShared<GLES::FramebufferImpl::BackendFramebufferObject>();
});
framebuffer.reset();
::_exit(0);
}
} // namespace
// P5c (hd, CONTRACT-P5C §3.1 / §6 layer 1): this case's original drive - mint the framebuffer
// twin on the apply thread off the frontend object's lifetime id, then let the frontend death
// notice reach the in-process death switch there - is refused by name at the first step:
// the minting GetOrCreate(StatePtr) is monolith glue and the apply-thread call is
// Fatal{RoleViolation, "MGPipeSlots"}. The deletion-on-owner semantics it pinned return with
// ct's object_death record (the framebuffer family's first wire delete), whose sink releases
// the twin BY HANDLE. The name stays; the pin is now the refusal that stands until ct lands.
TEST(ServerLoopEglTest, FrontendFramebufferDeathDeletesOnTheContextOwner) {
MG_Config::Features.PipePush |= MG_Pipe::kMGPipeSubsystemEsprytSlots;
{
EglServerFixture probe;
MGL_EGL_BRING_UP_OR_BAIL(probe);
probe.TearDown();
}
const SizeT mark = ReadLog().size();
EXPECT_EXIT(RunFrontendFramebufferDeathOnApplyThreadAndExit(), ::testing::KilledBySignal(SIGABRT), ".*")
<< "the apply-thread mint of a frontend framebuffer's twin was not refused; exit 8 is the "
"child's own bring-up failing";
const std::string appended = ReadLogFrom(mark);
EXPECT_NE(appended.find("Fatal{RoleViolation, \"MGPipeSlots\"}"), std::string::npos)
<< "the abort was not the allocator guard's; the log says: " << appended;
}
#endif // !_WIN32
// =====================================================================================
+49
View File
@@ -822,6 +822,55 @@ TEST(SessionTest, TheEventRingCarriesTheThreeReverseCallbacks) {
EXPECT_EQ(session.eventIn.DroppedEvents(), 0u);
}
// P5c ev (CONTRACT-P5C §1, §4.5): the fourth event kind's unit round-trip, in the same shape
// as the three above - the producer writes the head plus the inline NUL-terminated message,
// the consumer reads every field back, the in-segment offset of the message stays inside
// SEG_EVENT, and a drained ring reports zero drops.
TEST(SessionTest, TheEventRingCarriesAGlError) {
SessionFixture session;
ASSERT_TRUE(session.Build(TestSizes()));
const char message[] = "DirectVulkan: vkCreateGraphicsPipelines failed";
const std::uint32_t messageBytes = static_cast<std::uint32_t>(sizeof(message)); // NUL included
ASSERT_LT(messageBytes, kEventGlErrorMaxMessageBytes);
{
void* slot = session.eventOut.Reserve(kEventGlError,
sizeof(EventGlErrorHead) + messageBytes);
ASSERT_NE(slot, nullptr);
EventGlErrorHead head{};
head.Code = 4; // ErrorCode::InvalidOperation, widened
head.MessageBytes = messageBytes;
std::memcpy(slot, &head, sizeof(head));
std::memcpy(static_cast<std::uint8_t*>(slot) + sizeof(head), message, messageBytes);
}
session.eventOut.PublishAndNotify(session.clientTransport->SelfDoorbell(),
session.Control().producerParked);
RingRecordView view{};
ASSERT_TRUE(session.eventIn.Pop(view));
EXPECT_EQ(view.kind, kEventGlError);
// The record's payload is rounded up to the ring's 8-byte alignment; the head's
// MessageBytes is the authoritative inline length.
ASSERT_GE(view.payloadSize, sizeof(EventGlErrorHead) + messageBytes);
EventGlErrorHead head{};
std::memcpy(&head, view.payload, sizeof(head));
EXPECT_EQ(head.Code, 4u);
EXPECT_EQ(head.MessageBytes, messageBytes);
const char* inlineMessage =
reinterpret_cast<const char*>(static_cast<const std::uint8_t*>(view.payload) + sizeof(head));
EXPECT_STREQ(inlineMessage, message);
// The offset a consumer would resolve the inline message at: inside SEG_EVENT and past
// its control page, never a host address.
const std::uint64_t offset = session.eventIn.OffsetInSegment(inlineMessage);
EXPECT_GE(offset, sizeof(RingControl));
EXPECT_LT(offset, session.clientSegments.AnnouncedSize(SessionSegmentSlot::Event));
EXPECT_FALSE(session.eventIn.Pop(view));
session.eventIn.Drained();
EXPECT_FALSE(session.eventIn.RingIsFull());
EXPECT_EQ(session.eventIn.DroppedEvents(), 0u);
}
TEST(SessionTest, AFullEventRingLatchesTheFlagRatherThanDecidingWhatToDoAboutIt) {
SessionFixture session;
ASSERT_TRUE(session.Build(TestSizes()));
@@ -0,0 +1,376 @@
// MobileGL - MobileGL/MG_Test/Wire/StagedTextureStoreTest.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
// Package tx's suite (P5c): the server's staged-texture shadow.
//
// THE SHAPE IS StagedShadowTest's (ServerLoopTest.cpp:606-760), for the R-16 reason stated
// there: every case must be able to go red for the reason it exists, and no other. The store
// unit cases build one store of each kind and assert the DIFFERENCE (copies is a constructor
// parameter, not a read of MG_Config::Transport); the production case drives the REAL
// resource op table - the same g_glesResourceOps RegisterBufferBackendOps installs -
// because a suite that only exercised StagedTextureStore in isolation would stay green with
// the ops-table registration deleted.
//
// E-P5c GATE #2 LIVES IN THE PRODUCTION CASE: reverting the adoption to P5's pointer-dropping
// (delete the copy inside Ops_H_TextureSubData, or the ops-table registration, or the
// ApplyTextureUpload hook call) turns it red - that is what makes "the server consumes the
// staged bytes" a checked fact rather than a design intention.
#include <Config.h>
#include <MG_Backend/DirectGLES/Managers.h>
#include <MG_Pipe/PipeApply.h>
#include <MG_Remote/Server/StagedTextureStore.h>
#include <MG_State/GLState/TextureState/TextureEnum.h>
#include <csignal>
#include <gtest/gtest.h>
#include <filesystem>
#include <fstream>
#include <string>
#include <vector>
#if defined(_WIN32)
#include <process.h>
#else
#include <unistd.h>
#endif
using namespace MobileGL;
namespace Server = MobileGL::MG_Remote::Server;
namespace {
std::string g_logPath;
std::string ReadLog() {
std::ifstream in(g_logPath, std::ios::binary);
if (!in) return {};
return std::string(std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>());
}
unsigned ProcessId() {
#if defined(_WIN32)
return static_cast<unsigned>(_getpid());
#else
return static_cast<unsigned>(::getpid());
#endif
}
constexpr Uint16 kTex2DTarget = static_cast<Uint16>(TextureUploadTarget::Texture2D);
MG_Pipe::MGPipeHandle TestHandle(Uint32 slot, Uint32 gen) {
MG_Pipe::MGPipeHandle handle{};
handle.Slot = slot;
handle.Gen = gen;
return handle;
}
} // namespace
// =====================================================================================
// The store, in isolation
// =====================================================================================
// THE PROPERTY MOBILEGL_IPC_AUDIT=1's 0xDD FILL EXISTS TO TEST, at unit scope: after the
// staged source bytes are overwritten - which is what the decoder does to a retired SEG_STAGE
// run - the server's copy still reads the original. The monolith store is the control: the
// SAME calls are no-ops on it, because the monolith sync answers from the client shadow.
TEST(StagedTextureStoreTest, TheSplitArmCopiesAndSurvivesTheSourceBeingPoisoned) {
Server::StagedTextureStore splitStore(/*copies=*/true);
Server::StagedTextureStore monolithStore(/*copies=*/false);
const Uint64 key = Server::StagedTextureStore::KeyForHandle(TestHandle(3, 1));
Vector<Uint8> staged(64, 0xAB);
const IntVec3 extent{4, 4, 1};
const Uint8* splitBase = splitStore.Adopt(key, kTex2DTarget, 0, extent, staged.data(), staged.size());
const Uint8* monolithBase =
monolithStore.Adopt(key, kTex2DTarget, 0, extent, staged.data(), staged.size());
ASSERT_NE(splitBase, nullptr);
EXPECT_EQ(monolithBase, nullptr)
<< "the monolith arm allocates nothing and answers nothing - the client shadow answers";
EXPECT_EQ(monolithStore.TrackedResources(), 0u);
EXPECT_FALSE(monolithStore.IsCovered(key, kTex2DTarget, 0));
EXPECT_NE(splitBase, staged.data()) << "the adoption returned the CLIENT's pointer - the "
"exact rule-C violation this store exists to fix";
// w1's retired-stage poison, by hand and at the right moment: the record has retired, so
// the staging run is dead.
std::fill(staged.begin(), staged.end(), Uint8{0xDD});
for (SizeT i = 0; i < 64; ++i) {
EXPECT_EQ(splitBase[i], 0xAB) << "byte " << i << " of the server's copy is the poison, "
<< "so the copy never happened";
}
}
// Defined-ness is tracked separately from bytes: a null-data definition (NoteLevelDefined
// with no Adopt) makes the level EXIST at the derived extent without covering any bytes, and
// an extent move redefines the coordinate system, so the old run goes with it while the
// level stays defined. A same-extent re-note keeps the run - the driver keeps the old texels
// for a same-shape redefinition too.
TEST(StagedTextureStoreTest, DefinednessIsTrackedAndAnExtentMoveDropsTheBytes) {
Server::StagedTextureStore store(/*copies=*/true);
const Uint64 key = Server::StagedTextureStore::KeyForHandle(TestHandle(4, 1));
EXPECT_EQ(store.LevelExtentOrUndefined(key, kTex2DTarget, 0), IntVec3(0, 0, 0))
<< "a level nothing defined must answer {0,0,0} - the sparse-chain skip reads exactly "
"this, and the frontend's GetMipmapTexelSize answers the same";
EXPECT_FALSE(store.IsLevelDefined(key, kTex2DTarget, 0));
store.NoteLevelDefined(key, kTex2DTarget, 0, IntVec3{4, 4, 1});
EXPECT_TRUE(store.IsLevelDefined(key, kTex2DTarget, 0));
EXPECT_FALSE(store.IsCovered(key, kTex2DTarget, 0)) << "defined-without-bytes covers nothing";
EXPECT_EQ(store.LevelExtentOrUndefined(key, kTex2DTarget, 0), IntVec3(4, 4, 1));
EXPECT_EQ(store.LevelByteSize(key, kTex2DTarget, 0), 0u);
Vector<Uint8> bytes(64, 0x11);
store.Adopt(key, kTex2DTarget, 0, IntVec3{4, 4, 1}, bytes.data(), bytes.size());
EXPECT_TRUE(store.IsCovered(key, kTex2DTarget, 0));
EXPECT_EQ(store.LevelByteSize(key, kTex2DTarget, 0), 64u);
store.NoteLevelDefined(key, kTex2DTarget, 0, IntVec3{4, 4, 1});
EXPECT_TRUE(store.IsCovered(key, kTex2DTarget, 0)) << "a same-extent re-definition keeps the run";
store.NoteLevelDefined(key, kTex2DTarget, 0, IntVec3{8, 8, 1});
EXPECT_TRUE(store.IsLevelDefined(key, kTex2DTarget, 0));
EXPECT_FALSE(store.IsCovered(key, kTex2DTarget, 0))
<< "an extent move replaced the coordinate system; the old run must not answer for it";
EXPECT_EQ(store.LevelExtentOrUndefined(key, kTex2DTarget, 0), IntVec3(8, 8, 1));
}
// Keys are independent, ResetLevels drops one resource's whole chain, Drop one key and
// DropAll every one - the three events the contract names (respecify, destroy, context death)
// each have their call site, and these are the answers those call sites rely on.
TEST(StagedTextureStoreTest, ResetDropAndDropAllForgetExactlyWhatTheyName) {
Server::StagedTextureStore store(/*copies=*/true);
const Uint64 a = Server::StagedTextureStore::KeyForHandle(TestHandle(5, 1));
const Uint64 b = Server::StagedTextureStore::KeyForHandle(TestHandle(6, 1));
Vector<Uint8> bytes(16, 0x22);
store.Adopt(a, kTex2DTarget, 0, IntVec3{4, 4, 1}, bytes.data(), bytes.size());
store.Adopt(a, kTex2DTarget, 1, IntVec3{2, 2, 1}, bytes.data(), bytes.size());
store.Adopt(b, kTex2DTarget, 0, IntVec3{4, 4, 1}, bytes.data(), bytes.size());
ASSERT_EQ(store.TrackedResources(), 2u);
ASSERT_EQ(store.TrackedLevelCount(a), 2u);
store.ResetLevels(a);
EXPECT_FALSE(store.HasShadow(a)) << "a whole-resource respecify forgets every level";
EXPECT_TRUE(store.IsCovered(b, kTex2DTarget, 0));
store.Adopt(a, kTex2DTarget, 0, IntVec3{4, 4, 1}, bytes.data(), bytes.size());
store.Drop(a);
EXPECT_EQ(store.TrackedResources(), 1u);
EXPECT_TRUE(store.IsCovered(b, kTex2DTarget, 0));
store.DropAll();
EXPECT_EQ(store.TrackedResources(), 0u);
EXPECT_FALSE(store.HasShadow(b));
}
// T5's dirty mark: a GPU-side generation dirties the SERVER's shadow, and the mark - not the
// client - answers "dirty region, level has no pending upload". It is settable and clearable
// per (uploadTarget, level), independent of bytes, and inert on a monolith store.
TEST(StagedTextureStoreTest, TheGpuDirtyMarkIsTheServersOwnDirtyAnswer) {
Server::StagedTextureStore store(/*copies=*/true);
Server::StagedTextureStore monolithStore(/*copies=*/false);
const Uint64 key = Server::StagedTextureStore::KeyForHandle(TestHandle(7, 1));
EXPECT_FALSE(store.IsLevelGpuDirty(key, kTex2DTarget, 2));
store.NoteLevelDefined(key, kTex2DTarget, 2, IntVec3{2, 2, 1});
store.MarkLevelGpuDirty(key, kTex2DTarget, 2, true);
EXPECT_TRUE(store.IsLevelGpuDirty(key, kTex2DTarget, 2));
EXPECT_FALSE(store.IsLevelGpuDirty(key, kTex2DTarget, 3)) << "the mark is per level";
EXPECT_FALSE(store.IsCovered(key, kTex2DTarget, 2))
<< "a generated level holds no bytes; a texel read of it is the Fatal case";
store.MarkLevelGpuDirty(key, kTex2DTarget, 2, false);
EXPECT_FALSE(store.IsLevelGpuDirty(key, kTex2DTarget, 2));
monolithStore.MarkLevelGpuDirty(key, kTex2DTarget, 2, true);
EXPECT_FALSE(monolithStore.IsLevelGpuDirty(key, kTex2DTarget, 2));
EXPECT_EQ(monolithStore.TrackedResources(), 0u);
}
// The two key namespaces share one map, so their disjointness is a property to pin, not to
// assume: handle keys carry the top bit, twin addresses (user-space, aligned) never do.
TEST(StagedTextureStoreTest, HandleKeysAndTwinAddressKeysCannotCollide) {
const MG_Pipe::MGPipeHandle handle = TestHandle(7, 1);
const Uint64 handleKey = Server::StagedTextureStore::KeyForHandle(handle);
int twin = 0;
const Uint64 twinKey = Server::StagedTextureStore::KeyForTwinAddress(&twin);
EXPECT_NE(handleKey, twinKey);
EXPECT_NE(handleKey, Server::StagedTextureStore::KeyForHandle(TestHandle(7, 2)))
<< "a recycled slot's new generation must key a different entry";
}
// §1's derivation: max(1, base >> level) per SHRINKING axis, with an array texture's layer
// count fixed. This is the mip chain's definition, so the server and the client compute the
// same number - and the layer axes are exactly where a naive shift would diverge.
TEST(StagedTextureStoreTest, TheMipExtentDerivationKeepsArrayLayersFixed) {
EXPECT_EQ(Server::StagedTextureMipExtent(static_cast<Uint8>(MG_Pipe::MGPipeResourceTarget::Tex2D), 8, 4, 1, 2),
IntVec3(2, 1, 1));
EXPECT_EQ(Server::StagedTextureMipExtent(static_cast<Uint8>(MG_Pipe::MGPipeResourceTarget::Tex3D), 8, 8, 8, 3),
IntVec3(1, 1, 1));
EXPECT_EQ(
Server::StagedTextureMipExtent(static_cast<Uint8>(MG_Pipe::MGPipeResourceTarget::Tex2DArray), 8, 8, 6, 2),
IntVec3(2, 2, 6)) << "the layer count is not a dimension of the image";
EXPECT_EQ(
Server::StagedTextureMipExtent(static_cast<Uint8>(MG_Pipe::MGPipeResourceTarget::Tex1DArray), 16, 4, 1, 3),
IntVec3(2, 4, 1)) << "a 1D array's HEIGHT is the layer count";
EXPECT_EQ(Server::StagedTextureMipExtent(static_cast<Uint8>(MG_Pipe::MGPipeResourceTarget::TexCube), 7, 7, 1, 3),
IntVec3(1, 1, 1)) << "shrinking clamps at 1, never 0";
}
// The Fatal, and it asserts ITS OWN failure string rather than "the process died" -
// ServerLoopTest.cpp:702-704's reason: a death test that only checks for a crash goes green
// on any other abort in the same body. ONE death per case: the forked children of two
// EXPECT_EXITs would share this process's log file, and the second child's truncated open
// would erase the first's line.
#if !defined(_WIN32)
TEST(StagedTextureStoreTest, ATexelReadOutsideTheStagedCoverageIsFatalByName) {
Server::StagedTextureStore store(/*copies=*/true);
const Uint64 key = Server::StagedTextureStore::KeyForHandle(TestHandle(8, 1));
Vector<Uint8> bytes(16, 0x33);
store.Adopt(key, kTex2DTarget, 0, IntVec3{4, 4, 1}, bytes.data(), bytes.size());
// In coverage: no Fatal, asserted first so the death below cannot be a function that
// aborts on everything.
ASSERT_NE(store.RequireLevelBytes(key, kTex2DTarget, 0, "unit"), nullptr);
// The death MODE and the diagnostic, both pinned: KilledBySignal(SIGABRT) refuses a
// SIGSEGV, and the log grep names the exact wording. The log flush is pinned the way
// ServerLoopTest's is: Log.cpp's WriteToFile fflushes after every write and MGLOG_F logs
// before abort(), so the line is on disk in the forked child before it dies.
EXPECT_EXIT(store.RequireLevelBytes(key, kTex2DTarget, 5, "unit_undefined_level"),
::testing::KilledBySignal(SIGABRT), ".*");
const std::string log = ReadLog();
EXPECT_NE(log.find("Fatal{StageSnapshotTooNarrow, \"unit_undefined_level\"}"), std::string::npos)
<< "the abort happened but not for this rule's reason; the log says: " << log;
}
TEST(StagedTextureStoreTest, AGpuGeneratedLevelHasNoBytesAndItsTexelReadIsFatalByName) {
Server::StagedTextureStore store(/*copies=*/true);
const Uint64 key = Server::StagedTextureStore::KeyForHandle(TestHandle(9, 1));
// Defined-without-bytes (T5's GPU-generated level): the level EXISTS, and a texel read of
// it is the same named refusal, because no byte answer exists on this side.
store.NoteLevelDefined(key, kTex2DTarget, 1, IntVec3{2, 2, 1});
ASSERT_TRUE(store.IsLevelDefined(key, kTex2DTarget, 1));
ASSERT_FALSE(store.IsCovered(key, kTex2DTarget, 1));
EXPECT_EXIT(store.RequireLevelBytes(key, kTex2DTarget, 1, "unit_gpu_level"),
::testing::KilledBySignal(SIGABRT), ".*");
const std::string log = ReadLog();
EXPECT_NE(log.find("Fatal{StageSnapshotTooNarrow, \"unit_gpu_level\"}"), std::string::npos)
<< "the abort happened but not for this rule's reason; the log says: " << log;
}
#endif
// =====================================================================================
// The production wiring - E-P5c gate #2 at unit scope
// =====================================================================================
// THE GATE. The REAL resource op table (RegisterBufferBackendOps installs g_glesResourceOps,
// the exact table the apply path dispatches through), a REAL applier record, and the REAL
// TextureSubData hook ApplyTextureUpload calls - then w1's poison. Reverting ANY link of the
// adoption - the ops-table registration, the hook call in PipeApply.cpp, or the copy inside
// Ops_H_TextureSubData (i.e. going back to P5's pointer-dropping) - turns this red, which is
// the R-16 red-once for "the server consumes the staged bytes" (E-P5c #2).
TEST(StagedTextureProductionTest, TextureSubDataThroughTheRealOpsTableCopiesAndSurvivesTheSourcePoison) {
// MG_Config::Transport is InProcess (main), so ServerStagedTexture() latches its copying
// arm on - the same latch ServerLoopTest's R-11 production case relies on.
MG_Backend::DirectGLES::BufferImpl::RegisterBufferBackendOps();
const MG_Pipe::MGPipeResourceOps* ops = MG_Pipe::MGPipeGetResourceOps();
ASSERT_NE(ops, nullptr) << "RegisterBufferBackendOps did not install the resource op table";
ASSERT_NE(ops->TextureSubData, nullptr)
<< "the texture half of resource_subdata has no adoption hook - the staged bytes are "
"dropped at apply time and the sync re-reads the client";
// A real applier record: the hook derives the level's extent from the record's
// descriptor, so the record must exist the way resource_create makes it.
const MG_Pipe::MGPipeHandle res = TestHandle(41, 1);
MG_Pipe::MGPResourceDesc desc{};
desc.Resource = res;
desc.Target = static_cast<Uint8>(MG_Pipe::MGPipeResourceTarget::Tex2D);
desc.Width = 4;
desc.Height = 4;
desc.Depth = 1;
desc.Levels = 1;
ASSERT_TRUE(MG_Pipe::MGPipeApplyResourceCreate(desc));
Vector<Uint8> src(64, 0xAB); // 4x4 texels, 4 bytes each
MG_Pipe::MGPSubData rec{};
rec.Res = res;
rec.Target = MG_Pipe::MGPipePackSubDataTarget(
static_cast<Uint32>(MG_Pipe::MGPipeResourceTarget::Tex2D),
static_cast<Uint32>(TextureUploadTarget::Texture2D));
rec.Level = 0;
rec.UnionBox = {0, 0, 0, 4, 4, 1};
rec.RegionCount = 0;
// Under split the codec declares the run's length: "the bytes this record declares ARE
// the level shadow" (TextureEmit.h:1285). The adoption reads exactly this field.
rec.Blob.Size = src.size();
// THE PRODUCTION CALL. Not StagedTextureStore::Adopt directly - the whole point of the
// gate is that the OPS TABLE carries the bytes into the store.
ops->TextureSubData(res, rec, src.data(), nullptr);
auto& store = Server::ServerStagedTexture();
const Uint64 key = Server::StagedTextureStore::KeyForHandle(res);
ASSERT_TRUE(store.IsCovered(key, kTex2DTarget, 0))
<< "the hook ran but nothing was adopted - the sync will Fatal or re-read the client";
EXPECT_EQ(store.LevelExtentOrUndefined(key, kTex2DTarget, 0), IntVec3(4, 4, 1));
EXPECT_EQ(store.LevelByteSize(key, kTex2DTarget, 0), src.size());
const Uint8* base = store.RequireLevelBytes(key, kTex2DTarget, 0, "unit_production");
ASSERT_NE(base, nullptr);
EXPECT_NE(base, static_cast<const Uint8*>(src.data()))
<< "the sync's texel base points into the CLIENT's staging run - the pointer-dropping "
"shape P5 had; restoring it turns this red, and that is the gate";
// w1's retired-stage poison, by hand and at the right moment: the record has retired, so
// the staging run is dead. A server that copied still reads the original bytes.
std::fill(src.begin(), src.end(), Uint8{0xDD});
for (SizeT i = 0; i < 64; ++i) {
ASSERT_EQ(base[i], 0xAB) << "byte " << i << " of the sync's texel source is the poison, "
<< "so the adoption never happened";
}
// And the death drops the key, through the same ops table the applier dispatches.
MG_Pipe::MGPHandleOnly death{};
death.Handle = res;
death.Kind = static_cast<Uint32>(MG_Pipe::MGPipeKind::Texture);
MG_Pipe::MGPipeApplyResourceDestroy(death);
EXPECT_FALSE(store.HasShadow(key))
<< "a destroyed texture's staged levels must not answer for the slot's next owner";
}
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*. The name carries this process's pid, because
// gtest_discover_tests runs every case as its own process, in parallel under ctest -j.
namespace fs = std::filesystem;
const fs::path path =
fs::temp_directory_path() / ("mobilegl-stagedtexture-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
// THIS PROCESS IS A SPLIT ONE - ServerLoopTest's main() ruling, and it matters twice here:
// ServerStagedTexture() latches its copying arm off MG_Config::Transport at first use,
// and a suite that left it at Monolith would be testing the monolith answers.
MG_Config::Transport = MG_Config::TransportMode::InProcess;
::testing::InitGoogleTest(&argc, argv);
const int rc = RUN_ALL_TESTS();
fs::remove(path, ec);
return rc;
}
+5 -6
View File
@@ -58,12 +58,11 @@ def cases():
[SUITE+'ReadPixelsPutsTheTightExtentOnTheWire'], 'RemoteClientTest'),
('M4-escape-errors-deleted', WIRE, escape_error,
[SUITE+'ResourceRespecifyErrorIsNotADecline', SUITE+'MapPersistentErrorIsNotADecline'], 'RemoteClientTest'),
('M5-server-role-guards-deleted', FILL,
replace('!MG_Remote::Client::RunsAsTheServerRole() && ', '', 2),
[SUITE+'ServerRoleRespecifyDoesNotEmitClientInitialBytes'], 'RemoteClientTest'),
('M5-server-flush-guard-deleted', FILL,
replace('!MG_Remote::Client::RunsAsTheServerRole() && size != 0', 'size != 0'),
[SUITE+'ServerRoleFlushDoesNotRunTheClientSubDataFollowup'], 'RemoteClientTest'),
('M5-allocator-guards-deleted', 'MobileGL/MG_Impl/Pipe/SlotAllocator.cpp',
lambda src: replace('MGPipeRefuseAllocatorFromApplyThread("FindByLifetimeId");', '')(
replace('MGPipeRefuseAllocatorFromApplyThread("Acquire");', '')(src)),
[SUITE+'ServerRoleRespecifyDoesNotEmitClientInitialBytes',
SUITE+'ServerRoleFlushDoesNotRunTheClientSubDataFollowup'], 'RemoteClientTest'),
('M8-real-pack-binding', EMIT,
replace('if (MG_State::pGLContext != nullptr &&', 'if (false && MG_State::pGLContext != nullptr &&'),
[SUITE+'BoundPackBufferOffsetReadRefusesByName'], 'RemoteClientTest'),
+5 -3
View File
@@ -1,6 +1,6 @@
# MGPipe 设计与架构
> 本文只写**已决定**的设计,每条决定附一行理由。落地状态:P0–P5b 已落地(代码头 `82683d4a`);标 **P6+** 的是后续形状,阶段号见 `ROADMAP.md`;实测数字见 `MEASUREMENTS.md`;P5 / P5b 的 wire 契约原文在 `MobileGL/MG_Remote/CONTRACT-P5.md`、`CONTRACT-P5B.md`。
> 本文只写**已决定**的设计,每条决定附一行理由。落地状态:P0–P5c 已落地(代码头 `b88e8487`);标 **P6+** 的是后续形状,阶段号见 `ROADMAP.md`;实测数字见 `MEASUREMENTS.md`;P5 / P5b / P5c 的 wire 契约原文在 `MobileGL/MG_Remote/CONTRACT-P5.md`、`CONTRACT-P5B.md`、`CONTRACT-P5C.md`。
## 1. 边界
@@ -563,11 +563,13 @@ client 表(`Client/EmitTables.cpp`)把后端函数表的 71 个槽分成三
- **具名 blit**:`BlitNamedFramebuffer` 经作用域化 client-shadow read/draw 绑定发布,降为现有 bound backend 调用,退出恢复公开绑定。**GLES mip storage**:前端先定义并发布层级,server 只验证 applier descriptor 的 Levels/extent;registry 身份解析只 Find 不 mint。
- **P5b 留下的 inproc 依赖**:具名 blit 的 scoped client binding + barrier;mip descriptor 的 barrier-held registry 查询;FBO death 的 inproc mailbox。三者跨地址空间都不成立——它们只是 §17.6 清单里的三行。
### 17.6 `inproc` 仍经共享地址空间的访问,与 P5c 的形状(计划,未实现)
### 17.6 `inproc` 仍经共享地址空间的访问,与 P5c 的形状(已落地,头 `b88e8487`)
P5 / P5b 的 wire 只覆盖 verb 记录、`SEG_STAGE` blob、reply 与 caps 快照。对 `a79a0af6` 的只读静态审计(`ROADMAP.md` "P5c 计划",报告 `~/w7/notes/p5c/p5c-audit-v1.md`)列出 59 处仍靠 verb barrier 与同一地址空间才正确的直接访问,最重的四类:**纹理纹素**虽已过 `SEG_STAGE` 但 applier 丢掉指针、Espryt 回读 client 的 `MipmapStorage`(整个纹理家族不在 `FieldOwnership.def`,`rsp` / strict / audit 都看不见);**反向通道**是 apply 线程直接调进 client `MG_State`(`OnBufferWriteback` 传裸指针,`SEG_EVENT` 已铺好但零 producer,十个回调只装了两个);**server 用前端 `GetLifetimeId()` 去 client 的 slot 分配器查找甚至铸造句柄**,而记录里其实已带句柄;**Magma** 直接读 client 的 caps 镜像、直接 `MarkGpuWritten`、直接写 client 的 mip 存储。
P5c 的设计决定:(1) **server 端纹理 staged shadow**——`ApplyTextureUpload` 采纳 `SEG_STAGE` 字节,`SyncMipmapsToBackend` 只读它与描述符,`0xDD` audit 因此覆盖纹理;(2) **`SEG_EVENT` 成为唯一反向通道**——`OnBufferWriteback` 的 `MGPBlobRef` 约定 `Seg = kSegEvent`,`OnGpuWritten` / `OnSurfaceChanged` 走同一 ring,Magma 与 Espryt 共用回调,溢出策略按 §11.7;(3) **sink 与 twin 按记录里的句柄解析**(`GetOrCreate(MGPipeHandle)`),server 永不触 `MGPipeSlots()`;(4) **两条控制记录** `applier_reset`(make-current 边)与 `object_death`(framebuffer 首次有 delete opcode),mailbox 只剩 EGL forwarder 给 P6;(5) **值类 BARRIER-PULLED 行改为每 verb 残余值记录或 server 自答**,对象类行保持 barrier 直到 twin 表落地(P3b/P4b、P7、P8);(6) **角色守卫**——split 构建有传输时,apply 线程触前端对象表面、GL 线程触 server 状态表面都是 `Fatal{RoleViolation}`;这是 P5c 的出口门,也是 P6 只做传输替换的前提。
P5c 的设计决定(六条全部落地,落地形状与偏差以 `MobileGL/MG_Remote/CONTRACT-P5C.md` 为最新权威):(1) **server 端纹理 staged shadow**——`ApplyTextureUpload` 采纳 `SEG_STAGE` 字节,`SyncMipmapsToBackend` 只读它与描述符,`0xDD` audit 因此覆盖纹理;(2) **`SEG_EVENT` 成为唯一反向通道**——`OnBufferWriteback` 的 `MGPBlobRef` 约定 `Seg = kSegEvent`,`OnGpuWritten` / `OnSurfaceChanged` 走同一 ring,Magma 与 Espryt 共用回调,溢出策略按 §11.7;(3) **sink 与 twin 按记录里的句柄解析**(`GetOrCreate(MGPipeHandle)`),server 永不触 `MGPipeSlots()`;(4) **两条控制记录** `applier_reset`(make-current 边)与 `object_death`(framebuffer 首次有 delete opcode),mailbox 只剩 EGL forwarder 给 P6;(5) **值类 BARRIER-PULLED 行改为每 verb 残余值记录或 server 自答**,对象类行保持 barrier 直到 twin 表落地(P3b/P4b、P7、P8);(6) **角色守卫**——split 构建有传输时,apply 线程触前端对象表面、GL 线程触 server 状态表面都是 `Fatal{RoleViolation}`;这是 P5c 的出口门,也是 P6 只做传输替换的前提。
落地时的三条结构性补充(契约 §3.1 与 §5.4 的具名豁免):审计漏了三族无句柄站点——绑定记录 P4b 才发射的 ensure/通告族(`MGPipeReverseAnnouncementScope`)、G6 前端键 twin registry(`MGPipeFrontendKeyedRegistryScope`,P3b/P4b 重键)、Magma 拆除期的隐藏资源;两个 scope 内的只读探测是具名、可 grep、带退役阶段的债,不是守卫的洞。
## 附 A:开关
+35 -20
View File
@@ -1,6 +1,6 @@
# 当前阶段进度
分支 `feat/disaggregated`;代码头 `82683d4a`(2026-09-16),其后只有文档提交。本文随每次落地更新。ID-1..75 的逐条裁定长文在 git 历史(`ef35ea0c` 之前版本的本文件)。
分支 `feat/disaggregated`;代码头 `b88e8487`(2026-09-17,P5c 收官)。本文随每次落地更新。ID-1..75 的逐条裁定长文在 git 历史(`ef35ea0c` 之前版本的本文件)。
## 1. 阶段状态
@@ -9,27 +9,41 @@
| P0 / P0.5 / P1 / P2 / P3a / P4a(monolith 跑道) | 已落地 | `ROADMAP.md` 阶段表;`MEASUREMENTS.md` §1–§5 |
| **P5** 首个 IPC 帧(reduced path,lockstep inproc) | 已收官 | `ff2994d9..37fc4fdb`;`MEASUREMENTS.md` §6 |
| **P5b** inproc 下的 verb 迁移(Minecraft 优先) | **已收官(2026-09-16)** | `37fc4fdb..82683d4a`;`MEASUREMENTS.md` §7 |
| **P5c** `inproc` 共享内存读点归零 | **已审计、已计划(2026-09-17),未开始** | 审计 `~/w7/notes/p5c/p5c-audit-v1.md`(59 行,头 `a79a0af6`);计划 `ROADMAP.md` "P5c 计划";设计 `ARCHITECTURE.md` §17.6 |
| P6 spawn transport | P5c 之后 | 届时只是传输替换 |
| **P5c** `inproc` 共享内存读点归零 | **已收官(2026-09-17)** | `11ac3de6..b88e8487` + triage 修复;契约 `MobileGL/MG_Remote/CONTRACT-P5C.md`;审计 `~/w7/notes/p5c/p5c-audit-v1.md` |
| P6 spawn transport | **下一个** | 届时只是传输替换 |
## 2. 当前头实测
| 门 | 结果 |
|---|---|
| 构建 | pull / push / verify / split 四个 flavour 全部通过 |
| G1(pull 符号恒等) | `.text +0`,27814 符号 0 增 / 0 删 / 0 resize / 0 重命名 |
| 发射表分区(`EmitTables.cpp` 的 `static_assert`) | A(本地回答)2 / B(发射)54 / C(具名拒绝)15,共 71 槽 |
| unit | pull / push / verify 各 1817;split 2138(含 `7cb29d46` 后 `UserIndexSpan` 3/3) |
| `integration-split`(inproc) | **107/107**(P5 收官时 22) |
| `integration-gpu` | push 1148/1148;split 单体传输 1267/1267 |
| G5(p3a / p4a 保护区) | 双绿 |
| 主机收尾全门(`348d22a4`) | complete=true,exit 0:31 步 rc=0;retrace-push 79/79、retrace-verify 79/79(钉住库续跑合并);OpenRA 2/2 |
| 集成普查(inproc 车道,`348d22a4`) | 1267 selected = 811 passed / 203 skipped / 62 aborted / 191 failed;对 c0b 基线零回退 |
| 79 trace 普查(inproc,stage 256 MiB,`348d22a4`) | **72 passed / 6 aborted / 1 failed** |
| Redmi 正确性(`82683d4a`,APK `p5bcodex2`,stage 256 MiB) | **8/8**:四条 A/B trace × 双后端首次在设备上 inproc 渲染 |
| Redmi 四臂 A/B | 24/32 组 200 帧尾验证全绿;barrier tax(split−push 逐线程 CPU p50)+5.9% – +18.2%;iris-bsl 8 组为 fixture 123 帧上限(pull 同失败),补充表另记 |
| G1(pull 符号恒等) | `.text` −16 B,0 增 / 0 删 / **3 认定 resize** / 0 重命名(`SwapchainObject::Create` ev 的表面事件化、`CopyTexSubImage2D` hd 的传输臂、`ScopedRestartIndexSubstitution` 的 server-shadow 臂,均已在合并提交具名);pull 构建零 `MG_Remote` 符号 |
| 发射表分区(`EmitTables.cpp` 的 `static_assert`) | A 2 / B 54 / C 15,共 71 槽(未变) |
| unit | split **2187/2187**(`MOBILEGL_IPC_STRICT_ERRORS=1` 下同绿) |
| `integration-split`(inproc) | **111/111**(107 + ct 的 4 条 CtWireScenario) |
| `integration-gpu` 普查(inproc,对 11ac3de6 同机基线逐名比对) | 修复后 newly-failing 全部归类:设计红(传输下旧臂具名拒绝的对照车道 + Magma P7 未迁移面,逐条 Fatal 名证据在案);三个真回归(默认 FBO 格式时序、大 writeback 切片、XFB scatter 读 server shadow)已修并回归绿 |
| G5(p3a / p4a 保护区) | 双绿(`11ac3de6` ↔ 收官头字节一致) |
| 生成器 / 卫生门 | `gen_pipe` / `gen_pipe_field_ownership` 的 --check/--self-test 绿;doc 引用 0 problem;include 闭包 0 problem;dirty-surface rc=0 |
| 纹理 `0xDD` audit(`MOBILEGL_IPC_AUDIT=1`) | bsl in-world(100000 调用)与 iris-complementary in-world 全程零 Fatal |
| `rsp` 按帧实测(`MOBILEGL_PIPE_STATS_PERIOD=1`) | bsl 948.5/帧(38.7/draw)、complementary 1591.9/帧;值类 = 0,残留即 FieldOwnershipTest 钉住的 15 行对象类 |
| Redmi 四臂复测 | **未做**(E-P5c #5 是记录项;本机无设备,需 Redmi `2f7cbe2e` 窗口) |
| 79 trace 普查 | **未重跑**(全集语料不在本机;本机可用语料的实测见 `rsp` 与 audit 行)。P5b 收官数字(72/6/1)仍以其头为准 |
## 3. P5b 落地内容
## 3. P5c 落地内容
| 包 | 内容 | 效果 |
|---|---|---|
| c0c | `MG_Remote/CONTRACT-P5C.md`:纹理 staged shadow 所有权 / SEG_EVENT blobref 约定 / 按句柄解析 / 两条控制记录 / 残余值字段表 / 角色守卫语义;落地偏差全部写回 | 六包按同一契约施工 |
| tx | `StagedTextureStore`(句柄为键、整段覆盖、defined-ness 追踪);`SyncMipmapsToBackend` 四臂改读 store + 描述符;Magma mip 改标 server shadow | 纹理纹素不再回读 client;`0xDD` audit 覆盖纹理 |
| ev | `SEG_EVENT` 三个 producer + `kEventGlError`;producer 归 server session 安装;消费端三臂(拆 monolith guard);`InvalidateCompileEnv` forward 删除 | 反向通道零裸指针 |
| hd | sink / twin 按记录句柄解析(具名 blit 经 verb 句柄工作区、CopyTex、mip、间接族);`HasDefinedContent` 读描述符位 | 守卫面闭合前的解析层 |
| 合并协调 | 两个具名豁免 scope(通告家族 P4b/P7、G6 registry 家族 P3b/P4b);PrimitiveRestart 改读 server shadow;Magma 具名 blit 的 G6 消费臂 | 审计漏报的三个无句柄家族有具名归宿 |
| ct | `applier_reset`(77)/ `object_death`(78,framebuffer 首个 wire delete);GL 线程直调 `MGPipeApplierReset` 成 RoleViolation | 控制面补全 |
| rv | `set_context_values`(79);值类 BARRIER-PULLED 清零;三 shutter 自答;`MGPAttribValue` 三视图 | rsp 值类 = 0 |
| gt | 纹理九表面 layer-1 守卫(挂 MipmapStorage 汇聚点);`InBarrierWait` 接线成 gPipeInputs 单写者规则的 client 半边;strict CI 车道(unit 绿门 + 场景预期红);rsp 按帧实测 | 每层守卫 red-once 按名验证 |
| triage 修复 | 默认 FBO 格式事件的第二类排空点(EGL RPC 返回);大 writeback 的客户端切片(环 1/4);XFB scatter 改读 server staged shadow | 普查三个真回归修复 |
## 4. P5b 落地内容
| 包 | 迁移的槽 / 内容 | 效果 |
|---|---|---|
@@ -58,7 +72,7 @@
| Magma(DirectVulkan)split compute/image 路径:89 个错答中 82 个 | `p5b-results/i1-v1.md` |
| rd12 GLES `InitialBytesNotCarried/resource_respecify`、rd12 VK `BarrierTimeout/Present`、`iris-bsl-esc-menu-854` GLES、三条 `texture-remint-pull` 仿真槽、`create-indirect` VK 内存膨胀 | 79 trace 普查 `counts.json` / `trace-transitions.json` |
| RGB 三通道 CPU mip 回退仍是具名 Fatal | `p5b-results/mip-codex-v1.md` |
| **`inproc` 仍有 59 处不经 wire 的直接内存访问**(2026-09-17 审计):纹理纹素已过 `SEG_STAGE` 却被 applier 丢掉、Espryt 回读 client `MipmapStorage`(整个纹理家族不在 `FieldOwnership.def`,`rsp` / strict / audit 看不见);反向通道是 apply 线程直接调进 client(`OnBufferWriteback` 传裸指针,`SEG_EVENT` 零 producer,十个回调只装两个);server 用前端 `GetLifetimeId()` 查 / 铸 client 的 slot 分配器(记录已带句柄);Magma 四处直读 client caps 镜像、直接 `MarkGpuWritten`、直接写 client mip 存储;`MGPipeApplierReset` 与对象死亡经裸指针跨角色;`InBarrierWait` 从未接线。P5b 记下的三处 inproc 依赖只是其中三行 | `~/w7/notes/p5c/p5c-audit-v1.md`;`ROADMAP.md` "P5c 计划"(T1–A1 清单、包、出口门) |
| ~~`inproc` 仍有 59 处不经 wire 的直接内存访问~~(2026-09-17 审计) | **P5c 已收官归零**:四族修复(tx/ev/hd/ct/rv/gt)+ 普查 triage 三真回归修复;剩余为具名债——两个豁免 scope(通告家族 P4b/P7、G6 registry 家族 P3b/P4b)内的只读探测与对象类 15 行 BARRIER-PULLED,全部可 grep、有退役阶段 | `MobileGL/MG_Remote/CONTRACT-P5C.md`;`MEASUREMENTS.md` §8 |
| 27 个 P5 inproc 错答:22 纹理读回走 client-shadow 回退、3 query、1 inspection、1 FBO/RBO 删除后生命期 | P4b / P7 / P6 债 |
| `rsp` 残余输入;`SEG_REPLY` 2 MiB 单槽上限;GetCaps 两个 blobref 的载体;PACK-PBO 读回真实形式 | P3b/P4b、P6+ |
| 15 个 class-C 槽(query / sync 尾 / `GetTexImage` / `SetSwapInterval` 等)无负载命中,仍具名拒绝 | P9 / P10 |
@@ -67,10 +81,10 @@
## 6. 下一步
1. **P5c**:c0c 契约 → tx(纹理 staged shadow)/ ev(`SEG_EVENT` producer)/ hd(按句柄解析、caps 改读 server backend)并行 → ct(`applier_reset` / `object_death` 记录)/ rv(值类残余值记录)→ gt(角色守卫门、`rsp` 按帧实测)。出口门 E-P5c 见 `ROADMAP.md`。
2. **P6 spawn transport**:`SocketTransport` + `ServerMain` + 握手 / 退出语义 + EGL forwarder 的控制面帧;届时只换传输。
3. 剩余首阻塞一轮(Magma compute/image、rd12、RGB mip、`texture-remint-pull` 仿真槽)。
4. P6 出口门:P5b 的完整渲染路径在 `spawn` 下绿;OpenRA 在 Adreno 830 上 split SSIM ≥ 0.99。
1. **P6 spawn transport**:`SocketTransport` + `ServerMain` + 握手 / 退出语义 + EGL forwarder 的控制面帧;P5c 之后这只是传输替换。注意 P5c 留下的:`s_synced` / `g_syncedRenderStateParameters` 按 context 世代重置;两个豁免 scope 里的探测在 spawn 下根本不存在对应内存,P6 第一天的红就是它们的清单。
2. 剩余首阻塞一轮(Magma compute/image、rd12、RGB mip、`texture-remint-pull` 仿真槽)。
3. P6 出口门:P5b 的完整渲染路径在 `spawn` 下绿;OpenRA 在 Adreno 830 上 split SSIM ≥ 0.99。
4. Redmi 四臂复测(P5c 的记录项,需设备窗口);79 trace 普查重跑(需全集语料)。
## 7. 记录位置
@@ -84,6 +98,7 @@
| P5b 设备证据 | `~/w7/notes/p5b/apk/p5bcodex2/`(APK + proof);`MobileGL/.trace-work/p5b-redmi/p5bcodex2/2f7cbe2e/`(correctness 8/8、`ab-tables.md` 与 bsl 补充表) |
| class-C 普查 | `~/w7/notes/p6/census-classC.md`;基线 `~/w7/p5b-c0b-census-logs/results.json` |
| P5c 审计 | `~/w7/notes/p5c/p5c-audit-v1.md`(59 行清单、wire-clean 清单、与契约的分歧、已有 `rsp` 数字)+ `BRIEF-p5c-audit.md`;Kimi K3 只读静态审计,头 `a79a0af6`,关键行已由集成者逐条抽查 |
| P5c 契约 / 实测 | `MobileGL/MG_Remote/CONTRACT-P5C.md`(含落地修订);`MEASUREMENTS.md` §8(逐门数字);普查逐名 Fatal 证据 `~/p5c-fatal-map.tsv`;G1 报告 `~/p5c-g1-report.json`;audit 日志 `~/p5c-audit-{bsl,comp}.log` |
| 门日志 | `~/w7/p5-joint-gate.log`、`~/w7/p5b-quickgate.log`、`~/w7/p5-joint-evidence/` |
| 脚本 | `~/w7/notes/tools/`(`wsl_p5_gate.sh`、`p5_ab_redmi.sh`、`p5b_codex_redmi.sh`、`wsl_build_p5_apks.sh`、`p6_census_*.{sh,py}`、`p5b-c0b-census.sh`) |
+21
View File
@@ -426,3 +426,24 @@ Redmi `2f7cbe2e`,证据根 `MobileGL/.trace-work/p5b-redmi/p5bcodex2/2f7cbe2e/
splitctl−push 全部在 ±1.6% 内(增量来自 inproc 传输与 barrier,不是 APK / 构建差);p99 同向放大(sodium DirectVulkan 帧 p99 +107.7% 为离群尾帧)。inproc 臂 peak RSS 389 MiB – 2.5 GiB,全角色映射 560.5 MiB(256 MiB × 角色视图是虚拟映射容量,不是 RSS 增量)。
**fixture 受限的 8 组**:`iris-bsl-in-world` 只有 123 个 benchmark 帧,低于 200 帧尾规则,四臂 × 双后端验证全部失败(pull 同失败,是 fixture 上限不是回归);123 帧完整序列按同法折算成补充表 `ab-tables-bsl-123frame-supplement.md`:barrier tax CPU p50 DirectGLES **+7.1%**、DirectVulkan **+9.1%**,不混入上表。性能仍只记录、不作阻塞门。
## 8. P5c(`11ac3de6..b88e8487`,同日收官)
出口门(E-P5c)实测:
| 门 | 结果 |
|---|---|
| 守卫开启下 unit | **2187/2187**(strict `MOBILEGL_IPC_STRICT_ERRORS=1` 下同绿) |
| 守卫开启下 `integration-split` | **111/111**(107 + ct 的 4 条 CtWireScenario,全真跑) |
| 每层守卫 red-once | layer-1(MipmapStorage 守卫短路 → `TextureMapMipmapDataFromTheApplyThreadIsFatalByName` 红)与 layer-2(`RefusePipeInputsTouchWhileApplierOwnsIt` 短路 → `ClientPipeInputsFillWhileTheApplierOwnsItIsFatalByName` 红)各红一次并复原;tx 的采纳改回丢指针 → 恰 `StagedTextureProductionTest` 红;ev 的 writeback 改回裸指针 → `AtomicCounterScenario.SubDataAfterDispatchSurvivesAnImmediateReadback` 按名红;ct 的发射短路 → Ct 4/4 按名红;rv 的发射门短路 → 7 条按名红 |
| 纹理 `0xDD` audit | bsl in-world(100000 调用)与 iris-complementary in-world 全程零 Fatal |
| `SEG_EVENT` 往返 | 三种事件 + `kEventGlError` 各有单元往返;排空点 `eventDropped == 0` |
| `rsp` 分类 | 值类 = 0(rv 的 FieldOwnershipTest 钉住);按帧实测:bsl 948.5/帧(38.7/draw,123 帧)、complementary 1591.9/帧(151 帧)、iterationrp 286.2/帧(108 帧后止于既有具名 `texture-remint-pull`);残留全为对象类 15 行 |
| 普查(integration-gpu @ inproc,对同机 11ac3de6 基线逐名比对) | 基线 253 红 / 收官头 423 红;183 条 newly-failing 中 11 条为三个真回归(默认 FBO 格式时序、大 writeback 溢出、XFB scatter 读前端)——已修并回归绿;其余 172 条全部带 Fatal 名证据归类为设计红(传输下旧臂具名拒绝的对照车道 14 条 + Magma P7 未迁移面 156 条)与 2 条 DirectVulkan CtWire(改按名 skip:Magma 无 object_death 生产者,P7) |
| G1(pull 符号恒等,`11ac3de6` ↔ 收官头,CI 同款 sym 构建) | 0 增 / 0 删 / **3 认定 resize** / 0 重命名,`.text` −16 B:`SwapchainObject::Create`(ev 表面事件化)、`CopyTexSubImage2D`(hd 传输臂)、`ScopedRestartIndexSubstitution`(server-shadow 臂);pull 构建零 `MG_Remote` 符号 |
| G5(p3a / p4a 保护区) | 字节一致 |
| 生成器 / 卫生门 | 双生成器 --check/--self-test 绿;doc 引用、include 闭包、dirty-surface 绿 |
| Redmi 四臂复测 | **未做**(记录项,需设备窗口;barrier tax 重测随之) |
| 79 trace 普查 | **未重跑**(全集语料不在本机;P5b 的 72/6/1 仍以其头为准) |
审计的 59 处直接访问的终态:纹理纹素 / 形状 / 脏区改读 server staged shadow(tx);反向通道四条事件(ev);句柄解析全部按记录(hd);`applier_reset` / `object_death` 上 wire(ct);值类残余读清零(rv);双层角色守卫 + `InBarrierWait`(gt)。**未到期的具名债**:`MGPipeReverseAnnouncementScope`(绑定记录 P4b 才发射的 ensure/通告族)与 `MGPipeFrontendKeyedRegistryScope`(G6 前端键 twin registry,P3b/P4b 重键)两个 scope 内的只读探测,以及对象类 15 行 BARRIER-PULLED——全部具名、可 grep、有退役阶段。
+2 -2
View File
@@ -1,6 +1,6 @@
# MGPipe:MobileGL 前后端拆分
> 状态:**P0–P5b 已收官**(2026-09-16,代码头 `82683d4a`)。目标负载(四条 Minecraft A/B trace)已在 Redmi Adreno 830 上以 `inproc`(独立 apply 线程)双后端渲染,barrier tax 首次实测。**下一个是 P5c**:审计(2026-09-17)显示 `inproc` 的两个角色仍有 59 处不经 wire 的直接内存访问(纹理纹素回读 client、反向通道裸指针、server 用 client 的 slot 分配器等),P5c 先把它们归零,**然后才是 P6 spawn transport**(计划见 `ROADMAP.md` "P5c 计划")。当前头、逐门数字与开放项见 [`CURRENT_STAGE_PROGRESS.md`](CURRENT_STAGE_PROGRESS.md)。
> 状态:**P0–P5c 已收官**(2026-09-17,代码头 `b88e8487`)。目标负载(四条 Minecraft A/B trace)已在 Redmi Adreno 830 上以 `inproc`(独立 apply 线程)双后端渲染,barrier tax 首次实测;P5c 把审计出的 59 处不经 wire 的直接内存访问全部归零(契约 `MobileGL/MG_Remote/CONTRACT-P5C.md`),`inproc` 成为只经 wire 交换的诚实两角色。**下一个是 P6 spawn transport**——此时只是传输替换。当前头、逐门数字与开放项见 [`CURRENT_STAGE_PROGRESS.md`](CURRENT_STAGE_PROGRESS.md)。
>
> 性能纪律(2026-09-08 起):逐线程 CPU 与 tracker 绝对 ns **对着 pull 臂基线记录**,不作阻塞门;专门的优化阶段排在路线图推完之后。
@@ -16,7 +16,7 @@ MGPipe 是 MobileGL 前端(`MG_State` + `MG_Impl`)与后端(`MG_Backend`
应用 GL 调用
→ MG_Impl(GL 语义、错误、shadow)
→ MG_Impl/Pipe/Tracker:在每条 verb 之前 validate,把变化推成 MGPipe 调用
→ MGPipeScreen / MGPipeContext(两张函数指针表,76 条调用,单一真相源 PipeCalls.def)
→ MGPipeScreen / MGPipeContext(两张函数指针表,79 条调用,单一真相源 PipeCalls.def)
monolith:直调 backend 函数 split:发射器写 SEG_CMD ring → server applier(apply 线程)
→ server 对象表(按 {slot, gen} 句柄索引的数组)+ PipeInputs(后端被推送的状态块)
→ MG_Backend(Espryt / Magma),两个后端的 ring / pool / memo / lowering pass 原样不动
+2 -2
View File
@@ -1,6 +1,6 @@
# MGPipe 路线图
> 状态:**P0、P0.5、P1、P2、P3a、P4a、P5、P5b 已收官**(2026-09-16,代码头 `82683d4a`)。当前头、逐门数字、开放项与下一步见 **[`CURRENT_STAGE_PROGRESS.md`](CURRENT_STAGE_PROGRESS.md)**;设计见 `ARCHITECTURE.md`;逐阶段实测见 `MEASUREMENTS.md`。**下一个是 P5c**(`inproc` 的共享内存读点归零,2026-09-17 已审计、已计划、未开始,见下文"P5c 计划"),**然后才是 P6 spawn transport**。
> 状态:**P0、P0.5、P1、P2、P3a、P4a、P5、P5b、P5c 已收官**(2026-09-17,代码头 `b88e8487`)。当前头、逐门数字、开放项与下一步见 **[`CURRENT_STAGE_PROGRESS.md`](CURRENT_STAGE_PROGRESS.md)**;设计见 `ARCHITECTURE.md`;逐阶段实测见 `MEASUREMENTS.md`。**下一个是 P6 spawn transport**(此时只是传输替换)。
## 通用纪律(每个 commit)
@@ -26,7 +26,7 @@
| **P4a** handle wave 2(Espryt):FBO / 纹理 / sampler / program | ✅ `8c458cd5` | 十四条族调用接线(framebuffer state、sampler state / view、texture params、shader images、shader state、draw / dispatch program、global constants);纹理 / renderbuffer 复用 `resource_*`(目录不加行);六种 kind 按 `{slot, gen}` 重键;`CompositeResolver`;`Named = 3` framebuffer 记录;消费者门 + 客户端依赖表;位 9–12,push 默认 `0x1fff`;emulation 在 split 下具名 Fatal | 全门:G1 0/0/0/0;G5 17 区;G2 2902;单元 1785×3;`integration-gpu` 1117 七臂;verify 920;retrace 79/79;八族拒绝普查 0;`PipeApplyPeek` 白盒对照。实际 1 天。§5 |
| **P5** 传输 + inproc applier + 发射表 | ✅ `ff2994d9..37fc4fdb` | 同一 codec 上的 `InProcessTransport`;四种 build flavour;发射表三类 / caps mirror / reply mailbox;apply-thread context 终身持有;lockstep verb barrier;tight ReadPixels;persistent-map 块推送;G8 字段归属生成器;split 测试 / CI / APK 车道;八包(c0 契约、w1 codec、s1 session、p1 归属、b1 persistent map、t1 车道、c1 路由、v1 server)+ j0 / x2 / v1-r3 收尾 | joint:OpenRA inproc 2/2 SSIM 1.0;`integration-split` 21/21;E1 14/14 红;G1 0/0/0/0。收尾头全门在 E3(a) 停止(设计性 skip 被判红),Part 2/4 未到达;收官审查 1 blocker / 10 major / 2 minor → P5b r1/r2。§6 |
| **P5b** `inproc` verb migration | ✅ `37fc4fdb..82683d4a` | class-C 普查决定顺序;d1 19 / i1 7 / t2 6 / f1 11 槽迁移;sync 五槽;具名 blit;GLES mip descriptor;r1 / r2;收官审查三项修复。发射表 A=2 / B=54 / C=15 | 主机全门 `348d22a4` complete;`integration-split` 107/107;合并普查零回退、79 trace 72/6/1;**Redmi 正确性 8/8 + 四臂 A/B、barrier tax 首测**。§7 |
| **P5c** `inproc` 共享内存读点归零 | **下一个**(2026-09-17 已计划,未开始) | server 端纹理 staged shadow;`SEG_EVENT` 的三个 producer;sink / twin 按记录里的句柄解析;`applier_reset` / `object_death` 控制记录;值类 BARRIER-PULLED 行改残余值记录;角色守卫门。详见下文"P5c 计划" | 角色守卫开启下 `integration-split` / 普查 / 79 trace 全绿且每层守卫能红;纹理 `0xDD` audit 红一次;`SEG_EVENT` 往返红一次;`rsp` 只剩对象类行且按帧测得;Redmi 四臂复测记录 | P5b |
| **P5c** `inproc` 共享内存读点归零 | ✅ `11ac3de6..b88e8487` | server 端纹理 staged shadow(`StagedTextureStore`,句柄为键、整段覆盖、defined-ness 追踪);`SEG_EVENT` 三个 producer + `kEventGlError`(反向通道零裸指针);sink / twin 按记录句柄解析(blit 具名臂经 verb 句柄工作区,Magma 走 G6 消费臂);`applier_reset` / `object_death` 控制记录(opcode 77/78,framebuffer 首个 wire delete);`set_context_values`(79)退役全部值类 BARRIER-PULLED 行,三 shutter 自答;双层 `Fatal{RoleViolation}` 守卫 + `InBarrierWait` 接线;两个具名豁免 scope(通告家族 P4b/P7、G6 registry 家族 P3b/P4b)承接未到期的债 | 角色守卫开启下 unit 2187/2187(strict 下同绿)、`integration-split` 111/111、每层守卫 red-once 按名变红;纹理 `0xDD` audit 在 bsl / complementary 两条 in-world trace 零 Fatal;rsp 按帧实测(bsl 948.5/帧,残留全为钉住的对象类 15 行);G1 三个认定 resize(SwapchainObject::Create / CopyTexSubImage2D / ScopedRestartIndexSubstitution,均已具名)+ `.text` −16 B、pull 构建零 MG_Remote 符号;G5 保护区字节一致;双生成器 --check/--self-test 绿 | P5b |
| **P6** spawn transport | P5c 之后 | `SocketTransport`(socketpair + fork/execve,envp 剔除 + 强制 monolith 双保险);`ServerMain`;`MOBILEGL_IPC_SERVER_PATH` + `dladdr` 兜底;有界重试握手;EOF 即时退出;device-lost latch;EGL forwarder 的控制面帧;P5c 留下的 `s_synced` / `g_syncedRenderStateParameters` 按 context 世代重置 | P5b 的完整渲染路径在 `spawn` 下绿;进程树只多一个子进程;`HeadlessGL` fork 预检无孤儿;OpenRA 在 Adreno 830 上 split SSIM ≥ 0.99 |
| **P3b / P4b** 深化(Espryt) | 待排 | 按存储属主键控的发射游标与 view 索引重映射;`g_fboTextureSyncList`;`ResolvedTextureBindingMemo` / `SamplerPassMemo` / image sweep / program registry 重键;XFB scatter 搬到 client;删 fragColor 重推导 workaround 与 `g_broadcastMemo*`;raw-depth-fetch sampler 原生化;回读 / pack state;P4a 记下的 R-3 / R-4 / R-5 / R-7 / R-10 / R-11;`ProgramArtifacts.h` 的 NDK 尺寸钉 | 纹理 / program 场景;CTS `texture_*` / `shader_image_*` / `packed_pixels` 在 0.5 pp 内;每一个 Iris trace;`TextureUploadShapeScenario` 升级成门 |
| **P7** DirectVulkan(Magma)全量迁移 | 待排 | 其余 10 个子系统:`SetupDrawSnapshot` 探测字段塌成 dirty mask;占位纹理原生化;具名 UBO host payload(D-B8);内部 shader 烘焙;`VertexInputStateFactory` 内容寻址 CSO;D18 容器纪律保留 | 集成 + trace 在 Magma 的 push 与 split 下全绿;verify 零分歧;`nm -D libMobileGLServer.so \| grep glslang` 为空;CTS 0.5 pp 内。**再基线检查点:中点完成子系统 < 40% 立即重定基线** |
+20 -1
View File
@@ -462,6 +462,25 @@ def check_field_lists_cover_struct_members(field_lists, payloads, header_texts=N
ACCESSOR_READ_RE = re.compile(r"\b(?:MGB_CTX|pGLContext)\s*->\s*(\w+)")
# The scanner's NAMED exemptions: accessors a backend reads through MGB_CTX-> / pGLContext->
# that are NOT PipeInputs fields and never will be, each with the reason written down. A name
# here is a DEBT ENTRY, not a silence: it exists so the gate can tell "scoped, named, phased"
# from "forgot the row".
#
# P5c (the tx/ev/hd merge): the G6 frontend-keyed registry's framebuffer arm - two probes a
# backend makes inside MGPipeFrontendKeyedRegistryScope (CONTRACT-P5C.md section 3.1's second
# named exemption: the registry probes ride the scope, an unwrapped probe still aborts, and
# the scope retires with the twin tables at P3b/P4b). They are object-registry lookups, not
# PipeInputs state reads, so no Coverage.def row can ever describe them - a row there is a
# field in the fill table, and these have no storage to fill.
SCAN_EXEMPT_ACCESSORS = {
"GetFramebufferObject": "P5c G6 registry probe (the default framebuffer's object), inside "
"MGPipeFrontendKeyedRegistryScope; retires with the twin tables (P3b/P4b)",
"FindFramebufferObjectByLifetimeId": "P5c G6 registry probe, inside "
"MGPipeFrontendKeyedRegistryScope; retires with the twin tables (P3b/P4b)",
}
def scan_live_accessors(accessors, backend_dir=None, verbose=True):
"""Every accessor a backend reads through MGB_CTX-> or pGLContext-> (comments and
strings masked) must have a Coverage.def row - a read without a row is a PipeInputs
@@ -479,7 +498,7 @@ def scan_live_accessors(accessors, backend_dir=None, verbose=True):
masked = mask_comments_and_strings(read(path))
for match in ACCESSOR_READ_RE.finditer(masked):
read_names.setdefault(match.group(1), set()).add(os.path.relpath(path, REPO_ROOT))
unknown = sorted(n for n in read_names if n not in known)
unknown = sorted(n for n in read_names if n not in known and n not in SCAN_EXEMPT_ACCESSORS)
if unknown:
sys.exit("Coverage.def: accessor(s) read by a backend with no row: %s"
% ", ".join("%s (%s)" % (n, ", ".join(sorted(read_names[n]))) for n in unknown))
+16 -13
View File
@@ -558,10 +558,13 @@ def self_test():
# substring is not decoration: see expect_trip.
# 1. THE HEADLINE CONTROL (exit gate E4): take one field out of the table. It is in no
# class, and that is a build failure rather than a silent default.
dropped = edit(r"X\(GetActiveTextureUnit," + GAP + r"BARRIER_PULLED," + GAP + r"\"[^\"]*\","
+ GAP + r"\"[^\"]*\"\)", "", "remove GetActiveTextureUnit's row")
controls = [("a field in NO class (GetActiveTextureUnit's row removed)",
# class, and that is a build failure rather than a silent default. GetBoundVertexArray is
# the control's field since P5c rv (it keeps a hand-written BARRIER_PULLED row; the value
# rows the first version used are RECORD_SUPPLIED-derived now, so they have no row to
# edit).
dropped = edit(r"X\(GetBoundVertexArray," + GAP + r"BARRIER_PULLED," + GAP + r"\"[^\"]*\","
+ GAP + r"\"[^\"]*\"\)", "", "remove GetBoundVertexArray's row")
controls = [("a field in NO class (GetBoundVertexArray's row removed)",
"field(s) in NO class",
lambda: run(own_text=dropped))]
@@ -575,9 +578,9 @@ def self_test():
lambda: run(own_text=doubled)))
# 3. A row naming something that is not a field at all.
typo = edit(r"X\(GetActiveTextureUnit,", "X(GetActiveTextureUnitt,", "misspell a field name")
typo = edit(r"X\(GetBoundVertexArray,", "X(GetBoundVertexArrayy,", "misspell a field name")
controls.append(("a row naming a non-field",
"GetActiveTextureUnitt, which is not a PipeInputs field",
"GetBoundVertexArrayy, which is not a PipeInputs field",
lambda: run(own_text=typo)))
# 4. A BARRIER_PULLED row with no retiring phase: the debt is only sized if every row
@@ -585,17 +588,17 @@ def self_test():
# THE REPLACEMENT IS NOT A RAW STRING. It was, and the backslashes survived into the
# substitution, mangled the row past ROW_RE's reach and made this control a silent
# duplicate of #1 for a whole round.
unphased = edit(r"(X\(GetActiveTextureUnit," + GAP + r"BARRIER_PULLED,)" + GAP + r"\"[^\"]*\",",
unphased = edit(r"(X\(GetBoundVertexArray," + GAP + r"BARRIER_PULLED,)" + GAP + r"\"[^\"]*\",",
"\\1 \"-\",", "blank a BARRIER_PULLED row's retiring phase")
controls.append(("a BARRIER_PULLED row with no retiring phase",
"GetActiveTextureUnit is BARRIER_PULLED and names no retiring phase",
"GetBoundVertexArray is BARRIER_PULLED and names no retiring phase",
lambda: run(own_text=unphased)))
# 5. A class that is not one of the four.
bogus = edit(r"(X\(GetActiveTextureUnit,)" + GAP + r"BARRIER_PULLED,",
bogus = edit(r"(X\(GetBoundVertexArray,)" + GAP + r"BARRIER_PULLED,",
"\\1 SOMEHOW_FINE,", "introduce a fifth class")
controls.append(("a fifth class",
"GetActiveTextureUnit is in class SOMEHOW_FINE",
"GetBoundVertexArray is in class SOMEHOW_FINE",
lambda: run(own_text=bogus)))
# 6. A sticky forward that lost its own row - the seven most dangerous fields are exactly
@@ -699,9 +702,9 @@ def self_test():
"the field set (%d of %d)" % (total, len(accessors)))
if len(sticky) != 7:
sys.exit("gen_pipe_field_ownership: self-test: Coverage.def no longer has seven sticky fields")
if len(refused) != 9:
if len(refused) != 7:
sys.exit("gen_pipe_field_ownership: self-test: EmittedCallSuppliesTheWholeField refuses %d "
"fields, not the nine the contract's derivation is written against" % len(refused))
"fields, not the seven the contract's derivation is written against" % len(refused))
if trips == 0:
sys.exit("gen_pipe_field_ownership: self-test: no negative control tripped - the gates are "
"not checking anything")
@@ -710,7 +713,7 @@ def self_test():
% (len(controls) - trips, len(controls)))
print("gen_pipe_field_ownership: self-test: %d negative-control trip(s), each asserted against "
"its OWN message; harness control OK; positive control OK "
"(%d fields partitioned, 7 sticky forwards, 9 refusals)" % (trips, total))
"(%d fields partitioned, 7 sticky forwards, 7 refusals)" % (trips, total))
return 0