Compare commits

..
Author SHA1 Message Date
swung0x48andClaude Fable 5.1 c5e1e59048 [docs, MG_Remote] (P7): the roadmap rows say what the tree says, and CONTRACT-P7 is drafted
ROADMAP.md: the Ph / P3b-P4b / P7 rows carry the audit's verdicts and the factual
corrections it found - the @P7 refusal list is 15 sites in 4 files (the row printed 8),
the 29-commit DirectVulkan shape wave was never recorded, the device divergence is two
observations with no per-case attribution and no lockstep control, SetupDrawSnapshot /
content-addressed CSO are declined for this stage, "XFB scatter to client" is retired
in favour of the two real holes, readback/pack state splits into closed and open
halves, the NDK size pin is obsolete, PACK-PBO readback landed in 70df57bb, the ABI
fingerprint landed in P6.5, and OQ-8 / OQ-10 / OQ-13 / OQ-21 get their current answers.
P6-ENDSTATE-REVIEW.md:284 qualifies an Init.cpp citation the lint reported ambiguous.

MG_Remote/CONTRACT-P7.md: rules I (no std::abort on the Magma wire arm) and J (every
fix reds once on a two-process arm), the five exit gates in testable form, the
retire-vs-decline table for every @P7 name, the ratchet's definition and P7 target,
the nine-subsystem denominator for the 40% checkpoint, the wave-2 file partition,
and the amendments to CONTRACT-P6. Census, ratchet and lane numbers are marked
待填 until wave 0's packages report them.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-22 13:26:34 -04:00
swung0x48andClaude Fable 5.1 78b7d6beac [docs, MG_Test] (P7): the Ph / P3b-P4b / P7 program plan, and the pull flavour builds its tests again
Plan for driving the roadmap to P7 close-out, from a per-item audit of the three
rows against a96875bf (19 reader groups, two refuters per done/obsolete verdict,
one completeness critic): what is landed, what is declined and why, what remains
with file anchors, five waves, the P7 subsystem denominator for the 40%
re-baseline checkpoint, and eleven integrator decisions (ID-P7-1..11).

The three findings the roadmap text did not carry: Magma has zero two-process
integration coverage (every split arm hardcodes DirectGLES), the 184-symbol
ratchet has no instrument, and the device DirectVulkan divergence was never
diagnosed (the lockstep control was never run under golden).

MG_Test/Util/PipeStatsTest.cpp: the pull flavour (MOBILEGL_PIPE_PUSH=OFF) did not
compile since the P6 wrap-up - the window-arithmetic case used the push-only
PipeStats::Gauge API unguarded. CI's pull control builds with
MOBILEGL_BUILD_TEST=OFF and never saw it. The gauge lines are now #if
MOBILEGL_PIPE_PUSH; the case name stays registered in both flavours for G2/G14.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-22 13:03:20 -04:00
swung0x48 a96875bf3f [docs] (P6.5): the first wave recorded as landed - review + fixes + representative re-validation, residual to CI 2026-09-22 11:58:22 -04:00
swung0x48 fe27380ab8 [MG_Remote, MG_Pipe, MG_Test, CI, tools, docs] (P6.5): the first wave completed and reviewed - archive v2, publication boundary, half-close, AcceptPair/role fixes, device re-validation 2026-09-22 10:56:19 -04:00
swung0x48 52ffc6a7f2 [WIP] (MG_Remote): implement P6.5 TCP and stream transport 2026-09-22 07:19:18 -04:00
swung0x48 810b9b7a9f [Fix] (CI): read role logs and retry device disconnects 2026-09-22 07:19:17 -04:00
swung0x48 e6c51d0711 [MG_Test, CI] (P6): the last two readers the role split left behind
build-linux-verify could not compile PipeStatsTest: RoleDerivedJsonDumpPathForTesting is DISAGGREGATED-only and the verify flavour is deliberately monolith. The case name stays registered and GTEST_SKIPs there, matching the PIPE_PUSH pattern, so ctest -N still matches between flavours.

runtime_mode_proof.py logs opened MOBILEGL_LOG_FILE_PATH as a file. After the split that name is a base and the sink writes <base>.client.log / <base>.server.log, so the inproc proof died on FileNotFoundError after a green lane. It now reads through split_log_paths' role helpers and names the paths it looked for when none exist.
2026-09-22 04:40:03 -04:00
swung0x48andClaude Fable 5.1 2ec8e7f4a1 [docs] (P6): the closeout - gates 7 and 8 are measured and P6 is closed
The device gate: Redmi 2f7cbe2e, reboot-clean, paired A/B in one thermal
window (arms interleaved, best-of-3 then best-of-2), rd12 + DirectGLES.
inproc vs spawn client CPU p50 7.880/7.889 vs 7.876/7.869 (-0.15%) and
7.987/7.989 vs 7.992/8.009 (+0.16%) - a tie inside the 0.2-4.2% within-
arm spread, sign flipping with arm order, recorded and not gated.
monolith is ~30% dearer. 22/22 runner exits clean, 44/44 PINNED, zero
Fatal.

The three mandatory numbers: socket doorbell vs condvar is a tie too -
client 121.1 waits/frame identical across transports, server 10 866-11
963 (inproc) vs 10 415-10 416 (spawn) waits/frame, and the contract's
'converting that into ~4 blocking reads may be cheaper' did not pay off;
the only column where the socket is worse is clipark/f (6.07 vs 5.60/5.75).
SEG_STAGE bytes/frame: 130.8 KB median / 8.01 MB steady (OpenRA), 816.2
KB / 1.53 MB (rd12). Records/frame post-chunking: 211/206 and 7 497/7
504. maxrec stays 1808 - the 8 MiB chunk budget is never reached. Both
framings reported throughout (the startup window runs ~7x the steady
state) rather than the flattering one.

MEASUREMENTS.md gains section 12 with the full protocol and tables; the
6.3 'no post-chunking distribution exists' gap now points there.
CURRENT_STAGE_PROGRESS.md marks gates 7/8 met and records the closeout
work plus two structural limits (spawn client windowed fields are zero
by construction - OnPresent runs in the server process - though its run
totals are valid stores; the stats dump is role-derived). ROADMAP marks
P6 closed in the stage table, the header and the milestone.

Evidence: notes/p6/gate7-device-ab.md, gate8-doorbell-device.md,
gate8-wire-counters.md, git-worktree-fix.md. check_doc_citations: 82
citations in the three documents, 0 problems.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-22 03:38:17 -04:00
swung0x48andClaude Fable 5.1 bf3e6f8ad3 [MG_Util, MG_Remote, tools] (P6): the wire counters and the spawn server's stats latch
Gate 8's last two numbers (SEG_STAGE bytes/frame, records/frame post-
chunking) had no producer at all: the summary line's byte classes are
backend-to-driver bytes and maxrec is a max, not a per-frame. Two push-
guarded counters answer them at their single choke points - ByteClass::
StageSegmentBytes at PipeWireCodec's StageAllocate (the only allocation
behind StageBytes, so every buffer walk, texture slab and CSO archive
lands there and emitters cannot double-count) and CallClass::WireRecords
on EncodeRecord's committed path (post-chunking an emitter no longer
knows how many records its one call produced). A staged-blob histogram
rides along. G1 holds: symbols 0/0/0/0, .text byte-identical, pull build
carries no MG_Remote symbols.

The spawn server never counted anything: PipeStats::Init() is a step of
MobileGL::Initialize(), which ServerMain never reaches, so every Enabled()
site in that process - including ServerLoop's own ServerWaits/ServerParks
publish - stayed false and the server log carried no summary line at all
(a zero that means 'another process' printed in the shape of one that
means 'never waited' is the milder misreading; the line was simply
absent). ServerMain now arms and closes PipeStats at its role boundary -
after MG_ConfigLoader::Init (Init latches from the parsed config), after
the server-role latch (the log sink's role), and before ::_exit(0).
Red-once: 0 server summary lines before, 29 after, SSIM 1.0 unchanged.

MOBILEGL_PIPE_STATS_FILE now derives per role through the log sink's
exported RoleLogPath rule - run.client.json / run.server.json, the bare
name resolves to no file - because both roles reach FormatJson() and ofstream
trunc made the second writer replace the first. G1 caught three separate
leaks on the way (a string temporary in the monolith body, one resized
Shutdown() from unequal #if arms, two rewritten MGLOG_W literals in
.rodata); the pull arm is statement-for-statement the original.

Device tooling for the paired A/B lands with it: pin_device.sh gains a
measured 2f7cbe2e entry (this board clamps the GPU at 1050 MHz -
thermal_pwrlevel writes 0 and reads back 1, max_gpuclk is read-only;
absolute times are not comparable with the 1100 MHz-era rows), and
tools/device_bench/p6/ carries the session collector and renderer beside
run_android_retrace_local.py's MOBILEGL_TRACE_PACKAGE override.

Unit 2367/2367 (PipeStats 25/25), spawn integration 102/102.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-22 03:37:51 -04:00
swung0x48andClaude Fable 5.1 2bd86664ec [docs] (P6.5): the design for the first wave - all-TCP transport, WSL client to adb-device server
ROADMAP gains the section "the immediate next item": a design, not an
implementation, for running the frontend on an x86_64 WSL process and the
backend on the Redmi over TCP, with the integration lane and the CI retrace
subset as the acceptance. The P6.5 row now points at it.

What the design rests on, verified in the tree: the control plane already
treats the rendezvous as a NAME with two ordered connections (SocketTransport),
ClientSession::StartOverSocket already separates "how the socket came" from the
handshake, MGPBlobRef addresses kSegStage only through one ResolveOrFatal, the
reply header and the event heads are already wire-shaped, LogLine exists in
CtrlMsg with no producer, goldens are shared between desktop and device, and
the trace APK can already exec libMobileGLServer.so from nativeLibraryDir.

What it does not rest on, stated rather than assumed: ILink is declared and
unused beyond LinkProgress, ShmLink does not exist, both sessions hold
SessionSegments directly - the lk seam body from the end-state review was never
built and is this wave's first package (lk2). The manifest has no INTERNET
permission.

The mechanism: StreamLink as mirrored private segments replicated by messages -
same sizes both ends, same offsets, so the codec, the watermark rules, the apply
thread and the encoder do not change; RingControl becomes Progress frames sent
on flush-on-idle (the recorded amendment to "appliedSeq is never lazy": late by
at most one flush, never early); replies become seq-stamped messages; the event
ring is mirrored with the P5e blocking rule intact. Cross-architecture makes
the PipeFields.def layout digest mandatory (wf). Server logs on another machine
make LogLine forwarding mandatory (lf) so the 34 server-log readers stay
unchanged. A --serve supervisor forks one child per session on the device,
started by a foreground Service in the trace APK.

Packages lk2 -> wf -> ct -> sl -> lf -> sv -> t65, each with red-once; the gate
list, the mandatory numbers (kWaitReply per frame x RTT, SEG_STAGE bytes/frame
against the link, PRESENT_CREDIT 1..3), the two-sided configuration runbook and
the risks (RTT per reply row, single large uploads, AP isolation) are in the
section. check_doc_citations: 74 citations, 0 problems.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-22 03:04:50 -04:00
swung0x48andClaude Fable 5.1 2d86e07ab6 [docs, MG_Remote] (P6->P6.5): the end state is TCP across machines, and the transport stack has two axes
The end state is re-ruled: client and server may sit on different machines,
OSes and architectures, joined over TCP. The AVF pVM / AF_VSOCK end state the
P6 end-state review assumed is withdrawn (retraction at its head, form D added
to its table, the vsock probe and both external unknowns struck).

The transport stack becomes two independently selectable axes, negotiated in
the handshake and mixable: control plane (ITransport: fork / unix:<path> /
tcp://host:port) and data plane (ILink: ShmLink / StreamLink). On one machine
control over TCP with data over shared segments is a legal pair; ShmLink brings
its own AF_UNIX aux rendezvous for SCM_RIGHTS, so ITransport narrows to control
frames. `auto` is decided by a successful segment delivery, never by inspecting
addresses, and a fall-back is named. Nothing above Transport/ may branch on the
link kind. ARCHITECTURE.md gains 11.9 for this; CONTRACT-P6.md gains 10.3.

ROADMAP: P6.5 and Ph get rows (both were referenced by the contract and absent
from the stage table); the IPC track becomes P6 -> P6.5 -> Ph -> P12 -> P9 ->
P10 -> P11(same-machine arm). Every later row is reconciled against the tree:
items already landed are struck (client vertex arrays, client-minted query
handles, credit default 1, SEG_EVENT overflow mechanism), the unreachable P7
gate (`nm | grep glslang` on a server image that IS libMobileGL.so) is replaced
by the 184-symbol ratchet share, fixed-width wire form moves from P7 to P6.5,
P12 is cut down per the review (server-owned display, no Surface passing), and
the debt table's stale claims are corrected: class C is down to two slots, not
15 and not 511; PACK-PBO and the 2 MiB reply cap are P9's, not P6's.

Verified against the tree and recorded honestly: the contract's three hs rows
(LinkTerms, Refuse, the fingerprint split) never landed - protocol.fbs has
neither - so CURRENT_STAGE_PROGRESS.md's claim that S6 ran red is withdrawn and
the rows move to P6.5; the 184-symbol ratchet gate does not exist in CI; the
server process never initialises PipeStats, so gate 8's `srv=0 srvpark=0` is a
structural zero (fix in progress in the tree, not in this commit).

check_doc_citations.py: 159 citations, one pre-existing basename ambiguity.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-22 02:17:18 -04:00
swung0x48andClaude Opus 5 71aa995128 [MG_Util, MG_IntegrationTest, CI] (P6): the readers the role split left behind
The per-role log split renamed BOTH halves so that an un-updated reader would
fail loudly instead of silently reading half a session. It worked: CI found
four readers this way. This is them.

- MG_Util/Debug/Log.h: the role vocabulary now exists in the PULL build too,
  header-only. It was wholly inside #if MOBILEGL_BUILD_DISAGGREGATED, so
  PipeInputsTest - which builds in the verify flavour - could not name
  ReadRoleLogs and took the whole build-linux-verify job down at compile time.
  Inline rather than out-of-line because of G1: nothing in the library calls
  these, so an inline definition emits code into the readers and NOTHING into
  libMobileGL.so. Verified: pull symbols 30570 -> 30570, 0 added / 0 removed,
  .text still 0xa52203, and zero role-log symbols in the pull library.

- PipeStatsWindow.h: the harness copy of the naming rule is now flavour-aware.
  It derived `.client` in BOTH flavours, so in the verify build - one role,
  MOBILEGL_LOG_FILE_PATH written unchanged - it opened a file that never
  existed. The copy has to stay a copy: MG_Util's RoleLogPath is `t` (local)
  in the shipping .so this module links, so calling it does not link.
  Added LogMark/MarkLaneLog/ReadLaneLogSince: one offset PER ROLE, because a
  single scalar over the concatenation slides by whatever the other role wrote.

- The four arming scenarios: they asserted on lines the BACKEND emits, and
  under inproc the backend runs on the apply thread - the server role - so the
  line lands in the server's log. Reading only the client's half reported the
  emulation unarmed, i.e. accused the product of a defect the reader invented.
  Four copies of the same private helper pair now delegate to the harness.

- scripts/ci/magma_runahead_checks.py: it unlinked and read the base name as
  if it were a file, so the negative arm saw an empty log and could not prove
  the knob took. It now imports split_log_paths' derivation - the authoritative
  one - rather than becoming a third copy.

Local verification (WSL, lk-split + c6-pull):
  - the 4 CI-red entries: 10/10 PASS under inproc, 10/10 under monolith
  - unit role-log readers: 510/510 PASS
  - magma_runahead_checks negative: run_ahead_0 EXPECTED_RED, restored GREEN
  - the 5 affected TUs compile clean with MOBILEGL_BUILD_DISAGGREGATED=0
  - G1: 0/0/0/0, .text 0xa52203

Red-once is the CI run itself (35677991453), which failed for each of these
reasons before the change.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-22 00:37:39 -04:00
swung0x48andClaude Opus 4.8 98d0b96cbe [docs] (P6): the roadmap and the current-stage doc record P6 as landed-not-closed
All ten P6 packages (a6/c6/lk/so/sm/cp/hs/dl/st/t6) are on feat/disaggregated
through 16bfab10. The two docs now say so honestly:

- ROADMAP.md (cumulative): the status line, the P6 stage row, and a new
  milestone bullet record every package landed, exit-gate items 1-6 met, and
  items 7 (device paired A/B in one thermal window) and 8 (the three mandatory
  perf numbers) still pending -- so P6 is "implementation complete, exit
  perf/device numbers pending", NOT closed.
- CURRENT_STAGE_PROGRESS.md: rewritten to hold ONLY the current stage. All
  P5* history is gone (it lives in ROADMAP.md and the P5* reports); what
  remains is P6's package table, the CONTRACT-P6 section-9 gate with each
  item's honest status, the device results, the per-role log split, and the
  explicitly-not-P6 list.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-09-21 22:02:15 -04:00
swung0x48andClaude Opus 4.8 16bfab1032 [MG_Remote] (P6/dl): record the Session::Fail funnel as landed in the contract
§5.2 gains a LANDED note: the three steps (the FatalFamilies.def vocabulary,
the SessionFail funnel that byte-identically routes ~90 aborts through one
place, and the SessionFault frame that names the family to the peer), and the
one deliberate deviation from the prose - seq/op are not threaded through the
90 sites because the message already names the op, so the frame carries code,
family and message rather than a field that is always zero.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-09-21 21:52:18 -04:00
swung0x48andClaude Opus 4.8 91d0cb78c7 [MG_Remote] (P6/dl): a dying session names itself to the peer
Step three of CONTRACT-P6 5.2, the funnel's whole point: instead of the peer
reading a bare EOF and guessing, the session publishes a SessionFault frame
that names the family before it aborts.

THE WIRE CHANGE IS D2's, exactly: `table Fatal` appends `family: string`,
append-only, so an older peer still reads `code` and `message`. `code` stays
the coarse seven-value projection; `family` carries the full word.

SessionFail publishes it before the abort, on whichever session's control
plane is active - the client has a ClientSession, the server a ServerSession,
so under spawn the frame reaches the far side whichever role is dying. Under
inproc both exist and it goes to an in-process transport the aborting process
will never read, which is harmless and cheaper than a special case that would
then be the untested one. Best-effort by nature: this thread is about to die,
so a send that blocks or fails changes nothing.

seq/op from the prose are NOT threaded through the 90 sites: the message
already names the op where it matters, so the frame carries what it can name
honestly (code, family, message) rather than a field that is always zero.

The client recognizes it: RunRemoteSurfaceControlFrame's reply loop, which
already demuxes CapsSnapshot from SurfaceReply, gains a Fatal arm that logs the
family and detail, latches device-lost from it, and returns transport-closed.
A server that DETECTS a fatal condition and aborts itself now tells the client
why; a kill -9 still bypasses abort entirely and is caught by dl's hangup
witness instead - the two cover the two ways a server can die.

The census learns SessionFail: a SessionFail call, like a WireLogFatal call,
must carry a Fatal{ word in its string, so the enum and the string cannot
disagree. FatalFunnel.{h,cpp} join the funnel exemption. Baseline is 4 aborts.

FatalFamilyTest gains the wire round-trip: every family's frame carries its
word and its projected code across encode/verify/decode.

G1 re-measured after the schema change: 0 symbol diff, .text unchanged at
0xa52203. Unit 2359 (one pre-existing environmental failure), integration-split
186/186, integration-spawn 102/102, retrace 6/6, census 0 unmarked.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-09-21 21:51:50 -04:00
swung0x48andClaude Opus 4.8 5968863fb9 [MG_Remote] (P6/dl): every session death goes through one funnel
Step two of CONTRACT-P6 5.2. The ~90 scattered `MGLOG_F("...Fatal{...}"); std::abort();`
pairs under MG_Remote/ become one call each to SessionFail(MGFatalFamily, fmt, ...),
which logs, echoes to stderr, counts, and aborts in one place. a6's census
found no single chokepoint existed; now there is one, and step three hangs the
SessionFault-to-peer publish off it.

THE MESSAGE STRING IS PASSED VERBATIM. The contract requires the log lines, the
CI greps and every red-once byte-identical, so SessionFail does not compose the
line from the family - it takes the SAME string the site handed MGLOG_F and
forwards it unchanged. The family enum rides alongside, redundantly, so the
funnel has the coarse wire FatalCode without parsing the string. The census now
checks that redundancy the way it checks WireLogFatal: every SessionFail call's
string must carry a Fatal{ word, so the enum and the string cannot silently
disagree.

The conversion was mechanical - 89 sites by a transform that injects the family
as MGLOG_F's new first argument and drops the trailing abort - with three sites
fixed by hand that the transform would have broken: a stub macro, and two
if/else-then-shared-abort blocks (PersistentMapTracker's adopt-tier and
SurfaceOpCodec's three surface-error branches) where a naive rewrite stole the
abort from the earlier branches and would have let them fall through. The
death tests are the safety net for byte-identity, and every one stayed green.

Four std::abort() remain under MG_Remote/, all inside the two funnels
(WireLog.cpp, FatalFunnel.cpp); the census exempts both files because their
callers carry the family word, and its baseline drops from 93 aborts to 4.
SessionFaultCount() is the one telemetry point S8 will assert zero over a good
run.

G1 re-measured: 0 symbol diff, .text unchanged at 0xa52203 (FatalFunnel and
FatalFamily live under MG_Remote/, compiled only in the disaggregated build).
Unit 2358 (one pre-existing environmental failure), integration-split 186/186,
integration-spawn 102/102, retrace 6/6, census 0 unmarked.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-09-21 21:44:17 -04:00
swung0x48andClaude Opus 4.8 f98f2067db [MG_Remote] (P6/dl): the Fatal-family vocabulary as a table, projected onto the wire's seven codes
CONTRACT-P6 5.2's D2 ruling, step one of the Session::Fail funnel: the internal
vocabulary before the funnel that routes through it.

a6 censused thirty family words against a seven-value wire FatalCode, so
Session::Fail(FatalCode, detail) cannot carry the vocabulary in its first
argument - the word would collapse to one of seven and the log would say
ProtocolCorruption where the code said UnmigratedVerb. FatalFamilies.def is the
internal enum; the wire keeps FatalCode; each row carries the coarse code the
PEER is told when that family ends the session.

THE PROJECTION IS A TOTAL TABLE, NOT A SWITCH WITH A DEFAULT. This build has no
-Werror anywhere, so a default arm would silently swallow a family added
without a code. A row IS the arm; a family with no row is not a value of the
enum. FatalFamily.h generates the enum, the projection and the name from the
one .def, so a family, its word and its code cannot drift apart.

The buckets are documented per row in the .def: ProtocolCorruption for
malformed records / unimplemented verbs / role invariants / reply-contract
breaks; RingOverrun for a ring or event channel overrun; SegmentMismatch for a
segment too small for what a role must place in it; AbiMismatch for layout or
version disagreement; ServerCrashed for the liveness ends a WAITING peer
attributes to the other side. DeviceLost gets no row on purpose - it is armed
from the doorbell (5.3), never raised as a Fatal, and a test asserts no family
projects onto it so an abort can never masquerade as a device loss.

Five tests, all walking the table so a new row is covered without editing them:
count agreement, every family projects to a non-None code, none projects onto
DeviceLost, names distinct and non-empty, and a handful of anchors pinned by
meaning so a bulk-edit drift is caught.

No call site changes yet; the funnel that uses this is the next step.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-09-21 21:33:05 -04:00
swung0x48andClaude Opus 4.8 b3155525e8 [MG_Util, MG_Test, MG_IntegrationTest, CI] (P6): one log per role, and every reader moved with it
The spawn work had the two roles append to one MOBILEGL_LOG_FILE_PATH under
O_APPEND. It was correct - two processes at one offset would corrupt the file,
O_APPEND made each write atomic - but it put two sessions' lines in one place
and made every per-side assertion a search. This splits the sink: the client
role writes <base>.client.log and the server role writes <base>.server.log.

THE BASE NAME NAMES NO FILE ANY MORE, AND THAT IS THE POINT. Leaving the
client at the old unsuffixed path would have been the compatible choice and the
wrong one: a reader that was not updated would go on finding a file, go on
passing, and go on seeing only half the session - and a refusal census that
reports a confident zero for the half it cannot see is worse than one that
fails. With both names moved, an un-updated reader gets "file not found" and
says so. There were 34 such readers; every one is moved here.

THE ROLE IS PER-THREAD, not per-process, because under inproc both roles are
threads of one process. Log.cpp keys the sink on a thread-local role: the apply
thread declares itself server (ServerLoop.cpp), a spawned image is server for
its whole life (MOBILEGL_IPC_ROLE=server, read once), and everything else is
the client. The naming rule (RoleLogPath) and the two whole-log operations
(ReadRoleLogs / TruncateRoleLogs) are EXPORTED from the library, so no reader
reimplements the derivation - a second copy is the copy that falls behind.

Readers, by how they read:
 - unit mains set MOBILEGL_LOG_FILE_PATH and read a role file: they keep the
   base in the env and derive the client path from the library helper.
 - the death-test child runners (ReadLog) now concatenate BOTH roles: a death
   test asserts the CHILD said something, and the applier's refusals - the very
   diagnostics these check - are written under the server role.
 - the offset-based Emit readers derive the client path once after setenv.
 - PipeStatsWindow reads both, because draws/vbs increment in the backend's
   PrepareForDraw - the apply thread, the server role - so the summary line is
   in the server file even under inproc.
 - run_trace_case.cmake's split census reads both files; the client keeps the
   transport markers.
 - split_log_paths.py (and its self-test, and the control stub) derive both
   role files from the declared base.
 - the Android script pulls both role files off the device and concatenates
   them, so every downstream check is unchanged - and it judges a role file by
   CONTENT, because `run-as test -f` through `exec-out` returned 0 for a missing
   file on the device and `exec-out` folds cat's own not-found line into stdout.
   The monolith arm legitimately has no server file, and that is a silent skip
   rather than a one-line server log.

Guarded so a pull build is untouched: RoleLogPath and the role sink are wholly
inside MOBILEGL_BUILD_DISAGGREGATED; a non-disaggregated build writes the base
path exactly as before. G1 re-measured - 0 symbol diff, .text unchanged at
0xa52203.

Verified on device 2f7cbe2e: monolith writes only the client log (no phantom
server log), inproc and spawn each write both and pass their transport proofs
(spawn: server role in pid 16125). Unit 2353 (one pre-existing environmental
failure), integration-split 186/186, integration-spawn 102/102, retrace 6/6,
control smoke 12/12, split-log-paths self-test 9/9.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-09-21 21:26:05 -04:00
swung0x48andClaude Opus 5 8cd00f42fd [MG_IntegrationTest, CI] (P6/t6): integration-spawn, and the set identity made structural instead of maintained
Exit gates 9.2 and 9.3. Until now nothing ran the integration suite across a
process boundary at all - the spawn shape was proven only by the retrace lane,
which exercises one trace per case and no scenario assertions.

integration-spawn: 102 cases, 102 green.

THE SET IDENTITY IS THE POINT, AND IT IS NOT MAINTAINED BY HAND. 9.2 asks that
the spawn lane's case-name set equal the split lane's. Registering the spawn
arm as a second copy of each block would satisfy that today and drift the first
time somebody adds a scenario to one of them - and a spawn lane covering LESS
goes green while proving less, with nothing about a smaller green lane looking
wrong. The eleven split-environment blocks become eleven calls to one macro
that emits BOTH arms from one filter, so a case added to either is added to
both or to neither.

scripts/ci/spawn_lane_parity.py asserts it anyway, because a macro is one edit
from a hand-written block. It compares SETS rather than counts - a count can
agree while the membership does not - and carries exactly one sanctioned
asymmetry, named in the file: integration-split also labels the PUSH-MONOLITH
arm, whose scenario is monolith-only by construction. R-16: introduce a
split-only block and it reds naming the case and the macro to use.

THREE CASES SKIP UNDER SPAWN, BY NAME. CtWireScenario reads PipeApplier's
in-process tallies through ServerVerbs(); under spawn those live in the SERVER's
process and this one's copy is 0 forever, so the assertions were failing about
somebody else's memory. That is a harness limit, not a product defect - the
records themselves cross, which the retrace lane proves. They are SKIPPED and
not deregistered: a case dropped from the registration would make the two sets
differ silently, which is the drift the macro exists to prevent. What retires
the skip is cross-process telemetry, which is also what S8's SessionFaultCount
needs.

TWO REAL REGRESSIONS THE EXISTING GATES CAUGHT, both from this refactor:

  * the macro dropped the per-block TEST_LIST variables, which were what
    SplitLogPaths fed to give every entry a PRIVATE MOBILEGL_LOG_FILE_PATH.
    SplitLogPaths.PrivateAndDistinct went red naming the first orphan. The
    macro accumulates list NAMES now, so a block added later is covered without
    anyone remembering to extend a list - and the names have to be unique,
    because gtest_discover_tests' TEST_LIST is populated when CTEST runs, not
    at configure time, so one shared variable held only the last block's
    entries. That matters more on the spawn arm: there TWO PROCESSES append to
    the path, so a shared file interleaves two sessions rather than merely
    being ambiguous.

  * the configure_file that substitutes those names ran BEFORE the F1 and Ct
    blocks registered, so it captured neither. Same gate, naming
    F1WireScenario.ClearBufferfiPixels. It now runs last.

junit_tally gains --require-spawn-ran beside --require-split-ran: the prefix IS
the arm, and a shared flag would let one lane tally the other's entries and call
itself run. Verified to discriminate - the spawn junit reads 96/0/5 under its
own flag and 0/0/0 under the split flag, which correctly fails.

Two death tests follow the ADOPT_TIER message the census commit retagged with
Fatal{UnimplementedAdoptTier}; their regexes asserted the old wording.

Unit 2353 (one pre-existing environmental failure), integration-split 186/186,
integration-spawn 102/102, retrace 6/6, fatal census 0 unmarked, G1 0 symbols
and .text unchanged at 0xa52203.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-21 20:20:24 -04:00
swung0x48andClaude Opus 5 e50463dc5c [MG_Remote, CI] (P6/dl): the Fatal census gate, and the one death under MG_Remote that named nothing
Exit gate S7, and the precondition for CONTRACT-P6 5.2's funnel rather than
its replacement.

S7 says "a bare abort() added outside Session::Fail -> the census gate goes
red". Session::Fail does not exist: it is the 93-site refactor 5.2 describes,
and it is not in this commit. What IS checkable today is the property that
funnel exists to guarantee and that every consumer already depends on - every
death under MG_Remote/ names a FAMILY, in a Fatal{Word} marker a grep can
find. run_trace_case.cmake reds a split retrace on any `Fatal{` line, the
retrace lane's refusal census counts them by name, and MEASUREMENTS quotes
the distinct words. A death with no word is invisible to all three.

TWO RULES, BECAUSE ONE WOULD LAUNDER THE OTHER. An abort must carry a marker
within twelve lines; and every WireLogFatal call must carry one in its format
string. WireLog.cpp's own abort is exempt from the first rule ONLY because its
five callers satisfy the second - a funnel that accepted an unmarked string
would be a hole shaped exactly like the rule.

THE BASELINE BOUNDS SILENCE, NOT DEATHS. Abort sites may grow freely; a new
family word may not appear unrecorded. Freezing the total would make every new
guard a gate change, which is how a gate stops being run. The wire's FatalCode
has seven values and the internal vocabulary is thirty-two, which is the
divergence D2 exists to bound - so growing it has to be an act, not an
accident.

THE CENSUS ALSO CORRECTS ITSELF. Its first run reported WireLog.h's own PROSE
as an unmarked death: the comment explaining why the stderr echo exists
contains the words std::abort(). So the scanner strips comments before
matching, with a character-level pass rather than a regex - a `"http://"`
inside a string literal is not a comment - while KEEPING string literals,
because the markers it looks for live in them. Real numbers after that fix:
93 abort sites, 32 family words, 0 unmarked. a6 had counted 92 and 30 from a
scan that did not make the distinction.

AND THE ONE REAL FINDING. a6 named two aborts with no marker at all;
WireLog.cpp's is the sanctioned funnel, so the genuine one is
PersistentMapTracker's invalid-MOBILEGL_IPC_ADOPT_TIER death. It now carries
Fatal{UnimplementedAdoptTier}, which is what makes the census zero.

R-16 both ways, run: a bare std::abort() reds it naming the file and line, and
a new family word reds it naming the word and how to record it.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-21 19:42:18 -04:00
swung0x48andClaude Opus 5 743d1facba [MG_Pipe, MG_Backend, MG_Impl] (P6/sm, P6/st): four guards that were compiled in and could never arm, and the crash behind one of them
CONTRACT-P6 3.2 (D1c), 3.3 (D13) and 3.4 (D10).

Every guard below asked a question a SERVER PROCESS answers wrongly - "is a
ClientSession active" (never, there) or "am I on the apply thread" (every
thread is, there) - so all four were present, compiled, and permanently
disarmed in the one shape they exist for. That is worse than absent: it reads
as coverage.

D13 FIRST, THEN THE WIDENING. MGPipeRoleSplitActive() meant "the REHEARSAL
knob is on AND the transport is real", so widening it in place would have left
a narrow name describing a wide predicate. It is renamed to
MGPipeRoleSplitRehearsalActive() across its 12 sites - including the
DualBlockScenario assertion message that embeds it - and the wider predicate
is introduced BESIDE it.

MGPipeBlocksAreDistinct() IS TRUE FOR TWO DIFFERENT REASONS, which is the
whole point: under the rehearsal the two blocks are distinct objects in one
process; under SPAWN they are distinct because they are in different ADDRESS
SPACES, and no knob is involved. The spawn retrace runs with
role-split-state=0 - measured off the lane's own log - so every guard gated on
the rehearsal was off there.

THE CRASH. MGPipeServerBlockNoteIdentity early-returned on the rehearsal, so a
spawn server's gPipeInputs.ContextIdentity() stayed nullptr for the life of the
process. DirectGLES' framebuffer binding-slot memo compares that identity FIRST
and with NO generation, against a cache variable that also starts nullptr - so
nullptr == nullptr reads as a CACHE HIT and the function returns a slot pointer
nothing ever filled. `sm` widens the gate; `st` lands the named Fatal
PipeInputs.h had already asked for, so a reopening says which memo and which
identity instead of corrupting memory three frames later. Guarded on
MOBILEGL_PIPE_PUSH: in a pull build that identity is the live GLContext's
address and is never null, so the test would be dead code and G1 measures that.

DISJUNCTS, NOT SUBSTITUTIONS - and this was measured the hard way. The first
attempt REPLACED OnApplyThread() with MGPipeServerArm() and
ClientSession::Active() with MGPipeSessionLive(). 14 RemoteGuards and
RemoteClientControls cases went green by omission: a ServerLoop fixture with no
client session has only the original facts, so swapping them out disarmed every
test that drives the apply thread directly. The originals stay; the new
predicates are added beside them.

AND THE PROBE HAD TO BE THE RIGHT ONE. Installing
ClientSession::ApplyThreadIsInsideApplier as the apply-thread probe made every
GL-thread call a role violation whenever the applier happened to be busy - the
inproc retrace died on Fatal{RoleViolation, "MGPipeSlots"} raised from the GL
thread. "Am I the apply thread" and "is the apply thread inside the applier"
are different questions; the second is R-1's mutual-exclusion probe and is
about another thread entirely. ServerLoop::OnApplyThread is the one the guards
mean.

Three of D1c's six predicates land here, the three the four guards need. The
other three (MGPipeSplitActive, MGPipeShouldDial, MGPipeBackendIsLocal) have no
D10 site and are not added as dead code; their call sites are ContextEpoch and
ActiveXfbState, which this commit does not touch.

D14 holds: the non-disaggregated build gets constexpr false definitions, not
runtime-false predicates, so every consult folds at compile time. G1
re-measured - 0 symbol diff, .text unchanged at 0xa52203.

Two test names added, both falsifiable by construction: the spawn case asserts
the blocks are distinct with the rehearsal knob OFF, and the monolith case
asserts the predicate is not simply a constant. Unit suite 2353 tests, one
pre-existing environmental failure. All six OpenRA arms green.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-21 19:38:19 -04:00
swung0x48andClaude Opus 5 570ebde9bc [MG_Remote] (P6/hs): the build stamp that was silently empty, and two asymmetries the handshake never checked
CONTRACT-P6 4.2 and 4.3. Three defects, all of them things the handshake
believed it was checking and was not.

1. THE BUILD STAMP WAS "" AND NOTHING SAID SO. CMakeLists took the git hash
   through an execute_process with NO RESULT_VARIABLE, so a failed
   `git rev-parse` yielded the empty string. Verified live rather than
   inferred: this worktree's `.git` is a file holding a WINDOWS path, WSL's
   git answers `fatal: not a git repository`, result 128 - and every WSL build
   mixed "" into its ABI fingerprint. Two builds from different commits then
   agreed exactly, which is the one thing the stamp exists to prevent. The
   already-failing SessionHandshakeTest was reporting this the whole time.

   The fix may NOT touch GIT_COMMIT_HASH_SHORT: it is baked into
   glGetString(GL_VERSION), so redefining it changes an application-visible GL
   string and the pull build's .rodata - a behaviour leak and a G1 break at
   once. MGGitHash.h.in gains a SECOND pair instead, consumed only by the
   fingerprint, plus -DMOBILEGL_BUILD_STAMP for trees git cannot read (CI has
   ${GITHUB_SHA} in hand). A stampless build is now a configure-time WARNING
   naming the consequence, not silence.

   MOBILEGL_BUILD_STAMP_PRESENT IS MIXED AS ITS OWN FIELD. "this build cannot
   name its commit" and "this build's commit is the empty string" are different
   claims, and collapsing them is how every stampless build in the world agreed
   with every other. The test asserts the flag moves the fingerprint in EITHER
   build state, and the `BuildStamp = ""` perturbation is now guarded - in a
   stampless build production's value already IS "", so that assertion was
   passing while proving nothing.

2. THE CLIENT NEVER READ abiMajor/abiMinor. Hello has carried them since P5
   and the SERVER checks them; the client compared only the fingerprint. The
   fingerprint mixes AbiVersion so a mismatch would fire anyway - but as
   "struct shapes", which sends the reader looking for a layout change that is
   not there. Under spawn the peer is a SEPARATE IMAGE the operator chose with
   MOBILEGL_IPC_SERVER_PATH, so this is exactly the failure that needs its own
   sentence. Both handshake sites call one helper; there are two sites, and
   only one of them was reachable before `sm`, which is how the gap survived.

3. Hello::pid WAS 0 AND Welcome::serverPid ECHOED IT. So both were always 0 and
   neither named anything, while §9.5's arm-proof gate wants exactly the child
   pid. Both now carry real ids, and the pair is the cheapest arm proof in the
   protocol: under spawn they MUST differ, and a same-process session cannot
   produce two different values. The client keeps what the server STATED -
   local launcher knowledge is a different fact from one that crossed the wire,
   and only the second can be asserted from the server's own mouth.

R-16 both ways: revert serverPid to echoing hello->pid() and the new test reds
on both halves, naming 4.3. G1 re-measured after the CMake and header changes:
0 symbol diff, .text unchanged at 0xa52203.

Unit suite goes from two long-standing failures to one - the remaining
PipeCatalogue.FrontendNeverTakesAnApplierAddress is an environmental path
problem in this tree, unrelated. All six OpenRA arms still green.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-21 19:21:43 -04:00
swung0x48andClaude Opus 5 e766351299 [MG_Remote, MG_Impl] (P6/dl): the device-lost latch, taken from a descriptor and never from a deadline
Before this, CONTRACT-P6 5.3's own sentence held: "a dead server leaves the
client silently DECLINE-ing every verb forever with glGetError clean".
FatalCode::DeviceLost had zero producers and zero consumers and
glGetGraphicsResetStatus returned GL_NO_ERROR unconditionally, so an
application had no way to learn that the process holding its GPU objects was
gone. Measured cost of that: a server killed on its first Clear left the
client waiting out the full 120 s barrier and reporting Fatal{BarrierTimeout}
- the wrong diagnosis, two minutes late. It now notices in 0.01 s.

THE MACHINERY WAS ALREADY THERE. Doorbell::Wait breaks out on Dead(),
SessionProducer::Park turns that into SessionWait::ShutDown, and ClientSession
already had the named DECLINED path. What did not exist was the death FACT:
D5c's finding is that the client parks on clientBell[0] and rings ITSELF
through clientBell[1], holding both ends, so EOF can never arrive on the one
descriptor it watches. A bell that can wake itself cannot hear a death.

SetDeathWitness(fd) fixes that with no new descriptor: the control socket's
far end is held only by the server. The subtlety is that the bell must watch a
socket it must NEVER read - the transport's reassembler owns those bytes and a
control reply is not a death. So the witness enters the poll set with
`events = POLLRDHUP` and nothing else: POLLHUP/POLLERR/POLLNVAL arrive in
revents unrequested, so the hangup is seen while POLLIN never is. Nothing is
recv'd from it and its ownership stays with SocketTransport.

Dead() AND PeerHungUp() ARE TWO FACTS. Park sets m_dead for POLLERR, POLLNVAL
and unrecognised revents too - each a fault in THIS process's descriptor - and
CondVarDoorbell::Kill() sets it on every orderly Stop(). A latch taken from
Dead() would report a lost GPU for a local fd bug and a context reset for
every clean exit, so only PeerHungUp() arms it.

GL_UNKNOWN_CONTEXT_RESET, not GUILTY or INNOCENT: those assign blame, and the
server died for a reason that never crossed the wire.

D5b, in the control-reply wait, which had the right comment and no code: EOF
on the control stream is device loss; a TIMEOUT with the socket still open is
"ALIVE BUT SILENT" and says so by name. 5.4 forbids calling a frozen or merely
slow peer dead, and under P5e run-ahead a server one frame behind is the
INTENDED steady state - a latch armed by a deadline would fire on a healthy
session under load.

MOBILEGL_IPC_RESPAWN is now a NAMED REFUSAL rather than a variable nothing
reads. The latch is one-way on purpose: every handle this client minted names
an object inside the server process, so recovery means re-pushing the world.

THREE TEST NAMES ADDED, none renamed (G14), and R-16 run both ways:
  * remove the witness -> AKilledServerLatchesDeviceLostFromTheHangupAndNot-
    ADeadline goes red, takes 2 s instead of 0.01 s, and names D5c.
  * collapse PeerHungUp() into Dead() -> ADeadBellIsNotAlwaysAHungUpPeer goes
    red naming the local-fd-bug consequence.
  * AnOrderlyStopIsNotADeviceLoss stays GREEN under that collapse, and its
    comment now says so. The first draft claimed it was the control for it;
    running the falsification proved otherwise - under spawn the self bell is a
    SocketDoorbell and Stop() never kills one. The comment was corrected rather
    than the claim quietly kept.

G1 RE-MEASURED, NOT ASSUMED: 0 symbol diff against the c6 baseline and .text
unchanged at 0xa52203. That measurement earned its keep - it caught a 16-byte
drift that had nothing to do with dl: P6's O_APPEND log-sink fix was compiling
into the PULL build, where a second process can never exist. Now guarded, and
.text is back to the baseline exactly.

Full unit suite: 2350 tests, the same two pre-existing environmental failures
and no others. All six OpenRA arms (2 backends x monolith/inproc/spawn) green.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-21 18:49:56 -04:00
swung0x48andClaude Opus 5 15bd9a676c [CI, android-plugin] (P6): CI starts a second MobileGL process on a device
The Android retrace matrix gains a third lane, spawn-acceptance, beside
monolith-control and inproc-acceptance. Until now nothing in CI had ever
started a second MobileGL process on a device at all.

The apk.yml retrace job already carried a `transport` matrix dimension and
already branched on it, so the lane itself is three edits: a row in
github_transport_matrix, an elif in the retrace step, and a summary to render.
What needed thought was the gate.

THE SPAWN LANE IS APK-ONLY, and that is a statement about where evidence is
missing rather than about what spawn can do. Linux already has
test.yml's `retrace-split`, which is {backend, case, transport} over inproc AND
spawn with the two negative controls that make it mean anything. A spawn row in
the Linux transport matrix would pay for a second full sweep proving nothing -
and test.yml's `retrace` job stages no server image, so the lane would not
merely be redundant, it would be red. self_test_transport_matrices now asserts
the absence in both directions, because an accidental removal of the `if apk`
has to be caught in the self-test rather than in CI.

--require-spawn REQUIRES TWO SENTENCES, and the second is the one that matters.
ConfigLoader's marker proves the VALUE RESOLVED - it exists only in the Spawn
arm, which exists only under MOBILEGL_BUILD_DISAGGREGATED - but that is a
statement about a parser. `spawn ARMED - the server role runs in pid N` is
written only after the launch, the connect and the handshake have all
succeeded, and the pid in it is the SERVER's. It is the only line in the log a
same-process run cannot produce.

Both halves red once, measured:
  * a monolith run demanded to prove spawn: REFUSED, transport_resolution_marker
    false, server_pid null - while the retrace itself scored ssim=1.000000,
    which is exactly the trap. OpenRA matches its golden under monolith too, so
    the picture has never been the evidence.
  * the same run's real spawn log with the one ARMED line deleted: REFUSED,
    transport_resolution_marker TRUE and server_pid null. That is the
    "resolved the transport and then never left the process" case, isolated.

THE PROOF USES `any` WHERE THE inproc GATE USES `all`, and the difference is
load-bearing rather than a relaxation. Under spawn two processes append to one
MOBILEGL_LOG_FILE_PATH, and the launcher deliberately scrubs every
MOBILEGL_IPC_* from the child's environment (anti-recursion catch (b)) - so the
server's own `Config: IPC` line reads strict=0 role-split-state=0 BY
CONSTRUCTION. Demanding every line match would red every spawn run for the one
thing the design requires.

--use-pbuffer is not optional on this lane: until P12 a spawned server cannot be
handed a window, because an ANativeWindow* is a pointer into the CLIENT's
process (Rule H). MOBILEGL_IPC_SERVER_PATH is deliberately NOT passed -
nativeLibraryDir carries an install-time hash that nothing off the device can
spell, and the Activity resolves it.

The local runner now passes the same knobs and the same --require-* flag CI
does, so "it works locally" can no longer mean "it ran monolith locally". That
change immediately caught its own omission: the first local run with the gate
armed failed on client_ipc_line_present=false because the runner had been
sending MOBILEGL_TRANSPORT alone.

Verified on device 2f7cbe2e: OpenRA.DirectGLES spawn, ssim=1.000000,
mismatchPixels=0, "real spawn transport, server role in pid 9885, and zero
Fatal records confirmed".

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-21 18:30:18 -04:00
swung0x48andClaude Opus 5 2afa000295 [MG_Remote, android-plugin] (P6): a real phone retraces a real trace across two processes
OpenRA.DirectGLES, transport=spawn, on a Redmi: ssim=1.000000,
mismatchPixels=0, zero Fatal{ lines, three runs for three. The server is a
process the client launched out of the APK's lib/arm64/, and the client's own
log names its pid.

Four things stood between the desktop green and the device green, and every
one of them was invisible on desktop for the same reason: a build tree is not
a deployment, and Linux is not Android.

1. THE SERVER COULD NOT LINK. It links libMobileGL.so and is EXEC'd, not
   dlopen'd, so it gets a fresh linker namespace with the DEFAULT search path
   - and an APK's lib/<abi>/ is not on it. `CANNOT LINK EXECUTABLE ...:
   library "libMobileGL.so" not found: needed by main executable`, before a
   single line of MobileGL ran. On desktop CMake had been giving the target an
   absolute build-tree RPATH, so the WSL server resolved its dependency
   through a path no phone has. $ORIGIN is asked for via BUILD_RPATH (a raw
   -Wl,-rpath,$ORIGIN reaches the generator unquoted and the SHELL eats it -
   the device linker said `normalize_path - invalid input: "$"`), and because
   the NDK drops RPATH from the link anyway, the LAUNCHER states
   LD_LIBRARY_PATH: it is the one component that has already resolved where
   the image lives, and a pair that is not co-located is not a pair.

2. THE RENDEZVOUS NEEDED A WRITABLE DIRECTORY. An Android app has no /tmp, so
   bind() in the child had nowhere to put the node and the client refused by
   name 20 s later. AF_UNIX endpoints now accept the ABSTRACT namespace with a
   leading '@' - the systemd/D-Bus convention - which has no filesystem
   presence at all: no directory, no mode bits, and no stale node to unlink
   after a crash, which is the bind() failure Listen() has been working
   around. Its reach is the network namespace, which for an app is the app.
   StartSpawned mints '@' names; an explicit path still works everywhere, and
   that is what P12's "connect to something somebody else is listening on"
   will use.

3. PBUFFER WAS A DirectGLES-ONLY KNOB. Twice over: trace-replay-ci.sh gated
   `--ez use_pbuffer true` on the backend name, and the JNI demanded a native
   window for DirectVulkan unconditionally. A surface SHAPE is not a backend
   property, and the coupling mattered because the Android GLWS makes a window
   surface whenever gNativeWindow is non-null - so handing Magma a window was
   the same as asking for one. Until P12 a spawned server cannot be given a
   window at all: an ANativeWindow* is a pointer into the CLIENT's process and
   SetWindowHandle is refused on the way across with Fatal{UnmigratedSurface,
   "AndroidNativeWindow@P12"} (Rule H). Which is exactly what happened, one op
   after the server had come up green.

4. THE RUNNER LOOKED IN ONE OF THE TWO OUTPUT DIRECTORIES. assembleTraceRelease
   writes apk/trace/release; CI has staged the same artifact under
   apk/trace/debug. A tree that has built locally has both, and picking the
   wrong one retraces last month's APK and says nothing about it. Newest of
   either, now.

MEASURED AND NOT FIXED: DirectVulkan on this device diverges under BOTH split
transports and does so nondeterministically - inproc scored ssim=0.988998 /
9836 px, spawn scored 0.976494 / 14658 px and then 0.988998 / 9836 px on a
repeat, while monolith with the same pbuffer surface scores 1.000000 / 0 px.
The two transports draw from the same set of outcomes, so this is the split
path on Magma against a real GPU, not the process boundary: P6 neither caused
it nor can fix it. DirectVulkan spawn IS green on desktop (lavapipe, 1.000000).

G14: one test name added, AnAbstractEndpointNeedsNoWritableDirectoryAndLeaves-
NoFile, which pins both halves - the handshake crosses an abstract name, and
nothing is left on the filesystem. A '@' mistaken for a path would have bound
a file of that literal name, passed here, and failed on the one platform this
exists for.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-21 13:33:57 -04:00
swung0x48andClaude Opus 5 f6a0bd3024 [MG_Remote] (P6/dl): D5c - a bell that can wake itself cannot hear a death
Measured while running the 78-entry spawn matrix, not predicted.

minecraft-1.21.4-fabric-iris-iterationrp-in-world kills the SERVER process
outright on this machine - llvmpipe cannot lower the shader pack's
%llvm.x86.vcvtps2ph.256 and aborts at call 159429 - and the client did NOT
take the SessionWait::ShutDown path, which already exists and is already
correct. It sat out the full 120 s and reported Fatal{BarrierTimeout,
"ResourceRespecify"}: the wrong diagnosis, at two minutes a case, for a
server that had been gone since the first second. The same trace fails in 3 s
under monolith.

The cause is structural and is the price of `sm`'s two-fd bell. The client
parks on clientBell[0] and rings ITSELF through clientBell[1], so it holds
both ends of that socketpair. EOF arrives only when every writer closes and
the client is one of them, so that descriptor can never hang up no matter
what happens to the peer.

`dl` therefore needs a witness descriptor whose far end only the server
holds, polled beside the park fd and never read from, whose POLLHUP/EOF
latches Dead(). The control socket already is exactly that, so no new
descriptor is needed.

This is NOT a defect in `sm`: holding both ends is what self-notification
requires, and without it the server's control pump could not wake its own
apply thread - the bug that cost this branch an afternoon. The mistake would
be assuming one descriptor can answer both questions.

Recorded rather than fixed: it turns no red case green, and the only case
that reaches it fails identically in all three arms for a reason that is not
MobileGL's. `dl` owns the fix and S2 already names the red-once for it.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-21 12:42:03 -04:00
swung0x48andClaude Opus 5 1039502ee6 [MG_Remote, android-plugin] (P6): the device can run the split retrace, and only the app can spell the server's path
Two small pieces, so an Android spawn arm is a flag rather than a project.

THE RUNNER GAINS --transport. It already had a generic env passthrough - one
intent extra carries `K=V;K=V` all the way to setenv before the library is
dlopened - so the transport itself costs one entry and no new plumbing in the
five files between here and the device. monolith passes NOTHING rather than
MOBILEGL_TRANSPORT=monolith, so the default arm's environment stays
byte-identical to what it was before this option existed: a control that
changed when the option landed would not be one.

THE SERVER PATH CANNOT COME FROM THE HOST. Every other knob can, but this one
names a file that must be EXEC-ABLE, and on Android there is exactly one such
place: an APK's lib/<abi>/. W^X has forbidden the app's own data dirs since
API 29, and the packager only puts a file in lib/<abi>/ if it is named
lib*.so - which is why the server executable wears that name, and what P0
spike A proved on two devices. nativeLibraryDir contains an install-time
hash, so no host-side script can spell the path; the process about to launch
the server is the only one that can. TraceReplayActivity resolves it, and
only when the caller actually asked for spawn.

AN EXPLICIT MOBILEGL_IPC_SERVER_PATH STILL WINS. A caller that set one is
pointing somewhere deliberately - at a pushed build, say - and silently
replacing it would make that knob untestable on the one platform where it
matters most.

The APK must be built with -Pmobilegl.buildDisaggregated=ON or none of this
is reachable: without it ConfigLoader has no transport parser, accepts the
value, ignores it (CONTRACT-P5 rule 5), and the run is monolith under a name
that says spawn. The --transport help says so where somebody will read it.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-21 12:34:34 -04:00
swung0x48andClaude Opus 5 94e2f2e0d8 [MG_Remote, CI] (P6): the split retrace lane becomes the whole CI matrix, both backends, both transports
It was one case on one backend under one transport: OpenRA, DirectGLES,
inproc. It is now every CI case, both backends, inproc AND spawn - 154 CI
entries, 156 local ctest entries - because every defect the spawn work turned
up was a question about the SERVER's process and not about any one trace or
either backend.

THE DirectVulkan ARM. tools/trace_replay/CMakeLists.txt carried "a
DirectVulkan arm would be measuring a server nobody has written yet". True
when P5 wrote it; false since P5f/P7 landed Magma's server consumers and its
run-ahead readiness gate. Leaving it would have shipped a split shape whose
second backend nothing ever ran - the same class of hole as a lane that runs
monolith under a name that says split. Magma now brings up a server process
of its own and OpenRA retraces across it at ssim=1.000000, which is only
possible because this branch also taught the child to load its config: before
that, a DirectVulkan session brought up a DirectGLES server and the two
halves disagreed about which backend the capability mask describes.

`split` BECOMES AN OPT-OUT. It began as an opt-in naming one case, because
one case was the work. Marking 39 cases `"split": true` would carry no
information and would reinstate the hole the key was written to close, only
mirrored: a case added later would get the monolith arms and be silently
absent from the split ones, and absent is the one state nothing reds on. A CI
case is now in the subset unless it says `"split": false`, which is a
reviewable claim that a trace cannot cross a role boundary.

THE CI MATRIX GAINS A THIRD DIMENSION. The job took {backend, case} and
hard-coded MOBILEGL_TRANSPORT=inproc in its own run block, so `spawn` had no
way into CI at all; the .SPAWN ctest entries existed only for a local build.
It is {backend, case, transport} now, the backends are the case's own
ci_backends rather than a hard-coded DirectGLES, and the artifact names carry
the transport or the two arms of one {backend, case} would overwrite each
other's uploads.

inproc STAYS AS THE CONTROL. Same library, same codec, same applier, same
picture; the only difference is which process the server role runs in.
Running only spawn would leave "did the transport break it?" and "did the
phase break it?" answerable only together - which is the question every
failure in this phase has turned on, including the SIGSEGV that D1 explained.

BOTH NEGATIVE CONTROLS FOLLOW THE ARM. retrace_pull_library_control.sh and
retrace_drop_draw_control.sh each exported MOBILEGL_TRANSPORT=inproc
themselves, so on a spawn job they would have gone on proving something about
the other arm while spawn ran unguarded. They read SPLIT_TRANSPORT now, and
default to inproc so a caller that sets nothing behaves exactly as before.
scripts/ci/control_smoke_test.sh: 22 passed, 0 failed against the stubbed
ctest, including the two modes that matter most - a red whose SSIM never fell
and a knob that armed and dropped nothing.

The spawn arm needs a second binary and the inproc arm needs none, so the job
places libMobileGLServer.so only on the spawn arm and a missing one is a
named failure there rather than a LaunchServer refusal 78 jobs deep.

Measured locally as this lands: 39 of the 78 SPAWN entries complete, all
green. The rest are still running.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-21 12:31:49 -04:00
swung0x48andClaude Opus 5 ea9fc7fa71 [MG_Remote] (P6/cp): a real trace retraces across two processes, pixel-for-pixel
OpenRA.DirectGLES.SPAWN is green: ssim=1.000000, mismatchPixels=0, zero
Fatal{ lines, against a server in a process the client started by name. The
inproc SPLIT arm stays beside it as the control, so "did the transport break
it" and "did the phase break it" remain separately answerable.

Five defects stood between the handshake and that picture. Each one was
silent in its own way, and none of them looked like what it was.

1. THE DOORBELL COULD NOT WAKE ITSELF. SocketDoorbell's one-fd form sends on
   the end it polls, so a write is delivered to the PEER - correct for waking
   the other process, useless for waking a thread in this one. The server's
   control pump posts into the apply thread's mailbox and must ring the bell
   that thread parks on. Symptom: every eglInitialize crossed, landed in the
   mailbox, and timed out at 5 s. The two-fd form (park on [0], notify on [1])
   is restored here, and the bell handover goes from two descriptors to THREE
   - the client needs the same split for the same reason. Seven offers now.

2. InitCapabilities HAD NO WIRE KIND. CONTRACT-P6 §2 predicted this exactly
   ("the request has a live client caller and the codec refuses to encode
   it"). SurfaceOpKind gains 11, append-only; the decode range's upper bound
   moves with it, or the new tag reads as out-of-range and surfaces as
   Fatal{ProtocolCorruption} rather than the missing row it is. The op's name
   loses its InprocOnly suffix, which stopped being true here.

3. THE CHILD LOADED NO CONFIG AT ALL. mobilegl_server_main calls
   InitServerRoleForSpawn directly, and MG_ConfigLoader::Init is a step of
   MobileGL::Initialize - so every MG_Config value in the server was its
   static default. MOBILEGL_BACKEND_TYPE survives the launcher's scrub on
   purpose and was read by nobody: a DirectVulkan session would have brought
   up a DirectGLES server and then disagreed with its client about which
   backend the capability mask describes.

4. AND THEREFORE Transport READ AS Monolith, which CONTRACT-P6 §3.1 (D1)
   forbids in as many words. a6 measured the cost: 226 live lines test
   `Transport != Monolith` to select the SERVER arm, 148 in MG_Backend.
   Monolith flips all of them to frontend glue in the one process with no
   frontend. Observed precisely as predicted - UnitTexturesByHandle() answered
   false, Clear took the legacy arm that dereferences borrowed FRONTEND slot
   pointers, and the apply thread took a SIGSEGV inside SyncNeccessaryTextures
   on the first Clear record of the trace. It is pinned in-process rather than
   through the environment because the environment is where it must NOT be:
   LooksLikeAClientEnvironment exits 65 on a surviving MOBILEGL_TRANSPORT, and
   that check is anti-recursion catch (b). Dial, not Transport, is that axis.

5. THE LOG WAS CORRUPT, NOT MERELY INTERLEAVED. Two processes opened the same
   MOBILEGL_LOG_FILE_PATH with "w" and each carried its OWN file offset, so
   they overwrote each other's bytes - half-lines like `ote client: CapsMirror
   generation 1 adopted`, and the server's whole startup block vanishing under
   the client's later writes. This cost real diagnosis time twice, because a
   missing line read as a code path not taken. O_APPEND now; the client still
   truncates once so a fresh run is not a pile of old ones, and the server
   never does - it would delete the very startup lines a failed session needs.
   run_trace_case.cmake's Fatal{ census reads exactly this file, so it was
   also reading a lie.

The retrace runner's split assertions become transport-aware: one row per
transport it admits, and a transport with no row is a FATAL rather than a
fall-through, because the fall-through is the accident the block exists to
prevent. The spawn row carries a SECOND sentence and it is the stronger half
- ConfigLoader's marker proves the value RESOLVED, while `spawn ARMED - the
server role runs in pid N` is written only after the launch, the connect and
the handshake all succeeded, and carries a pid that is not this process's.
inproc resolves its own marker while running the server role on a thread
here; nothing on that path can write this one.

G14: one test name added (TheEleventhFramedOpIsInitCapabilitiesAndItCrosses-
TheWire), none removed. The ten-op table keeps its name and its scope rather
than being renamed to eleven.

Two unit failures predate this change and are environmental in this tree:
PipeCatalogue.FrontendNeverTakesAnApplierAddress (the frontend source root
resolves empty) and SessionHandshakeTest.TheAbiFingerprintChangesWhenAnyOf-
ItsInputsDoes (GIT_COMMIT_HASH_SHORT is empty here, which a6 already recorded
as red in this configuration).

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-21 12:23:41 -04:00
swung0x48andClaude Opus 5 b0f4f8b744 [MG_Remote] (P6/cp): EGL control frames cross to the other process, and answer
An eglInitialize issued in one process is dispatched in another and its answer
comes back. That is the last thing standing between the session and a native
context, because the server creates its context on the apply thread when the
client's first eglMakeCurrent crosses - and until now nothing crossed.

ONE SEAM, NOT TWELVE. a6 row A4-13 counted twelve Server* forwarders, each
ending in ServerLoopInstance().RunSurfaceControlFrame(frame) with no role
branch, and concluded twelve edits. They all funnel through that one function,
so the branch goes there and the forwarders are untouched.

A HOOK, NOT A CALL. ServerLoop::SetRemoteControlSink takes a function pointer
the client installs at handshake. The obvious alternative - the server half
asking ClientSession::Active() - would have added a fifth symbol to the six
MG_Remote already owes itself (a6-link-experiment §5), in the one file with a
clean reason not to.

The branch is BEFORE the local seq mint, deliberately. RunSurfaceControlFrame
numbers unnumbered local posts; a wire request must keep the CLIENT's number all
the way through dispatch and reply or its answer cannot be correlated
(CONTRACT-P6 §6.3, which says the client mints, always).

The client sink encodes with EncodeSurfaceOpFrame, sends, and waits for the
SurfaceReply carrying its own seq - under one mutex, because the twelve
forwarders are already caller-serialised on the server's m_callerMutex under
inproc and two replies racing for one correlation is the same bug on either
side. A CapsSnapshot arriving while it waits is ADOPTED rather than dropped:
the server republishes caps from inside its MakeCurrent dispatch (a6 row A4-30)
so a snapshot legitimately precedes the reply to the op that produced it. The
wait is bounded and its expiry is NOT fatal - a peer that is gone is a different
fact from a peer that is slow, and only the doorbell's death latch may say which.

The server's pump decodes and applies through ServerApplyWireSurfaceOp, which
a6 found had no production caller anywhere. It runs on ServerMain's own thread -
NOT the apply thread - which is what §6.2 asks for: a control arrival must not
wake the applier, and frame decode must not happen on the thread holding the
native context. A frame that is not a verifiable SurfaceOp ends the session
rather than being ignored, because a silent drop is the failure mode this
project refuses everywhere else.

THE TEST'S ASSERTION IS THE OUT-PARAMETERS, not the EGL result. A headless
machine has no display to initialise, so the op is expected to be refused - and
ServerInitializeEGLDisplay writes major/minor "whenever the dispatch ran,
success or not" (the forwarder's own comment). They move off -1 if and only if
a SurfaceReply came back from the other process; a transport failure returns
before the write-back. I got this backwards first and the test said so.

Gates: ServerSpawnTest 5/5; unit suite 2345 with the same two pre-existing
environmental failures; G1 pull 0 added / 0 removed, .text 10822147 unchanged.

Not TCP. It was considered and dropped for now: TCP has no SCM_RIGHTS, so the
four segments cannot cross it, and a TCP control plane would have to refuse a
data plane by name until StreamLink exists (P6.5). Recorded here so the reason
is on file rather than re-derived.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-21 10:50:28 -04:00
swung0x48andClaude Opus 5 207c31f6db [MG_Remote] (P6/sm): two INDEPENDENT processes, joined by a name, sharing memory
The cross-process session is up. A server process is started on its own with an
endpoint and nothing else, it listens; a client started separately connects to
that name; Hello crosses, Welcome comes back with four SegmentRefs, six
descriptors cross by SCM_RIGHTS, and the client maps memory another process
created. ClientSession::Active() is non-null at the end of it, which is the flag
that arms the thirty-seven wire emitters.

INDEPENDENT, NOT FORKED - and that is a correction to this package's first
shape. The version committed an hour ago forked the server and handed it fds
3..6. It worked, and it was less code, but inheritance can only ever produce a
server that is a CHILD OF ITS CLIENT, which is the one arrangement the end state
cannot use: there the server is a standing application and the client is
somewhere else entirely, possibly on another kernel. CONTRACT-P6 §3.1 called
this Dial == Connect and filed it as a later shape. It is the primary one, and
fork/execve survives only as a way to START a process - every descriptor it used
to carry is gone.

What that costs and buys, concretely: the rendezvous becomes a NAME, so
SocketTransport grows Listen/AcceptPair/ConnectTo, with a bounded connect retry
that is the CLIENT's (a launcher that waited for the server to be ready would be
coupling the two again by the back door). The bells stop being inherited fds and
are created by the server and handed over with the segments - slots 4 and 5 of
six SCM_RIGHTS offers. And the client connects TWICE to the same path: an fd
offer is a sendmsg whose ancillary data rides with specific bytes, so it may not
share a socket with the framed control stream, or the frame reassembler and the
descriptor receiver race for the same bytes.

The pieces behind it:
  - SessionSegments::AdoptFromDescriptors, which is the same Adopt+Map loop
    AttachInProcess has run on every inproc session since P5. That was the point
    of writing the inproc attach as dup+Adopt+Map rather than as an alias: only
    the origin of the descriptor is new.
  - ServerSession::SetExternalDoorbells, the narrow fix for a6 row A7-1 - the
    §3.9 accessors abort for every role but InProcess, so a spawn apply thread
    died before popping its first record. lk deletes them; until then an injected
    pair is honest about where the bells come from.
  - MG_Backend::InitServerRoleForSpawn: steps 1 and 2 of the split bring-up
    extracted so the server process runs the SAME code the inproc server role
    runs. The capability bits are a statement about the server's own backend and
    a second copy would diverge the first time a backend registers a slot.
  - ClientSession::FinishStartup: everything below the attach - producer, reply
    pool, event ring, segment table, encoder, first CapsSnapshot, emitter tables -
    shared verbatim between inproc and spawn. Its one parameter is not a
    transport question: under inproc the client starts the apply thread because
    there is no server-side main; under spawn there is one, and it started the
    thread before it sent the first descriptor.

G1 CAUGHT A REAL LEAK on the way: InitServerRoleForSpawn was guarded on the
inside, so the pull build still DEFINED the symbol - 2 added, 1 removed, .text
+16 bytes. The whole function and its declaration are now inside the guard.
"It returns false there" is not the same as "it is not there", and the gate is
what said so.

Gates: ServerSpawnTest 4/4; unit suite 2344 with the same two pre-existing
environmental failures; G1 pull 0 added / 0 removed, .text 10822147 unchanged.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-21 10:36:14 -04:00
swung0x48andClaude Opus 5 e156ea5f7a [MG_Remote] (P6/sm): two MobileGL processes, talking
The first time this project has had a second process. fork + execve of a real
server image, the control socket surviving the exec, bytes crossing a process
boundary, and the child exiting on EOF with nothing left behind.

mobilegl_server_main EXISTS NOW. a6 found ARCHITECTURE.md:488-496 had described
it for three phases while the symbol was nowhere in the tree, and the only
MobileGLServer target was the P0 spike stub, which links no MobileGL library at
all. The spike keeps its evidence and its name becomes MobileGLServerSpike; the
real image links the library, so an undefined symbol is a build error rather
than a dlsym failure in a child whose stderr is /dev/null.

WHAT sm OWNS AND WHAT IT LEAVES: the process, the inherited descriptors, the
transport and the exit discipline. Not the session, not the applier, not the
four segments - wiring those from ServerMain before lk has a seam to wire them
THROUGH is how call sites get written twice. The loop is a read/answer/exit-on-
EOF stand-in whose SHAPE is the part that matters: one reader, EOF ends the
process, and no timeout is ever allowed to stand in for the death fact (§5.4).

ANTI-RECURSION IS TWO CATCHES, and neither is ARCHITECTURE.md:488's. That rule
says the child hard-sets Transport to Monolith; a6 measured that 226 live lines
test `Transport != Monolith` to select the SERVER arm, 148 in MG_Backend, so
obeying it flips the whole backend to frontend glue in the one process with no
frontend. Instead: (a) MOBILEGL_IPC_DIAL=no, structural and separate from role,
and (b) MOBILEGL_TRANSPORT and every MOBILEGL_IPC_* scrubbed from the child's
envp. The child refuses with 64 for (a) and 65 for (b) so the two safeties are
distinguishable - two that cannot be told apart are one.

TWO BUGS WORTH RECORDING, both found by the test rather than by review:

dup2(n, n) IS A NO-OP THAT DOES NOT CLEAR CLOSE-ON-EXEC. FdPassing sets
SOCK_CLOEXEC on the aux pair, so the child depends on dup2 to clear it - but in
a gtest process a fresh socketpair lands on exactly fds 3..8, so a source fd
often IS its own target. The no-op left CLOEXEC set and the following close()
then shut the descriptor we had just "installed". The child came up with no
socket and the parent saw TRANSPORT_CLOSED on its first send. Now spelled out
rather than written cleverly.

THE CHILD'S DIAGNOSTICS WERE INVISIBLE. WireLogError reaches the file sink
only - Defines.h builds the logger with the console sink off - so a child that
refused to start said so into a file the parent does not know the path of.
ARCHITECTURE.md §15.2 warns about exactly this on Android. Both refusal paths
now also write stderr directly, and both carry a distinct exit code the parent
can name without reading anything.

TESTS: six cases, 6/6. Each exists because something would otherwise pass
silently - the reply carries the child's own getpid() so a test that talked to
itself cannot pass (ID-124's lesson at the smallest scale); the process tree is
COUNTED before, during and after, not promised; the child is proven not to exit
while merely idle before it is proven to exit on EOF; an unresolvable image is a
named refusal that spawns nothing (S1); a surviving client knob is caught by
name (S3); and a descriptor crosses execve by SCM_RIGHTS, which is the mechanism
the four segments will ride on and is now exercised before it is needed.

Also records the asio decision in the contract: declined for P6 because spawn
needs five platform mechanisms and asio covers one - its own socketpair returns
operation_not_supported on Windows, it has no descriptor passing, segment
delivery is POSIX-only by design, and there is no fork. Revisit at P6.5, where
asio::generic::stream_protocol carries a raw family/type/protocol triple and
therefore gives AF_VSOCK from one implementation.

Gates: unit suite 2346, up 6, same two pre-existing environmental failures. G1
pull 0 added / 0 removed, .text size 10822147 unchanged, and zero spawn, server
or SocketTransport symbols in the pull build.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-21 10:04:31 -04:00
swung0x48andClaude Opus 5 a351836154 [MG_Remote] (P6/so): SocketTransport, green over a real socketpair before any second process
The first P6 code that runs. ITransport over a connected AF_UNIX SOCK_STREAM
socket, with SCM_RIGHTS descriptor passing on a dedicated SOCK_DGRAM aux pair.
No shared memory: this is the CONTROL plane, and the hot path bypasses
ITransport entirely by its own header's account. What the socket carries is the
handshake, surface ops, resync, aux requests and fatals - and, once sm exists,
the four segment descriptors that let the peer map the data plane. It moves the
keys, not the bytes.

CONTRACT-P6 §8 and the spawn plan both require this green over a plain
socketpair with two threads BEFORE a child is ever forked, for the reason
SessionRings.h gives about the attach half: a transport first exercised on the
day the process appears is a transport whose bugs all arrive at once, on the
hardest day to debug them. That requirement is now met.

It reinvents nothing. Framing.h already had AppendFrame and a real byte-stream
reassembler with exactly the BUFFER_TOO_SMALL keep-the-message semantics
ITransport specifies - written for this and never before driven by a socket.
FdPassing.h already had SCM_RIGHTS over a dedicated datagram pair. What is new
is ~250 lines joining them, plus the platform refusal: Windows has no
SCM_RIGHTS and ShmSegment::Adopt is POSIX-only, so CreatePair refuses BY NAME
at construction rather than handing back a transport that fails every later
call.

SOCK_STREAM rather than SOCK_SEQPACKET, deliberately: Doorbell.h:390-398
already chose a stream socket so a closed peer surfaces as POLLIN|POLLHUP with
recv()==0 rather than as a hang, and the control plane may not disagree with
the bell about what death looks like. Framing.h is what makes a stream safe -
the message boundary is in the payload, not in the socket.

TESTS: the same nine ITransport-contract cases InProcessTransportTest runs,
copied rather than shared. Folding both suites into one parameterised fixture
would rename the sixteen existing cases and G14 says names only grow; and the
two suites do not share a handle anyway, since InProcessTransport's tests reach
into condvar doorbells this class does not have. Nine names added, zero
removed. The seven Doorbell* cases are deliberately absent: they exercise
CondVarDoorbell, not ITransport.

Plus three a stream has and a message queue cannot: a 256 KiB payload that
provably crosses in several reads; a garbage stream that must latch failed and
must NOT resync onto a boundary it invented; and adopting an already-connected
fd with no aux channel, which answers UNSUPPORTED to ShareFd rather than
pretending - rule G, a transport declares what it supports.

Red-once, both run: drop the message on BUFFER_TOO_SMALL and six cases go red;
make the framing latch recoverable and AGarbageStreamIsLatchedFailed fails by
name.

Gates: 12/12 in 677 ms. Unit suite 2340 tests, up 12, with the same two
pre-existing environmental failures. G1 pull 0 added / 0 removed, .text size
10822147 unchanged, and zero SocketTransport symbols in the pull build.

One note for the VM track this eventually serves: swapping AF_UNIX for
AF_VSOCK is one line here and nothing at all in Framing. It is the shared-memory
half that does not cross a kernel.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-21 09:47:32 -04:00
swung0x48andClaude Opus 5 f4cbaa8945 [MG_Remote] (P6/lk): regroup RingControl by writer, and make the asserts that pin it falsifiable
The shared control page both roles map had a mixed-writer cache line:
{appliedSeq, submittedSeq, retiredSeq, completedFrameSerial, presentAckSerial}
sat together, but submittedSeq is producer-written (Ring.h's "THE FIVE
WATERMARKS") while the other four are consumer-written. That is why no
single-writer progress block could be aliased over it, and it is what this
package fixes: submittedSeq moves up beside cmdHead, the other thing the
producer writes, and the four that remain become a named LinkProgress member -
the struct c6 declared in ILink.h - so a data plane with no shared page can own
the same four values and every wait predicate in SessionRings.h keeps ONE
implementation at source level.

The two event flags deliberately stay in the doorbell group. Promoting them
would put the client's per-drain exchange(0) on eventRingFull (EventRing.h:200)
onto the line the client's own spin predicate reads 1e5-1e6 times a frame.

73 call sites rewritten, 15 in the library and 58 in tests. The rewrite is
receiver-scoped rather than field-scoped, because SplitRuntimePeek.h:77 has its
own struct with a field of the same name and SplitRuntimePeek.cpp:146 has both
on one line - a field-scoped rename would have silently broken the peek struct
that MagmaRunAheadScenario reads nine times.

THE ASSERTS ARE THE PART THAT NEEDED A SECOND PASS. The first revision shipped
four aggregate asserts and an adversarial review broke them by counterexample:
swapping retiredSeq and completedFrameSerial inside LinkProgress compiled
clean, passed all four, and passed the runtime layout test too - because
appliedSeq stays at offset 0. Three wire-visible offsets on a shared page were
pinned by nothing. Nothing else in the tree covers it either: the ABI
fingerprint takes no input from this page, and sizeof(RingControl) is 4096
whatever the members do, because alignas(4096) makes it so.

So the block is now per-field as CONTRACT-P6 §8.3 actually asked, plus a
standard-layout precondition, a tail bound that alignas cannot satisfy for us,
and the LinkEventFlags mirror. Each was run red: the field swap reds the
per-field asserts by name, a fifth member inside LinkProgress reds sizeof.

One of them cannot go red, and Ring.h now says so rather than implying
otherwise. A SMALL member inserted between Progress and serverEpoch lands at
offset 288, inside Progress's own line, and serverEpoch's alignas(64) absorbs
up to 32 bytes of it - so both line asserts still pass. The review's proposed
fix does not catch it either; I tried it. A gate nobody can falsify is worse
than no gate, so the limit is written down beside the asserts.

Also: RingTest.ControlPageLayoutIsTheSharedContract said nothing about the one
field this package moved, and now asserts the producer/consumer separation and
the event flags' exclusion itself rather than borrowing the claim from Ring.h.
Ring.h grew 30 lines, so the Ring.h:NN citations this package and c6 authored
are re-anchored to named blocks instead of line numbers. ARCHITECTURE.md §11.2
is updated for the new layout, and a factual error introduced in the previous
revision of that paragraph - submittedSeq annotated as releasing staging, which
retiredSeq does - is corrected.

Gates: pull 0 added / 0 removed, .text size 10822147 unchanged; split 0/0,
.text size 11681395 unchanged; unit suite 2326/2328 with the same two
pre-existing environmental failures as the baseline. The five edits behind
MGITEST_SPLIT_RUNTIME_PEEK were proven compiled by a red-once, not assumed.

Note on the .text claim: that is a SIZE, not the bytes - field offsets moved,
so immediates moved with them. And this page's layout IS observable across
binaries; what is unobservable is behaviour within one binary. The contract
already books the layout change deliberately, before spawn exists to care.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-21 09:23:48 -04:00
swung0x48andClaude Opus 5 a54ae47ab9 [MG_Remote] (P6/lk): the pre-flight itemisation, and a correction to c6's regroup design
CONTRACT-P6 §8.5 requires lk to publish its blast radius before it starts,
because an earlier draft's ratchet baseline was wrong by a factor of three and
a ratchet installed on the wrong number is red on its first CI run for reasons
that have nothing to do with a leak. The itemisation is mechanical, per file,
with the grep spelling stated: 250 seam-identifier references outside
Transport/ across 23 files (127 production, 123 test), and 44 member-access
sites that the regroup itself must rewrite, across 9 files - 17 of them in
MG_IntegrationTest, which is why lk builds with the integration tests ON.
The earlier build did not, and a missed edit there would have been green.

THE CORRECTION. Measuring that radius turned up a mistake in c6, landed two
commits ago. §8.3 and ILink.h both said lk should promote eventRingFull and
eventDropped into the watermark group and called the result single-writer.
eventRingFull has TWO writers: the server latches it with store(1) when
SEG_EVENT fills (EventRing.h:140) and the CLIENT clears it with an exchange(0)
on EVERY DRAIN (:200). Promoting it would put a per-drain read-modify-write by
the client on the same cache line as appliedSeq - which the server
release-stores every 64 records and the client's spin predicate reads 1e5-1e6
times a frame. That is new false sharing on the hottest line in the system,
and it would land in exactly the numbers this package's gate has to hold
constant. It is also the same class of error the earlier draft made with
submittedSeq, one field over.

So LinkProgress is now the four consumer-written watermarks and nothing else -
genuinely single-writer - and the two flags stay in the doorbell/generation
group, where mixed writers already live beside consumerParked/producerParked,
crossing the seam through a separate EventFlags() accessor on its own line.
The contract records the correction and its reasoning rather than quietly
restating the rule.

ALSO CORRECTED, from running the baseline suite: a6's link-experiment report
said the silently-empty build stamp had "no log and no gate to say so". That
is false. SessionHandshakeTest.cpp:140 asserts BuildStamp[0] != '\0' and :180
asserts that perturbing it changes the fingerprint, and BOTH GO RED in this
configuration right now - the worktree's .git holds a Windows path WSL's git
cannot resolve, so GIT_COMMIT_HASH_SHORT is "". The finding is therefore
stronger, not weaker: the gate that catches it already exists and is already
red. What is silent is the BUILD, and hs owes a named configure-time failure
rather than a new gate.

Baseline for lk, recorded: 3878 tests, two failures, both environmental and
understood - the fingerprint one above, and PipeCatalogue.FrontendNeverTakes-
AnApplierAddress, which walks up from cwd looking for MobileGL/MG_Impl and so
fails for any out-of-source build directory.

No behaviour change. The headers are still included by nothing.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-21 08:54:48 -04:00
swung0x48andClaude Opus 5 0bbe41c291 [MG_Remote] (P6/c6): the normative contract, and the data-plane seam declared but not wired
c6 is P6's contract package. It lands CONTRACT-P6.md plus two headers and
changes nothing: no caller moves, no byte moves on any wire.

THE CONTRACT supersedes P6-CONTRACT-DRAFT.md, which was written before its own
audit and is wrong in four places - the ABI row, "the latch is implemented
unchanged", "cp is transport only", and "a transport swap and nothing else".
a6 measured all four. It carries 21 rulings, of which the load-bearing one is
D1: the spawned child keeps Transport == Spawn and anti-recursion becomes a
separate Dial axis. ARCHITECTURE.md:488's literal instruction is amended,
because 226 live lines test `Transport != Monolith` to select the SERVER arm
and forcing Monolith flips 148 MG_Backend lines to frontend glue in the one
process that has no frontend.

That ruling can be stated normatively without changing behaviour because of
something a6 found and the contract exploits: TransportMode::Spawn is
UNREACHABLE at this head. ConfigLoader.cpp:344 is the only writer for the
string "spawn" and it writes Monolith. So every rule conditioned on
Transport == Spawn constrains a state no process can enter - and the same fact
is why ConfigLoader's named refusal cannot currently falsify itself, which is
sm's to fix and §9.5's arm-proof gate to catch.

THE SEAM. ITransport says in its own header that the hot path bypasses it;
below it there was no interface of any kind, because Ring.h, ReplySlot.h and
EventRing.h each take a raw void* plus a capacity. ILink.h is that missing
thing. It is setup-time, not hot-path: no method is called per record or inside
a spin predicate, because Doorbell::Wait's predicate runs 1e5-1e6 times a frame
reading watermarks straight off the page, and because the only lane that could
measure a virtual there has four times the dispersion of the effect - a gate
that can only print "within noise" is ID-124 one level down.

StreamLink.h is declared and implemented by nobody, and that is its job: ILink's
adequacy is a claim only a compile can settle. Writing it forced three methods
the brief did not name - ResolveSpan, FlushProgress, and the reply pair - so it
has already earned its keep. Delete one ILink method it declares and the build
goes red.

Deliberately NOT here, each for a reason the contract records: Watermark::Reached
is not redefined (SessionRings.h owns it); Ring.cpp's reserve/pop bodies are not
relocated into a header that would then need the logger; RingControl is not
regrouped, because that rename is 109 production sites with five behind a
non-Android #if, so it is lk's with a published itemisation; and the schema rows
are specified but left to hs, because deprecating SurfaceReply.defaultFb while
appending `result` changes CreateSurfaceReply's arity and the existing
six-argument call would silently bind its defaultFb 0 to result.

INERTNESS IS STRUCTURAL, not measured. Zero object dependency files reference
either header, zero build rules do, and nothing in the tree includes them.
Verified anyway on both flavours: pull and split each have 0 symbols added,
0 removed, and .text byte-identical (10822147 / 11681395). check_doc_citations
resolves all 61 citations.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-21 08:35:50 -04:00
swung0x48andClaude Opus 5 785fed0b00 [Docs] (Disaggregated): P6 a6 close-out, and the end-state review it was re-scoped from
a6 is the read-only audit P6-SPAWN-PLAN puts first. Seven static items, each
produced by one auditor and re-resolved line by line by one adversarial
verifier; 198 rows, 65 of them contested, and only the surviving ones carry
into the report. Item 5 - can the server link without MG_Impl - is the one
experiment, and it is answered.

The headline is that P6's transport half is smaller than the plan assumed
(fc and fs really did land) and its process/role half is much larger. Four
statements in P6-SPAWN-PLAN / P6-CONTRACT-DRAFT are false at this head:

  - `spawn` is not an observable state at all. ConfigLoader.cpp:339-346
    recognises it and then writes Transport = Monolith, so "the child was
    forced to monolith" and "the parent fell back" are the same value and
    that named refusal cannot falsify itself. Meanwhile 226 live lines test
    `Transport != Monolith` to select the SERVER arm, 148 of them in
    MG_Backend - so ARCHITECTURE.md:488's rule, implemented literally, flips
    the whole backend to frontend glue in the one process with no frontend.
  - `cp` is not transport-only: the InitCapabilities REQUEST has no wire form,
    and the codec refuses to encode the kind a live client still calls.
  - the device-lost latch is not implemented; it was booked as carriage.
  - the server cannot link without MG_Impl: 184 symbols, 177 of them real
    function calls, owed 101 to P7 / 14 to P3b-P4b / 60 shared / 6 to P6.
    There is also no module target to link, so the question could not have
    been answered by editing a link line.

Four more blockers the earlier review missed: the apply thread aborts in
ConsumerDoorbell before popping its first record (contract 3.9's ruling, which
lk should retire rather than amend); neither side of the control plane is
wired to a socket; the control-reply wait has no deadline, so a frozen peer
wedges the GL thread inside eglMakeCurrent; and SurfaceReply cannot carry a
MobileGLResult, so a client cannot tell a dead server from a legitimate
refusal.

The abort census makes dl's funnel a redesign rather than a rename: 92 sites,
30 distinct family words against a 7-value wire enum, and three unbounded
peer-driven allocations with no try/catch anywhere under MG_Remote.

P6-ENDSTATE-REVIEW.md is the re-examination of P6 against the gfxstream-shaped
end state that produced a6's three added items. a6 overturned four of its own
claims - the MG_State eight's shape, the abort count, m_windowHandle's
injection points and a predicate name collision - and those are corrected in
place rather than left to be rediscovered.

Docs only. No code, no gate, no behaviour.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-21 07:49:37 -04:00
876 changed files with 22989 additions and 395933 deletions

No files matched your search

+4 -15
View File
@@ -11,19 +11,8 @@ on:
# someone remembering to dispatch the workflow by hand.
- feat/disaggregated
- codex/fix-github-ci
# A docs-only push builds nothing this workflow tests (231 emulator legs per run). The Test
# workflow keeps running for docs: it hosts the doc citation lint.
paths-ignore:
- 'docs/**'
- '**/*.md'
workflow_dispatch:
# ONE LIVE RUN PER BRANCH, as in test.yml: a superseded push is cancelled rather than left queued
# behind its successor; a manual dispatch gets a group of its own; dev queues rather than cancels.
concurrency:
group: ${{ github.workflow }}-${{ github.event_name == 'workflow_dispatch' && github.run_id || github.ref }}
cancel-in-progress: ${{ github.event_name == 'push' && github.ref != 'refs/heads/dev' }}
jobs:
build:
runs-on: ubuntu-latest
@@ -364,7 +353,7 @@ jobs:
--avd-name "${AVD_NAME}"
retrace:
name: retrace (${{ matrix.backend.name }} / ${{ matrix.transport || 'monolith' }}, ${{ matrix.case.name }})
name: retrace (${{ matrix.backend.name }} / ${{ matrix.lane || 'monolith-control' }} / ${{ matrix.transport || 'monolith' }}, ${{ matrix.case.name }})
runs-on: ubuntu-latest
needs:
- build
@@ -385,7 +374,7 @@ jobs:
max-parallel: 4
matrix: ${{ fromJSON(needs.trace-cases.outputs.android) }}
steps:
- name: Set swap space
- name: Set Swap Space
uses: pierotofy/set-swap-space@v1.0
with:
swap-size-gb: 8
@@ -454,7 +443,7 @@ jobs:
--profile pixel_6 \
--avd-name "${AVD_NAME}"
- name: Launch emulator
- name: Launch Emulator
run: |
sh android-plugin/run-avd-ci.sh start \
--avd-name "${AVD_NAME}" \
@@ -611,7 +600,7 @@ jobs:
free -h > android-retrace-result/diagnostics/host-memory.txt 2>&1 || true
sudo dmesg -T 2>/dev/null | tail -300 > android-retrace-result/diagnostics/host-dmesg.txt || true
- name: Stop emulator
- name: Stop Emulator
if: always()
run: |
sh android-plugin/run-avd-ci.sh stop \
File diff suppressed because it is too large. Load diff
-17
View File
@@ -655,15 +655,6 @@ if (MOBILEGL_BUILD_DISAGGREGATED)
# and its codec against protocol.fbs's SurfaceOp/SurfaceReply (the spawn arm's seam).
MobileGL/MG_Remote/Server/SurfaceControlFrame.cpp
MobileGL/MG_Remote/Protocol/SurfaceOpCodec.cpp
# P12 (on-screen server window): the process-wide holder of the server's own window
# (the display Activity's SurfaceView on Android; nobody installs one on the host, so a
# ServerOwned request is refused by name there).
MobileGL/MG_Remote/Server/ServerDisplay.cpp
# P7 gate 5 (g5-msprobe): the Magma wire arm's two multisample depth/stencil resolve
# arms and the probe that measures the first against the second, shared by the
# renderer's bring-up and the Vulkan POST. Wire-only - the monolith records neither arm -
# so it stays out of the pull build (gate G1).
MobileGL/MG_Backend/DirectVulkan/Renderer/WireDepthResolveProbe.cpp
)
endif()
@@ -681,14 +672,6 @@ if (ANDROID)
MobileGL/MG_Util/SelfTest/DriverPostJni.cpp
MobileGL/MG_Util/SelfTest/DriverBenchJni.cpp
)
if (MOBILEGL_BUILD_DISAGGREGATED)
# P12 (on-screen server window): the trace APK's MobileGLDisplayActivity - the in-process
# display server's thread, its SurfaceView's ANativeWindow in and out of ServerDisplay, and
# the geometry up-call. Split build only: nothing else has an in-process server to drive.
list(APPEND SOURCE_FILES
MobileGL/MG_Remote/Server/DisplayServerJni.cpp
)
endif()
endif()
if (WIN32)
-127
View File
@@ -456,20 +456,6 @@ namespace MobileGL::MG_Config {
// The <path> of `unix:` / the <name> of `pipe:`. Empty for the other three modes.
extern String TransportEndpoint;
// P7 F1. DID **THIS PROCESS'S OWN CONFIGURATION** ASK FOR A SPLIT TRANSPORT.
//
// `Transport` alone cannot answer that, and the difference is exactly the one the F1 gate
// turns on. A unit fixture assigns `Transport` by hand to put the code under test on its
// split arm (ServerLoopTest's main does, and says why) while building no client at all; a
// real run gets it from MG_ConfigLoader::Init(), and that run WILL bring a client half up.
// Only the second may be held to "never decide a record family's fate from a placeholder
// caps mirror" - in the first there is no handshake, no mirror to adopt and nothing the
// rule could mean.
//
// Written once, by InitTransport(), and never cleared: a process does not stop having been
// configured. Read by MG_Remote::Client::CapsMirror::RequireFirstSnapshot.
extern Bool SplitTransportRequestedByConfig;
// The MOBILEGL_IPC_* family. A separate table rather than more FeaturesTable members,
// for the G1 reason above and because every field here is meaningless without the
// transport: a build that cannot reach the MG_Remote code cannot honour one of them.
@@ -479,12 +465,6 @@ namespace MobileGL::MG_Config {
// the full planned inventory (PRESENT_CREDIT, POLL_ESCALATE, SHADOW_SHM,
// INLINE_PAYLOADS, TRACE, ATTACH, RESPAWN, IDLE_EXIT_S), and every one of those belongs
// to P6 or later.
//
// P12 (on-screen server window): MOBILEGL_IPC_SURFACE's two values. See IpcTable::Surface.
enum class IpcSurface : Uint8 {
Offscreen = 0, // a window surface is the client's own window, as before (the default)
Server = 1, // a window surface is the SERVER's window: WindowKind::ServerOwned
};
struct IpcTable {
// MOBILEGL_IPC_SERVER_PATH: where to find libMobileGLServer. P6 consumes it; P5
// lands the parse because t1's ctest ENVIRONMENT blocks and add_trace_replay_test's
@@ -503,37 +483,8 @@ namespace MobileGL::MG_Config {
// stage chunk budget (MGPipeStageChunkBytes, a quarter of this), and a record type with
// no cut is Fatal{RingOverrun, "SEG_STAGE"} rather than allowed to exceed it.
Uint32 StageMb = 32;
// MOBILEGL_IPC_WIRE_DEFERRED_MB (P7 wave 4 M2, ID-P7-32): the SERVER's budget, in MiB,
// for orphaned wire buffer stores - the old VkBuffer every glBufferData that crosses the
// wire leaves behind - that a GPU command recorded but not yet retired may still name.
// Stores no command names are destroyed at once and stores whose last submission has
// retired are destroyed at the next park; this bounds the REST. When the parked bytes
// exceed it after a sweep, the server flushes what it has recorded and waits for it
// (WaitForWireBufferHostAccess's sync point, mid-frame), which retires every one. It is
// not a frame count because a frame is not bounded: a snapshot-exiting pbuffer replay
// delivers one present for 1.3 M calls. The same sync point also fires above a fixed
// 1024 parked stores (VkBufferManager::kWireDeferredCountCeiling), because small
// orphans never reach a byte budget. 0 IS THE NEGATIVE CONTROL for both, not "unlimited
// by design": no forced sync, so a one-frame respecify-and-draw loop grows without bound
// and MagmaWireReclaimScenario's watermark cases must go red.
Uint32 WireDeferredMb = 64;
// MOBILEGL_IPC_SPIN_US: spin before parking on a doorbell, either direction.
Uint32 SpinUs = 50;
// MOBILEGL_IPC_EVENT_WAIT_MS (PH-6, ID-P7-2): the SERVER's patience, in ms, for ONE
// reverse-channel event that finds SEG_EVENT full under run-ahead. The apply thread
// publishes, rings the client and parks until the client drains enough room; a client
// that has not made room when this runs out - it stopped draining (NotDraining) or it
// drains a slot at a time (TooSlow) - FORFEITS the reverse channel: that event and every
// later one is dropped and counted (eventDropped), and the session stops by the ordinary
// stop path rather than by Fatal{EventRingOverflow}. A peer that goes away (PeerGone) or
// a session that is stopped (Stopped) ends the wait at once instead, so the knob may
// exceed ServerLoop::Stop()'s 5000 ms join. It bounds the whole reservation, not one
// park, so a trickling peer cannot stretch it - nor can a shm peer that writes the
// (peer-writable) eventRingFull latch to 0 itself, though that one keeps the apply
// thread spinning rather than parked until the budget runs out. Was a 30000 ms constant
// spent twice. Read by the server only (ServerSpawn.cpp passes it to a spawned child);
// the lockstep arm (no kCapRunAheadApply, i.e. Magma) never waits and keeps P5C's Fatal.
Uint32 EventWaitMs = 2000;
// MOBILEGL_IPC_PERSISTENT_BLOCK_KB: block granularity of the persistent-map push.
// 0 IS A NEGATIVE CONTROL, NOT "unlimited": it disables the push, and
// PersistentCoherentMapScenario must go RED under it (exit gate E3(a)).
@@ -548,53 +499,6 @@ namespace MobileGL::MG_Config {
// every reply-slot row), which is the only place BARRIER-PULLED fields are read. 0
// restores the per-record barrier of R-1.
Uint32 BatchWaits = 1;
// MOBILEGL_IPC_CREATE_WINDOW: how many RESOURCE_CREATE answers may be outstanding before the
// client waits for one. 1 = every create waits (the shape R-5 shipped with); N > 1 = up to N
// creates go out fire-and-forget, their caller reads a PROVISIONAL accept, and the oldest
// answer is taken when the window fills.
//
// DEFAULT 2, AND IT TOOK THREE THINGS TO GET HERE. The deferral was inert for two
// measured reasons and one structural one, in the order they were found:
// 1. the reply buffer was a ring of the last 8 answers, and between two creates this
// client emits on the order of a thousand records - so the answer was always gone
// (`want=310` on every miss while the ring spanned [1175..1504]);
// 2. a residency budget that tried to take answers back early could not help, because
// what displaces an answer is what the SERVER sends, not what the client emits;
// 3. and so the fix was RETENTION - a link keeps a declared answer until its reader
// takes it (Transport/ILink.h's RetainsReplies, StreamLink's declared-answer store).
//
// MEASURED ON THE DEVICE, load frame, both ends rebuilt (create 4,536, records 103,097,
// frame-sent identical per op throughout):
// window 1 4,536 blocking takes 28.66 s (the shape R-5 shipped)
// window 2 2,500 17.27 s
// window 4 1,644 11.02 s
// and the round trip does NOT grow as the window deepens (5,285 / 4,082 us against 5,672
// at 1), which is the measurement that says the ~5 ms is a WAKEUP the server batches away
// rather than its apply throughput - so amortising four creates per wakeup is a real 2.6x.
//
// 6 IS THE DEFAULT, AND IT IS WHERE THE CURVE FLATTENS - the sweep that says so is the
// one the paragraph above asked for, and it moved the ceiling too (kCreateWindowMax is 8
// now; the old 4 was derived from a reply pool the window does not run on). Three
// interleaved runs per arm on one binary, load frame, create 4,536 sent in every arm:
//
// window 4 1,503 blocking takes 13.23 s median (spread 11.37-16.29)
// window 5 1,277 11.31 s (10.61-12.12)
// window 6 1,155 10.79 s ( 9.69-10.81)
// window 8 859 10.96 s ( 8.92-11.03)
//
// 4->5 buys 1.92 s, 5->6 buys 0.53 s, 6->8 buys NOTHING (-0.18 s, inside a session noise
// of ~1.5-2 s) - so 6 is the smallest window on the flat part and the extra answers a
// deeper one holds buy no time. AND PAST THIS POINT THE FRAME IS NOT WAIT-BOUND ANY MORE:
// window 8 pays 296 fewer blocking takes than window 6 and the wall clock does not move.
// The store is not the constraint either - its peak is logged as it crosses (StreamLink's
// P12 line) and reads 6..11 against a cap of 24 at every arm from 5 up. What is left is
// the constant ~350-400 creates that block for a reason depth does not reach, and the
// 101 MB / 103k records the SERVER has to apply. NOTE THE PREDICATE the whole mechanism rests
// on: an answer is retained because the wire DECLARED it will be read - NOT because its
// caller was fire-and-forget. The window's own creates are fire-and-forget AND read, so a
// flag keyed on wantReply would disable the very mechanism it exists to enable
// (docs/Disaggregated/notes/p12/CREATE-WINDOW-MEASURED.md sections 7-11).
Uint32 CreateWindow = 10;
// MOBILEGL_IPC_ADOPT_TIER: 2 = emulate (client keeps the shadow and pushes), which
// is the only tier P5 implements and the reason persistent-map-push can be non-zero
// at all (R-6). 0 and 1 parse and are Fatal at use with "P11"; they exist now so the
@@ -632,21 +536,6 @@ namespace MobileGL::MG_Config {
// client that is already CPU-bound and costs a frame of latency, which is why the
// default is 1 and not "as deep as the ring".
Uint32 PresentCredit = 1;
// MOBILEGL_IPC_CONTROL_TIMEOUT_MS (CONTRACT-P6 §5.4 D5b): how long a spawn/tcp client
// waits for the SurfaceReply to one surface-control op (eglCreate*Surface, MakeCurrent,
// ...) once the server's backend is up. Its expiry is NOT fatal: the doorbell's death
// latch decides dead (device lost) from alive-but-silent (a named diagnostic). The
// contract named this knob from P6 on; the client hard-coded its default until P7.
Uint32 ControlTimeoutMs = 5000;
// MOBILEGL_IPC_COLD_START_MS (P7): the same wait for the three ops a server may bring its
// NATIVE backend up inside - CreatePbufferSurface, CreateWindowSurface, MakeCurrent -
// until the session's first MakeCurrent is answered ok. The bring-up is lazy (Espryt's
// eglInitialize, Magma's Vulkan instance and device), ~100 ms on a workstation and more
// than the steady 5 s on a loaded CI runner (retrace-split spawn legs, runs 35671704873
// and 35706183230). Never shorter than CONTROL_TIMEOUT_MS; its expiry is the same
// non-fatal named answer. The default is the spawn connect budget, for the same reason:
// "the server has to create a backend, and a cold software rasteriser is not fast".
Uint32 ColdStartMs = 20000;
// MOBILEGL_IPC_STRICT_ERRORS: promote a BARRIER-PULLED field read - and, in a split
// build, the seven sticky forwards that are otherwise exempt - from "count it in
// rsp" to Fatal (R-7.3).
@@ -671,24 +560,8 @@ namespace MobileGL::MG_Config {
// because the resolved mask is logged by whoever starts the apply thread, and the
// string is what an operator typed.
String ServerAffinity = "auto";
// MOBILEGL_IPC_SURFACE (P12, on-screen server window) = offscreen | server. `server` makes
// the client a HEADLESS one: eglCreateWindowSurface / eglCreatePlatformWindowSurface accept
// any native window including NULL, send ONE CreateWindowSurface naming
// WindowKind::ServerOwned (token 0, the size from EGL_WIDTH/EGL_HEIGHT, 0/0 = the server's
// own) and no SetWindowHandle, and take the surface's real geometry back from the server.
// Meaningful only when this client talks to a remote server (MOBILEGL_TRANSPORT=spawn, the
// fork or tcp:// control); under monolith / inproc it is parsed, logged as ignored, and
// changes nothing. `offscreen` (the default) is today's behaviour byte for byte.
// Pbuffers stay pbuffers in both modes (D4: one mode per session, decided by the first).
IpcSurface Surface = IpcSurface::Offscreen;
};
extern IpcTable Ipc;
// P12: the one predicate every client-side consumer of MOBILEGL_IPC_SURFACE asks - a window
// surface is the server's when the knob says so AND there is a remote server to own it.
inline Bool ServerOwnedWindowSurfaces() {
return Transport == TransportMode::Spawn && Ipc.Surface == IpcSurface::Server;
}
#else
// The whole point: in a build without MG_Remote this folds at compile time, so
// `if (MG_Config::Transport != MG_Config::TransportMode::Monolith)` in Init.cpp is a
+6 -79
View File
@@ -16,11 +16,6 @@
#include <cerrno>
#include <cstdlib>
#if MOBILEGL_BUILD_DISAGGREGATED
// std::strcmp, for InitIpc's server-role check (P12). Split-only, so the pull build's TU is
// unchanged (G1).
#include <cstring>
#endif
#ifndef _WIN32
extern char** environ;
@@ -37,7 +32,6 @@ namespace MobileGL::MG_Config {
// and there is nothing to define.
TransportMode Transport = TransportMode::Monolith;
String TransportEndpoint;
Bool SplitTransportRequestedByConfig = false;
IpcTable Ipc;
#endif
} // namespace MobileGL::MG_Config
@@ -336,10 +330,6 @@ namespace MobileGL::MG_ConfigLoader {
}
if (lowered == "inproc") {
MG_Config::Transport = MG_Config::TransportMode::InProcess;
// P7 F1: see Config.h. Set beside the mode, on the two arms that actually resolve
// one, and NOT on the two that name a transport and then stay monolith - a process
// that was refused its transport brings no client half up either.
MG_Config::SplitTransportRequestedByConfig = true;
MGLOG_I("Config: MOBILEGL_TRANSPORT=inproc - the MGPipe record stream crosses a real "
"ring to an apply thread");
return;
@@ -352,7 +342,6 @@ namespace MobileGL::MG_ConfigLoader {
// rather than the fork-coupled shape ARCHITECTURE.md:488 described.
if (lowered == "spawn") {
MG_Config::Transport = MG_Config::TransportMode::Spawn;
MG_Config::SplitTransportRequestedByConfig = true; // P7 F1, as above.
// THE SAME SHAPE AS THE inproc LINE ABOVE, AND FOR THE SAME REASON.
// run_trace_case.cmake asserts on a distinctive sentence from this
// function rather than on `MOBILEGL_TRANSPORT=spawn` alone, because
@@ -397,14 +386,7 @@ namespace MobileGL::MG_ConfigLoader {
// are sanity, not policy.
ipc.RingMb = QueryEnvUint32("MOBILEGL_IPC_RING_MB", 8, 1, 1024);
ipc.StageMb = QueryEnvUint32("MOBILEGL_IPC_STAGE_MB", 32, 1, 4096);
// P7 wave 4 M2 (Config.h has the semantics). 0 is admitted ON PURPOSE as the negative
// control: no forced sync, and MagmaWireReclaimScenario's watermark case must go red.
ipc.WireDeferredMb = QueryEnvUint32("MOBILEGL_IPC_WIRE_DEFERRED_MB", 64, 0, 65536);
ipc.SpinUs = QueryEnvUint32("MOBILEGL_IPC_SPIN_US", 50, 0, 1000000);
// PH-6 (ID-P7-2; Config.h has the semantics). 0 is NOT admitted: a server with no
// patience at all would forfeit a healthy run-ahead client the first time its ring
// filled between two of the client's drains, which is an ordinary backlog.
ipc.EventWaitMs = QueryEnvUint32("MOBILEGL_IPC_EVENT_WAIT_MS", 2000, 1, 600000);
// 0 is admitted ON PURPOSE and is the negative control of exit gate E3(a): it turns
// the persistent-map push OFF, and PersistentCoherentMapScenario must go red.
ipc.PersistentBlockKb = QueryEnvUint32("MOBILEGL_IPC_PERSISTENT_BLOCK_KB", 64, 0, 65536);
@@ -412,15 +394,6 @@ namespace MobileGL::MG_ConfigLoader {
// xxHash64 changed since the last push are shipped.
ipc.PersistentHashSuppress = QueryEnvUint32("MOBILEGL_IPC_PERSISTENT_HASH_SUPPRESS", 1, 0, 1);
ipc.BatchWaits = QueryEnvUint32("MOBILEGL_IPC_BATCH_WAITS", 1, 0, 1);
// The create window. DEFAULT 6, and it works because a link that declares RetainsReplies
// keeps a declared answer until its reader takes it - Config.h carries the three reasons it
// was inert before, the device numbers, and the sweep that put the default at 6 rather
// than 4 or 8 (the curve flattens at 6: 4->5 buys 1.92 s, 5->6 0.53 s, 6->8 nothing).
// Capped at 8: the retained set is bounded by the window's own depth, the store holds 24
// declared answers, and the device sweep showed the wall clock still falling at the old
// cap of 4 (see WireTables.cpp's kCreateWindowMax). WireTables.cpp's static_assert and
// StreamLink's crossing log are the checks on this number.
ipc.CreateWindow = QueryEnvUint32("MOBILEGL_IPC_CREATE_WINDOW", 10, 1, 12);
// The verify harness compares the pushed block against the applier per verb; a
// batched queue lets the comparer read a supplied field mid-apply, which is a
// torn read rather than a divergence. The batch is therefore off whenever the
@@ -441,10 +414,6 @@ namespace MobileGL::MG_ConfigLoader {
// deeper queue buys nothing on a CPU-bound client and pays for it in latency. 0 is NOT
// admitted: a credit of zero would mean "publish no present at all".
ipc.PresentCredit = QueryEnvUint32("MOBILEGL_IPC_PRESENT_CREDIT", 1, 1, 8);
// CONTRACT-P6 D5b's reply bound and P7's cold-start budget (Config.h has the semantics).
// Both are floored at 100 ms: a zero bound would declare every live server silent.
ipc.ControlTimeoutMs = QueryEnvUint32("MOBILEGL_IPC_CONTROL_TIMEOUT_MS", 5000, 100, 600000);
ipc.ColdStartMs = QueryEnvUint32("MOBILEGL_IPC_COLD_START_MS", 20000, 100, 600000);
ipc.StrictErrors = QueryEnvFlag("MOBILEGL_IPC_STRICT_ERRORS");
ipc.Audit = QueryEnvFlag("MOBILEGL_IPC_AUDIT");
QueryEnvVariable("MOBILEGL_IPC_SERVER_AFFINITY", ipc.ServerAffinity, "auto");
@@ -484,63 +453,21 @@ namespace MobileGL::MG_ConfigLoader {
}
}
// P12 (on-screen server window): MOBILEGL_IPC_SURFACE = offscreen | server (Config.h has
// the semantics). An unknown value is named and read as the default, like every knob here.
{
String surface;
QueryEnvVariable("MOBILEGL_IPC_SURFACE", surface, "offscreen");
std::transform(surface.begin(), surface.end(), surface.begin(),
[](unsigned char c) { return static_cast<char>(std::tolower(c)); });
if (surface.empty() || surface == "offscreen") {
ipc.Surface = MG_Config::IpcSurface::Offscreen;
} else if (surface == "server") {
ipc.Surface = MG_Config::IpcSurface::Server;
} else {
MGLOG_W("Config: Ignoring invalid env variable MOBILEGL_IPC_SURFACE='%s'; expected "
"offscreen|server, using offscreen",
surface.c_str());
ipc.Surface = MG_Config::IpcSurface::Offscreen;
}
// (Not said by a server process: a spawned server inherits the client's environment,
// parses this before RunSession sets its own transport, and has no client half anyway.)
const char* role = std::getenv("MOBILEGL_IPC_ROLE");
const Bool serverProcess = role != nullptr && std::strcmp(role, "server") == 0;
if (ipc.Surface == MG_Config::IpcSurface::Server && !serverProcess &&
MG_Config::Transport != MG_Config::TransportMode::Spawn) {
// Said, not silently honoured: there is no remote server here to own a window.
MGLOG_W("Config: MOBILEGL_IPC_SURFACE=server is IGNORED - it asks a remote server "
"(MOBILEGL_TRANSPORT=spawn, a fork or tcp:// control) to own the window surface, "
"and this run has none. Window surfaces stay the client's own");
}
}
if (MG_Config::Transport == MG_Config::TransportMode::Monolith) return;
// One line, on the arm where these numbers decide behaviour, because every one of
// them is a number a bug report has to quote.
// CREATE-WINDOW IS IN THIS LINE BECAUSE A RUN HAS TO SAY WHICH WINDOW IT USED. It was
// missing while the value was a number nobody varied, and the moment it became one that
// changes the wall clock by seconds (the P12 sweep: 28.3 s at 1 down to 10.8 s at 6) a
// log that does not name it makes every run ambiguous about its own configuration.
MGLOG_I("Config: IPC ring=%uMiB stage=%uMiB wire-deferred=%uMiB spin=%uus event-wait=%ums "
"persistent-block=%uKiB create-window=%u "
"adopt-tier=%u verb-barrier=%u run-ahead=%u present-credit=%u control-timeout=%ums "
"cold-start=%ums strict=%d audit=%d role-split-state=%d affinity='%s' surface=%s",
ipc.RingMb, ipc.StageMb, ipc.WireDeferredMb, ipc.SpinUs, ipc.EventWaitMs,
ipc.PersistentBlockKb, ipc.CreateWindow, ipc.AdoptTier,
ipc.VerbBarrier, ipc.RunAhead, ipc.PresentCredit, ipc.ControlTimeoutMs, ipc.ColdStartMs,
MGLOG_I("Config: IPC ring=%uMiB stage=%uMiB spin=%uus persistent-block=%uKiB "
"adopt-tier=%u verb-barrier=%u run-ahead=%u present-credit=%u strict=%d "
"audit=%d role-split-state=%d affinity='%s'",
ipc.RingMb, ipc.StageMb, ipc.SpinUs, ipc.PersistentBlockKb, ipc.AdoptTier,
ipc.VerbBarrier, ipc.RunAhead, ipc.PresentCredit,
static_cast<int>(ipc.StrictErrors), static_cast<int>(ipc.Audit),
static_cast<int>(ipc.RoleSplitState), ipc.ServerAffinity.c_str(),
MG_Config::ServerOwnedWindowSurfaces() ? "server" : "offscreen");
static_cast<int>(ipc.RoleSplitState), ipc.ServerAffinity.c_str());
if (ipc.VerbBarrier == 0) {
MGLOG_W("Config: MOBILEGL_IPC_VERB_BARRIER=0 is the R-1 NEGATIVE CONTROL and is "
"expected to fail: the client still pulls 31 of 63 PipeInputs fields from a "
"live GLContext, so an unbarriered queue lets the server read future values");
}
if (ipc.WireDeferredMb == 0) {
MGLOG_W("Config: MOBILEGL_IPC_WIRE_DEFERRED_MB=0 is the M2 NEGATIVE CONTROL: the "
"server never forces a sync for orphaned wire buffer stores, so a long frame "
"that respecifies and draws holds every one of them until the frame ends");
}
if (ipc.PersistentBlockKb == 0) {
MGLOG_W("Config: MOBILEGL_IPC_PERSISTENT_BLOCK_KB=0 is the E3(a) NEGATIVE CONTROL: "
"the persistent-map push is OFF and a coherent-map scenario must go red");
+1 -53
View File
@@ -21,9 +21,6 @@
#include <MG_Util/ShaderTranspiler/ShaderCompiler.h>
#include <MG_State/GLState/ProgramState/ProgramTranslationCache.h>
#include <MG_Util/ShaderTranspiler/TranslationCache.h>
#if MOBILEGL_PIPE_VERIFY
#include <MG_Backend/MGPipe/PipeInputs.h> // MGPipeVerifyFlushSummary, before Debug::Close in DestroyImpl
#endif
#include <atomic>
#include <mutex>
@@ -102,14 +99,6 @@ namespace MobileGL {
MG_State::GLState::ClearProgramTranslationCache();
MG_Backend::gBackendFunctionsTable = {};
g_isInitialized = false;
#if MOBILEGL_PIPE_VERIFY
// BEFORE Close, and from here rather than from a static destructor (V1 fix round 2):
// Close() nulls the role's sink and Log.cpp's next write reopens it with "w", so the
// FATAL=0 summary the comparator used to write from __run_exit_handlers truncated the
// client half of every such run to that one line. Verify builds only - the guard is
// the compile definition, not a runtime knob, and the pull build gains no byte (G1).
MG_Pipe::MGPipeVerifyFlushSummary();
#endif
if (logLifecycle) {
MG_Util::Debug::Close();
}
@@ -132,50 +121,9 @@ namespace MobileGL {
// boundary counters latch their enable flag here, so every counting site in the
// two backends is a load of an already-settled global for the rest of the run.
MG_Util::PipeStats::Init();
#if MOBILEGL_BUILD_DISAGGREGATED
// F1 (P7 wave 2). THE WIRE COMES UP BEFORE THE FIRST FRONTEND OBJECT IS BORN, and the
// ORDER is the fix - not a wait, and not a friendlier default mask.
//
// MG_State::Init() constructs GLContext, and GLContext's TextureState constructor
// materialises one default texture object per target (GL 3.3 core 3.8,
// TextureState.cpp:62-71). TextureObjectBase's constructor emits resource_create for
// every one of them (TextureState/TextureObject.cpp:168-169), and that emission is
// gated, through PipeFill's FamilyIsLive, on
// CapsMirror::ServerConsumes(kMGPipeSubsystemTextureResources). In the old order the
// mirror was still GENERATION 0 when it was asked - it had no snapshot because the
// session had not been started yet, MG_Backend::Init() being what starts it - so it
// answered from the placeholder, every one of those creates was withheld, and the log
// said so once and then never again:
//
// MG_Remote client: the server does not consume MGPipe subsystem 0x400 - this
// family emits NOTHING and the legacy pull path runs for it (R-8). callMask=0x0,
// caps generation 0
//
// That is not a race and it never was one: the line reproduces byte-for-byte on
// lavapipe and on an Adreno 830, because the two Init calls are two statements in one
// thread. And "the legacy pull path runs for it" is false under split - the client has
// no pull path to fall back to - so the records are simply lost, and only a later
// respecify's self-healing create (TextureEmit.h:872) ever brings one back.
//
// A BOUNDED WAIT INSIDE ServerConsumes CANNOT FIX THIS AND WOULD DEADLOCK: during
// MG_State::Init() no handshake is in flight, and the one that will land is started
// LATER BY THIS SAME THREAD. The only correct answer is to have already brought it up,
// which is what this hook does. ServerConsumes now REFUSES to answer from a
// placeholder (CapsMirror.cpp), so a regression of this order is a named Fatal rather
// than a whole family of silently dropped records.
//
// In a build without MOBILEGL_BUILD_DISAGGREGATED this statement does not exist, so
// the pull build gains no symbol, no branch and no byte - which is what G1 measures.
const Bool splitBackendIsUp = MG_Backend::InitSplitRolesBeforeState();
#endif
MG_State::Init();
MGLOG_D("MG_State initialized");
#if MOBILEGL_BUILD_DISAGGREGATED
if (!splitBackendIsUp)
#endif
{
MG_Backend::Init();
}
MG_Backend::Init();
MGLOG_D("MG_Backend initialized");
MG_Impl::Init();
MGLOG_D("MG_Impl initialized");
-16
View File
@@ -39,21 +39,5 @@ namespace MobileGL::MG_Backend {
// client-minted and needs no backend call, which is P10's. CONTRACT-P5 4 flags this as a
// KNOWN OPEN ITEM and asks v1 to record which way it went: P5 keeps today's order.
void ShutdownSplitRoles();
// F1 (P7 wave 2). Init()'s SPLIT ARM, run BEFORE MG_State::Init() rather than after it.
//
// Returns true when this process took the split path - whether the bring-up succeeded or
// was refused by name - and the caller must then NOT call Init() a second time. Returns
// false under MG_Config::TransportMode::Monolith, where there is nothing to bring up and
// Init() keeps its own place after MG_State::Init().
//
// WHY IT EXISTS AT ALL, rather than MobileGL::Initialize simply calling Init() earlier:
// the monolith arm of Init() must keep running after MG_State::Init(), because
// BackendObject_DirectGLES::Initialize() is the tree's own order for it and moving it is a
// pull-build change G1 forbids. So the split arm - and only the split arm - moves.
//
// It exists ONLY in a split build, for the reason InitServerRoleForSpawn states: a
// definition guarded only on the inside still emits a symbol, and G1 measured that.
Bool InitSplitRolesBeforeState();
#endif
} // namespace MobileGL::MG_Backend
@@ -893,16 +893,6 @@ namespace MobileGL::MG_Backend::DirectGLES {
DestroyEGLContext();
#if MOBILEGL_BUILD_DISAGGREGATED
NoteNativeContextGone();
// P12: under a transport this object is the SERVER's backend and its destruction is the
// end of a session (ServerLoop's apply thread, after the final drain). The in-process
// display server runs the next session in this same process, so the twins this one built
// - naming ids of the context just destroyed - must not answer for the next client's
// handles (Managers.h, DropEveryTwinForEndedServerSession). Monolith keeps its twins.
if (MG_Config::Transport != MG_Config::TransportMode::Monolith) {
DropEveryTwinForEndedServerSession();
// Review fix: and the swap interval it asked for (DirectGLES.h).
ForgetRequestedSwapInterval();
}
#endif
}
+39 -195
View File
@@ -66,20 +66,8 @@
namespace MobileGL::MG_Backend::DirectGLES {
#if MOBILEGL_BUILD_DISAGGREGATED
// A readback on the server writes REPLY SCRATCH, so it has no pack buffer - and this
// function is how every pack-PBO lookup in this file says so under a transport.
//
// THE REASON IS NOT "THE CLIENT REFUSES PACK_BUFFER BEFORE EMISSION", which is what this
// comment used to claim and is not true of the tree (P3b/P4b espryt D1 slice 4). The client
// SERVICES the pack PBO itself, AFTER the reply lands: EmitTables.cpp uploads the reply's
// tight rows into the bound buffer with pbo->UploadSubData, one row at a time at the stride
// the application's GL_PACK_* state implies, so padding and untouched bytes survive. A
// refusal would have been visible as a GL error; what actually happens is an ordinary
// buffer upload the client performs on its own side.
//
// The server's half is ID-49's: read with NEUTRAL pack state into a tight w*h*bpp reply.
// Which is exactly why the server must see NO pack buffer here - not because the client
// forbade one, but because the client kept it.
// read_pixels writes server reply scratch. The client refuses PACK_BUFFER before
// emission, so no frontend pack binding can affect this destination.
static const SharedPtr<MG_State::GLState::BufferObject>& SplitReadbackPackBuffer() {
static const SharedPtr<MG_State::GLState::BufferObject> none;
return none;
@@ -691,29 +679,24 @@ namespace MobileGL::MG_Backend::DirectGLES {
// family bit, so an operator can put the whole binding-point family back on the
// frontend walk with one cleared bit.
//
// THE BINDING-POINT FAMILY'S DEPENDENCY ROW IS READ FROM MG_Pipe/SubsystemDeps.def
// (P3b/P4b R-5, switched over by wave 2-D package D3), refused here rather than half-run,
// in ResolveVertexInputSubsystemArm's exact shape. The hand-rolled
// `bitSet && !resourcesBitSet` this used to be was the sixth statement of D-K2's rule -
// the .def's own "WHO READS IT" section names this function, and now it does. The reason
// is the table's and is printed from it.
// BIT 13 REQUIRES BIT 7, refused here rather than half-run, in
// ResolveVertexInputSubsystemArm's exact shape and for its exact reason: every
// MGPBufferRange::Res is resolved through the resource slot table and only bit 7 puts
// twins there, so the pair would produce a walk in which every point logged once and
// `continue`d WITHOUT unbinding - every draw then reading through whatever the driver
// last had at that point.
Bool ResolveBufferBindingSubsystemArm() {
if (MG_Config::Transport == MG_Config::TransportMode::Monolith) return false;
const Uint64 mask = MG_Config::Features.PipePush;
const Bool bitSet = (mask & MG_Pipe::kMGPipeSubsystemBufferBindings) != 0;
if (bitSet &&
!MG_Pipe::MGPipeSubsystemDependenciesAreSet(MG_Pipe::kMGPipeSubsystemBufferBindings, mask)) {
const Uint64 required =
MG_Pipe::MGPipeSubsystemRequires(MG_Pipe::kMGPipeSubsystemBufferBindings);
const Bool bitSet =
(MG_Config::Features.PipePush & MG_Pipe::kMGPipeSubsystemBufferBindings) != 0;
const Bool resourcesBitSet =
(MG_Config::Features.PipePush & MG_Pipe::kMGPipeSubsystemResources) != 0;
if (bitSet && !resourcesBitSet) {
MGLOG_E("MGPipe: kMGPipeSubsystemBufferBindings (bit 13) is set but "
"MOBILEGL_PIPE_PUSH=0x%llx does not carry every bit "
"MG_Pipe/SubsystemDeps.def says it requires (requires 0x%llx, missing "
"0x%llx): %s - REFUSING bit 13 and running the legacy binding-point walk. "
"Set every bit of the row, or clear bit 13",
static_cast<unsigned long long>(mask),
static_cast<unsigned long long>(required),
static_cast<unsigned long long>(required & ~mask),
MG_Pipe::MGPipeSubsystemDependencyWhy(MG_Pipe::kMGPipeSubsystemBufferBindings));
"kMGPipeSubsystemResources (bit 7) is clear; every MGPBufferRange::Res "
"resolves through the resource slot table, which only bit 7 populates - "
"REFUSING bit 13 and running the legacy binding-point walk. Set bit 7 as "
"well, or clear both");
return false;
}
MGLOG_D("MGPipe: Espryt binding-point family runs the %s arm",
@@ -1751,22 +1734,6 @@ namespace MobileGL::MG_Backend::DirectGLES {
g_GLESFuncs.glResumeTransformFeedback != nullptr;
}
#if MOBILEGL_BUILD_DISAGGREGATED
// How wide one OnBufferWriteback may be for a capture range of `rangeBytes`, which is
// the whole range when the transport imposes no limit (monolith, where the callback is
// a direct call with no ring under it) or when the range already fits one.
//
// BOTH XFB WRITEBACK PRODUCERS ASK THE SAME FUNCTION. They post from different sources
// - one from a live glMapBufferRange mapping, one from a staged Vector<Uint8> - but
// they post the same KIND of record into the same ring, and a second spelling of the
// width is how one of them ends up being the producer that still kills the server.
SizeT XfbWritebackSliceStep(SizeT rangeBytes) {
const Uint64 slice = MG_Pipe::MGPipeBufferWritebackSliceBytes();
if (slice == 0 || slice >= static_cast<Uint64>(rangeBytes)) return rangeBytes;
return static_cast<SizeT>(slice);
}
#endif
// Mirrors one capture span's results into the frontend CPU shadows. The GPU wrote
// the capture buffers behind the frontend's back, so the shadows that back
// MapBuffer/GetBufferSubData still hold the pre-draw bytes. Buffers whose storage
@@ -1812,27 +1779,11 @@ namespace MobileGL::MG_Backend::DirectGLES {
continue;
}
if (MG_Pipe::gMGPipeCallbacks.OnBufferWriteback != nullptr) {
// ONE EVENT PER SLICE, NOT ONE PER CAPTURE. The bytes travel
// INLINE in a SEG_EVENT record and the ring refuses any record
// above half its capacity outright, so a whole-range post of a
// capture wider than ~128 KiB was Fatal{EventRingOverflow} - the
// SERVER dying on a large buffer. The slicing shape is
// BufferObject.cpp's one ring over: in-order delivery makes the
// last slice's landing imply every earlier one, so the client
// needs nothing new to reassemble them.
//
// INSIDE THE MAPPING, deliberately: the map is the expensive part
// and the slices are reads of one live pointer, so this unmaps
// once below however many events it posts.
const SizeT step = XfbWritebackSliceStep(size);
for (SizeT off = 0; off < size; off += step) {
const SizeT bytes = std::min(step, size - off);
MG_Pipe::gMGPipeCallbacks.OnBufferWriteback(
res, target.start + off,
MG_Pipe::MGPBlobRef{
reinterpret_cast<Uint64>(static_cast<Uint8*>(mapped) + off),
static_cast<Uint64>(bytes), MG_Pipe::kMGHostSpanSegNone, 0});
}
MG_Pipe::gMGPipeCallbacks.OnBufferWriteback(
res, target.start,
MG_Pipe::MGPBlobRef{reinterpret_cast<Uint64>(mapped),
static_cast<Uint64>(size),
MG_Pipe::kMGHostSpanSegNone, 0});
} else {
MGLOG_E_ONCE("EndTransformFeedback: no reverse channel is installed, so the "
"captured bytes of buffer {%u,%u} cannot reach the client shadow",
@@ -1986,43 +1937,17 @@ namespace MobileGL::MG_Backend::DirectGLES {
if (MG_Config::Transport != MG_Config::TransportMode::Monolith) {
splitRes = target.handle;
splitResource = BufferImpl::FindBufferResourceForHandle(splitRes);
if (splitResource == nullptr) {
// THE ONLY DISCARD LEFT, and it is the impossible one: this target
// was recorded by BindBufferRange/Base against a handle the applier
// had already minted a twin for, so no twin here means the slot
// table and the capture list disagree about one resource. There is
// no backendId to upload into either, so there is nothing to do but
// name it.
const Uint8* hostBytes = splitResource != nullptr ? splitResource->hostBytes : nullptr;
if (splitResource == nullptr || hostBytes == nullptr) {
MGLOG_E_ONCE("EndTransformFeedback: a scattered capture target (handle {%u,%u}) has "
"no server twin at all; its capture is discarded",
"no server shadow to read the pre-capture bytes from; its capture is "
"discarded",
splitRes.Slot, splitRes.Gen);
continue;
}
const Uint8* hostBytes = splitResource->hostBytes;
// A NULL SHADOW IS NOT A LOST CAPTURE. It is the ORPHANED store
// (glBufferData(size, NULL) with no resource_subdata since), which
// M-3 declares legal: every byte the application has not staged is
// UNDEFINED by its own declaration, and `staged` is already
// value-initialised to zero - which is byte for byte what the monolith
// arm scatters over when it reads a fresh MappedData(). Skipping the
// Memcpy is therefore the WHOLE of the difference; skipping the TARGET
// threw the varyings away and left the application's buffer holding its
// pre-draw bytes under GL_NO_ERROR, the silent-loss class this file's
// preamble exists to close. The streaming idiom that hits it - orphan,
// partial glBufferSubData, capture into the rest - is ordinary.
if (hostBytes != nullptr) {
// Managers.cpp's pool-reuse ladder guards its whole-store
// MGL_SERVER_STAGED_REQUIRE with exactly this predicate and for
// exactly this reason: for a store whose content the application
// SUPPLIED a coverage gap is a missing record and zero-filling past
// it is silent data loss (Fatal by name); for an orphaned one the
// gap is its own undefined content and the read is legal.
if (BufferImpl::ResourceContentIsDeclared(splitRes)) {
BufferImpl::RequireStagedCoverage(*splitResource, hostBytes, target.start,
target.end, "xfb_scatter_pre_capture");
}
Memcpy(staged.data(), hostBytes + target.start, rangeBytes);
}
BufferImpl::RequireStagedCoverage(*splitResource, hostBytes, target.start, target.end,
"xfb_scatter_pre_capture");
Memcpy(staged.data(), hostBytes + target.start, rangeBytes);
} else
#endif
Memcpy(staged.data(), target.buffer->MappedData() + target.start, rangeBytes);
@@ -2041,23 +1966,11 @@ namespace MobileGL::MG_Backend::DirectGLES {
#if MOBILEGL_BUILD_DISAGGREGATED
if (MG_Config::Transport != MG_Config::TransportMode::Monolith) {
if (MG_Pipe::gMGPipeCallbacks.OnBufferWriteback != nullptr) {
// Sliced for the reason the readback path above is sliced: the bytes
// are INLINE in a SEG_EVENT record and the ring refuses a record wider
// than half its capacity outright, so one whole-range post of a
// capture over ~128 KiB was Fatal{EventRingOverflow} and the server
// died. Only the EVENT is cut; the glBufferSubData below stays one
// call over the whole `staged` vector, because the ES store has no
// ring and cutting it would change how many backend calls one
// application call makes.
const SizeT step = XfbWritebackSliceStep(rangeBytes);
for (SizeT off = 0; off < rangeBytes; off += step) {
const SizeT bytes = std::min(step, rangeBytes - off);
MG_Pipe::gMGPipeCallbacks.OnBufferWriteback(
splitRes, target.start + off,
MG_Pipe::MGPBlobRef{reinterpret_cast<Uint64>(staged.data() + off),
static_cast<Uint64>(bytes),
MG_Pipe::kMGHostSpanSegNone, 0});
}
MG_Pipe::gMGPipeCallbacks.OnBufferWriteback(
splitRes, target.start,
MG_Pipe::MGPBlobRef{reinterpret_cast<Uint64>(staged.data()),
static_cast<Uint64>(rangeBytes),
MG_Pipe::kMGHostSpanSegNone, 0});
} else {
MGLOG_E_ONCE("EndTransformFeedback: no reverse channel is installed, so the "
"scattered capture of buffer {%u,%u} cannot reach the client shadow",
@@ -14934,43 +14847,11 @@ namespace MobileGL::MG_Backend::DirectGLES {
if (width <= 0 || sliceHeight <= 0 || sliceCount <= 0) {
return true;
}
const void* shadow = textureMipmapObject->MapMipmapData(uploadTarget, level);
#if MOBILEGL_PIPE_PUSH
#if MOBILEGL_BUILD_DISAGGREGATED
// P4a (D-M) SAID "a split server holds no shadow to convert" AND ABORTED. That is the
// premise this row of P3b/P4b re-examined, and it is wrong in the only case that can
// get here: the level storage this converts IS the server's own, fed by the staged
// texture store, so when MapMipmapData answers the conversion is reading bytes that
// exist on this side and the answer is right. There is nothing to migrate - the
// emulation was never reaching across the split, it only looked as though it must.
//
// WHEN IT DOES NOT ANSWER, THE VERB DECLINES BY NAME (rule I) RATHER THAN ABORTING.
// std::abort inside a server that is answering a client's readback takes the whole
// session down for a texture level it happens not to hold; GL's own answer for "this
// read cannot be served" is an error code and untouched destination bytes, and a
// client that gets GL_INVALID_OPERATION can carry on. The abort also bypassed
// Session::Fail entirely, which is the funnel the census gate watches.
//
// THE FUNNEL KEEPS ITS TEETH FOR THE OTHER SITES: MGPipeUnmigratedEmulation still
// aborts for generate-mipmap-storage, generate-mipmap-cpu-fallback,
// generate-mipmap-cpu-filter and texture-remint-pull, which really do reach into a
// client address space. Only this call site is retired, and only because its own
// premise did not hold.
if (MG_Config::Transport != MG_Config::TransportMode::Monolith) {
if (shadow == nullptr) {
MGLOG_E_ONCE("GetTexImage: no level shadow on this side for target=0x%x level=%d, and under an "
"active transport there is no client shadow to fall back to - the read is "
"DECLINED and the destination keeps its bytes",
static_cast<unsigned>(uploadTarget), level);
MGB_CTX->RecordError(
ErrorCode::InvalidOperation,
MakeUnique<GenericErrorInfo>(
"DirectGLES", "GetTexImage",
"the level has no shadow on the server and there is no client shadow to convert"));
return false;
}
} else
#endif
// P4a (D-M). glGetTexImage is answered out of the frontend's own level shadow,
// converted to the requested format and type. Monolith is unchanged; a split server
// holds no shadow to convert, and the readback family as a whole is P3b/P4b's and
// P8's rather than this phase's.
MG_Pipe::MGPipeUnmigratedEmulation("get-tex-image-shadow");
#endif
const auto& pixelPackBufferObject =
@@ -14983,6 +14864,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
return true;
}
const void* shadow = textureMipmapObject->MapMipmapData(uploadTarget, level);
if (!shadow) {
return false;
}
@@ -15816,13 +15698,6 @@ namespace MobileGL::MG_Backend::DirectGLES {
static EGLSurface g_Surface = EGL_NO_SURFACE;
static EGLConfig g_Config = nullptr;
#if MOBILEGL_BUILD_DISAGGREGATED
// P12 (on-screen server window), D3: true only while InitWindowSurface publishes the default
// framebuffer's shape, so that publish - and no pbuffer's - may carry the surface's extent.
// Split builds only: the pull build's publish is unchanged (G1).
static Bool g_publishWindowExtent = false;
#endif
static Bool QueryCurrentSurfaceSize(Int& outWidth, Int& outHeight) {
outWidth = 0;
outHeight = 0;
@@ -15954,23 +15829,6 @@ namespace MobileGL::MG_Backend::DirectGLES {
MG_Pipe::MGPSurfaceInfo info{};
info.InternalFormat = static_cast<Uint32>(depthFormat);
info.IsDefault = 1;
#if MOBILEGL_BUILD_DISAGGREGATED
// P12 (on-screen server window), D3: A WINDOW SURFACE OF A REMOTE SESSION ALSO SAYS HOW
// BIG IT IS. Under spawn / tcp (this server process set Transport=Spawn in RunSession)
// the only window surface is the server's own - a headless client's ServerOwned one -
// and that client learns its extent here and from the reply, as Magma's swapchain
// already tells it. An extent switches the client's consumer to the reallocating arm
// (ClientSession.cpp ApplySurfaceChangedToClient), so it is deliberately NOT published
// for a pbuffer, nor under inproc / monolith: those keep the format-only shape above.
if (g_publishWindowExtent && MG_Config::Transport == MG_Config::TransportMode::Spawn) {
Int extentWidth = 0;
Int extentHeight = 0;
if (QueryCurrentSurfaceSize(extentWidth, extentHeight)) {
info.Width = static_cast<Uint32>(extentWidth);
info.Height = static_cast<Uint32>(extentHeight);
}
}
#endif
MG_Pipe::gMGPipeCallbacks.OnSurfaceChanged(&info);
} else
#endif
@@ -16246,10 +16104,6 @@ namespace MobileGL::MG_Backend::DirectGLES {
ApplyRequestedSwapInterval();
}
#if MOBILEGL_BUILD_DISAGGREGATED
void ForgetRequestedSwapInterval() { g_requestedSwapInterval = -1; }
#endif
Bool InitWindowSurface(NativeWindowType window) {
if (!window) return false;
@@ -16261,17 +16115,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
if (!MakeCurrent()) return false;
ApplyRequestedSwapInterval();
#if MOBILEGL_BUILD_DISAGGREGATED
// P12 (D3): this publish may carry the window's extent (see the push arm of the publish) -
// review fix: only when the window is the SERVER's own (a headless client's ServerOwned
// surface). A window the client named keeps the format-only publish without the knob.
g_publishWindowExtent = MG_Pipe::MGPipeServerOwnedWindow() != nullptr &&
reinterpret_cast<const void*>(window) == MG_Pipe::MGPipeServerOwnedWindow();
PublishDefaultFramebufferDepthStencilFormat();
g_publishWindowExtent = false;
#else
PublishDefaultFramebufferDepthStencilFormat();
#endif
MGLOG_D("EGL context created successfully: display=%p, surface=%p, context=%p. window=%p", g_Display, g_Surface,
g_Context, window);
@@ -188,13 +188,6 @@ namespace MobileGL::MG_Backend::DirectGLES {
// Applies (or defers until the window surface exists) the app-requested
// eglSwapInterval on the native EGL surface.
void SetSwapInterval(Int interval);
#if MOBILEGL_BUILD_DISAGGREGATED
// P12 review fix: the swap interval an ended server session asked for is not the next one's.
// The request outlives the context on purpose (a surface re-created mid-session re-applies it),
// so the in-process display server's session end forgets it: the next session starts at the
// driver's default until it asks (BackendObject_DirectGLES's destructor under a transport).
void ForgetRequestedSwapInterval();
#endif
void SetEGLFuncsTable(const MG_External::EGLFunctionsTable& eglFuncs);
void SetGLESFuncsTable(const MG_External::GLESFunctionsTable& glesFuncs);
void SetGLESCapabilities(const MG_External::GLESCapabilities& capabilities);
+117 -297
View File
@@ -188,18 +188,9 @@ namespace MobileGL::MG_Backend::DirectGLES {
namespace {
Bool g_processTeardown = false;
std::once_flag g_teardownSentinelOnce;
#if MOBILEGL_BUILD_DISAGGREGATED
// P12: raised only while DropEveryTwinForEndedServerSession empties the twin tables, on the
// apply thread that is the only reader of the twins (Managers.h).
Bool g_serverSessionTwinTeardown = false;
#endif
} // namespace
#if MOBILEGL_BUILD_DISAGGREGATED
Bool InProcessTeardown() { return g_processTeardown || g_serverSessionTwinTeardown; }
#else
Bool InProcessTeardown() { return g_processTeardown; }
#endif
void EnsureProcessTeardownSentinel() {
std::call_once(g_teardownSentinelOnce,
[] { std::atexit(+[] { g_processTeardown = true; }); });
@@ -316,9 +307,8 @@ namespace MobileGL::MG_Backend::DirectGLES {
// whole death itself (MGPipeEmitVertexElementsDestroyAndFree: delete the
// applier record, raise this notice, free the slot), because the slot is minted
// client-side on every backend and a backend that installs no death ops - which
// Magma did not until P7 wave 2 package C, and whose table even now only EMITS
// the wire record - otherwise leaked the slot and the record per VAO for the
// life of the process. What is left here is the one thing only this
// Magma deliberately does not - otherwise leaked the slot and the record per
// VAO for the life of the process. What is left here is the one thing only this
// side can do: drop the driver VAO the twin owns. It is raised while the handle
// still resolves, so OnFrontendObjectDestroyed's shared free (which the other
// five kinds still depend on) is simply the one that gets there first; the
@@ -405,36 +395,6 @@ namespace MobileGL::MG_Backend::DirectGLES {
return false;
}
}
// P12: see Managers.h. Every table is replaced by an empty one, holders first (views before
// the textures they view, framebuffers before their attachments, VAOs before the buffers they
// fetch from), so the last reference to each twin goes here and its destructor - answered
// InProcessTeardown() - touches neither the driver nor another TU's statics.
void DropEveryTwinForEndedServerSession() {
if (g_processTeardown) return;
g_serverSessionTwinTeardown = true;
SamplerViewImpl::g_backendSamplerViews = {};
FramebufferImpl::g_backendFramebufferObjects = {};
VertexArrayImpl::g_backendVertexArrayObjects = {};
PrgramImpl::g_backendProgramObjects = {};
SamplerImpl::g_backendSamplerObjects = {};
TextureImpl::g_backendTextureObjects = {};
RenderbufferImpl::g_backendRenderbufferObjects = {};
BufferImpl::g_backendBufferResources = {};
// P12 review fix (major): AND THE UNIT SHADOWS THAT POINT AT THEM. A texture or sampler twin
// scrubs itself out of g_boundTexturesCache / g_boundSamplersCache in its destructor - but
// not under InProcessTeardown(), which answered true for every twin just dropped. Left
// behind, those raw pointers name freed twins; the next session's twin allocated at the same
// address then reads "already bound" and skips its glBindTexture / glBindSampler on a
// context where nothing is bound, so its uploads land on texture 0 and it samples black.
// The new context's active unit is GL_TEXTURE0, so the active-unit shadow goes back to 0 too.
TextureImpl::g_boundTexturesCache = {};
TextureImpl::g_activeTextureUnit = 0;
SamplerImpl::g_boundSamplersCache = {};
g_serverSessionTwinTeardown = false;
MGLOG_I("DirectGLES: the ended server session's twins are dropped (every kind, no driver call); the next "
"session in this process starts from empty twin tables");
}
#endif
// The one sentence that decides the arm, written once so that a test can drive every
@@ -2172,10 +2132,23 @@ namespace MobileGL::MG_Backend::DirectGLES {
const auto* record = ResourceRecordOf(res);
return record != nullptr ? static_cast<SizeT>(record->Desc.Width) : 0;
}
// ResourceContentIsDeclared MOVED OUT OF THIS ANONYMOUS NAMESPACE (P3b/P4b espryt
// D1 slice 1) to sit beside RequireStagedCoverage at namespace scope: the XFB
// scatter in DirectGLES.cpp has to ask the same M-3 question this file's pool-reuse
// ladder asks, and the two must not be able to answer it differently.
#if MOBILEGL_BUILD_DISAGGREGATED
// M-3's rule for the two WHOLE-STORE readers (v1 round 3). The descriptor is the
// application's own statement about the store: HasDefinedContent set means it SUPPLIED
// the content (glBufferData(size, data)), which under split arrives as resource_subdata
// records behind the respecify (table 1 row 19) - so a coverage gap at the draw is a
// MISSING RECORD and the zero-fill past the coverage is not the application's bytes.
// Clear means it ORPHANED the store (glBufferData(size, NULL), glBufferStorage(NULL)):
// every byte it has not staged since is UNDEFINED by its own declaration, the streaming
// idiom (orphan, partial glBufferSubData, draw) is the ordinary case, and uploading the
// shadow's zero-fill for the rest is exactly what the monolith arm uploads from
// MappedData(). Round 2 refused both shapes and aborted six LargeArenaAdoption /
// ResourceSubsystemControl entries on the joint by name (v1-v3.md 6).
Bool ResourceContentIsDeclared(MG_Pipe::MGPipeHandle res) {
const auto* record = ResourceRecordOf(res);
return record != nullptr && record->Desc.HasDefinedContent != 0;
}
#endif
void Ops_H_Create(MG_Pipe::MGPipeHandle res, const MG_Pipe::MGPResourceDesc& desc) {
(void)res;
@@ -2773,13 +2746,12 @@ namespace MobileGL::MG_Backend::DirectGLES {
if (!store.CopiesIntoServerStorage()) return;
const Uint64 key = MG_Remote::Server::StagedTextureStore::KeyForHandle(res);
if (level != nullptr) {
// ONE glTexImage*D redefined one level: its exact extent crossed with the
// accepted scope carrier, including a legal noncanonical mutable mip.
// 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,
IntVec3{static_cast<Int>(level->Width), static_cast<Int>(level->Height),
static_cast<Int>(level->Depth)},
desc.Target, desc.InternalFormat);
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.
@@ -2794,8 +2766,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
store.NoteLevelDefined(
key, static_cast<Uint16>(uploadTarget), static_cast<Uint16>(levelIndex),
MG_Remote::Server::StagedTextureMipExtent(desc.Target, desc.Width, desc.Height,
desc.Depth, levelIndex),
desc.Target, desc.InternalFormat);
desc.Depth, levelIndex));
}
}
}
@@ -2993,26 +2964,24 @@ namespace MobileGL::MG_Backend::DirectGLES {
}
Bool ResolveVertexInputSubsystemArm() {
const Uint64 mask = MG_Config::Features.PipePush;
const Bool bitSet = (mask & MG_Pipe::kMGPipeSubsystemVertexInput) != 0;
// The vertex-input family's row, READ FROM MG_Pipe/SubsystemDeps.def (P3b/P4b R-5,
// switched over by wave 2-D package D3) rather than restated as the hand-rolled
// `bitSet && !resourcesBitSet` this function used to carry - one of the six statements
// of D-K2's rule that R-5 found with nothing comparing them. The table's own sentence
// is what the refusal prints. The mirror pair (bit 7 set, bit 8 clear) is fine - the
// legacy VAO walk calls BindAttributeBuffer -> EnsureBufferResource, which dispatches
// to the handle arm by itself - and lives with the other mirror pairs in MGPipe.h.
if (bitSet && !MG_Pipe::MGPipeSubsystemDependenciesAreSet(MG_Pipe::kMGPipeSubsystemVertexInput, mask)) {
MGLOG_E("MGPipe: kMGPipeSubsystemVertexInput (bit 8) is set but MOBILEGL_PIPE_PUSH="
"0x%llx does not carry every bit MG_Pipe/SubsystemDeps.def says it requires "
"(requires 0x%llx, missing 0x%llx): %s - REFUSING bit 8 and running the "
"legacy vertex-input arm. Set every bit of the row, or clear bit 8",
static_cast<unsigned long long>(mask),
static_cast<unsigned long long>(
MG_Pipe::MGPipeSubsystemRequires(MG_Pipe::kMGPipeSubsystemVertexInput)),
static_cast<unsigned long long>(
MG_Pipe::MGPipeSubsystemRequires(MG_Pipe::kMGPipeSubsystemVertexInput) & ~mask),
MG_Pipe::MGPipeSubsystemDependencyWhy(MG_Pipe::kMGPipeSubsystemVertexInput));
const Bool bitSet = (MG_Config::Features.PipePush & MG_Pipe::kMGPipeSubsystemVertexInput) != 0;
const Bool resourcesBitSet =
(MG_Config::Features.PipePush & MG_Pipe::kMGPipeSubsystemResources) != 0;
// BIT 8 REQUIRES BIT 7, and it is refused here rather than half-run. The vertex-input
// handle arm resolves every attribute's driver buffer id through
// FindBufferResourceForHandle, i.e. out of the resource SLOT TABLE - and only bit 7
// puts twins in that table (with bit 7 clear EnsureBufferResource takes the legacy
// arm and parks the twin on PipeResource::m_backend instead). The pair therefore
// produced a walk in which every BindAttributeBufferByHandle logged once and
// `continue`d WITHOUT disabling the array, so every draw fetched through whatever
// pointer the driver VAO last held. The mirror pair (bit 7 set, bit 8 clear) is fine:
// the legacy VAO walk calls BindAttributeBuffer -> EnsureBufferResource, which
// dispatches to the handle arm by itself.
if (bitSet && !resourcesBitSet) {
MGLOG_E("MGPipe: kMGPipeSubsystemVertexInput (bit 8) is set but kMGPipeSubsystemResources "
"(bit 7) is clear; the vertex-input handle arm resolves attribute buffer ids "
"through the resource slot table, which only bit 7 populates - REFUSING bit 8 and "
"running the legacy vertex-input arm. Set bit 7 as well, or clear both");
return false;
}
#if MOBILEGL_PIPE_LEGACY_MEMOS
@@ -3050,33 +3019,17 @@ namespace MobileGL::MG_Backend::DirectGLES {
// refusal, because MOBILEGL_ASSERT compiles out at INFO and a resource that silently
// stops being twinned is the failure mode the refusal exists to replace.
if (res.Slot >= BackendBufferResourceTable::kMaxHandleSlot) {
#if MOBILEGL_BUILD_DISAGGREGATED
MG_Pipe::MGPipeSessionFail( // @Ph-declined (ID-P7-1): PH-2 stays Fatal, CONTRACT-P7 §12
MG_Pipe::MGPipeFatalFamily::ProtocolCorruption,
"MGPipe: Fatal{ProtocolCorruption, \"BackendSlotTable.HandleSlot\"} - "
"buffer twin request named slot %u, past this table's %u bound",
res.Slot, BackendBufferResourceTable::kMaxHandleSlot);
#else
MGLOG_E_ONCE("MGPipe: resource handle slot %u is past the backend table's %u bound - "
"refusing to twin it",
res.Slot, BackendBufferResourceTable::kMaxHandleSlot);
return nullptr;
#endif
}
const Uint32 liveGen = g_backendBufferResources.LiveGenAt(res.Slot);
if (liveGen != 0 && liveGen > res.Gen) {
#if MOBILEGL_BUILD_DISAGGREGATED
MG_Pipe::MGPipeSessionFail( // @Ph-declined (ID-P7-1): PH-2 stays Fatal, CONTRACT-P7 §12
MG_Pipe::MGPipeFatalFamily::ProtocolCorruption,
"MGPipe: Fatal{ProtocolCorruption, \"BackendSlotTable.Generation\"} - "
"buffer twin request named generation %u at slot %u, behind live generation %u",
res.Gen, res.Slot, liveGen);
#else
MGLOG_E_ONCE("MGPipe: resource handle {%u, %u} names a generation BEHIND the live twin's "
"%u - refusing rather than dropping the incumbent's driver storage",
res.Slot, res.Gen, liveGen);
return nullptr;
#endif
}
auto& twin = g_backendBufferResources.GetOrCreate(res);
if (!twin) {
@@ -3098,27 +3051,6 @@ namespace MobileGL::MG_Backend::DirectGLES {
SizeT end, const char* site) {
ServerStaged().RequireCoverage(&resource, hostBase, start, end, site);
}
// M-3's rule for the WHOLE-STORE readers (v1 round 3). The descriptor is the
// application's own statement about the store: HasDefinedContent set means it SUPPLIED
// the content (glBufferData(size, data)), which under split arrives as resource_subdata
// records behind the respecify (table 1 row 19) - so a coverage gap at the draw is a
// MISSING RECORD and the zero-fill past the coverage is not the application's bytes.
// Clear means it ORPHANED the store (glBufferData(size, NULL), glBufferStorage(NULL)):
// every byte it has not staged since is UNDEFINED by its own declaration, the streaming
// idiom (orphan, partial glBufferSubData, draw) is the ordinary case, and uploading the
// shadow's zero-fill for the rest is exactly what the monolith arm uploads from
// MappedData(). Round 2 refused both shapes and aborted six LargeArenaAdoption /
// ResourceSubsystemControl entries on the joint by name (v1-v3.md 6).
//
// AT NAMESPACE SCOPE, not in the anonymous namespace it was written in (P3b/P4b espryt
// D1 slice 1): the XFB scatter guards ITS whole-store read with the same question, and
// a second spelling of "did the application declare these bytes" is how the pool-reuse
// ladder and the scatter end up disagreeing about one buffer.
Bool ResourceContentIsDeclared(MG_Pipe::MGPipeHandle res) {
const auto* record = ResourceRecordOf(res);
return record != nullptr && record->Desc.HasDefinedContent != 0;
}
#endif
MG_Pipe::MGPipeHandle HandleOfBuffer(const MG_State::GLState::BufferObject* bufferObject) {
@@ -4287,69 +4219,17 @@ namespace MobileGL::MG_Backend::DirectGLES {
// Fatal{PipeLegacyMemosDisabled, ...} rather than running the very arm the operator asked
// to have taken away and handing back a result measured on it.
namespace {
// Shared by the dependent families, so the refusal reads the same way every time and a
// future family cannot invent a different wording. Returns true when the dependency is
// missing, having said so once.
//
// P3b/P4b wave 2-D package D3: THE ROWS ARE READ FROM MG_Pipe/SubsystemDeps.def AND ARE
// NO LONGER RESTATED HERE. This function used to take a single dependency BIT written out
// at each call site - the server's own copy of the rule, one of the six statements R-5
// found and two of which had drifted - and a family with two required bits needed two
// guarded calls with two hand-written sentences. It now takes the FAMILY and asks
// MGPipeSubsystemDependenciesAreSet, so the set of required bits, the subset that is
// actually missing and the reason all come from the table; `what` is only the family's
// own name. The client's gate reads the same rows
// (MG_Impl/Pipe/PipeFill.cpp P4aFamilyDependencyBits), which is what makes
// MG_Test/Backend/DirectGLES/SubsystemDepsTest.cpp's comparison of the two a comparison
// of two readers rather than of two copies.
Bool PipeSubsystemDependencyMissing(Uint64 mask, Uint64 family, const char* what) {
if (MG_Pipe::MGPipeSubsystemDependenciesAreSet(family, mask)) return false;
const Uint64 required = MG_Pipe::MGPipeSubsystemRequires(family);
MGLOG_E("MGPipe: %s is set but MOBILEGL_PIPE_PUSH=0x%llx does not carry every bit "
"MG_Pipe/SubsystemDeps.def says it requires (requires 0x%llx, missing 0x%llx): "
"%s - REFUSING the dependent bit and running the legacy arm. Set every bit of "
"the row, or clear the family's own",
what, static_cast<unsigned long long>(mask),
static_cast<unsigned long long>(required),
static_cast<unsigned long long>(required & ~mask),
MG_Pipe::MGPipeSubsystemDependencyWhy(family));
// Shared by the three dependent families, so the refusal reads the same way three times
// and a future fourth cannot invent a different wording. Returns true when the
// dependency is missing, having said so once.
Bool PipeSubsystemDependencyMissing(Uint64 mask, Uint64 dependencyBit, const char* what) {
if ((mask & dependencyBit) != 0) return false;
MGLOG_E("MGPipe: %s - REFUSING the dependent bit and running the legacy arm. "
"Set both bits, or clear both",
what);
return true;
}
#if MOBILEGL_BUILD_DISAGGREGATED
// THE SAFETY ARGUMENT P4a MADE AND NEVER RAN (P3b/P4b espryt D1 slice 5).
//
// "Running the legacy arm" is a real answer in a monolith and a POSTPONED CRASH under a
// transport. All four pre-handle arms reach frontend state through accessors that are
// BARRIER_PULLED rows (FieldOwnership.def) - GetFramebufferBindingSlot is the loudest of
// them - and under an active transport that state belongs to a client that is no longer
// parked behind this apply. The accessor's honest answer is
// Fatal{UnmigratedPipeInput, "<field>@<verb>"}, raised on the first verb that reaches it.
//
// So the verdict "Legacy" under a transport is not safe, it is merely quiet. The audit
// that called g_fboTextureSyncList "separation-safe because the record arm returns first"
// was right only while the record arm is ARMED, and nothing checked that.
//
// A FRAME-TIME FATAL IS THE WORST SPELLING OF "MOBILEGL_PIPE_PUSH LEFT BIT 9 CLEAR": it
// arrives after a session is up, inside a scenario body, naming an accessor and a verb
// rather than the mask that chose them. Stop at resolve time instead - once, before the
// first verb - where both causes are still in scope and can be said in one sentence.
//
// THROUGH StopOnArmlessPipeSubsystem AND NOT A SECOND FATAL, deliberately: it is this
// file's one voice for "the configuration left no arm to run", the census already knows
// its word, and a transport with no record arm IS that condition - the legacy arm is
// present but unreachable, which is the same "no arm" with a different cause. The cause
// is what `detail` carries.
[[noreturn]] void StopOnTransportWithoutRecordArm(const char* bit, const char* detail) {
char what[512];
std::snprintf(what, sizeof(what),
"MOBILEGL_TRANSPORT is not monolith and %s is clear (or refused), so the "
"record arm is off and the legacy arm is unreachable: %s",
bit, detail);
BufferImpl::StopOnArmlessPipeSubsystem(what);
}
#endif
// The release-build VOICE for StateBackendObjectRegistry::GetOrCreateByHandle's two
// silent refusals, shared by the kinds P4a re-keys so the wording cannot drift between
// them. It is the shape GetOrCreateBufferResourceForHandle gives P3a's buffer family,
@@ -4386,28 +4266,13 @@ namespace MobileGL::MG_Backend::DirectGLES {
Bool PipeTwinHandleIsAdoptable(Registry& registry, MG_Pipe::MGPipeHandle handle, const char* kindName) {
if (MG_Pipe::MGPipeHandleIsNull(handle)) return false;
if (handle.Slot >= Registry::SlotTable::kMaxHandleSlot) {
#if MOBILEGL_BUILD_DISAGGREGATED
MG_Pipe::MGPipeSessionFail( // @Ph-declined (ID-P7-1): PH-2 stays Fatal, CONTRACT-P7 §12
MG_Pipe::MGPipeFatalFamily::ProtocolCorruption,
"MGPipe: Fatal{ProtocolCorruption, \"BackendSlotTable.HandleSlot\"} - "
"%s handle slot %u is past this table's %u bound",
kindName, handle.Slot, Registry::SlotTable::kMaxHandleSlot);
#else
MGLOG_E_ONCE("MGPipe: %s handle slot %u is past the backend table's %u bound - "
"refusing to twin it",
kindName, handle.Slot, Registry::SlotTable::kMaxHandleSlot);
return false;
#endif
}
const Uint32 liveGen = registry.LiveGenAt(handle.Slot);
if (liveGen != 0 && liveGen > handle.Gen) {
#if MOBILEGL_BUILD_DISAGGREGATED
MG_Pipe::MGPipeSessionFail( // @Ph-declined (ID-P7-1): PH-2 stays Fatal, CONTRACT-P7 §12
MG_Pipe::MGPipeFatalFamily::ProtocolCorruption,
"MGPipe: Fatal{ProtocolCorruption, \"BackendSlotTable.Generation\"} - "
"%s handle {%u, %u} names generation behind live generation %u",
kindName, handle.Slot, handle.Gen, liveGen);
#else
// SlotTables.h:301-321: forward is a recycle and resets the twin, BACKWARD is
// refused, because adopting it would release the incumbent LIVE twin's driver
// id and then stamp the slot back to the dead object's generation, after which
@@ -4419,7 +4284,6 @@ namespace MobileGL::MG_Backend::DirectGLES {
"object",
kindName, handle.Slot, handle.Gen, liveGen);
return false;
#endif
}
return true;
}
@@ -4437,13 +4301,17 @@ namespace MobileGL::MG_Backend::DirectGLES {
const Bool bitSet = (mask & MG_Pipe::kMGPipeSubsystemFramebuffer) != 0;
Bool refused = false;
if (bitSet) {
// The framebuffer family's row, from MG_Pipe/SubsystemDeps.def. The mirror pair (bit
// 10 set, bit 9 clear) is FINE - the legacy FBO sync reaches the texture twin through
// SyncTextureObjectToBackend, which dispatches to the handle arm by itself - and that
// is stated with the other mirror pairs in MGPipe.h, beside the table it is the
// complement of, rather than here.
refused = PipeSubsystemDependencyMissing(mask, MG_Pipe::kMGPipeSubsystemFramebuffer,
"kMGPipeSubsystemFramebuffer (bit 9)");
// BIT 9 REQUIRES BIT 10. Every MGPSurface::Res in the record names a Texture or a
// Renderbuffer handle, and only bit 10 puts twins in those two slot tables; without
// it every attachment lookup would miss and the walk would leave the driver
// framebuffer holding whatever the last owner attached. The mirror pair (bit 10 set,
// bit 9 clear) is FINE: the legacy FBO sync reaches the texture twin through
// SyncTextureObjectToBackend, which dispatches to the handle arm by itself.
refused = PipeSubsystemDependencyMissing(
mask, MG_Pipe::kMGPipeSubsystemTextureResources,
"kMGPipeSubsystemFramebuffer (bit 9) is set but kMGPipeSubsystemTextureResources "
"(bit 10) is clear; MGPSurface::Res names a Texture or Renderbuffer handle and "
"only bit 10 populates those slot tables");
// D-C3: the wire array is Color[8] and this is the driver's RAW ES cap, which is
// NOT clamped to 8 on the GLES path (ValidateColorAttachmentInRange rejects at or
// above it, and BackendObject_DirectGLES publishes it verbatim). Every campaign
@@ -4470,18 +4338,6 @@ namespace MobileGL::MG_Backend::DirectGLES {
"MOBILEGL_PIPE_PUSH leaves kMGPipeSubsystemFramebuffer (bit 9) clear (or refuses "
"it) and MOBILEGL_PIPE_LEGACY_MEMOS=0 disables the pre-handle g_fboSynced* arm");
}
#if MOBILEGL_BUILD_DISAGGREGATED
if (MG_Config::Transport != MG_Config::TransportMode::Monolith &&
verdict != BufferImpl::PipeSubsystemArmVerdict::Handles) {
StopOnTransportWithoutRecordArm(
"kMGPipeSubsystemFramebuffer (bit 9)",
"the pre-handle g_fboSynced* / g_fboTextureSyncList arm reads the framebuffer "
"binding slots, and under a transport GetFramebufferBindingSlot is a BARRIER_PULLED "
"row belonging to a client that is not parked behind this apply - so the first verb "
"to reach it would raise Fatal{UnmigratedPipeInput, "
"\"GetFramebufferBindingSlot@<verb>\"} mid-frame instead");
}
#endif
const Bool enabled = verdict == BufferImpl::PipeSubsystemArmVerdict::Handles;
MGLOG_D("MGPipe: Espryt framebuffer family runs the %s arm", enabled ? "handle" : "legacy");
return enabled;
@@ -4492,19 +4348,42 @@ namespace MobileGL::MG_Backend::DirectGLES {
const Bool bitSet = (mask & MG_Pipe::kMGPipeSubsystemTextureResources) != 0;
Bool refused = false;
if (bitSet) {
// The texture family's row, from MG_Pipe/SubsystemDeps.def. It is the ONLY row with
// two required bits, and it used to be TWO guarded calls here with the pair of
// sentences written out by hand - bit 7 for a buffer texture's BufferForTexBuffer,
// and bit 11, D-K2's FOURTH ROW (ID-14/ID-15), for MGPTextureParams::BuiltinSampler.
// One call now asks the table for both, and the refusal names whichever of the two is
// actually missing instead of always naming the first. Package F pins this arm at
// 0x5ff and CMakeLists.txt's refusal lane at 0x7ff; both are rows of the table now.
// BIT 10 REQUIRES BIT 7. A buffer texture's MGPResourceDesc::BufferForTexBuffer
// names a Buffer handle and only bit 7 puts twins in the resource slot table, so
// with bit 7 clear every glTexBuffer would resolve to no storage at all. The mirror
// pair (bit 7 set, bit 10 clear) is FINE and is P3a's shipped configuration.
refused = PipeSubsystemDependencyMissing(
mask, MG_Pipe::kMGPipeSubsystemResources,
"kMGPipeSubsystemTextureResources (bit 10) is set but kMGPipeSubsystemResources "
"(bit 7) is clear; a buffer texture's BufferForTexBuffer names a Buffer handle "
"and only bit 7 populates the resource slot table");
// BIT 10 REQUIRES BIT 11 - D-K2's FOURTH ROW (ID-14/ID-15), and it is the exact
// mirror of ResolveVertexInputSubsystemArm's bit-8-requires-bit-7 refusal above:
// the same "the handle arm resolves through a slot table only the other bit
// populates" shape, refused here rather than half-run, with the legacy arm as the
// fall-back. MGPTextureParams::BuiltinSampler is a SamplerCso HANDLE and only bit 11
// mints sampler CSOs (contract c0b's four unconditional mints deliberately exclude
// it), so with bit 11 clear every set_texture_params would carry a null there - and
// the applier's verdict for a null BuiltinSampler is Fatal{ProtocolCorruption}, not
// a decline. The brief's original sentence "bit 10 without 11 is fine" is WITHDRAWN
// for P4a as built; package F pins this arm at 0x5ff.
//
// The mirror pairs live in MGPipe.h with the rest. The one worth remembering at this
// call site is that bits 10 and 11 are SYMMETRIC - each row names the other - so the
// only two masks that reach the texture handle arm are "both set" and "neither set".
refused = PipeSubsystemDependencyMissing(mask, MG_Pipe::kMGPipeSubsystemTextureResources,
"kMGPipeSubsystemTextureResources (bit 10)");
// THE TWO MIRROR PAIRS THAT STAY FINE, said out loud because an unreachable branch
// that says something different is how the reachable one drifts:
// - bit 7 set, bit 10 clear: P3a's shipped configuration (above).
// - bit 11 set, bit 10 clear: refused one function down, by the bit-11-requires-
// bit-10 row, so the pair is symmetric and neither half can run alone. That
// symmetry is the point: bits 10 and 11 are now ONE arm with two switches, and
// the only two masks that reach the texture handle arm are "both set" and
// "neither set".
if (!refused) {
refused = PipeSubsystemDependencyMissing(
mask, MG_Pipe::kMGPipeSubsystemSamplers,
"kMGPipeSubsystemTextureResources (bit 10) is set but kMGPipeSubsystemSamplers "
"(bit 11) is clear; MGPTextureParams::BuiltinSampler is a SamplerCso handle, "
"only bit 11 mints sampler CSOs, and the applier's verdict for a null one is "
"Fatal{ProtocolCorruption}");
}
}
const BufferImpl::PipeSubsystemArmVerdict verdict = BufferImpl::ClassifyPipeSubsystemArm(
bitSet && !refused, MG_Config::Features.PipeLegacyMemos,
@@ -4515,16 +4394,6 @@ namespace MobileGL::MG_Backend::DirectGLES {
"refuses it) and MOBILEGL_PIPE_LEGACY_MEMOS=0 disables the pre-handle texture "
"cheap-gate trio");
}
#if MOBILEGL_BUILD_DISAGGREGATED
if (MG_Config::Transport != MG_Config::TransportMode::Monolith &&
verdict != BufferImpl::PipeSubsystemArmVerdict::Handles) {
StopOnTransportWithoutRecordArm(
"kMGPipeSubsystemTextureResources (bit 10)",
"the pre-handle texture cheap-gate trio resolves through the frontend texture "
"objects and their binding slots, which under a transport are client memory (rule "
"E) rather than anything this side owns");
}
#endif
const Bool enabled = verdict == BufferImpl::PipeSubsystemArmVerdict::Handles;
MGLOG_D("MGPipe: Espryt texture-resource family runs the %s arm", enabled ? "handle" : "legacy");
return enabled;
@@ -4535,12 +4404,23 @@ namespace MobileGL::MG_Backend::DirectGLES {
const Bool bitSet = (mask & MG_Pipe::kMGPipeSubsystemSamplers) != 0;
Bool refused = false;
if (bitSet) {
// The sampler family's row, from MG_Pipe/SubsystemDeps.def, and this is the pair G12
// drives at 0x9ff. Its mirror (bit 10 set, bit 11 clear) is NOT fine either - that is
// D-K2's fourth row, refused by ResolveTextureResourceSubsystemArm above - so the
// dependency is SYMMETRIC and the table carries both halves.
refused = PipeSubsystemDependencyMissing(mask, MG_Pipe::kMGPipeSubsystemSamplers,
"kMGPipeSubsystemSamplers (bit 11)");
// BIT 11 REQUIRES BIT 10, and this is the pair G12 drives at 0x9ff. Every
// MGPBoundView::Texture and every MGPImageView::Res names a Texture handle, and
// only bit 10 puts one in the slot table; without it every per-unit lookup would
// miss and the walk would `continue` WITHOUT unbinding - i.e. every draw would
// sample through whatever the unit last held, which is exactly the shape the
// bit-8-without-bit-7 refusal exists to prevent one family over.
//
// THE MIRROR PAIR (bit 10 set, bit 11 clear) IS NOT FINE EITHER, and that is D-K2's
// fourth row (ID-14/ID-15): it is refused by ResolveTextureResourceSubsystemArm
// above, because MGPTextureParams::BuiltinSampler is a SamplerCso handle only bit 11
// mints. So this dependency is SYMMETRIC - the two bits are one arm with two
// switches - and this sentence used to claim the opposite.
refused = PipeSubsystemDependencyMissing(
mask, MG_Pipe::kMGPipeSubsystemTextureResources,
"kMGPipeSubsystemSamplers (bit 11) is set but kMGPipeSubsystemTextureResources "
"(bit 10) is clear; every MGPBoundView::Texture and MGPImageView::Res names a "
"Texture handle and only bit 10 populates that slot table");
}
const BufferImpl::PipeSubsystemArmVerdict verdict = BufferImpl::ClassifyPipeSubsystemArm(
bitSet && !refused, MG_Config::Features.PipeLegacyMemos,
@@ -4551,17 +4431,6 @@ namespace MobileGL::MG_Backend::DirectGLES {
"it) and MOBILEGL_PIPE_LEGACY_MEMOS=0 disables UnitSamplerLookupMemo's WeakPtr "
"arm and SamplerPassMemo's raw-pointer rows");
}
#if MOBILEGL_BUILD_DISAGGREGATED
if (MG_Config::Transport != MG_Config::TransportMode::Monolith &&
verdict != BufferImpl::PipeSubsystemArmVerdict::Handles) {
StopOnTransportWithoutRecordArm(
"kMGPipeSubsystemSamplers (bit 11)",
"UnitSamplerLookupMemo's WeakPtr arm and SamplerPassMemo's raw-pointer rows are "
"keyed on FRONTEND objects, and under a transport there is no frontend object on "
"this side to key on - a WeakPtr that can never lock is not a slower arm, it is a "
"unit that samples through whatever it last held");
}
#endif
const Bool enabled = verdict == BufferImpl::PipeSubsystemArmVerdict::Handles;
MGLOG_D("MGPipe: Espryt sampler family runs the %s arm", enabled ? "handle" : "legacy");
return enabled;
@@ -4580,17 +4449,6 @@ namespace MobileGL::MG_Backend::DirectGLES {
"MOBILEGL_PIPE_PUSH leaves kMGPipeSubsystemPrograms (bit 12) clear and "
"MOBILEGL_PIPE_LEGACY_MEMOS=0 disables g_programTwinLookupMemo");
}
#if MOBILEGL_BUILD_DISAGGREGATED
if (MG_Config::Transport != MG_Config::TransportMode::Monolith &&
verdict != BufferImpl::PipeSubsystemArmVerdict::Handles) {
StopOnTransportWithoutRecordArm(
"kMGPipeSubsystemPrograms (bit 12)",
"g_programTwinLookupMemo is keyed on the frontend ProgramObject and the legacy arm "
"reads the current program through it; under a transport the program arrives as a "
"ShaderCso handle with its archive beside the record and there is no frontend "
"program here at all");
}
#endif
const Bool enabled = verdict == BufferImpl::PipeSubsystemArmVerdict::Handles;
MGLOG_D("MGPipe: Espryt program family runs the %s arm", enabled ? "handle" : "legacy");
return enabled;
@@ -4621,24 +4479,6 @@ namespace MobileGL::MG_Backend::DirectGLES {
return PipeRecordAt(MG_Pipe::MGPipeApplier().RenderbufferResources, res);
}
// P3b/P4b (wave 2-D, package D3). See the declaration for why a view's storage clauses are
// asked of another record, why null means "ask again" and why the deletion order cannot
// strand this walk.
const MG_Pipe::MGPipeResourceRecord* PipeTextureStorageRecordForRecord(
const MG_Pipe::MGPipeResourceRecord& record) {
// ONE hop is the shape the client emits and the second is already generous; the bound is
// here so a cyclic chain is a null answer rather than a hang, not because a real chain
// is ever this long.
constexpr Uint32 kViewChainBound = 4;
const MG_Pipe::MGPipeResourceRecord* storage = &record;
for (Uint32 hop = 0; hop < kViewChainBound; ++hop) {
if (MG_Pipe::MGPipeHandleIsNull(storage->Desc.ViewOf)) return storage;
storage = PipeTextureRecordForHandle(storage->Desc.ViewOf);
if (storage == nullptr) return nullptr;
}
return nullptr;
}
MobileGL::TextureTarget PipeTextureTargetForHandle(MG_Pipe::MGPipeHandle res) {
const auto* record = PipeTextureRecordForHandle(res);
if (record == nullptr) return MobileGL::TextureTarget::Unknown;
@@ -7590,19 +7430,11 @@ namespace MobileGL::MG_Backend::DirectGLES {
MGLOG_D("Storage texture of view %u has no ES name yet.", record.Desc.GlNameForDiag);
return;
}
// P3b/P4b D3: THE SERIAL THIS TWIN STAMPS IS THE STORAGE'S, not this view's, because
// the gate that reads it back (IsDrawSyncCleanByRecord) now asks the same record. It
// is read AFTER the storage sync above - which has just consumed the owner's pending
// uploads - and taken by VALUE, because the applier's vector may move under any later
// call and a Uint64 cannot dangle. A storage record that has gone answers 0, which
// the gate reads as "never clean": the direction that re-syncs.
const MG_Pipe::MGPipeResourceRecord* storageRecord = PipeTextureStorageRecordForRecord(record);
const Uint64 storageSerial = storageRecord != nullptr ? storageRecord->Serial : 0;
if (m_isInitialized && m_viewSourceBackendTextureId == storageBackendTextureId) {
// The steady case, and the only one this arm has to be fast at: one record read,
// one integer compare and the serial stamp that keeps the aggregate clean gate
// (IsDrawSyncCleanByRecord) answering true for the next draw.
m_syncedResourceSerial = storageSerial;
m_syncedResourceSerial = record.Serial;
return;
}
// The view window is a sampler-view CSO, created even when this
@@ -7644,8 +7476,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
m_prevTextureInfo = {static_cast<TextureInternalFormat>(record.Desc.InternalFormat),
record.Desc.Width, record.Desc.Height, record.Desc.Depth, view.NumLevels, 0,
record.Desc.Samples, record.Desc.FixedSampleLocations != 0};
// The storage's, for the steady arm's reason above (P3b/P4b D3).
m_syncedResourceSerial = storageSerial;
m_syncedResourceSerial = record.Serial;
}
#endif
@@ -15597,20 +15428,9 @@ namespace MobileGL::MG_Backend::DirectGLES {
Bool BackendTextureObject::IsDrawSyncCleanByRecord(MG_Pipe::MGPipeHandle res,
const MG_Pipe::MGPipeResourceRecord& record) const {
(void)res;
// P3b/P4b D3: THE TWO STORAGE CLAUSES ARE ASKED OF THE STORAGE RECORD, which is this
// record for every texture that owns its texels and the record named by Desc.ViewOf
// for a glTextureView. A view's own Serial is moved by nothing an upload does - the
// client keys every resource_subdata on the storage owner, and the applier moves that
// record's Serial and PendingUploads alone - so reading the view's here answered
// "clean" for every owner write after the view's first sample. The three PARAMETER
// clauses below stay this record's: a view has its own texture parameters and its own
// built-in sampler, which is the whole point of the name existing. See
// PipeTextureStorageRecordForRecord and CONTRACT-P5E.md §5.2.
const MG_Pipe::MGPipeResourceRecord* storage = PipeTextureStorageRecordForRecord(record);
if (storage == nullptr) return false;
// SyncMipmapsToBackend's own early-out, verbatim.
if (!m_isInitialized || m_syncedResourceSerial == 0 || m_syncedResourceSerial != storage->Serial ||
!storage->PendingUploads.empty()) {
if (!m_isInitialized || m_syncedResourceSerial == 0 || m_syncedResourceSerial != record.Serial ||
!record.PendingUploads.empty()) {
return false;
}
// SyncTextureParamsToBackend's (ResolvePushedTextureParams' gate).
+8 -113
View File
@@ -479,29 +479,9 @@ namespace MobileGL::MG_Backend::DirectGLES {
BackendPtr* GetOrCreateByHandle(MG_Pipe::MGPipeHandle handle) {
if (!EsprytSlotTablesEnabled()) return nullptr;
if (MG_Pipe::MGPipeHandleIsNull(handle)) return nullptr;
if (handle.Slot >= SlotTable::kMaxHandleSlot) {
#if MOBILEGL_BUILD_DISAGGREGATED
MG_Pipe::MGPipeSessionFail( // @Ph-declined (ID-P7-1): PH-2 stays Fatal, CONTRACT-P7 §12
MG_Pipe::MGPipeFatalFamily::ProtocolCorruption,
"MGPipe: Fatal{ProtocolCorruption, \"BackendSlotTable.HandleSlot\"} - "
"GetOrCreateByHandle named slot %u, past this table's %u bound",
handle.Slot, SlotTable::kMaxHandleSlot);
#else
return nullptr;
#endif
}
if (handle.Slot >= SlotTable::kMaxHandleSlot) return nullptr;
const Uint32 liveGen = m_slotTable.LiveGenAt(handle.Slot);
if (liveGen != 0 && liveGen > handle.Gen) {
#if MOBILEGL_BUILD_DISAGGREGATED
MG_Pipe::MGPipeSessionFail( // @Ph-declined (ID-P7-1): PH-2 stays Fatal, CONTRACT-P7 §12
MG_Pipe::MGPipeFatalFamily::ProtocolCorruption,
"MGPipe: Fatal{ProtocolCorruption, \"BackendSlotTable.Generation\"} - "
"GetOrCreateByHandle named generation %u at slot %u, behind live generation %u",
handle.Gen, handle.Slot, liveGen);
#else
return nullptr;
#endif
}
if (liveGen != 0 && liveGen > handle.Gen) return nullptr;
return &m_slotTable.GetOrCreate(handle);
}
@@ -707,24 +687,12 @@ namespace MobileGL::MG_Backend::DirectGLES {
// BackendSamplerObject* rows;
// programs - g_programTwinLookupMemo.
//
// THE DEPENDENCY ROWS ARE IN MG_Pipe/SubsystemDeps.def, ONCE (P3b/P4b R-5), and the four
// resolvers below READ them through MGPipeSubsystemDependenciesAreSet rather than carrying a
// copy: a dependency the table declares is diagnosed and REFUSED here rather than half-run,
// the bit-8-requires-bit-7 shape ResolveVertexInputSubsystemArm already ships.
//
// THIS COMMENT USED TO RESTATE THE ROWS AND WAS WRONG IN TWO WAYS THAT NOTHING COULD FAIL,
// in the header of the file that IMPLEMENTS the refusal. It said "THREE OF THEM CARRY A
// DEPENDENCY" when there are six rows (bits 8 and 13 were the two it did not know about),
// and it listed "10 without 11" among the mirror pairs that are FINE - when 10-without-11 is
// precisely D-K2's FOURTH row (ID-14/ID-15), refused twenty lines below by
// ResolveTextureResourceSubsystemArm and withheld by the client at PipeFill.cpp's own gate.
// MGPipe.h carried the identical pair of defects and lost them with the table; this copy was
// left behind because Managers.h belonged to a package in flight. The rows are not restated
// here again: the file that states them is the one the code reads.
//
// The mirror pairs that really ARE fine are stated in MGPipe.h beside the table, because an
// absence is not a row - and because that is the one place where saying it cannot drift away
// from the rows it is the complement of.
// THREE OF THEM CARRY A DEPENDENCY (MGPipe.h, D-K2) and it is diagnosed and REFUSED here
// rather than half-run, the bit-8-requires-bit-7 shape ResolveVertexInputSubsystemArm
// already ships: bit 11 requires bit 10, bit 9 requires bit 10, bit 10 requires bit 7. The
// mirror pairs (10 without 11, 10 without 9, 7 without 10) are all FINE and are said so out
// loud, because an unreachable branch that says something different is how the reachable
// one drifts. Bit 12 depends on nothing: a ShaderCso handle names no texture and no buffer.
//
// ResolveFramebufferSubsystemArm additionally carries D-C3's bring-up refusal: the wire
// array is MGPFramebufferState::Color[8] and GetDynamicParameters().MaxColorAttachments is
@@ -802,48 +770,6 @@ namespace MobileGL::MG_Backend::DirectGLES {
// composite: this reader hides the split behind one lookup, exactly as the wire does.
const MG_Pipe::MGPipeShaderCsoRecord* PipeShaderCsoRecordForHandle(MG_Pipe::MGPipeHandle cso);
// P3b/P4b (wave 2-D, package D3): THE STORAGE RECORD BEHIND A TEXTURE RECORD - the record of
// the texture it views for a glTextureView, and itself for every other texture.
//
// WHY THERE IS A SECOND READER. A view owns no texels, and the client keeps ONE emission
// cursor per storage: an upload through a view's own name is remapped onto its storage owner
// before it is emitted (MG_Impl/Pipe/TextureEmit.h, `ViewOf names the storage owner, and ONE
// HOP always reaches storage`), so every resource_subdata for either name is keyed on the
// OWNER and the applier moves the OWNER's Serial and PendingUploads alone
// (MG_Pipe/PipeApply.cpp, ApplyTextureUpload). A view therefore has a Serial that no upload
// ever moves, and the two STORAGE clauses of its draw-path clean gate have to be asked of
// this record instead of its own - which is what the monolith gate gets for free, because
// GetContentVersion() through a view is forwarded to the owner
// (MG_State/GLState/TextureState/TextureObjectView.cpp:100-102). CONTRACT-P5E.md §5.2 states
// the rule; without it a view that has been sampled once never sees another owner write.
//
// NULL IS "ASK AGAIN", NEVER "CLEAN". Every caller treats a null answer as a reason to RUN
// the sync, which is the direction that re-uploads rather than the direction that shows stale
// texels, and it raises nothing: a missing record is PipeTextureRecordForHandle's own
// null-on-miss answer one level up, not a protocol refusal.
//
// BOUNDED, THOUGH ONE HOP IS ALWAYS ENOUGH. glTextureView composes a view-of-a-view onto the
// ROOT at creation - the spec's additive min-level rule - and TextureObjectView's invariant
// is that its owner "is never a view itself", so Desc.ViewOf already names storage. The walk
// is written transitively anyway and gives up after a fixed number of hops, because THIS side
// may not depend on a client invariant to terminate: a chain the wire could make cyclic ends
// as a null answer rather than as a hang.
//
// DELETION ORDERING: THE LIVE/GEN TEST IS THE GUARANTEE, NOT THE EMIT ORDER. A view holds a
// strong SharedPtr to its storage owner (TextureObjectView::m_storageOwner) and the client
// emits resource_destroy from the DESTRUCTOR - "the last SharedPtr to this object dropping,
// not the glDelete* that only marks the name and leaves a still-bound object very much alive"
// (MG_State/GLState/TextureState/TextureObject.cpp:63). So the owner's storage cannot go away
// under a live view, whatever order the application deletes the two names in. But the two
// destroys are emitted back to back from one destructor chain, and when the view holds the
// owner's LAST reference the member is destroyed before the view's base destructor runs, so
// the wire carries resource_destroy(owner) and then resource_destroy(view): for one apply the
// view record is live with Desc.ViewOf naming a freed slot. No draw can land in between, and
// PipeTextureRecordForHandle tests Live and Gen, so that window answers null (= not clean)
// rather than a recycled stranger's record.
const MG_Pipe::MGPipeResourceRecord* PipeTextureStorageRecordForRecord(
const MG_Pipe::MGPipeResourceRecord& record);
// P5e (fb): the texture's own TARGET, from its descriptor. The image-unit bind needs it
// (glBindImageTexture's layered/format rules are per target) and MGPImageView has no room
// for it - 24 bytes, no pad - so it is read off the resource record instead of being added
@@ -1103,16 +1029,6 @@ namespace MobileGL::MG_Backend::DirectGLES {
// 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);
// M-3's WHOLE-STORE predicate, and the GUARD every caller of RequireStagedCoverage over
// a whole-store read has to carry: true when the application DECLARED the store's
// content (glBufferData(size, data)), so a coverage gap is a missing record; false when
// it ORPHANED the store (glBufferData(size, NULL)), where every byte it has not staged
// since is undefined by its own declaration and the shadow's zero-fill is exactly what
// the monolith arm would have uploaded from MappedData(). Managers.cpp's pool-reuse
// ladder and DirectGLES.cpp's XFB scatter are its two callers and they must not be able
// to answer it differently.
Bool ResourceContentIsDeclared(MG_Pipe::MGPipeHandle res);
#endif
// MONOLITH GLUE, and named as such: the handle of a resource this backend is looking
@@ -3608,26 +3524,5 @@ namespace MobileGL::MG_Backend::DirectGLES {
// 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);
// P12 (on-screen server window): A SERVER SESSION ENDS IN A PROCESS THAT OUTLIVES IT.
//
// The twin tables above are process globals, and until P12 every server process served ONE
// session: the exec'd supervisor forks a child per session and the child exits with it, so the
// twins a session built died with its process (InProcessTeardown's deliberate leak). The
// in-process display server (mobilegl_server_serve_inprocess, the display Activity's process)
// runs sessions ONE AFTER ANOTHER IN ONE PROCESS, and the next session's client mints its
// handles from the same {slot, gen} space again. A twin the previous session left behind then
// answers for the new session's object: a program twin names a program of the DESTROYED
// context, so the link fails with an empty log and every draw no-ops (Espryt on Adreno and on
// llvmpipe alike), a stale VAO/buffer twin feeds the driver a dead name (a SIGSEGV inside
// Adreno's glDrawElements), and a stale live generation ahead of the new client's refuses its
// handle as ProtocolCorruption.
//
// So the server backend's destruction - the end of a session under a transport, on the apply
// thread, after DestroyEGLContext destroyed the context those ids belonged to - drops EVERY
// twin of every kind, with InProcessTeardown() answering true for the duration so no twin
// destructor calls into the driver (there is no current context, and the ids name nothing).
// A no-op once exit() has begun (the statics may already be gone). Monolith never calls it.
void DropEveryTwinForEndedServerSession();
#endif
} // namespace MobileGL::MG_Backend::DirectGLES
@@ -14,9 +14,6 @@
#if MOBILEGL_PIPE_PUSH
#include <MG_Impl/Pipe/SlotAllocator.h>
#endif
#if MOBILEGL_BUILD_DISAGGREGATED
#include <MG_Pipe/PipeSessionFail.h>
#endif
// Espryt 0b, the first Track H slice: the DENSE, {slot, gen}-keyed twin table that replaces
// StateBackendObjectRegistry's UnorderedMap<StateObject*, Entry>.
@@ -348,19 +345,9 @@ namespace MobileGL::MG_Backend::DirectGLES {
// already orders of magnitude past any real GL object count, while a corrupt 32-bit
// slot asks for a four-billion-entry resize.
if (handle.Slot >= kMaxHandleSlot) {
#if MOBILEGL_BUILD_DISAGGREGATED
// PH-2: handle.Slot is peer supplied on the disaggregated arm. Release builds
// must publish a named protocol fault instead of silently returning m_nullTwin.
MG_Pipe::MGPipeSessionFail( // @Ph-declined (ID-P7-1): PH-2 stays Fatal, CONTRACT-P7 §12
MG_Pipe::MGPipeFatalFamily::ProtocolCorruption,
"MGPipe: Fatal{ProtocolCorruption, \"BackendSlotTable.HandleSlot\"} - "
"GetOrCreate(handle) named slot %u, past this table's %u bound",
handle.Slot, kMaxHandleSlot);
#else
MOBILEGL_ASSERT(false, "GetOrCreate(handle) named slot %u, past this table's %u bound",
handle.Slot, kMaxHandleSlot);
return m_nullTwin;
#endif
}
// Same arming as the minting overload, and for the same reason: twin creation is
@@ -382,21 +369,11 @@ namespace MobileGL::MG_Backend::DirectGLES {
// below already gives the same input.
Entry& entry = EntryAt(handle.Slot);
if (entry.Live && entry.Gen > handle.Gen) {
#if MOBILEGL_BUILD_DISAGGREGATED
// PH-2: a stale peer generation must not silently shed the incumbent twin in a
// release server. The funnel names the exact identity fault and notifies the peer.
MG_Pipe::MGPipeSessionFail( // @Ph-declined (ID-P7-1): PH-2 stays Fatal, CONTRACT-P7 §12
MG_Pipe::MGPipeFatalFamily::ProtocolCorruption,
"MGPipe: Fatal{ProtocolCorruption, \"BackendSlotTable.Generation\"} - "
"GetOrCreate(handle) named generation %u at slot %u, behind live generation %u",
handle.Gen, handle.Slot, entry.Gen);
#else
MOBILEGL_ASSERT(false,
"GetOrCreate(handle) named generation %u at slot %u, which is BEHIND "
"the live entry's %u - refusing rather than destroying the incumbent",
handle.Gen, handle.Slot, entry.Gen);
return m_nullTwin;
#endif
}
if (entry.Live && entry.Gen != handle.Gen) entry.backend.reset();
entry.Gen = handle.Gen;
@@ -330,25 +330,7 @@ namespace MobileGL::MG_Backend::DirectVulkan {
PopulateFormatCapabilitiesImpl(physicalDevice, getFormatProperties, capabilities, cache);
}
#if MOBILEGL_BUILD_DISAGGREGATED
BackendObject_DirectVulkan::~BackendObject_DirectVulkan() {
// P12 review fix: A SERVER SESSION THAT ENDS WITHOUT A CLEAN TEARDOWN LEAVES NO RENDERER ON
// THE WINDOW. The renderer - swapchain and VkSurfaceKHR on the window - is a process global
// that only ReleaseEGLResources / a released surface drops, and a client that went away
// without eglTerminate (a crash, a kill, a dropped connection) sends neither. Under a
// transport this object is the server's and its destruction is the session's end (ServerLoop's
// apply thread, after the final drain, before the display lease ends), so the renderer goes
// here: nothing of the ended session keeps presenting into, or holding a surface on, the
// server's window once its lease is over. Monolith keeps its renderer.
if (MG_Config::Transport != MG_Config::TransportMode::Monolith && pVulkanRenderer != nullptr) {
BumpRendererGeneration();
pVulkanRenderer.reset();
ClearProgramResourceCaches();
}
}
#else
BackendObject_DirectVulkan::~BackendObject_DirectVulkan() = default;
#endif
BackendObject_DirectVulkan::BackendObject_DirectVulkan() : m_rendererInfo{GetRendererIdentity()} {}
@@ -385,15 +367,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
void BackendObject_DirectVulkan::Initialize() {
#if MOBILEGL_BUILD_DISAGGREGATED
VkBufferManager::RegisterWireResourceOps();
#if MOBILEGL_PIPE_PUSH
// P7 wave 2 package C (CONTRACT-P7 §5.5). BESIDE the resource ops and for the same
// reason: this is the one place both Magma server roles pass through - the inproc
// role and the spawn/TCP session child - and ServerLoop::CreateBackend calls it at
// step 1 of InitServerRoleCommon, before the client session exists and therefore
// before any frontend object can die unheard. A per-transport install is how one of
// the two roles ends up without it.
InstallStateObjectDeathOps();
#endif
#endif
m_initialized = true;
}
@@ -21,13 +21,6 @@
#include <Config.h>
#include <MG_Remote/Server/ServerLoop.h>
#include <MG_Pipe/PipeApply.h>
#if MOBILEGL_PIPE_PUSH
// P7 wave 2 package C (CONTRACT-P7 §5.5): Magma's own death-notice table. Both headers are
// push-only and reached here for the same reason DirectGLES/Managers.cpp reaches them - the
// notice is declared by the frontend and answered by whichever backend is running.
#include <MG_Remote/Client/WireTables.h>
#include <MG_State/GLState/StateObjectDeathNotice.h>
#endif
#endif
#include <atomic>
#include <bit>
@@ -62,66 +55,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
std::atomic<Uint64> g_rendererGeneration{1};
} // namespace
#if MOBILEGL_BUILD_DISAGGREGATED && MOBILEGL_PIPE_PUSH
namespace {
// P7 wave 2 package C, CONTRACT-P7 §5.5: MAGMA'S MIRROR OF g_glesStateObjectDeathOps
// (DirectGLES/Managers.cpp:335), and the one arm of that table Magma has any work in.
//
// WHAT THE NOTICE IS FOR HERE, and it is not what it is for on Espryt. Espryt's arm
// destroys a BACKEND TWIN keyed by lifetime id; Magma keeps no such twin - its two
// client-minted kinds (VertexElementsCso, Buffer) are keyed on {slot, gen} by
// MagmaPipeIdentityTables and every other kind is still reached from its frontend
// object. So the switch Espryt runs under `#else` has nothing to do on this backend
// and this table is exactly the EMIT arm: with a transport up and off the apply
// thread, the death crosses as the `object_death` record
// (MG_Remote::Client::EmitObjectDeathRecord, CONTRACT-P5C §5.2).
//
// WHY THAT MATTERS, measured rather than argued (package L's probe,
// notes/p7/magma-two-process-first-run.md §6): under SPAWN the client process has no
// DirectVulkan backend at all, so InstallClientWireTables' own emitter already
// answered the notice and CtWireScenario's two death cases PASSED. Under INPROC the
// server role's backend is a thread of this process, Transport is Split rather than
// Spawn, and WireTables' install condition deliberately stands aside for "the
// backend's own dispatcher" - which on Magma did not exist. Both cases therefore
// FAILED on inproc with `deaths` stuck at 0. This table is that dispatcher.
//
// FRAMEBUFFER IS WHY THE GAP WAS NOT MERELY COSMETIC. The client-side SLOT is freed
// backend-neutrally by P4a's per-kind helpers (MG_Impl/Pipe/PipeFill.cpp's
// NotifyAndFree frees whatever the notice does), so PipeSlotPeek never saw a leak.
// What leaked was the SERVER's twin: a framebuffer has NO wire delete opcode at all
// (BRIEF-P4A D-I2), so `object_death` is its only death delivery, and without a
// consumer here the server's record stayed Live for the life of the session.
void OnMagmaFrontendStateObjectDestroyed(MG_Pipe::MGPipeKind kind, Uint64 lifetimeId) {
// Monolith has no record to emit and no server twin to tell.
if (MG_Config::Transport == MG_Config::TransportMode::Monolith) return;
// Raised ON the apply thread: the server role destroying a frontend object it
// created itself (Magma's hidden blit / depth-mipmap resources). The client's
// allocator is a client-thread surface (CONTRACT-P5C §3.1) and EmitObjectDeathRecord
// probes it, so this arm stays silent exactly as Espryt's does.
if (MG_Remote::Server::ServerLoop::OnApplyThread()) return;
(void)MG_Remote::Client::EmitObjectDeathRecord(kind, lifetimeId);
}
const MG_State::GLState::StateObjectDeathOps g_magmaStateObjectDeathOps = {
.OnDestroyed = OnMagmaFrontendStateObjectDestroyed,
};
} // namespace
void InstallStateObjectDeathOps() {
// Installed from BackendObject_DirectVulkan::Initialize(), i.e. step 1 of
// InitServerRoleCommon (ServerLoop::CreateBackend calls Initialize), which is before
// the client session starts and therefore before any frontend object can die.
// Unconditional, exactly as Espryt's ResolveEsprytSlotTablesArm is: only one backend
// is live at a time, and InstallClientWireTables' own "whoever installed first keeps
// the notice" guard is what keeps the remote client from stomping this.
MG_State::GLState::SetStateObjectDeathOps(&g_magmaStateObjectDeathOps);
}
Bool StateObjectDeathOpsInstalled() {
return MG_State::GLState::GetStateObjectDeathOps() == &g_magmaStateObjectDeathOps;
}
#endif // MOBILEGL_BUILD_DISAGGREGATED && MOBILEGL_PIPE_PUSH
Uint64 GetRendererGeneration() {
return g_rendererGeneration.load(std::memory_order_acquire);
}
@@ -131,21 +64,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
}
namespace {
#if !MOBILEGL_BUILD_DISAGGREGATED
// P7 wave 2 package C, OQ-8: THE PULL BUILD'S HALF, VERBATIM. A disaggregated build
// answers GetShaderStorageBlock{Index,Binding} out of LinkArtifacts::storageBlocks
// instead (see those functions below), which retires this whole cache - the map, the
// SPIRV-Reflect rebuild, the teardown clear and the rehash hazard. It cannot be
// retired HERE because the archive member it reads is itself disaggregated-only, for
// G1: one more Vector in LinkArtifacts moves the pull build's .text, which is pinned
// byte-for-byte at 0xa52203.
//
// NOTHING OUTSIDE THIS FILE READS ANY OF IT (measured: BufferVariableResource,
// bufferVariables, activeVariables and StorageBlockResource have no reference anywhere
// else in the tree, and `dataSize` is written and never read - GL_BUFFER_VARIABLE and
// GL_ACTIVE_VARIABLES are answered by MG_Impl/GLImpl/Program/ProgramInterface.cpp out
// of glslang's own reflection, which is a different index space). So the two arms
// below differ in exactly the two functions their callers use, and in nothing else.
struct BufferVariableResource {
String name;
GLuint blockIndex = 0;
@@ -177,7 +95,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
Vector<StorageBlockResource> storageBlocks;
Vector<BufferVariableResource> bufferVariables;
};
#endif // !MOBILEGL_BUILD_DISAGGREGATED
struct DrawElementsIndirectCommand {
Uint32 count = 0;
@@ -194,14 +111,12 @@ namespace MobileGL::MG_Backend::DirectVulkan {
Uint32 baseInstance = 0;
};
#if !MOBILEGL_BUILD_DISAGGREGATED
// Keyed by GL program name so the freed-name reuse in IndexGenerator bounds the
// map at the peak-simultaneous-program high-water mark; each slot's ownership is
// checked against the program's lifetime id before it is served (see
// GetProgramResourceCache). Cleared wholesale at EGL teardown via
// ClearProgramResourceCaches.
UnorderedMap<GLuint, ProgramResourceCache> g_programResourceCaches;
#endif
void ClearReadPixelsOutput(GLsizei width, GLsizei height, GLenum format, GLenum type, void* pixels) {
if (!pixels || width <= 0 || height <= 0) {
@@ -216,7 +131,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
}
}
#if !MOBILEGL_BUILD_DISAGGREGATED
String NormalizeDescriptorName(const SpvReflectDescriptorBinding& binding) {
const char* rawName = binding.name;
if (binding.type_description != nullptr && binding.type_description->type_name != nullptr) {
@@ -367,7 +281,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
}
return cache;
}
#endif // !MOBILEGL_BUILD_DISAGGREGATED
#if MOBILEGL_BUILD_DISAGGREGATED
// The verb's handles identify server stores. Readback orders GPU-produced
@@ -468,67 +381,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
} // namespace
#if MOBILEGL_BUILD_DISAGGREGATED
// P7 wave 2 package C, OQ-8 (CONTRACT-P7 §5.3): THE MONOLITH CONSUMER READS THE ARCHIVE
// TOO, so one published list serves both of this backend's arms.
//
// THE TWO ARMS BELOW ARE NOT TWO ANSWERS. ProgramTest's
// TheArchivesStorageBlockOrderIsTheOneSpirvReflectProduces runs the OLD arm's algorithm -
// SPIRV-Reflect over the real modules, sorted and deduplicated exactly as
// GetProgramResourceCache does it - over a multi-stage program with an arrayed SSBO and an
// atomic-counter block, and asserts element-for-element equality with what the archive
// published. That equivalence is what makes an #if here a build-time SELECTION rather than
// a behavioural fork, and it is the reason the case exists.
//
// WHY AN #if AT ALL, AND WHAT IT COSTS. LinkArtifacts::storageBlocks is
// MOBILEGL_BUILD_DISAGGREGATED-only, because one more Vector member changes the struct's
// size, its implicit destructor and its move constructor in the PULL build whose .text G1
// pins byte-for-byte (0xa52203). So the pull build keeps `g_programResourceCaches`, the
// SPIRV-Reflect rebuild and `ClearProgramResourceCaches`, verbatim; only this build drops
// them - and with them the rehash hazard the ordering comment below the block-binding
// setter documents. Retiring the pull half is the day the member stops needing its guard,
// which is a G1/P13 decision and not a wave-2 one; recorded in notes/p7/magma-c.md.
void ClearProgramResourceCaches() {
// Nothing to clear: there is no cache in this build. Kept as an entry point so
// BackendObject_DirectVulkan's two EGL-teardown call sites stay statement for
// statement what they are in the pull build.
}
GLuint GetShaderStorageBlockIndex(const MG_State::GLState::ProgramObject& program, const String& name) {
const auto& blocks = program.GetLinkReflection().storageBlocks;
const auto find = [&blocks](const String& key) {
return std::find_if(blocks.begin(), blocks.end(),
[&](const MG_State::GLState::StorageBlockReflection& block) { return block.name == key; });
};
auto it = find(name);
if (it == blocks.end()) {
// Archive names are normalised, so an arrayed block that GL enumerates per element
// - "B[0]", "B[1]" - is one entry here, spelled "B". Same second chance the cache
// gave, for the same callers.
const auto bracket = name.rfind('[');
if (bracket == String::npos || name.empty() || name.back() != ']') return GL_INVALID_INDEX;
it = find(name.substr(0, bracket));
if (it == blocks.end()) return GL_INVALID_INDEX;
}
return static_cast<GLuint>(std::distance(blocks.begin(), it));
}
GLuint GetShaderStorageBlockBinding(const MG_State::GLState::ProgramObject& program, GLuint blockIndex) {
const auto& blocks = program.GetLinkReflection().storageBlocks;
if (blockIndex >= blocks.size()) {
return 0;
}
// THE OVERRIDE IS APPLIED ON READ, where the cache used to apply it on rebuild and
// patch it in place on rebind. Same answer by a shorter route: the program is the
// authoritative record of a rebound block (it is what GL_BUFFER_BINDING reports), the
// archive carries the DECLARED binding only, and asking the program here means a
// rebind can no longer be lost to a cache rebuild that happened to race a state-version
// bump.
const Int rebound = program.GetShaderStorageBlockBindingOverride(blocks[blockIndex].name);
if (rebound >= 0) return static_cast<GLuint>(rebound);
return blocks[blockIndex].binding;
}
#else
void ClearProgramResourceCaches() {
// Called from EGL teardown while the backend's m_eglStateMutex is held; GL
// calls are serialized in this codebase (contexts migrate threads but never
@@ -564,7 +416,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
}
return cache.storageBlocks[blockIndex].binding;
}
#endif
void ClearBufferfi(GLenum buffer, GLint drawbuffer, GLfloat depth, GLint stencil) {
MOBILEGL_ASSERT(pVulkanRenderer, "DirectVulkan::ClearBufferfi called with null VulkanRenderer");
@@ -1031,27 +882,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
MakeUnique<GenericErrorInfo>("DirectVulkan", __func__, "Shader storage binding is out of range."));
return;
}
#if MOBILEGL_BUILD_DISAGGREGATED
// P7 wave 2 package C, OQ-8: NOTHING LEFT TO PATCH, and the hazard goes with it.
//
// The frontend has already recorded the new binding on the program, and that record is
// now what GetShaderStorageBlockBinding reads (it asks
// GetShaderStorageBlockBindingOverride on every call, over an IMMUTABLE archive list).
// What stood here was the other half of a mutable cache: resolve the index, take a
// reference into g_programResourceCaches and patch `binding` in place so an
// already-built entry need not be thrown away.
//
// THE HAZARD THAT CAME WITH IT IS GONE TOO, and it is worth naming because it was a
// real crash rather than a theoretical one: GetShaderStorageBlockIndex re-entered
// GetProgramResourceCache, which indexes an OPEN-ADDRESSED map and can therefore
// insert, and a rehash moves entries - so a reference taken before that call dangled.
// Binding one program's storage block while another program's entry was still absent
// from the cache was a reproducible segfault (ProgramPipelineScenario's two
// storage-block cases, in one process). The ordering above was the fix; having no
// cache is the retirement. The pull build below keeps both.
(void)storageBlockBinding;
}
#else
// The frontend already validated that the name denotes an active block, and has
// already recorded the new binding on the program - which is what reseeds this cache
// whenever it is rebuilt. Writing the entry here as well keeps an ALREADY-BUILT cache
@@ -1070,7 +900,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
if (blockIndex >= cache.storageBlocks.size()) return;
cache.storageBlocks[blockIndex].binding = storageBlockBinding;
}
#endif
void ReadPixels(GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, void* pixels) {
MOBILEGL_ASSERT(pVulkanRenderer, "DirectVulkan::ReadPixels called with null VulkanRenderer");
MOBILEGL_ASSERT(MGB_CTX_LIVE, "DirectVulkan::ReadPixels called with null GL context");
@@ -23,18 +23,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
Uint64 GetRendererGeneration();
void BumpRendererGeneration();
#if MOBILEGL_BUILD_DISAGGREGATED && MOBILEGL_PIPE_PUSH
// P7 wave 2 package C (CONTRACT-P7 §5.5). Magma's StateObjectDeathOps table, installed
// from BackendObject_DirectVulkan::Initialize() so that GetStateObjectDeathOps() is
// non-null on every Magma role that owns a backend. See the definition for what the one
// arm does and for the inproc gap it closes. Push-only and disaggregated-only: a pull
// build declares no notice at all (StateObjectDeathNotice.h) and has nothing to emit.
void InstallStateObjectDeathOps();
// True when the notice currently installed is this backend's. Read by MG_Test so the
// install can be asserted without a death having to happen first.
Bool StateObjectDeathOpsInstalled();
#endif
// Drops every cached program-resource reflection entry (CPU-side strings/vectors
// only, no Vulkan handles). Called at EGL teardown next to the renderer reset;
// safe because GL calls are serialized in this codebase, and any still-live
@@ -307,10 +307,8 @@ namespace MobileGL::MG_Backend::DirectVulkan {
if (result != VK_SUCCESS) {
return result;
}
// Under disaggregation VulkanRenderer waits every registered fence
// through this slot's last submit before calling here. That aggregate
// proof covers mid-frame pooled-fence flushes too; the slot fence alone
// would not. Initialize's first acquire has no prior submissions.
// The slot's fence has been waited: every command buffer this slot
// submitted (including mid-frame flushes) has finished executing.
FreeRetiredCommandBuffers(frame);
result = vkAcquireNextImageKHR(device, swapchain, timeout, frame.imageAvailableSemaphore, acquireFence,
@@ -166,17 +166,9 @@ namespace MobileGL::MG_Backend::DirectVulkan {
// WHAT IT DOES NOT COVER, AND WHY NO REPRODUCER OF THIS SHAPE CAN [fix-aba review v1,
// MAJOR 1]. It does NOT exercise the GENERATION half of {slot, gen}:
//
// * THIS MINT still has no death notification, and that is now a narrower statement than
// it was. P7 wave 2 package C gives DirectVulkan a StateObjectDeathOps table
// (DirectVulkan.cpp's g_magmaStateObjectDeathOps, CONTRACT-P7 §5.5), so
// NotifyStateObjectDestroyed DOES have a consumer on this backend - but that consumer's
// one job is to emit the `object_death` RECORD so the server drops its twin, and it
// never touches these per-renderer identity tables: they are the SERVER-side renderer's
// own, the notice is raised on the CLIENT thread, and an Acquire/retire from the wrong
// side is precisely the cross-role read CONTRACT-P5C §3.1 forbids. So a slot here still
// returns to the free list only through OnFrameBoundary's age sweep (kSweepInterval
// 256, kRetireAgeBoundaries 1024, below), and everything the two bullets below derive
// from that is unchanged;
// * this mint has no death notification - nothing in MG_Backend/DirectVulkan consumes
// NotifyStateObjectDestroyed - so a slot returns to the free list only through
// OnFrameBoundary's age sweep (kSweepInterval 256, kRetireAgeBoundaries 1024, below);
// * HandleRecycleScenario issues five frame boundaries, so the free list is empty when
// the replacement VAO acquires and it gets a BRAND-NEW slot at Gen 1 (measured:
// redVao slot=2 gen=1, greenVao slot=3 gen=1). The knob-off FRESH verdict there is
@@ -7,11 +7,7 @@
#include <MG_Pipe/PipeApply.h>
#include <MG_State/GLState/ProgramState/ProgramArtifactsCodec.h>
#include "../DirectVulkanResourceState.h"
// P7 wave 2 package C, OQ-8: spirv_reflect.h is GONE from this header, and its absence is the
// gate. Everything this class needed it for - the storage-block index space - now travels in
// the archive (LinkArtifacts::storageBlocks), so the SPIR-V reflector is off the Magma wire
// draw path entirely. A future edit that re-adds the include is re-adding a per-draw reflect,
// because a MagmaProgramSource is constructed once per draw and can memoise nothing.
#include <spirv_reflect.h>
#endif
namespace MobileGL::MG_Backend::DirectVulkan {
@@ -157,49 +153,30 @@ namespace MobileGL::MG_Backend::DirectVulkan {
GLenum GetTransformFeedbackBufferMode() const {
return IsWire() ? Link().xfbBufferMode : m_frontend->GetTransformFeedbackBufferMode();
}
// P7 wave 2 package C, OQ-8 (CONTRACT-P7 §5.3): READ OUT OF THE ARCHIVE.
//
// What stood here re-ran spvReflectCreateShaderModule over EVERY stage module of the
// program, and it did so PER DRAW: a MagmaProgramSource is a borrowed view that
// WireDraw.inc's WireProgramSource constructs afresh for each wire draw, so the lazy
// `m_storageBlocksReady` latch could never outlive one. The list it rebuilt is a pure
// function of the linked program, so it is now built once at link time and travels in
// the archive (LinkArtifacts::storageBlocks), which takes the SPIR-V reflector off the
// wire draw path entirely - this header no longer includes spirv_reflect.h at all.
Uint GetShaderStorageBlockIndex(const String& name) const {
if (!IsWire()) return DirectVulkan::GetShaderStorageBlockIndex(*m_frontend, name);
const auto& blocks = Link().storageBlocks;
// The archive carries NORMALISED names (the array subscript stripped), because
// that is the spelling SPIRV-Reflect's type_name gives and the spelling
// ProgramFactory::ReflectLayout looks up. A caller that still holds a GL-style
// "Foo[2]" gets the same second chance it always had.
const auto find = [&blocks](const String& key) {
return std::find_if(blocks.begin(), blocks.end(),
[&](const MG_State::GLState::StorageBlockReflection& block) {
return block.name == key;
});
EnsureStorageBlocks();
String key = name;
auto find = [&] {
return std::find_if(m_storageBlocks.begin(), m_storageBlocks.end(),
[&](const StorageBlock& block) { return block.Name == key; });
};
auto found = find(name);
if (found == blocks.end() && !name.empty() && name.back() == ']') {
auto found = find();
if (found == m_storageBlocks.end() && !name.empty() && name.back() == ']') {
const auto bracket = name.rfind('[');
if (bracket != String::npos) found = find(name.substr(0, bracket));
if (bracket != String::npos) { key = name.substr(0, bracket); found = find(); }
}
return found == blocks.end() ? GL_INVALID_INDEX
: static_cast<Uint>(found - blocks.begin());
return found == m_storageBlocks.end() ? GL_INVALID_INDEX : static_cast<Uint>(found - m_storageBlocks.begin());
}
Uint GetShaderStorageBlockBinding(Uint index) const {
if (!IsWire()) return DirectVulkan::GetShaderStorageBlockBinding(*m_frontend, index);
const auto& blocks = Link().storageBlocks;
if (index >= blocks.size()) return 0;
const auto& block = blocks[index];
// THE OVERRIDE STILL WINS, and it still comes off the RECORD rather than the
// archive: glShaderStorageBlockBinding is a post-link mutable and the archive
// carries link-time defaults only (rule on MagmaProgramSource, and the reason
// StorageBlockReflection::binding is documented as the DECLARED binding).
EnsureStorageBlocks();
if (index >= m_storageBlocks.size()) return 0;
const auto& block = m_storageBlocks[index];
for (const auto& override : m_record->StorageOverrides) {
if (override.Name == block.name) return override.Binding;
if (override.Name == block.Name) return override.Binding;
}
return block.binding;
return block.Binding;
}
private:
@@ -210,13 +187,48 @@ namespace MobileGL::MG_Backend::DirectVulkan {
return tIndex >= 0 && static_cast<SizeT>(tIndex) < Link().blockReflection.size()
? &Link().blockReflection[tIndex] : nullptr;
}
struct StorageBlock { String Name; Uint Binding; };
void EnsureStorageBlocks() const {
if (m_storageBlocksReady) return;
m_storageBlocksReady = true;
// Match the legacy resource-query index order: stage order, then
// normalized descriptor name/binding, deduplicated across stages.
for (const auto& spirv : GetGeneratedSpirv()) {
if (spirv.empty()) continue;
SpvReflectShaderModule module{};
if (spvReflectCreateShaderModule(spirv.size() * sizeof(Uint), spirv.data(), &module) != SPV_REFLECT_RESULT_SUCCESS) continue;
Uint32 count = 0;
if (spvReflectEnumerateDescriptorBindings(&module, &count, nullptr) == SPV_REFLECT_RESULT_SUCCESS) {
Vector<SpvReflectDescriptorBinding*> bindings(count);
if (spvReflectEnumerateDescriptorBindings(&module, &count, bindings.data()) == SPV_REFLECT_RESULT_SUCCESS) {
auto name = [](const SpvReflectDescriptorBinding* binding) {
const char* raw = binding->name;
if (binding->type_description && binding->type_description->type_name) raw = binding->type_description->type_name;
String result = raw ? raw : "";
const auto suffix = result.find("[0]");
return suffix == String::npos ? result : result.substr(0, suffix);
};
std::sort(bindings.begin(), bindings.end(), [&](const auto* a, const auto* b) {
const String an = a ? name(a) : String(), bn = b ? name(b) : String();
return an != bn ? an < bn : (a && b && a->binding < b->binding);
});
for (const auto* binding : bindings) {
if (!binding || binding->descriptor_type != SPV_REFLECT_DESCRIPTOR_TYPE_STORAGE_BUFFER) continue;
const String key = name(binding);
if (key.empty() || std::any_of(m_storageBlocks.begin(), m_storageBlocks.end(),
[&](const StorageBlock& block) { return block.Name == key; })) continue;
m_storageBlocks.push_back({key, binding->binding});
}
}
}
spvReflectDestroyShaderModule(&module);
}
}
const Program* m_frontend = nullptr;
MG_Pipe::MGPipeHandle m_handle = MG_Pipe::kMGPipeNullHandle;
const MG_Pipe::MGPipeShaderCsoRecord* m_record = nullptr;
// P7 OQ-8: the two mutables that memoised the per-draw reflect are gone with it. They
// were `mutable` precisely because this class is a borrowed const view - and that is
// also why they never helped: a view lives for one draw, so the latch was cold every
// time it was read.
mutable Bool m_storageBlocksReady = false;
mutable Vector<StorageBlock> m_storageBlocks;
};
#else
using MagmaProgramSource = MG_State::GLState::ProgramObject;
@@ -1,41 +0,0 @@
// MobileGL - MobileGL/MG_Backend/DirectVulkan/Renderer/SubmitFencePrefix.h
// Copyright (c) 2025-2026 MobileGL-Dev
// Licensed under the GNU Lesser General Public License v3.0:
// https://www.gnu.org/licenses/gpl-3.0.txt
// https://www.gnu.org/licenses/lgpl-3.0.txt
// SPDX-License-Identifier: LGPL-3.0-only
// End of Source File Header
#pragma once
#include <cstdint>
#include <vector>
namespace MobileGL::MG_Backend::DirectVulkan {
// Collect every fence in the ordered submission prefix. Waiting on only the last matching
// frame-serial record is insufficient: the same serial may have an earlier in-flight submit.
template <typename Records, typename Fence>
bool CollectSubmitFencePrefix(const Records& records, std::uint64_t submitIndex,
Fence nullFence, std::vector<Fence>& fences) {
fences.clear();
bool foundTarget = false;
for (const auto& record : records) {
if (record.submitIndex > submitIndex) {
break;
}
if (record.fence == nullFence) {
fences.clear();
return false;
}
fences.push_back(record.fence);
foundTarget = foundTarget || record.submitIndex == submitIndex;
}
if (!foundTarget) {
fences.clear();
return false;
}
return true;
}
} // namespace MobileGL::MG_Backend::DirectVulkan
@@ -31,10 +31,6 @@
#include <Config.h>
#if MOBILEGL_BUILD_DISAGGREGATED
#include <MG_Pipe/PipeApply.h>
// P7 wave 0: the seam WireDescriptorFatal dies through. See MG_Pipe/PipeSessionFail.h.
#include <MG_Pipe/PipeSessionFail.h>
// P7 wave 2 package B3: rule I's tally for this file's silent wire-draw exits.
#include "WireDeclineTally.h"
#endif
#include <vulkan/utility/vk_format_utils.h>
#include <algorithm>
@@ -69,11 +65,9 @@ namespace MobileGL::MG_Backend::DirectVulkan {
return hash;
}
// P7 wave 0, the descriptor half of WireFramebuffer.inc's MagmaWireFatal - same message,
// same seam, same reason. Four of the fifteen P7-marked refusals die here.
[[noreturn]] static void WireDescriptorFatal(const char* detail) {
MG_Pipe::MGPipeSessionFail(MG_Pipe::MGPipeFatalFamily::UnmigratedVerb,
"MGPipe: Fatal{UnmigratedVerb, \"Magma:%s\"}", detail);
MGLOG_F("MGPipe: Fatal{UnmigratedVerb, \"Magma:%s\"}", detail);
std::abort();
}
static Bool ResolveWireRange(Uint64 offset, Uint64 declaredSize, VkDeviceSize bufferSize,
@@ -99,49 +93,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
}
}
// GL ignores Layer/Layered for a target with no layers. In particular image1D stays a 1D
// view, and an ignored nonzero Layer must not address another slice.
static Bool WireTargetHasLayers(MG_Pipe::MGPipeResourceTarget target) {
using T = MG_Pipe::MGPipeResourceTarget;
return target == T::Tex1DArray || target == T::Tex2DArray || target == T::Tex2DMSArray ||
target == T::Tex3D || target == T::TexCube || target == T::TexCubeArray;
}
// GL 4.6 core 8.26: an access through an image unit whose texture does not HAVE the
// (level, layer) the unit names is INVALID. A load returns zero, a store does nothing, an
// atomic updates nothing - and none of it is an error, neither at bind time (the bind only
// checks the level's and the layer's signs) nor at the draw. It is the observable an empty
// unit has, so the answer is the empty unit's (ResolveWirePlaceholderImage): a NULL storage
// descriptor where the device enables VK_EXT_robustness2 nullDescriptor, else a storage
// placeholder private to the unit (per shape), cleared before each use, of the dimensionality
// the SHADER declared.
//
// KHR-GL46.shader_image_load_store.incomplete_textures is the shape that found it: level 2
// of a texture that defines only level 0 (MAX_LEVEL 7, a mipmapping filter). The same
// question comes up empty for a level past an immutable texture's storage, a layer past an
// array's last slice, a texture that has no storage at all, and a level past a texture
// view's own window even where its owner has one. The record carries exactly what
// glBindImageTexture was given, so it is decided here, by the walk every wire consumer uses
// to find a texel's storage, and from that walk's "not there" answer ONLY: a null for any
// other reason (a dead record, a stale view CSO) stays the descriptor resolve's refusal.
//
// NOT DECIDED HERE, deliberately: a level that IS in storage but lies outside
// [BASE_LEVEL, MAX_LEVEL], or of a texture that is not mipmap-complete. The monolith arm
// binds those as it finds them too, and the P7 gate 5 comparison is against that arm.
static Bool WireShaderImageNamesNoTexel(VkTextureManager& textures, const MG_Pipe::MGPImageView& image) {
const auto& state = MG_Pipe::MGPipeApplier();
if (MG_Pipe::MGPipeHandleIsNull(image.Res) || image.Res.Slot >= state.TextureResources.size()) return false;
const auto& record = state.TextureResources[image.Res.Slot];
if (!record.Live || record.Gen != image.Res.Gen) return false;
const Bool selectsLayer =
WireTargetHasLayers(static_cast<MG_Pipe::MGPipeResourceTarget>(record.Desc.Target)) && !image.Layered;
Uint32 level = image.Level;
Uint32 layer = selectsLayer ? image.Layer : 0;
Bool outsideWindow = false;
(void)textures.ResolveWireTextureStorage(image.Res, level, layer, nullptr, nullptr, &outsideWindow);
return outsideWindow;
}
static VkComponentSwizzle WireSwizzle(Uint8 value) {
switch (static_cast<TextureSwizzleParam>(value)) {
case TextureSwizzleParam::Red: return VK_COMPONENT_SWIZZLE_R;
@@ -167,31 +118,23 @@ namespace MobileGL::MG_Backend::DirectVulkan {
if (unit < 0 || static_cast<Uint32>(unit) >=
(storage ? MG_Pipe::kMGPipeMaxImageUnits : MG_Pipe::kMGPipeMaxTextureUnits)) return false;
const auto handle = storage ? state.BoundShaderImages[unit].Res : state.BoundSamplerViews[unit].Texture;
// An EMPTY image unit is the same 8.26 invalid access as the named-but-missing texel
// below, so it takes the same answer: a null storage descriptor where the device has
// one, else the unit-private placeholder (codex closeout finding 2).
if (MG_Pipe::MGPipeHandleIsNull(handle))
return ResolveWirePlaceholderImage(commandBuffer, program, programObj, binding, storage, out,
VK_FORMAT_UNDEFINED, static_cast<Uint32>(unit));
return ResolveWirePlaceholderImage(commandBuffer, program, programObj, binding, storage, out);
if (handle.Slot >= state.TextureResources.size()) WireDescriptorFatal("image-record");
const auto& record = state.TextureResources[handle.Slot];
if (!record.Live || record.Gen != handle.Gen) WireDescriptorFatal("image-record-generation");
// Before the sync: a texture with no storage at all is one of the shapes, and syncing
// it would refuse rather than answer.
if (storage && WireShaderImageNamesNoTexel(*m_textureManager, state.BoundShaderImages[unit])) {
const VkFormat bound = MG_Util::ConvertTextureInternalFormatToVkEnum(
MG_Util::ConvertGLEnumToTextureInternalFormat(state.BoundShaderImages[unit].InternalFormat));
return ResolveWirePlaceholderImage(commandBuffer, program, programObj, binding, storage, out, bound,
static_cast<Uint32>(unit));
}
auto* resource = m_textureManager->SyncTextureResourceByHandle(handle, false, storage);
if (!resource) WireDescriptorFatal("image-resource");
m_textureManager->FlushPendingUploads();
const auto target = static_cast<MG_Pipe::MGPipeResourceTarget>(record.Desc.Target);
const Bool layerable = WireTargetHasLayers(target);
using Target = MG_Pipe::MGPipeResourceTarget;
const Bool layerable = target == Target::Tex1DArray || target == Target::Tex2DArray ||
target == Target::Tex2DMSArray || target == Target::Tex3D ||
target == Target::TexCube || target == Target::TexCubeArray;
Uint32 level = storage ? state.BoundShaderImages[unit].Level : record.Params.BaseLevel;
// GL ignores Layer/Layered for non-layerable targets (WireTargetHasLayers).
// GL ignores Layer/Layered for non-layerable targets. In particular image1D
// stays a 1D view, and an ignored nonzero Layer must not address another slice.
Uint32 layer = storage && layerable && !state.BoundShaderImages[unit].Layered
? state.BoundShaderImages[unit].Layer : 0;
const Uint32 localLevel = level;
@@ -659,8 +602,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
#if MOBILEGL_BUILD_DISAGGREGATED
for (auto& entry : m_wirePlaceholderImages) DestroyWirePlaceholderImage(entry.second);
m_wirePlaceholderImages.clear();
m_wirePrivateStoragePlaceholders = 0;
m_wireInvalidStorageImagesBindNull = false;
#endif
m_bufferManager = nullptr;
@@ -727,40 +668,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
}
}
#if MOBILEGL_BUILD_DISAGGREGATED
Bool UniformManager::WireDescriptorSetBudgetReached(Uint32 frameIndex) const {
MOBILEGL_ASSERT(frameIndex < m_frames.size(), "WireDescriptorSetBudgetReached invalid frame index");
return m_frames[frameIndex].allocatedSetsThisFrame >= kWireDescriptorSetBudget;
}
SizeT UniformManager::RewindWireDescriptorSets(Uint32 frameIndex) {
MOBILEGL_ASSERT(frameIndex < m_frames.size(), "RewindWireDescriptorSets invalid frame index");
auto& frame = m_frames[frameIndex];
// The caller proved that the last graphics submit using these sets has
// retired and that no unsubmitted command buffer still references them.
// Keep the pools and sets: only the per-layout write cursors rewind.
// Image and buffer views stay alive until the regular frame boundary.
m_peakDescriptorSetsObserved = std::max(m_peakDescriptorSetsObserved, frame.peakAllocatedSetsThisFrame);
SizeT cachedSets = 0;
for (auto& entry : frame.descriptorSetCacheByLayout) {
cachedSets += entry.second.sets.size();
entry.second.cursor = 0;
}
frame.allocatedSetsThisFrame = 0;
frame.peakAllocatedSetsThisFrame = 0;
for (auto& entry : m_descriptorReuseMemo) entry.valid = false;
m_fastRebindMemo.valid = false;
m_lastBindValid = false;
const Uint32 touchedBindings =
std::min<Uint32>(m_samplerResolveMemoHighWater, static_cast<Uint32>(m_samplerResolveMemo.size()));
for (Uint32 binding = 0; binding < touchedBindings; ++binding) {
m_samplerResolveMemo[binding].valid = false;
m_samplerResolveMemo[binding].infoValid = false;
}
return cachedSets;
}
#endif
void UniformManager::OnDescriptorSetLayoutDestroyed(VkDescriptorSetLayout descriptorSetLayout) {
SizeT purgedSets = 0;
for (auto& frame : m_frames) {
@@ -1242,58 +1149,16 @@ namespace MobileGL::MG_Backend::DirectVulkan {
state.BoundShaderImages[unit].InternalFormat));
if (format == VK_FORMAT_UNDEFINED) format = MG_Util::ConvertTextureInternalFormatToVkEnum(internalFormat);
const auto feature = storage ? VK_FORMAT_FEATURE_STORAGE_TEXEL_BUFFER_BIT : VK_FORMAT_FEATURE_UNIFORM_TEXEL_BUFFER_BIT;
if (format == VK_FORMAT_UNDEFINED || !BufferFormatSupportsFeature(m_physicalDevice, format, feature)) {
// P7 A.5, a decline (rule I (a)). GL's buffer-texture format list is wider than what
// Vulkan mandates for texel buffers - GL_RGB32{F,I,UI} and the 16-bit UNORM members
// are the realistic misses on a real driver - so this is a device capability gap, not
// anything the application did wrong, and nothing it could have sent differently.
//
// The placeholder is the RIGHT answer here, where it was not for the unaligned range
// above, and the difference is whether a correct answer exists at all. There, the
// bytes are addressable and only the descriptor cannot name them, so a placeholder
// would have hidden a fixable gap behind silently dropped writes. Here the device
// cannot represent this format as a texel buffer in any form - so the honest
// observable is monolith's for a missing view: the fetch reads zeros and the draw
// survives. AcquireUnboundTexelBufferView falls back to the R32 member of the
// shader's numeric class, whose texel-buffer support is mandatory, so the fallback
// itself cannot fail for want of device features.
MGLOG_E_ONCE("ResolveWireTexelBufferDescriptor: binding %u wants VkFormat %d as a %s texel buffer and "
"this device does not support it; the binding falls back to the zero placeholder and the "
"fetch reads zeros (texel-buffer-native-format)",
binding, static_cast<Int>(format), storage ? "storage" : "uniform");
return placeholder();
}
if (format == VK_FORMAT_UNDEFINED || !BufferFormatSupportsFeature(m_physicalDevice, format, feature))
WireDescriptorFatal("texel-buffer-native-format@P7");
const VkDeviceSize texelSize = MG_Util::GetSizedInternalFormatSizeInBytes(internalFormat);
VkDeviceSize start = 0, size = 0;
if (texelSize == 0 || !ResolveWireRange(record.Desc.BufOffset, record.Desc.BufSize, slice.size, start, size)) return false;
size = std::min(size / texelSize, static_cast<VkDeviceSize>(m_wireMaxTexelElements)) * texelSize;
if (size == 0) return false;
if (start > std::numeric_limits<VkDeviceSize>::max() - slice.offset)
WireDescriptorFatal("texel-buffer-offset-overflow");
if ((slice.offset + start) % m_wireTexelOffsetAlignment != 0) {
// P7 A.4, a named decline (rule I (a)). Not reachable through the public API:
// glTexBufferRange already refuses an offset that is not a multiple of
// GL_TEXTURE_BUFFER_OFFSET_ALIGNMENT (GL_Texture.cpp), and that cap is published
// from this same minTexelBufferOffsetAlignment. It stays a decline rather than a
// copy for the reason below.
const Bool writable = storage && state.BoundShaderImages[unit].Access != kMGPipeImageAccessReadOnly;
MGLOG_E_ONCE("ResolveWireTexelBufferDescriptor: binding %u is bound at offset %llu, which is not a "
"multiple of this device's minTexelBufferOffsetAlignment (%llu); the %s view is DECLINED "
"(unaligned-texel-buffer-range)", binding,
static_cast<unsigned long long>(slice.offset + start),
static_cast<unsigned long long>(m_wireTexelOffsetAlignment),
writable ? "writable" : "read-only");
// A read-only fetch can still be served the way an unbound buffer texture is -
// zeros, which is what a missing view gives in monolith - and that keeps the draw.
// A writable imageBuffer must not: the placeholder is shared by every unbound
// binding, so absorbing real stores into it would alias other bindings AND lose
// the application's writes without a word. Copying into an aligned transient slice
// is not the answer either: the transient arena carries no
// {UNIFORM,STORAGE}_TEXEL_BUFFER usage (VkBufferManager::InitializeTransientArenas),
// so no VkBufferView can be made over it, and widening a shared per-frame
// allocation to buy an unreachable path is the wrong trade. See notes/p7/magma-a.md.
return writable ? false : placeholder();
}
if (start > std::numeric_limits<VkDeviceSize>::max() - slice.offset ||
(slice.offset + start) % m_wireTexelOffsetAlignment != 0)
WireDescriptorFatal("unaligned-texel-buffer-range@P7");
VkBufferViewCreateInfo viewInfo{VK_STRUCTURE_TYPE_BUFFER_VIEW_CREATE_INFO};
viewInfo.buffer = slice.buffer;
viewInfo.format = format;
@@ -1681,56 +1546,11 @@ namespace MobileGL::MG_Backend::DirectVulkan {
if (!m_bufferManager->AcquireWireSlice(BufferKind::ShaderStorage, range.Res, slice) || !slice.IsValid()) return false;
VkDeviceSize start = 0, size = 0;
if (!ResolveWireRange(range.Offset, range.Size, slice.size, start, size)) return false;
if (start > std::numeric_limits<VkDeviceSize>::max() - slice.offset)
WireDescriptorFatal("storage-buffer-offset-overflow");
if ((slice.offset + start) % m_wireStorageOffsetAlignment != 0) {
// P7 A.4, a named decline (rule I (a)), and the one shape in this cluster an
// application can actually reach. GL has no queryable atomic-counter buffer
// offset alignment, so glBindBufferRange only enforces offset % 4 for
// GL_ATOMIC_COUNTER_BUFFER (GL 4.6 core 6.1.1, GL_Buffer.cpp
// ValidateBufferRangeOffsetAndSize); glslang lowers the counter block onto a
// storage buffer, whose descriptor offset must be a multiple of
// minStorageBufferOffsetAlignment - 16 on lavapipe, 64 on Adreno. Offset 4 is
// therefore a legal bind this backend cannot express. The plain SSBO half is
// unreachable by comparison: GL_SHADER_STORAGE_BUFFER_OFFSET_ALIGNMENT is
// published from that same Vulkan limit, so the frontend already refused it
// with GL_INVALID_VALUE.
//
// DECLINED RATHER THAN COPIED, deliberately. Copying the window into an aligned
// transient slice reads correctly and then silently DROPS every shader write,
// and this site cannot tell a writable block from a read-only one: there is no
// readonly bit in the storage-block reflection (ProgramFactory.h carries only
// name and index), an atomic counter is written by definition, and
// MarkWireBufferGpuWritten below already assumes any binding here may be
// written. A correct copy needs a post-dispatch copy-back from the transient
// slice to the unaligned source, ordered with a barrier - and the place to
// record that is the draw/dispatch tail in VulkanRenderer.cpp / WireDraw.inc,
// which belong to wave-2 packages B and C, not to this file. Losing the
// dispatch with a named line in the role log beats returning stale counters
// with no error at all. notes/p7/magma-a.md carries the recipe.
MGLOG_E_ONCE("ResolveStorageBufferDescriptor: block '%s' is bound at offset %llu, which is not a "
"multiple of this device's minStorageBufferOffsetAlignment (%llu); %s ranges cannot be "
"expressed as a descriptor and the shader's writes would be dropped by a read-only "
"copy, so the binding is DECLINED (unaligned-%s-buffer-range)",
blockName.c_str(), static_cast<unsigned long long>(slice.offset + start),
static_cast<unsigned long long>(m_wireStorageOffsetAlignment),
isAtomicCounterBlock ? "atomic-counter" : "shader-storage",
isAtomicCounterBlock ? "atomic" : "storage");
return false;
}
if (size > m_wireMaxStorageRange) {
// P7 A.3: clamp, do not refuse. The monolith arm binds whatever the GL range
// asked for and never consults maxStorageBufferRange at all (see the resident
// path below), so refusing here was the wire arm inventing a death the other
// backend does not have. A clamped binding keeps every byte the device can
// name reachable; past it the shader is out of the descriptor and
// robustBufferAccess answers zero, which beats losing the draw outright.
MGLOG_E_ONCE("ResolveStorageBufferDescriptor: block '%s' bound %llu bytes, past this device's "
"maxStorageBufferRange of %llu; the binding is clamped to the limit",
blockName.c_str(), static_cast<unsigned long long>(size),
static_cast<unsigned long long>(m_wireMaxStorageRange));
size = m_wireMaxStorageRange;
}
if (start > std::numeric_limits<VkDeviceSize>::max() - slice.offset ||
(slice.offset + start) % m_wireStorageOffsetAlignment != 0)
WireDescriptorFatal(isAtomicCounterBlock ? "unaligned-atomic-buffer-range@P7"
: "unaligned-storage-buffer-range@P7");
if (size > m_wireMaxStorageRange) WireDescriptorFatal("storage-buffer-native-range@P7");
outBufferInfo = {slice.buffer, slice.offset + start, size};
// Shader writes stay in the canonical server VkBuffer. The event marks the
// client's shadow stale; neither this path nor later acquires seed it back.
@@ -2538,25 +2358,9 @@ namespace MobileGL::MG_Backend::DirectVulkan {
Uint32 blockIndex, Uint32 bindingPoint, UboBindResult& out) const {
if (bindingPoint >= MG_Pipe::kMGPipeMaxBufferBindingPoints)
WireDescriptorFatal("uniform-buffer-binding-point");
VkDeviceSize blockSize = program.GetUBOSizeAt(blockIndex);
const VkDeviceSize blockSize = program.GetUBOSizeAt(blockIndex);
if (blockSize == 0) return false;
if (blockSize > m_wireMaxUniformRange) {
// P7 A.3: clamp, do not refuse. A conformant program cannot get here -
// GL_MAX_UNIFORM_BLOCK_SIZE is published straight from this same
// maxUniformBufferRange (BackendLoaders/Vulkan/Loader.cpp), so a block this big
// fails to link long before a draw - which makes refusing it a Fatal for a shape
// nothing can produce. If the two ever disagree, the honest answer is the bytes
// the device CAN name: everything past the clamp is outside the descriptor and
// reads back as zero under robustBufferAccess, which is inside GL's "undefined"
// for a block the implementation never promised to hold. Clamping keeps the range
// constant across draws, so the descriptor-set reuse hash is unaffected.
MGLOG_E_ONCE("ResolveWireUniformBufferPayload: reflected uniform block %u is %llu bytes, past this "
"device's maxUniformBufferRange of %llu; the binding is clamped to the limit and the "
"remainder reads zero",
blockIndex, static_cast<unsigned long long>(blockSize),
static_cast<unsigned long long>(m_wireMaxUniformRange));
blockSize = m_wireMaxUniformRange;
}
if (blockSize > m_wireMaxUniformRange) WireDescriptorFatal("uniform-block-native-range@P7");
const auto& range = MG_Pipe::MGPipeApplier().BoundShaderBuffers[
MG_Pipe::kMGPipeShaderBufferClassUniform][bindingPoint];
BufferSlice source{};
@@ -2583,45 +2387,17 @@ namespace MobileGL::MG_Backend::DirectVulkan {
// inside the GL binding range. A readback here could retire the command buffer
// whose value BindProgramUniformBuffers is currently holding.
const VkDeviceSize copied = std::min(available, blockSize);
if (bound && ((start & 3u) != 0 || ((source.offset + start) & 3u) != 0 || (copied & 3u) != 0))
WireDescriptorFatal("uniform-buffer-byte-tail@P7");
static thread_local Vector<Uint8> zero;
zero.assign(static_cast<SizeT>(blockSize), 0);
BufferSlice padded{};
if (!m_bufferManager->UploadTransient(BufferKind::Uniform, m_wireFrameIndex, zero.data(), blockSize,
std::max<VkDeviceSize>(4, m_minDynamicOffsetAlignment), padded) || !padded.IsValid()) return false;
if (bound && copied != 0) {
// P7 A.1 retires `uniform-buffer-byte-tail`. The window is word-aligned at both
// ends on nearly every bind - glBindBufferRange already forces the offset onto
// GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT, and that is a multiple of four on every
// device - but GL 4.6 core 6.1.1 puts no such rule on the SIZE, so `copied` is free
// to end mid-word and the Redmi Minecraft run lands there
// (notes/p5f/magma-inproc-fix.md #5). An unaligned start is not reachable through
// the public API and only a protocol-level offset can produce one; the sub-word arm
// handles it anyway rather than leaving a second shape to trip over later. Both arms
// copy the same bytes to the same place: the sub-word one pays one extra transient
// slice and one extra region copy, and nothing outside [start, start + copied)
// reaches the block, which is what makes the padded zeros the visible tail.
const Bool wordWindow = ((start | copied) & 3u) == 0;
if (!(wordWindow
? m_bufferManager->CopyWireBufferRangeToSlice(range.Res, start, copied, padded)
: m_bufferManager->CopyWireBufferSubWordRangeToSlice(range.Res, start, copied,
m_wireFrameIndex, padded, 0)))
return false;
}
if (padded.offset > std::numeric_limits<Uint32>::max()) {
// P7 A.2, a decline (rule I (a)), not a session death. A Vulkan dynamic offset is a
// uint32_t, so a transient uniform ring that grew past 4 GiB inside one frame has
// nowhere to put this block - which is our ring's problem, not a protocol fault, and
// nothing the peer could have sent differently. One binding is skipped and the draw
// is lost; the session keeps running and the next frame's rewound ring resolves it.
// The monolith arm has the same ceiling and truncates silently on the way out
// (ResolveDynamicUboDescriptor's static_cast<Uint32>), i.e. it binds a WRONG window
// rather than none, so declining is the strictly better observable of the two.
MGLOG_E_ONCE("ResolveWireUniformBufferPayload: the transient uniform ring reached offset "
"%llu, past the 4 GiB a Vulkan dynamic offset can name; uniform binding "
"point %u is declined for this draw",
static_cast<unsigned long long>(padded.offset), bindingPoint);
return false;
}
if (bound && copied != 0 &&
!m_bufferManager->CopyWireBufferRangeToSlice(range.Res, start, copied, padded)) return false;
if (padded.offset > std::numeric_limits<Uint32>::max())
WireDescriptorFatal("uniform-buffer-dynamic-offset@P7");
out.directBindable = true;
out.buffer = padded.buffer;
out.range = blockSize;
@@ -3033,10 +2809,7 @@ namespace MobileGL::MG_Backend::DirectVulkan {
Bool UniformManager::PrepareWireTextureResources(const MagmaProgramSource& program,
const ProgramFactory::VkProgramObject& programObj) {
if (!program.IsWire()) return true;
if (programObj.declinedDescriptors || m_textureManager == nullptr) {
MGL_WIRE_DECLINE_AT(DescriptorDeclined, "the program carries a descriptor MobileGL could not resolve");
return false;
}
if (programObj.declinedDescriptors || m_textureManager == nullptr) return false;
const auto& state = MG_Pipe::MGPipeApplier();
// Resolve writable images first: aliases sampled by the same draw must
// see the final STORAGE-capable allocation before any view is built.
@@ -3050,28 +2823,16 @@ namespace MobileGL::MG_Backend::DirectVulkan {
const Uint32 count = BindingDescriptorCount(programObj, binding);
for (Uint32 element = 0; element < count; ++element) {
const Int location = baseLocation + static_cast<Int>(element);
if (baseLocation < 0 || !program.UniformLocationsAliasSameUniform(baseLocation, location)) {
MGL_WIRE_DECLINE_AT(SamplerLocationAlias,
"binding %u element %u does not alias one sampler uniform", binding,
element);
if (baseLocation < 0 || !program.UniformLocationsAliasSameUniform(baseLocation, location))
return false;
}
const Int unit = program.GetUniformSamplerOrImageUnitIndex(static_cast<Uint>(location));
if (unit < 0 || static_cast<Uint32>(unit) >=
(storage ? MG_Pipe::kMGPipeMaxImageUnits : MG_Pipe::kMGPipeMaxTextureUnits)) {
MGL_WIRE_DECLINE_AT(SamplerUnitRange, "sampler/image unit %d is out of range", unit);
return false;
}
(storage ? MG_Pipe::kMGPipeMaxImageUnits : MG_Pipe::kMGPipeMaxTextureUnits)) return false;
const auto handle = storage ? state.BoundShaderImages[unit].Res
: state.BoundSamplerViews[unit].Texture;
// Null is the wire's unbound/incomplete binding. Its native
// placeholder needs no resource upload or frontend allocation.
if (MG_Pipe::MGPipeHandleIsNull(handle)) continue;
// Nor does an image unit naming a (level, layer) its texture lacks: the
// descriptor resolve binds that same placeholder (GL 4.6 core 8.26), and
// preparing the texture would decline a storage-less one and lose the pass.
if (storage && WireShaderImageNamesNoTexel(*m_textureManager, state.BoundShaderImages[unit]))
continue;
if (!m_textureManager->SyncTextureResourceByHandle(handle, false, storage)) return false;
}
}
@@ -3119,12 +2880,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
(samplerBindingOverrides == nullptr || samplerBindingOverrides->empty());
if (cacheable && samplerDescriptorsUnchangedHint && m_fastRebindMemo.valid &&
m_fastRebindMemo.frameIndex == frameIndex &&
#if MOBILEGL_BUILD_DISAGGREGATED
// A wire store destroyed since the memo was taken may have handed its handle
// value to a later mint (see FastRebindMemo): "same VkBuffer" then names a
// different store, so the memo is refused and the full walk re-records it.
m_fastRebindMemo.wireStoreDestroyEpoch == m_bufferManager->GetWireStoreDestroyEpoch() &&
#endif
m_fastRebindMemo.programLifetimeId == program.GetLifetimeId() &&
m_fastRebindMemo.programHash == programObj.hash) {
VkBuffer uboBuffer = VK_NULL_HANDLE;
@@ -3421,16 +3176,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
}
};
mixWords(&programObj.descriptorSetLayout, sizeof(programObj.descriptorSetLayout));
#if MOBILEGL_BUILD_DISAGGREGATED
// P7 M2 round 2 (ID-P7-43): the buffer infos below name WIRE stores by VkBuffer
// handle, and a wire store can be destroyed mid-frame (VkBufferManager::
// DeferredWireRelease) with its handle value re-minted before this frame's memo
// is cleared. Folding the destroy epoch in makes every entry taken before such a
// destroy miss, so a byte-identical info can never revive a set baked to a dead
// store. NOT the slice epoch: that moves on every glBufferSubData and would make
// the memo miss on every draw.
mix64(m_bufferManager->GetWireStoreDestroyEpoch());
#endif
for (const auto& write : writes) {
mix64((static_cast<Uint64>(write.dstBinding) << 40) ^
(static_cast<Uint64>(write.descriptorType) << 8) ^
@@ -3485,11 +3230,7 @@ namespace MobileGL::MG_Backend::DirectVulkan {
m_fastRebindMemo = FastRebindMemo{
/*valid=*/true, frameIndex, program.GetLifetimeId(), programObj.hash,
fastRebindUboBinding, bufferInfos[0].buffer,
bufferInfos[0].range, descriptorSet,
#if MOBILEGL_BUILD_DISAGGREGATED
m_bufferManager->GetWireStoreDestroyEpoch(),
#endif
};
bufferInfos[0].range, descriptorSet};
} else {
m_fastRebindMemo.valid = false;
}
@@ -13,7 +13,6 @@
#include "VkBufferManager.h"
#include "VkSamplerManager.h"
#include "VkTextureManager.h"
#include "WirePlaceholderKey.h"
#include "../VkIncludes.h"
#include <Includes.h>
@@ -55,25 +54,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
void Shutdown();
void BeginFrame(Uint32 frameIndex);
#if MOBILEGL_BUILD_DISAGGREGATED
// A present-less wire frame may run arbitrarily many draws. Before its
// descriptor cursor reaches this budget, the renderer retires the
// submission that last used the sets and rewinds every layout cursor.
static constexpr Uint32 kWireDescriptorSetBudget = 2048;
Bool WireDescriptorSetBudgetReached(Uint32 frameIndex) const;
SizeT RewindWireDescriptorSets(Uint32 frameIndex);
// How the wire arm answers a STORAGE image unit that GL 4.6 core 8.26 makes invalid (no
// texture, or a (level, layer) its texture lacks): a load returns zero, a store and an
// atomic are discarded. `deviceNullDescriptor` is the renderer's enablement of
// VK_EXT_robustness2's nullDescriptor at device creation. With it the unit binds a NULL
// storage-image descriptor, which is exactly that rule. Without it (or under
// MGITEST_MAGMA_FORCE_PRIVATE_IMAGE_PLACEHOLDER=1, the host lanes' way onto this arm) the
// unit binds a placeholder PRIVATE to its unit (per shape), cleared before each use, so no
// two units ever alias; what that cannot give is a load of the SAME unit after its own
// store inside one pass reading zero, nor privacy past kWirePrivateStoragePlaceholderCap
// placeholders (CONTRACT-P7 §12). Called after Initialize.
void SetWireInvalidStorageImageArm(Bool deviceNullDescriptor);
#endif
// A command buffer (re)began recording: descriptor bindings recorded into
// the previous buffer do not carry over, so drop the bind-dedup shadow.
void OnCommandBufferBoundary() { m_lastBindValid = false; }
@@ -222,20 +202,10 @@ namespace MobileGL::MG_Backend::DirectVulkan {
VkImageLayout layout = VK_IMAGE_LAYOUT_UNDEFINED;
Uint32 layers = 1;
};
// Keyed by shape, and a storage placeholder on the arm without a null descriptor by its
// image unit too (WirePlaceholderKey.h: ChooseWirePlaceholderKey, and its cap).
mutable UnorderedMap<WirePlaceholderKey, WirePlaceholderImage, WirePlaceholderKeyHash> m_wirePlaceholderImages;
// How many of those are private to a unit (against kWirePrivateStoragePlaceholderCap).
mutable SizeT m_wirePrivateStoragePlaceholders = 0;
// See SetWireInvalidStorageImageArm.
Bool m_wireInvalidStorageImagesBindNull = false;
// boundStorageFormat: for a storage binding with no reflected format, the format the
// unit's glBindImageTexture named, when the unit holds a texture it cannot address
// (GL 4.6 core 8.26); UNDEFINED keeps the numeric-domain R32 default. `unit` is the image
// unit of a storage binding (what its private placeholder is private to); unused for a sampler.
mutable UnorderedMap<Uint64, WirePlaceholderImage> m_wirePlaceholderImages;
Bool ResolveWirePlaceholderImage(VkCommandBuffer commandBuffer, const MagmaProgramSource& program,
const ProgramFactory::VkProgramObject& programObj, Uint32 binding, Bool storage,
VkDescriptorImageInfo& out, VkFormat boundStorageFormat = VK_FORMAT_UNDEFINED, Uint32 unit = ~0u) const;
VkDescriptorImageInfo& out) const;
void DestroyWirePlaceholderImage(WirePlaceholderImage& image) const;
#endif
@@ -472,15 +442,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
// drops the hint upstream; an arena wrap or growth resolves a different
// VkBuffer and misses. AcquireDescriptorSet's per-frame cursor only
// advances, so the recorded set is never re-written within its frame.
// P7 M2 round 2 (ID-P7-43): a WIRE store can die MID-FRAME on the reclaim
// path (VkBufferManager::DeferredWireRelease), and the next mint can hand
// its VkBuffer handle value back - a heap pointer under lavapipe - so "the
// same VkBuffer+range" is no longer proof of the same store. The memo
// therefore records VkBufferManager::GetWireStoreDestroyEpoch() and misses
// once any wire store has been destroyed since; the descriptor-reuse
// signature below folds the same epoch in. On the wire arm this memo is
// never consulted (SetupWireDraw passes no sampler hint), so the field is
// the defensive half; the signature is the half the wire arm reaches.
struct FastRebindMemo {
Bool valid = false;
Uint32 frameIndex = 0;
@@ -490,9 +451,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
VkBuffer uboBuffer = VK_NULL_HANDLE;
VkDeviceSize uboRange = 0;
VkDescriptorSet set = VK_NULL_HANDLE;
#if MOBILEGL_BUILD_DISAGGREGATED
Uint64 wireStoreDestroyEpoch = 0;
#endif
};
FastRebindMemo m_fastRebindMemo;
@@ -442,94 +442,41 @@ namespace MobileGL::MG_Backend::DirectVulkan {
for (Uint32 location = 0; location < elements.AttributeCount; ++location) {
const auto& attr = elements.Attributes[location];
if (!attr.Enabled || !(activeMask & (1u << location))) continue;
// P7 wave 2 package C, CONTRACT-P7 §3.2 `vertex-layout`: THE ONE STRING BECAME TWO
// VERDICTS, and the split is by what the reason is ABOUT rather than by severity.
//
// Every reason here used to return false, and the single caller answered that with
// one P7-marked MagmaWireFatal - an abort, bypassing Session::Fail, invisible
// to the census gate and with no equivalent on the monolith arm at all. But the
// reasons are not one kind of thing:
//
// * `buffer-window` is a statement about the RECORD: an enabled attribute the
// program reads names a slot outside the window set_vertex_buffers published.
// Nothing about the device or the format is involved; the two halves of the
// protocol disagree about what crossed. It stays a named Fatal through the hook
// (see the caller), and it is load-bearing rather than defensive - it is what
// caught the Redmi VAO hash collision fixed in 376c04be.
//
// * every other reason is a statement about what VULKAN CAN EXPRESS on this
// device: a GL type with no VkFormat, a format without
// VK_FORMAT_FEATURE_VERTEX_BUFFER_BIT, a component size we cannot compute, an
// offset sum that does not fit. The monolith arm has had an answer for these
// since it was written, and it is not an abort: mask the attribute out of the
// vertex input state and carry on (the `unsupportedAttribMask |= ...; continue;`
// sites in GetOrCreateVertexInputState above). The draw path then decides,
// loudly and once, whether the masked attribute was one the program actually
// reads. This arm now does exactly that, which is what "same observable as the
// monolith lane" means for this row.
//
// THE COUNT: the contract says "the other six"; there are SEVEN return sites below
// it, because `offset-overflow` was added after the audit's count and is an
// arithmetic guard rather than a shape one. It is masked with the rest: an
// attribute whose base offsets cannot be added is one Vulkan cannot fetch, the
// monolith arm never computes that sum at all, and masking is strictly safer than
// a Fatal for a number no application can reach on purpose. Recorded in
// notes/p7/magma-c.md rather than silently reconciled.
const auto describe = [&](const char* reason, VkFormat format) {
MGLOG_E_ONCE("Magma wire vertex layout: %s location=%u type=%u size=%u normalized=%u integer=%u long=%u bgra=%u stride=%d offset=%llu format=%d bufferWindow=%u+%u activeMask=0x%x",
const auto reject = [&](const char* reason, VkFormat format = VK_FORMAT_UNDEFINED) {
MGLOG_E("Magma wire vertex layout: %s location=%u type=%u size=%u normalized=%u integer=%u long=%u bgra=%u stride=%d offset=%llu format=%d bufferWindow=%u+%u activeMask=0x%x",
reason, location, attr.Type, static_cast<Uint32>(attr.Size), static_cast<Uint32>(attr.Normalized),
static_cast<Uint32>(attr.IsInteger), static_cast<Uint32>(attr.IsLong), static_cast<Uint32>(attr.IsBgra),
attr.Stride, static_cast<unsigned long long>(attr.Offset), static_cast<Int>(format),
state.VertexBufferStart, state.VertexBufferCount, activeMask);
};
// The protocol verdict: the caller turns a false into the named Fatal.
const auto reject = [&](const char* reason, VkFormat format = VK_FORMAT_UNDEFINED) {
describe(reason, format);
return false;
};
// The device verdict: MGLOG_E_ONCE + mask + continue, the monolith arm's shape.
// MGLOG_E_ONCE and not MGLOG_E, also the monolith arm's: an unmappable attribute is
// a property of the VAO and the device, so it repeats every draw, and the per-draw
// line is what made the old abort look preferable to whoever wrote it.
const auto maskOut = [&](const char* reason, VkFormat format = VK_FORMAT_UNDEFINED) {
describe(reason, format);
out.unsupportedAttribMask |= 1u << location;
};
// set_vertex_buffers is flattened PER ATTRIBUTE (VertexInputEmit.h), not
// indexed by the original ARB binding point in attr.BindingIndex.
if (location < state.VertexBufferStart ||
location - state.VertexBufferStart >= state.VertexBufferCount) return reject("buffer-window");
const auto& buffer = state.VertexBuffers[location];
const auto type = static_cast<DataType>(attr.Type);
if (attr.Stride < 0 || attr.Size < 1 || attr.Size > 4) { maskOut("attribute-shape"); continue; }
if (attr.Stride < 0 || attr.Size < 1 || attr.Size > 4) return reject("attribute-shape");
VkFormat format = ToVkVertexFormat(type, attr.Size, attr.Normalized, attr.IsInteger,
attr.IsBgra, attr.IsLong);
auto conversion = VertexStreamConversion::None;
if (format == VK_FORMAT_UNDEFINED && type == DataType::Float64) {
const auto* backend = MG_Remote::Server::ServerLoopInstance().Backend();
if (backend && backend->GetDynamicParameters().SupportsFloat64VertexAttributes) {
// Exactly the monolith arm's answer for the same state: with native fp64
// the module KEPT its 64-bit inputs (DemoteFloat64Pass did not run), so
// narrowing the stream would feed float32 to a Float64 input - and the
// monolith build therefore leaves sourceVkFormat UNDEFINED and falls into
// its own mask-out below. Same place, same mask.
maskOut("native-fp64-format");
continue;
}
if (backend && backend->GetDynamicParameters().SupportsFloat64VertexAttributes) return reject("native-fp64-format");
format = ToFloat32VertexFormat(attr.Size);
conversion = VertexStreamConversion::Float64ToFloat32;
}
if (format == VK_FORMAT_UNDEFINED) { maskOut("format-map"); continue; }
if (format == VK_FORMAT_UNDEFINED) return reject("format-map");
if (!SupportsVertexBufferFormat(format)) {
if (!IsScaledIntegerVertexFormat(format)) { maskOut("native-format-feature", format); continue; }
if (!IsScaledIntegerVertexFormat(format)) return reject("native-format-feature", format);
format = ToFloat32VertexFormat(attr.Size);
conversion = VertexStreamConversion::ScaledIntegerToFloat32;
if (!SupportsVertexBufferFormat(format)) { maskOut("converted-format-feature", format); continue; }
if (!SupportsVertexBufferFormat(format)) return reject("converted-format-feature", format);
}
const SizeT elementSize = GetAttributeByteSize(type, attr.Size, attr.IsBgra);
if (!elementSize) { maskOut("element-size", format); continue; }
if (!elementSize) return reject("element-size", format);
const Uint64 offset = attr.Offset + buffer.Offset;
if (offset < attr.Offset) { maskOut("offset-overflow", format); continue; }
if (offset < attr.Offset) return reject("offset-overflow", format);
const SizeT alignment = (type == DataType::Int2101010Rev || type == DataType::Uint2101010Rev)
? elementSize : GetComponentSize(type);
if (conversion == VertexStreamConversion::None && alignment > 1 &&
@@ -553,15 +500,8 @@ namespace MobileGL::MG_Backend::DirectVulkan {
// resolved binding/attribute/divisor values, including a legal zero stride.
Uint64 hash = XXH64(out.bindings.data(), out.bindings.size() * sizeof(out.bindings[0]), 0);
hash = XXH64(out.attributes.data(), out.attributes.size() * sizeof(out.attributes[0]), hash);
hash = XXH64(out.bindingDivisors.data(),
out.layoutHash = XXH64(out.bindingDivisors.data(),
out.bindingDivisors.size() * sizeof(out.bindingDivisors[0]), hash);
// THE MASK IS PART OF THE LAYOUT NOW, for the same reason the monolith entry's hash
// carries it (the XXH64_update over unsupportedAttribMask in GetOrCreateVertexInputState
// above). Before this package the mask was always zero here, so leaving it out of the
// hash was free; now two VAOs can produce the SAME bindings, attributes and divisors
// and differ only in which enabled attribute was masked out, and a hash blind to that
// would serve one of them the other's pipeline.
out.layoutHash = XXH64(&out.unsupportedAttribMask, sizeof(out.unsupportedAttribMask), hash);
out.state.vertexBindingDescriptionCount = static_cast<Uint32>(out.bindings.size());
out.state.pVertexBindingDescriptions = out.bindings.data();
out.state.vertexAttributeDescriptionCount = static_cast<Uint32>(out.attributes.size());
@@ -21,52 +21,6 @@
namespace MobileGL::MG_Backend::DirectVulkan {
namespace {
#if MOBILEGL_BUILD_DISAGGREGATED
// P7 wave 2 package B3, INVESTIGATION PROBE (split-only, read once, not in
// ConfigLoader's accepted-env table - package B's MGITEST_MAGMA_FORCE_SHADER_MIPMAP
// shape). MOBILEGL_MAGMA_WIREBUF_PROBE=1 prints one line per streamed-buffer event so
// the `glBufferSubData -> draw` ordering of a trace can be read off a log instead of
// inferred. Costs a branch on a cached bool when unset.
Bool WireBufProbeEnabled() {
static const Bool enabled = [] {
const char* value = std::getenv("MOBILEGL_MAGMA_WIREBUF_PROBE");
return value && value[0] == '1';
}();
return enabled;
}
// P7 wave 2 package B3, FORCING KNOB (split-only, read once, not in ConfigLoader's
// accepted-env table - package B's MGITEST_MAGMA_FORCE_SHADER_MIPMAP shape).
//
// WriteWireBuffer has exactly one unsafe shape: taking the immediate host memcpy
// because `lastUseSerial > GetCompletedSerial()` said the buffer is idle. That
// predicate's first term is PURE COUNTING (`m_frameSerial - frameCount`, no fence),
// so on any arm where the frame serial advances without the GPU having proved the
// frame's submissions complete, the answer is a guess. Host lanes never reach that
// state on their own (measured: 0 mid-frame frame-boundary drains over the whole
// OpenRA replay), so the lane cannot arm against it without forcing it.
//
// 0/unset = off. 1 = the serial term answers "idle" for every write it would have
// ordered. N>1 = only the Nth such write (1-based), which is how one
// `glBufferSubData -> draw` pair is poisoned in isolation and the device's "one draw
// contributed nothing" signature is reproduced rather than the whole frame destroyed.
//
// The knob forces ONLY the counting term to lie. It does NOT bypass the ordered copy,
// so it stays a valid red-once across the fix: before the submission term existed the
// lie reached the host memcpy (red); with the submission term the lie is caught and
// the copy is still ordered (green).
Uint64 ForceStaleSerialSelector() {
static const Uint64 selector = [] {
const char* value = std::getenv("MGITEST_MAGMA_FORCE_STALE_BUFFER_SERIAL");
if (!value || !value[0]) return Uint64{0};
return static_cast<Uint64>(std::strtoull(value, nullptr, 10));
}();
return selector;
}
// Counts only the writes the busy predicate wanted to ORDER, so the selector indexes
// the streamed subdata -> draw pairs and nothing else.
Uint64 g_orderedWireWriteCounter = 0;
#endif
constexpr VmaAllocationCreateFlags kResidentBufferAllocationFlags =
VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT;
constexpr SizeT kLiveResourcePruneThreshold = 256;
@@ -240,15 +194,9 @@ namespace MobileGL::MG_Backend::DirectVulkan {
res.Slot, res.Gen);
std::abort();
}
// THE SERIAL IS READ BEFORE THE RESET BELOW ZEROES IT. Whether it is zero - whether any
// GPU command has named this store - decides whether the orphan can go at once or has
// to wait for a submission (DeferredWireRelease), and three lines from now the record
// no longer carries it.
const Uint64 orphanedUseSerial = resource->lastUseSerial;
DeferWireRelease(std::move(resource->buffer), orphanedUseSerial);
DeferRelease(std::move(resource->buffer));
resource->size = desc.Width;
resource->lastUseSerial = 0;
resource->lastUseSubmitIndex = 0; // M2 r2: the new store carries no submission yet (B3's stamp is per store)
resource->gpuWritesPending = false;
resource->stagedCoverage.clear();
++m_sliceEpochCounter;
@@ -268,9 +216,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
res.Slot, res.Gen, static_cast<unsigned long long>(resource->size));
std::abort();
}
++m_wireStoreCount;
NoteWireStorePeaks();
PublishWireReclaimGauges();
// Under transport, defined bytes follow as resource_subdata records. An
// undefined store has no shadow to upload and no implicit zero snapshot.
if (initialBytes != nullptr && desc.HasDefinedContent) {
@@ -279,13 +224,7 @@ namespace MobileGL::MG_Backend::DirectVulkan {
}
Bool VkBufferManager::WaitForWireBufferHostAccess(WireBufferResource& resource) {
// B3 review: the early return must consult the same submission term WriteWireBuffer
// does, or a caller that reaches here with the serial term idle skips the wait the
// term would have demanded.
if (resource.lastUseSerial <= GetCompletedSerial() && !resource.gpuWritesPending &&
(pVulkanRenderer == nullptr || pVulkanRenderer->IsSubmitIndexComplete(resource.lastUseSubmitIndex))) {
return true;
}
if (resource.lastUseSerial <= GetCompletedSerial() && !resource.gpuWritesPending) return true;
if (!m_copyProvider || !pVulkanRenderer) return false;
const VkCommandBuffer commands = m_copyProvider->AcquireBufferCopyCommandBuffer();
if (commands == VK_NULL_HANDLE) return false;
@@ -298,9 +237,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
return false;
}
resource.lastUseSerial = 0;
// B3: the wait above proved every submission at or below the sync point complete, so
// the submission term must be cleared with the serial or it would keep answering busy.
resource.lastUseSubmitIndex = 0;
resource.gpuWritesPending = false;
return true;
}
@@ -315,52 +251,7 @@ namespace MobileGL::MG_Backend::DirectVulkan {
}
if (size == 0) return;
Bool uploaded = false;
const Uint64 probeLastUse = resource->lastUseSerial;
const Uint64 probeCompleted = GetCompletedSerial();
// ---- P7 wave 2 package B3: WHAT EACH TERM OF THIS PREDICATE IS FOR -----------------
//
// A streamed `glBufferSubData -> draw` pair is only correct if the write is ordered
// against every draw that still reads the bytes it overwrites; a write this predicate
// answers "idle" is applied as an unsynchronised host memcpy, and a draw still reading
// the range then renders bytes that are not its own - silently, with no log line, no GL
// error and no Fatal. That was the OpenRA device divergence (magma-b3.md §2).
//
// THE GUARANTEE IS THE SERIAL TERM, and it is sound because of the FLOOR, not because
// of anything here. GetCompletedSerial() is max(m_frameSerial - frameCount,
// m_completedSerialFloor). The floor used to be raised to a retired submission's frame
// serial even while another submission carrying the SAME serial was still executing -
// on the wire arm a serial has two (a mid-frame FlushPendingCommands under a pooled
// fence, then Present) - so "frame N-1 complete" was asserted on a fence nobody waited.
// VulkanRenderer::OnSubmitsCompletedUpTo now raises it only to a serial no in-flight
// submission still carries, and run_trace_case.cmake reds a split retrace on any
// "MGWIRE-FLOOR unsound-serial-complete" line, which is that fix's lane.
//
// THE SUBMISSION TERM IS A PROBE AND A DEFENCE, NOT A SECOND GUARANTEE. It is not sound
// on its own: lastUseSubmitIndex is stamped at AcquireWireSlice with the next submission
// index, but the draw that acquired the slice can still be pushed into a LATER
// submission - BindProgramUniformBuffers -> SyncWireTextureShape's preserve path ->
// FlushWirePendingCommandsForTextureUpdate submits the stamped index without the draw -
// so the stamp can name S1 while the draw rides S2. What it does do: with the floor
// sound it should never be the term that says "busy" (the WBUF probe reports bySubmit
// separately, so a device that shows one has found a floor hole), and it is the only
// thing the MGITEST_MAGMA_FORCE_STALE_BUFFER_SERIAL knob leaves standing, which is what
// the StaleSerial. entries pin.
Bool busyBySerial = resource->lastUseSerial > GetCompletedSerial();
if (busyBySerial && ForceStaleSerialSelector() != 0) {
const Uint64 index = ++g_orderedWireWriteCounter;
const Uint64 selector = ForceStaleSerialSelector();
if (selector == 1 || selector == index) {
busyBySerial = false;
MGLOG_W("MGITEST_MAGMA_FORCE_STALE_BUFFER_SERIAL: write #%llu {slot=%u, gen=%u} off=%llu "
"size=%llu - the counting term is forced to answer \"idle\"",
static_cast<unsigned long long>(index), res.Slot, res.Gen,
static_cast<unsigned long long>(offset), static_cast<unsigned long long>(size));
}
}
const Bool busyBySubmission =
pVulkanRenderer != nullptr && !pVulkanRenderer->IsSubmitIndexComplete(resource->lastUseSubmitIndex);
if (busyBySerial || busyBySubmission) {
if (resource->lastUseSerial > GetCompletedSerial()) {
// Vulkan buffer copies require four-byte aligned ranges. An odd GL
// byte update waits, then writes only the exact range; rounding it
// from a CPU shadow could overwrite neighbouring GPU-written bytes.
@@ -368,7 +259,10 @@ namespace MobileGL::MG_Backend::DirectVulkan {
uploaded = StagedWireRangeCopy(*resource, bytes, static_cast<SizeT>(offset),
static_cast<SizeT>(size));
}
if (!uploaded && !WaitForWireBufferHostAccess(*resource)) WireBufferSyncFatal("host-write");
if (!uploaded && !WaitForWireBufferHostAccess(*resource)) {
MGLOG_F("Magma: Fatal{ResourceUnavailable, \"buffer-write-sync\"}");
std::abort();
}
}
if (!uploaded) {
uploaded = resource->buffer.Upload(bytes, size, offset);
@@ -380,18 +274,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
MGLOG_F("Magma: Fatal{ResourceUnavailable, \"buffer-upload\"}");
std::abort();
}
if (WireBufProbeEnabled()) {
MGLOG_I("WBUF write slot=%u gen=%u off=%llu size=%llu branch=%s bySerial=%d bySubmit=%d "
"lastUse=%llu completed=%llu frameSerial=%llu floor=%llu lastUseSubmit=%llu",
res.Slot, res.Gen, static_cast<unsigned long long>(offset),
static_cast<unsigned long long>(size),
(busyBySerial || busyBySubmission) ? "STAGED-or-WAIT" : "HOST-IMMEDIATE",
busyBySerial ? 1 : 0, busyBySubmission ? 1 : 0,
static_cast<unsigned long long>(probeLastUse), static_cast<unsigned long long>(probeCompleted),
static_cast<unsigned long long>(m_frameSerial),
static_cast<unsigned long long>(m_completedSerialFloor),
static_cast<unsigned long long>(resource->lastUseSubmitIndex));
}
MG_Remote::Server::StagedShadowStore::CoverageAdd(resource->stagedCoverage,
static_cast<SizeT>(offset),
static_cast<SizeT>(offset + size));
@@ -422,17 +304,8 @@ namespace MobileGL::MG_Backend::DirectVulkan {
auto* resource = FindWireBuffer(res);
if (!resource || !resource->buffer.IsValid() || resource->size == 0) return false;
resource->lastUseSerial = m_frameSerial;
// B3: the draw this slice is being acquired for is normally recorded into the NEXT
// submission - normally, not always: a mid-draw flush (SyncWireTextureShape's preserve
// path) can submit this index without the draw. This stamp is the defence term's input
// (see WriteWireBuffer); the floor behind lastUseSerial is the guarantee.
if (pVulkanRenderer) resource->lastUseSubmitIndex = pVulkanRenderer->GetWireNextSubmitIndex();
outSlice = resource->buffer.GetSlice(0, resource->size);
outSlice.mapped = nullptr;
if (WireBufProbeEnabled()) {
MGLOG_I("WBUF bind slot=%u gen=%u frameSerial=%llu", res.Slot, res.Gen,
static_cast<unsigned long long>(m_frameSerial));
}
return true;
}
@@ -450,9 +323,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
// work, not the draw that will bind that previously acquired slice.
// Preserve its reservation even if the idle drain advanced the frame.
resource->lastUseSerial = m_frameSerial;
// B3 review: and the submission half of the same reservation - the wait cleared it,
// and the draw holding the slice has not been submitted yet.
if (pVulkanRenderer) resource->lastUseSubmitIndex = pVulkanRenderer->GetWireNextSubmitIndex();
}
if (!resource->buffer.Invalidate(size, offset)) return false;
Memcpy(dst, static_cast<const Uint8*>(resource->buffer.GetMappedData()) + offset, static_cast<SizeT>(size));
@@ -483,59 +353,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
return true;
}
Bool VkBufferManager::CopyWireBufferSubWordRangeToSlice(MG_Pipe::MGPipeHandle res, Uint64 offset,
Uint64 size, Uint32 frameIndex,
const BufferSlice& dst, Uint64 dstSkip) {
auto* resource = FindWireBuffer(res);
if (!resource || offset > resource->size || size > resource->size - offset) return false;
if (dstSkip > dst.size || size > dst.size - dstSkip) return false;
if (size == 0) return true;
if (!m_copyProvider || dst.buffer == VK_NULL_HANDLE) return false;
// Round the read of the application's store OUT to whole words. The tail can only be
// clipped by the end of the store itself, and [offset, offset + size) already fits
// inside it, so the widened window still covers every byte the caller asked for.
const Uint64 alignedOffset = offset & ~Uint64{3};
const Uint64 stagedEnd = std::min<Uint64>((offset + size + 3) & ~Uint64{3}, resource->size);
const Uint64 headPad = offset - alignedOffset;
const Uint64 stagedSize = stagedEnd - alignedOffset;
if (stagedSize < headPad + size) return false;
// Uninitialized on purpose: the widening copy below writes every byte of it. The
// arena can grow to satisfy this, which parks (never frees) the buffer `dst` may
// already name - see BufferArena::EnsureCapacity - so the two slices are allowed to
// sit in different VkBuffers and the copy names each slice's own handle.
BufferSlice staging{};
if (!m_transientUploadArena.Allocate(frameIndex, stagedSize, 4, staging) || !staging.IsValid())
return false;
const VkCommandBuffer commands = m_copyProvider->AcquireBufferCopyCommandBuffer();
if (commands == VK_NULL_HANDLE) return false;
VkMemoryBarrier before{VK_STRUCTURE_TYPE_MEMORY_BARRIER};
before.srcAccessMask = VK_ACCESS_MEMORY_WRITE_BIT | VK_ACCESS_HOST_WRITE_BIT;
before.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT;
vkCmdPipelineBarrier(commands, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT | VK_PIPELINE_STAGE_HOST_BIT,
VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 1, &before, 0, nullptr, 0, nullptr);
const VkBufferCopy widen{alignedOffset, staging.offset, stagedSize};
vkCmdCopyBuffer(commands, resource->buffer.GetHandle(), staging.buffer, 1, &widen);
// The shift reads what the widening copy just wrote, so it needs its own edge even
// though both halves are transfers on one command buffer.
VkMemoryBarrier staged{VK_STRUCTURE_TYPE_MEMORY_BARRIER};
staged.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
staged.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
vkCmdPipelineBarrier(commands, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT,
0, 1, &staged, 0, nullptr, 0, nullptr);
const VkBufferCopy shift{staging.offset + headPad, dst.offset + dstSkip, size};
vkCmdCopyBuffer(commands, staging.buffer, dst.buffer, 1, &shift);
VkMemoryBarrier after{VK_STRUCTURE_TYPE_MEMORY_BARRIER};
after.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
after.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT;
vkCmdPipelineBarrier(commands, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
0, 1, &after, 0, nullptr, 0, nullptr);
resource->lastUseSerial = m_frameSerial;
return true;
}
void VkBufferManager::ReadbackWireBuffer(MG_Pipe::MGPipeHandle res, Uint64 offset, Uint64 size) {
Vector<Uint8> bytes(static_cast<SizeT>(size));
if (!ReadWireBuffer(res, offset, size, bytes.data())) {
@@ -576,134 +393,9 @@ namespace MobileGL::MG_Backend::DirectVulkan {
void VkBufferManager::DestroyWireBuffer(MG_Pipe::MGPipeHandle res) {
const auto found = m_wireBuffers.find(WireBufferKey(res));
if (found == m_wireBuffers.end()) return;
DeferWireRelease(std::move(found->second.buffer), found->second.lastUseSerial);
DeferRelease(std::move(found->second.buffer));
m_wireBuffers.erase(found);
++m_sliceEpochCounter;
PublishWireReclaimGauges();
}
void VkBufferManager::DeferWireRelease(VkBufferObject&& buffer, Uint64 lastUseSerial) {
if (!buffer.IsValid()) return;
// Two stores go NOW rather than into the list. With no frame slots (DeferRelease's own
// teardown guard, and for its reason) there is no manager left to reclaim anything
// later. And a store whose last-use serial is 0 was never named by a GPU command since
// it was minted or since a host-access wait retired everything recorded before it - see
// DeferredWireRelease - so there is nothing to wait for.
if (m_deferredBufferReleases.empty() || lastUseSerial == 0) {
buffer.Destroy();
++m_wireStoreDestroyEpoch;
if (m_wireStoreCount > 0) --m_wireStoreCount;
return;
}
DeferredWireRelease entry;
entry.lastUseSerial = lastUseSerial;
// The last submission that can name this store: see DeferredWireRelease. Zero when there
// is no renderer, which is also when there is no queue and nothing to wait for.
entry.submitIndex = pVulkanRenderer != nullptr ? pVulkanRenderer->GetSyncPointSubmitIndex() : 0;
entry.bytes = static_cast<Uint64>(buffer.GetSize());
entry.buffer = std::move(buffer);
m_deferredWireBytes += entry.bytes;
m_deferredWireReleases.push_back(std::move(entry));
NoteWireStorePeaks();
// EVERY PARK SWEEPS. The frame boundary is not a reclaim point this arm can lean on - a
// pbuffer replay that snapshot-exits delivers ONE present for 1.3 M calls (ID-P7-32) -
// so the only cadence that tracks the workload is the workload itself.
SweepDeferredWireReleases();
EnforceWireDeferredWatermark();
}
void VkBufferManager::EnforceWireDeferredWatermark() {
const Uint64 budget = static_cast<Uint64>(MG_Config::Ipc.WireDeferredMb) * 1024u * 1024u;
// TWO TRIGGERS, ONE SWITCH. Bytes are what the knob names, but a VkBuffer costs per
// OBJECT as well as per byte, and small orphans never reach a byte budget: measured on
// bsl-esc-menu-854 (spawn, lavapipe), one stretch with no submission parked 12,498 stores
// in 39.5 MB against 64 MiB. So a fixed count ceiling rides the same sync point; the
// knob's 0 turns both off, which keeps it one negative control.
if (budget == 0) return;
if (m_deferredWireBytes <= budget && m_deferredWireReleases.size() <= kWireDeferredCountCeiling) return;
// What is left after the sweep is named by work that is recorded but unsubmitted, or
// submitted but unretired. Every entry is tagged at or below the sync point taken HERE,
// so waiting it out - the host-access wait's own call, which flushes the recording first
// - proves all of them dead. A mid-frame flush is what WaitForWireBufferHostAccess and a
// glClientWaitSync already do to this command stream; it costs one submission per
// budget's worth of orphans, not one per glBufferData.
if (pVulkanRenderer == nullptr ||
!pVulkanRenderer->WaitForSubmitIndex(pVulkanRenderer->GetSyncPointSubmitIndex(), UINT64_MAX, true)) {
WireBufferSyncFatal("deferred-watermark");
}
++m_wireDeferredSyncs;
SweepDeferredWireReleases();
}
void VkBufferManager::NoteWireStorePeaks() {
m_wireStoreCountPeak = std::max(m_wireStoreCountPeak, m_wireStoreCount);
m_deferredWireBytesPeak = std::max(m_deferredWireBytesPeak, m_deferredWireBytes);
}
void VkBufferManager::PublishWireReclaimGauges() {
if (!MG_Util::PipeStats::Enabled()) return;
using MG_Util::PipeStats::Gauge;
MG_Util::PipeStats::PublishGauge(Gauge::WireBuffers, static_cast<Uint64>(m_wireBuffers.size()));
MG_Util::PipeStats::PublishGauge(Gauge::WireStoresPeak, m_wireStoreCountPeak);
MG_Util::PipeStats::PublishGauge(Gauge::WireDeferredBytesPeak, m_deferredWireBytesPeak);
MG_Util::PipeStats::PublishGauge(Gauge::WireDeferredSyncs, m_wireDeferredSyncs);
}
void VkBufferManager::WireBufferSyncFatal(const char* site) {
MGLOG_F("Magma: Fatal{ResourceUnavailable, \"buffer-write-sync\"} {site=%s}", site);
std::abort();
}
SizeT VkBufferManager::SweepDeferredWireReleases() {
if (m_deferredWireReleases.empty()) return 0;
SizeT dead = 0;
if (pVulkanRenderer == nullptr ||
pVulkanRenderer->IsSubmitIndexComplete(pVulkanRenderer->GetSyncPointSubmitIndex())) {
// Idle: nothing recorded, every submission retired - or no renderer, so no queue.
// Every parked store is dead, including one tagged for a batch that was abandoned
// instead of submitted.
dead = m_deferredWireReleases.size();
} else {
// The list is in park order and GetSyncPointSubmitIndex() steps back only when a
// pending recording is abandoned instead of submitted (RecreateSwapchain and the
// minimized Present force-clear the recording flags, so `m_submitCounter + 1`
// becomes `m_submitCounter`). Everywhere else the submit indices are non-decreasing
// and the dead entries are a PREFIX: the first entry the renderer will not call
// complete proves none after it is either. Across an abandonment a later entry can
// carry the LOWER index; the walk then stops at the earlier, higher one and holds
// both until the next submission takes that index and retires - conservative, never
// early, and the idle rule above retires them regardless. That bounds the walk to a
// couple of fence polls, which matters because this runs on every glBufferData the
// wire carries.
while (dead < m_deferredWireReleases.size() &&
pVulkanRenderer->IsSubmitIndexComplete(m_deferredWireReleases[dead].submitIndex)) {
++dead;
}
}
if (dead == 0) return 0;
for (SizeT i = 0; i < dead; ++i) {
DeferredWireRelease& entry = m_deferredWireReleases[i];
m_deferredWireBytes -= entry.bytes;
entry.buffer.Destroy();
}
// One bump per sweep that destroyed anything is enough: what a memo needs to know
// is "some handle it may name has been freed since", not how many.
++m_wireStoreDestroyEpoch;
m_deferredWireReleases.erase(m_deferredWireReleases.begin(),
m_deferredWireReleases.begin() + static_cast<std::ptrdiff_t>(dead));
const Uint64 destroyedCount = static_cast<Uint64>(dead);
m_wireStoreCount = destroyedCount <= m_wireStoreCount ? m_wireStoreCount - destroyedCount : 0;
return dead;
}
void VkBufferManager::DestroyAllDeferredWireReleases() {
if (!m_deferredWireReleases.empty()) ++m_wireStoreDestroyEpoch;
for (auto& entry : m_deferredWireReleases) {
entry.buffer.Destroy();
if (m_wireStoreCount > 0) --m_wireStoreCount;
}
m_deferredWireReleases.clear();
m_deferredWireBytes = 0;
}
#endif
@@ -748,14 +440,7 @@ namespace MobileGL::MG_Backend::DirectVulkan {
DestroyAllDeferredReleases();
ReleaseAllLiveResources();
#if MOBILEGL_BUILD_DISAGGREGATED
// DestroyAllDeferredReleases above emptied the parked list; this destroys the stores the
// records still hold, so nothing this arm minted outlives the count.
if (!m_wireBuffers.empty()) ++m_wireStoreDestroyEpoch;
m_wireBuffers.clear();
m_wireStoreCount = 0;
m_wireStoreCountPeak = 0;
m_deferredWireBytesPeak = 0;
m_wireDeferredSyncs = 0;
#endif
m_copyProvider = nullptr;
m_initInfo = {};
@@ -785,13 +470,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
"VkBufferManager::BeginFrame frame index out of range");
m_currentFrameIndex = frameIndex;
++m_frameSerial;
#if MOBILEGL_BUILD_DISAGGREGATED
if (WireBufProbeEnabled()) {
MGLOG_I("WBUF BEGINFRAME idx=%u newSerial=%llu floor=%llu (arena slot rewound)", frameIndex,
static_cast<unsigned long long>(m_frameSerial),
static_cast<unsigned long long>(m_completedSerialFloor));
}
#endif
CollectDeferredReleases(frameIndex);
m_transientUploadArena.BeginFrame(frameIndex);
}
@@ -808,9 +486,8 @@ namespace MobileGL::MG_Backend::DirectVulkan {
// Nothing bumps the slice epoch for those other resources, so freeing the buffer
// here left the streamed memo handing a destroyed VkBuffer to vkCmdBindIndexBuffer
// (llvmpipe then faulted inside the draw; the Create/Flywheel indirect retrace died
// exactly this way). Most mid-frame drains do not advance m_frameSerial; every
// eighth does, but only through BeginFrame after the arena/memo boundary work.
// The drain's per-resource sweep must not free arena storage: ResetFrame/BeginFrame is where
// exactly this way). Mid-frame drains do not advance m_frameSerial, so they must not
// free arena storage either: the arena's own ResetFrame/BeginFrame is the point where
// the slot's slices stop being reachable, and that is where these releases land.
for (Uint32 frameIndex = 0; frameIndex < m_deferredBufferReleases.size(); ++frameIndex) {
CollectDeferredReleases(frameIndex);
@@ -1089,9 +766,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
&afterBarrier, 0, nullptr, 0, nullptr);
resource.lastUseSerial = m_frameSerial;
// B3: the copy just recorded rides the next submission too, so a later host write to
// the same bytes must wait for it exactly as a draw's read must.
if (pVulkanRenderer) resource.lastUseSubmitIndex = pVulkanRenderer->GetWireNextSubmitIndex();
resource.gpuWritesPending = true;
return true;
}
@@ -1473,12 +1147,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
"VkBufferManager::CollectDeferredReleases frame index out of range");
m_deferredBufferReleases[frameIndex].clear();
m_deferredResourceReleases[frameIndex].clear();
#if MOBILEGL_BUILD_DISAGGREGATED
// The wire list is not per-slot and does not wait for a frame boundary; a boundary is
// just one more point to sweep at (BeginFrame after its slot fence, and every slot of
// the idle drain, where the renderer-idle rule empties the list).
SweepDeferredWireReleases();
#endif
}
BufferSlice VkBufferManager::AcquireUnboundStorageDescriptor() {
@@ -1574,10 +1242,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
}
void VkBufferManager::DestroyAllDeferredReleases() {
#if MOBILEGL_BUILD_DISAGGREGATED
// Both callers (Shutdown, RecreateTransientArenas) have proven the device idle.
DestroyAllDeferredWireReleases();
#endif
for (auto& releases : m_deferredBufferReleases) {
for (auto& buffer : releases) {
buffer.Destroy();
@@ -113,17 +113,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
Bool ReadWireBuffer(MG_Pipe::MGPipeHandle res, Uint64 offset, Uint64 size, void* dst);
Bool CopyWireBufferRangeToSlice(MG_Pipe::MGPipeHandle res, Uint64 offset, Uint64 size,
const BufferSlice& dst);
// P7 A.1, the sub-word half of the one above: the same copy for a window whose start
// or end does not land on a four-byte boundary. The read of the APPLICATION's store is
// rounded OUT to whole words and clamped to the store's end, so the widened window can
// never touch a byte the application does not own; it lands in a transient staging
// slice, and only the staging -> dst shift is sub-word - inside our own arena, where an
// unaligned region cannot alias anything else. vkCmdCopyBuffer places no alignment rule
// on a region's offsets or size (unlike vkCmdUpdateBuffer / vkCmdFillBuffer), so the
// shift is a plain legal copy. `dstSkip` is the byte inside `dst` the window starts at.
// This retires `uniform-buffer-byte-tail`.
Bool CopyWireBufferSubWordRangeToSlice(MG_Pipe::MGPipeHandle res, Uint64 offset, Uint64 size,
Uint32 frameIndex, const BufferSlice& dst, Uint64 dstSkip);
void MarkWireBufferGpuWritten(MG_Pipe::MGPipeHandle res, Uint64 offset, Uint64 size);
// Resource-op entry points. All run on the server apply owner.
@@ -208,13 +197,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
// back, and none was persistently mapped, in between - so a memo of resolved
// slices needs no per-buffer re-check. See AcquirePersistentMap for the mapping half.
Uint64 GetSliceEpochCounter() const { return m_sliceEpochCounter; }
#if MOBILEGL_BUILD_DISAGGREGATED
// Bumped every time this manager destroys a WIRE store's VkBuffer (see
// m_wireStoreDestroyEpoch). Unchanged since a memo was taken means no VkBuffer handle
// that memo names can have been freed and re-minted in between, which is the one
// fact a handle-keyed memo of wire descriptors needs and cannot read off the handle.
Uint64 GetWireStoreDestroyEpoch() const { return m_wireStoreDestroyEpoch; }
#endif
// Highest frame serial whose GPU work is known complete; serials at or
// below it may be considered signaled. Drives IsResourceBusy and the
// backend GL fence objects.
@@ -235,12 +217,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
VkBufferObject buffer;
Uint64 size = 0;
Uint64 lastUseSerial = 0;
// P7 wave 2 package B3: the submission expected to carry the most recent GPU use
// of this buffer - the busy predicate's DEFENCE term, not its guarantee (see
// WriteWireBuffer). IsSubmitIndexComplete polls the real fence and reports an
// unsubmitted index as incomplete, but the stamp is taken before the draw is
// recorded and a mid-draw flush can submit it without the draw.
Uint64 lastUseSubmitIndex = 0;
Bool gpuWritesPending = false;
// Only ranges actually submitted by resource_subdata are covered. No
// shadow is retained: flush cannot replay stale bytes over GPU writes.
@@ -251,91 +227,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
}
WireBufferResource* FindWireBuffer(MG_Pipe::MGPipeHandle res);
Bool WaitForWireBufferHostAccess(WireBufferResource& resource);
// P7 wave 4 (M2), ID-P7-27: THE WIRE ARM'S ORPHANS NEED A RECLAIM THAT IS NOT A FRAME
// BOUNDARY.
//
// RespecifyWireBuffer - which is every glBufferData that crosses the wire - orphans the
// old store unconditionally, because unlike OnRespecify it has no shadow to upload in
// place from and no cheap way to know the client is re-sending the same size. The orphan
// is legitimate (M1 measured the conditional-orphan mirror: 6701 live against 6702).
// What was missing is the RECLAIM. DeferRelease parks into m_deferredBufferReleases,
// whose only sweep is CollectDeferredReleases from a frame boundary, and on a pbuffer
// replay the server sees ONE present record for the whole run - so on
// minecraft-1.21.4-fabric-iris-bsl-esc-menu-854 the buckets held 25,923 dead stores
// against 28 live wire buffers, one memfd mapping each, and the server died in scudo's
// secondary allocator.
//
// So a wire store is parked HERE instead, with the facts that say when it is dead, and
// THE DEFER PATH ITSELF RECLAIMS - every park sweeps, and the frame boundary is only one
// more sweep point (CollectDeferredReleases), never the one this depends on:
//
// * `lastUseSerial == 0` - read BEFORE RespecifyWireBuffer zeroes it. Zero means no
// GPU command has named the store since it was minted or since the last host-access
// wait proved every recorded command complete (WaitForWireBufferHostAccess); every
// path that hands the store to the GPU stamps m_frameSerial, which starts at 1. Such
// a store is destroyed at the park and never enters the list.
// * `submitIndex` - the renderer's GetSyncPointSubmitIndex() at park time, which is by
// construction the LAST submission that can name this store: every command that
// names it was recorded before the park (the record left behind a bumped slice
// epoch, so no memo can hand it out again), and a recorded command is either already
// submitted (<= m_submitCounter) or in the batch that becomes m_submitCounter + 1.
// IsSubmitIndexComplete(submitIndex) is a fence observation, so this is the gate
// that empties the set MID-FRAME - the shape CollectWireObjects already uses for
// the wire image/view tables.
// * THE RENDERER IS IDLE - IsSubmitIndexComplete(GetSyncPointSubmitIndex()): nothing
// is recorded and every submission has retired. Then every parked store is dead,
// including one tagged for a batch that was abandoned rather than submitted (a
// minimized Present drops its recording), whose own index may never complete.
//
// THE FRAME-SERIAL FLOOR IS DELIBERATELY NOT A PROOF HERE. It cannot move inside a
// frame (NotifyFrameSerialComplete refuses the current serial), so it frees nothing in
// the one-present replay this exists for; the submit index above is the fact that CAN
// move mid-frame, and it is a fence observation rather than a count.
//
// AND EVERY DESTROY HERE HAPPENS MID-FRAME, which the memos above this manager were not
// written for. UniformManager's descriptor memos are keyed on the VkBuffer HANDLE, and
// before M2 a wire store only ever died at the same boundary that clears those memos
// (UniformManager::BeginFrame, from Present or a drain). A store destroyed here can
// have its handle value re-minted by the next Create - a heap pointer under lavapipe -
// while a memo still maps that handle to a descriptor set baked to the dead store's
// memory: silent wrong bytes, no Fatal (ID-P7-43). m_wireStoreDestroyEpoch is the
// fact the memos fold in: every wire-store destroy bumps it, so a memo taken before
// the destroy cannot match after it. Deliberately NOT m_sliceEpochCounter, which every
// WriteWireBuffer bumps and which would defeat the memo on every glBufferSubData.
struct DeferredWireRelease {
VkBufferObject buffer;
Uint64 lastUseSerial = 0;
Uint64 submitIndex = 0;
// Cached: GetSize() is gone once the object is destroyed, and the watermark's
// running total has to stay exact as entries leave.
Uint64 bytes = 0;
};
// Park a wire store, sweep, then hold the watermark. `lastUseSerial` is the releasing
// resource's, captured before the caller resets it.
void DeferWireRelease(VkBufferObject&& buffer, Uint64 lastUseSerial);
// Destroy every parked store proven dead by the rules above. Returns how many.
SizeT SweepDeferredWireReleases();
// MOBILEGL_IPC_WIRE_DEFERRED_MB (Config.h has the semantics): when the parked bytes
// still exceed the budget after a sweep, take the sync point WaitForWireBufferHostAccess
// takes - flush what is recorded, wait for it - and sweep again, which retires every
// parked store, because none can be tagged past the sync point it just waited out.
void EnforceWireDeferredWatermark();
// ...and the same sync point when more than this many stores are parked, whatever their
// bytes (see the definition for the measurement). Not a knob: it bounds an object count
// the byte budget cannot see, and MOBILEGL_IPC_WIRE_DEFERRED_MB=0 disables it too.
static constexpr SizeT kWireDeferredCountCeiling = 1024;
// Teardown: the caller has proven the device idle (Shutdown / RecreateTransientArenas).
void DestroyAllDeferredWireReleases();
// THE one Fatal{ResourceUnavailable, "buffer-write-sync"} site (rule I: no second abort
// for the census to count), shared by the host write that cannot wait for the GPU and
// the watermark that cannot. `site` says which.
[[noreturn]] static void WireBufferSyncFatal(const char* site);
// The wbuf[] gauges (PipeStats.h, Gauge::WireBuffers..WireDeferredSyncs). The peaks are
// taken at the two points the numbers can rise - a park and a mint - and published when
// the stats channel is on; MagmaWireReclaimScenario reads them off the server's line.
void NoteWireStorePeaks();
void PublishWireReclaimGauges();
#endif
Bool InitializeTransientArenas();
static VkBufferUsageFlags GetVkBufferUsage(BufferKind kind);
@@ -372,23 +263,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
Vector<WeakPtr<VkBufferResource>> m_liveResources;
#if MOBILEGL_BUILD_DISAGGREGATED
std::unordered_map<Uint64, WireBufferResource> m_wireBuffers;
// See DeferredWireRelease. ONE FLAT LIST rather than the per-frame-slot buckets above:
// the whole point is that these entries do not wait for a frame slot to come round.
Vector<DeferredWireRelease> m_deferredWireReleases;
// Bytes currently parked in that list, kept exact so the watermark needs no walk.
Uint64 m_deferredWireBytes = 0;
// Live VkBuffers this arm owns: the stores held by m_wireBuffers plus the parked ones.
// Maintained rather than counted, because the publish runs on every park.
Uint64 m_wireStoreCount = 0;
// Run maxima of the two numbers above and the watermark's sync count, for the gauges.
Uint64 m_wireStoreCountPeak = 0;
Uint64 m_deferredWireBytesPeak = 0;
Uint64 m_wireDeferredSyncs = 0;
// See GetWireStoreDestroyEpoch and the DeferredWireRelease comment. Bumped on every
// path that destroys a wire store's VkBuffer, and never reset (not even by Shutdown),
// for m_sliceEpochCounter's reason: a memo taken before a re-initialize must not match
// a handle minted after it.
Uint64 m_wireStoreDestroyEpoch = 0;
#endif
// Size m_liveResources had just after the last sweep; the next sweep waits for it to double.
SizeT m_liveResourcesLastPruned = 0;
@@ -23,8 +23,6 @@
#include <MG_Pipe/PipeApply.h>
#include <MG_Remote/Server/StagedTextureStore.h>
#include "../DirectVulkan.h"
// P7 wave 2 package B3: rule I's tally for the silent exits on this file's wire arm.
#include "WireDeclineTally.h"
#endif
#include <algorithm>
#include <cstdio>
@@ -1807,8 +1805,8 @@ namespace MobileGL::MG_Backend::DirectVulkan {
// SyncTexture reads the frontend ITextureObject: the target, the format, the level
// chain, the dirty scan and - through UploadDirtyMipLevels - the CLIENT's mip shadow
// texels. Under an active transport none of that memory is the server's to read
// (rule E), which is exactly what Magma's texture-legacy-arm scope waived from P5c until
// P7 retired it (SyncTexture). This arm is the same sync re-sourced: the SHAPE comes from the applier's
// (rule E), which is exactly what Magma's texture-legacy-arm scope has been waiving
// since P5c. This arm is the same sync re-sourced: the SHAPE comes from the applier's
// resource record (MGPipeApplier().TextureResources - the resource_create /
// resource_respecify descriptors), the TEXELS from the server's staged-texture store
// (P5c tx, adopted at apply time), and the WHICH-LEVELS from the record's
@@ -2071,21 +2069,13 @@ namespace MobileGL::MG_Backend::DirectVulkan {
if (desc.StorageKind != static_cast<Uint8>(TextureStorageType::Mipmap)) {
MGLOG_W_ONCE("Magma wire texture {slot=%u, gen=%u}: buffer-backed textures are not migrated; declined",
desc.Resource.Slot, desc.Resource.Gen);
WireDeclineTally::Count(WireDeclineSite::ShapeBufferBacked);
return false;
}
// ResolveWireTextureStorage has already followed ViewOf. Views share the storage
// owner's image and layout; allocating a second image would break aliasing.
if (!MG_Pipe::MGPipeHandleIsNull(desc.ViewOf)) {
MGL_WIRE_DECLINE_AT(ShapeViewOfStorage,
"texture {slot=%u, gen=%u} is a view whose storage owner did not resolve",
desc.Resource.Slot, desc.Resource.Gen);
return false;
}
if (!MG_Pipe::MGPipeHandleIsNull(desc.ViewOf)) return false;
if (desc.Levels == 0) {
// A create before the first respecify: no storage, nothing to back.
MGL_WIRE_DECLINE_AT(ShapeNoLevels, "texture {slot=%u, gen=%u} has no defined level yet",
desc.Resource.Slot, desc.Resource.Gen);
return false;
}
TextureShapeInfo shapeInfo{};
@@ -2094,7 +2084,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
"(%ux%ux%u, %u layers); declined",
desc.Resource.Slot, desc.Resource.Gen, static_cast<Uint32>(desc.Target), desc.Width,
desc.Height, desc.Depth, static_cast<Uint32>(desc.ArrayLayers));
WireDeclineTally::Count(WireDeclineSite::ShapeNoVulkanShape);
return false;
}
const TextureInternalFormat internalFormat = static_cast<TextureInternalFormat>(desc.InternalFormat);
@@ -2103,7 +2092,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
if (format == VK_FORMAT_UNDEFINED) {
MGLOG_W_ONCE("Magma wire texture {slot=%u, gen=%u}: no backing VkFormat for internal format 0x%x",
desc.Resource.Slot, desc.Resource.Gen, desc.InternalFormat);
WireDeclineTally::Count(WireDeclineSite::ShapeNoVkFormat);
return false;
}
// X8_D24 lacks optimal-tiling support on several drivers (lavapipe included); the same
@@ -2126,7 +2114,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
if (!TryResolveSampleCountFlagBits(static_cast<Int>(desc.Samples), resolvedSampleCount)) {
MGLOG_W_ONCE("Magma wire texture {slot=%u, gen=%u}: unsupported sample count %u",
desc.Resource.Slot, desc.Resource.Gen, static_cast<Uint32>(desc.Samples));
WireDeclineTally::Count(WireDeclineSite::ShapeSampleCount);
return false;
}
// glTexStorage*Multisample(samples = 1) is legal GL, but a one-sample image cannot
@@ -2262,13 +2249,7 @@ namespace MobileGL::MG_Backend::DirectVulkan {
// old image must reach the queue first; waiting only for the preservation
// fence cannot order work that is still in the renderer's open recording.
// The descriptor caller preflights this before capturing its command buffer.
if (preserve && pVulkanRenderer && !pVulkanRenderer->FlushWirePendingCommandsForTextureUpdate()) {
MGL_WIRE_DECLINE_AT(ShapePreserveFlushFailed,
"texture {slot=%u, gen=%u}: earlier work could not be submitted before "
"preserving its texels across a reallocation",
desc.Resource.Slot, desc.Resource.Gen);
return false;
}
if (preserve && pVulkanRenderer && !pVulkanRenderer->FlushWirePendingCommandsForTextureUpdate()) return false;
TextureResource replacement;
VkImageCreateInfo imageInfo{};
@@ -2315,14 +2296,9 @@ namespace MobileGL::MG_Backend::DirectVulkan {
}
if (imageFormatResult != VK_SUCCESS ||
(isMultisample && (imageFormatProperties.sampleCounts & resolvedSampleCount) == 0)) {
// Was an MGLOG_D, which a Release build compiles away, so on the builds that ship
// this exit left no line - one of five Shape* exits that did (with ViewOf,
// NoLevels, preserve-flush and preserve-copy) before B3's review round.
MGL_WIRE_DECLINE_AT(ShapeImageFlagsUnsupported,
"texture {slot=%u, gen=%u}: image flags=0x%x sampleCount=%d are unsupported "
"by the device",
desc.Resource.Slot, desc.Resource.Gen, static_cast<Uint32>(imageInfo.flags),
static_cast<Int>(imageInfo.samples));
MGLOG_D("%s: image flags=0x%x sampleCount=%d are unsupported for texture {slot=%u, gen=%u}",
__func__, static_cast<Uint32>(imageInfo.flags),
static_cast<Int>(imageInfo.samples), desc.Resource.Slot, desc.Resource.Gen);
return false;
}
}
@@ -2341,7 +2317,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
imageInfo.extent.height, imageInfo.extent.depth, imageInfo.arrayLayers,
imageInfo.mipLevels, static_cast<Int>(imageInfo.samples),
static_cast<Int>(imageInfo.format));
WireDeclineTally::Count(WireDeclineSite::ShapeCreateImageFailed);
return false;
}
++m_textureImageEpoch; // a new attachment image invalidates cached render passes
@@ -2363,13 +2338,7 @@ namespace MobileGL::MG_Backend::DirectVulkan {
if (preserve) {
FlushPendingUploads();
if (!PreserveTextureContentsOnRecreate(m_device, m_commandPool, m_graphicsQueue,
resource, replacement, true)) {
MGL_WIRE_DECLINE_AT(ShapePreserveCopyFailed,
"texture {slot=%u, gen=%u}: its texels could not be copied into the "
"reallocated image",
desc.Resource.Slot, desc.Resource.Gen);
return false;
}
resource, replacement, true)) return false;
}
DeferResourceRelease(Move(resource));
std::destroy_at(&resource);
@@ -2416,7 +2385,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
MGLOG_E_ONCE("Magma wire texture {slot=%u, gen=%u}: pending upload for level %u exceeds the "
"image's %u levels; left pending",
handle.Slot, handle.Gen, static_cast<Uint32>(level), resource.mipLevels);
WireDeclineTally::Count(WireDeclineSite::UploadLevelBeyondChain);
continue;
}
const IntVec3 glExtent = store.LevelExtentOrUndefined(key, uploadTarget, level);
@@ -2437,19 +2405,9 @@ namespace MobileGL::MG_Backend::DirectVulkan {
texelSize.y() != static_cast<Int>(std::max(resource.extent.height >> level, 1u)) ||
(volume && texelSize.z() != static_cast<Int>(std::max(resource.depth >> level, 1u))) ||
(!volume && Uint64(ResolveUploadArrayLayer(static_cast<TextureUploadTarget>(uploadTarget))) +
static_cast<Uint64>(texelSize.z()) > resource.arrayLayers)) {
// NOT `incomplete`: this arm reports SUCCESS while leaving the entry pending,
// so the draw proceeds against texels that were never uploaded. Counted
// separately for exactly that reason (B3).
MGL_WIRE_DECLINE_AT(UploadLevelExtentMismatch,
"texture {slot=%u, gen=%u} level %u: the staged extent does not match the "
"image's extent for that level; left pending and NOT uploaded",
handle.Slot, handle.Gen, static_cast<Uint32>(level));
static_cast<Uint64>(texelSize.z()) > resource.arrayLayers))
continue;
}
if (texelSize.x() <= 0 || texelSize.y() <= 0 || byteSize == 0) {
MGL_WIRE_DECLINE_AT(UploadEmptyLevel, "texture {slot=%u, gen=%u} level %u is empty",
handle.Slot, handle.Gen, static_cast<Uint32>(level));
incomplete = true;
continue;
}
@@ -2465,7 +2423,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
"level %u left pending",
handle.Slot, handle.Gen, static_cast<Int>(resource.format),
static_cast<Uint32>(level));
WireDeclineTally::Count(WireDeclineSite::UploadConversion);
incomplete = true;
continue;
}
@@ -2478,10 +2435,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
(resource.aspect & VK_IMAGE_ASPECT_STENCIL_BIT);
if (vkuFormatIsCompressed(resource.format) || !levelTexels ||
item.byteSize % levelTexels != 0 || item.byteSize / levelTexels == 0) {
MGL_WIRE_DECLINE_AT(UploadTexelArithmetic,
"texture {slot=%u, gen=%u} level %u: compressed, or its byte size is not a "
"whole number of texels",
handle.Slot, handle.Gen, static_cast<Uint32>(level));
incomplete = true;
continue;
}
@@ -2501,10 +2454,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
if (offset[axis] < 0 || extent[axis] <= 0 ||
static_cast<Uint64>(offset[axis]) + static_cast<Uint64>(extent[axis]) >
static_cast<Uint64>(texelSize[axis])) {
MGL_WIRE_DECLINE_AT(UploadRegionOutOfBounds,
"texture {slot=%u, gen=%u} level %u: a staged region lies outside "
"the level",
handle.Slot, handle.Gen, static_cast<Uint32>(level));
incomplete = true;
return;
}
@@ -2547,25 +2496,7 @@ namespace MobileGL::MG_Backend::DirectVulkan {
addRegion({region.X, region.Y, region.Z, region.W, region.H, region.D});
}
}
// B3: the pending gauge is sampled here, on every pass through the funnel, because a
// refusal below does NOT consume the entries - they and their level shadows stay
// alive for the next draw to trip over (and, on a heavy-texture trace, to accumulate).
{
Uint64 pendingBytes = 0;
for (const auto& pending : record.PendingUploads) {
pendingBytes += static_cast<Uint64>(
store.LevelByteSize(MG_Remote::Server::StagedTextureStore::KeyForHandle(handle),
pending.UploadTarget, pending.Level));
}
WireDeclineTally::SetPendingGauge(static_cast<Uint64>(record.PendingUploads.size()), pendingBytes);
}
if (incomplete) {
MGL_WIRE_DECLINE_AT(UploadIncomplete,
"texture {slot=%u, gen=%u}: at least one pending level could not be staged; "
"every draw that samples it is declined until it can",
handle.Slot, handle.Gen);
return false;
}
if (incomplete) return false;
if (items.empty()) {
return true;
}
@@ -2574,13 +2505,7 @@ namespace MobileGL::MG_Backend::DirectVulkan {
// Submit older renderer work before adding the new bytes to the batch,
// otherwise Draw(old T), TexSubImage(T), Draw(new T) can upload before
// the first draw. A clean texture never reaches this submission boundary.
if (pVulkanRenderer && !pVulkanRenderer->FlushWirePendingCommandsForTextureUpdate()) {
MGL_WIRE_DECLINE_AT(UploadFlushFailed,
"texture {slot=%u, gen=%u}: earlier renderer work could not be submitted before "
"its upload batch",
handle.Slot, handle.Gen);
return false;
}
if (pVulkanRenderer && !pVulkanRenderer->FlushWirePendingCommandsForTextureUpdate()) return false;
// UploadDirtyMipLevels' batching rules, verbatim: flush an open batch that already
// writes this image and was touched by the open recording, and bound the staging bytes
@@ -2677,14 +2602,9 @@ namespace MobileGL::MG_Backend::DirectVulkan {
MG_Pipe::MGPipeHandle VkTextureManager::ResolveWireTextureStorage(
MG_Pipe::MGPipeHandle handle, Uint32& level, Uint32& layer,
VkFormat* viewFormat, Uint32* layerCount, Bool* outsideWindow) {
VkFormat* viewFormat, Uint32* layerCount) {
const auto& state = MG_Pipe::MGPipeApplier();
if (viewFormat) *viewFormat = VK_FORMAT_UNDEFINED;
if (outsideWindow) *outsideWindow = false;
const auto outside = [outsideWindow] {
if (outsideWindow) *outsideWindow = true;
return MG_Pipe::kMGPipeNullHandle;
};
Uint32 mappedLevel = level, mappedLayer = layer;
Uint32 remainingLayers = ~Uint32{0};
VkFormat outerFormat = VK_FORMAT_UNDEFINED;
@@ -2696,13 +2616,12 @@ namespace MobileGL::MG_Backend::DirectVulkan {
const auto& record = state.TextureResources[handle.Slot];
if (!record.Live || record.Gen != handle.Gen) return MG_Pipe::kMGPipeNullHandle;
if (MG_Pipe::MGPipeHandleIsNull(record.Desc.ViewOf)) {
// Levels == 0 is a texture with no storage at all: every level is outside it.
if (mappedLevel >= record.Desc.Levels) return outside();
if (mappedLevel >= record.Desc.Levels) return MG_Pipe::kMGPipeNullHandle;
const Uint32 layers = record.Desc.Target ==
static_cast<Uint8>(MG_Pipe::MGPipeResourceTarget::Tex3D)
? std::max(record.Desc.Depth >> mappedLevel, 1u)
: std::max<Uint32>(record.Desc.ArrayLayers, 1u);
if (mappedLayer >= layers) return outside();
if (mappedLayer >= layers) return MG_Pipe::kMGPipeNullHandle;
level = mappedLevel;
layer = mappedLayer;
if (viewFormat) *viewFormat = outerFormat;
@@ -2714,9 +2633,9 @@ namespace MobileGL::MG_Backend::DirectVulkan {
return MG_Pipe::kMGPipeNullHandle;
const auto& viewRecord = state.SamplerViewCsos[viewHandle.Slot];
const auto& view = viewRecord.View;
if (!viewRecord.Live || viewRecord.Gen != viewHandle.Gen || view.Texture != handle)
if (!viewRecord.Live || viewRecord.Gen != viewHandle.Gen || view.Texture != handle ||
mappedLevel >= view.NumLevels || mappedLayer >= view.NumLayers)
return MG_Pipe::kMGPipeNullHandle;
if (mappedLevel >= view.NumLevels || mappedLayer >= view.NumLayers) return outside();
if (outerFormat == VK_FORMAT_UNDEFINED) {
outerFormat = ResolveTextureFormatInfo(static_cast<TextureInternalFormat>(view.InternalFormat)).format;
if (outerFormat == VK_FORMAT_UNDEFINED) return MG_Pipe::kMGPipeNullHandle;
@@ -2740,12 +2659,7 @@ namespace MobileGL::MG_Backend::DirectVulkan {
Uint32 level = 0, layer = 0;
VkFormat viewFormat = VK_FORMAT_UNDEFINED;
const auto storage = ResolveWireTextureStorage(handle, level, layer, &viewFormat);
if (MG_Pipe::MGPipeHandleIsNull(storage)) {
MGL_WIRE_DECLINE_AT(TexResolveStorage,
"texture {slot=%u, gen=%u}: no storage owner resolved", handle.Slot,
handle.Gen);
return nullptr;
}
if (MG_Pipe::MGPipeHandleIsNull(storage)) return nullptr;
if (storage != handle) {
auto* resource = SyncTextureResourceByHandle(storage, false, requireStorage);
if (!resource) return nullptr;
@@ -2754,7 +2668,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
vkuFormatCompatibilityClass(viewFormat) != vkuFormatCompatibilityClass(resource->format))) {
MGLOG_E_ONCE("Magma wire view: format %d cannot reinterpret storage format %d",
static_cast<Int>(viewFormat), static_cast<Int>(resource->format));
WireDeclineTally::Count(WireDeclineSite::TexViewFormat);
return nullptr;
}
return resource;
@@ -2765,7 +2678,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
if (handle.Slot >= records.size()) {
MGLOG_E_ONCE("Magma wire texture {slot=%u, gen=%u}: no applier record at that slot; declined",
handle.Slot, handle.Gen);
WireDeclineTally::Count(WireDeclineSite::TexNoApplierRecord);
return nullptr;
}
auto& record = records[handle.Slot];
@@ -2775,7 +2687,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
MGLOG_E_ONCE("Magma wire texture {slot=%u, gen=%u}: the applier's record is %s; declined",
handle.Slot, handle.Gen,
!record.Live ? "dead" : "of another generation");
WireDeclineTally::Count(WireDeclineSite::TexRecordDeadOrStale);
return nullptr;
}
const Uint64 key = MG_Remote::Server::StagedTextureStore::KeyForHandle(handle);
@@ -2787,24 +2698,12 @@ namespace MobileGL::MG_Backend::DirectVulkan {
return &resource;
}
if (!SyncWireTextureShape(record, resource, requireStorage)) {
MGL_WIRE_DECLINE_AT(TexShapeSync, "texture {slot=%u, gen=%u}: no backing image; see the Shape* tally",
handle.Slot, handle.Gen);
return nullptr;
}
if (!renderbuffer && !UploadPendingWireLevels(handle, record, resource)) {
MGL_WIRE_DECLINE_AT(TexUploadPendingLevels,
"texture {slot=%u, gen=%u}: pending levels could not be uploaded; see the "
"Upload* tally",
handle.Slot, handle.Gen);
return nullptr;
}
if (requireStorage && (resource.usageFlags & VK_IMAGE_USAGE_STORAGE_BIT) == 0) {
MGL_WIRE_DECLINE_AT(TexStorageUsage,
"texture {slot=%u, gen=%u} is bound as a shader image but its allocation has no "
"STORAGE usage",
handle.Slot, handle.Gen);
return nullptr;
}
if (requireStorage && (resource.usageFlags & VK_IMAGE_USAGE_STORAGE_BIT) == 0) return nullptr;
resource.syncedWireSerial = record.Serial;
return &resource;
}
@@ -2964,16 +2863,16 @@ namespace MobileGL::MG_Backend::DirectVulkan {
Bool VkTextureManager::SyncTexture(MG_State::GLState::ITextureObject &texture,
TextureResource &outResource) {
// This is the FRONTEND-object sync: it reads - and clears - the client's mip shadow (the
// dirty scan below, UploadDirtyMipLevels' texel / region reads and MarkStorageDirty(false)
// clears), so it belongs to the monolith arm only. Under an active transport every wire
// verb syncs through the handle-keyed arm (SyncTextureResourceByHandle, and the sampled
// wire descriptors in UniformManager) from the applier's record and the staged-texture
// store. P5c's named exemption for this function (MGPipeTextureLegacyArmScope) was retired
// in P7 (ratchet88) once a probe proved it never armed on the apply thread; a regression
// now meets the layer-1 guard (Fatal{RoleViolation, "texture-legacy-arm"},
// MipmapStorage.cpp) by accessor name. This block is exactly as many lines as the one it
// replaced: __LINE__ reaches this file's pull .text, and G1 compares the bytes.
#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
@@ -566,13 +566,8 @@ public:
// Map a texture/view-relative subresource to its live storage owner. layerCount, when
// supplied, receives the number of accessible layers starting at the input layer.
// viewFormat is UNDEFINED for an ordinary texture, or the outer view's format.
// outsideWindow, when supplied, says WHY a null came back: true only when every record on
// the way was live and consistent and the (level, layer) simply is not there - past the
// owner's levels or layers, or past a view's own window. A dead record, a missing or stale
// view CSO and an unresolvable view format leave it false.
MG_Pipe::MGPipeHandle ResolveWireTextureStorage(MG_Pipe::MGPipeHandle handle, Uint32& level,
Uint32& layer, VkFormat* viewFormat = nullptr, Uint32* layerCount = nullptr,
Bool* outsideWindow = nullptr);
Uint32& layer, VkFormat* viewFormat = nullptr, Uint32* layerCount = nullptr);
// Grows the live image of a handle-keyed resource to `requiredMipLevels`, carrying the
// existing levels' content across with an in-command-buffer copy. The caller
// (GenerateMipmap's record arm) has flushed every pending submission first, so the old
File diff suppressed because it is too large. Load diff
@@ -147,19 +147,8 @@ namespace MobileGL::MG_Backend::DirectVulkan {
#if MOBILEGL_BUILD_DISAGGREGATED
VkBufferManager& GetWireBufferManager() { return m_bufferManager; }
Bool FlushWirePendingCommandsForTextureUpdate() {
// A new texture upload must not race graphics work that samples
// the old texels. No current recording does not imply no in-flight
// submission: finish the recorded work, then wait its whole prefix.
if (HasPendingRecordedWork() && !FlushPendingCommands()) return false;
return WaitForSubmitsUpTo(m_submitCounter, UINT64_MAX);
return !HasPendingRecordedWork() || FlushPendingCommands();
}
// P7 wave 2 package B3: the submission that will carry whatever is recorded NEXT.
// RetireWireObjects (WireDraw.inc) already tags future objects with exactly this, and
// for the same reason: a draw being set up now is not in any submission yet, so the
// index that names it is one past the counter. Deliberately NOT
// GetSyncPointSubmitIndex(), which answers m_submitCounter when nothing is recorded -
// true for a fence taken at that instant, wrong for work about to be recorded.
Uint64 GetWireNextSubmitIndex() const { return m_submitCounter + 1; }
#endif
// FrameContext::IRecordingObserver: prepares the frame's timer-query
@@ -416,20 +405,7 @@ namespace MobileGL::MG_Backend::DirectVulkan {
Int padding[3] = {0, 0, 0};
};
// P7 wave 2-B2, CONTRACT-P7 §5.2 (B'): THE FRONTEND MEMBERS ARE PULL-BUILD ONLY. In a
// disaggregated build the monolith arm blits and generates depth mips with the baked
// modules (WireColorBlit.inc, WireDepthMipmap.inc), so no DirectVulkan object holds a
// ProgramObject, a ShaderObject or a SamplerObject any more - which is what takes
// ProgramObject::{AllocateLifetimeId, AttachShader, Link, ~ProgramObject},
// ShaderObject::{SetShaderSource, Compile, JoinPendingCompile, ReleaseCompileNode,
// DropCompileNode} and SamplerObject::{SetWrapS, SetWrapT, SetWrapR, SetLodRange} out
// of the link ratchet's `p7-magma` bucket (§4.2). The destructor of a SharedPtr member
// is a reference too, so the MEMBER has to go and not only its construction.
//
// The structs stay, empty, so ShutdownBlitResources and the two `= {}` assignments read
// the same on both builds.
struct BlitResources {
#if !MOBILEGL_BUILD_DISAGGREGATED
SharedPtr<MG_State::GLState::ProgramObject> program;
SharedPtr<MG_State::GLState::SamplerObject> nearestSampler;
SharedPtr<MG_State::GLState::SamplerObject> linearSampler;
@@ -437,18 +413,15 @@ namespace MobileGL::MG_Backend::DirectVulkan {
Int dstRectLocation = -1;
Int surfaceTransformLocation = -1;
Uint32 samplerBinding = 0;
#endif
};
struct DepthMipmapResources {
#if !MOBILEGL_BUILD_DISAGGREGATED
SharedPtr<MG_State::GLState::ProgramObject> program;
Int srcRectLocation = -1;
Int dstRectLocation = -1;
Int surfaceTransformLocation = -1;
Int srcTexelSizeLocation = -1;
Uint32 samplerBinding = 0;
#endif
};
// A single-sample staging image for multisample-resolve blits that also have to change
@@ -494,8 +467,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
VkImageLayout* trackedLayout = nullptr;
VkSampleCountFlagBits samples = VK_SAMPLE_COUNT_1_BIT;
VkImageAspectFlags aspect = 0;
// Zero for the default framebuffer, which no arm that reads this ever reaches.
VkImageUsageFlags usageFlags = 0;
Uint32 level = 0, layer = 0, layers = 1, levels = 1;
Bool isDefault = false;
// Set when isDefault: the swapchain image index this role resolved to.
@@ -517,85 +488,18 @@ namespace MobileGL::MG_Backend::DirectVulkan {
void ResolveWireDepthStencil(WireImage source, WireImage destination,
GLint sx0, GLint sy0, GLint sx1, GLint sy1,
GLint dx0, GLint dy0, GLint dx1, GLint dy1);
// One aspect of a depth/stencil image through a buffer (source in TRANSFER_SRC_OPTIMAL,
// destination in TRANSFER_DST_OPTIMAL, one format). The returned buffer is named by the
// recorded commands and must be retired with them.
UniquePtr<VkBufferObject> CopyWireAspectThroughBuffer(VkImage srcImage, Uint32 srcLevel, Uint32 srcLayer,
GLint sx, GLint sy, const WireImage& destination,
GLint dx, GLint dy, Uint32 width, Uint32 height,
VkImageAspectFlags aspect, VkFormat format,
Bool mirrorY, const char* fatalDetail);
// A single-sample depth/stencil blit whose rectangles make it a plain copy, performed
// without vkCmdBlitImage (P7 gate 5). False when the shape is not a plain copy.
Bool CopyWireDepthStencilBlit(WireImage& source, WireImage& destination,
GLint sx0, GLint sy0, GLint sx1, GLint sy1,
GLint dx0, GLint dy0, GLint dx1, GLint dy1, VkImageAspectFlags aspect);
// True when the rectangles give a multisample depth/stencil resolve a shape it declines
// (a scale, an X mirror, a Y mirror across two formats); the decline has then been
// logged and its INVALID_OPERATION recorded. BlitWireFramebuffers asks it BEFORE any
// aspect runs, so a call the SHAPE declines leaves every attachment alone - the user
// and the default draw framebuffer alike. The CAPABILITY decline inside
// ResolveWireDepthStencil (a stencil-only resolve without VK_EXT_shader_stencil_export
// on a device without VK_KHR_depth_stencil_resolve) is still decided per aspect, after
// colour ran; rule I (a) accepts that (notes/p7/magma-b2.md §2.10).
Bool DeclineWireDepthStencilResolveShape(const WireImage& source, const WireImage& destination,
GLint sx0, GLint sy0, GLint sx1, GLint sy1,
GLint dx0, GLint dy0, GLint dx1, GLint dy1);
PFN_vkCreateRenderPass2 m_wireCreateRenderPass2 = nullptr;
VkResolveModeFlags m_wireDepthResolveModes = 0;
VkResolveModeFlags m_wireStencilResolveModes = 0;
// P7 wave 2-B2, CONTRACT-P7 §3.2 (`multisample-blit-aspect`): the SECOND arm of the
// multisample depth/stencil resolve, for the device that does not carry
// VK_KHR_depth_stencil_resolve. One baked pass per aspect, sample zero, no frontend
// object - see WireMultisampleResolve.inc. `resolved` must be a single-sample image of
// the source's format and extent; the rect is expressed by the scissor.
Bool ResolveWireDepthStencilWithShader(WireImage source, WireImage resolved,
VkImageAspectFlags aspect, GLint sx0, GLint sy0,
Uint32 width, Uint32 height);
struct WireMultisampleResolveResources;
WireMultisampleResolveResources* m_wireMultisampleResolveResources = nullptr;
void DestroyWireMultisampleResolveResources();
Bool m_wireShaderStencilExport = false;
// VK_EXT_robustness2 (or its KHR promotion) with ONLY nullDescriptor enabled, wire arms
// only: an invalid image unit binds a null storage descriptor (codex closeout finding 2).
Bool m_wireNullDescriptor = false;
// The resolve probe's verdict for this device (WireDepthResolveArm.h,
// WireDepthResolveProbe.h): true when the no-draw render pass was measured leaving its
// target unwritten while the shader control resolved - the shader arm then resolves
// first and the render-pass arm is the fallback (P7 gate 5, g5-msprobe).
Bool m_wirePreferShaderDepthResolve = false;
// Runs the probe (memoized per device identity) and sets the member above. Called at the end of
// device creation, after ArmPrimGenReroute: it records on m_graphicsQueue.
void ArmWireDepthResolveOrder();
Bool BlitWireColorToDefault(WireImage source, WireImage destination,
GLint sx0, GLint sy0, GLint sx1, GLint sy1,
GLint dx0, GLint dy0, GLint dx1, GLint dy1, GLenum filter);
Bool BlitWireColorImage(WireImage source, WireImage destination,
GLint sx0, GLint sy0, GLint sx1, GLint sy1,
GLint dx0, GLint dy0, GLint dx1, GLint dy1, GLenum filter, Bool mipmap);
// P7 wave 2-B, CONTRACT-P7 §3.2 (`default-color-blit-shape`): the rotated arm. Moves the
// source region into an owned single-sample 2D image of a sampled-float format in the
// same size-compatibility class, then shader-blits THAT to the rotated default
// framebuffer - the shapes BlitWireColorImage itself cannot sample (an integer format, a
// 3D or array source) become shapes it can.
Bool BlitWireColorToDefaultThroughScratch(WireImage source, WireImage destination,
GLint sx0, GLint sy0, GLint sx1, GLint sy1,
GLint dx0, GLint dy0, GLint dx1, GLint dy1,
GLenum filter);
struct WireColorBlitResources;
WireColorBlitResources* m_wireColorBlitResources = nullptr;
void DestroyWireColorBlitResources();
// P7 wave 2-B, CONTRACT-P7 §5.1 (A): the baked depth-mip program (WireDepthMipmap.inc).
// One level of a depth chain, source and destination being two depth subresources of
// the same image; the caller loops. It owns no frontend object, which is what the
// monolith arm's GenerateDepthMipmapWithShader cannot say.
Bool GenerateWireDepthMipLevel(WireImage source, WireImage destination);
struct WireDepthMipmapResources;
WireDepthMipmapResources* m_wireDepthMipmapResources = nullptr;
void DestroyWireDepthMipmapResources();
// P7 wave 2-B (exit gate 3): the readback's own write-visibility barrier, recorded before
// the copy instead of inferred from the image's tracked layout. See WireFramebuffer.inc.
void RecordWireReadbackWriteBarrier();
void ReadWirePixels(GLint x, GLint y, GLsizei width, GLsizei height,
GLenum format, GLenum type, void* pixels);
void GenerateWireMipmap();
@@ -656,7 +560,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
Vector<WireRetiredObjects> m_wireRetiredObjects;
Uint32 m_wirePreparationDepth = 0;
void DispatchWireCompute(GLuint x, GLuint y, GLuint z);
void RewindWireDescriptorSetsIfDue();
UniquePtr<RenderPassEntry> m_wireDrawPass;
Vector<VkImageView> m_wireDrawViews;
VkPipeline GetOrCreatePipelineWithInput(GLenum mode, const MagmaProgramSource& program,
@@ -713,11 +616,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
// was waited or the device was idled); drops their records and
// recycles pooled fences.
void OnSubmitsCompletedUpTo(Uint64 submitIndex);
#if MOBILEGL_BUILD_DISAGGREGATED
// A later fence alone cannot retire earlier submissions. Wait for the
// whole still-live prefix before advancing the completed submit floor.
Bool WaitForSubmitsUpTo(Uint64 submitIndex, Uint64 timeoutNs);
#endif
VkFence AcquirePooledSubmitFence();
void DestroySubmitFencePool();
Bool HasPendingRecordedWork() const;
@@ -1885,12 +1783,7 @@ namespace MobileGL::MG_Backend::DirectVulkan {
Bool MaterializePendingDepthStencilClearForDefaultFramebuffer(
VkCommandBuffer commandBuffer, const MG_State::GLState::FramebufferAttachmentObject& attachment,
const ClearAttachmentPayload& payload);
#if !MOBILEGL_BUILD_DISAGGREGATED
// P7 wave 2-B2 (CONTRACT-P7 §5.2, (B')): the hidden blit program's pipeline. A
// disaggregated build has no hidden program on either arm, so this has neither a body
// nor a caller there.
VkPipeline GetOrCreateBlitPipeline(const RenderPassEntry& renderPassEntry);
#endif
Bool GenerateDepthMipmapWithShader(FrameContext::FrameData& frame,
MG_State::GLState::ITextureObject& texture,
VkTextureManager::TextureResource& resource,
@@ -43,112 +43,6 @@
return BlitWireColorImage(source, destination, sx0, sy0, sx1, sy1, dx0, dy0, dx1, dy1, filter, false);
}
// P7 wave 2-B (CONTRACT-P7 §3.2, `default-color-blit-shape`). The shader blit below can only
// SAMPLE its source: sampler2D, a float result, and one of two 2D view types. A framebuffer
// whose colour attachment is RGBA8UI, or a layer of a 3D texture, is none of those, and on a
// rotated Android surface there is no other arm - an axis-aligned vkCmdBlitImage cannot
// express a quarter turn. So the source region becomes an owned 2D image first, through
// vkCmdCopyImage, which cares about the texel BLOCK SIZE and not about how the block is
// interpreted; the scratch then takes the shader blit as an ordinary 2D float source.
//
// REINTERPRETATION IS THE POINT FOR THE INTEGER CASE, and GL agrees: glBlitFramebuffer
// between an integer and a normalized format is INVALID_OPERATION (GL 4.6 core 18.3.1), so
// there is no defined result to be wrong about - only a shape that used to end the session
// and now produces the source's bits. For a float source of the wrong VIEW TYPE the copy is
// a plain slice extraction and the result is exactly right.
Bool VulkanRenderer::BlitWireColorToDefaultThroughScratch(WireImage source, WireImage destination,
GLint sx0, GLint sy0, GLint sx1, GLint sy1,
GLint dx0, GLint dy0, GLint dx1, GLint dy1, GLenum filter) {
if (!destination.isDefault || source.isDefault) return false;
if (source.samples != VK_SAMPLE_COUNT_1_BIT || destination.samples != VK_SAMPLE_COUNT_1_BIT)
return false;
if (!source.image || !destination.image || source.image == destination.image) return false;
const Int64 width = std::abs(static_cast<Int64>(sx1) - sx0);
const Int64 height = std::abs(static_cast<Int64>(sy1) - sy0);
if (!width || !height || dx0 == dx1 || dy0 == dy1) return true;
if (std::min(sx0, sx1) < 0 || std::min(sy0, sy1) < 0 ||
static_cast<Uint64>(std::max(sx0, sx1)) > source.extent.width ||
static_cast<Uint64>(std::max(sy0, sy1)) > source.extent.height) return false;
// A compressed source cannot be a colour attachment, so it cannot be a framebuffer blit's
// source either - but the block arithmetic below would silently produce nonsense for one,
// and "cannot happen" is the reason the guards this package retires were written as
// asserts. The size-compatibility classes are Vulkan's own (VkFormat texel block size);
// the destination format is whatever the swapchain uses and is always sampled-float.
if (vkuFormatIsCompressed(source.format)) return false;
VkFormat scratchFormat = VK_FORMAT_UNDEFINED;
switch (vkuFormatTexelBlockSize(source.format)) {
case 1: scratchFormat = VK_FORMAT_R8_UNORM; break;
case 2: scratchFormat = VK_FORMAT_R8G8_UNORM; break;
case 4: scratchFormat = VK_FORMAT_R8G8B8A8_UNORM; break;
case 8: scratchFormat = VK_FORMAT_R16G16B16A16_SFLOAT; break;
case 16: scratchFormat = VK_FORMAT_R32G32B32A32_SFLOAT; break;
default: return false;
}
VkFormatProperties scratchProperties{};
vkGetPhysicalDeviceFormatProperties(m_physicalDevice.handle, scratchFormat, &scratchProperties);
const VkFormatFeatureFlags scratchRequired = VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT |
(filter == GL_LINEAR ? VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT : 0);
if ((scratchProperties.optimalTilingFeatures & scratchRequired) != scratchRequired) return false;
auto scratch = MakeUnique<VkTextureManager::TextureResource>();
VkImageCreateInfo info{VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO};
info.imageType = VK_IMAGE_TYPE_2D;
info.format = scratchFormat;
info.extent = {static_cast<Uint32>(width), static_cast<Uint32>(height), 1};
info.mipLevels = info.arrayLayers = 1;
info.samples = VK_SAMPLE_COUNT_1_BIT;
info.tiling = VK_IMAGE_TILING_OPTIMAL;
info.usage = VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT;
info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
VmaAllocationCreateInfo allocation{};
allocation.usage = VMA_MEMORY_USAGE_AUTO_PREFER_DEVICE;
allocation.requiredFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT;
if (vmaCreateImage(m_allocator, &info, &allocation, &scratch->image, &scratch->allocation,
nullptr) != VK_SUCCESS)
return false;
scratch->format = scratchFormat;
scratch->extent = {info.extent.width, info.extent.height};
scratch->mipLevels = scratch->arrayLayers = scratch->depth = 1;
scratch->aspect = VK_IMAGE_ASPECT_COLOR_BIT;
WireImage staged{};
staged.image = scratch->image;
staged.format = scratchFormat;
staged.aspect = VK_IMAGE_ASPECT_COLOR_BIT;
staged.extent = scratch->extent;
staged.trackedLayout = &scratch->layout;
m_textureManager->FlushPendingUploads();
TransitionWireImage(source, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL);
TransitionWireImage(staged, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL);
VkImageCopy copy{};
// A 3D source carries its slice on z and always names layer 0; every other source
// carries it on the layer axis, which is the same split ResolveWireImage records.
copy.srcSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, source.level, source.is3D ? 0u : source.layer, 1};
copy.srcOffset = {std::min(sx0, sx1), std::min(sy0, sy1),
source.is3D ? static_cast<Int32>(source.layer) : 0};
copy.dstSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1};
copy.dstOffset = {0, 0, 0};
copy.extent = {static_cast<Uint32>(width), static_cast<Uint32>(height), 1};
vkCmdCopyImage(m_frameContext.GetCurrent().commandBuffer, source.image,
VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, staged.image,
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &copy);
staged.layout = scratch->layout;
// The scratch holds the region at its own origin, so a reversed source rectangle
// becomes a reversed rectangle OVER THE SCRATCH - the multisample resolve arm's shape.
const GLint rx0 = sx1 > sx0 ? 0 : static_cast<GLint>(width);
const GLint rx1 = sx1 > sx0 ? static_cast<GLint>(width) : 0;
const GLint ry0 = sy1 > sy0 ? 0 : static_cast<GLint>(height);
const GLint ry1 = sy1 > sy0 ? static_cast<GLint>(height) : 0;
const Bool blitted = BlitWireColorImage(staged, destination, rx0, ry0, rx1, ry1,
dx0, dy0, dx1, dy1, filter, false);
// Retired whether or not the blit took: the copy above is already recorded against this
// image, so the submission that consumes it owns the storage either way.
WireRetiredObjects retired{};
retired.textures.push_back(Move(scratch));
RetireWireObjects(Move(retired));
return blitted;
}
Bool VulkanRenderer::BlitWireColorImage(WireImage source, WireImage destination,
GLint sx0, GLint sy0, GLint sx1, GLint sy1,
GLint dx0, GLint dy0, GLint dx1, GLint dy1, GLenum filter, Bool mipmap) {
@@ -340,14 +234,7 @@
alloc.descriptorSetCount = 1;
alloc.pSetLayouts = &cache.descriptorLayout;
VK_VERIFY(vkAllocateDescriptorSets(m_device, &alloc, &descriptorSet));
// GL_LINEAR filters only a STRETCHED blit; an unscaled one (mirrored or not, on any of the
// four transforms) is a copy and samples NEAREST, which is exact where linear filtering
// at a quantised coordinate is not (WireColorBlitFilter.h). The format check above still
// asks for SAMPLED_IMAGE_FILTER_LINEAR whenever GL said GL_LINEAR, so which blits reach
// this pass is unchanged.
const VkFilter samplerFilter = WireColorBlitFilterFor({sx0, sy0, sx1, sy1}, {dx0, dy0, dx1, dy1},
filter, transform);
const VkDescriptorImageInfo sampled{samplerFilter == VK_FILTER_LINEAR ? cache.linear : cache.nearest,
const VkDescriptorImageInfo sampled{filter == GL_LINEAR ? cache.linear : cache.nearest,
sourceView, sourceLayout};
VkWriteDescriptorSet write{VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET};
write.dstSet = descriptorSet;
@@ -1,66 +0,0 @@
// MobileGL - MobileGL/MG_Backend/DirectVulkan/Renderer/WireColorBlitFilter.h
// Copyright (c) 2025-2026 MobileGL-Dev
// Licensed under the GNU Lesser General Public License v3.0:
// https://www.gnu.org/licenses/gpl-3.0.txt
// https://www.gnu.org/licenses/lgpl-3.0.txt
// SPDX-License-Identifier: LGPL-3.0-only
// End of Source File Header
#pragma once
#include <Includes.h>
#include "../VkIncludes.h"
// P7 g3-blit (g3det, gate 3): WHICH SAMPLER THE WIRE ARM'S SHADER COLOUR BLIT READS ITS SOURCE
// THROUGH.
//
// GL applies a blit's `filter` only where the image is STRETCHED (GL 4.6 core 18.3.1). A blit whose
// source and destination rectangles are the same size is a copy, whatever `filter` says, and so is
// a mirrored one. The wire arm's shader blit (WireColorBlit.inc, BlitWireColorImage) draws a quad
// and samples `textureLod(sourceImage, texCoord, 0)` at interpolated coordinates, and it used the
// LINEAR sampler for every GL_LINEAR blit. At 1:1 every fragment centre maps to a texel centre, so
// in exact arithmetic linear filtering reads the same single texel. Adreno 830 quantises the
// coordinate to sub-texel precision: a fragment that lands a fraction off the centre blends in a
// small weight of a neighbour. minecraft-1.21.1-neoforge-create-instancing-in-world ends with a
// 1:1 GL_LINEAR glBlitFramebuffer into FB 0, and on the wire arm 712 high-contrast pixels moved by
// 1 LSB toward a neighbour. The monolith's vkCmdBlitImage copied them exactly
// (~/w7/logs/g3det/VERDICT.md section 3). NEAREST within half a texel of the centre is exact, so an
// unscaled blit takes NEAREST. Lavapipe samples texel centres exactly, so no host picture can see
// the difference; this pure half is what the unit test pins
// (MG_Test/Pipeline/PipelineQuirkTest.cpp, WireColorBlitSamples*).
//
// THE SURFACE TRANSFORM DOES NOT TURN A COPY INTO A STRETCH. BlitWireColorImage applies the
// quarter and half turns in NDC, over a viewport of the native image, and for a quarter turn it
// takes the logical extent as the native extent swapped. A native pixel then has exactly the pitch
// of a logical one, and the rotation maps pixel centres onto pixel centres. So the scale test is on
// GL's own (logical) rectangles for identity and all three rotations. BlitWireColorImage declines
// any other transform before it chooses a sampler; for one, this answers with the filter's own
// mapping, as before this package.
#if MOBILEGL_BUILD_DISAGGREGATED
namespace MobileGL::MG_Backend::DirectVulkan {
// A glBlitFramebuffer rectangle as GL names it: two corners, either order.
struct WireBlitRect {
GLint x0 = 0, y0 = 0, x1 = 0, y1 = 0;
};
// Same extent on both axes, orientation aside. The extents are taken in 64 bits: GL accepts any
// GLint corner, and INT_MAX - INT_MIN does not fit in one.
inline Bool WireBlitIsUnscaled(const WireBlitRect& source, const WireBlitRect& destination) {
const auto extent = [](GLint a, GLint b) {
return std::abs(static_cast<Int64>(b) - static_cast<Int64>(a));
};
return extent(source.x0, source.x1) == extent(destination.x0, destination.x1) &&
extent(source.y0, source.y1) == extent(destination.y0, destination.y1);
}
inline VkFilter WireColorBlitFilterFor(const WireBlitRect& source, const WireBlitRect& destination,
GLenum filter, VkSurfaceTransformFlagBitsKHR transform) {
if (filter != GL_LINEAR) return VK_FILTER_NEAREST;
const Bool expressed = transform == VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR ||
transform == VK_SURFACE_TRANSFORM_ROTATE_90_BIT_KHR ||
transform == VK_SURFACE_TRANSFORM_ROTATE_180_BIT_KHR ||
transform == VK_SURFACE_TRANSFORM_ROTATE_270_BIT_KHR;
if (expressed && WireBlitIsUnscaled(source, destination)) return VK_FILTER_NEAREST;
return VK_FILTER_LINEAR;
}
} // namespace MobileGL::MG_Backend::DirectVulkan
#endif
@@ -1,11 +1,6 @@
// Generated from WireColorBlit.vert / WireColorBlit.frag (Vulkan 1.0 / SPIR-V 1.0) by
// scripts/bake_internal_shaders.py, which runs MG_Test's BakedInternalShadersTest with the
// IN-TREE glslang and splices the words it emits into the arrays below. Do not edit the words
// by hand: MOBILEGL_BAKED_INTERNAL_SHADERS (the same test, run as a gate) recompiles every
// source in its table and reds on the first word that disagrees.
//
// These words were hand-run through glslangValidator before that gate existed, and the gate
// reproduces them exactly - which is the one thing nobody could have known beforehand.
// Generated from WireColorBlit.vert / WireColorBlit.frag with:
// glslangValidator -V --target-env vulkan1.0 -o <stage>.spv <source>
// Validated with spirv-val --target-env vulkan1.0. Do not edit the words by hand.
#pragma once
static constexpr Uint32 kWireColorBlitVertexSpirv[] = {
@@ -1,172 +0,0 @@
// MobileGL - MobileGL/MG_Backend/DirectVulkan/Renderer/WireDeclineTally.h
// Copyright (c) 2025-2026 MobileGL-Dev
// Licensed under the GNU Lesser General Public License v3.0:
// https://www.gnu.org/licenses/gpl-3.0.txt
// https://www.gnu.org/licenses/lgpl-3.0.txt
// SPDX-License-Identifier: LGPL-3.0-only
// End of Source File Header
#pragma once
#include <Config.h>
#if MOBILEGL_BUILD_DISAGGREGATED
#include <Includes.h>
#include <MG_Util/Debug/Log.h>
#include <atomic>
namespace MobileGL::MG_Backend::DirectVulkan {
// P7 wave 2 package B3: the per-site tally behind CONTRACT-P7 §0 rule I.
//
// Shape is PipeApplier.h's ServerVerbSink tallies, and for the same reason (R-16: a probe may
// not arm against a stub). "The retrace passed" and "the retrace silently dropped nine draws"
// produce the same exit code and the same log, so the lane has to assert the number that only
// this path can move.
//
// Counters are process-wide and monotone. On the spawn arm they live in the SERVER process,
// which is where the draw path runs - a client-side reader would always see zero, so the
// two-process case asserts pixels and reads these from the server's own dump.
enum class WireDeclineSite : Uint32 {
#define MGL_WIRE_DECLINE(name) name,
#include "WireDeclines.def"
#undef MGL_WIRE_DECLINE
Count
};
inline const char* WireDeclineSiteName(WireDeclineSite site) {
switch (site) {
#define MGL_WIRE_DECLINE(name) \
case WireDeclineSite::name: \
return #name;
#include "WireDeclines.def"
#undef MGL_WIRE_DECLINE
case WireDeclineSite::Count:
break;
}
return "Unnamed";
}
class WireDeclineTally {
public:
static constexpr SizeT kSiteCount = static_cast<SizeT>(WireDeclineSite::Count);
static void Count(WireDeclineSite site) {
Slots()[static_cast<SizeT>(site)].fetch_add(1, std::memory_order_relaxed);
Total().fetch_add(1, std::memory_order_relaxed);
}
static Uint64 Get(WireDeclineSite site) {
return Slots()[static_cast<SizeT>(site)].load(std::memory_order_relaxed);
}
static Uint64 TotalDeclines() { return Total().load(std::memory_order_relaxed); }
// The memory half (package M1's thread): a refused upload does not consume its
// PendingUpload entry, so the entry and the level shadow behind it stay alive. These are
// GAUGES, not counters - the last observed live depth, sampled where the refusal happens -
// so a monotone climb across frames is the signature that a refusal is also a leak.
static void SetPendingGauge(Uint64 entries, Uint64 bytes) {
PendingEntries().store(entries, std::memory_order_relaxed);
PendingBytes().store(bytes, std::memory_order_relaxed);
Uint64 peak = PeakPendingBytes().load(std::memory_order_relaxed);
while (bytes > peak && !PeakPendingBytes().compare_exchange_weak(peak, bytes, std::memory_order_relaxed)) {
}
}
// The frame-serial floor's own counter. An "unsound serial complete" is an advance of
// VkBufferManager's completed-frame-serial floor to a serial that ANOTHER submission still
// in flight also carries - i.e. the renderer telling the buffer manager "frame N-1 is done"
// while the submission holding frame N-1's buffer copies is still executing. It is what
// lets a streamed glBufferSubData take the unordered host path and tear one draw's vertex
// range. With a provable floor it is unreachable, so this counter is the red-once's reading:
// non-zero on the wire arms before the fix, zero after, zero on monolith either way.
static void CountUnsoundSerialComplete() {
UnsoundSerial().fetch_add(1, std::memory_order_relaxed);
}
static Uint64 UnsoundSerialCompleteEvents() { return UnsoundSerial().load(std::memory_order_relaxed); }
static Uint64 PendingUploadEntries() { return PendingEntries().load(std::memory_order_relaxed); }
static Uint64 PendingUploadBytes() { return PendingBytes().load(std::memory_order_relaxed); }
static Uint64 PeakPendingUploadBytes() { return PeakPendingBytes().load(std::memory_order_relaxed); }
static void Reset() {
for (SizeT i = 0; i < kSiteCount; ++i) Slots()[i].store(0, std::memory_order_relaxed);
Total().store(0, std::memory_order_relaxed);
UnsoundSerial().store(0, std::memory_order_relaxed);
PendingEntries().store(0, std::memory_order_relaxed);
PendingBytes().store(0, std::memory_order_relaxed);
PeakPendingBytes().store(0, std::memory_order_relaxed);
}
// One line per site that moved, plus the pending gauges. Called at session teardown and
// from the forced-condition harness; silent when nothing declined, so a green lane stays
// quiet and a lane that dropped a draw cannot.
static void Dump(const char* tag) {
// The floor counter prints unconditionally: "zero unsound advances" is the reading the
// red-once needs, and an absent line cannot be told from a lane that never ran.
MGLOG_I("MGWIRE-FLOOR[%s] unsoundSerialComplete=%llu", tag,
static_cast<unsigned long long>(UnsoundSerialCompleteEvents()));
if (TotalDeclines() == 0 && PeakPendingUploadBytes() == 0) return;
MGLOG_I("MGWIRE-DECLINES[%s] total=%llu pendingEntries=%llu pendingBytes=%llu peakPendingBytes=%llu", tag,
static_cast<unsigned long long>(TotalDeclines()),
static_cast<unsigned long long>(PendingUploadEntries()),
static_cast<unsigned long long>(PendingUploadBytes()),
static_cast<unsigned long long>(PeakPendingUploadBytes()));
for (SizeT i = 0; i < kSiteCount; ++i) {
const Uint64 value = Slots()[i].load(std::memory_order_relaxed);
if (!value) continue;
MGLOG_I("MGWIRE-DECLINES[%s] %s=%llu", tag, WireDeclineSiteName(static_cast<WireDeclineSite>(i)),
static_cast<unsigned long long>(value));
}
}
private:
static std::atomic<Uint64>* Slots() {
static std::atomic<Uint64> slots[kSiteCount]{};
return slots;
}
static std::atomic<Uint64>& Total() {
static std::atomic<Uint64> total{0};
return total;
}
static std::atomic<Uint64>& PendingEntries() {
static std::atomic<Uint64> value{0};
return value;
}
static std::atomic<Uint64>& PendingBytes() {
static std::atomic<Uint64> value{0};
return value;
}
static std::atomic<Uint64>& PeakPendingBytes() {
static std::atomic<Uint64> value{0};
return value;
}
static std::atomic<Uint64>& UnsoundSerial() {
static std::atomic<Uint64> value{0};
return value;
}
};
// Every decline goes through this: the tally moves ALWAYS, the log line is once per site.
// `MGL_WIRE_DECLINE_AT(Site, "why", ...); return false;` is the statement pair that replaces
// a bare `return false;` (the few sites that call WireDeclineTally::Count directly stand
// under an MGLOG_W/E of their own; scripts/ci/wire_declines_audit.py holds them to that).
//
// A DECLINE IS NOT ALWAYS A SKIPPED DRAW, so the line does not say "draw". The Tex*, Shape* and
// Upload* rows are counted per texture SYNC: SyncTextureResourceByHandle is reached from the
// draw/dispatch texture preparation, but also from the descriptor resolver, framebuffer
// attachments, CopyTexSubImage, mipmap generation and CopyImageSubData - each of which Fatals
// right after a failed sync - and from texture readback, which falls back to the unbacked
// shadow. A draw that samples three unsyncable textures counts three; a failed attachment
// sync counts once and is then a Fatal, not a skipped draw.
#define MGL_WIRE_DECLINE_AT(site, fmt, ...) \
do { \
::MobileGL::MG_Backend::DirectVulkan::WireDeclineTally::Count( \
::MobileGL::MG_Backend::DirectVulkan::WireDeclineSite::site); \
MGLOG_E_ONCE("Magma wire decline [" #site "]: " fmt, ##__VA_ARGS__); \
} while (0)
} // namespace MobileGL::MG_Backend::DirectVulkan
#endif // MOBILEGL_BUILD_DISAGGREGATED
@@ -1,106 +0,0 @@
// MobileGL - MobileGL/MG_Backend/DirectVulkan/Renderer/WireDeclines.def
// Copyright (c) 2025-2026 MobileGL-Dev
// Licensed under the GNU Lesser General Public License v3.0:
// https://www.gnu.org/licenses/gpl-3.0.txt
// https://www.gnu.org/licenses/lgpl-3.0.txt
// SPDX-License-Identifier: LGPL-3.0-only
// End of Source File Header
// P7 wave 2 package B3. THE NAMES OF EVERY WAY THE MAGMA WIRE ARM CAN DECLINE.
//
// A DECLINE IS NOT ALWAYS A SKIPPED DRAW. The SetupWireDraw / DispatchWireCompute rows are one
// per refused draw or dispatch; the Tex* / Shape* / Upload* rows are counted per texture SYNC,
// which the draw path reaches once per sampled texture and the descriptor resolver, framebuffer
// attachments, CopyTexSubImage, mipmap generation, CopyImageSubData and texture readback reach
// on their own (WireDeclineTally.h, above MGL_WIRE_DECLINE_AT).
//
// CONTRACT-P7 §0 rule I says a refusal on the wire arm is either a named decline or a named
// Fatal. Before B3 the draw path had a third shape the rule does not admit: a bare
// `return false` with no log, no counter and no census entry - roughly twenty of them in
// SetupWireDraw alone, plus the texture-sync chain behind PrepareWireTextureResources. A draw
// that took one of those exits left NO trace anywhere, which is precisely why the OpenRA
// device divergence survived four device windows with client and server logs that were
// LINE-IDENTICAL between a passing and a failing run.
//
// Each row below is one such exit. The name is what the decline logs and what the tally
// counts, so "which exit did this frame take" is answerable from a counter dump instead of
// from a bisect. Rows are append-only: the integration lane asserts specific counters moved.
//
// EVERY ROW HAS A SITE AND EVERY SITE HAS A LINE. A row with no site is a name that can never
// be counted - it reads as "this cannot happen here" when it only means "nobody wired it up" -
// and a site with no line puts the reader back on a bisect. Sites reached through a macro
// (MGL_WIRE_DECLINE_AT) get both at once; the few that use WireDeclineTally::Count directly do
// so ONLY because the statement above them already carries the same reason as an _ONCE log.
// scripts/ci/wire_declines_audit.py holds both halves.
//
// MGL_WIRE_DECLINE(Name)
// ---- SetupWireDraw, in statement order -------------------------------------------------
MGL_WIRE_DECLINE(ProgramLinkOrSpirv)
MGL_WIRE_DECLINE(PointSizeCapability)
MGL_WIRE_DECLINE(TextureResourcesUnprepared)
MGL_WIRE_DECLINE(VertexFormatUnsupported)
MGL_WIRE_DECLINE(VertexAttributeWindow)
MGL_WIRE_DECLINE(VertexStreamCountZero)
MGL_WIRE_DECLINE(VertexStreamRead)
MGL_WIRE_DECLINE(VertexStreamConverter)
MGL_WIRE_DECLINE(VertexTransientUpload)
MGL_WIRE_DECLINE(IndexViewMissing)
MGL_WIRE_DECLINE(IndexTypeWidth)
MGL_WIRE_DECLINE(IndexWindow)
MGL_WIRE_DECLINE(IndexStreamRead)
MGL_WIRE_DECLINE(IndexTransientUpload)
MGL_WIRE_DECLINE(IndexSliceInvalid)
MGL_WIRE_DECLINE(UniformBufferBinding)
MGL_WIRE_DECLINE(NoAttachments)
MGL_WIRE_DECLINE(PipelineUnavailable)
MGL_WIRE_DECLINE(CurrentAttributePayload)
MGL_WIRE_DECLINE(CurrentAttributeUpload)
MGL_WIRE_DECLINE(BeginRenderPass)
// ---- DispatchWireCompute ----------------------------------------------------------------
MGL_WIRE_DECLINE(ComputeProgramLinkOrSpirv)
MGL_WIRE_DECLINE(ComputeTextureResourcesUnprepared)
MGL_WIRE_DECLINE(ComputePipelineUnavailable)
MGL_WIRE_DECLINE(ComputeUniformBufferBinding)
// ---- UniformManager::PrepareWireTextureResources ----------------------------------------
MGL_WIRE_DECLINE(DescriptorDeclined)
MGL_WIRE_DECLINE(SamplerLocationAlias)
MGL_WIRE_DECLINE(SamplerUnitRange)
// ---- VkTextureManager::SyncTextureResourceByHandle --------------------------------------
MGL_WIRE_DECLINE(TexResolveStorage)
MGL_WIRE_DECLINE(TexViewFormat)
MGL_WIRE_DECLINE(TexNoApplierRecord)
MGL_WIRE_DECLINE(TexRecordDeadOrStale)
MGL_WIRE_DECLINE(TexShapeSync)
MGL_WIRE_DECLINE(TexUploadPendingLevels)
MGL_WIRE_DECLINE(TexStorageUsage)
// ---- VkTextureManager::UploadPendingWireLevels ------------------------------------------
// The five `incomplete`/false exits the investigation named, plus the two that leave an
// entry pending WITHOUT failing (a `continue`) - those are the ones that can starve a draw
// of its texels while still reporting success, so they are counted separately.
MGL_WIRE_DECLINE(UploadLevelBeyondChain)
MGL_WIRE_DECLINE(UploadLevelExtentMismatch)
MGL_WIRE_DECLINE(UploadEmptyLevel)
MGL_WIRE_DECLINE(UploadConversion)
MGL_WIRE_DECLINE(UploadTexelArithmetic)
MGL_WIRE_DECLINE(UploadRegionOutOfBounds)
MGL_WIRE_DECLINE(UploadIncomplete)
MGL_WIRE_DECLINE(UploadFlushFailed)
// ---- VkTextureManager::SyncWireTextureShape ---------------------------------------------
MGL_WIRE_DECLINE(ShapeBufferBacked)
MGL_WIRE_DECLINE(ShapeViewOfStorage)
MGL_WIRE_DECLINE(ShapeNoLevels)
MGL_WIRE_DECLINE(ShapeNoVulkanShape)
MGL_WIRE_DECLINE(ShapeNoVkFormat)
MGL_WIRE_DECLINE(ShapeSampleCount)
MGL_WIRE_DECLINE(ShapePreserveFlushFailed)
MGL_WIRE_DECLINE(ShapeImageFlagsUnsupported)
MGL_WIRE_DECLINE(ShapeCreateImageFailed)
// Appended by the B3 review round: the preserve-copy arm of a reallocation was the one exit in
// SyncWireTextureShape still leaving no trace at all.
MGL_WIRE_DECLINE(ShapePreserveCopyFailed)
@@ -1,28 +0,0 @@
#version 450
// The monolith arm's kDepthMipmapFragmentShaderSource (VulkanRenderer.cpp), ported to the
// baked pipeline: the same 2x2 box of texelFetches, the same clamp, the same average, the
// same gl_FragDepth. It is a PORT and not a rewrite on purpose - CONTRACT-P7 §3.2 retires a
// refusal by making the wire arm observably the monolith's, so the two arms have to agree
// texel for texel, including where they read.
//
// uSrcTexelSize arrives on the push constant rather than in a uniform block: the wire arm
// owns no GL program, so there is no default-block uniform to write and no global UBO to
// bind. That is the whole of OQ-13's narrow half for this program.
layout(push_constant) uniform DepthMipmapRect {
vec4 srcRect;
vec4 dstRect;
int surfaceTransform;
ivec2 srcTexelSize;
} rect;
layout(set = 0, binding = 0) uniform sampler2D sourceImage;
layout(location = 0) in vec2 texCoord;
void main() {
ivec2 srcBase = ivec2(texCoord * vec2(rect.srcTexelSize));
ivec2 srcMax = rect.srcTexelSize - ivec2(1);
float depth0 = texelFetch(sourceImage, clamp(srcBase, ivec2(0), srcMax), 0).r;
float depth1 = texelFetch(sourceImage, clamp(srcBase + ivec2(1, 0), ivec2(0), srcMax), 0).r;
float depth2 = texelFetch(sourceImage, clamp(srcBase + ivec2(0, 1), ivec2(0), srcMax), 0).r;
float depth3 = texelFetch(sourceImage, clamp(srcBase + ivec2(1, 1), ivec2(0), srcMax), 0).r;
gl_FragDepth = 0.25 * (depth0 + depth1 + depth2 + depth3);
}
@@ -1,320 +0,0 @@
// Included by VulkanRenderer.cpp inside the backend namespace, after WireColorBlit.inc.
// The native depth mip owns no frontend object and never invokes the GL shader compiler.
//
// WHY THIS FILE EXISTS AT ALL. vkCmdBlitImage is the ordinary way to halve a mip, and for a
// depth format it is often not available: VK_FORMAT_FEATURE_BLIT_DST is optional for depth,
// and the monolith arm has carried a shader fallback for exactly that case since before the
// split (VulkanRenderer.cpp's GenerateDepthMipmapWithShader). The wire arm had no such
// fallback, so every depth mip the device could not blit died as
// `Magma:mipmap-shader-format-or-shape`, and a DEPTH|STENCIL texture died one guard earlier
// as `Magma:depth-stencil-mipmap@P7` whether or not it could be blitted.
//
// The monolith fallback is not reusable here and that is the whole of CONTRACT-P7 §5.1 (A):
// it builds a GL ProgramObject, two GL ShaderObjects and a GL sampler, binds through the
// uniform manager's global UBO, and writes uSrcTexelSize as a default-block uniform - four
// frontend objects and a GL compiler on the server's apply thread. The baked program below is
// the same shader with the same arithmetic, driven by a push constant and its own descriptor
// set, which is what lets the server generate a depth mip while owning nothing of the client.
#if MOBILEGL_BUILD_DISAGGREGATED
#include "WireDepthMipmapSpirv.h"
struct VulkanRenderer::WireDepthMipmapResources {
struct Target {
VkFormat format = VK_FORMAT_UNDEFINED;
VkImageLayout layout = VK_IMAGE_LAYOUT_UNDEFINED;
VkRenderPass renderPass = VK_NULL_HANDLE;
VkPipeline pipeline = VK_NULL_HANDLE;
};
VkShaderModule vertex = VK_NULL_HANDLE, fragment = VK_NULL_HANDLE;
VkDescriptorSetLayout descriptorLayout = VK_NULL_HANDLE;
VkPipelineLayout pipelineLayout = VK_NULL_HANDLE;
VkSampler nearest = VK_NULL_HANDLE;
Vector<Target> targets;
};
void VulkanRenderer::DestroyWireDepthMipmapResources() {
if (!m_wireDepthMipmapResources) return;
// Shutdown calls this after vkDeviceWaitIdle and after all per-submit
// descriptor pools/framebuffers/views have been collected.
auto& cache = *m_wireDepthMipmapResources;
for (const auto& target : cache.targets) {
vkDestroyPipeline(m_device, target.pipeline, nullptr);
vkDestroyRenderPass(m_device, target.renderPass, nullptr);
}
vkDestroySampler(m_device, cache.nearest, nullptr);
vkDestroyPipelineLayout(m_device, cache.pipelineLayout, nullptr);
vkDestroyDescriptorSetLayout(m_device, cache.descriptorLayout, nullptr);
vkDestroyShaderModule(m_device, cache.vertex, nullptr);
vkDestroyShaderModule(m_device, cache.fragment, nullptr);
delete m_wireDepthMipmapResources;
m_wireDepthMipmapResources = nullptr;
}
// ONE LEVEL, source -> destination, both depth subresources of the same image. The shape
// mirrors BlitWireColorImage deliberately: the same lazily built module pair, the same
// per-format render pass/pipeline cache, the same per-submit descriptor pool, and the
// same GENERAL-on-both-sides layout rule for a same-image pass, so the two native passes
// cannot disagree about how an image is handed between them.
Bool VulkanRenderer::GenerateWireDepthMipLevel(WireImage source, WireImage destination) {
const Bool sameImage = source.image == destination.image;
if (!source.image || !destination.image) return false;
if (sameImage && source.level == destination.level && source.layer == destination.layer)
return false;
if (source.isDefault || destination.isDefault) return false;
if (source.samples != VK_SAMPLE_COUNT_1_BIT || destination.samples != VK_SAMPLE_COUNT_1_BIT)
return false;
if (source.is3D || destination.is3D) return false;
if (source.format != destination.format) return false;
// DEPTH ONLY. A combined depth/stencil image can be sampled for its depth and
// rendered as a depth attachment, but this pass writes gl_FragDepth and NOTHING
// else - the stencil aspect would come out of the render pass undefined, which is
// not what GL's glGenerateMipmap promises for the level it just produced. The
// caller declines that shape rather than producing half a level.
if (source.aspect != VK_IMAGE_ASPECT_DEPTH_BIT ||
destination.aspect != VK_IMAGE_ASPECT_DEPTH_BIT) return false;
if (!source.extent.width || !source.extent.height ||
!destination.extent.width || !destination.extent.height) return false;
VkFormatProperties properties{};
vkGetPhysicalDeviceFormatProperties(m_physicalDevice.handle, source.format, &properties);
const VkFormatFeatureFlags required = VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT |
VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT;
if ((properties.optimalTilingFeatures & required) != required) return false;
// The baked block's layout, and the offsets are not a guess: the generated header
// decorates its members at 0 / 16 / 32 / 40, which is where a vec4, a vec4, an int
// and an 8-byte-aligned ivec2 land. The pad is what makes the C++ agree.
struct Constants {
float srcRect[4];
float dstRect[4];
Int32 surfaceTransform;
Int32 reservedForIvec2Alignment;
Int32 srcTexelSize[2];
};
static_assert(sizeof(Constants) == 48);
static_assert(offsetof(Constants, srcTexelSize) == 40);
if (!m_wireDepthMipmapResources) {
m_wireDepthMipmapResources = new WireDepthMipmapResources;
auto& cache = *m_wireDepthMipmapResources;
const auto shader = [&](const Uint32* code, SizeT bytes, VkShaderModule& module) {
VkShaderModuleCreateInfo info{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO};
info.codeSize = bytes;
info.pCode = code;
VK_VERIFY(vkCreateShaderModule(m_device, &info, nullptr, &module));
};
shader(kWireDepthMipmapVertexSpirv, sizeof(kWireDepthMipmapVertexSpirv), cache.vertex);
shader(kWireDepthMipmapFragmentSpirv, sizeof(kWireDepthMipmapFragmentSpirv), cache.fragment);
const VkDescriptorSetLayoutBinding binding{0, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
1, VK_SHADER_STAGE_FRAGMENT_BIT, nullptr};
VkDescriptorSetLayoutCreateInfo layout{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO};
layout.bindingCount = 1;
layout.pBindings = &binding;
VK_VERIFY(vkCreateDescriptorSetLayout(m_device, &layout, nullptr, &cache.descriptorLayout));
// BOTH STAGES ON ONE RANGE: the block is declared identically in the vertex and
// fragment sources (a push-constant block must be), the vertex stage reads the
// rects and the fragment stage reads srcTexelSize.
const VkPushConstantRange push{VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT,
0, sizeof(Constants)};
VkPipelineLayoutCreateInfo pipelineLayout{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO};
pipelineLayout.setLayoutCount = 1;
pipelineLayout.pSetLayouts = &cache.descriptorLayout;
pipelineLayout.pushConstantRangeCount = 1;
pipelineLayout.pPushConstantRanges = &push;
VK_VERIFY(vkCreatePipelineLayout(m_device, &pipelineLayout, nullptr, &cache.pipelineLayout));
// NEAREST, and it is not a default: the fragment shader does its own 2x2 box with
// texelFetch, so any filtering the sampler added would be applied twice. It also
// keeps the sampler legal on a device that does not advertise linear filtering for
// depth formats, which is most of them.
VkSamplerCreateInfo sampler{VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO};
sampler.mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST;
sampler.addressModeU = sampler.addressModeV = sampler.addressModeW =
VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE;
sampler.magFilter = sampler.minFilter = VK_FILTER_NEAREST;
sampler.maxLod = 0.0f;
VK_VERIFY(vkCreateSampler(m_device, &sampler, nullptr, &cache.nearest));
}
auto& cache = *m_wireDepthMipmapResources;
const VkImageLayout sourceLayout = sameImage ? VK_IMAGE_LAYOUT_GENERAL
: VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
const VkImageLayout destinationLayout = sameImage ? VK_IMAGE_LAYOUT_GENERAL
: VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
WireDepthMipmapResources::Target* target = nullptr;
for (auto& entry : cache.targets) {
if (entry.format == destination.format && entry.layout == destinationLayout) {
target = &entry;
break;
}
}
if (!target) {
cache.targets.emplace_back();
target = &cache.targets.back();
target->format = destination.format;
target->layout = destinationLayout;
VkAttachmentDescription attachment{};
attachment.format = destination.format;
attachment.samples = VK_SAMPLE_COUNT_1_BIT;
// DONT_CARE, not LOAD: the pass writes gl_FragDepth at every texel of the level
// it is producing, so there is nothing in the destination worth loading, and a
// level that has just been grown has no defined contents to load anyway.
attachment.loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
attachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
attachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
attachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
attachment.initialLayout = attachment.finalLayout = destinationLayout;
const VkAttachmentReference depth{0, destinationLayout};
VkSubpassDescription subpass{};
subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
subpass.pDepthStencilAttachment = &depth;
VkRenderPassCreateInfo pass{VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO};
pass.attachmentCount = 1;
pass.pAttachments = &attachment;
pass.subpassCount = 1;
pass.pSubpasses = &subpass;
VK_VERIFY(vkCreateRenderPass(m_device, &pass, nullptr, &target->renderPass));
VkPipelineShaderStageCreateInfo stages[2]{};
for (auto& stage : stages) {
stage.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
stage.pName = "main";
}
stages[0].stage = VK_SHADER_STAGE_VERTEX_BIT;
stages[0].module = cache.vertex;
stages[1].stage = VK_SHADER_STAGE_FRAGMENT_BIT;
stages[1].module = cache.fragment;
const VkPipelineVertexInputStateCreateInfo vertex{VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO};
VkPipelineInputAssemblyStateCreateInfo assembly{VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO};
assembly.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
VkPipelineViewportStateCreateInfo viewport{VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO};
viewport.viewportCount = viewport.scissorCount = 1;
VkPipelineRasterizationStateCreateInfo raster{VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO};
raster.polygonMode = VK_POLYGON_MODE_FILL;
raster.cullMode = VK_CULL_MODE_NONE;
raster.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE;
raster.lineWidth = 1.0f;
VkPipelineMultisampleStateCreateInfo samples{VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO};
samples.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT;
// ALWAYS + write enabled: the fragment shader's gl_FragDepth is the answer, and a
// comparison against whatever DONT_CARE left behind would discard some of it.
VkPipelineDepthStencilStateCreateInfo depthStencil{VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO};
depthStencil.depthTestEnable = VK_TRUE;
depthStencil.depthWriteEnable = VK_TRUE;
depthStencil.depthCompareOp = VK_COMPARE_OP_ALWAYS;
depthStencil.minDepthBounds = 0.0f;
depthStencil.maxDepthBounds = 1.0f;
// No colour attachment in this render pass, so no attachment states either.
VkPipelineColorBlendStateCreateInfo blend{VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO};
const VkDynamicState dynamicStates[]{VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR};
VkPipelineDynamicStateCreateInfo dynamic{VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO};
dynamic.dynamicStateCount = 2;
dynamic.pDynamicStates = dynamicStates;
VkGraphicsPipelineCreateInfo pipeline{VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO};
pipeline.stageCount = 2;
pipeline.pStages = stages;
pipeline.pVertexInputState = &vertex;
pipeline.pInputAssemblyState = &assembly;
pipeline.pViewportState = &viewport;
pipeline.pRasterizationState = &raster;
pipeline.pMultisampleState = &samples;
pipeline.pDepthStencilState = &depthStencil;
pipeline.pColorBlendState = &blend;
pipeline.pDynamicState = &dynamic;
pipeline.layout = cache.pipelineLayout;
pipeline.renderPass = target->renderPass;
VK_VERIFY(vkCreateGraphicsPipelines(m_device, VK_NULL_HANDLE, 1, &pipeline, nullptr, &target->pipeline));
}
m_textureManager->FlushPendingUploads();
// Distinct mip views of the same image are legal shader input and output at once.
// GENERAL keeps the whole-image layout tracker truthful; the transition also orders
// the previous level's attachment write against this level's sample of it.
TransitionWireImage(source, sourceLayout);
if (sameImage) destination.layout = source.layout;
else TransitionWireImage(destination, destinationLayout);
const auto makeView = [&](const WireImage& image) {
VkImageViewCreateInfo view{VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO};
view.image = image.image;
view.viewType = VK_IMAGE_VIEW_TYPE_2D;
view.format = image.format;
view.subresourceRange = {VK_IMAGE_ASPECT_DEPTH_BIT, image.level, 1, image.layer, 1};
VkImageView handle = VK_NULL_HANDLE;
VK_VERIFY(vkCreateImageView(m_device, &view, nullptr, &handle));
return handle;
};
const VkImageView sourceView = makeView(source), destinationView = makeView(destination);
VkFramebufferCreateInfo framebufferInfo{VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO};
framebufferInfo.renderPass = target->renderPass;
framebufferInfo.attachmentCount = 1;
framebufferInfo.pAttachments = &destinationView;
framebufferInfo.width = destination.extent.width;
framebufferInfo.height = destination.extent.height;
framebufferInfo.layers = 1;
VkFramebuffer framebuffer = VK_NULL_HANDLE;
VK_VERIFY(vkCreateFramebuffer(m_device, &framebufferInfo, nullptr, &framebuffer));
// Each in-flight pass owns its descriptor set, for the colour blit's reason: updating
// a cached set would rewrite the source view of an older queued pass.
VkDescriptorPool descriptorPool = VK_NULL_HANDLE;
VkDescriptorSet descriptorSet = VK_NULL_HANDLE;
const VkDescriptorPoolSize poolSize{VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1};
VkDescriptorPoolCreateInfo pool{VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO};
pool.maxSets = 1;
pool.poolSizeCount = 1;
pool.pPoolSizes = &poolSize;
VK_VERIFY(vkCreateDescriptorPool(m_device, &pool, nullptr, &descriptorPool));
VkDescriptorSetAllocateInfo alloc{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO};
alloc.descriptorPool = descriptorPool;
alloc.descriptorSetCount = 1;
alloc.pSetLayouts = &cache.descriptorLayout;
VK_VERIFY(vkAllocateDescriptorSets(m_device, &alloc, &descriptorSet));
const VkDescriptorImageInfo sampled{cache.nearest, sourceView, sourceLayout};
VkWriteDescriptorSet write{VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET};
write.dstSet = descriptorSet;
write.dstBinding = 0;
write.descriptorCount = 1;
write.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
write.pImageInfo = &sampled;
vkUpdateDescriptorSets(m_device, 1, &write, 0, nullptr);
// The destination rectangle is flipped exactly as BlitWireColorImage flips it for an
// offscreen target, because it shares that file's vertex shader and therefore its
// window-Y flip. With the flip undone, destination row r samples texCoord.y
// (r + 0.5) / dstHeight, and the fragment's ivec2(texCoord * srcTexelSize) lands on
// the same source texels the monolith arm's fullscreen triangle lands on - which is
// the point: §3.2 retires a refusal by making the wire arm observably the monolith's,
// half-texel offset included.
const Constants constants{
{0.0f, 0.0f, 1.0f, 1.0f},
{0.0f, 1.0f, 1.0f, -1.0f},
0, 0,
{static_cast<Int32>(source.extent.width), static_cast<Int32>(source.extent.height)}};
auto& frame = m_frameContext.GetCurrent();
VkRenderPassBeginInfo begin{VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO};
begin.renderPass = target->renderPass;
begin.framebuffer = framebuffer;
begin.renderArea = {{0, 0}, destination.extent};
vkCmdBeginRenderPass(frame.commandBuffer, &begin, VK_SUBPASS_CONTENTS_INLINE);
vkCmdBindPipeline(frame.commandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, target->pipeline);
const VkViewport viewport{0.0f, 0.0f, static_cast<float>(destination.extent.width),
static_cast<float>(destination.extent.height), 0.0f, 1.0f};
const VkRect2D scissor{{0, 0}, destination.extent};
vkCmdSetViewport(frame.commandBuffer, 0, 1, &viewport);
vkCmdSetScissor(frame.commandBuffer, 0, 1, &scissor);
vkCmdBindDescriptorSets(frame.commandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS,
cache.pipelineLayout, 0, 1, &descriptorSet, 0, nullptr);
vkCmdPushConstants(frame.commandBuffer, cache.pipelineLayout,
VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT,
0, sizeof(constants), &constants);
vkCmdDraw(frame.commandBuffer, 6, 1, 0, 0);
vkCmdEndRenderPass(frame.commandBuffer);
ResetDynamicStateShadow();
InvalidatePipelineMemo();
// This native pass binds its own set/layout without going through the application's
// descriptor binder. Its next fast path must rebind.
if (m_uniformManager) m_uniformManager->OnCommandBufferBoundary();
WireRetiredObjects retired{};
retired.framebuffers.push_back(framebuffer);
retired.imageViews = {sourceView, destinationView};
retired.descriptorPools.push_back(descriptorPool);
RetireWireObjects(Move(retired));
return true;
}
#endif
@@ -1,33 +0,0 @@
#version 450
// Native Vulkan depth mip generation: no GL program, registry entry, or runtime transpilation.
//
// The geometry is WireColorBlit.vert's, unchanged - the same quad, the same push-constant
// rect, the same GL-bottom-left to native-image mapping - so a depth mip and a colour blit
// place their fragments identically and only the fragment stage differs. The block carries
// one member more than the colour blit's, and the fragment stage is the member's only
// reader: a push-constant block must be declared identically in every stage of one pipeline,
// so it is declared here too rather than split into a second range.
layout(push_constant) uniform DepthMipmapRect {
vec4 srcRect;
vec4 dstRect;
int surfaceTransform;
ivec2 srcTexelSize;
} rect;
layout(location = 0) out vec2 texCoord;
void main() {
// A quad, rather than an oversized triangle, also clips partial blits to
// their destination rectangle. The Vulkan viewport covers the native image.
const vec2 corners[6] = vec2[](
vec2(0.0, 0.0), vec2(1.0, 0.0), vec2(0.0, 1.0),
vec2(0.0, 1.0), vec2(1.0, 0.0), vec2(1.0, 1.0));
vec2 uv = corners[gl_VertexIndex];
vec2 p = (rect.dstRect.xy + uv * rect.dstRect.zw) * 2.0 - 1.0;
// Same GL-bottom-left to native-image mapping as the monolithic blit.
p.y = -p.y;
if (rect.surfaceTransform == 1) p = vec2(-p.y, p.x);
else if (rect.surfaceTransform == 2) p = -p;
else if (rect.surfaceTransform == 3) p = vec2(p.y, -p.x);
gl_Position = vec4(p, 0.0, 1.0);
texCoord = rect.srcRect.xy + uv * rect.srcRect.zw;
}
@@ -1,174 +0,0 @@
// Generated from WireDepthMipmap.vert / WireDepthMipmap.frag by
// scripts/bake_internal_shaders.py, which runs MG_Test's BakedInternalShadersTest with the
// IN-TREE glslang and splices the words it emits into the arrays below. Do not edit the
// words by hand: MOBILEGL_BAKED_INTERNAL_SHADERS (the same test, run as a gate) recompiles
// every source in its table and reds on the first word that disagrees.
#pragma once
static constexpr Uint32 kWireDepthMipmapVertexSpirv[] = {
0x07230203u, 0x00010000u, 0x0008000bu, 0x00000071u, 0x00000000u, 0x00020011u, 0x00000001u, 0x0006000bu,
0x00000001u, 0x4c534c47u, 0x6474732eu, 0x3035342eu, 0x00000000u, 0x0003000eu, 0x00000000u, 0x00000001u,
0x0008000fu, 0x00000000u, 0x00000004u, 0x6e69616du, 0x00000000u, 0x00000016u, 0x0000005eu, 0x00000067u,
0x00030003u, 0x00000002u, 0x000001c2u, 0x00040005u, 0x00000004u, 0x6e69616du, 0x00000000u, 0x00030005u,
0x00000009u, 0x00007675u, 0x00060005u, 0x00000016u, 0x565f6c67u, 0x65747265u, 0x646e4978u, 0x00007865u,
0x00050005u, 0x00000019u, 0x65646e69u, 0x6c626178u, 0x00000065u, 0x00030005u, 0x0000001cu, 0x00000070u,
0x00060005u, 0x0000001fu, 0x74706544u, 0x70694d68u, 0x5270616du, 0x00746365u, 0x00050006u, 0x0000001fu,
0x00000000u, 0x52637273u, 0x00746365u, 0x00050006u, 0x0000001fu, 0x00000001u, 0x52747364u, 0x00746365u,
0x00080006u, 0x0000001fu, 0x00000002u, 0x66727573u, 0x54656361u, 0x736e6172u, 0x6d726f66u, 0x00000000u,
0x00070006u, 0x0000001fu, 0x00000003u, 0x54637273u, 0x6c657865u, 0x657a6953u, 0x00000000u, 0x00040005u,
0x00000021u, 0x74636572u, 0x00000000u, 0x00060005u, 0x0000005cu, 0x505f6c67u, 0x65567265u, 0x78657472u,
0x00000000u, 0x00060006u, 0x0000005cu, 0x00000000u, 0x505f6c67u, 0x7469736fu, 0x006e6f69u, 0x00070006u,
0x0000005cu, 0x00000001u, 0x505f6c67u, 0x746e696fu, 0x657a6953u, 0x00000000u, 0x00070006u, 0x0000005cu,
0x00000002u, 0x435f6c67u, 0x4470696cu, 0x61747369u, 0x0065636eu, 0x00070006u, 0x0000005cu, 0x00000003u,
0x435f6c67u, 0x446c6c75u, 0x61747369u, 0x0065636eu, 0x00030005u, 0x0000005eu, 0x00000000u, 0x00050005u,
0x00000067u, 0x43786574u, 0x64726f6fu, 0x00000000u, 0x00040047u, 0x00000016u, 0x0000000bu, 0x0000002au,
0x00030047u, 0x0000001fu, 0x00000002u, 0x00050048u, 0x0000001fu, 0x00000000u, 0x00000023u, 0x00000000u,
0x00050048u, 0x0000001fu, 0x00000001u, 0x00000023u, 0x00000010u, 0x00050048u, 0x0000001fu, 0x00000002u,
0x00000023u, 0x00000020u, 0x00050048u, 0x0000001fu, 0x00000003u, 0x00000023u, 0x00000028u, 0x00030047u,
0x0000005cu, 0x00000002u, 0x00050048u, 0x0000005cu, 0x00000000u, 0x0000000bu, 0x00000000u, 0x00050048u,
0x0000005cu, 0x00000001u, 0x0000000bu, 0x00000001u, 0x00050048u, 0x0000005cu, 0x00000002u, 0x0000000bu,
0x00000003u, 0x00050048u, 0x0000005cu, 0x00000003u, 0x0000000bu, 0x00000004u, 0x00040047u, 0x00000067u,
0x0000001eu, 0x00000000u, 0x00020013u, 0x00000002u, 0x00030021u, 0x00000003u, 0x00000002u, 0x00030016u,
0x00000006u, 0x00000020u, 0x00040017u, 0x00000007u, 0x00000006u, 0x00000002u, 0x00040020u, 0x00000008u,
0x00000007u, 0x00000007u, 0x00040015u, 0x0000000au, 0x00000020u, 0x00000000u, 0x0004002bu, 0x0000000au,
0x0000000bu, 0x00000006u, 0x0004001cu, 0x0000000cu, 0x00000007u, 0x0000000bu, 0x0004002bu, 0x00000006u,
0x0000000du, 0x00000000u, 0x0005002cu, 0x00000007u, 0x0000000eu, 0x0000000du, 0x0000000du, 0x0004002bu,
0x00000006u, 0x0000000fu, 0x3f800000u, 0x0005002cu, 0x00000007u, 0x00000010u, 0x0000000fu, 0x0000000du,
0x0005002cu, 0x00000007u, 0x00000011u, 0x0000000du, 0x0000000fu, 0x0005002cu, 0x00000007u, 0x00000012u,
0x0000000fu, 0x0000000fu, 0x0009002cu, 0x0000000cu, 0x00000013u, 0x0000000eu, 0x00000010u, 0x00000011u,
0x00000011u, 0x00000010u, 0x00000012u, 0x00040015u, 0x00000014u, 0x00000020u, 0x00000001u, 0x00040020u,
0x00000015u, 0x00000001u, 0x00000014u, 0x0004003bu, 0x00000015u, 0x00000016u, 0x00000001u, 0x00040020u,
0x00000018u, 0x00000007u, 0x0000000cu, 0x00040017u, 0x0000001du, 0x00000006u, 0x00000004u, 0x00040017u,
0x0000001eu, 0x00000014u, 0x00000002u, 0x0006001eu, 0x0000001fu, 0x0000001du, 0x0000001du, 0x00000014u,
0x0000001eu, 0x00040020u, 0x00000020u, 0x00000009u, 0x0000001fu, 0x0004003bu, 0x00000020u, 0x00000021u,
0x00000009u, 0x0004002bu, 0x00000014u, 0x00000022u, 0x00000001u, 0x00040020u, 0x00000023u, 0x00000009u,
0x0000001du, 0x0004002bu, 0x00000006u, 0x0000002du, 0x40000000u, 0x0004002bu, 0x0000000au, 0x00000031u,
0x00000001u, 0x00040020u, 0x00000032u, 0x00000007u, 0x00000006u, 0x0004002bu, 0x00000014u, 0x00000037u,
0x00000002u, 0x00040020u, 0x00000038u, 0x00000009u, 0x00000014u, 0x00020014u, 0x0000003bu, 0x0004002bu,
0x0000000au, 0x00000042u, 0x00000000u, 0x0004002bu, 0x00000014u, 0x00000051u, 0x00000003u, 0x0004001cu,
0x0000005bu, 0x00000006u, 0x00000031u, 0x0006001eu, 0x0000005cu, 0x0000001du, 0x00000006u, 0x0000005bu,
0x0000005bu, 0x00040020u, 0x0000005du, 0x00000003u, 0x0000005cu, 0x0004003bu, 0x0000005du, 0x0000005eu,
0x00000003u, 0x0004002bu, 0x00000014u, 0x0000005fu, 0x00000000u, 0x00040020u, 0x00000064u, 0x00000003u,
0x0000001du, 0x00040020u, 0x00000066u, 0x00000003u, 0x00000007u, 0x0004003bu, 0x00000066u, 0x00000067u,
0x00000003u, 0x00050036u, 0x00000002u, 0x00000004u, 0x00000000u, 0x00000003u, 0x000200f8u, 0x00000005u,
0x0004003bu, 0x00000008u, 0x00000009u, 0x00000007u, 0x0004003bu, 0x00000018u, 0x00000019u, 0x00000007u,
0x0004003bu, 0x00000008u, 0x0000001cu, 0x00000007u, 0x0004003du, 0x00000014u, 0x00000017u, 0x00000016u,
0x0003003eu, 0x00000019u, 0x00000013u, 0x00050041u, 0x00000008u, 0x0000001au, 0x00000019u, 0x00000017u,
0x0004003du, 0x00000007u, 0x0000001bu, 0x0000001au, 0x0003003eu, 0x00000009u, 0x0000001bu, 0x00050041u,
0x00000023u, 0x00000024u, 0x00000021u, 0x00000022u, 0x0004003du, 0x0000001du, 0x00000025u, 0x00000024u,
0x0007004fu, 0x00000007u, 0x00000026u, 0x00000025u, 0x00000025u, 0x00000000u, 0x00000001u, 0x0004003du,
0x00000007u, 0x00000027u, 0x00000009u, 0x00050041u, 0x00000023u, 0x00000028u, 0x00000021u, 0x00000022u,
0x0004003du, 0x0000001du, 0x00000029u, 0x00000028u, 0x0007004fu, 0x00000007u, 0x0000002au, 0x00000029u,
0x00000029u, 0x00000002u, 0x00000003u, 0x00050085u, 0x00000007u, 0x0000002bu, 0x00000027u, 0x0000002au,
0x00050081u, 0x00000007u, 0x0000002cu, 0x00000026u, 0x0000002bu, 0x0005008eu, 0x00000007u, 0x0000002eu,
0x0000002cu, 0x0000002du, 0x00050050u, 0x00000007u, 0x0000002fu, 0x0000000fu, 0x0000000fu, 0x00050083u,
0x00000007u, 0x00000030u, 0x0000002eu, 0x0000002fu, 0x0003003eu, 0x0000001cu, 0x00000030u, 0x00050041u,
0x00000032u, 0x00000033u, 0x0000001cu, 0x00000031u, 0x0004003du, 0x00000006u, 0x00000034u, 0x00000033u,
0x0004007fu, 0x00000006u, 0x00000035u, 0x00000034u, 0x00050041u, 0x00000032u, 0x00000036u, 0x0000001cu,
0x00000031u, 0x0003003eu, 0x00000036u, 0x00000035u, 0x00050041u, 0x00000038u, 0x00000039u, 0x00000021u,
0x00000037u, 0x0004003du, 0x00000014u, 0x0000003au, 0x00000039u, 0x000500aau, 0x0000003bu, 0x0000003cu,
0x0000003au, 0x00000022u, 0x000300f7u, 0x0000003eu, 0x00000000u, 0x000400fau, 0x0000003cu, 0x0000003du,
0x00000046u, 0x000200f8u, 0x0000003du, 0x00050041u, 0x00000032u, 0x0000003fu, 0x0000001cu, 0x00000031u,
0x0004003du, 0x00000006u, 0x00000040u, 0x0000003fu, 0x0004007fu, 0x00000006u, 0x00000041u, 0x00000040u,
0x00050041u, 0x00000032u, 0x00000043u, 0x0000001cu, 0x00000042u, 0x0004003du, 0x00000006u, 0x00000044u,
0x00000043u, 0x00050050u, 0x00000007u, 0x00000045u, 0x00000041u, 0x00000044u, 0x0003003eu, 0x0000001cu,
0x00000045u, 0x000200f9u, 0x0000003eu, 0x000200f8u, 0x00000046u, 0x00050041u, 0x00000038u, 0x00000047u,
0x00000021u, 0x00000037u, 0x0004003du, 0x00000014u, 0x00000048u, 0x00000047u, 0x000500aau, 0x0000003bu,
0x00000049u, 0x00000048u, 0x00000037u, 0x000300f7u, 0x0000004bu, 0x00000000u, 0x000400fau, 0x00000049u,
0x0000004au, 0x0000004eu, 0x000200f8u, 0x0000004au, 0x0004003du, 0x00000007u, 0x0000004cu, 0x0000001cu,
0x0004007fu, 0x00000007u, 0x0000004du, 0x0000004cu, 0x0003003eu, 0x0000001cu, 0x0000004du, 0x000200f9u,
0x0000004bu, 0x000200f8u, 0x0000004eu, 0x00050041u, 0x00000038u, 0x0000004fu, 0x00000021u, 0x00000037u,
0x0004003du, 0x00000014u, 0x00000050u, 0x0000004fu, 0x000500aau, 0x0000003bu, 0x00000052u, 0x00000050u,
0x00000051u, 0x000300f7u, 0x00000054u, 0x00000000u, 0x000400fau, 0x00000052u, 0x00000053u, 0x00000054u,
0x000200f8u, 0x00000053u, 0x00050041u, 0x00000032u, 0x00000055u, 0x0000001cu, 0x00000031u, 0x0004003du,
0x00000006u, 0x00000056u, 0x00000055u, 0x00050041u, 0x00000032u, 0x00000057u, 0x0000001cu, 0x00000042u,
0x0004003du, 0x00000006u, 0x00000058u, 0x00000057u, 0x0004007fu, 0x00000006u, 0x00000059u, 0x00000058u,
0x00050050u, 0x00000007u, 0x0000005au, 0x00000056u, 0x00000059u, 0x0003003eu, 0x0000001cu, 0x0000005au,
0x000200f9u, 0x00000054u, 0x000200f8u, 0x00000054u, 0x000200f9u, 0x0000004bu, 0x000200f8u, 0x0000004bu,
0x000200f9u, 0x0000003eu, 0x000200f8u, 0x0000003eu, 0x0004003du, 0x00000007u, 0x00000060u, 0x0000001cu,
0x00050051u, 0x00000006u, 0x00000061u, 0x00000060u, 0x00000000u, 0x00050051u, 0x00000006u, 0x00000062u,
0x00000060u, 0x00000001u, 0x00070050u, 0x0000001du, 0x00000063u, 0x00000061u, 0x00000062u, 0x0000000du,
0x0000000fu, 0x00050041u, 0x00000064u, 0x00000065u, 0x0000005eu, 0x0000005fu, 0x0003003eu, 0x00000065u,
0x00000063u, 0x00050041u, 0x00000023u, 0x00000068u, 0x00000021u, 0x0000005fu, 0x0004003du, 0x0000001du,
0x00000069u, 0x00000068u, 0x0007004fu, 0x00000007u, 0x0000006au, 0x00000069u, 0x00000069u, 0x00000000u,
0x00000001u, 0x0004003du, 0x00000007u, 0x0000006bu, 0x00000009u, 0x00050041u, 0x00000023u, 0x0000006cu,
0x00000021u, 0x0000005fu, 0x0004003du, 0x0000001du, 0x0000006du, 0x0000006cu, 0x0007004fu, 0x00000007u,
0x0000006eu, 0x0000006du, 0x0000006du, 0x00000002u, 0x00000003u, 0x00050085u, 0x00000007u, 0x0000006fu,
0x0000006bu, 0x0000006eu, 0x00050081u, 0x00000007u, 0x00000070u, 0x0000006au, 0x0000006fu, 0x0003003eu,
0x00000067u, 0x00000070u, 0x000100fdu, 0x00010038u,
};
static constexpr Uint32 kWireDepthMipmapFragmentSpirv[] = {
0x07230203u, 0x00010000u, 0x0008000bu, 0x00000059u, 0x00000000u, 0x00020011u, 0x00000001u, 0x0006000bu,
0x00000001u, 0x4c534c47u, 0x6474732eu, 0x3035342eu, 0x00000000u, 0x0003000eu, 0x00000000u, 0x00000001u,
0x0007000fu, 0x00000004u, 0x00000004u, 0x6e69616du, 0x00000000u, 0x0000000du, 0x0000004fu, 0x00030010u,
0x00000004u, 0x00000007u, 0x00030010u, 0x00000004u, 0x0000000cu, 0x00030003u, 0x00000002u, 0x000001c2u,
0x00040005u, 0x00000004u, 0x6e69616du, 0x00000000u, 0x00040005u, 0x00000009u, 0x42637273u, 0x00657361u,
0x00050005u, 0x0000000du, 0x43786574u, 0x64726f6fu, 0x00000000u, 0x00060005u, 0x00000010u, 0x74706544u,
0x70694d68u, 0x5270616du, 0x00746365u, 0x00050006u, 0x00000010u, 0x00000000u, 0x52637273u, 0x00746365u,
0x00050006u, 0x00000010u, 0x00000001u, 0x52747364u, 0x00746365u, 0x00080006u, 0x00000010u, 0x00000002u,
0x66727573u, 0x54656361u, 0x736e6172u, 0x6d726f66u, 0x00000000u, 0x00070006u, 0x00000010u, 0x00000003u,
0x54637273u, 0x6c657865u, 0x657a6953u, 0x00000000u, 0x00040005u, 0x00000012u, 0x74636572u, 0x00000000u,
0x00040005u, 0x0000001au, 0x4d637273u, 0x00007861u, 0x00040005u, 0x00000021u, 0x74706564u, 0x00003068u,
0x00050005u, 0x00000025u, 0x72756f73u, 0x6d496563u, 0x00656761u, 0x00040005u, 0x00000031u, 0x74706564u,
0x00003168u, 0x00040005u, 0x0000003bu, 0x74706564u, 0x00003268u, 0x00040005u, 0x00000045u, 0x74706564u,
0x00003368u, 0x00060005u, 0x0000004fu, 0x465f6c67u, 0x44676172u, 0x68747065u, 0x00000000u, 0x00040047u,
0x0000000du, 0x0000001eu, 0x00000000u, 0x00030047u, 0x00000010u, 0x00000002u, 0x00050048u, 0x00000010u,
0x00000000u, 0x00000023u, 0x00000000u, 0x00050048u, 0x00000010u, 0x00000001u, 0x00000023u, 0x00000010u,
0x00050048u, 0x00000010u, 0x00000002u, 0x00000023u, 0x00000020u, 0x00050048u, 0x00000010u, 0x00000003u,
0x00000023u, 0x00000028u, 0x00040047u, 0x00000025u, 0x00000021u, 0x00000000u, 0x00040047u, 0x00000025u,
0x00000022u, 0x00000000u, 0x00040047u, 0x0000004fu, 0x0000000bu, 0x00000016u, 0x00020013u, 0x00000002u,
0x00030021u, 0x00000003u, 0x00000002u, 0x00040015u, 0x00000006u, 0x00000020u, 0x00000001u, 0x00040017u,
0x00000007u, 0x00000006u, 0x00000002u, 0x00040020u, 0x00000008u, 0x00000007u, 0x00000007u, 0x00030016u,
0x0000000au, 0x00000020u, 0x00040017u, 0x0000000bu, 0x0000000au, 0x00000002u, 0x00040020u, 0x0000000cu,
0x00000001u, 0x0000000bu, 0x0004003bu, 0x0000000cu, 0x0000000du, 0x00000001u, 0x00040017u, 0x0000000fu,
0x0000000au, 0x00000004u, 0x0006001eu, 0x00000010u, 0x0000000fu, 0x0000000fu, 0x00000006u, 0x00000007u,
0x00040020u, 0x00000011u, 0x00000009u, 0x00000010u, 0x0004003bu, 0x00000011u, 0x00000012u, 0x00000009u,
0x0004002bu, 0x00000006u, 0x00000013u, 0x00000003u, 0x00040020u, 0x00000014u, 0x00000009u, 0x00000007u,
0x0004002bu, 0x00000006u, 0x0000001du, 0x00000001u, 0x0005002cu, 0x00000007u, 0x0000001eu, 0x0000001du,
0x0000001du, 0x00040020u, 0x00000020u, 0x00000007u, 0x0000000au, 0x00090019u, 0x00000022u, 0x0000000au,
0x00000001u, 0x00000000u, 0x00000000u, 0x00000000u, 0x00000001u, 0x00000000u, 0x0003001bu, 0x00000023u,
0x00000022u, 0x00040020u, 0x00000024u, 0x00000000u, 0x00000023u, 0x0004003bu, 0x00000024u, 0x00000025u,
0x00000000u, 0x0004002bu, 0x00000006u, 0x00000028u, 0x00000000u, 0x0005002cu, 0x00000007u, 0x00000029u,
0x00000028u, 0x00000028u, 0x00040015u, 0x0000002eu, 0x00000020u, 0x00000000u, 0x0004002bu, 0x0000002eu,
0x0000002fu, 0x00000000u, 0x0005002cu, 0x00000007u, 0x00000034u, 0x0000001du, 0x00000028u, 0x0005002cu,
0x00000007u, 0x0000003eu, 0x00000028u, 0x0000001du, 0x00040020u, 0x0000004eu, 0x00000003u, 0x0000000au,
0x0004003bu, 0x0000004eu, 0x0000004fu, 0x00000003u, 0x0004002bu, 0x0000000au, 0x00000050u, 0x3e800000u,
0x00050036u, 0x00000002u, 0x00000004u, 0x00000000u, 0x00000003u, 0x000200f8u, 0x00000005u, 0x0004003bu,
0x00000008u, 0x00000009u, 0x00000007u, 0x0004003bu, 0x00000008u, 0x0000001au, 0x00000007u, 0x0004003bu,
0x00000020u, 0x00000021u, 0x00000007u, 0x0004003bu, 0x00000020u, 0x00000031u, 0x00000007u, 0x0004003bu,
0x00000020u, 0x0000003bu, 0x00000007u, 0x0004003bu, 0x00000020u, 0x00000045u, 0x00000007u, 0x0004003du,
0x0000000bu, 0x0000000eu, 0x0000000du, 0x00050041u, 0x00000014u, 0x00000015u, 0x00000012u, 0x00000013u,
0x0004003du, 0x00000007u, 0x00000016u, 0x00000015u, 0x0004006fu, 0x0000000bu, 0x00000017u, 0x00000016u,
0x00050085u, 0x0000000bu, 0x00000018u, 0x0000000eu, 0x00000017u, 0x0004006eu, 0x00000007u, 0x00000019u,
0x00000018u, 0x0003003eu, 0x00000009u, 0x00000019u, 0x00050041u, 0x00000014u, 0x0000001bu, 0x00000012u,
0x00000013u, 0x0004003du, 0x00000007u, 0x0000001cu, 0x0000001bu, 0x00050082u, 0x00000007u, 0x0000001fu,
0x0000001cu, 0x0000001eu, 0x0003003eu, 0x0000001au, 0x0000001fu, 0x0004003du, 0x00000023u, 0x00000026u,
0x00000025u, 0x0004003du, 0x00000007u, 0x00000027u, 0x00000009u, 0x0004003du, 0x00000007u, 0x0000002au,
0x0000001au, 0x0008000cu, 0x00000007u, 0x0000002bu, 0x00000001u, 0x0000002du, 0x00000027u, 0x00000029u,
0x0000002au, 0x00040064u, 0x00000022u, 0x0000002cu, 0x00000026u, 0x0007005fu, 0x0000000fu, 0x0000002du,
0x0000002cu, 0x0000002bu, 0x00000002u, 0x00000028u, 0x00050051u, 0x0000000au, 0x00000030u, 0x0000002du,
0x00000000u, 0x0003003eu, 0x00000021u, 0x00000030u, 0x0004003du, 0x00000023u, 0x00000032u, 0x00000025u,
0x0004003du, 0x00000007u, 0x00000033u, 0x00000009u, 0x00050080u, 0x00000007u, 0x00000035u, 0x00000033u,
0x00000034u, 0x0004003du, 0x00000007u, 0x00000036u, 0x0000001au, 0x0008000cu, 0x00000007u, 0x00000037u,
0x00000001u, 0x0000002du, 0x00000035u, 0x00000029u, 0x00000036u, 0x00040064u, 0x00000022u, 0x00000038u,
0x00000032u, 0x0007005fu, 0x0000000fu, 0x00000039u, 0x00000038u, 0x00000037u, 0x00000002u, 0x00000028u,
0x00050051u, 0x0000000au, 0x0000003au, 0x00000039u, 0x00000000u, 0x0003003eu, 0x00000031u, 0x0000003au,
0x0004003du, 0x00000023u, 0x0000003cu, 0x00000025u, 0x0004003du, 0x00000007u, 0x0000003du, 0x00000009u,
0x00050080u, 0x00000007u, 0x0000003fu, 0x0000003du, 0x0000003eu, 0x0004003du, 0x00000007u, 0x00000040u,
0x0000001au, 0x0008000cu, 0x00000007u, 0x00000041u, 0x00000001u, 0x0000002du, 0x0000003fu, 0x00000029u,
0x00000040u, 0x00040064u, 0x00000022u, 0x00000042u, 0x0000003cu, 0x0007005fu, 0x0000000fu, 0x00000043u,
0x00000042u, 0x00000041u, 0x00000002u, 0x00000028u, 0x00050051u, 0x0000000au, 0x00000044u, 0x00000043u,
0x00000000u, 0x0003003eu, 0x0000003bu, 0x00000044u, 0x0004003du, 0x00000023u, 0x00000046u, 0x00000025u,
0x0004003du, 0x00000007u, 0x00000047u, 0x00000009u, 0x00050080u, 0x00000007u, 0x00000048u, 0x00000047u,
0x0000001eu, 0x0004003du, 0x00000007u, 0x00000049u, 0x0000001au, 0x0008000cu, 0x00000007u, 0x0000004au,
0x00000001u, 0x0000002du, 0x00000048u, 0x00000029u, 0x00000049u, 0x00040064u, 0x00000022u, 0x0000004bu,
0x00000046u, 0x0007005fu, 0x0000000fu, 0x0000004cu, 0x0000004bu, 0x0000004au, 0x00000002u, 0x00000028u,
0x00050051u, 0x0000000au, 0x0000004du, 0x0000004cu, 0x00000000u, 0x0003003eu, 0x00000045u, 0x0000004du,
0x0004003du, 0x0000000au, 0x00000051u, 0x00000021u, 0x0004003du, 0x0000000au, 0x00000052u, 0x00000031u,
0x00050081u, 0x0000000au, 0x00000053u, 0x00000051u, 0x00000052u, 0x0004003du, 0x0000000au, 0x00000054u,
0x0000003bu, 0x00050081u, 0x0000000au, 0x00000055u, 0x00000053u, 0x00000054u, 0x0004003du, 0x0000000au,
0x00000056u, 0x00000045u, 0x00050081u, 0x0000000au, 0x00000057u, 0x00000055u, 0x00000056u, 0x00050085u,
0x0000000au, 0x00000058u, 0x00000050u, 0x00000057u, 0x0003003eu, 0x0000004fu, 0x00000058u, 0x000100fdu,
0x00010038u,
};
@@ -1,329 +0,0 @@
// MobileGL - MobileGL/MG_Backend/DirectVulkan/Renderer/WireDepthResolveArm.h
// Copyright (c) 2025-2026 MobileGL-Dev
// Licensed under the GNU Lesser General Public License v3.0:
// https://www.gnu.org/licenses/gpl-3.0.txt
// https://www.gnu.org/licenses/lgpl-3.0.txt
// SPDX-License-Identifier: LGPL-3.0-only
// End of Source File Header
#pragma once
#include <Includes.h>
#include <cstring>
#include <mutex>
#include <utility>
// P7 gate 5 (g5-msrbo, g5-msprobe): WHICH ARM RESOLVES A MULTISAMPLE DEPTH/STENCIL ASPECT FIRST.
//
// The wire arm has two (WireFramebuffer.inc, ResolveWireDepthStencil): a render pass that carries
// a VK_KHR_depth_stencil_resolve attachment and no draw, and the baked shader pass of
// WireMultisampleResolve.inc, which draws. P7 wave 2-B2 took the render pass wherever the
// extension exists. On the Redmi (Adreno 830, Vulkan 1.3.284, driver 512.800.71) that pass left
// its resolve target unwritten - KHR-GL46.direct_state_access.renderbuffers_storage_multisample
// read every resolved depth and stencil value back as 0 on the inproc arm while the monolith arm
// passed, and the same case passed on the device with the shader arm forced
// (MGITEST_MAGMA_FORCE_SHADER_DEPTH_RESOLVE=1).
//
// A DRIVER THAT CLAIMS WHAT IT CANNOT DO IS A POST PROBE, NOT A VENDOR QUIRK (standing rule,
// 2026-08-22). The first fix keyed the order on Qualcomm's vendor id; it is replaced by a probe
// that reproduces the production resolve on the actual VkDevice (WireDepthResolveProbe.cpp) and
// asks the one question the order depends on: does the no-draw render pass write the resolve
// target? A driver that fixes the defect gets the fast arm back, and a driver of any vendor that
// has it gets the shader arm - neither needs a table edit.
//
// EVERY BUG PROBE CARRIES A CONTROL (MG_Util/SelfTest/DriverBugProbes.h). The control is the
// production SHADER arm fed the same inputs: when it does not resolve them either, the probe has
// measured its own setup (or a device that cannot resolve depth at all) rather than the render
// pass, the verdict is INCONCLUSIVE, and the default order stands.
//
// This header is the pure half - the measurement, the verdict, the test knob and the choice - so
// a unit test pins every mapping with a fake result source (MG_Test/Pipeline/PipelineQuirkTest.cpp).
// The Vulkan half that fills the measurement is WireDepthResolveProbe.{h,cpp}.
namespace MobileGL::MG_Backend::DirectVulkan {
// One aspect of one probed format, both arms. Values are the RAW aspect words the
// buffer copy returns (D16: 16 bits; D24: the low 24 bits of the 32-bit word; D32F: the float's
// bits; stencil: 8 bits), compared within `tolerance` (1 LSB for a UNORM depth, 0 otherwise).
struct WireDepthResolveAspectReading {
// The format has this aspect and the render-pass arm's copy of it was read back.
Bool measured = false;
Uint32 texels = 0;
Uint32 expected = 0; // the multisample source's cleared value
Uint32 sentinel = 0; // what the resolve target was pre-filled with
Uint32 tolerance = 0;
// THE SUBJECT: VK_KHR_depth_stencil_resolve render pass, no draw.
Uint32 renderPassMatches = 0; // texels within tolerance of `expected`
Uint32 renderPassSentinels = 0; // texels still holding the sentinel
Uint32 renderPassFirst = 0; // texel (0,0)
// THE CONTROL: the production shader pass, same inputs. False where it cannot run for this
// aspect (a stencil aspect without VK_EXT_shader_stencil_export, a failed pipeline).
Bool shaderRan = false;
Uint32 shaderMatches = 0;
Uint32 shaderFirst = 0;
};
struct WireDepthResolveFormatReading {
String name; // e.g. "D24_UNORM_S8_UINT"
Int32 format = 0; // the VkFormat
Uint32 samples = 0;
// False when the format was not probed; `skipReason` says why (unsupported, the render-pass
// arm would not be taken for it, an object the probe needed could not be created).
Bool ran = false;
String skipReason;
WireDepthResolveAspectReading depth, stencil;
};
struct WireDepthResolveProbeMeasurement {
// At least one format was recorded, submitted and read back.
Bool ran = false;
// The bounded fence wait expired: every object the probe created was deliberately leaked
// (the queue may still be executing it), and nothing was read back.
Bool fenceWaitTimedOut = false;
String failureReason;
// Came from MGITEST_MAGMA_DEPTH_RESOLVE_PROBE=bug|clean, not from the device.
Bool fromKnob = false;
// Measured on the device, but with MGITEST_MAGMA_DEPTH_RESOLVE_PROBE=elide-subject: the probe
// recorded no render-pass resolve at all, so the subject's target kept its sentinel.
Bool subjectElided = false;
Vector<WireDepthResolveFormatReading> formats;
};
enum class WireDepthResolveProbeVerdict : Uint8 {
// Nothing was measured: the render-pass arm is not available (nothing to choose between),
// or the probe could not set itself up. The default order stands.
NotRun,
// Measured, but no format's CONTROL resolved: the probe cannot tell the render pass's
// defect from its own. The default order stands, and the report must never call it a bug.
Inconclusive,
// Every format whose control resolved was resolved by the render pass too.
Clean,
// The defect: on at least one format the shader control resolved the inputs and the
// render pass did not (wrote nothing - the sentinel survived - or wrote wrong values).
RenderPassResolveBroken,
};
inline const char* WireDepthResolveProbeVerdictName(WireDepthResolveProbeVerdict verdict) {
switch (verdict) {
case WireDepthResolveProbeVerdict::NotRun: return "not-run";
case WireDepthResolveProbeVerdict::Inconclusive: return "inconclusive";
case WireDepthResolveProbeVerdict::Clean: return "clean";
case WireDepthResolveProbeVerdict::RenderPassResolveBroken: return "render-pass-resolve-broken";
}
return "?";
}
inline Bool WireDepthResolveControlHolds(const WireDepthResolveAspectReading& aspect) {
return aspect.measured && aspect.shaderRan && aspect.texels > 0 && aspect.shaderMatches == aspect.texels;
}
inline Bool WireDepthResolveSubjectHolds(const WireDepthResolveAspectReading& aspect) {
return aspect.texels > 0 && aspect.renderPassMatches == aspect.texels;
}
// An aspect only counts where its control holds; a format is conclusive when any of its
// aspects is. The render pass resolves every aspect of the format in one pass, so one aspect
// it fails is the defect for the whole arm.
inline WireDepthResolveProbeVerdict EvaluateWireDepthResolveProbe(const WireDepthResolveProbeMeasurement& measurement) {
if (!measurement.ran || measurement.fenceWaitTimedOut) return WireDepthResolveProbeVerdict::NotRun;
Bool conclusive = false, broken = false;
for (const WireDepthResolveFormatReading& reading : measurement.formats) {
if (!reading.ran) continue;
for (const WireDepthResolveAspectReading* aspect : {&reading.depth, &reading.stencil}) {
if (!WireDepthResolveControlHolds(*aspect)) continue;
conclusive = true;
if (!WireDepthResolveSubjectHolds(*aspect)) broken = true;
}
}
if (broken) return WireDepthResolveProbeVerdict::RenderPassResolveBroken;
return conclusive ? WireDepthResolveProbeVerdict::Clean : WireDepthResolveProbeVerdict::Inconclusive;
}
// THE TEST KNOB, read by the SERVER (split and spawn arms only; the tcp server is a lane fixture
// whose environment no entry reaches - spawn_lane_parity.py's MAGMA_SERVER_ENV_KNOB_NO_TCP).
// Lavapipe resolves correctly through both arms, so no host lane can reach the verdict that
// matters on the Redmi. MGITEST_MAGMA_DEPTH_RESOLVE_PROBE=bug|clean replaces the MEASUREMENT
// with a canned one that says exactly that, and nothing else: the canned measurement still goes
// through EvaluateWireDepthResolveProbe and the same member, so an entry that forces `bug` is red
// when the evaluation stops detecting the defect.
//
// A canned measurement cannot see the REAL probe - its recording, readback and tally - stop
// detecting the defect, and on lavapipe the real subject is clean, so nothing would. The third
// value, MGITEST_MAGMA_DEPTH_RESOLVE_PROBE=elide-subject, is that negative control: the REAL
// probe runs (ChooseWireDepthResolveArm treats it as Measure) and the caller passes it on as
// WireDepthResolveProbeContext::elideSubject, so the probe records no render-pass resolve and
// the real readback keeps the sentinel while the shader control still runs. The
// DirectVulkan.{Split,Spawn}.MsResolveElide. entries then require the defect verdict from the
// measurement itself.
enum class WireDepthResolveProbeKnob : Uint8 { Measure, ForceBug, ForceClean, ElideSubject, Unrecognised };
inline WireDepthResolveProbeKnob ParseWireDepthResolveProbeKnob(const char* value) {
if (value == nullptr || *value == '\0') return WireDepthResolveProbeKnob::Measure;
if (std::strcmp(value, "bug") == 0) return WireDepthResolveProbeKnob::ForceBug;
if (std::strcmp(value, "clean") == 0) return WireDepthResolveProbeKnob::ForceClean;
if (std::strcmp(value, "elide-subject") == 0) return WireDepthResolveProbeKnob::ElideSubject;
return WireDepthResolveProbeKnob::Unrecognised;
}
// One packed format's worth of readings: the control resolved both aspects; the render pass
// either did too (`renderPassWrites`) or left the sentinel everywhere.
inline WireDepthResolveProbeMeasurement CannedWireDepthResolveProbeMeasurement(Bool renderPassWrites) {
WireDepthResolveProbeMeasurement measurement;
measurement.ran = true;
measurement.fromKnob = true;
WireDepthResolveFormatReading reading;
reading.name = "MGITEST_MAGMA_DEPTH_RESOLVE_PROBE";
reading.samples = 4;
reading.ran = true;
const auto fill = [&](WireDepthResolveAspectReading& aspect, Uint32 expected, Uint32 sentinel) {
aspect.measured = true;
aspect.texels = 16;
aspect.expected = expected;
aspect.sentinel = sentinel;
aspect.renderPassMatches = renderPassWrites ? 16 : 0;
aspect.renderPassSentinels = renderPassWrites ? 0 : 16;
aspect.renderPassFirst = renderPassWrites ? expected : sentinel;
aspect.shaderRan = true;
aspect.shaderMatches = 16;
aspect.shaderFirst = expected;
};
fill(reading.depth, 0x400000u, 0xBFFFFFu);
fill(reading.stencil, 0x5Au, 0xA5u);
measurement.formats.push_back(Move(reading));
return measurement;
}
struct WireDepthResolveArmChoice {
WireDepthResolveProbeMeasurement measurement;
WireDepthResolveProbeVerdict verdict = WireDepthResolveProbeVerdict::NotRun;
// m_wirePreferShaderDepthResolve: the shader pass goes first, the render pass is the
// fallback for what the shader cannot write.
Bool preferShader = false;
};
// The whole decision, with the Vulkan half behind `measure` (called at most once, and only when
// the knob does not decide and the render-pass arm exists at all: without it the shader pass
// is the only arm and there is no order to choose). ElideSubject does not decide: it is
// measured like Measure, and the elision is the measuring callable's to apply.
template <typename MeasureFn>
WireDepthResolveArmChoice ChooseWireDepthResolveArm(WireDepthResolveProbeKnob knob, Bool renderPassArmAvailable,
MeasureFn&& measure) {
WireDepthResolveArmChoice choice;
if (knob == WireDepthResolveProbeKnob::ForceBug || knob == WireDepthResolveProbeKnob::ForceClean) {
choice.measurement = CannedWireDepthResolveProbeMeasurement(knob == WireDepthResolveProbeKnob::ForceClean);
} else if (renderPassArmAvailable) {
choice.measurement = measure();
}
choice.verdict = EvaluateWireDepthResolveProbe(choice.measurement);
choice.preferShader = choice.verdict == WireDepthResolveProbeVerdict::RenderPassResolveBroken;
return choice;
}
// WHOSE VERDICT IT IS (codex closeout finding 7). The verdict is a property of ONE device and
// driver, and a process can hold more than one: inproc tears a renderer down and initializes
// another, possibly on a different physical device or under a different driver. The choice was
// a function-static - the first renderer's answer for every renderer after it - so a second
// device skipped its own probe and took an order measured elsewhere. It is now memoized per
// IDENTITY: the device (vendor, device, driver version, pipeline-cache UUID - the last changes
// with the driver build even where the version number does not) plus the two inputs the choice
// itself depends on (whether a render-pass arm exists to judge, and the test knob). The same
// identity is still probed once per process; a different one is probed for itself.
struct WireDepthResolveDeviceIdentity {
Uint32 vendorID = 0;
Uint32 deviceID = 0;
Uint32 driverVersion = 0;
Uint8 pipelineCacheUUID[16] = {};
Bool renderPassArmAvailable = false;
WireDepthResolveProbeKnob knob = WireDepthResolveProbeKnob::Measure;
Bool operator==(const WireDepthResolveDeviceIdentity& other) const {
return vendorID == other.vendorID && deviceID == other.deviceID && driverVersion == other.driverVersion &&
std::memcmp(pipelineCacheUUID, other.pipelineCacheUUID, sizeof(pipelineCacheUUID)) == 0 &&
renderPassArmAvailable == other.renderPassArmAvailable && knob == other.knob;
}
};
// The renderer's identity from its device's VkPhysicalDeviceProperties - the ONE place the fields
// are filled (VulkanRenderer::ArmWireDepthResolveOrder calls it), so the unit test proves that each
// property reaches the key: with only the cache tested, a field left out here stayed green.
inline WireDepthResolveDeviceIdentity MakeWireDepthResolveDeviceIdentity(const VkPhysicalDeviceProperties& properties,
Bool renderPassArmAvailable,
WireDepthResolveProbeKnob knob) {
WireDepthResolveDeviceIdentity identity;
identity.vendorID = properties.vendorID;
identity.deviceID = properties.deviceID;
identity.driverVersion = properties.driverVersion;
static_assert(sizeof(identity.pipelineCacheUUID) == sizeof(properties.pipelineCacheUUID));
std::memcpy(identity.pipelineCacheUUID, properties.pipelineCacheUUID, sizeof(identity.pipelineCacheUUID));
identity.renderPassArmAvailable = renderPassArmAvailable;
identity.knob = knob;
return identity;
}
class WireDepthResolveArmCache {
public:
// The identity's memoized choice, or `decide()`'s - called at most once per identity, under
// the cache's lock (a probe records on the device's queue; two renderers of one identity
// must not both run it). `decided`, when given, says whether this call ran `decide`.
template <typename DecideFn>
WireDepthResolveArmChoice Resolve(const WireDepthResolveDeviceIdentity& identity, DecideFn&& decide,
Bool* decided = nullptr) {
std::lock_guard<std::mutex> lock(m_mutex);
for (const auto& entry : m_entries) {
if (entry.first == identity) {
if (decided) *decided = false;
return entry.second;
}
}
WireDepthResolveArmChoice choice = decide();
m_entries.emplace_back(identity, choice);
if (decided) *decided = true;
return choice;
}
SizeT Size() const {
std::lock_guard<std::mutex> lock(m_mutex);
return m_entries.size();
}
private:
mutable std::mutex m_mutex;
Vector<std::pair<WireDepthResolveDeviceIdentity, WireDepthResolveArmChoice>> m_entries;
};
// One format's readings, both arms: "D24_UNORM_S8_UINT x4: depth expected 0x400000 sentinel
// 0xbfffff: render pass 0/16 (first 0xbfffff, sentinel 16), shader control 16/16 (first
// 0x400000) / stencil ...".
inline String DescribeWireDepthResolveFormat(const WireDepthResolveFormatReading& reading) {
const auto aspectText = [](const char* name, const WireDepthResolveAspectReading& aspect) {
String text = format("{} expected 0x{:x} sentinel 0x{:x}: render pass {}/{} (first 0x{:x}, sentinel {}), ",
name, aspect.expected, aspect.sentinel, aspect.renderPassMatches, aspect.texels,
aspect.renderPassFirst, aspect.renderPassSentinels);
if (aspect.shaderRan) {
text += format("shader control {}/{} (first 0x{:x})", aspect.shaderMatches, aspect.texels,
aspect.shaderFirst);
} else {
text += "no shader control";
}
return text;
};
String out = reading.name;
if (!reading.ran) return out + " skipped (" + reading.skipReason + ")";
out += format(" x{}: ", reading.samples);
if (reading.depth.measured) out += aspectText("depth", reading.depth);
if (reading.depth.measured && reading.stencil.measured) out += " / ";
if (reading.stencil.measured) out += aspectText("stencil", reading.stencil);
return out;
}
// Every format, "; "-separated, for the POST row.
inline String DescribeWireDepthResolveProbe(const WireDepthResolveProbeMeasurement& measurement) {
if (!measurement.ran) {
return measurement.failureReason.empty() ? String("not run") : "not run (" + measurement.failureReason + ")";
}
String out;
for (const WireDepthResolveFormatReading& reading : measurement.formats) {
if (!out.empty()) out += "; ";
out += DescribeWireDepthResolveFormat(reading);
}
return out;
}
} // namespace MobileGL::MG_Backend::DirectVulkan
@@ -1,992 +0,0 @@
// MobileGL - MobileGL/MG_Backend/DirectVulkan/Renderer/WireDepthResolveProbe.cpp
// Copyright (c) 2026 MobileGL-Dev
// Licensed under the GNU Lesser General Public License v3.0:
// https://www.gnu.org/licenses/gpl-3.0.txt
// https://www.gnu.org/licenses/lgpl-3.0.txt
// SPDX-License-Identifier: LGPL-3.0-only
// End of Source File Header
//
// See WireDepthResolveProbe.h for the arms and the probe's shape, WireDepthResolveArm.h for the
// verdict. The plumbing is the PRIMITIVES_GENERATED probe's (MG_Util/SelfTest/
// PrimitivesGeneratedNoXfbProbe.cpp): one throwaway command buffer, a bounded fence wait that
// leaks rather than idle-waits a hung GPU, teardown on every other path.
#include "WireDepthResolveProbe.h"
#include <MG_Util/Debug/Log.h>
#include <bit>
#include <cmath>
#include <cstring>
#include <vulkan/vulkan_core.h>
#if MOBILEGL_BUILD_DISAGGREGATED
namespace MobileGL::MG_Backend::DirectVulkan {
#include "WireMultisampleResolveSpirv.h"
VkImageAspectFlags WireDepthStencilFormatAspects(VkFormat format) {
if (format == VK_FORMAT_S8_UINT) return VK_IMAGE_ASPECT_STENCIL_BIT;
if (format == VK_FORMAT_D16_UNORM_S8_UINT || format == VK_FORMAT_D24_UNORM_S8_UINT ||
format == VK_FORMAT_D32_SFLOAT_S8_UINT)
return VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT;
return VK_IMAGE_ASPECT_DEPTH_BIT;
}
VkImageViewCreateInfo WireDepthStencilViewInfo(VkImage image, VkFormat format, VkImageAspectFlags aspects,
Uint32 level, Uint32 layer) {
VkImageViewCreateInfo info{VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO};
info.image = image;
info.viewType = VK_IMAGE_VIEW_TYPE_2D;
info.format = format;
info.subresourceRange = {aspects, level, 1, layer, 1};
return info;
}
VkResult CreateWireDepthStencilResolvePass(PFN_vkCreateRenderPass2 createRenderPass2, VkDevice device,
VkFormat format, VkSampleCountFlagBits samples, VkRenderPass* pass) {
const VkImageAspectFlags formatAspects = WireDepthStencilFormatAspects(format);
VkAttachmentDescription2 attachments[2]{};
for (Uint32 i = 0; i < 2; ++i) {
auto& attachment = attachments[i];
attachment.sType = VK_STRUCTURE_TYPE_ATTACHMENT_DESCRIPTION_2;
attachment.format = format;
attachment.samples = i == 0 ? samples : VK_SAMPLE_COUNT_1_BIT;
attachment.loadOp = attachment.stencilLoadOp =
i == 0 ? VK_ATTACHMENT_LOAD_OP_LOAD : VK_ATTACHMENT_LOAD_OP_DONT_CARE;
attachment.storeOp = attachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_STORE;
attachment.initialLayout = attachment.finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
}
VkAttachmentReference2 sourceReference{VK_STRUCTURE_TYPE_ATTACHMENT_REFERENCE_2};
sourceReference.attachment = 0;
sourceReference.layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
sourceReference.aspectMask = formatAspects;
VkAttachmentReference2 resolveReference = sourceReference;
resolveReference.attachment = 1;
VkSubpassDescriptionDepthStencilResolve resolve{VK_STRUCTURE_TYPE_SUBPASS_DESCRIPTION_DEPTH_STENCIL_RESOLVE};
resolve.depthResolveMode =
(formatAspects & VK_IMAGE_ASPECT_DEPTH_BIT) ? VK_RESOLVE_MODE_SAMPLE_ZERO_BIT : VK_RESOLVE_MODE_NONE;
resolve.stencilResolveMode =
(formatAspects & VK_IMAGE_ASPECT_STENCIL_BIT) ? VK_RESOLVE_MODE_SAMPLE_ZERO_BIT : VK_RESOLVE_MODE_NONE;
resolve.pDepthStencilResolveAttachment = &resolveReference;
VkSubpassDescription2 subpass{VK_STRUCTURE_TYPE_SUBPASS_DESCRIPTION_2};
subpass.pNext = &resolve;
subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
subpass.pDepthStencilAttachment = &sourceReference;
VkRenderPassCreateInfo2 passInfo{VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO_2};
passInfo.attachmentCount = 2;
passInfo.pAttachments = attachments;
passInfo.subpassCount = 1;
passInfo.pSubpasses = &subpass;
return createRenderPass2(device, &passInfo, nullptr, pass);
}
VkResult CreateWireShaderResolveKit(VkDevice device, Bool shaderStencilExport, WireShaderResolveKit& kit) {
const auto shader = [&](const Uint32* code, SizeT bytes, VkShaderModule& module) {
VkShaderModuleCreateInfo info{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO};
info.codeSize = bytes;
info.pCode = code;
return vkCreateShaderModule(device, &info, nullptr, &module);
};
VkResult result =
shader(kWireMultisampleResolveVertexSpirv, sizeof(kWireMultisampleResolveVertexSpirv), kit.vertex);
if (result != VK_SUCCESS) return result;
result = shader(kWireMultisampleDepthResolveFragmentSpirv, sizeof(kWireMultisampleDepthResolveFragmentSpirv),
kit.depthFragment);
if (result != VK_SUCCESS) return result;
// THE STENCIL MODULE IS ONLY CREATED WHERE IT CAN RUN: its SPIR-V declares the
// StencilExportEXT capability, and handing a module with an unsupported capability to
// vkCreateShaderModule is undefined behaviour - not an error this could catch.
if (shaderStencilExport) {
result = shader(kWireMultisampleStencilResolveFragmentSpirv,
sizeof(kWireMultisampleStencilResolveFragmentSpirv), kit.stencilFragment);
if (result != VK_SUCCESS) return result;
}
const VkDescriptorSetLayoutBinding binding{0, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1,
VK_SHADER_STAGE_FRAGMENT_BIT, nullptr};
VkDescriptorSetLayoutCreateInfo layout{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO};
layout.bindingCount = 1;
layout.pBindings = &binding;
result = vkCreateDescriptorSetLayout(device, &layout, nullptr, &kit.descriptorLayout);
if (result != VK_SUCCESS) return result;
// NO PUSH CONSTANT RANGE AT ALL: the pass reads its coordinate from gl_FragCoord and its
// rectangle from the scissor, so neither stage takes an input.
VkPipelineLayoutCreateInfo pipelineLayout{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO};
pipelineLayout.setLayoutCount = 1;
pipelineLayout.pSetLayouts = &kit.descriptorLayout;
result = vkCreatePipelineLayout(device, &pipelineLayout, nullptr, &kit.pipelineLayout);
if (result != VK_SUCCESS) return result;
// NEAREST: texelFetch ignores the sampler's filter, and most devices do not advertise
// linear filtering for a depth format anyway. The sampler exists only because GLSL's
// sampler2DMS is a COMBINED image sampler.
VkSamplerCreateInfo sampler{VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO};
sampler.mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST;
sampler.addressModeU = sampler.addressModeV = sampler.addressModeW = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE;
sampler.magFilter = sampler.minFilter = VK_FILTER_NEAREST;
sampler.maxLod = 0.0f;
return vkCreateSampler(device, &sampler, nullptr, &kit.nearest);
}
void DestroyWireShaderResolveKit(VkDevice device, WireShaderResolveKit& kit) {
vkDestroySampler(device, kit.nearest, nullptr);
vkDestroyPipelineLayout(device, kit.pipelineLayout, nullptr);
vkDestroyDescriptorSetLayout(device, kit.descriptorLayout, nullptr);
vkDestroyShaderModule(device, kit.vertex, nullptr);
vkDestroyShaderModule(device, kit.depthFragment, nullptr);
vkDestroyShaderModule(device, kit.stencilFragment, nullptr);
kit = {};
}
VkResult CreateWireShaderResolveRenderPass(VkDevice device, VkFormat format, VkRenderPass* pass) {
VkAttachmentDescription attachment{};
attachment.format = format;
attachment.samples = VK_SAMPLE_COUNT_1_BIT;
// DONT_CARE on BOTH aspects: the pass writes every texel of the scissored rect for the
// aspect it owns, and the caller copies only that aspect out. The other aspect of a packed
// format is left undefined on purpose - it is never read, and LOADing it would order this
// pass behind a write nobody is waiting for.
attachment.loadOp = attachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
attachment.storeOp = attachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_STORE;
attachment.initialLayout = attachment.finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
const VkAttachmentReference depthStencil{0, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL};
VkSubpassDescription subpass{};
subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
subpass.pDepthStencilAttachment = &depthStencil;
VkRenderPassCreateInfo info{VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO};
info.attachmentCount = 1;
info.pAttachments = &attachment;
info.subpassCount = 1;
info.pSubpasses = &subpass;
return vkCreateRenderPass(device, &info, nullptr, pass);
}
VkResult CreateWireShaderResolvePipeline(VkDevice device, const WireShaderResolveKit& kit, VkRenderPass pass,
VkImageAspectFlags aspect, VkPipeline* pipeline) {
const VkShaderModule fragment =
aspect == VK_IMAGE_ASPECT_STENCIL_BIT ? kit.stencilFragment : kit.depthFragment;
if (fragment == VK_NULL_HANDLE || kit.vertex == VK_NULL_HANDLE) return VK_ERROR_FEATURE_NOT_PRESENT;
VkPipelineShaderStageCreateInfo stages[2]{};
for (auto& stage : stages) {
stage.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
stage.pName = "main";
}
stages[0].stage = VK_SHADER_STAGE_VERTEX_BIT;
stages[0].module = kit.vertex;
stages[1].stage = VK_SHADER_STAGE_FRAGMENT_BIT;
stages[1].module = fragment;
const VkPipelineVertexInputStateCreateInfo vertex{VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO};
VkPipelineInputAssemblyStateCreateInfo assembly{VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO};
assembly.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
VkPipelineViewportStateCreateInfo viewport{VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO};
viewport.viewportCount = viewport.scissorCount = 1;
VkPipelineRasterizationStateCreateInfo raster{VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO};
raster.polygonMode = VK_POLYGON_MODE_FILL;
raster.cullMode = VK_CULL_MODE_NONE;
raster.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE;
raster.lineWidth = 1.0f;
VkPipelineMultisampleStateCreateInfo samples{VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO};
samples.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT;
VkPipelineDepthStencilStateCreateInfo depthStencilState{VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO};
depthStencilState.minDepthBounds = 0.0f;
depthStencilState.maxDepthBounds = 1.0f;
if (aspect == VK_IMAGE_ASPECT_DEPTH_BIT) {
// ALWAYS + write: gl_FragDepth is the answer, and a comparison against whatever
// DONT_CARE left behind would discard some of it.
depthStencilState.depthTestEnable = VK_TRUE;
depthStencilState.depthWriteEnable = VK_TRUE;
depthStencilState.depthCompareOp = VK_COMPARE_OP_ALWAYS;
} else {
// REPLACE on every outcome, compare ALWAYS, full write mask: that is what makes the
// shader-exported reference the value that lands. The static `reference` is overridden
// by gl_FragStencilRefARB, which is the whole point of the extension.
depthStencilState.stencilTestEnable = VK_TRUE;
VkStencilOpState op{};
op.failOp = op.passOp = op.depthFailOp = VK_STENCIL_OP_REPLACE;
op.compareOp = VK_COMPARE_OP_ALWAYS;
op.compareMask = op.writeMask = 0xFFu;
op.reference = 0;
depthStencilState.front = depthStencilState.back = op;
}
// No colour attachment in this render pass, so no attachment states either.
VkPipelineColorBlendStateCreateInfo blend{VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO};
const VkDynamicState dynamicStates[]{VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR};
VkPipelineDynamicStateCreateInfo dynamic{VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO};
dynamic.dynamicStateCount = 2;
dynamic.pDynamicStates = dynamicStates;
VkGraphicsPipelineCreateInfo info{VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO};
info.stageCount = 2;
info.pStages = stages;
info.pVertexInputState = &vertex;
info.pInputAssemblyState = &assembly;
info.pViewportState = &viewport;
info.pRasterizationState = &raster;
info.pMultisampleState = &samples;
info.pDepthStencilState = &depthStencilState;
info.pColorBlendState = &blend;
info.pDynamicState = &dynamic;
info.layout = kit.pipelineLayout;
info.renderPass = pass;
return vkCreateGraphicsPipelines(device, VK_NULL_HANDLE, 1, &info, nullptr, pipeline);
}
void RecordWireShaderResolveDraw(VkCommandBuffer commandBuffer, const WireShaderResolveKit& kit,
VkRenderPass pass, VkPipeline pipeline, VkFramebuffer framebuffer,
VkDescriptorSet descriptorSet, VkExtent2D attachmentExtent, VkRect2D rect) {
VkRenderPassBeginInfo begin{VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO};
begin.renderPass = pass;
begin.framebuffer = framebuffer;
// The RECTANGLE is the render area, exactly as the render-pass arm's renderArea is - the
// scratch outside it is never read.
begin.renderArea = rect;
vkCmdBeginRenderPass(commandBuffer, &begin, VK_SUBPASS_CONTENTS_INLINE);
vkCmdBindPipeline(commandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline);
// THE VIEWPORT IS THE WHOLE ATTACHMENT AND THE SCISSOR IS THE RECT, and the two are not
// interchangeable here: gl_FragCoord is what the fragment shader fetches by, so the
// clip-space-to-attachment mapping has to be the identity for every rectangle. A viewport
// shrunk onto the rect would slide the whole image instead of moving a window over it.
const VkViewport viewport{0.0f, 0.0f, static_cast<float>(attachmentExtent.width),
static_cast<float>(attachmentExtent.height), 0.0f, 1.0f};
vkCmdSetViewport(commandBuffer, 0, 1, &viewport);
vkCmdSetScissor(commandBuffer, 0, 1, &rect);
vkCmdBindDescriptorSets(commandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, kit.pipelineLayout, 0, 1,
&descriptorSet, 0, nullptr);
vkCmdDraw(commandBuffer, 3, 1, 0, 0);
vkCmdEndRenderPass(commandBuffer);
}
namespace {
constexpr Uint32 kProbeExtent = 4;
constexpr Uint32 kProbeTexels = kProbeExtent * kProbeExtent;
// Every Vulkan device must support 4 samples on a depth/stencil attachment
// (framebufferDepthSampleCounts), and the CTS case the probe stands for fails at 2 and 4.
constexpr VkSampleCountFlagBits kProbeSamples = VK_SAMPLE_COUNT_4_BIT;
constexpr Float kClearDepth = 0.25f;
constexpr Float kSentinelDepth = 0.75f;
constexpr Uint32 kClearStencil = 0x5Au;
constexpr Uint32 kSentinelStencil = 0xA5u;
constexpr Uint64 kFenceTimeoutNs = 5ull * 1000ull * 1000ull * 1000ull;
// The formats the wire maps GL's depth/stencil internal formats onto (VkTextureManager),
// packed first: the case that set all this off failed on every one of them.
struct ProbeFormat {
VkFormat format;
const char* name;
};
constexpr ProbeFormat kProbeFormats[] = {
{VK_FORMAT_D24_UNORM_S8_UINT, "D24_UNORM_S8_UINT"},
{VK_FORMAT_D32_SFLOAT_S8_UINT, "D32_SFLOAT_S8_UINT"},
{VK_FORMAT_D16_UNORM, "D16_UNORM"},
{VK_FORMAT_X8_D24_UNORM_PACK32, "X8_D24_UNORM_PACK32"},
{VK_FORMAT_D32_SFLOAT, "D32_SFLOAT"},
{VK_FORMAT_S8_UINT, "S8_UINT"},
};
// The usages production gives the two images: a wire multisample depth/stencil attachment
// (VkTextureManager: SAMPLED | DEPTH_STENCIL_ATTACHMENT | TRANSFER_SRC | TRANSFER_DST) and
// ResolveWireDepthStencil's resolve scratch (DEPTH_STENCIL_ATTACHMENT | TRANSFER_SRC).
constexpr VkImageUsageFlags kSourceUsage = VK_IMAGE_USAGE_SAMPLED_BIT |
VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT |
VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT;
constexpr VkImageUsageFlags kScratchUsage =
VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT;
Bool IsFloatDepth(VkFormat format) {
return format == VK_FORMAT_D32_SFLOAT || format == VK_FORMAT_D32_SFLOAT_S8_UINT;
}
Uint32 DepthCopyBytes(VkFormat format) { return format == VK_FORMAT_D16_UNORM ? 2u : 4u; }
Uint32 EncodeDepth(VkFormat format, Float depth) {
if (IsFloatDepth(format)) return std::bit_cast<Uint32>(depth);
const double scale = format == VK_FORMAT_D16_UNORM ? 65535.0 : 16777215.0;
return static_cast<Uint32>(std::lround(static_cast<double>(depth) * scale));
}
Uint32 ReadDepthWord(VkFormat format, const Uint8* texel) {
if (format == VK_FORMAT_D16_UNORM) {
Uint16 word = 0;
std::memcpy(&word, texel, sizeof(word));
return word;
}
Uint32 word = 0;
std::memcpy(&word, texel, sizeof(word));
// A D24 aspect copies out as a 32-bit word whose top byte is undefined.
return IsFloatDepth(format) ? word : (word & 0x00FFFFFFu);
}
Uint32 WordDistance(Uint32 a, Uint32 b) { return a > b ? a - b : b - a; }
struct ProbeImage {
VkImage image = VK_NULL_HANDLE;
VkDeviceMemory memory = VK_NULL_HANDLE;
};
struct ControlPass {
Bool ready = false;
ProbeImage target;
VkRenderPass pass = VK_NULL_HANDLE;
VkPipeline pipeline = VK_NULL_HANDLE;
VkImageView sampledView = VK_NULL_HANDLE;
VkImageView targetView = VK_NULL_HANDLE;
VkFramebuffer framebuffer = VK_NULL_HANDLE;
VkDescriptorSet set = VK_NULL_HANDLE;
VkDeviceSize offset = 0;
};
struct FormatWork {
SizeT reading = 0;
VkFormat format = VK_FORMAT_UNDEFINED;
VkImageAspectFlags aspects = 0;
ProbeImage subjectSource, controlSource, subjectTarget;
VkRenderPass resolvePass = VK_NULL_HANDLE;
VkImageView resolveViews[2]{};
VkFramebuffer resolveFramebuffer = VK_NULL_HANDLE;
VkDeviceSize subjectDepthOffset = 0, subjectStencilOffset = 0;
ControlPass depthControl, stencilControl;
};
// Everything the probe creates, destroyed together (or leaked together on a timeout).
struct ProbeObjects {
VkDevice device = VK_NULL_HANDLE;
Vector<VkImage> images;
Vector<VkDeviceMemory> memories;
Vector<VkImageView> views;
Vector<VkRenderPass> passes;
Vector<VkFramebuffer> framebuffers;
Vector<VkPipeline> pipelines;
VkBuffer buffer = VK_NULL_HANDLE;
VkDescriptorPool descriptorPool = VK_NULL_HANDLE;
VkCommandPool commandPool = VK_NULL_HANDLE;
VkFence fence = VK_NULL_HANDLE;
WireShaderResolveKit kit;
void Destroy() {
for (VkPipeline pipeline : pipelines) vkDestroyPipeline(device, pipeline, nullptr);
for (VkFramebuffer framebuffer : framebuffers) vkDestroyFramebuffer(device, framebuffer, nullptr);
for (VkRenderPass pass : passes) vkDestroyRenderPass(device, pass, nullptr);
for (VkImageView view : views) vkDestroyImageView(device, view, nullptr);
for (VkImage image : images) vkDestroyImage(device, image, nullptr);
vkDestroyBuffer(device, buffer, nullptr);
for (VkDeviceMemory memory : memories) vkFreeMemory(device, memory, nullptr);
vkDestroyDescriptorPool(device, descriptorPool, nullptr);
vkDestroyCommandPool(device, commandPool, nullptr);
vkDestroyFence(device, fence, nullptr);
DestroyWireShaderResolveKit(device, kit);
}
};
Optional<Uint32> PickMemoryType(const VkPhysicalDeviceMemoryProperties& properties, Uint32 allowed,
VkMemoryPropertyFlags wanted, VkMemoryPropertyFlags required) {
Optional<Uint32> fallback;
for (Uint32 i = 0; i < properties.memoryTypeCount; ++i) {
if (!(allowed & (1u << i))) continue;
const VkMemoryPropertyFlags flags = properties.memoryTypes[i].propertyFlags;
if (flags & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) continue;
if ((flags & required) != required) continue;
if ((flags & wanted) == wanted) return i;
if (!fallback) fallback = i;
}
return fallback;
}
void ImageBarrier(VkCommandBuffer commandBuffer, VkImage image, VkImageAspectFlags aspects,
VkImageLayout oldLayout, VkImageLayout newLayout, VkPipelineStageFlags srcStage,
VkAccessFlags srcAccess, VkPipelineStageFlags dstStage, VkAccessFlags dstAccess) {
VkImageMemoryBarrier barrier{VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER};
barrier.srcAccessMask = srcAccess;
barrier.dstAccessMask = dstAccess;
barrier.oldLayout = oldLayout;
barrier.newLayout = newLayout;
barrier.srcQueueFamilyIndex = barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.image = image;
barrier.subresourceRange = {aspects, 0, 1, 0, VK_REMAINING_ARRAY_LAYERS};
vkCmdPipelineBarrier(commandBuffer, srcStage, dstStage, 0, 0, nullptr, 0, nullptr, 1, &barrier);
}
} // namespace
WireDepthResolveProbeMeasurement RunWireDepthResolveProbe(const WireDepthResolveProbeContext& context) {
WireDepthResolveProbeMeasurement measurement;
measurement.subjectElided = context.elideSubject;
const VkDevice device = context.device;
if (device == VK_NULL_HANDLE || context.queue == VK_NULL_HANDLE || context.createRenderPass2 == nullptr) {
measurement.failureReason = "no device, queue or vkCreateRenderPass2";
return measurement;
}
ProbeObjects objects;
objects.device = device;
Bool leak = false;
struct Teardown {
ProbeObjects& objects;
Bool& leak;
~Teardown() {
if (!leak) objects.Destroy();
}
} teardown{objects, leak};
const auto fail = [&](String reason) {
measurement.ran = false;
measurement.failureReason = Move(reason);
return measurement;
};
VkPhysicalDeviceMemoryProperties memoryProperties{};
vkGetPhysicalDeviceMemoryProperties(context.physicalDevice, &memoryProperties);
const auto makeImage = [&](VkFormat format, VkSampleCountFlagBits samples, VkImageUsageFlags usage,
ProbeImage& out) -> Bool {
VkImageCreateInfo info{VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO};
info.imageType = VK_IMAGE_TYPE_2D;
info.format = format;
info.extent = {kProbeExtent, kProbeExtent, 1};
info.mipLevels = info.arrayLayers = 1;
info.samples = samples;
info.tiling = VK_IMAGE_TILING_OPTIMAL;
info.usage = usage;
info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
if (vkCreateImage(device, &info, nullptr, &out.image) != VK_SUCCESS) return false;
objects.images.push_back(out.image);
VkMemoryRequirements requirements{};
vkGetImageMemoryRequirements(device, out.image, &requirements);
const Optional<Uint32> type = PickMemoryType(memoryProperties, requirements.memoryTypeBits,
VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, 0);
if (!type) return false;
VkMemoryAllocateInfo allocate{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO};
allocate.allocationSize = requirements.size;
allocate.memoryTypeIndex = *type;
if (vkAllocateMemory(device, &allocate, nullptr, &out.memory) != VK_SUCCESS) return false;
objects.memories.push_back(out.memory);
return vkBindImageMemory(device, out.image, out.memory, 0) == VK_SUCCESS;
};
const auto makeView = [&](const VkImageViewCreateInfo& info, VkImageView& out) -> Bool {
if (vkCreateImageView(device, &info, nullptr, &out) != VK_SUCCESS) return false;
objects.views.push_back(out);
return true;
};
const auto makeFramebuffer = [&](VkRenderPass pass, const VkImageView* views, Uint32 count,
VkFramebuffer& out) -> Bool {
VkFramebufferCreateInfo info{VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO};
info.renderPass = pass;
info.attachmentCount = count;
info.pAttachments = views;
info.width = info.height = kProbeExtent;
info.layers = 1;
if (vkCreateFramebuffer(device, &info, nullptr, &out) != VK_SUCCESS) return false;
objects.framebuffers.push_back(out);
return true;
};
// The wire's clear (WireFramebuffer.inc, ClearWireFramebuffer): a LOAD/STORE pass over every
// aspect of the format with vkCmdClearAttachments inside it. Recorded later; built now.
struct ClearPass {
VkRenderPass pass = VK_NULL_HANDLE;
VkFramebuffer framebuffer = VK_NULL_HANDLE;
VkImageAspectFlags aspects = 0;
Float depth = 0.0f;
Uint32 stencil = 0;
};
Vector<ClearPass> clears;
const auto makeClear = [&](const ProbeImage& image, VkFormat format, VkSampleCountFlagBits samples,
Float depth, Uint32 stencil) -> Bool {
const VkImageAspectFlags aspects = WireDepthStencilFormatAspects(format);
VkImageView view = VK_NULL_HANDLE;
if (!makeView(WireDepthStencilViewInfo(image.image, format, aspects, 0, 0), view)) return false;
VkAttachmentDescription attachment{};
attachment.format = format;
attachment.samples = samples;
attachment.loadOp = attachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_LOAD;
attachment.storeOp = attachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_STORE;
attachment.initialLayout = attachment.finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
const VkAttachmentReference reference{0, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL};
VkSubpassDescription subpass{};
subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
subpass.pDepthStencilAttachment = &reference;
VkRenderPassCreateInfo info{VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO};
info.attachmentCount = 1;
info.pAttachments = &attachment;
info.subpassCount = 1;
info.pSubpasses = &subpass;
ClearPass clear;
if (vkCreateRenderPass(device, &info, nullptr, &clear.pass) != VK_SUCCESS) return false;
objects.passes.push_back(clear.pass);
if (!makeFramebuffer(clear.pass, &view, 1, clear.framebuffer)) return false;
clear.aspects = aspects;
clear.depth = depth;
clear.stencil = stencil;
clears.push_back(clear);
return true;
};
// THE CONTROL'S FORMAT-INDEPENDENT HALF. A kit that cannot be made leaves every control
// un-run, which the verdict reads as INCONCLUSIVE - never as the bug.
String kitFailure;
if (const VkResult result = CreateWireShaderResolveKit(device, context.shaderStencilExport, objects.kit);
result != VK_SUCCESS)
kitFailure = format("shader resolve kit creation failed (VkResult {})", static_cast<Int>(result));
// Readback layout: every region on a 16-byte boundary (a depth/stencil buffer copy wants a
// multiple of 4).
VkDeviceSize bufferBytes = 0;
const auto reserve = [&](VkDeviceSize bytes) {
const VkDeviceSize offset = bufferBytes;
bufferBytes += (bytes + 15u) & ~VkDeviceSize{15u};
return offset;
};
Vector<FormatWork> work;
for (const ProbeFormat& probeFormat : kProbeFormats) {
WireDepthResolveFormatReading reading;
reading.name = probeFormat.name;
reading.format = static_cast<Int32>(probeFormat.format);
reading.samples = static_cast<Uint32>(kProbeSamples);
const SizeT readingIndex = measurement.formats.size();
measurement.formats.push_back(reading);
auto& slot = measurement.formats.back();
// A skipped format records nothing: the clears it had already built are dropped with it
// (their images stay in `objects` and are only destroyed).
const SizeT clearsBefore = clears.size();
const auto skip = [&](String reason) {
slot.skipReason = Move(reason);
clears.resize(clearsBefore);
};
const VkFormat format = probeFormat.format;
const VkImageAspectFlags aspects = WireDepthStencilFormatAspects(format);
VkFormatProperties formatProperties{};
vkGetPhysicalDeviceFormatProperties(context.physicalDevice, format, &formatProperties);
constexpr VkFormatFeatureFlags kRequired =
VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT | VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT;
if ((formatProperties.optimalTilingFeatures & kRequired) != kRequired) {
skip("not a sampled depth/stencil attachment format here");
continue;
}
VkImageFormatProperties imageProperties{};
if (vkGetPhysicalDeviceImageFormatProperties(context.physicalDevice, format, VK_IMAGE_TYPE_2D,
VK_IMAGE_TILING_OPTIMAL, kSourceUsage, 0,
&imageProperties) != VK_SUCCESS ||
!(imageProperties.sampleCounts & kProbeSamples)) {
skip("no 4x multisample image with the wire's attachment usage");
continue;
}
if (vkGetPhysicalDeviceImageFormatProperties(context.physicalDevice, format, VK_IMAGE_TYPE_2D,
VK_IMAGE_TILING_OPTIMAL, kScratchUsage, 0,
&imageProperties) != VK_SUCCESS) {
skip("no single-sample image with the resolve scratch's usage");
continue;
}
// ResolveWireDepthStencil's own test for the render-pass arm, per format.
if (((aspects & VK_IMAGE_ASPECT_DEPTH_BIT) &&
!(context.depthResolveModes & VK_RESOLVE_MODE_SAMPLE_ZERO_BIT)) ||
((aspects & VK_IMAGE_ASPECT_STENCIL_BIT) &&
!(context.stencilResolveModes & VK_RESOLVE_MODE_SAMPLE_ZERO_BIT))) {
skip("the render-pass arm is not taken for this format (no SAMPLE_ZERO resolve mode)");
continue;
}
FormatWork item;
item.reading = readingIndex;
item.format = format;
item.aspects = aspects;
if (!makeImage(format, kProbeSamples, kSourceUsage, item.subjectSource) ||
!makeImage(format, kProbeSamples, kSourceUsage, item.controlSource) ||
!makeImage(format, VK_SAMPLE_COUNT_1_BIT, kScratchUsage, item.subjectTarget)) {
skip("image creation failed");
continue;
}
if (CreateWireDepthStencilResolvePass(context.createRenderPass2, device, format, kProbeSamples,
&item.resolvePass) != VK_SUCCESS) {
skip("the render-pass arm's vkCreateRenderPass2 failed");
continue;
}
objects.passes.push_back(item.resolvePass);
if (!makeView(WireDepthStencilViewInfo(item.subjectSource.image, format, aspects, 0, 0),
item.resolveViews[0]) ||
!makeView(WireDepthStencilViewInfo(item.subjectTarget.image, format, aspects, 0, 0),
item.resolveViews[1]) ||
!makeFramebuffer(item.resolvePass, item.resolveViews, 2, item.resolveFramebuffer)) {
skip("the render-pass arm's views or framebuffer could not be created");
continue;
}
if (!makeClear(item.subjectSource, format, kProbeSamples, kClearDepth, kClearStencil) ||
!makeClear(item.controlSource, format, kProbeSamples, kClearDepth, kClearStencil) ||
!makeClear(item.subjectTarget, format, VK_SAMPLE_COUNT_1_BIT, kSentinelDepth, kSentinelStencil)) {
skip("the clear passes could not be created");
continue;
}
// The control, one target per aspect: the shader pass's attachment is DONT_CARE on both
// aspects, so a second aspect's pass into the same target would discard the first.
const auto makeControl = [&](VkImageAspectFlags aspect, ControlPass& control) {
if (!kitFailure.empty()) return;
if (aspect == VK_IMAGE_ASPECT_STENCIL_BIT && objects.kit.stencilFragment == VK_NULL_HANDLE) return;
if (!makeImage(format, VK_SAMPLE_COUNT_1_BIT, kScratchUsage, control.target)) return;
if (CreateWireShaderResolveRenderPass(device, format, &control.pass) != VK_SUCCESS) return;
objects.passes.push_back(control.pass);
if (CreateWireShaderResolvePipeline(device, objects.kit, control.pass, aspect, &control.pipeline) !=
VK_SUCCESS)
return;
objects.pipelines.push_back(control.pipeline);
if (!makeView(WireDepthStencilViewInfo(item.controlSource.image, format, aspect, 0, 0),
control.sampledView) ||
!makeView(WireDepthStencilViewInfo(control.target.image, format, aspects, 0, 0),
control.targetView) ||
!makeFramebuffer(control.pass, &control.targetView, 1, control.framebuffer))
return;
if (!makeClear(control.target, format, VK_SAMPLE_COUNT_1_BIT, kSentinelDepth, kSentinelStencil))
return;
control.ready = true;
};
if (aspects & VK_IMAGE_ASPECT_DEPTH_BIT) makeControl(VK_IMAGE_ASPECT_DEPTH_BIT, item.depthControl);
if (aspects & VK_IMAGE_ASPECT_STENCIL_BIT) makeControl(VK_IMAGE_ASPECT_STENCIL_BIT, item.stencilControl);
if (aspects & VK_IMAGE_ASPECT_DEPTH_BIT) {
item.subjectDepthOffset = reserve(kProbeTexels * DepthCopyBytes(format));
if (item.depthControl.ready) item.depthControl.offset = reserve(kProbeTexels * DepthCopyBytes(format));
}
if (aspects & VK_IMAGE_ASPECT_STENCIL_BIT) {
item.subjectStencilOffset = reserve(kProbeTexels);
if (item.stencilControl.ready) item.stencilControl.offset = reserve(kProbeTexels);
}
slot.ran = true;
work.push_back(item);
}
if (work.empty()) return fail("no format could be probed");
// Descriptor sets for the controls, one per draw (the production shader arm's own rule).
Uint32 controlDraws = 0;
for (const FormatWork& item : work)
controlDraws += (item.depthControl.ready ? 1u : 0u) + (item.stencilControl.ready ? 1u : 0u);
if (controlDraws > 0) {
const VkDescriptorPoolSize poolSize{VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, controlDraws};
VkDescriptorPoolCreateInfo pool{VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO};
pool.maxSets = controlDraws;
pool.poolSizeCount = 1;
pool.pPoolSizes = &poolSize;
if (vkCreateDescriptorPool(device, &pool, nullptr, &objects.descriptorPool) != VK_SUCCESS)
return fail("vkCreateDescriptorPool failed");
for (FormatWork& item : work) {
for (ControlPass* control : {&item.depthControl, &item.stencilControl}) {
if (!control->ready) continue;
VkDescriptorSetAllocateInfo alloc{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO};
alloc.descriptorPool = objects.descriptorPool;
alloc.descriptorSetCount = 1;
alloc.pSetLayouts = &objects.kit.descriptorLayout;
if (vkAllocateDescriptorSets(device, &alloc, &control->set) != VK_SUCCESS)
return fail("vkAllocateDescriptorSets failed");
const VkDescriptorImageInfo sampled{objects.kit.nearest, control->sampledView,
VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL};
VkWriteDescriptorSet write{VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET};
write.dstSet = control->set;
write.dstBinding = 0;
write.descriptorCount = 1;
write.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
write.pImageInfo = &sampled;
vkUpdateDescriptorSets(device, 1, &write, 0, nullptr);
}
}
}
// The host-visible readback buffer.
VkDeviceMemory bufferMemory = VK_NULL_HANDLE;
Bool bufferCoherent = false;
{
VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO};
info.size = bufferBytes;
info.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT;
info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
if (vkCreateBuffer(device, &info, nullptr, &objects.buffer) != VK_SUCCESS)
return fail("vkCreateBuffer failed");
VkMemoryRequirements requirements{};
vkGetBufferMemoryRequirements(device, objects.buffer, &requirements);
const Optional<Uint32> type =
PickMemoryType(memoryProperties, requirements.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT);
if (!type) return fail("no host-visible memory type for the readback buffer");
bufferCoherent = (memoryProperties.memoryTypes[*type].propertyFlags &
VK_MEMORY_PROPERTY_HOST_COHERENT_BIT) != 0;
VkMemoryAllocateInfo allocate{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO};
allocate.allocationSize = requirements.size;
allocate.memoryTypeIndex = *type;
if (vkAllocateMemory(device, &allocate, nullptr, &bufferMemory) != VK_SUCCESS)
return fail("vkAllocateMemory (readback) failed");
objects.memories.push_back(bufferMemory);
if (vkBindBufferMemory(device, objects.buffer, bufferMemory, 0) != VK_SUCCESS)
return fail("vkBindBufferMemory failed");
}
VkCommandPoolCreateInfo poolInfo{VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO};
poolInfo.flags = VK_COMMAND_POOL_CREATE_TRANSIENT_BIT;
poolInfo.queueFamilyIndex = context.queueFamilyIndex;
if (vkCreateCommandPool(device, &poolInfo, nullptr, &objects.commandPool) != VK_SUCCESS)
return fail("vkCreateCommandPool failed");
VkCommandBufferAllocateInfo commandInfo{VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO};
commandInfo.commandPool = objects.commandPool;
commandInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
commandInfo.commandBufferCount = 1;
VkCommandBuffer cmd = VK_NULL_HANDLE;
if (vkAllocateCommandBuffers(device, &commandInfo, &cmd) != VK_SUCCESS)
return fail("vkAllocateCommandBuffers failed");
VkCommandBufferBeginInfo beginInfo{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO};
beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
if (vkBeginCommandBuffer(cmd, &beginInfo) != VK_SUCCESS) return fail("vkBeginCommandBuffer failed");
const VkRect2D fullRect{{0, 0}, {kProbeExtent, kProbeExtent}};
// (1) Every image UNDEFINED -> DEPTH_STENCIL_ATTACHMENT_OPTIMAL, the way TransitionWireImage
// moves a fresh image (source state from UNDEFINED, destination ALL_COMMANDS).
for (const FormatWork& item : work) {
const VkImage images[] = {item.subjectSource.image, item.controlSource.image, item.subjectTarget.image,
item.depthControl.ready ? item.depthControl.target.image : VK_NULL_HANDLE,
item.stencilControl.ready ? item.stencilControl.target.image : VK_NULL_HANDLE};
for (const VkImage image : images) {
if (image == VK_NULL_HANDLE) continue;
ImageBarrier(cmd, image, item.aspects, VK_IMAGE_LAYOUT_UNDEFINED,
VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, 0,
VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT);
}
}
// (2) The inputs and the sentinels, cleared the wire's way.
for (const ClearPass& clear : clears) {
VkRenderPassBeginInfo begin{VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO};
begin.renderPass = clear.pass;
begin.framebuffer = clear.framebuffer;
begin.renderArea = fullRect;
vkCmdBeginRenderPass(cmd, &begin, VK_SUBPASS_CONTENTS_INLINE);
VkClearAttachment attachment{};
attachment.aspectMask = clear.aspects;
attachment.clearValue.depthStencil = {clear.depth, clear.stencil};
const VkClearRect rect{fullRect, 0, 1};
vkCmdClearAttachments(cmd, 1, &attachment, 1, &rect);
vkCmdEndRenderPass(cmd);
}
// (3) What TransitionWireImage records when the layout already matches - the case of a
// source the application cleared and then resolves.
{
VkMemoryBarrier memory{VK_STRUCTURE_TYPE_MEMORY_BARRIER};
memory.srcAccessMask = VK_ACCESS_MEMORY_WRITE_BIT;
memory.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT;
vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, 1,
&memory, 0, nullptr, 0, nullptr);
}
// (4) THE SUBJECT: the render-pass arm, begun and ended with no draw. Under the test-only
// elideSubject it is not recorded at all: its target keeps the sentinel cleared in (2) and
// the layout it was left in, which is what (6) expects either way.
if (!context.elideSubject) {
for (const FormatWork& item : work) {
VkRenderPassBeginInfo begin{VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO};
begin.renderPass = item.resolvePass;
begin.framebuffer = item.resolveFramebuffer;
begin.renderArea = fullRect;
vkCmdBeginRenderPass(cmd, &begin, VK_SUBPASS_CONTENTS_INLINE);
vkCmdEndRenderPass(cmd);
}
}
// (5) THE CONTROL: the shader arm on the twin source, which TransitionWireImage moves to
// SHADER_READ_ONLY_OPTIMAL first (both aspects of a packed format).
for (const FormatWork& item : work) {
if (!item.depthControl.ready && !item.stencilControl.ready) continue;
ImageBarrier(cmd, item.controlSource.image, item.aspects, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL,
VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT,
VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT,
VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT);
for (const ControlPass* control : {&item.depthControl, &item.stencilControl}) {
if (!control->ready) continue;
RecordWireShaderResolveDraw(cmd, objects.kit, control->pass, control->pipeline, control->framebuffer,
control->set, {kProbeExtent, kProbeExtent}, fullRect);
}
}
// (6) Every target to TRANSFER_SRC with the barrier ResolveWireDepthStencil puts after its
// resolve (a depth/stencil resolve writes in COLOR_ATTACHMENT_OUTPUT), then one copy per aspect.
const auto copyOut = [&](VkImage image, VkImageAspectFlags aspect, VkDeviceSize offset) {
VkBufferImageCopy copy{};
copy.bufferOffset = offset;
copy.imageSubresource = {aspect, 0, 0, 1};
copy.imageExtent = {kProbeExtent, kProbeExtent, 1};
vkCmdCopyImageToBuffer(cmd, image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, objects.buffer, 1, &copy);
};
const auto toTransfer = [&](VkImage image, VkImageAspectFlags aspects) {
ImageBarrier(cmd, image, aspects, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL,
VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT | VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT |
VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT,
VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT,
VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_TRANSFER_READ_BIT);
};
for (const FormatWork& item : work) {
toTransfer(item.subjectTarget.image, item.aspects);
if (item.aspects & VK_IMAGE_ASPECT_DEPTH_BIT)
copyOut(item.subjectTarget.image, VK_IMAGE_ASPECT_DEPTH_BIT, item.subjectDepthOffset);
if (item.aspects & VK_IMAGE_ASPECT_STENCIL_BIT)
copyOut(item.subjectTarget.image, VK_IMAGE_ASPECT_STENCIL_BIT, item.subjectStencilOffset);
if (item.depthControl.ready) {
toTransfer(item.depthControl.target.image, item.aspects);
copyOut(item.depthControl.target.image, VK_IMAGE_ASPECT_DEPTH_BIT, item.depthControl.offset);
}
if (item.stencilControl.ready) {
toTransfer(item.stencilControl.target.image, item.aspects);
copyOut(item.stencilControl.target.image, VK_IMAGE_ASPECT_STENCIL_BIT, item.stencilControl.offset);
}
}
{
VkBufferMemoryBarrier barrier{VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER};
barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
barrier.dstAccessMask = VK_ACCESS_HOST_READ_BIT;
barrier.srcQueueFamilyIndex = barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.buffer = objects.buffer;
barrier.size = VK_WHOLE_SIZE;
vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_HOST_BIT, 0, 0, nullptr, 1,
&barrier, 0, nullptr);
}
if (vkEndCommandBuffer(cmd) != VK_SUCCESS) return fail("vkEndCommandBuffer failed");
VkFenceCreateInfo fenceInfo{VK_STRUCTURE_TYPE_FENCE_CREATE_INFO};
if (vkCreateFence(device, &fenceInfo, nullptr, &objects.fence) != VK_SUCCESS)
return fail("vkCreateFence failed");
VkSubmitInfo submit{VK_STRUCTURE_TYPE_SUBMIT_INFO};
submit.commandBufferCount = 1;
submit.pCommandBuffers = &cmd;
if (const VkResult result = vkQueueSubmit(context.queue, 1, &submit, objects.fence); result != VK_SUCCESS)
return fail(format("vkQueueSubmit failed (VkResult {})", static_cast<Int>(result)));
const VkResult waited = vkWaitForFences(device, 1, &objects.fence, VK_TRUE, kFenceTimeoutNs);
if (waited == VK_TIMEOUT) {
// The submission may still be executing: destroying anything it names, or idle-waiting
// the device, is the hang the bound exists to prevent. Everything leaks.
leak = true;
measurement.fenceWaitTimedOut = true;
return fail("the probe's fence did not signal within 5 s");
}
if (waited != VK_SUCCESS) return fail(format("vkWaitForFences failed (VkResult {})", static_cast<Int>(waited)));
void* mapped = nullptr;
if (vkMapMemory(device, bufferMemory, 0, VK_WHOLE_SIZE, 0, &mapped) != VK_SUCCESS || mapped == nullptr)
return fail("vkMapMemory failed");
if (!bufferCoherent) {
VkMappedMemoryRange range{VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE};
range.memory = bufferMemory;
range.size = VK_WHOLE_SIZE;
vkInvalidateMappedMemoryRanges(device, 1, &range);
}
const Uint8* bytes = static_cast<const Uint8*>(mapped);
const auto tally = [&](WireDepthResolveAspectReading& aspect, VkDeviceSize offset, Uint32 texelBytes,
Bool depth, VkFormat format, Bool subject) {
Uint32 matches = 0, sentinels = 0, first = 0;
for (Uint32 i = 0; i < kProbeTexels; ++i) {
const Uint8* texel = bytes + offset + static_cast<VkDeviceSize>(i) * texelBytes;
const Uint32 word = depth ? ReadDepthWord(format, texel) : static_cast<Uint32>(*texel);
if (i == 0) first = word;
if (WordDistance(word, aspect.expected) <= aspect.tolerance) ++matches;
if (WordDistance(word, aspect.sentinel) <= aspect.tolerance) ++sentinels;
}
if (subject) {
aspect.renderPassMatches = matches;
aspect.renderPassSentinels = sentinels;
aspect.renderPassFirst = first;
} else {
aspect.shaderRan = true;
aspect.shaderMatches = matches;
aspect.shaderFirst = first;
}
};
for (const FormatWork& item : work) {
WireDepthResolveFormatReading& reading = measurement.formats[item.reading];
if (item.aspects & VK_IMAGE_ASPECT_DEPTH_BIT) {
auto& aspect = reading.depth;
aspect.measured = true;
aspect.texels = kProbeTexels;
aspect.expected = EncodeDepth(item.format, kClearDepth);
aspect.sentinel = EncodeDepth(item.format, kSentinelDepth);
aspect.tolerance = IsFloatDepth(item.format) ? 0u : 1u;
tally(aspect, item.subjectDepthOffset, DepthCopyBytes(item.format), true, item.format, true);
if (item.depthControl.ready)
tally(aspect, item.depthControl.offset, DepthCopyBytes(item.format), true, item.format, false);
}
if (item.aspects & VK_IMAGE_ASPECT_STENCIL_BIT) {
auto& aspect = reading.stencil;
aspect.measured = true;
aspect.texels = kProbeTexels;
aspect.expected = kClearStencil;
aspect.sentinel = kSentinelStencil;
aspect.tolerance = 0;
tally(aspect, item.subjectStencilOffset, 1, false, item.format, true);
if (item.stencilControl.ready)
tally(aspect, item.stencilControl.offset, 1, false, item.format, false);
}
}
vkUnmapMemory(device, bufferMemory);
measurement.ran = true;
if (!kitFailure.empty()) measurement.failureReason = kitFailure;
return measurement;
}
WireDepthResolveProbeMeasurement RunWireDepthResolveProbeOnThrowawayDevice(
PFN_vkGetInstanceProcAddr getInstanceProcAddr, VkInstance instance, VkPhysicalDevice physicalDevice,
Uint32 graphicsQueueFamilyIndex, const Vector<VkExtensionProperties>& deviceExtensions,
Bool& renderPassArmAvailable, Bool& shaderStencilExport) {
WireDepthResolveProbeMeasurement measurement;
const auto has = [&](const char* name) {
for (const VkExtensionProperties& extension : deviceExtensions)
if (std::strcmp(extension.extensionName, name) == 0) return true;
return false;
};
renderPassArmAvailable = has(VK_KHR_CREATE_RENDERPASS_2_EXTENSION_NAME) &&
has(VK_KHR_DEPTH_STENCIL_RESOLVE_EXTENSION_NAME);
shaderStencilExport = has(VK_EXT_SHADER_STENCIL_EXPORT_EXTENSION_NAME);
if (!renderPassArmAvailable) {
measurement.failureReason = "no VK_KHR_create_renderpass2 + VK_KHR_depth_stencil_resolve";
return measurement;
}
VkPhysicalDeviceProperties properties{};
vkGetPhysicalDeviceProperties(physicalDevice, &properties);
auto getProperties2 = reinterpret_cast<PFN_vkGetPhysicalDeviceProperties2>(
getInstanceProcAddr(instance, "vkGetPhysicalDeviceProperties2"));
if (getProperties2 == nullptr)
getProperties2 = reinterpret_cast<PFN_vkGetPhysicalDeviceProperties2>(
getInstanceProcAddr(instance, "vkGetPhysicalDeviceProperties2KHR"));
const auto createDevice =
reinterpret_cast<PFN_vkCreateDevice>(getInstanceProcAddr(instance, "vkCreateDevice"));
if (properties.apiVersion < VK_API_VERSION_1_1 || getProperties2 == nullptr || createDevice == nullptr) {
renderPassArmAvailable = false;
measurement.failureReason = "a pre-1.1 device, or no vkGetPhysicalDeviceProperties2 / vkCreateDevice";
return measurement;
}
VkPhysicalDeviceDepthStencilResolveProperties resolveProperties{
VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DEPTH_STENCIL_RESOLVE_PROPERTIES};
VkPhysicalDeviceProperties2 properties2{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2};
properties2.pNext = &resolveProperties;
getProperties2(physicalDevice, &properties2);
// The renderer's own extension set for the two arms (VulkanRenderer.cpp,
// CreateLogicalDeviceAndQueues), nothing more.
const Float priority = 1.0f;
VkDeviceQueueCreateInfo queueInfo{VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO};
queueInfo.queueFamilyIndex = graphicsQueueFamilyIndex;
queueInfo.queueCount = 1;
queueInfo.pQueuePriorities = &priority;
Vector<const char*> extensions{VK_KHR_CREATE_RENDERPASS_2_EXTENSION_NAME,
VK_KHR_DEPTH_STENCIL_RESOLVE_EXTENSION_NAME};
if (shaderStencilExport) extensions.push_back(VK_EXT_SHADER_STENCIL_EXPORT_EXTENSION_NAME);
VkDeviceCreateInfo deviceInfo{VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO};
deviceInfo.queueCreateInfoCount = 1;
deviceInfo.pQueueCreateInfos = &queueInfo;
deviceInfo.enabledExtensionCount = static_cast<Uint32>(extensions.size());
deviceInfo.ppEnabledExtensionNames = extensions.data();
VkDevice device = VK_NULL_HANDLE;
if (const VkResult result = createDevice(physicalDevice, &deviceInfo, nullptr, &device);
result != VK_SUCCESS || device == VK_NULL_HANDLE) {
measurement.failureReason = format("vkCreateDevice failed (VkResult {})", static_cast<Int>(result));
return measurement;
}
WireDepthResolveProbeContext context;
context.physicalDevice = physicalDevice;
context.device = device;
vkGetDeviceQueue(device, graphicsQueueFamilyIndex, 0, &context.queue);
context.queueFamilyIndex = graphicsQueueFamilyIndex;
context.createRenderPass2 =
reinterpret_cast<PFN_vkCreateRenderPass2>(vkGetDeviceProcAddr(device, "vkCreateRenderPass2KHR"));
context.depthResolveModes = resolveProperties.supportedDepthResolveModes;
context.stencilResolveModes = resolveProperties.supportedStencilResolveModes;
context.shaderStencilExport = shaderStencilExport;
measurement = RunWireDepthResolveProbe(context);
// A timed-out probe leaked its children on purpose; destroying their device would block
// exactly where the bound says not to.
if (!measurement.fenceWaitTimedOut) vkDestroyDevice(device, nullptr);
return measurement;
}
} // namespace MobileGL::MG_Backend::DirectVulkan
#endif
@@ -1,121 +0,0 @@
// MobileGL - MobileGL/MG_Backend/DirectVulkan/Renderer/WireDepthResolveProbe.h
// Copyright (c) 2026 MobileGL-Dev
// Licensed under the GNU Lesser General Public License v3.0:
// https://www.gnu.org/licenses/gpl-3.0.txt
// https://www.gnu.org/licenses/lgpl-3.0.txt
// SPDX-License-Identifier: LGPL-3.0-only
// End of Source File Header
#pragma once
#include "WireDepthResolveArm.h"
#include <Config.h>
#include <Includes.h>
// P7 gate 5 (g5-msprobe): the Vulkan half of the multisample depth/stencil resolve probe, and the
// two resolve arms it measures.
//
// THE ARMS LIVE HERE, NOT ONLY IN THE RENDERER. A probe that rebuilt "something like" the wire's
// render pass would measure its own copy; the render-pass description, the shader pass's modules,
// pipeline and draw, and the view shapes both arms attach are defined once below and called by
// ResolveWireDepthStencil (WireFramebuffer.inc), ResolveWireDepthStencilWithShader
// (WireMultisampleResolve.inc) and the probe alike.
//
// Two callers: the Magma renderer at device bring-up (server side, once per process, only where
// the render-pass arm exists at all - VulkanRenderer::ArmWireDepthResolveOrder) and the POST's
// "Known Driver Bugs" section (MG_Util/SelfTest/DriverBugProbes.cpp) on a throwaway device.
//
// Disaggregated builds only: the monolith never records either arm, and the pull build's image
// must not change (P7 gate G1).
#if MOBILEGL_BUILD_DISAGGREGATED
namespace MobileGL::MG_Backend::DirectVulkan {
// Every aspect a wire depth/stencil format has.
VkImageAspectFlags WireDepthStencilFormatAspects(VkFormat format);
// A 2D view of one level/layer of a depth/stencil image naming `aspects`. The render-pass arm
// attaches both images with every aspect of the format; the shader arm SAMPLES its source
// through a view of exactly one aspect (a depth/stencil image can only be sampled that way) and
// attaches its target with every aspect.
VkImageViewCreateInfo WireDepthStencilViewInfo(VkImage image, VkFormat format, VkImageAspectFlags aspects,
Uint32 level, Uint32 layer);
// THE RENDER-PASS ARM: attachment 0 the multisample source (LOAD/STORE), attachment 1 the
// single-sample resolve target (DONT_CARE/STORE), both in DEPTH_STENCIL_ATTACHMENT_OPTIMAL, one
// subpass whose VkSubpassDescriptionDepthStencilResolve resolves every aspect of the format
// with VK_RESOLVE_MODE_SAMPLE_ZERO_BIT. The caller begins and ends it with NO draw.
VkResult CreateWireDepthStencilResolvePass(PFN_vkCreateRenderPass2 createRenderPass2, VkDevice device,
VkFormat format, VkSampleCountFlagBits samples, VkRenderPass* pass);
// THE SHADER ARM's device objects that do not depend on the format.
struct WireShaderResolveKit {
VkShaderModule vertex = VK_NULL_HANDLE;
VkShaderModule depthFragment = VK_NULL_HANDLE;
// Only where VK_EXT_shader_stencil_export is enabled: its SPIR-V declares StencilExportEXT.
VkShaderModule stencilFragment = VK_NULL_HANDLE;
VkDescriptorSetLayout descriptorLayout = VK_NULL_HANDLE;
VkPipelineLayout pipelineLayout = VK_NULL_HANDLE;
VkSampler nearest = VK_NULL_HANDLE;
};
// Creates every member; the first failure is returned and the members made so far stay set,
// for DestroyWireShaderResolveKit.
VkResult CreateWireShaderResolveKit(VkDevice device, Bool shaderStencilExport, WireShaderResolveKit& kit);
void DestroyWireShaderResolveKit(VkDevice device, WireShaderResolveKit& kit);
// One (format, aspect)'s single-attachment render pass: DONT_CARE/STORE on both aspects,
// DEPTH_STENCIL_ATTACHMENT_OPTIMAL throughout.
VkResult CreateWireShaderResolveRenderPass(VkDevice device, VkFormat format, VkRenderPass* pass);
// Its pipeline: full-screen triangle, gl_FragDepth (ALWAYS + write) or gl_FragStencilRefARB
// (REPLACE everywhere), viewport and scissor dynamic. VK_ERROR_FEATURE_NOT_PRESENT when the kit
// has no fragment module for `aspect`.
VkResult CreateWireShaderResolvePipeline(VkDevice device, const WireShaderResolveKit& kit, VkRenderPass pass,
VkImageAspectFlags aspect, VkPipeline* pipeline);
// Records the draw: the render area and the scissor are `rect`, the viewport is the WHOLE
// attachment (gl_FragCoord is what the fragment stage fetches by), one triangle.
void RecordWireShaderResolveDraw(VkCommandBuffer commandBuffer, const WireShaderResolveKit& kit,
VkRenderPass pass, VkPipeline pipeline, VkFramebuffer framebuffer,
VkDescriptorSet descriptorSet, VkExtent2D attachmentExtent, VkRect2D rect);
// What the probe runs on. The device must have been created with VK_KHR_create_renderpass2 and
// VK_KHR_depth_stencil_resolve (or Vulkan 1.2 core), and with VK_EXT_shader_stencil_export where
// `shaderStencilExport` says so. The queue must be otherwise idle for the probe's duration.
struct WireDepthResolveProbeContext {
VkPhysicalDevice physicalDevice = VK_NULL_HANDLE;
VkDevice device = VK_NULL_HANDLE;
VkQueue queue = VK_NULL_HANDLE;
Uint32 queueFamilyIndex = 0;
PFN_vkCreateRenderPass2 createRenderPass2 = nullptr;
VkResolveModeFlags depthResolveModes = 0;
VkResolveModeFlags stencilResolveModes = 0;
Bool shaderStencilExport = false;
// TEST ONLY (MGITEST_MAGMA_DEPTH_RESOLVE_PROBE=elide-subject, WireDepthResolveArm.h): record
// NO render-pass resolve, so every subject target keeps its sentinel - the Adreno 830's
// reading - while the shader control runs as always. Everything else is the real probe.
Bool elideSubject = false;
};
// Per format the device can host as a 4x multisample depth/stencil attachment AND for which
// ResolveWireDepthStencil would take the render-pass arm (D16, X8_D24, D32F, D24S8, D32FS8, S8):
// - two identical 4x4 4x multisample sources (production usage), each cleared to depth 0.25 /
// stencil 0x5A the way the wire clears (a LOAD pass with vkCmdClearAttachments);
// - single-sample resolve targets (the production scratch usage) pre-filled with the sentinel
// depth 0.75 / stencil 0xA5;
// - SUBJECT: the render-pass arm's exact pass, begun and ended with no draw;
// - CONTROL: the shader arm's exact pass on the other source, one target per aspect (stencil
// only with VK_EXT_shader_stencil_export);
// - every target copied aspect by aspect into a host-visible buffer and compared texel by texel.
// One submission, a bounded fence wait (on timeout every object is leaked and the measurement
// says so - the caller must then not destroy or idle-wait the device), teardown on every other
// path. Never touches renderer state.
WireDepthResolveProbeMeasurement RunWireDepthResolveProbe(const WireDepthResolveProbeContext& context);
// The POST's entry: creates a throwaway device on `physicalDevice` with exactly the extensions
// the renderer enables for the two arms, runs the probe on its graphics queue and destroys the
// device (leaks it on a fence timeout). `renderPassArmAvailable` is false - and nothing is run -
// when the device lacks VK_KHR_create_renderpass2 / VK_KHR_depth_stencil_resolve; the shader
// pass is then the only arm and the probe has nothing to choose between.
// `shaderStencilExport` reports whether VK_EXT_shader_stencil_export was available.
WireDepthResolveProbeMeasurement RunWireDepthResolveProbeOnThrowawayDevice(
PFN_vkGetInstanceProcAddr getInstanceProcAddr, VkInstance instance, VkPhysicalDevice physicalDevice,
Uint32 graphicsQueueFamilyIndex, const Vector<VkExtensionProperties>& deviceExtensions,
Bool& renderPassArmAvailable, Bool& shaderStencilExport);
} // namespace MobileGL::MG_Backend::DirectVulkan
#endif
@@ -11,13 +11,9 @@
return MagmaProgramSource(handle, records[index]);
}
// Through the same seam as MagmaWireFatal, and for the same reason (P7 wave 0). The family
// stays RoleViolation: reaching the legacy buffer arm inside a Magma server is a role
// invariant the two halves must hold, not a verb the wire failed to migrate.
[[noreturn]] static void WireBufferLegacyFatal() {
MG_Pipe::MGPipeSessionFail(
MG_Pipe::MGPipeFatalFamily::RoleViolation,
"MGPipe: Fatal{RoleViolation, \"buffer-legacy-arm\"} (Magma P7 buffer consumer)");
MGLOG_F("MGPipe: Fatal{RoleViolation, \"buffer-legacy-arm\"} (Magma P7 buffer consumer)");
std::abort();
}
static const MG_Pipe::MGPStreamOutputBegin& WireXfbSpan() {
@@ -203,10 +199,7 @@
Flags<DrawSetupAspect> aspects, const DrawCmdParam& drawParams, const IndexBufferView* indices) {
auto& state = MG_Pipe::MGPipeApplier();
const auto program = WireProgramSource(state.BoundShaderCso);
if (!program.GetLinkStatus() || !program.GetSpirvStatus()) {
MGL_WIRE_DECLINE_AT(ProgramLinkOrSpirv, "program is not linked or carries no SPIR-V");
return false;
}
if (!program.GetLinkStatus() || !program.GetSpirvStatus()) return false;
if (aspects & DrawSetupAspect::IndirectDrawBuffer)
WireBufferLegacyFatal();
MakeXfbWritesVisible();
@@ -227,16 +220,10 @@
flags |= ProgramFactory::CompileOptionBit::ZeroBaseVertex;
programObject = &m_programFactory->GetOrCreateProgram(program, flags);
}
if (programObject->pointSizeCapabilityUnsupported) {
MGL_WIRE_DECLINE_AT(PointSizeCapability, "the program writes gl_PointSize and the device cannot express it");
return false;
}
if (programObject->pointSizeCapabilityUnsupported) return false;
const auto& programObj = *programObject;
m_currentDrawXfbCaptureDeclined = programObj.xfbCaptureDeclined;
if (!m_uniformManager->PrepareWireTextureResources(program, programObj)) {
MGL_WIRE_DECLINE_AT(TextureResourcesUnprepared, "a sampled/storage image could not be made ready; see the Tex* tally");
return false;
}
if (!m_uniformManager->PrepareWireTextureResources(program, programObj)) return false;
// Lazy image uploads/promotions can submit the old recording. Resolve
// ALL attachments before descriptor binding captures the current cmd.
for (Uint32 i = 0; i < MG_Pipe::kMGPipeMaxColorAttachments; ++i) {
@@ -254,41 +241,8 @@
const auto& vao = state.VertexElementsCsos[vaoHandle.Slot];
if (!vao.Live || vao.Gen != vaoHandle.Gen) MagmaWireFatal("vertex-elements-generation");
VertexInputStateFactory::BackendVertexInputState input{};
// P7 wave 2 package C, CONTRACT-P7 §3.2: THE `vertex-layout` ROW IS RETIRED AND SPLIT.
//
// A false is now ONE reason and only one - `buffer-window`, an enabled attribute the
// program reads whose slot lies outside the window set_vertex_buffers published. That
// is a disagreement about what crossed, not about what this device can express, so it
// keeps a named Fatal through the hook (MGPipeSessionFail -> Session::Fail, which is
// what rule I asks of a refusal that must stay a refusal). It is the check that caught
// the Redmi VAO hash collision fixed in 376c04be, which is why it is not softened.
// The P7 marker is gone from the detail string with the abort: this is a permanent
// protocol error, not a shape the split path has yet to migrate, so it must not keep
// counting against the census of unmigrated refusals (scripts/ci/fatal_census.py
// counts the marker literally, which is also why no comment in this package spells it).
if (!m_vertexInputStateFactory->BuildWireVertexInput(vao, state,
programObj.activeVertexInputLocationMask, input))
MagmaWireFatal("vertex-layout-buffer-window");
// The seven device/format reasons are now MASKED OUT of the vertex input state, and
// this is the monolith arm's pre-flight for them, statement for statement
// (VulkanRenderer.cpp's SetupDraw: "Fail loudly rather than render wrong pixels"). An
// enabled array with no usable VkFormat never reaches the vertex input state, which
// makes it indistinguishable from a DISABLED one - and a disabled one is answered
// below by uploading the current attribute value, so without this check the draw would
// quietly feed the shader a constant in place of the application's vertex data.
//
// A DECLINE, NOT A FATAL (rule I (a)): the draw is skipped, the reason is named once,
// and the observable is the monolith lane's for the same VAO on the same device.
// BuildWireVertexInput only considers attributes the program reads, so a masked bit is
// always an active one and this predicate is the whole of the difference.
if ((input.unsupportedAttribMask & programObj.activeVertexInputLocationMask) != 0) {
MGLOG_E_ONCE("Magma wire draw skipped: program=%u reads vertex attribute location "
"mask 0x%x whose enabled array has no supported vertex format",
program.GetExternalIndex(),
input.unsupportedAttribMask & programObj.activeVertexInputLocationMask);
WireDeclineTally::Count(WireDeclineSite::VertexFormatUnsupported);
return false;
}
programObj.activeVertexInputLocationMask, input)) MagmaWireFatal("vertex-layout@P7");
Vector<BufferSlice> vertexSlices(input.bindings.size());
for (SizeT binding = 0; binding < input.bindings.size(); ++binding) {
const Uint32 location = input.bindingAttributeLocations[binding];
@@ -301,10 +255,7 @@
const VkDeviceSize offset = input.bindingBaseOffsets[binding];
const auto type = static_cast<DataType>(attr.Type);
const SizeT elementSize = VertexInputStateFactory::GetAttributeByteSize(type, attr.Size, attr.IsBgra);
if (offset > slice.size || elementSize > slice.size - offset) {
MGL_WIRE_DECLINE_AT(VertexAttributeWindow, "an enabled attribute's first element lies outside its buffer");
return false;
}
if (offset > slice.size || elementSize > slice.size - offset) return false;
const auto conversion = input.bindingConversions[binding];
if (conversion != VertexInputStateFactory::VertexStreamConversion::None) {
const SizeT stride = static_cast<SizeT>(attr.Stride);
@@ -313,38 +264,14 @@
// name arbitrary vertices, so preserve the entire valid source stream.
if (stride && !(aspects & DrawSetupAspect::IndexBuffer) && !resource.Divisor)
count = std::min<SizeT>(count, static_cast<SizeT>(drawParams.firstVertex) + drawParams.vertexCount);
if (!count) {
MGL_WIRE_DECLINE_AT(VertexStreamCountZero, "the converted vertex stream would hold no elements");
return false;
}
if (!count) return false;
Vector<Uint8> source((count - 1) * stride + elementSize);
if (!m_bufferManager.ReadWireBuffer(resource.Res, offset, source.size(), source.data())) {
MGL_WIRE_DECLINE_AT(VertexStreamRead, "the vertex bytes to convert could not be read back");
return false;
}
if (!m_bufferManager.ReadWireBuffer(resource.Res, offset, source.size(), source.data())) return false;
Vector<Uint8> converted;
// P7 wave 2 package C, CONTRACT-P7 §3.2 `vertex-format-conversion`: DECLINE.
// The converter is asked only for a conversion BuildWireVertexInput already
// chose, so a refusal here means the two disagree about what is convertible -
// a MobileGL-internal defect, not a peer's malformed record and not a verb the
// split path has yet to migrate. Killing the session for it told the peer
// "protocol corruption" about a bug on this side; skipping the draw and naming
// it once is the honest answer and is what the row asks for. The packed
// converter that would make the refusal unreachable is the row's optional half
// and is not taken here.
if (!ConvertWireVertexStream(attr, conversion, source.data(), stride, count, converted)) {
MGLOG_E_ONCE("Magma wire draw skipped: no vertex stream converter for "
"location=%u type=%u size=%u conversion=%d",
location, attr.Type, static_cast<Uint32>(attr.Size),
static_cast<Int>(conversion));
WireDeclineTally::Count(WireDeclineSite::VertexStreamConverter);
return false;
}
if (!ConvertWireVertexStream(attr, conversion, source.data(), stride, count, converted))
MagmaWireFatal("vertex-format-conversion@P7");
if (!m_bufferManager.UploadTransient(BufferKind::Vertex, m_frameContext.GetCurrentFrameIndex(),
converted.data(), converted.size(), 16, vertexSlices[binding])) {
MGL_WIRE_DECLINE_AT(VertexTransientUpload, "the converted vertex stream did not fit the transient arena");
return false;
}
converted.data(), converted.size(), 16, vertexSlices[binding])) return false;
} else {
slice.offset += offset;
slice.size -= offset;
@@ -355,15 +282,9 @@
BufferSlice indexSlice{};
VkIndexType indexType = VK_INDEX_TYPE_MAX_ENUM;
if (aspects & DrawSetupAspect::IndexBuffer) {
if (!indices) {
MGL_WIRE_DECLINE_AT(IndexViewMissing, "an indexed draw arrived with no index view");
return false;
}
if (!indices) return false;
const SizeT width = MG_Util::GetGLTypeSize(indices->indexType);
if (width != 1 && width != 2 && width != 4) {
MGL_WIRE_DECLINE_AT(IndexTypeWidth, "the index type is not 1, 2 or 4 bytes wide");
return false;
}
if (width != 1 && width != 2 && width != 4) return false;
indexType = width == 4 ? VK_INDEX_TYPE_UINT32 : width == 2 ? VK_INDEX_TYPE_UINT16 : VK_INDEX_TYPE_UINT8;
const auto& restart = MGB_CTX->GetRenderStateParameters();
const Uint32 fixed = MG_Util::FixedRestartIndexForGLType(indices->indexType);
@@ -379,16 +300,10 @@
MagmaWireFatal("index-buffer-resource");
const Uint64 offset = state.IndexBuffer.Offset + indices->indexByteOffset;
if (offset < state.IndexBuffer.Offset || offset > indexSlice.size ||
indices->indexByteSize > indexSlice.size - offset) {
MGL_WIRE_DECLINE_AT(IndexWindow, "the index range lies outside its buffer");
return false;
}
indices->indexByteSize > indexSlice.size - offset) return false;
if (replaceRestart || expandByte || offset % width) {
copied.resize(indices->indexByteSize);
if (!m_bufferManager.ReadWireBuffer(state.IndexBuffer.Res, offset, copied.size(), copied.data())) {
MGL_WIRE_DECLINE_AT(IndexStreamRead, "the indices to rewrite could not be read back");
return false;
}
if (!m_bufferManager.ReadWireBuffer(state.IndexBuffer.Res, offset, copied.size(), copied.data())) return false;
bytes = copied.data();
}
indexSlice.offset += offset;
@@ -412,15 +327,9 @@
if (expandByte) indexType = VK_INDEX_TYPE_UINT16;
}
if (!m_bufferManager.UploadTransient(BufferKind::Index, m_frameContext.GetCurrentFrameIndex(),
bytes, uploadSize, 16, indexSlice)) {
MGL_WIRE_DECLINE_AT(IndexTransientUpload, "the rewritten indices did not fit the transient arena");
return false;
}
}
if (!indexSlice.IsValid()) {
MGL_WIRE_DECLINE_AT(IndexSliceInvalid, "no usable index slice was resolved");
return false;
bytes, uploadSize, 16, indexSlice)) return false;
}
if (!indexSlice.IsValid()) return false;
}
if (!frame.isCommandRecording) m_frameContext.BeginCommandRecording();
@@ -428,10 +337,7 @@
// Resolve it before constructing framebuffer views so both roles of that image
// name the same allocation even on its first storage-image use.
if (!m_uniformManager->BindProgramUniformBuffers(frame.commandBuffer, program, programObj,
m_frameContext.GetCurrentFrameIndex(), VK_PIPELINE_BIND_POINT_GRAPHICS)) {
MGL_WIRE_DECLINE_AT(UniformBufferBinding, "the program's uniform/storage bindings could not be bound");
return false;
}
m_frameContext.GetCurrentFrameIndex(), VK_PIPELINE_BIND_POINT_GRAPHICS)) return false;
Vector<VkAttachmentDescription> attachments;
Vector<VkImageViewCreateInfo> viewInfos;
@@ -503,10 +409,7 @@
depth.attachment = add(fbo->Depth, VK_IMAGE_ASPECT_DEPTH_BIT);
else if (fbo->Stencil.Kind != MG_Pipe::kMGPipeSurfaceKindNone)
depth.attachment = add(fbo->Stencil, VK_IMAGE_ASPECT_STENCIL_BIT);
if (attachments.empty()) {
MGL_WIRE_DECLINE_AT(NoAttachments, "the draw framebuffer resolved to no attachments");
return false;
}
if (attachments.empty()) return false;
passKey.width = extent.width;
passKey.height = extent.height;
passKey.layers = layers;
@@ -563,10 +466,7 @@
const Uint64 compatibilityId = m_wireRenderPassCompatibility.Intern(pipelinePassKey);
const auto pipeline = GetOrCreatePipelineWithInput(mode, program, programObj, flags, input, pass,
ResolvePrimitiveRestartEnable(aspects, indices), compatibilityId);
if (pipeline == VK_NULL_HANDLE) {
MGL_WIRE_DECLINE_AT(PipelineUnavailable, "no graphics pipeline could be created for this draw");
return false;
}
if (pipeline == VK_NULL_HANDLE) return false;
for (Uint32 i = 0; i < vertexSlices.size(); ++i)
vkCmdBindVertexBuffers(frame.commandBuffer, i, 1, &vertexSlices[i].buffer, &vertexSlices[i].offset);
Uint32 binding = static_cast<Uint32>(vertexSlices.size());
@@ -577,23 +477,14 @@
const void* data = nullptr;
VkDeviceSize size = 0;
if (!TryGetCurrentVertexAttributeUploadPayload(MGB_CTX->GetCurrentVertexAttribute(location),
programObj.vertexInputTypes[location], format, data, size)) {
MGL_WIRE_DECLINE_AT(CurrentAttributePayload, "a disabled array's current attribute value has no upload payload");
return false;
}
programObj.vertexInputTypes[location], format, data, size)) return false;
BufferSlice slice{};
if (!m_bufferManager.UploadTransient(BufferKind::Vertex, m_frameContext.GetCurrentFrameIndex(),
data, size, 16, slice)) {
MGL_WIRE_DECLINE_AT(CurrentAttributeUpload, "the current attribute value did not fit the transient arena");
return false;
}
data, size, 16, slice)) return false;
vkCmdBindVertexBuffers(frame.commandBuffer, binding++, 1, &slice.buffer, &slice.offset);
}
if (indexSlice.IsValid()) vkCmdBindIndexBuffer(frame.commandBuffer, indexSlice.buffer, indexSlice.offset, indexType);
if (!VkRenderPassManager::BeginRenderPass(frame.commandBuffer, pass)) {
MGL_WIRE_DECLINE_AT(BeginRenderPass, "the render pass for this draw could not be begun");
return false;
}
if (!VkRenderPassManager::BeginRenderPass(frame.commandBuffer, pass)) return false;
vkCmdBindPipeline(frame.commandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline);
ApplyDynamicDrawStateTail(frame, pass.extent, fbo->IsDefault,
ResolveDrawViewportCount(programObj.writesViewportIndexBuiltin));
@@ -605,26 +496,14 @@
RetireWireDrawPass();
auto& frame = m_frameContext.GetCurrent();
const auto program = WireProgramSource(MG_Pipe::MGPipeApplier().DispatchProgram);
if (!program.GetLinkStatus() || !program.GetSpirvStatus()) {
MGL_WIRE_DECLINE_AT(ComputeProgramLinkOrSpirv, "the compute program is not linked or carries no SPIR-V");
return;
}
if (!program.GetLinkStatus() || !program.GetSpirvStatus()) return;
const auto& programObj = m_programFactory->GetOrCreateProgram(program, {});
if (!m_uniformManager->PrepareWireTextureResources(program, programObj)) {
MGL_WIRE_DECLINE_AT(ComputeTextureResourcesUnprepared, "a sampled/storage image could not be made ready for the dispatch");
return;
}
if (!m_uniformManager->PrepareWireTextureResources(program, programObj)) return;
const auto pipeline = GetOrCreateComputePipeline(programObj);
if (!pipeline) {
MGL_WIRE_DECLINE_AT(ComputePipelineUnavailable, "no compute pipeline could be created for this dispatch");
return;
}
if (!pipeline) return;
if (!frame.isCommandRecording) m_frameContext.BeginCommandRecording();
if (!m_uniformManager->BindProgramUniformBuffers(frame.commandBuffer, program, programObj,
m_frameContext.GetCurrentFrameIndex(), VK_PIPELINE_BIND_POINT_COMPUTE)) {
MGL_WIRE_DECLINE_AT(ComputeUniformBufferBinding, "the dispatch's uniform/storage bindings could not be bound");
return;
}
m_frameContext.GetCurrentFrameIndex(), VK_PIPELINE_BIND_POINT_COMPUTE)) return;
vkCmdBindPipeline(frame.commandBuffer, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline);
vkCmdDispatch(frame.commandBuffer, x, y, z);
}
File diff suppressed because it is too large. Load diff
@@ -1,16 +0,0 @@
#version 450
// SAMPLE ZERO, and it is not an approximation: VK_RESOLVE_MODE_SAMPLE_ZERO_BIT is the mode the
// VK_KHR_depth_stencil_resolve arm asks for, and GL 4.6 core 18.3.1 says a depth resolve picks
// a value "in an implementation-dependent manner where the result will be between the minimum
// and maximum depth values in the pixel" - sample 0 is one of the samples, so it qualifies, and
// taking the same sample as the extension arm is what makes the two arms interchangeable on one
// device.
//
// AVERAGING WOULD NOT BE: a mean of four depths is a surface that exists nowhere, and GL's
// bound is on the per-pixel min/max, which a mean satisfies but a shadow comparison against it
// does not survive.
layout(set = 0, binding = 0) uniform sampler2DMS sourceImage;
void main() {
gl_FragDepth = texelFetch(sourceImage, ivec2(gl_FragCoord.xy), 0).r;
}
@@ -1,167 +0,0 @@
// Included by VulkanRenderer.cpp inside the backend namespace, after WireDepthMipmap.inc.
// The native multisample depth/stencil resolve owns no frontend object and never invokes the
// GL shader compiler.
//
// WHY THIS FILE EXISTS. vkCmdResolveImage is COLOUR ONLY. The one way Vulkan resolves a depth
// or stencil aspect without a shader is a render pass with a depth/stencil resolve attachment,
// which needs VK_KHR_create_renderpass2 and VK_KHR_depth_stencil_resolve - and until this
// package a device without either killed the session at
// `Magma:multisample-depth-resolve-capability` the first time an application resolved a
// multisample depth buffer, which is what glBlitFramebuffer(GL_DEPTH_BUFFER_BIT) from a
// multisampled read framebuffer IS. CONTRACT-P7 §3.2's `multisample-blit-aspect` row names both
// arms; this is the second one.
//
// SAMPLE ZERO IN BOTH ARMS. The extension arm asks for VK_RESOLVE_MODE_SAMPLE_ZERO_BIT, so the
// shader arm fetches sample 0 - not an average. Two arms that answer differently on two devices
// would make "the wire arm is observably the monolith's" untestable, and GL 4.6 core 18.3.1
// requires a SELECTED sample for stencil anyway.
#if MOBILEGL_BUILD_DISAGGREGATED
// The pass's modules, layouts, render passes and pipeline, and the draw it records, are
// WireDepthResolveProbe.cpp's (g5-msprobe): the multisample depth/stencil resolve probe runs
// this exact arm as its CONTROL, so it is defined once for both.
struct VulkanRenderer::WireMultisampleResolveResources {
struct Target {
VkFormat format = VK_FORMAT_UNDEFINED;
VkImageAspectFlags aspect = 0; // the ONE aspect this pipeline writes
VkRenderPass renderPass = VK_NULL_HANDLE;
VkPipeline pipeline = VK_NULL_HANDLE;
};
WireShaderResolveKit kit;
Vector<Target> targets;
};
void VulkanRenderer::DestroyWireMultisampleResolveResources() {
if (!m_wireMultisampleResolveResources) return;
// Shutdown calls this after vkDeviceWaitIdle and after all per-submit descriptor
// pools/framebuffers/views have been collected.
auto& cache = *m_wireMultisampleResolveResources;
for (const auto& target : cache.targets) {
vkDestroyPipeline(m_device, target.pipeline, nullptr);
vkDestroyRenderPass(m_device, target.renderPass, nullptr);
}
DestroyWireShaderResolveKit(m_device, cache.kit);
delete m_wireMultisampleResolveResources;
m_wireMultisampleResolveResources = nullptr;
}
// ONE ASPECT, source -> resolved, both 2D images of the same format and extent, the source
// multisampled and the destination not. Returns false for every shape it cannot express,
// which the caller turns into a decline; it never ends the session.
Bool VulkanRenderer::ResolveWireDepthStencilWithShader(WireImage source, WireImage resolved,
VkImageAspectFlags aspect, GLint sx0, GLint sy0, Uint32 width, Uint32 height) {
if (!source.image || !resolved.image || !width || !height) return false;
if (aspect != VK_IMAGE_ASPECT_DEPTH_BIT && aspect != VK_IMAGE_ASPECT_STENCIL_BIT) return false;
// A fragment shader cannot write the stencil aspect at all without
// VK_EXT_shader_stencil_export. §3.2: decline stencil-only rather than produce a level
// whose stencil is whatever the DONT_CARE left there.
if (aspect == VK_IMAGE_ASPECT_STENCIL_BIT && !m_wireShaderStencilExport) return false;
if (source.samples == VK_SAMPLE_COUNT_1_BIT) return false;
if (source.format != resolved.format) return false;
// SAMPLED is asked for by every attachment VkTextureManager creates; a device that
// declined it would make the descriptor write below undefined, not failed.
if (!(source.usageFlags & VK_IMAGE_USAGE_SAMPLED_BIT)) return false;
VkFormatProperties properties{};
vkGetPhysicalDeviceFormatProperties(m_physicalDevice.handle, source.format, &properties);
const VkFormatFeatureFlags required = VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT |
VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT;
if ((properties.optimalTilingFeatures & required) != required) return false;
const VkImageAspectFlags formatAspects = WireDepthStencilFormatAspects(source.format);
if (!(formatAspects & aspect)) return false;
if (!m_wireMultisampleResolveResources) {
m_wireMultisampleResolveResources = new WireMultisampleResolveResources;
VK_VERIFY(CreateWireShaderResolveKit(m_device, m_wireShaderStencilExport,
m_wireMultisampleResolveResources->kit));
}
auto& cache = *m_wireMultisampleResolveResources;
const VkShaderModule fragment = aspect == VK_IMAGE_ASPECT_STENCIL_BIT ? cache.kit.stencilFragment
: cache.kit.depthFragment;
if (fragment == VK_NULL_HANDLE) return false;
WireMultisampleResolveResources::Target* target = nullptr;
for (auto& entry : cache.targets)
if (entry.format == resolved.format && entry.aspect == aspect) { target = &entry; break; }
if (!target) {
cache.targets.emplace_back();
target = &cache.targets.back();
target->format = resolved.format;
target->aspect = aspect;
VK_VERIFY(CreateWireShaderResolveRenderPass(m_device, resolved.format, &target->renderPass));
if (CreateWireShaderResolvePipeline(m_device, cache.kit, target->renderPass, aspect,
&target->pipeline) != VK_SUCCESS) {
vkDestroyRenderPass(m_device, target->renderPass, nullptr);
cache.targets.pop_back();
return false;
}
}
m_textureManager->FlushPendingUploads();
TransitionWireImage(source, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
TransitionWireImage(resolved, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL);
// ONE ASPECT on the sampled view: a depth/stencil image can only be SAMPLED through a
// view that names exactly one of its aspects, which is also what makes the stencil half
// a usampler2DMS and the depth half a sampler2DMS.
const VkImageViewCreateInfo sourceViewInfo =
WireDepthStencilViewInfo(source.image, source.format, aspect, source.level, source.layer);
VkImageView sourceView = VK_NULL_HANDLE;
VK_VERIFY(vkCreateImageView(m_device, &sourceViewInfo, nullptr, &sourceView));
// BOTH aspects on the attachment view: a depth/stencil ATTACHMENT names every aspect
// its format has, whichever one the pipeline writes.
const VkImageViewCreateInfo targetViewInfo =
WireDepthStencilViewInfo(resolved.image, resolved.format, formatAspects, 0, 0);
VkImageView targetView = VK_NULL_HANDLE;
VK_VERIFY(vkCreateImageView(m_device, &targetViewInfo, nullptr, &targetView));
VkFramebufferCreateInfo framebufferInfo{VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO};
framebufferInfo.renderPass = target->renderPass;
framebufferInfo.attachmentCount = 1;
framebufferInfo.pAttachments = &targetView;
framebufferInfo.width = resolved.extent.width;
framebufferInfo.height = resolved.extent.height;
framebufferInfo.layers = 1;
VkFramebuffer framebuffer = VK_NULL_HANDLE;
VK_VERIFY(vkCreateFramebuffer(m_device, &framebufferInfo, nullptr, &framebuffer));
// Each in-flight pass owns its descriptor set, for the colour blit's reason: updating a
// cached set would rewrite the source view of an older queued pass.
VkDescriptorPool descriptorPool = VK_NULL_HANDLE;
VkDescriptorSet descriptorSet = VK_NULL_HANDLE;
const VkDescriptorPoolSize poolSize{VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1};
VkDescriptorPoolCreateInfo pool{VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO};
pool.maxSets = 1;
pool.poolSizeCount = 1;
pool.pPoolSizes = &poolSize;
VK_VERIFY(vkCreateDescriptorPool(m_device, &pool, nullptr, &descriptorPool));
VkDescriptorSetAllocateInfo alloc{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO};
alloc.descriptorPool = descriptorPool;
alloc.descriptorSetCount = 1;
alloc.pSetLayouts = &cache.kit.descriptorLayout;
VK_VERIFY(vkAllocateDescriptorSets(m_device, &alloc, &descriptorSet));
const VkDescriptorImageInfo sampled{cache.kit.nearest, sourceView,
VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL};
VkWriteDescriptorSet write{VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET};
write.dstSet = descriptorSet;
write.dstBinding = 0;
write.descriptorCount = 1;
write.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
write.pImageInfo = &sampled;
vkUpdateDescriptorSets(m_device, 1, &write, 0, nullptr);
auto& frame = m_frameContext.GetCurrent();
RecordWireShaderResolveDraw(frame.commandBuffer, cache.kit, target->renderPass, target->pipeline, framebuffer,
descriptorSet, resolved.extent, {{sx0, sy0}, {width, height}});
ResetDynamicStateShadow();
InvalidatePipelineMemo();
// This native pass binds its own set/layout without going through the application's
// descriptor binder. Its next fast path must rebind.
if (m_uniformManager) m_uniformManager->OnCommandBufferBoundary();
WireRetiredObjects retired{};
retired.framebuffers.push_back(framebuffer);
retired.imageViews = {sourceView, targetView};
retired.descriptorPools.push_back(descriptorPool);
RetireWireObjects(Move(retired));
return true;
}
#endif
@@ -1,18 +0,0 @@
#version 450
// Native Vulkan multisample depth/stencil resolve: no GL program, registry entry, or runtime
// transpilation.
//
// THIS STAGE CARRIES NOTHING, and that is the whole design. The scratch this pass writes has
// the SAME extent and the SAME coordinate space as the multisample source it reads - both are
// native images, neither is flipped against the other - so the fragment stage can take its
// coordinate straight out of gl_FragCoord and needs no varying, no push constant and no rect.
// The requested rectangle is expressed by the scissor instead, which is also what the
// VK_KHR_depth_stencil_resolve arm next door expresses with its renderArea.
//
// An oversized triangle rather than WireDepthMipmap.vert's quad: there is no destination
// rectangle to clip to here, only the scissor, and a triangle rasterizes the same area with
// one fewer primitive and no shared edge.
void main() {
const vec2 corners[3] = vec2[](vec2(-1.0, -1.0), vec2(3.0, -1.0), vec2(-1.0, 3.0));
gl_Position = vec4(corners[gl_VertexIndex], 0.0, 1.0);
}
@@ -1,103 +0,0 @@
// Generated from WireMultisampleResolve.vert / WireMultisampleDepthResolve.frag /
// WireMultisampleStencilResolve.frag by scripts/bake_internal_shaders.py, which runs MG_Test's
// BakedInternalShadersTest with the IN-TREE glslang and splices the words it emits into the
// arrays below. Do not edit the words by hand: MOBILEGL_BAKED_INTERNAL_SHADERS (the same test,
// run as a gate) recompiles every source in its table and reds on the first word that
// disagrees.
#pragma once
static constexpr Uint32 kWireMultisampleResolveVertexSpirv[] = {
0x07230203u, 0x00010000u, 0x0008000bu, 0x00000028u, 0x00000000u, 0x00020011u, 0x00000001u, 0x0006000bu,
0x00000001u, 0x4c534c47u, 0x6474732eu, 0x3035342eu, 0x00000000u, 0x0003000eu, 0x00000000u, 0x00000001u,
0x0007000fu, 0x00000000u, 0x00000004u, 0x6e69616du, 0x00000000u, 0x0000000du, 0x0000001au, 0x00030003u,
0x00000002u, 0x000001c2u, 0x00040005u, 0x00000004u, 0x6e69616du, 0x00000000u, 0x00060005u, 0x0000000bu,
0x505f6c67u, 0x65567265u, 0x78657472u, 0x00000000u, 0x00060006u, 0x0000000bu, 0x00000000u, 0x505f6c67u,
0x7469736fu, 0x006e6f69u, 0x00070006u, 0x0000000bu, 0x00000001u, 0x505f6c67u, 0x746e696fu, 0x657a6953u,
0x00000000u, 0x00070006u, 0x0000000bu, 0x00000002u, 0x435f6c67u, 0x4470696cu, 0x61747369u, 0x0065636eu,
0x00070006u, 0x0000000bu, 0x00000003u, 0x435f6c67u, 0x446c6c75u, 0x61747369u, 0x0065636eu, 0x00030005u,
0x0000000du, 0x00000000u, 0x00060005u, 0x0000001au, 0x565f6c67u, 0x65747265u, 0x646e4978u, 0x00007865u,
0x00050005u, 0x0000001du, 0x65646e69u, 0x6c626178u, 0x00000065u, 0x00030047u, 0x0000000bu, 0x00000002u,
0x00050048u, 0x0000000bu, 0x00000000u, 0x0000000bu, 0x00000000u, 0x00050048u, 0x0000000bu, 0x00000001u,
0x0000000bu, 0x00000001u, 0x00050048u, 0x0000000bu, 0x00000002u, 0x0000000bu, 0x00000003u, 0x00050048u,
0x0000000bu, 0x00000003u, 0x0000000bu, 0x00000004u, 0x00040047u, 0x0000001au, 0x0000000bu, 0x0000002au,
0x00020013u, 0x00000002u, 0x00030021u, 0x00000003u, 0x00000002u, 0x00030016u, 0x00000006u, 0x00000020u,
0x00040017u, 0x00000007u, 0x00000006u, 0x00000004u, 0x00040015u, 0x00000008u, 0x00000020u, 0x00000000u,
0x0004002bu, 0x00000008u, 0x00000009u, 0x00000001u, 0x0004001cu, 0x0000000au, 0x00000006u, 0x00000009u,
0x0006001eu, 0x0000000bu, 0x00000007u, 0x00000006u, 0x0000000au, 0x0000000au, 0x00040020u, 0x0000000cu,
0x00000003u, 0x0000000bu, 0x0004003bu, 0x0000000cu, 0x0000000du, 0x00000003u, 0x00040015u, 0x0000000eu,
0x00000020u, 0x00000001u, 0x0004002bu, 0x0000000eu, 0x0000000fu, 0x00000000u, 0x00040017u, 0x00000010u,
0x00000006u, 0x00000002u, 0x0004002bu, 0x00000008u, 0x00000011u, 0x00000003u, 0x0004001cu, 0x00000012u,
0x00000010u, 0x00000011u, 0x0004002bu, 0x00000006u, 0x00000013u, 0xbf800000u, 0x0005002cu, 0x00000010u,
0x00000014u, 0x00000013u, 0x00000013u, 0x0004002bu, 0x00000006u, 0x00000015u, 0x40400000u, 0x0005002cu,
0x00000010u, 0x00000016u, 0x00000015u, 0x00000013u, 0x0005002cu, 0x00000010u, 0x00000017u, 0x00000013u,
0x00000015u, 0x0006002cu, 0x00000012u, 0x00000018u, 0x00000014u, 0x00000016u, 0x00000017u, 0x00040020u,
0x00000019u, 0x00000001u, 0x0000000eu, 0x0004003bu, 0x00000019u, 0x0000001au, 0x00000001u, 0x00040020u,
0x0000001cu, 0x00000007u, 0x00000012u, 0x00040020u, 0x0000001eu, 0x00000007u, 0x00000010u, 0x0004002bu,
0x00000006u, 0x00000021u, 0x00000000u, 0x0004002bu, 0x00000006u, 0x00000022u, 0x3f800000u, 0x00040020u,
0x00000026u, 0x00000003u, 0x00000007u, 0x00050036u, 0x00000002u, 0x00000004u, 0x00000000u, 0x00000003u,
0x000200f8u, 0x00000005u, 0x0004003bu, 0x0000001cu, 0x0000001du, 0x00000007u, 0x0004003du, 0x0000000eu,
0x0000001bu, 0x0000001au, 0x0003003eu, 0x0000001du, 0x00000018u, 0x00050041u, 0x0000001eu, 0x0000001fu,
0x0000001du, 0x0000001bu, 0x0004003du, 0x00000010u, 0x00000020u, 0x0000001fu, 0x00050051u, 0x00000006u,
0x00000023u, 0x00000020u, 0x00000000u, 0x00050051u, 0x00000006u, 0x00000024u, 0x00000020u, 0x00000001u,
0x00070050u, 0x00000007u, 0x00000025u, 0x00000023u, 0x00000024u, 0x00000021u, 0x00000022u, 0x00050041u,
0x00000026u, 0x00000027u, 0x0000000du, 0x0000000fu, 0x0003003eu, 0x00000027u, 0x00000025u, 0x000100fdu,
0x00010038u,
};
static constexpr Uint32 kWireMultisampleDepthResolveFragmentSpirv[] = {
0x07230203u, 0x00010000u, 0x0008000bu, 0x0000001du, 0x00000000u, 0x00020011u, 0x00000001u, 0x0006000bu,
0x00000001u, 0x4c534c47u, 0x6474732eu, 0x3035342eu, 0x00000000u, 0x0003000eu, 0x00000000u, 0x00000001u,
0x0007000fu, 0x00000004u, 0x00000004u, 0x6e69616du, 0x00000000u, 0x00000008u, 0x00000010u, 0x00030010u,
0x00000004u, 0x00000007u, 0x00030010u, 0x00000004u, 0x0000000cu, 0x00030003u, 0x00000002u, 0x000001c2u,
0x00040005u, 0x00000004u, 0x6e69616du, 0x00000000u, 0x00060005u, 0x00000008u, 0x465f6c67u, 0x44676172u,
0x68747065u, 0x00000000u, 0x00050005u, 0x0000000cu, 0x72756f73u, 0x6d496563u, 0x00656761u, 0x00060005u,
0x00000010u, 0x465f6c67u, 0x43676172u, 0x64726f6fu, 0x00000000u, 0x00040047u, 0x00000008u, 0x0000000bu,
0x00000016u, 0x00040047u, 0x0000000cu, 0x00000021u, 0x00000000u, 0x00040047u, 0x0000000cu, 0x00000022u,
0x00000000u, 0x00040047u, 0x00000010u, 0x0000000bu, 0x0000000fu, 0x00020013u, 0x00000002u, 0x00030021u,
0x00000003u, 0x00000002u, 0x00030016u, 0x00000006u, 0x00000020u, 0x00040020u, 0x00000007u, 0x00000003u,
0x00000006u, 0x0004003bu, 0x00000007u, 0x00000008u, 0x00000003u, 0x00090019u, 0x00000009u, 0x00000006u,
0x00000001u, 0x00000000u, 0x00000000u, 0x00000001u, 0x00000001u, 0x00000000u, 0x0003001bu, 0x0000000au,
0x00000009u, 0x00040020u, 0x0000000bu, 0x00000000u, 0x0000000au, 0x0004003bu, 0x0000000bu, 0x0000000cu,
0x00000000u, 0x00040017u, 0x0000000eu, 0x00000006u, 0x00000004u, 0x00040020u, 0x0000000fu, 0x00000001u,
0x0000000eu, 0x0004003bu, 0x0000000fu, 0x00000010u, 0x00000001u, 0x00040017u, 0x00000011u, 0x00000006u,
0x00000002u, 0x00040015u, 0x00000014u, 0x00000020u, 0x00000001u, 0x00040017u, 0x00000015u, 0x00000014u,
0x00000002u, 0x0004002bu, 0x00000014u, 0x00000017u, 0x00000000u, 0x00040015u, 0x0000001au, 0x00000020u,
0x00000000u, 0x0004002bu, 0x0000001au, 0x0000001bu, 0x00000000u, 0x00050036u, 0x00000002u, 0x00000004u,
0x00000000u, 0x00000003u, 0x000200f8u, 0x00000005u, 0x0004003du, 0x0000000au, 0x0000000du, 0x0000000cu,
0x0004003du, 0x0000000eu, 0x00000012u, 0x00000010u, 0x0007004fu, 0x00000011u, 0x00000013u, 0x00000012u,
0x00000012u, 0x00000000u, 0x00000001u, 0x0004006eu, 0x00000015u, 0x00000016u, 0x00000013u, 0x00040064u,
0x00000009u, 0x00000018u, 0x0000000du, 0x0007005fu, 0x0000000eu, 0x00000019u, 0x00000018u, 0x00000016u,
0x00000040u, 0x00000017u, 0x00050051u, 0x00000006u, 0x0000001cu, 0x00000019u, 0x00000000u, 0x0003003eu,
0x00000008u, 0x0000001cu, 0x000100fdu, 0x00010038u,
};
static constexpr Uint32 kWireMultisampleStencilResolveFragmentSpirv[] = {
0x07230203u, 0x00010000u, 0x0008000bu, 0x0000001fu, 0x00000000u, 0x00020011u, 0x00000001u, 0x00020011u,
0x00001395u, 0x0009000au, 0x5f565053u, 0x5f545845u, 0x64616873u, 0x735f7265u, 0x636e6574u, 0x655f6c69u,
0x726f7078u, 0x00000074u, 0x0006000bu, 0x00000001u, 0x4c534c47u, 0x6474732eu, 0x3035342eu, 0x00000000u,
0x0003000eu, 0x00000000u, 0x00000001u, 0x0007000fu, 0x00000004u, 0x00000004u, 0x6e69616du, 0x00000000u,
0x00000008u, 0x00000012u, 0x00030010u, 0x00000004u, 0x00000007u, 0x00030010u, 0x00000004u, 0x000013a3u,
0x00030003u, 0x00000002u, 0x000001c2u, 0x00090004u, 0x415f4c47u, 0x735f4252u, 0x65646168u, 0x74735f72u,
0x69636e65u, 0x78655f6cu, 0x74726f70u, 0x00000000u, 0x00040005u, 0x00000004u, 0x6e69616du, 0x00000000u,
0x00080005u, 0x00000008u, 0x465f6c67u, 0x53676172u, 0x636e6574u, 0x65526c69u, 0x42524166u, 0x00000000u,
0x00050005u, 0x0000000du, 0x72756f73u, 0x6d496563u, 0x00656761u, 0x00060005u, 0x00000012u, 0x465f6c67u,
0x43676172u, 0x64726f6fu, 0x00000000u, 0x00040047u, 0x00000008u, 0x0000000bu, 0x00001396u, 0x00040047u,
0x0000000du, 0x00000021u, 0x00000000u, 0x00040047u, 0x0000000du, 0x00000022u, 0x00000000u, 0x00040047u,
0x00000012u, 0x0000000bu, 0x0000000fu, 0x00020013u, 0x00000002u, 0x00030021u, 0x00000003u, 0x00000002u,
0x00040015u, 0x00000006u, 0x00000020u, 0x00000001u, 0x00040020u, 0x00000007u, 0x00000003u, 0x00000006u,
0x0004003bu, 0x00000007u, 0x00000008u, 0x00000003u, 0x00040015u, 0x00000009u, 0x00000020u, 0x00000000u,
0x00090019u, 0x0000000au, 0x00000009u, 0x00000001u, 0x00000000u, 0x00000000u, 0x00000001u, 0x00000001u,
0x00000000u, 0x0003001bu, 0x0000000bu, 0x0000000au, 0x00040020u, 0x0000000cu, 0x00000000u, 0x0000000bu,
0x0004003bu, 0x0000000cu, 0x0000000du, 0x00000000u, 0x00030016u, 0x0000000fu, 0x00000020u, 0x00040017u,
0x00000010u, 0x0000000fu, 0x00000004u, 0x00040020u, 0x00000011u, 0x00000001u, 0x00000010u, 0x0004003bu,
0x00000011u, 0x00000012u, 0x00000001u, 0x00040017u, 0x00000013u, 0x0000000fu, 0x00000002u, 0x00040017u,
0x00000016u, 0x00000006u, 0x00000002u, 0x0004002bu, 0x00000006u, 0x00000018u, 0x00000000u, 0x00040017u,
0x0000001au, 0x00000009u, 0x00000004u, 0x0004002bu, 0x00000009u, 0x0000001cu, 0x00000000u, 0x00050036u,
0x00000002u, 0x00000004u, 0x00000000u, 0x00000003u, 0x000200f8u, 0x00000005u, 0x0004003du, 0x0000000bu,
0x0000000eu, 0x0000000du, 0x0004003du, 0x00000010u, 0x00000014u, 0x00000012u, 0x0007004fu, 0x00000013u,
0x00000015u, 0x00000014u, 0x00000014u, 0x00000000u, 0x00000001u, 0x0004006eu, 0x00000016u, 0x00000017u,
0x00000015u, 0x00040064u, 0x0000000au, 0x00000019u, 0x0000000eu, 0x0007005fu, 0x0000001au, 0x0000001bu,
0x00000019u, 0x00000017u, 0x00000040u, 0x00000018u, 0x00050051u, 0x00000009u, 0x0000001du, 0x0000001bu,
0x00000000u, 0x0004007cu, 0x00000006u, 0x0000001eu, 0x0000001du, 0x0003003eu, 0x00000008u, 0x0000001eu,
0x000100fdu, 0x00010038u,
};
@@ -1,19 +0,0 @@
#version 450
// The stencil half, and it needs an extension to exist at all: a fragment shader cannot write
// the stencil aspect without VK_EXT_shader_stencil_export (SPV_EXT_shader_stencil_export, which
// this `#extension` line is how glslang is asked for). CONTRACT-P7 §3.2 says so and says what
// happens otherwise - a stencil-only resolve DECLINES on a device without it, because there is
// no second way to put a value in the stencil aspect from a pass.
//
// usampler2DMS and not sampler2DMS: the stencil aspect of a depth/stencil image is an unsigned
// integer, and a float view of it would round the index.
//
// Sample zero, for WireMultisampleDepthResolve.frag's reason, and GL is stricter here: 18.3.1
// says integer and stencil resolves SELECT one sample rather than combining them, so sample 0
// is the answer and not merely an acceptable one.
#extension GL_ARB_shader_stencil_export : require
layout(set = 0, binding = 0) uniform usampler2DMS sourceImage;
void main() {
gl_FragStencilRefARB = int(texelFetch(sourceImage, ivec2(gl_FragCoord.xy), 0).r);
}
@@ -13,28 +13,9 @@
image = {};
}
void UniformManager::SetWireInvalidStorageImageArm(Bool deviceNullDescriptor) {
const char* forced = std::getenv("MGITEST_MAGMA_FORCE_PRIVATE_IMAGE_PLACEHOLDER");
const Bool forcePrivate = forced != nullptr && std::strcmp(forced, "1") == 0;
m_wireInvalidStorageImagesBindNull = deviceNullDescriptor && !forcePrivate;
MGLOG_I("Magma wire: an invalid or unbound image unit binds %s (VK_EXT_robustness2 nullDescriptor %s%s)",
m_wireInvalidStorageImagesBindNull ? "a NULL storage descriptor"
: "a placeholder private to its unit",
deviceNullDescriptor ? "enabled" : "unavailable",
deviceNullDescriptor && forcePrivate ? "; MGITEST_MAGMA_FORCE_PRIVATE_IMAGE_PLACEHOLDER=1" : "");
}
Bool UniformManager::ResolveWirePlaceholderImage(VkCommandBuffer commands, const MagmaProgramSource& program,
const ProgramFactory::VkProgramObject& programObj, Uint32 binding, Bool storage,
VkDescriptorImageInfo& out, VkFormat boundStorageFormat, Uint32 unit) const {
// GL 4.6 core 8.26, codex closeout finding 2: every access through an invalid image unit
// is invalid - a load returns zero, a store and an atomic are discarded. A NULL storage
// descriptor (VK_EXT_robustness2 nullDescriptor) is exactly that, for any target, format
// and sample count, so nothing below is needed.
if (storage && m_wireInvalidStorageImagesBindNull) {
out = {VK_NULL_HANDLE, VK_NULL_HANDLE, VK_IMAGE_LAYOUT_GENERAL};
return true;
}
VkDescriptorImageInfo& out) const {
if (binding >= programObj.samplerTextureTargetByBinding.size() ||
binding >= programObj.samplerNumericDomainByBinding.size()) return false;
const auto target = programObj.samplerTextureTargetByBinding[binding];
@@ -55,20 +36,6 @@
if (storage) {
if (binding >= programObj.storageImageFormatByBinding.size()) return false;
format = programObj.storageImageFormatByBinding[binding];
// A formatless declaration of an INVALID binding (a unit whose texture lacks the
// named level or layer) takes the format the application bound, where the device can
// store to it and it is in the shader's numeric class. The R32 default expands a load
// to (0, 0, 0, 1); a four-channel carrier cleared to zero reads (0, 0, 0, 0), which
// is what KHR-GL46.shader_image_load_store.incomplete_textures compares against.
if (format == VK_FORMAT_UNDEFINED && boundStorageFormat != VK_FORMAT_UNDEFINED) {
const Bool classMatches = domain == SamplerNumericDomain::Float
? !vkuFormatIsUINT(boundStorageFormat) && !vkuFormatIsSINT(boundStorageFormat)
: domain == SamplerNumericDomain::SignedInteger ? vkuFormatIsSINT(boundStorageFormat)
: domain == SamplerNumericDomain::UnsignedInteger && vkuFormatIsUINT(boundStorageFormat);
VkFormatProperties properties{};
if (classMatches) vkGetPhysicalDeviceFormatProperties(m_physicalDevice, boundStorageFormat, &properties);
if (properties.optimalTilingFeatures & VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT) format = boundStorageFormat;
}
if (format == VK_FORMAT_UNDEFINED) format = PlaceholderFormatForNumericDomain(domain);
} else if (shadow) format = VK_FORMAT_D16_UNORM;
else if (domain == SamplerNumericDomain::Float) format = VK_FORMAT_R8G8B8A8_UNORM;
@@ -93,22 +60,8 @@
break;
default: return false;
}
// A STORAGE placeholder is private to its unit (per shape). Shared by shape alone, a store
// through invalid unit A was visible, after a barrier, to a load through invalid unit B of
// the same shape - one Vulkan image behind both (codex closeout finding 2). The clear
// below still runs before each use; what a private image cannot hide is the SAME unit's
// own store to its own later load inside one pass (CONTRACT-P7 §12). Not per binding: GL
// aliases per unit, and a (binding, unit) key only multiplied allocations. Past
// kWirePrivateStoragePlaceholderCap a new (shape, unit) shares its shape's (WirePlaceholderKey.h).
const Uint64 shape = static_cast<Uint32>(format) | (static_cast<Uint64>(target) << 32) |
(static_cast<Uint64>(storage) << 48) | (static_cast<Uint64>(shadow) << 49);
const WirePlaceholderKey key = ChooseWirePlaceholderKey(shape, storage, unit, m_wirePrivateStoragePlaceholders,
[this](const WirePlaceholderKey& candidate) { return m_wirePlaceholderImages.count(candidate) != 0; });
if (storage && unit != WirePlaceholderKey::kShared && key.unit == WirePlaceholderKey::kShared) {
MGLOG_W_ONCE("Magma wire: %zu image-unit-private placeholders exist (the cap); a further invalid or "
"unbound unit shares its shape's placeholder, so two such units of one shape can alias",
static_cast<size_t>(m_wirePrivateStoragePlaceholders));
}
const Uint64 key = static_cast<Uint32>(format) | (static_cast<Uint64>(target) << 32) |
(static_cast<Uint64>(storage) << 48) | (static_cast<Uint64>(shadow) << 49);
auto found = m_wirePlaceholderImages.find(key);
if (found == m_wirePlaceholderImages.end()) {
WirePlaceholderImage image{};
@@ -198,12 +151,11 @@
if (vkCreateFramebuffer(m_device, &framebuffer, nullptr, &image.clearFramebuffer) != VK_SUCCESS) return fail();
}
found = m_wirePlaceholderImages.emplace(key, image).first;
if (key.unit != WirePlaceholderKey::kShared) ++m_wirePrivateStoragePlaceholders;
}
auto& image = found->second;
// Sampled incomplete textures remain immutable opaque black. A storage
// placeholder is reset before each use, so a prior discarded store cannot
// leak into a later pass's loads through the same unit.
// leak into an unrelated invocation's unbound image loads.
if (storage || image.layout == VK_IMAGE_LAYOUT_UNDEFINED) {
VkClearValue clear{};
if (!storage) {
@@ -1,62 +0,0 @@
// MobileGL - MobileGL/MG_Backend/DirectVulkan/Renderer/WirePlaceholderKey.h
// Copyright (c) 2025-2026 MobileGL-Dev
// Licensed under the GNU Lesser General Public License v3.0:
// https://www.gnu.org/licenses/gpl-3.0.txt
// https://www.gnu.org/licenses/lgpl-3.0.txt
// SPDX-License-Identifier: LGPL-3.0-only
// End of Source File Header
#pragma once
#include <Includes.h>
// The pure half of UniformManager's wire placeholder cache (WirePlaceholderImages.inc): WHICH
// placeholder a binding with no usable image takes. A unit test pins it
// (MG_Test/Pipeline/PipelineQuirkTest.cpp); the Vulkan half that makes the image stays in the .inc.
#if MOBILEGL_BUILD_DISAGGREGATED
#include <MG_Pipe/MGPipeTypes.h>
namespace MobileGL::MG_Backend::DirectVulkan {
// The placeholder's SHAPE (format, target, storage, shadow) and, for a STORAGE placeholder on
// the arm without a null descriptor, the image UNIT it is private to. GL aliases per UNIT, so the
// unit is the whole of the no-alias guarantee (codex closeout finding 2): two bindings that name
// one unit are one GL image, and keying them apart as well only multiplied allocations (cf-magma
// critic). A sampled placeholder is never written, so it stays shared: its unit is kShared.
struct WirePlaceholderKey {
static constexpr Uint32 kShared = ~0u;
Uint64 shape = 0;
Uint32 unit = kShared;
Bool operator==(const WirePlaceholderKey& other) const { return shape == other.shape && unit == other.unit; }
};
struct WirePlaceholderKeyHash {
SizeT operator()(const WirePlaceholderKey& key) const {
Uint64 h = key.shape * 0x9E3779B97F4A7C15ull;
h ^= static_cast<Uint64>(key.unit) + 0x9E3779B97F4A7C15ull + (h << 6) + (h >> 2);
return static_cast<SizeT>(h);
}
};
// Every private placeholder is its own vkCreateImage + vkAllocateMemory, freed only at Shutdown.
// (shape, unit) bounds them by shapes x kMGPipeMaxImageUnits, and a peer rotating formats and
// targets across the units could still walk that towards maxMemoryAllocationCount (4096 is the
// spec minimum). So past this many, a NEW (shape, unit) takes its shape's SHARED placeholder - the
// pre-fix aliasing, logged once by the caller - instead of another allocation; a unit that already
// has its private placeholder keeps it. Two per unit is far past any real program.
inline constexpr SizeT kWirePrivateStoragePlaceholderCap = 2 * static_cast<SizeT>(MG_Pipe::kMGPipeMaxImageUnits);
// The key a placeholder of `shape` is found or made under. `privateStorage` = a storage binding on
// the arm without a null descriptor (with one, the caller never gets here); `unit` = its image
// unit; `privateCount` = how many private placeholders exist; `known(key)` = the cache holds `key`.
template <typename KnownFn>
WirePlaceholderKey ChooseWirePlaceholderKey(Uint64 shape, Bool privateStorage, Uint32 unit, SizeT privateCount,
KnownFn&& known) {
WirePlaceholderKey key;
key.shape = shape;
if (!privateStorage || unit == WirePlaceholderKey::kShared) return key;
key.unit = unit;
if (privateCount < kWirePrivateStoragePlaceholderCap || known(key)) return key;
key.unit = WirePlaceholderKey::kShared;
return key;
}
} // namespace MobileGL::MG_Backend::DirectVulkan
#endif
+47 -112
View File
@@ -15,7 +15,6 @@
#include <MG_Pipe/MGPipe.h>
#include <MG_Pipe/PipeApply.h>
#include <MG_Remote/Client/ClientSession.h>
#include <MG_Remote/FatalFunnel.h> // InstallPipeSessionFailHook, installed at step 0 below
#include <MG_Remote/Server/ServerLoop.h>
#include <MG_Remote/Server/ServerSession.h>
#endif
@@ -160,14 +159,6 @@ namespace MobileGL::MG_Backend {
Bool InitServerRoleCommon() {
using namespace MobileGL::MG_Remote;
// 0. the Magma wire funnels' route to Session::Fail (P7 wave 0). FIRST, before
// CreateBackend can reach a wire arm: a hook installed after the first death it
// was meant to catch is a hook that does nothing on the only run that mattered.
// Here rather than in ServerMain because BOTH server roles pass through this
// function - the inproc role and the spawn/TCP session child - and a per-transport
// install is how one of the two ends up without it.
InstallPipeSessionFailHook();
// 1. the SERVER role's private backend object, on the app thread, with no GL and no
// EGL. The context is created and made current later, on mgl-srv-apply, when the
// client's first eglMakeCurrent crosses as a blocking control request.
@@ -220,32 +211,6 @@ namespace MobileGL::MG_Backend {
capBits |= MG_Pipe::kCapTimerQuery;
}
}
// P7 wave 2 package C, OQ-10 (CONTRACT-P7 §5.4): kCapResidentSubData, PUBLISHED
// OFF THE SERVER'S OWN WIRE RESOURCE TABLE AND NOTHING ELSE.
//
// The question the bit answers is the one BufferObject::LandBytesIntoResidentStore
// asks before it chooses between emitting `buffer_subdata_resident` (opcode 49) and
// falling back to the ordered in-place host memcpy: "does the side that will APPLY
// this record implement the resident arm at all?" Under a transport the client has
// no op table to probe - MGPipeResourceOpsHaveSubDataResident says so in as many
// words (MG_Impl/Pipe/PipeFill.cpp) and reads this bit instead - and until now
// nothing ever set it, so the answer was permanently "no" and BOTH backends fell
// back to the memcpy while both of them in fact register a SubDataResident arm
// (DirectGLES Managers.cpp's g_glesResourceOps, Magma VkBufferManager.cpp's
// g_vulkanWireResourceOps). Magma's implementation was dead code on the wire.
//
// BY THE TABLE, NEVER BY THE BACKEND ENUM, and that is ID-39's lesson rather than a
// style preference: a mask is a statement about THIS backend's registered table, so
// a bit derived from `ActiveBackendType == ...` would keep claiming the capability
// for a build, a flavour or a future backend whose table does not carry the arm -
// which is exactly how 66 uploads were lost to a consumer bit that nobody could
// have honoured. `g_resourceOpsAtStep2` is the pointer this function just pinned,
// and step 5 already refuses a run where that pointer was swapped underneath us, so
// reading the arm off it means the published bit and the table that has to answer
// for it cannot come apart.
if (g_resourceOpsAtStep2 != nullptr && g_resourceOpsAtStep2->SubDataResident != nullptr) {
capBits |= MG_Pipe::kCapResidentSubData;
}
// Each backend has an independent implementation-readiness gate.
// The runtime RunAhead knob can decline the feature, never create it.
const Bool runAheadReady = MG_Config::ActiveBackendType == BackendType::DirectVulkan
@@ -302,16 +267,55 @@ namespace MobileGL::MG_Backend {
pActiveBackendObject = MakeUnique<MG_Remote::Client::BackendObject_Remote>();
return true;
}
} // namespace
#endif
// F1 (P7 wave 2). THE WHOLE SPLIT ARM OF Init(), AS ONE BODY, so it can run from
// either of the two places that may reach it - MobileGL::Initialize's early hook,
// before MG_State::Init(), and Init() itself for a direct caller such as a unit
// fixture - without a second copy. Two copies of a bring-up order is how the two
// orders come to differ on the day one of them is wrong.
Bool g_splitBackendBroughtUp = false;
#if MOBILEGL_BUILD_DISAGGREGATED
void ShutdownSplitRoles() {
if (MG_Config::Transport == MG_Config::TransportMode::Monolith) return;
// ClientSession::Stop IS table 3's whole order and it is idempotent: publish and wait
// for the server to drain (bounded - a lost record must be a red lane, not a hung
// exit), Doorbell::Kill through the transport's Shutdown, ServerLoop::Stop's bounded
// join - which also destroys the server's private BackendObject ON the apply thread
// while it still owns the context - the transport, and only THEN anything an emitter
// owns. A var-tail still named by an unapplied record is a use-after-free the join is
// what prevents, which is why the order is not a preference.
MG_Remote::Client::ClientSessionInstance().Stop();
// M-6: ClientSession::Stop's !m_started arm (a Start that FAILED after
// ServerSession::Accept - a refused Accept, an invalid cmd/reply ring) tears down only
// the client half and never stops the apply thread or drops the server's private backend,
// which ServerLoop::CreateBackend already built and which holds the process-wide
// g_resourceOps. So call ServerLoop::Stop() here unconditionally. It is idempotent: on the
// started path ClientSession::Stop already joined the thread, so this hits Stop's
// !joinable arm, which resets a backend that never ran a thread and is otherwise a no-op.
// Without this an early Start failure leaves BackendObject_DirectGLES permanently alive
// and every later split bring-up in the process fails at CreateBackend's m_backend!=null
// guard.
MG_Remote::Server::ServerLoopInstance().Stop();
}
#endif
void InitSplitBackend() {
g_splitBackendBroughtUp = true;
#if MOBILEGL_BUILD_DISAGGREGATED
// The spawn server's entry into the SAME bring-up the inproc server role
// runs (ServerRole.h). A thin forwarder on purpose: the body stays in the
// anonymous namespace beside InitSplitRoles so the two cannot drift.
//
// THE WHOLE FUNCTION IS INSIDE THE GUARD, not just its body. A version with
// the guard inside still DEFINES the symbol in a pull build, and G1 caught
// it: 2 symbols added, 1 removed, .text +16 bytes. The pull build's identity
// is byte-for-byte, and "it returns false there" is not the same as "it is
// not there".
Bool InitServerRoleForSpawn() { return InitServerRoleCommon(); }
#endif
void Init() {
MGLOG_D("Initializing MobileGL Backend...");
#if MOBILEGL_BUILD_DISAGGREGATED
// THE SINGLE HOOK. In a build without MOBILEGL_BUILD_DISAGGREGATED, MG_Config::Transport
// is a `constexpr Monolith` (Config.h) and this whole statement is discarded, so the
// pull build gains no symbol, no branch and no byte - which is what G1 measures.
if (MG_Config::Transport != MG_Config::TransportMode::Monolith) {
if (!InitSplitRoles()) {
// NOT a fallback to the switch. pActiveBackendObject stays null and the next GL
// call fails loudly, which is the only honest outcome: the operator asked for a
@@ -360,75 +364,6 @@ namespace MobileGL::MG_Backend {
}
}
LogBackendInfo();
}
} // namespace
#endif
#if MOBILEGL_BUILD_DISAGGREGATED
// F1 (P7 wave 2). See BackendObjects.h for why this exists and MobileGL/Init.cpp for the
// defect the order closes.
Bool InitSplitRolesBeforeState() {
if (MG_Config::Transport == MG_Config::TransportMode::Monolith) return false;
InitSplitBackend();
return true;
}
#endif
#if MOBILEGL_BUILD_DISAGGREGATED
void ShutdownSplitRoles() {
g_splitBackendBroughtUp = false;
if (MG_Config::Transport == MG_Config::TransportMode::Monolith) return;
// ClientSession::Stop IS table 3's whole order and it is idempotent: publish and wait
// for the server to drain (bounded - a lost record must be a red lane, not a hung
// exit), Doorbell::Kill through the transport's Shutdown, ServerLoop::Stop's bounded
// join - which also destroys the server's private BackendObject ON the apply thread
// while it still owns the context - the transport, and only THEN anything an emitter
// owns. A var-tail still named by an unapplied record is a use-after-free the join is
// what prevents, which is why the order is not a preference.
MG_Remote::Client::ClientSessionInstance().Stop();
// M-6: ClientSession::Stop's !m_started arm (a Start that FAILED after
// ServerSession::Accept - a refused Accept, an invalid cmd/reply ring) tears down only
// the client half and never stops the apply thread or drops the server's private backend,
// which ServerLoop::CreateBackend already built and which holds the process-wide
// g_resourceOps. So call ServerLoop::Stop() here unconditionally. It is idempotent: on the
// started path ClientSession::Stop already joined the thread, so this hits Stop's
// !joinable arm, which resets a backend that never ran a thread and is otherwise a no-op.
// Without this an early Start failure leaves BackendObject_DirectGLES permanently alive
// and every later split bring-up in the process fails at CreateBackend's m_backend!=null
// guard.
MG_Remote::Server::ServerLoopInstance().Stop();
}
#endif
#if MOBILEGL_BUILD_DISAGGREGATED
// The spawn server's entry into the SAME bring-up the inproc server role
// runs (ServerRole.h). A thin forwarder on purpose: the body stays in the
// anonymous namespace beside InitSplitRoles so the two cannot drift.
//
// THE WHOLE FUNCTION IS INSIDE THE GUARD, not just its body. A version with
// the guard inside still DEFINES the symbol in a pull build, and G1 caught
// it: 2 symbols added, 1 removed, .text +16 bytes. The pull build's identity
// is byte-for-byte, and "it returns false there" is not the same as "it is
// not there".
Bool InitServerRoleForSpawn() { return InitServerRoleCommon(); }
#endif
void Init() {
MGLOG_D("Initializing MobileGL Backend...");
#if MOBILEGL_BUILD_DISAGGREGATED
// THE SINGLE HOOK. In a build without MOBILEGL_BUILD_DISAGGREGATED, MG_Config::Transport
// is a `constexpr Monolith` (Config.h) and this whole statement is discarded, so the
// pull build gains no symbol, no branch and no byte - which is what G1 measures.
if (MG_Config::Transport != MG_Config::TransportMode::Monolith) {
// F1: MobileGL::Initialize now brings the split roles up BEFORE MG_State::Init(),
// through InitSplitRolesBeforeState() below, so by the time Init() is reached on
// that path the work is done. A DIRECT caller - a unit fixture that calls
// MG_Backend::Init() itself - still gets the whole bring-up here. The flag rather
// than `pActiveBackendObject == nullptr`, because a bring-up that FAILED leaves
// that pointer null too and retrying it would refuse at CreateBackend's
// m_backend != nullptr guard with a second, misleading line.
if (!g_splitBackendBroughtUp) InitSplitBackend();
return;
}
#endif
-77
View File
@@ -54,60 +54,6 @@ namespace MobileGL::MG_Pipe {
namespace {
Uint64 g_residualPulls = 0;
#if MOBILEGL_PIPE_VERIFY
// ---- P7 wave 3 (V1): negative control B's SERVER half ----------------------------
//
// MOBILEGL_PIPE_POISON_OMIT withholds the STAMP of one (verb, field) pair, and until a
// verify build first ran on the split arm it was only ever read by the client's filler
// (MG_Impl/Pipe/PipeFill.cpp's ParsePoisonOmissionKnob). On the split arm that is not
// where the stamp the backend reads comes from: the stamp below re-stamps every field
// the verb's class can answer out of applied records, so it restamped the very field
// the client had withheld and the control went GREEN - measured, both backends, the
// child's glGenerateMipmap returned and the process exited 0 with
// GenerateMipmap:GetActiveTextureUnit omitted. The knob means "this verb's stamp of this
// field was never written", and under a transport the stamp that answers the backend is
// this one, so this one honours it too.
//
// PARSED HERE, NOT SHARED WITH THE CLIENT'S PARSER, because this file is in the server
// library and MG_Impl is not. A malformed value is the client's Fatal{PipeVerifyBadKnob}
// (it parses first, at the first fill of the process); this side simply does not arm.
// VERIFY BUILDS ONLY: the knob belongs to the verify harness, and a push build's stamp
// stays the branch-free fill the P5d profile asked for.
struct ServerPoisonOmission {
Bool Parsed = false;
String Value;
Bool Armed = false;
MGPipeVerb Verb = MGPipeVerb::kVerbCount;
MGPipeInputField Field = MGPipeInputField::kFieldCount;
};
ServerPoisonOmission g_serverOmission;
const ServerPoisonOmission& ServerOmission() {
const String& knob = MG_Config::Features.PipePoisonOmit;
if (g_serverOmission.Parsed && knob.size() == g_serverOmission.Value.size() &&
(knob.empty() || knob == g_serverOmission.Value)) {
return g_serverOmission;
}
g_serverOmission = ServerPoisonOmission{};
g_serverOmission.Parsed = true;
g_serverOmission.Value = knob;
const auto colon = knob.find(':');
if (colon == String::npos || colon == 0 || colon + 1 >= knob.size()) return g_serverOmission;
const auto verb = MGPipeFindVerb(knob.substr(0, colon).c_str());
const auto field = MGPipeFindInputField(knob.substr(colon + 1).c_str());
if (!verb || !field) return g_serverOmission;
g_serverOmission.Armed = true;
g_serverOmission.Verb = *verb;
g_serverOmission.Field = *field;
return g_serverOmission;
}
Bool ServerOmitsStamp(MGPipeVerb verb, MGPipeInputField field) {
const ServerPoisonOmission& omission = ServerOmission();
return omission.Armed && omission.Verb == verb && omission.Field == field;
}
#endif // MOBILEGL_PIPE_VERIFY
// The strict arm of R-7.3. Same first line as the ordinary poison Fatal, so every
// existing filter on Fatal{UnmigratedPipeInput still matches, plus the class and the
// phase that retires it - a strict abort that did not say which phase owes the answer
@@ -406,14 +352,6 @@ namespace MobileGL::MG_Pipe {
Bool MGPipeServerContextIsLive() { return g_serverContextLive; }
#if MOBILEGL_BUILD_DISAGGREGATED
namespace { const void* g_serverOwnedWindow = nullptr; }
void MGPipeServerSetOwnedWindow(const void* window) { g_serverOwnedWindow = window; }
const void* MGPipeServerOwnedWindow() { return g_serverOwnedWindow; }
#endif
void MGPipeServerBlockNoteIdentity() {
// D10: THE WIDER PREDICATE, and the narrow one was a latent crash rather than a missing
// optimisation. Gated on the REHEARSAL, this early-returned for the whole life of a
@@ -477,15 +415,6 @@ namespace MobileGL::MG_Pipe {
const Uint64 bit = (answerable.Words[i / 64] >> (i % 64)) & Uint64{1};
filled.FilledGen[i] = serial & (Uint64{0} - bit);
}
#if MOBILEGL_PIPE_VERIFY
// Negative control B's server half (ServerPoisonOmission above): the one withheld pair.
{
const ServerPoisonOmission& omission = ServerOmission();
if (omission.Armed && omission.Verb == verb) {
filled.FilledGen[static_cast<SizeT>(omission.Field)] = 0;
}
}
#endif
MGPipeStampAccess::SetServerStamped(inputs, true);
// P5f (f1): the server block's identity rides the stamp (CONTRACT-P5E §3.2's
// "SetIdentity moves to ApplyOne" - the stamp is the per-verb half of ApplyOne, and
@@ -509,12 +438,6 @@ namespace MobileGL::MG_Pipe {
// AND A READ OUTSIDE THE VERB'S OWN CLASS IS STILL FATAL even for a BARRIER-PULLED
// field: the value it would be answered with was never copied for this verb, so
// counting it would trade a loud staleness for a quiet one.
#if MOBILEGL_PIPE_VERIFY
// An injected omission is reported as what it models - a stamp nobody wrote, the
// client filler's own Fatal{UnmigratedPipeInput, "<Field>@<Verb>"} - and never as the
// RoleViolation below, which would blame the wire for a withdrawal the control made.
if (serverStamped && ServerOmitsStamp(verb, field)) MGPipeInputPoisonFatalForVerb(field, verb);
#endif
if (!serverStamped ||
kMGPipeFieldOwnership[static_cast<SizeT>(field)] != MGPipeFieldOwnership::kBarrierPulled ||
!FieldIsInVerbClass(field, verb)) {
-14
View File
@@ -938,13 +938,6 @@ namespace MobileGL::MG_Pipe {
// GLContext or resurrected by stamping a verb after teardown.
void MGPipeServerSetContextLive(Bool live);
Bool MGPipeServerContextIsLive();
// P12 review fix (size reports without the knob). The SERVER's own display window while this
// session holds its lease (ServerLoop's ServerOwned arm sets it, the lease's end clears it), else
// null. A backend whose window surface does not otherwise publish its extent (Espryt) publishes
// it only for this window: a window the client named itself keeps the format-only publish every
// earlier session relied on. Apply thread only.
void MGPipeServerSetOwnedWindow(const void* window);
const void* MGPipeServerOwnedWindow();
#else
// The push-without-transport build has one role and one block, so the fill side's spelling
// folds onto gPipeInputs and PipeFill.cpp reads identically in both build flavours. An
@@ -1057,12 +1050,5 @@ namespace MobileGL::MG_Pipe {
// dereferenced, the snapshot is only ever compared). Returns false for a forwarded field,
// which has nothing to corrupt.
Bool MGPipeApplyVerifyCorruption(PipeInputs& snapshot, MGPipeInputField field);
// PipeFill.cpp. Writes the MOBILEGL_PIPE_VERIFY_FATAL=0 summary line ("N divergence(s)
// survived") NOW, while the role's log file is still open. MobileGL::Destroy calls it right
// before MG_Util::Debug::Close(): the line used to come from a namespace-scope static's
// destructor, which runs AFTER Close, and Log.cpp reopens a closed sink with "w" - so that
// summary was the only line the client half of every FATAL=0 run kept. Idempotent: a second
// call with nothing new to report, the destructor's own included, writes nothing.
void MGPipeVerifyFlushSummary();
#endif
} // namespace MobileGL::MG_Pipe
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -1,900 +0,0 @@
// MobileGL - MobileGL/MG_Client/generated_wire_trampoline.h
// Copyright (c) 2025-2026 MobileGL-Dev
// Licensed under the GNU Lesser General Public License v3.0:
// SPDX-License-Identifier: LGPL-3.0-only
// End of Source File Header
#pragma once
#include <Includes.h>
// GENERATED by scripts/generate_client_trampoline.py
MOBILEGL_GL_API void glActiveProgramEXT(GLuint program);
MOBILEGL_GL_API void glActiveShaderProgram(GLuint pipeline, GLuint program);
MOBILEGL_GL_API void glActiveTexture(GLenum texture);
MOBILEGL_GL_API void glAttachShader(GLuint program, GLuint shader);
MOBILEGL_GL_API void glBeginConditionalRender(GLuint id, GLenum mode);
MOBILEGL_GL_API void glBeginConditionalRenderNV(GLuint id, GLenum mode);
MOBILEGL_GL_API void glBeginPerfMonitorAMD(GLuint monitor);
MOBILEGL_GL_API void glBeginPerfQueryINTEL(GLuint queryHandle);
MOBILEGL_GL_API void glBeginQuery(GLenum target, GLuint id);
MOBILEGL_GL_API void glBeginQueryIndexed(GLenum target, GLuint index, GLuint id);
MOBILEGL_GL_API void glBeginTransformFeedback(GLenum primitiveMode);
MOBILEGL_GL_API void glBindAttribLocation(GLuint program, GLuint index, const GLchar* name);
MOBILEGL_GL_API void glBindBuffer(GLenum target, GLuint buffer);
MOBILEGL_GL_API void glBindBufferBase(GLenum target, GLuint index, GLuint buffer);
MOBILEGL_GL_API void glBindBufferRange(GLenum target, GLuint index, GLuint buffer, GLintptr offset, GLsizeiptr size);
MOBILEGL_GL_API void glBindBuffersBase(GLenum target, GLuint first, GLsizei count, const GLuint* buffers);
MOBILEGL_GL_API void glBindFragDataLocation(GLuint program, GLuint color, const GLchar* name);
MOBILEGL_GL_API void glBindFragDataLocationIndexed(GLuint program, GLuint colorNumber, GLuint index, const GLchar* name);
MOBILEGL_GL_API void glBindFramebuffer(GLenum target, GLuint framebuffer);
MOBILEGL_GL_API void glBindImageTexture(GLuint unit, GLuint texture, GLint level, GLboolean layered, GLint layer, GLenum access, GLenum format);
MOBILEGL_GL_API void glBindImageTextures(GLuint first, GLsizei count, const GLuint* textures);
MOBILEGL_GL_API void glBindMultiTextureEXT(GLenum texunit, GLenum target, GLuint texture);
MOBILEGL_GL_API void glBindProgramPipeline(GLuint pipeline);
MOBILEGL_GL_API void glBindRenderbuffer(GLenum target, GLuint renderbuffer);
MOBILEGL_GL_API void glBindSampler(GLuint unit, GLuint sampler);
MOBILEGL_GL_API void glBindSamplers(GLuint first, GLsizei count, const GLuint* samplers);
MOBILEGL_GL_API void glBindShadingRateImageNV(GLuint texture);
MOBILEGL_GL_API void glBindTexture(GLenum target, GLuint texture);
MOBILEGL_GL_API void glBindTextureUnit(GLuint unit, GLuint texture);
MOBILEGL_GL_API void glBindTextures(GLuint first, GLsizei count, const GLuint* textures);
MOBILEGL_GL_API void glBindTransformFeedback(GLenum target, GLuint id);
MOBILEGL_GL_API void glBindVertexArray(GLuint array);
MOBILEGL_GL_API void glBindVertexBuffer(GLuint bindingindex, GLuint buffer, GLintptr offset, GLsizei stride);
MOBILEGL_GL_API void glBlendColor(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha);
MOBILEGL_GL_API void glBlendEquation(GLenum mode);
MOBILEGL_GL_API void glBlendEquationSeparate(GLenum modeRGB, GLenum modeAlpha);
MOBILEGL_GL_API void glBlendEquationSeparatei(GLuint buf, GLenum modeRGB, GLenum modeAlpha);
MOBILEGL_GL_API void glBlendEquationSeparateiARB(GLuint buf, GLenum modeRGB, GLenum modeAlpha);
MOBILEGL_GL_API void glBlendEquationi(GLuint buf, GLenum mode);
MOBILEGL_GL_API void glBlendEquationiARB(GLuint buf, GLenum mode);
MOBILEGL_GL_API void glBlendFunc(GLenum sfactor, GLenum dfactor);
MOBILEGL_GL_API void glBlendFuncSeparate(GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha);
MOBILEGL_GL_API void glBlendFuncSeparatei(GLuint buf, GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha);
MOBILEGL_GL_API void glBlendFuncSeparateiARB(GLuint buf, GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha);
MOBILEGL_GL_API void glBlendFunci(GLuint buf, GLenum src, GLenum dst);
MOBILEGL_GL_API void glBlendFunciARB(GLuint buf, GLenum src, GLenum dst);
MOBILEGL_GL_API void glBlendParameteriNV(GLenum pname, GLint value);
MOBILEGL_GL_API void glBlitFramebuffer(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter);
MOBILEGL_GL_API void glBlitNamedFramebuffer(GLuint readFramebuffer, GLuint drawFramebuffer, GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter);
MOBILEGL_GL_API void glBufferAddressRangeNV(GLenum pname, GLuint index, GLuint64EXT address, GLsizeiptr length);
MOBILEGL_GL_API void glBufferAttachMemoryNV(GLenum target, GLuint memory, GLuint64 offset);
MOBILEGL_GL_API void glBufferData(GLenum target, GLsizeiptr size, const void* data, GLenum usage);
MOBILEGL_GL_API void glBufferPageCommitmentARB(GLenum target, GLintptr offset, GLsizeiptr size, GLboolean commit);
MOBILEGL_GL_API void glBufferPageCommitmentMemNV(GLenum target, GLintptr offset, GLsizeiptr size, GLuint memory, GLuint64 memOffset, GLboolean commit);
MOBILEGL_GL_API void glBufferStorage(GLenum target, GLsizeiptr size, const void* data, GLbitfield flags);
MOBILEGL_GL_API void glBufferSubData(GLenum target, GLintptr offset, GLsizeiptr size, const void* data);
MOBILEGL_GL_API void glCallCommandListNV(GLuint list);
MOBILEGL_GL_API GLenum glCheckFramebufferStatus(GLenum target);
MOBILEGL_GL_API GLenum glCheckNamedFramebufferStatus(GLuint framebuffer, GLenum target);
MOBILEGL_GL_API GLenum glCheckNamedFramebufferStatusEXT(GLuint framebuffer, GLenum target);
MOBILEGL_GL_API void glClampColor(GLenum target, GLenum clamp);
MOBILEGL_GL_API void glClear(GLbitfield mask);
MOBILEGL_GL_API void glClearBufferSubData(GLenum target, GLenum internalformat, GLintptr offset, GLsizeiptr size, GLenum format, GLenum type, const void* data);
MOBILEGL_GL_API void glClearBufferfi(GLenum buffer, GLint drawbuffer, GLfloat depth, GLint stencil);
MOBILEGL_GL_API void glClearColor(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha);
MOBILEGL_GL_API void glClearDepth(GLclampd depth);
MOBILEGL_GL_API void glClearDepthdNV(GLdouble depth);
MOBILEGL_GL_API void glClearDepthf(GLfloat d);
MOBILEGL_GL_API void glClearNamedBufferSubData(GLuint buffer, GLenum internalformat, GLintptr offset, GLsizeiptr size, GLenum format, GLenum type, const void* data);
MOBILEGL_GL_API void glClearNamedBufferSubDataEXT(GLuint buffer, GLenum internalformat, GLsizeiptr offset, GLsizeiptr size, GLenum format, GLenum type, const void* data);
MOBILEGL_GL_API void glClearNamedFramebufferfi(GLuint framebuffer, GLenum buffer, GLint drawbuffer, GLfloat depth, GLint stencil);
MOBILEGL_GL_API void glClearStencil(GLint s);
MOBILEGL_GL_API void glClientAttribDefaultEXT(GLbitfield mask);
MOBILEGL_GL_API GLenum glClientWaitSync(GLsync sync, GLbitfield flags, GLuint64 timeout);
MOBILEGL_GL_API void glClipControl(GLenum origin, GLenum depth);
MOBILEGL_GL_API void glColorFormatNV(GLint size, GLenum type, GLsizei stride);
MOBILEGL_GL_API void glColorMask(GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha);
MOBILEGL_GL_API void glColorMaski(GLuint index, GLboolean r, GLboolean g, GLboolean b, GLboolean a);
MOBILEGL_GL_API void glCommandListSegmentsNV(GLuint list, GLuint segments);
MOBILEGL_GL_API void glCompileCommandListNV(GLuint list);
MOBILEGL_GL_API void glCompileShader(GLuint shader);
MOBILEGL_GL_API void glConservativeRasterParameterfNV(GLenum pname, GLfloat value);
MOBILEGL_GL_API void glConservativeRasterParameteriNV(GLenum pname, GLint param);
MOBILEGL_GL_API void glCopyBufferSubData(GLenum readTarget, GLenum writeTarget, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size);
MOBILEGL_GL_API void glCopyImageSubData(GLuint srcName, GLenum srcTarget, GLint srcLevel, GLint srcX, GLint srcY, GLint srcZ, GLuint dstName, GLenum dstTarget, GLint dstLevel, GLint dstX, GLint dstY, GLint dstZ, GLsizei srcWidth, GLsizei srcHeight, GLsizei srcDepth);
MOBILEGL_GL_API void glCopyMultiTexImage1DEXT(GLenum texunit, GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLint border);
MOBILEGL_GL_API void glCopyMultiTexImage2DEXT(GLenum texunit, GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border);
MOBILEGL_GL_API void glCopyMultiTexSubImage1DEXT(GLenum texunit, GLenum target, GLint level, GLint xoffset, GLint x, GLint y, GLsizei width);
MOBILEGL_GL_API void glCopyMultiTexSubImage2DEXT(GLenum texunit, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height);
MOBILEGL_GL_API void glCopyMultiTexSubImage3DEXT(GLenum texunit, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height);
MOBILEGL_GL_API void glCopyNamedBufferSubData(GLuint readBuffer, GLuint writeBuffer, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size);
MOBILEGL_GL_API void glCopyPathNV(GLuint resultPath, GLuint srcPath);
MOBILEGL_GL_API void glCopyTexImage1D(GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLint border);
MOBILEGL_GL_API void glCopyTexImage2D(GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border);
MOBILEGL_GL_API void glCopyTexSubImage1D(GLenum target, GLint level, GLint xoffset, GLint x, GLint y, GLsizei width);
MOBILEGL_GL_API void glCopyTexSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height);
MOBILEGL_GL_API void glCopyTexSubImage3D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height);
MOBILEGL_GL_API void glCopyTextureImage1DEXT(GLuint texture, GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLint border);
MOBILEGL_GL_API void glCopyTextureImage2DEXT(GLuint texture, GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border);
MOBILEGL_GL_API void glCopyTextureSubImage1D(GLuint texture, GLint level, GLint xoffset, GLint x, GLint y, GLsizei width);
MOBILEGL_GL_API void glCopyTextureSubImage1DEXT(GLuint texture, GLenum target, GLint level, GLint xoffset, GLint x, GLint y, GLsizei width);
MOBILEGL_GL_API void glCopyTextureSubImage2D(GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height);
MOBILEGL_GL_API void glCopyTextureSubImage2DEXT(GLuint texture, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height);
MOBILEGL_GL_API void glCopyTextureSubImage3D(GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height);
MOBILEGL_GL_API void glCopyTextureSubImage3DEXT(GLuint texture, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height);
MOBILEGL_GL_API void glCoverFillPathNV(GLuint path, GLenum coverMode);
MOBILEGL_GL_API void glCoverStrokePathNV(GLuint path, GLenum coverMode);
MOBILEGL_GL_API void glCoverageModulationNV(GLenum components);
MOBILEGL_GL_API void glCoverageModulationTableNV(GLsizei n, const GLfloat* v);
MOBILEGL_GL_API void glCreateBuffers(GLsizei n, GLuint* buffers);
MOBILEGL_GL_API void glCreateCommandListsNV(GLsizei n, GLuint* lists);
MOBILEGL_GL_API void glCreateFramebuffers(GLsizei n, GLuint* framebuffers);
MOBILEGL_GL_API void glCreateProgramPipelines(GLsizei n, GLuint* pipelines);
MOBILEGL_GL_API void glCreateQueries(GLenum target, GLsizei n, GLuint* ids);
MOBILEGL_GL_API void glCreateRenderbuffers(GLsizei n, GLuint* renderbuffers);
MOBILEGL_GL_API void glCreateSamplers(GLsizei n, GLuint* samplers);
MOBILEGL_GL_API GLuint glCreateShader(GLenum type);
MOBILEGL_GL_API GLuint glCreateShaderProgramEXT(GLenum type, const GLchar* string);
MOBILEGL_GL_API void glCreateStatesNV(GLsizei n, GLuint* states);
MOBILEGL_GL_API void glCreateTextures(GLenum target, GLsizei n, GLuint* textures);
MOBILEGL_GL_API void glCreateTransformFeedbacks(GLsizei n, GLuint* ids);
MOBILEGL_GL_API void glCreateVertexArrays(GLsizei n, GLuint* arrays);
MOBILEGL_GL_API void glCullFace(GLenum mode);
MOBILEGL_GL_API void glDebugMessageControl(GLenum source, GLenum type, GLenum severity, GLsizei count, const GLuint* ids, GLboolean enabled);
MOBILEGL_GL_API void glDebugMessageInsert(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar* buf);
MOBILEGL_GL_API void glDeleteBuffers(GLsizei n, const GLuint* buffers);
MOBILEGL_GL_API void glDeleteCommandListsNV(GLsizei n, const GLuint* lists);
MOBILEGL_GL_API void glDeleteFramebuffers(GLsizei n, const GLuint* framebuffers);
MOBILEGL_GL_API void glDeleteNamedStringARB(GLint namelen, const GLchar* name);
MOBILEGL_GL_API void glDeletePathsNV(GLuint path, GLsizei range);
MOBILEGL_GL_API void glDeletePerfMonitorsAMD(GLsizei n, GLuint* monitors);
MOBILEGL_GL_API void glDeletePerfQueryINTEL(GLuint queryHandle);
MOBILEGL_GL_API void glDeleteProgram(GLuint program);
MOBILEGL_GL_API void glDeleteProgramPipelines(GLsizei n, const GLuint* pipelines);
MOBILEGL_GL_API void glDeleteQueries(GLsizei n, const GLuint* ids);
MOBILEGL_GL_API void glDeleteRenderbuffers(GLsizei n, const GLuint* renderbuffers);
MOBILEGL_GL_API void glDeleteSamplers(GLsizei count, const GLuint* samplers);
MOBILEGL_GL_API void glDeleteShader(GLuint shader);
MOBILEGL_GL_API void glDeleteStatesNV(GLsizei n, const GLuint* states);
MOBILEGL_GL_API void glDeleteSync(GLsync sync);
MOBILEGL_GL_API void glDeleteTextures(GLsizei n, const GLuint* textures);
MOBILEGL_GL_API void glDeleteTransformFeedbacks(GLsizei n, const GLuint* ids);
MOBILEGL_GL_API void glDeleteVertexArrays(GLsizei n, const GLuint* arrays);
MOBILEGL_GL_API void glDepthBoundsdNV(GLdouble zmin, GLdouble zmax);
MOBILEGL_GL_API void glDepthFunc(GLenum func);
MOBILEGL_GL_API void glDepthMask(GLboolean flag);
MOBILEGL_GL_API void glDepthRange(GLclampd near_val, GLclampd far_val);
MOBILEGL_GL_API void glDepthRangeArraydvNV(GLuint first, GLsizei count, const GLdouble* v);
MOBILEGL_GL_API void glDepthRangeArrayv(GLuint first, GLsizei count, const GLdouble* v);
MOBILEGL_GL_API void glDepthRangeIndexed(GLuint index, GLdouble n, GLdouble f);
MOBILEGL_GL_API void glDepthRangeIndexeddNV(GLuint index, GLdouble n, GLdouble f);
MOBILEGL_GL_API void glDepthRangedNV(GLdouble zNear, GLdouble zFar);
MOBILEGL_GL_API void glDepthRangef(GLfloat n, GLfloat f);
MOBILEGL_GL_API void glDetachShader(GLuint program, GLuint shader);
MOBILEGL_GL_API void glDisable(GLenum cap);
MOBILEGL_GL_API void glDisableClientStateIndexedEXT(GLenum array, GLuint index);
MOBILEGL_GL_API void glDisableClientStateiEXT(GLenum array, GLuint index);
MOBILEGL_GL_API void glDisableIndexedEXT(GLenum target, GLuint index);
MOBILEGL_GL_API void glDisableVertexArrayAttrib(GLuint vaobj, GLuint index);
MOBILEGL_GL_API void glDisableVertexArrayAttribEXT(GLuint vaobj, GLuint index);
MOBILEGL_GL_API void glDisableVertexArrayEXT(GLuint vaobj, GLenum array);
MOBILEGL_GL_API void glDisableVertexAttribArray(GLuint index);
MOBILEGL_GL_API void glDisablei(GLenum target, GLuint index);
MOBILEGL_GL_API void glDispatchCompute(GLuint num_groups_x, GLuint num_groups_y, GLuint num_groups_z);
MOBILEGL_GL_API void glDispatchComputeGroupSizeARB(GLuint num_groups_x, GLuint num_groups_y, GLuint num_groups_z, GLuint group_size_x, GLuint group_size_y, GLuint group_size_z);
MOBILEGL_GL_API void glDispatchComputeIndirect(GLintptr indirect);
MOBILEGL_GL_API void glDrawArrays(GLenum mode, GLint first, GLsizei count);
MOBILEGL_GL_API void glDrawArraysInstanced(GLenum mode, GLint first, GLsizei count, GLsizei instancecount);
MOBILEGL_GL_API void glDrawArraysInstancedBaseInstance(GLenum mode, GLint first, GLsizei count, GLsizei instancecount, GLuint baseinstance);
MOBILEGL_GL_API void glDrawBuffer(GLenum mode);
MOBILEGL_GL_API void glDrawBuffers(GLsizei n, const GLenum* bufs);
MOBILEGL_GL_API void glDrawCommandsAddressNV(GLenum primitiveMode, const GLuint64* indirects, const GLsizei* sizes, GLuint count);
MOBILEGL_GL_API void glDrawCommandsStatesAddressNV(const GLuint64* indirects, const GLsizei* sizes, const GLuint* states, const GLuint* fbos, GLuint count);
MOBILEGL_GL_API void glDrawElements(GLenum mode, GLsizei count, GLenum type, const void* indices);
MOBILEGL_GL_API void glDrawElementsBaseVertex(GLenum mode, GLsizei count, GLenum type, const void* indices, GLint basevertex);
MOBILEGL_GL_API void glDrawElementsInstanced(GLenum mode, GLsizei count, GLenum type, const void* indices, GLsizei instancecount);
MOBILEGL_GL_API void glDrawElementsInstancedBaseInstance(GLenum mode, GLsizei count, GLenum type, const void* indices, GLsizei instancecount, GLuint baseinstance);
MOBILEGL_GL_API void glDrawElementsInstancedBaseVertex(GLenum mode, GLsizei count, GLenum type, const void* indices, GLsizei instancecount, GLint basevertex);
MOBILEGL_GL_API void glDrawElementsInstancedBaseVertexBaseInstance(GLenum mode, GLsizei count, GLenum type, const void* indices, GLsizei instancecount, GLint basevertex, GLuint baseinstance);
MOBILEGL_GL_API void glDrawMeshTasksIndirectNV(GLintptr indirect);
MOBILEGL_GL_API void glDrawMeshTasksNV(GLuint first, GLuint count);
MOBILEGL_GL_API void glDrawRangeElements(GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const void* indices);
MOBILEGL_GL_API void glDrawRangeElementsBaseVertex(GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const void* indices, GLint basevertex);
MOBILEGL_GL_API void glDrawTransformFeedback(GLenum mode, GLuint id);
MOBILEGL_GL_API void glDrawTransformFeedbackInstanced(GLenum mode, GLuint id, GLsizei instancecount);
MOBILEGL_GL_API void glDrawTransformFeedbackStream(GLenum mode, GLuint id, GLuint stream);
MOBILEGL_GL_API void glDrawTransformFeedbackStreamInstanced(GLenum mode, GLuint id, GLuint stream, GLsizei instancecount);
MOBILEGL_GL_API void glDrawVkImageNV(GLuint64 vkImage, GLuint sampler, GLfloat x0, GLfloat y0, GLfloat x1, GLfloat y1, GLfloat z, GLfloat s0, GLfloat t0, GLfloat s1, GLfloat t1);
MOBILEGL_GL_API void glEdgeFlagFormatNV(GLsizei stride);
MOBILEGL_GL_API void glEnable(GLenum cap);
MOBILEGL_GL_API void glEnableClientStateIndexedEXT(GLenum array, GLuint index);
MOBILEGL_GL_API void glEnableClientStateiEXT(GLenum array, GLuint index);
MOBILEGL_GL_API void glEnableIndexedEXT(GLenum target, GLuint index);
MOBILEGL_GL_API void glEnableVertexArrayAttrib(GLuint vaobj, GLuint index);
MOBILEGL_GL_API void glEnableVertexArrayAttribEXT(GLuint vaobj, GLuint index);
MOBILEGL_GL_API void glEnableVertexArrayEXT(GLuint vaobj, GLenum array);
MOBILEGL_GL_API void glEnableVertexAttribArray(GLuint index);
MOBILEGL_GL_API void glEnablei(GLenum target, GLuint index);
MOBILEGL_GL_API void glEndPerfMonitorAMD(GLuint monitor);
MOBILEGL_GL_API void glEndPerfQueryINTEL(GLuint queryHandle);
MOBILEGL_GL_API void glEndQuery(GLenum target);
MOBILEGL_GL_API void glEndQueryIndexed(GLenum target, GLuint index);
MOBILEGL_GL_API void glFlushMappedBufferRange(GLenum target, GLintptr offset, GLsizeiptr length);
MOBILEGL_GL_API void glFlushMappedNamedBufferRange(GLuint buffer, GLintptr offset, GLsizeiptr length);
MOBILEGL_GL_API void glFlushMappedNamedBufferRangeEXT(GLuint buffer, GLintptr offset, GLsizeiptr length);
MOBILEGL_GL_API void glFogCoordFormatNV(GLenum type, GLsizei stride);
MOBILEGL_GL_API void glFragmentCoverageColorNV(GLuint color);
MOBILEGL_GL_API void glFramebufferDrawBufferEXT(GLuint framebuffer, GLenum mode);
MOBILEGL_GL_API void glFramebufferDrawBuffersEXT(GLuint framebuffer, GLsizei n, const GLenum* bufs);
MOBILEGL_GL_API void glFramebufferParameteri(GLenum target, GLenum pname, GLint param);
MOBILEGL_GL_API void glFramebufferParameteriMESA(GLenum target, GLenum pname, GLint param);
MOBILEGL_GL_API void glFramebufferReadBufferEXT(GLuint framebuffer, GLenum mode);
MOBILEGL_GL_API void glFramebufferRenderbuffer(GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer);
MOBILEGL_GL_API void glFramebufferSampleLocationsfvARB(GLenum target, GLuint start, GLsizei count, const GLfloat* v);
MOBILEGL_GL_API void glFramebufferSampleLocationsfvNV(GLenum target, GLuint start, GLsizei count, const GLfloat* v);
MOBILEGL_GL_API void glFramebufferTexture(GLenum target, GLenum attachment, GLuint texture, GLint level);
MOBILEGL_GL_API void glFramebufferTexture1D(GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level);
MOBILEGL_GL_API void glFramebufferTexture1DEXT(GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level);
MOBILEGL_GL_API void glFramebufferTexture2D(GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level);
MOBILEGL_GL_API void glFramebufferTexture3D(GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLint zoffset);
MOBILEGL_GL_API void glFramebufferTexture3DEXT(GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLint zoffset);
MOBILEGL_GL_API void glFramebufferTextureFaceARB(GLenum target, GLenum attachment, GLuint texture, GLint level, GLenum face);
MOBILEGL_GL_API void glFramebufferTextureLayer(GLenum target, GLenum attachment, GLuint texture, GLint level, GLint layer);
MOBILEGL_GL_API void glFramebufferTextureMultiviewOVR(GLenum target, GLenum attachment, GLuint texture, GLint level, GLint baseViewIndex, GLsizei numViews);
MOBILEGL_GL_API void glFrontFace(GLenum mode);
MOBILEGL_GL_API void glGenBuffers(GLsizei n, GLuint* buffers);
MOBILEGL_GL_API void glGenFramebuffers(GLsizei n, GLuint* framebuffers);
MOBILEGL_GL_API GLuint glGenPathsNV(GLsizei range);
MOBILEGL_GL_API void glGenPerfMonitorsAMD(GLsizei n, GLuint* monitors);
MOBILEGL_GL_API void glGenProgramPipelines(GLsizei n, GLuint* pipelines);
MOBILEGL_GL_API void glGenQueries(GLsizei n, GLuint* ids);
MOBILEGL_GL_API void glGenRenderbuffers(GLsizei n, GLuint* renderbuffers);
MOBILEGL_GL_API void glGenSamplers(GLsizei count, GLuint* samplers);
MOBILEGL_GL_API void glGenTextures(GLsizei n, GLuint* textures);
MOBILEGL_GL_API void glGenTransformFeedbacks(GLsizei n, GLuint* ids);
MOBILEGL_GL_API void glGenVertexArrays(GLsizei n, GLuint* arrays);
MOBILEGL_GL_API void glGenerateMipmap(GLenum target);
MOBILEGL_GL_API void glGenerateMultiTexMipmapEXT(GLenum texunit, GLenum target);
MOBILEGL_GL_API void glGenerateTextureMipmap(GLuint texture);
MOBILEGL_GL_API void glGenerateTextureMipmapEXT(GLuint texture, GLenum target);
MOBILEGL_GL_API void glGetActiveAtomicCounterBufferiv(GLuint program, GLuint bufferIndex, GLenum pname, GLint* params);
MOBILEGL_GL_API void glGetActiveSubroutineUniformiv(GLuint program, GLenum shadertype, GLuint index, GLenum pname, GLint* values);
MOBILEGL_GL_API void glGetActiveUniformBlockiv(GLuint program, GLuint uniformBlockIndex, GLenum pname, GLint* params);
MOBILEGL_GL_API GLint glGetAttribLocation(GLuint program, const GLchar* name);
MOBILEGL_GL_API void glGetBooleanv(GLenum pname, GLboolean* data);
MOBILEGL_GL_API void glGetBufferParameteri64v(GLenum target, GLenum pname, GLint64* params);
MOBILEGL_GL_API void glGetBufferParameteriv(GLenum target, GLenum pname, GLint* params);
MOBILEGL_GL_API void glGetBufferParameterui64vNV(GLenum target, GLenum pname, GLuint64EXT* params);
MOBILEGL_GL_API void glGetBufferSubData(GLenum target, GLintptr offset, GLsizeiptr size, void* data);
MOBILEGL_GL_API GLuint glGetCommandHeaderNV(GLenum tokenID, GLuint size);
MOBILEGL_GL_API GLuint glGetDebugMessageLog(GLuint count, GLsizei bufSize, GLenum* sources, GLenum* types, GLuint* ids, GLenum* severities, GLsizei* lengths, GLchar* messageLog);
MOBILEGL_GL_API void glGetDoublei_vEXT(GLenum pname, GLuint index, GLdouble* params);
MOBILEGL_GL_API void glGetDoublev(GLenum pname, GLdouble* params);
MOBILEGL_GL_API void glGetFloati_vEXT(GLenum pname, GLuint index, GLfloat* params);
MOBILEGL_GL_API void glGetFloatv(GLenum pname, GLfloat* data);
MOBILEGL_GL_API GLint glGetFragDataIndex(GLuint program, const GLchar* name);
MOBILEGL_GL_API GLint glGetFragDataLocation(GLuint program, const GLchar* name);
MOBILEGL_GL_API void glGetFramebufferAttachmentParameteriv(GLenum target, GLenum attachment, GLenum pname, GLint* params);
MOBILEGL_GL_API void glGetFramebufferParameteriv(GLenum target, GLenum pname, GLint* params);
MOBILEGL_GL_API void glGetFramebufferParameterivMESA(GLenum target, GLenum pname, GLint* params);
MOBILEGL_GL_API GLuint64 glGetImageHandleARB(GLuint texture, GLint level, GLboolean layered, GLint layer, GLenum format);
MOBILEGL_GL_API GLuint64 glGetImageHandleNV(GLuint texture, GLint level, GLboolean layered, GLint layer, GLenum format);
MOBILEGL_GL_API void glGetInteger64v(GLenum pname, GLint64* data);
MOBILEGL_GL_API void glGetIntegerv(GLenum pname, GLint* data);
MOBILEGL_GL_API void glGetInternalformatSampleivNV(GLenum target, GLenum internalformat, GLsizei samples, GLenum pname, GLsizei count, GLint* params);
MOBILEGL_GL_API void glGetInternalformati64v(GLenum target, GLenum internalformat, GLenum pname, GLsizei count, GLint64* params);
MOBILEGL_GL_API void glGetInternalformativ(GLenum target, GLenum internalformat, GLenum pname, GLsizei bufSize, GLint* params);
MOBILEGL_GL_API void glGetMemoryObjectDetachedResourcesuivNV(GLuint memory, GLenum pname, GLint first, GLsizei count, GLuint* params);
MOBILEGL_GL_API void glGetMultiTexEnvfvEXT(GLenum texunit, GLenum target, GLenum pname, GLfloat* params);
MOBILEGL_GL_API void glGetMultiTexEnvivEXT(GLenum texunit, GLenum target, GLenum pname, GLint* params);
MOBILEGL_GL_API void glGetMultiTexGendvEXT(GLenum texunit, GLenum coord, GLenum pname, GLdouble* params);
MOBILEGL_GL_API void glGetMultiTexGenfvEXT(GLenum texunit, GLenum coord, GLenum pname, GLfloat* params);
MOBILEGL_GL_API void glGetMultiTexGenivEXT(GLenum texunit, GLenum coord, GLenum pname, GLint* params);
MOBILEGL_GL_API void glGetMultiTexLevelParameterfvEXT(GLenum texunit, GLenum target, GLint level, GLenum pname, GLfloat* params);
MOBILEGL_GL_API void glGetMultiTexLevelParameterivEXT(GLenum texunit, GLenum target, GLint level, GLenum pname, GLint* params);
MOBILEGL_GL_API void glGetMultiTexParameterIivEXT(GLenum texunit, GLenum target, GLenum pname, GLint* params);
MOBILEGL_GL_API void glGetMultiTexParameterIuivEXT(GLenum texunit, GLenum target, GLenum pname, GLuint* params);
MOBILEGL_GL_API void glGetMultiTexParameterfvEXT(GLenum texunit, GLenum target, GLenum pname, GLfloat* params);
MOBILEGL_GL_API void glGetMultiTexParameterivEXT(GLenum texunit, GLenum target, GLenum pname, GLint* params);
MOBILEGL_GL_API void glGetMultisamplefv(GLenum pname, GLuint index, GLfloat* val);
MOBILEGL_GL_API void glGetNamedBufferParameteri64v(GLuint buffer, GLenum pname, GLint64* params);
MOBILEGL_GL_API void glGetNamedBufferParameteriv(GLuint buffer, GLenum pname, GLint* params);
MOBILEGL_GL_API void glGetNamedBufferParameterivEXT(GLuint buffer, GLenum pname, GLint* params);
MOBILEGL_GL_API void glGetNamedBufferParameterui64vNV(GLuint buffer, GLenum pname, GLuint64EXT* params);
MOBILEGL_GL_API void glGetNamedBufferSubData(GLuint buffer, GLintptr offset, GLsizeiptr size, void* data);
MOBILEGL_GL_API void glGetNamedBufferSubDataEXT(GLuint buffer, GLintptr offset, GLsizeiptr size, void* data);
MOBILEGL_GL_API void glGetNamedFramebufferAttachmentParameteriv(GLuint framebuffer, GLenum attachment, GLenum pname, GLint* params);
MOBILEGL_GL_API void glGetNamedFramebufferAttachmentParameterivEXT(GLuint framebuffer, GLenum attachment, GLenum pname, GLint* params);
MOBILEGL_GL_API void glGetNamedFramebufferParameteriv(GLuint framebuffer, GLenum pname, GLint* param);
MOBILEGL_GL_API void glGetNamedFramebufferParameterivEXT(GLuint framebuffer, GLenum pname, GLint* params);
MOBILEGL_GL_API void glGetNamedProgramivEXT(GLuint program, GLenum target, GLenum pname, GLint* params);
MOBILEGL_GL_API void glGetNamedRenderbufferParameteriv(GLuint renderbuffer, GLenum pname, GLint* params);
MOBILEGL_GL_API void glGetNamedRenderbufferParameterivEXT(GLuint renderbuffer, GLenum pname, GLint* params);
MOBILEGL_GL_API void glGetNamedStringivARB(GLint namelen, const GLchar* name, GLenum pname, GLint* params);
MOBILEGL_GL_API GLfloat glGetPathLengthNV(GLuint path, GLsizei startSegment, GLsizei numSegments);
MOBILEGL_GL_API void glGetPathParameterfvNV(GLuint path, GLenum pname, GLfloat* value);
MOBILEGL_GL_API void glGetPathParameterivNV(GLuint path, GLenum pname, GLint* value);
MOBILEGL_GL_API void glGetPerfMonitorCounterDataAMD(GLuint monitor, GLenum pname, GLsizei dataSize, GLuint* data, GLint* bytesWritten);
MOBILEGL_GL_API void glGetProgramInterfaceiv(GLuint program, GLenum programInterface, GLenum pname, GLint* params);
MOBILEGL_GL_API void glGetProgramPipelineiv(GLuint pipeline, GLenum pname, GLint* params);
MOBILEGL_GL_API GLuint glGetProgramResourceIndex(GLuint program, GLenum programInterface, const GLchar* name);
MOBILEGL_GL_API GLint glGetProgramResourceLocation(GLuint program, GLenum programInterface, const GLchar* name);
MOBILEGL_GL_API GLint glGetProgramResourceLocationIndex(GLuint program, GLenum programInterface, const GLchar* name);
MOBILEGL_GL_API void glGetProgramResourcefvNV(GLuint program, GLenum programInterface, GLuint index, GLsizei propCount, const GLenum* props, GLsizei count, GLsizei* length, GLfloat* params);
MOBILEGL_GL_API void glGetProgramStageiv(GLuint program, GLenum shadertype, GLenum pname, GLint* values);
MOBILEGL_GL_API void glGetProgramiv(GLuint program, GLenum pname, GLint* params);
MOBILEGL_GL_API void glGetQueryBufferObjecti64v(GLuint id, GLuint buffer, GLenum pname, GLintptr offset);
MOBILEGL_GL_API void glGetQueryBufferObjectiv(GLuint id, GLuint buffer, GLenum pname, GLintptr offset);
MOBILEGL_GL_API void glGetQueryBufferObjectui64v(GLuint id, GLuint buffer, GLenum pname, GLintptr offset);
MOBILEGL_GL_API void glGetQueryBufferObjectuiv(GLuint id, GLuint buffer, GLenum pname, GLintptr offset);
MOBILEGL_GL_API void glGetQueryIndexediv(GLenum target, GLuint index, GLenum pname, GLint* params);
MOBILEGL_GL_API void glGetQueryObjecti64v(GLuint id, GLenum pname, GLint64* params);
MOBILEGL_GL_API void glGetQueryObjectiv(GLuint id, GLenum pname, GLint* params);
MOBILEGL_GL_API void glGetQueryObjectui64v(GLuint id, GLenum pname, GLuint64* params);
MOBILEGL_GL_API void glGetQueryObjectuiv(GLuint id, GLenum pname, GLuint* params);
MOBILEGL_GL_API void glGetQueryiv(GLenum target, GLenum pname, GLint* params);
MOBILEGL_GL_API void glGetRenderbufferParameteriv(GLenum target, GLenum pname, GLint* params);
MOBILEGL_GL_API void glGetSamplerParameterIiv(GLuint sampler, GLenum pname, GLint* params);
MOBILEGL_GL_API void glGetSamplerParameterIuiv(GLuint sampler, GLenum pname, GLuint* params);
MOBILEGL_GL_API void glGetSamplerParameterfv(GLuint sampler, GLenum pname, GLfloat* params);
MOBILEGL_GL_API void glGetSamplerParameteriv(GLuint sampler, GLenum pname, GLint* params);
MOBILEGL_GL_API void glGetShaderiv(GLuint shader, GLenum pname, GLint* params);
MOBILEGL_GL_API GLushort glGetStageIndexNV(GLenum shadertype);
MOBILEGL_GL_API const GLubyte* glGetString(GLenum name);
MOBILEGL_GL_API const GLubyte* glGetStringi(GLenum name, GLuint index);
MOBILEGL_GL_API GLuint glGetSubroutineIndex(GLuint program, GLenum shadertype, const GLchar* name);
MOBILEGL_GL_API GLint glGetSubroutineUniformLocation(GLuint program, GLenum shadertype, const GLchar* name);
MOBILEGL_GL_API void glGetSynciv(GLsync sync, GLenum pname, GLsizei bufSize, GLsizei* length, GLint* values);
MOBILEGL_GL_API void glGetTexLevelParameterfv(GLenum target, GLint level, GLenum pname, GLfloat* params);
MOBILEGL_GL_API void glGetTexLevelParameteriv(GLenum target, GLint level, GLenum pname, GLint* params);
MOBILEGL_GL_API void glGetTexParameterIiv(GLenum target, GLenum pname, GLint* params);
MOBILEGL_GL_API void glGetTexParameterIuiv(GLenum target, GLenum pname, GLuint* params);
MOBILEGL_GL_API void glGetTexParameterfv(GLenum target, GLenum pname, GLfloat* params);
MOBILEGL_GL_API void glGetTexParameteriv(GLenum target, GLenum pname, GLint* params);
MOBILEGL_GL_API GLuint64 glGetTextureHandleARB(GLuint texture);
MOBILEGL_GL_API GLuint64 glGetTextureHandleNV(GLuint texture);
MOBILEGL_GL_API void glGetTextureLevelParameterfv(GLuint texture, GLint level, GLenum pname, GLfloat* params);
MOBILEGL_GL_API void glGetTextureLevelParameterfvEXT(GLuint texture, GLenum target, GLint level, GLenum pname, GLfloat* params);
MOBILEGL_GL_API void glGetTextureLevelParameteriv(GLuint texture, GLint level, GLenum pname, GLint* params);
MOBILEGL_GL_API void glGetTextureLevelParameterivEXT(GLuint texture, GLenum target, GLint level, GLenum pname, GLint* params);
MOBILEGL_GL_API void glGetTextureParameterIiv(GLuint texture, GLenum pname, GLint* params);
MOBILEGL_GL_API void glGetTextureParameterIivEXT(GLuint texture, GLenum target, GLenum pname, GLint* params);
MOBILEGL_GL_API void glGetTextureParameterIuiv(GLuint texture, GLenum pname, GLuint* params);
MOBILEGL_GL_API void glGetTextureParameterIuivEXT(GLuint texture, GLenum target, GLenum pname, GLuint* params);
MOBILEGL_GL_API void glGetTextureParameterfv(GLuint texture, GLenum pname, GLfloat* params);
MOBILEGL_GL_API void glGetTextureParameterfvEXT(GLuint texture, GLenum target, GLenum pname, GLfloat* params);
MOBILEGL_GL_API void glGetTextureParameteriv(GLuint texture, GLenum pname, GLint* params);
MOBILEGL_GL_API void glGetTextureParameterivEXT(GLuint texture, GLenum target, GLenum pname, GLint* params);
MOBILEGL_GL_API GLuint64 glGetTextureSamplerHandleARB(GLuint texture, GLuint sampler);
MOBILEGL_GL_API GLuint64 glGetTextureSamplerHandleNV(GLuint texture, GLuint sampler);
MOBILEGL_GL_API void glGetTransformFeedbacki64_v(GLuint xfb, GLenum pname, GLuint index, GLint64* param);
MOBILEGL_GL_API void glGetTransformFeedbacki_v(GLuint xfb, GLenum pname, GLuint index, GLint* param);
MOBILEGL_GL_API void glGetTransformFeedbackiv(GLuint xfb, GLenum pname, GLint* param);
MOBILEGL_GL_API GLuint glGetUniformBlockIndex(GLuint program, const GLchar* uniformBlockName);
MOBILEGL_GL_API GLint glGetUniformLocation(GLuint program, const GLchar* name);
MOBILEGL_GL_API void glGetVertexArrayIndexed64iv(GLuint vaobj, GLuint index, GLenum pname, GLint64* param);
MOBILEGL_GL_API void glGetVertexArrayIndexediv(GLuint vaobj, GLuint index, GLenum pname, GLint* param);
MOBILEGL_GL_API void glGetVertexArrayIntegeri_vEXT(GLuint vaobj, GLuint index, GLenum pname, GLint* param);
MOBILEGL_GL_API void glGetVertexArrayIntegervEXT(GLuint vaobj, GLenum pname, GLint* param);
MOBILEGL_GL_API void glGetVertexArrayiv(GLuint vaobj, GLenum pname, GLint* param);
MOBILEGL_GL_API void glGetVertexAttribIiv(GLuint index, GLenum pname, GLint* params);
MOBILEGL_GL_API void glGetVertexAttribIuiv(GLuint index, GLenum pname, GLuint* params);
MOBILEGL_GL_API void glGetVertexAttribLdv(GLuint index, GLenum pname, GLdouble* params);
MOBILEGL_GL_API void glGetVertexAttribLi64vNV(GLuint index, GLenum pname, GLint64EXT* params);
MOBILEGL_GL_API void glGetVertexAttribLui64vARB(GLuint index, GLenum pname, GLuint64EXT* params);
MOBILEGL_GL_API void glGetVertexAttribLui64vNV(GLuint index, GLenum pname, GLuint64EXT* params);
MOBILEGL_GL_API void glGetVertexAttribdv(GLuint index, GLenum pname, GLdouble* params);
MOBILEGL_GL_API void glGetVertexAttribfv(GLuint index, GLenum pname, GLfloat* params);
MOBILEGL_GL_API void glGetVertexAttribiv(GLuint index, GLenum pname, GLint* params);
MOBILEGL_GL_API void glHint(GLenum target, GLenum mode);
MOBILEGL_GL_API void glIndexFormatNV(GLenum type, GLsizei stride);
MOBILEGL_GL_API void glInsertEventMarkerEXT(GLsizei length, const GLchar* marker);
MOBILEGL_GL_API void glInterpolatePathsNV(GLuint resultPath, GLuint pathA, GLuint pathB, GLfloat weight);
MOBILEGL_GL_API void glInvalidateBufferData(GLuint buffer);
MOBILEGL_GL_API void glInvalidateBufferSubData(GLuint buffer, GLintptr offset, GLsizeiptr length);
MOBILEGL_GL_API void glInvalidateTexImage(GLuint texture, GLint level);
MOBILEGL_GL_API void glInvalidateTexSubImage(GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth);
MOBILEGL_GL_API GLboolean glIsBuffer(GLuint buffer);
MOBILEGL_GL_API GLboolean glIsBufferResidentNV(GLenum target);
MOBILEGL_GL_API GLboolean glIsCommandListNV(GLuint list);
MOBILEGL_GL_API GLboolean glIsEnabled(GLenum cap);
MOBILEGL_GL_API GLboolean glIsEnabledIndexedEXT(GLenum target, GLuint index);
MOBILEGL_GL_API GLboolean glIsEnabledi(GLenum target, GLuint index);
MOBILEGL_GL_API GLboolean glIsFramebuffer(GLuint framebuffer);
MOBILEGL_GL_API GLboolean glIsImageHandleResidentARB(GLuint64 handle);
MOBILEGL_GL_API GLboolean glIsImageHandleResidentNV(GLuint64 handle);
MOBILEGL_GL_API GLboolean glIsNamedBufferResidentNV(GLuint buffer);
MOBILEGL_GL_API GLboolean glIsNamedStringARB(GLint namelen, const GLchar* name);
MOBILEGL_GL_API GLboolean glIsPathNV(GLuint path);
MOBILEGL_GL_API GLboolean glIsPointInFillPathNV(GLuint path, GLuint mask, GLfloat x, GLfloat y);
MOBILEGL_GL_API GLboolean glIsPointInStrokePathNV(GLuint path, GLfloat x, GLfloat y);
MOBILEGL_GL_API GLboolean glIsProgram(GLuint program);
MOBILEGL_GL_API GLboolean glIsProgramPipeline(GLuint pipeline);
MOBILEGL_GL_API GLboolean glIsQuery(GLuint id);
MOBILEGL_GL_API GLboolean glIsRenderbuffer(GLuint renderbuffer);
MOBILEGL_GL_API GLboolean glIsSampler(GLuint sampler);
MOBILEGL_GL_API GLboolean glIsShader(GLuint shader);
MOBILEGL_GL_API GLboolean glIsStateNV(GLuint state);
MOBILEGL_GL_API GLboolean glIsSync(GLsync sync);
MOBILEGL_GL_API GLboolean glIsTexture(GLuint texture);
MOBILEGL_GL_API GLboolean glIsTextureHandleResidentARB(GLuint64 handle);
MOBILEGL_GL_API GLboolean glIsTextureHandleResidentNV(GLuint64 handle);
MOBILEGL_GL_API GLboolean glIsTransformFeedback(GLuint id);
MOBILEGL_GL_API GLboolean glIsVertexArray(GLuint array);
MOBILEGL_GL_API void glLabelObjectEXT(GLenum type, GLuint object, GLsizei length, const GLchar* label);
MOBILEGL_GL_API void glLineWidth(GLfloat width);
MOBILEGL_GL_API void glLinkProgram(GLuint program);
MOBILEGL_GL_API void glLogicOp(GLenum opcode);
MOBILEGL_GL_API void glMakeBufferNonResidentNV(GLenum target);
MOBILEGL_GL_API void glMakeBufferResidentNV(GLenum target, GLenum access);
MOBILEGL_GL_API void glMakeImageHandleNonResidentARB(GLuint64 handle);
MOBILEGL_GL_API void glMakeImageHandleNonResidentNV(GLuint64 handle);
MOBILEGL_GL_API void glMakeImageHandleResidentARB(GLuint64 handle, GLenum access);
MOBILEGL_GL_API void glMakeImageHandleResidentNV(GLuint64 handle, GLenum access);
MOBILEGL_GL_API void glMakeNamedBufferNonResidentNV(GLuint buffer);
MOBILEGL_GL_API void glMakeNamedBufferResidentNV(GLuint buffer, GLenum access);
MOBILEGL_GL_API void glMakeTextureHandleNonResidentARB(GLuint64 handle);
MOBILEGL_GL_API void glMakeTextureHandleNonResidentNV(GLuint64 handle);
MOBILEGL_GL_API void glMakeTextureHandleResidentARB(GLuint64 handle);
MOBILEGL_GL_API void glMakeTextureHandleResidentNV(GLuint64 handle);
MOBILEGL_GL_API void* glMapBuffer(GLenum target, GLenum access);
MOBILEGL_GL_API void* glMapBufferRange(GLenum target, GLintptr offset, GLsizeiptr length, GLbitfield access);
MOBILEGL_GL_API void glMatrixFrustumEXT(GLenum mode, GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble zNear, GLdouble zFar);
MOBILEGL_GL_API void glMatrixLoadIdentityEXT(GLenum mode);
MOBILEGL_GL_API void glMatrixOrthoEXT(GLenum mode, GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble zNear, GLdouble zFar);
MOBILEGL_GL_API void glMatrixPopEXT(GLenum mode);
MOBILEGL_GL_API void glMatrixPushEXT(GLenum mode);
MOBILEGL_GL_API void glMatrixRotatedEXT(GLenum mode, GLdouble ane, GLdouble x, GLdouble y, GLdouble z);
MOBILEGL_GL_API void glMatrixRotatefEXT(GLenum mode, GLfloat ane, GLfloat x, GLfloat y, GLfloat z);
MOBILEGL_GL_API void glMatrixScaledEXT(GLenum mode, GLdouble x, GLdouble y, GLdouble z);
MOBILEGL_GL_API void glMatrixScalefEXT(GLenum mode, GLfloat x, GLfloat y, GLfloat z);
MOBILEGL_GL_API void glMatrixTranslatedEXT(GLenum mode, GLdouble x, GLdouble y, GLdouble z);
MOBILEGL_GL_API void glMatrixTranslatefEXT(GLenum mode, GLfloat x, GLfloat y, GLfloat z);
MOBILEGL_GL_API void glMaxShaderCompilerThreadsARB(GLuint count);
MOBILEGL_GL_API void glMaxShaderCompilerThreadsKHR(GLuint count);
MOBILEGL_GL_API void glMemoryBarrier(GLbitfield barriers);
MOBILEGL_GL_API void glMemoryBarrierByRegion(GLbitfield barriers);
MOBILEGL_GL_API void glMinSampleShading(GLfloat value);
MOBILEGL_GL_API void glMultiDrawMeshTasksIndirectCountNV(GLintptr indirect, GLintptr drawcount, GLsizei maxdrawcount, GLsizei stride);
MOBILEGL_GL_API void glMultiDrawMeshTasksIndirectNV(GLintptr indirect, GLsizei drawcount, GLsizei stride);
MOBILEGL_GL_API void glMultiTexBufferEXT(GLenum texunit, GLenum target, GLenum internalformat, GLuint buffer);
MOBILEGL_GL_API void glMultiTexCoordPointerEXT(GLenum texunit, GLint size, GLenum type, GLsizei stride, const void* pointer);
MOBILEGL_GL_API void glMultiTexEnvfEXT(GLenum texunit, GLenum target, GLenum pname, GLfloat param);
MOBILEGL_GL_API void glMultiTexEnviEXT(GLenum texunit, GLenum target, GLenum pname, GLint param);
MOBILEGL_GL_API void glMultiTexGendEXT(GLenum texunit, GLenum coord, GLenum pname, GLdouble param);
MOBILEGL_GL_API void glMultiTexGenfEXT(GLenum texunit, GLenum coord, GLenum pname, GLfloat param);
MOBILEGL_GL_API void glMultiTexGeniEXT(GLenum texunit, GLenum coord, GLenum pname, GLint param);
MOBILEGL_GL_API void glMultiTexParameterfEXT(GLenum texunit, GLenum target, GLenum pname, GLfloat param);
MOBILEGL_GL_API void glMultiTexParameteriEXT(GLenum texunit, GLenum target, GLenum pname, GLint param);
MOBILEGL_GL_API void glMultiTexRenderbufferEXT(GLenum texunit, GLenum target, GLuint renderbuffer);
MOBILEGL_GL_API void glNamedBufferAttachMemoryNV(GLuint buffer, GLuint memory, GLuint64 offset);
MOBILEGL_GL_API void glNamedBufferData(GLuint buffer, GLsizeiptr size, const void* data, GLenum usage);
MOBILEGL_GL_API void glNamedBufferDataEXT(GLuint buffer, GLsizeiptr size, const void* data, GLenum usage);
MOBILEGL_GL_API void glNamedBufferPageCommitmentARB(GLuint buffer, GLintptr offset, GLsizeiptr size, GLboolean commit);
MOBILEGL_GL_API void glNamedBufferPageCommitmentEXT(GLuint buffer, GLintptr offset, GLsizeiptr size, GLboolean commit);
MOBILEGL_GL_API void glNamedBufferPageCommitmentMemNV(GLuint buffer, GLintptr offset, GLsizeiptr size, GLuint memory, GLuint64 memOffset, GLboolean commit);
MOBILEGL_GL_API void glNamedBufferStorage(GLuint buffer, GLsizeiptr size, const void* data, GLbitfield flags);
MOBILEGL_GL_API void glNamedBufferStorageEXT(GLuint buffer, GLsizeiptr size, const void* data, GLbitfield flags);
MOBILEGL_GL_API void glNamedBufferSubData(GLuint buffer, GLintptr offset, GLsizeiptr size, const void* data);
MOBILEGL_GL_API void glNamedBufferSubDataEXT(GLuint buffer, GLintptr offset, GLsizeiptr size, const void* data);
MOBILEGL_GL_API void glNamedCopyBufferSubDataEXT(GLuint readBuffer, GLuint writeBuffer, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size);
MOBILEGL_GL_API void glNamedFramebufferDrawBuffer(GLuint framebuffer, GLenum buf);
MOBILEGL_GL_API void glNamedFramebufferDrawBuffers(GLuint framebuffer, GLsizei n, const GLenum* bufs);
MOBILEGL_GL_API void glNamedFramebufferParameteri(GLuint framebuffer, GLenum pname, GLint param);
MOBILEGL_GL_API void glNamedFramebufferParameteriEXT(GLuint framebuffer, GLenum pname, GLint param);
MOBILEGL_GL_API void glNamedFramebufferReadBuffer(GLuint framebuffer, GLenum src);
MOBILEGL_GL_API void glNamedFramebufferRenderbuffer(GLuint framebuffer, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer);
MOBILEGL_GL_API void glNamedFramebufferRenderbufferEXT(GLuint framebuffer, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer);
MOBILEGL_GL_API void glNamedFramebufferSampleLocationsfvARB(GLuint framebuffer, GLuint start, GLsizei count, const GLfloat* v);
MOBILEGL_GL_API void glNamedFramebufferSampleLocationsfvNV(GLuint framebuffer, GLuint start, GLsizei count, const GLfloat* v);
MOBILEGL_GL_API void glNamedFramebufferTexture(GLuint framebuffer, GLenum attachment, GLuint texture, GLint level);
MOBILEGL_GL_API void glNamedFramebufferTexture1DEXT(GLuint framebuffer, GLenum attachment, GLenum textarget, GLuint texture, GLint level);
MOBILEGL_GL_API void glNamedFramebufferTexture2DEXT(GLuint framebuffer, GLenum attachment, GLenum textarget, GLuint texture, GLint level);
MOBILEGL_GL_API void glNamedFramebufferTexture3DEXT(GLuint framebuffer, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLint zoffset);
MOBILEGL_GL_API void glNamedFramebufferTextureEXT(GLuint framebuffer, GLenum attachment, GLuint texture, GLint level);
MOBILEGL_GL_API void glNamedFramebufferTextureFaceEXT(GLuint framebuffer, GLenum attachment, GLuint texture, GLint level, GLenum face);
MOBILEGL_GL_API void glNamedFramebufferTextureLayer(GLuint framebuffer, GLenum attachment, GLuint texture, GLint level, GLint layer);
MOBILEGL_GL_API void glNamedFramebufferTextureLayerEXT(GLuint framebuffer, GLenum attachment, GLuint texture, GLint level, GLint layer);
MOBILEGL_GL_API void glNamedProgramLocalParameter4dEXT(GLuint program, GLenum target, GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w);
MOBILEGL_GL_API void glNamedProgramLocalParameter4fEXT(GLuint program, GLenum target, GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
MOBILEGL_GL_API void glNamedProgramLocalParameterI4iEXT(GLuint program, GLenum target, GLuint index, GLint x, GLint y, GLint z, GLint w);
MOBILEGL_GL_API void glNamedProgramLocalParameterI4uiEXT(GLuint program, GLenum target, GLuint index, GLuint x, GLuint y, GLuint z, GLuint w);
MOBILEGL_GL_API void glNamedProgramLocalParameters4fvEXT(GLuint program, GLenum target, GLuint index, GLsizei count, const GLfloat* params);
MOBILEGL_GL_API void glNamedProgramLocalParametersI4ivEXT(GLuint program, GLenum target, GLuint index, GLsizei count, const GLint* params);
MOBILEGL_GL_API void glNamedProgramLocalParametersI4uivEXT(GLuint program, GLenum target, GLuint index, GLsizei count, const GLuint* params);
MOBILEGL_GL_API void glNamedRenderbufferStorage(GLuint renderbuffer, GLenum internalformat, GLsizei width, GLsizei height);
MOBILEGL_GL_API void glNamedRenderbufferStorageEXT(GLuint renderbuffer, GLenum internalformat, GLsizei width, GLsizei height);
MOBILEGL_GL_API void glNamedRenderbufferStorageMultisample(GLuint renderbuffer, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height);
MOBILEGL_GL_API void glNamedRenderbufferStorageMultisampleAdvancedAMD(GLuint renderbuffer, GLsizei samples, GLsizei storageSamples, GLenum internalformat, GLsizei width, GLsizei height);
MOBILEGL_GL_API void glNamedRenderbufferStorageMultisampleCoverageEXT(GLuint renderbuffer, GLsizei coverageSamples, GLsizei colorSamples, GLenum internalformat, GLsizei width, GLsizei height);
MOBILEGL_GL_API void glNamedRenderbufferStorageMultisampleEXT(GLuint renderbuffer, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height);
MOBILEGL_GL_API void glNamedStringARB(GLenum type, GLint namelen, const GLchar* name, GLint strinen, const GLchar* string);
MOBILEGL_GL_API void glNormalFormatNV(GLenum type, GLsizei stride);
MOBILEGL_GL_API void glObjectLabel(GLenum identifier, GLuint name, GLsizei length, const GLchar* label);
MOBILEGL_GL_API void glObjectPtrLabel(const void* ptr, GLsizei length, const GLchar* label);
MOBILEGL_GL_API void glPatchParameteri(GLenum pname, GLint value);
MOBILEGL_GL_API void glPathCoverDepthFuncNV(GLenum func);
MOBILEGL_GL_API void glPathParameterfNV(GLuint path, GLenum pname, GLfloat value);
MOBILEGL_GL_API void glPathParameteriNV(GLuint path, GLenum pname, GLint value);
MOBILEGL_GL_API void glPathStencilDepthOffsetNV(GLfloat factor, GLfloat units);
MOBILEGL_GL_API void glPathStencilFuncNV(GLenum func, GLint ref, GLuint mask);
MOBILEGL_GL_API void glPathStringNV(GLuint path, GLenum format, GLsizei length, const void* pathString);
MOBILEGL_GL_API void glPixelStoref(GLenum pname, GLfloat param);
MOBILEGL_GL_API void glPixelStorei(GLenum pname, GLint param);
MOBILEGL_GL_API void glPointParameterf(GLenum pname, GLfloat param);
MOBILEGL_GL_API void glPointParameteri(GLenum pname, GLint param);
MOBILEGL_GL_API void glPointSize(GLfloat size);
MOBILEGL_GL_API void glPolygonMode(GLenum face, GLenum mode);
MOBILEGL_GL_API void glPolygonOffset(GLfloat factor, GLfloat units);
MOBILEGL_GL_API void glPolygonOffsetClamp(GLfloat factor, GLfloat units, GLfloat clamp);
MOBILEGL_GL_API void glPolygonOffsetClampEXT(GLfloat factor, GLfloat units, GLfloat clamp);
MOBILEGL_GL_API void glPrimitiveBoundingBoxARB(GLfloat minX, GLfloat minY, GLfloat minZ, GLfloat minW, GLfloat maxX, GLfloat maxY, GLfloat maxZ, GLfloat maxW);
MOBILEGL_GL_API void glPrimitiveRestartIndex(GLuint index);
MOBILEGL_GL_API void glProgramBinary(GLuint program, GLenum binaryFormat, const void* binary, GLsizei length);
MOBILEGL_GL_API void glProgramParameteri(GLuint program, GLenum pname, GLint value);
MOBILEGL_GL_API void glProgramUniform1d(GLuint program, GLint location, GLdouble v0);
MOBILEGL_GL_API void glProgramUniform1dEXT(GLuint program, GLint location, GLdouble x);
MOBILEGL_GL_API void glProgramUniform1dv(GLuint program, GLint location, GLsizei count, const GLdouble* value);
MOBILEGL_GL_API void glProgramUniform1dvEXT(GLuint program, GLint location, GLsizei count, const GLdouble* value);
MOBILEGL_GL_API void glProgramUniform1f(GLuint program, GLint location, GLfloat v0);
MOBILEGL_GL_API void glProgramUniform1fv(GLuint program, GLint location, GLsizei count, const GLfloat* value);
MOBILEGL_GL_API void glProgramUniform1i(GLuint program, GLint location, GLint v0);
MOBILEGL_GL_API void glProgramUniform1i64ARB(GLuint program, GLint location, GLint64 x);
MOBILEGL_GL_API void glProgramUniform1i64NV(GLuint program, GLint location, GLint64EXT x);
MOBILEGL_GL_API void glProgramUniform1i64vARB(GLuint program, GLint location, GLsizei count, const GLint64* value);
MOBILEGL_GL_API void glProgramUniform1i64vNV(GLuint program, GLint location, GLsizei count, const GLint64EXT* value);
MOBILEGL_GL_API void glProgramUniform1iv(GLuint program, GLint location, GLsizei count, const GLint* value);
MOBILEGL_GL_API void glProgramUniform1ui(GLuint program, GLint location, GLuint v0);
MOBILEGL_GL_API void glProgramUniform1ui64ARB(GLuint program, GLint location, GLuint64 x);
MOBILEGL_GL_API void glProgramUniform1ui64NV(GLuint program, GLint location, GLuint64EXT x);
MOBILEGL_GL_API void glProgramUniform1ui64vARB(GLuint program, GLint location, GLsizei count, const GLuint64* value);
MOBILEGL_GL_API void glProgramUniform1ui64vNV(GLuint program, GLint location, GLsizei count, const GLuint64EXT* value);
MOBILEGL_GL_API void glProgramUniform1uiv(GLuint program, GLint location, GLsizei count, const GLuint* value);
MOBILEGL_GL_API void glProgramUniform2d(GLuint program, GLint location, GLdouble v0, GLdouble v1);
MOBILEGL_GL_API void glProgramUniform2dEXT(GLuint program, GLint location, GLdouble x, GLdouble y);
MOBILEGL_GL_API void glProgramUniform2dv(GLuint program, GLint location, GLsizei count, const GLdouble* value);
MOBILEGL_GL_API void glProgramUniform2dvEXT(GLuint program, GLint location, GLsizei count, const GLdouble* value);
MOBILEGL_GL_API void glProgramUniform2f(GLuint program, GLint location, GLfloat v0, GLfloat v1);
MOBILEGL_GL_API void glProgramUniform2fv(GLuint program, GLint location, GLsizei count, const GLfloat* value);
MOBILEGL_GL_API void glProgramUniform2i(GLuint program, GLint location, GLint v0, GLint v1);
MOBILEGL_GL_API void glProgramUniform2i64ARB(GLuint program, GLint location, GLint64 x, GLint64 y);
MOBILEGL_GL_API void glProgramUniform2i64NV(GLuint program, GLint location, GLint64EXT x, GLint64EXT y);
MOBILEGL_GL_API void glProgramUniform2i64vARB(GLuint program, GLint location, GLsizei count, const GLint64* value);
MOBILEGL_GL_API void glProgramUniform2i64vNV(GLuint program, GLint location, GLsizei count, const GLint64EXT* value);
MOBILEGL_GL_API void glProgramUniform2iv(GLuint program, GLint location, GLsizei count, const GLint* value);
MOBILEGL_GL_API void glProgramUniform2ui(GLuint program, GLint location, GLuint v0, GLuint v1);
MOBILEGL_GL_API void glProgramUniform2ui64ARB(GLuint program, GLint location, GLuint64 x, GLuint64 y);
MOBILEGL_GL_API void glProgramUniform2ui64NV(GLuint program, GLint location, GLuint64EXT x, GLuint64EXT y);
MOBILEGL_GL_API void glProgramUniform2ui64vARB(GLuint program, GLint location, GLsizei count, const GLuint64* value);
MOBILEGL_GL_API void glProgramUniform2ui64vNV(GLuint program, GLint location, GLsizei count, const GLuint64EXT* value);
MOBILEGL_GL_API void glProgramUniform2uiv(GLuint program, GLint location, GLsizei count, const GLuint* value);
MOBILEGL_GL_API void glProgramUniform3d(GLuint program, GLint location, GLdouble v0, GLdouble v1, GLdouble v2);
MOBILEGL_GL_API void glProgramUniform3dEXT(GLuint program, GLint location, GLdouble x, GLdouble y, GLdouble z);
MOBILEGL_GL_API void glProgramUniform3dv(GLuint program, GLint location, GLsizei count, const GLdouble* value);
MOBILEGL_GL_API void glProgramUniform3dvEXT(GLuint program, GLint location, GLsizei count, const GLdouble* value);
MOBILEGL_GL_API void glProgramUniform3f(GLuint program, GLint location, GLfloat v0, GLfloat v1, GLfloat v2);
MOBILEGL_GL_API void glProgramUniform3fv(GLuint program, GLint location, GLsizei count, const GLfloat* value);
MOBILEGL_GL_API void glProgramUniform3i(GLuint program, GLint location, GLint v0, GLint v1, GLint v2);
MOBILEGL_GL_API void glProgramUniform3i64ARB(GLuint program, GLint location, GLint64 x, GLint64 y, GLint64 z);
MOBILEGL_GL_API void glProgramUniform3i64NV(GLuint program, GLint location, GLint64EXT x, GLint64EXT y, GLint64EXT z);
MOBILEGL_GL_API void glProgramUniform3i64vARB(GLuint program, GLint location, GLsizei count, const GLint64* value);
MOBILEGL_GL_API void glProgramUniform3i64vNV(GLuint program, GLint location, GLsizei count, const GLint64EXT* value);
MOBILEGL_GL_API void glProgramUniform3iv(GLuint program, GLint location, GLsizei count, const GLint* value);
MOBILEGL_GL_API void glProgramUniform3ui(GLuint program, GLint location, GLuint v0, GLuint v1, GLuint v2);
MOBILEGL_GL_API void glProgramUniform3ui64ARB(GLuint program, GLint location, GLuint64 x, GLuint64 y, GLuint64 z);
MOBILEGL_GL_API void glProgramUniform3ui64NV(GLuint program, GLint location, GLuint64EXT x, GLuint64EXT y, GLuint64EXT z);
MOBILEGL_GL_API void glProgramUniform3ui64vARB(GLuint program, GLint location, GLsizei count, const GLuint64* value);
MOBILEGL_GL_API void glProgramUniform3ui64vNV(GLuint program, GLint location, GLsizei count, const GLuint64EXT* value);
MOBILEGL_GL_API void glProgramUniform3uiv(GLuint program, GLint location, GLsizei count, const GLuint* value);
MOBILEGL_GL_API void glProgramUniform4d(GLuint program, GLint location, GLdouble v0, GLdouble v1, GLdouble v2, GLdouble v3);
MOBILEGL_GL_API void glProgramUniform4dEXT(GLuint program, GLint location, GLdouble x, GLdouble y, GLdouble z, GLdouble w);
MOBILEGL_GL_API void glProgramUniform4dv(GLuint program, GLint location, GLsizei count, const GLdouble* value);
MOBILEGL_GL_API void glProgramUniform4dvEXT(GLuint program, GLint location, GLsizei count, const GLdouble* value);
MOBILEGL_GL_API void glProgramUniform4f(GLuint program, GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3);
MOBILEGL_GL_API void glProgramUniform4fv(GLuint program, GLint location, GLsizei count, const GLfloat* value);
MOBILEGL_GL_API void glProgramUniform4i(GLuint program, GLint location, GLint v0, GLint v1, GLint v2, GLint v3);
MOBILEGL_GL_API void glProgramUniform4i64ARB(GLuint program, GLint location, GLint64 x, GLint64 y, GLint64 z, GLint64 w);
MOBILEGL_GL_API void glProgramUniform4i64NV(GLuint program, GLint location, GLint64EXT x, GLint64EXT y, GLint64EXT z, GLint64EXT w);
MOBILEGL_GL_API void glProgramUniform4i64vARB(GLuint program, GLint location, GLsizei count, const GLint64* value);
MOBILEGL_GL_API void glProgramUniform4i64vNV(GLuint program, GLint location, GLsizei count, const GLint64EXT* value);
MOBILEGL_GL_API void glProgramUniform4iv(GLuint program, GLint location, GLsizei count, const GLint* value);
MOBILEGL_GL_API void glProgramUniform4ui(GLuint program, GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3);
MOBILEGL_GL_API void glProgramUniform4ui64ARB(GLuint program, GLint location, GLuint64 x, GLuint64 y, GLuint64 z, GLuint64 w);
MOBILEGL_GL_API void glProgramUniform4ui64NV(GLuint program, GLint location, GLuint64EXT x, GLuint64EXT y, GLuint64EXT z, GLuint64EXT w);
MOBILEGL_GL_API void glProgramUniform4ui64vARB(GLuint program, GLint location, GLsizei count, const GLuint64* value);
MOBILEGL_GL_API void glProgramUniform4ui64vNV(GLuint program, GLint location, GLsizei count, const GLuint64EXT* value);
MOBILEGL_GL_API void glProgramUniform4uiv(GLuint program, GLint location, GLsizei count, const GLuint* value);
MOBILEGL_GL_API void glProgramUniformHandleui64ARB(GLuint program, GLint location, GLuint64 value);
MOBILEGL_GL_API void glProgramUniformHandleui64NV(GLuint program, GLint location, GLuint64 value);
MOBILEGL_GL_API void glProgramUniformHandleui64vARB(GLuint program, GLint location, GLsizei count, const GLuint64* values);
MOBILEGL_GL_API void glProgramUniformHandleui64vNV(GLuint program, GLint location, GLsizei count, const GLuint64* values);
MOBILEGL_GL_API void glProgramUniformMatrix2dv(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble* value);
MOBILEGL_GL_API void glProgramUniformMatrix2dvEXT(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble* value);
MOBILEGL_GL_API void glProgramUniformMatrix2fv(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat* value);
MOBILEGL_GL_API void glProgramUniformMatrix2x3dv(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble* value);
MOBILEGL_GL_API void glProgramUniformMatrix2x3dvEXT(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble* value);
MOBILEGL_GL_API void glProgramUniformMatrix2x3fv(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat* value);
MOBILEGL_GL_API void glProgramUniformMatrix2x4dv(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble* value);
MOBILEGL_GL_API void glProgramUniformMatrix2x4dvEXT(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble* value);
MOBILEGL_GL_API void glProgramUniformMatrix2x4fv(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat* value);
MOBILEGL_GL_API void glProgramUniformMatrix3dv(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble* value);
MOBILEGL_GL_API void glProgramUniformMatrix3dvEXT(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble* value);
MOBILEGL_GL_API void glProgramUniformMatrix3fv(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat* value);
MOBILEGL_GL_API void glProgramUniformMatrix3x2dv(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble* value);
MOBILEGL_GL_API void glProgramUniformMatrix3x2dvEXT(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble* value);
MOBILEGL_GL_API void glProgramUniformMatrix3x2fv(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat* value);
MOBILEGL_GL_API void glProgramUniformMatrix3x4dv(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble* value);
MOBILEGL_GL_API void glProgramUniformMatrix3x4dvEXT(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble* value);
MOBILEGL_GL_API void glProgramUniformMatrix3x4fv(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat* value);
MOBILEGL_GL_API void glProgramUniformMatrix4dv(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble* value);
MOBILEGL_GL_API void glProgramUniformMatrix4dvEXT(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble* value);
MOBILEGL_GL_API void glProgramUniformMatrix4fv(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat* value);
MOBILEGL_GL_API void glProgramUniformMatrix4x2dv(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble* value);
MOBILEGL_GL_API void glProgramUniformMatrix4x2dvEXT(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble* value);
MOBILEGL_GL_API void glProgramUniformMatrix4x2fv(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat* value);
MOBILEGL_GL_API void glProgramUniformMatrix4x3dv(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble* value);
MOBILEGL_GL_API void glProgramUniformMatrix4x3dvEXT(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble* value);
MOBILEGL_GL_API void glProgramUniformMatrix4x3fv(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat* value);
MOBILEGL_GL_API void glProgramUniformui64NV(GLuint program, GLint location, GLuint64EXT value);
MOBILEGL_GL_API void glProgramUniformui64vNV(GLuint program, GLint location, GLsizei count, const GLuint64EXT* value);
MOBILEGL_GL_API void glProvokingVertex(GLenum mode);
MOBILEGL_GL_API void glPushClientAttribDefaultEXT(GLbitfield mask);
MOBILEGL_GL_API void glPushDebugGroup(GLenum source, GLuint id, GLsizei length, const GLchar* message);
MOBILEGL_GL_API void glPushGroupMarkerEXT(GLsizei length, const GLchar* marker);
MOBILEGL_GL_API void glQueryCounter(GLuint id, GLenum target);
MOBILEGL_GL_API void glRasterSamplesEXT(GLuint samples, GLboolean fixedsamplelocations);
MOBILEGL_GL_API void glReadBuffer(GLenum src);
MOBILEGL_GL_API void glRenderbufferStorage(GLenum target, GLenum internalformat, GLsizei width, GLsizei height);
MOBILEGL_GL_API void glRenderbufferStorageMultisample(GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height);
MOBILEGL_GL_API void glRenderbufferStorageMultisampleAdvancedAMD(GLenum target, GLsizei samples, GLsizei storageSamples, GLenum internalformat, GLsizei width, GLsizei height);
MOBILEGL_GL_API void glRenderbufferStorageMultisampleCoverageNV(GLenum target, GLsizei coverageSamples, GLsizei colorSamples, GLenum internalformat, GLsizei width, GLsizei height);
MOBILEGL_GL_API void glResetMemoryObjectParameterNV(GLuint memory, GLenum pname);
MOBILEGL_GL_API void glSampleCoverage(GLfloat value, GLboolean invert);
MOBILEGL_GL_API void glSampleMaski(GLuint maskNumber, GLbitfield mask);
MOBILEGL_GL_API void glSamplerParameterf(GLuint sampler, GLenum pname, GLfloat param);
MOBILEGL_GL_API void glSamplerParameteri(GLuint sampler, GLenum pname, GLint param);
MOBILEGL_GL_API void glScissor(GLint x, GLint y, GLsizei width, GLsizei height);
MOBILEGL_GL_API void glScissorArrayv(GLuint first, GLsizei count, const GLint* v);
MOBILEGL_GL_API void glScissorExclusiveArrayvNV(GLuint first, GLsizei count, const GLint* v);
MOBILEGL_GL_API void glScissorExclusiveNV(GLint x, GLint y, GLsizei width, GLsizei height);
MOBILEGL_GL_API void glScissorIndexed(GLuint index, GLint left, GLint bottom, GLsizei width, GLsizei height);
MOBILEGL_GL_API void glSecondaryColorFormatNV(GLint size, GLenum type, GLsizei stride);
MOBILEGL_GL_API void glShaderBinary(GLsizei count, const GLuint* shaders, GLenum binaryformat, const void* binary, GLsizei length);
MOBILEGL_GL_API void glShaderStorageBlockBinding(GLuint program, GLuint storageBlockIndex, GLuint storageBlockBinding);
MOBILEGL_GL_API void glShadingRateImageBarrierNV(GLboolean synchronize);
MOBILEGL_GL_API void glShadingRateImagePaletteNV(GLuint viewport, GLuint first, GLsizei count, const GLenum* rates);
MOBILEGL_GL_API void glShadingRateSampleOrderNV(GLenum order);
MOBILEGL_GL_API void glSignalVkFenceNV(GLuint64 vkFence);
MOBILEGL_GL_API void glSignalVkSemaphoreNV(GLuint64 vkSemaphore);
MOBILEGL_GL_API void glStateCaptureNV(GLuint state, GLenum mode);
MOBILEGL_GL_API void glStencilFillPathNV(GLuint path, GLenum fillMode, GLuint mask);
MOBILEGL_GL_API void glStencilFunc(GLenum func, GLint ref, GLuint mask);
MOBILEGL_GL_API void glStencilFuncSeparate(GLenum face, GLenum func, GLint ref, GLuint mask);
MOBILEGL_GL_API void glStencilMask(GLuint mask);
MOBILEGL_GL_API void glStencilMaskSeparate(GLenum face, GLuint mask);
MOBILEGL_GL_API void glStencilOp(GLenum fail, GLenum zfail, GLenum zpass);
MOBILEGL_GL_API void glStencilOpSeparate(GLenum face, GLenum sfail, GLenum dpfail, GLenum dppass);
MOBILEGL_GL_API void glStencilStrokePathNV(GLuint path, GLint reference, GLuint mask);
MOBILEGL_GL_API void glStencilThenCoverFillPathNV(GLuint path, GLenum fillMode, GLuint mask, GLenum coverMode);
MOBILEGL_GL_API void glStencilThenCoverStrokePathNV(GLuint path, GLint reference, GLuint mask, GLenum coverMode);
MOBILEGL_GL_API void glSubpixelPrecisionBiasNV(GLuint xbits, GLuint ybits);
MOBILEGL_GL_API void glTexAttachMemoryNV(GLenum target, GLuint memory, GLuint64 offset);
MOBILEGL_GL_API void glTexBuffer(GLenum target, GLenum internalformat, GLuint buffer);
MOBILEGL_GL_API void glTexBufferRange(GLenum target, GLenum internalformat, GLuint buffer, GLintptr offset, GLsizeiptr size);
MOBILEGL_GL_API void glTexCoordFormatNV(GLint size, GLenum type, GLsizei stride);
MOBILEGL_GL_API void glTexImage2DMultisample(GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLboolean fixedsamplelocations);
MOBILEGL_GL_API void glTexImage3DMultisample(GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedsamplelocations);
MOBILEGL_GL_API void glTexPageCommitmentARB(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLboolean commit);
MOBILEGL_GL_API void glTexPageCommitmentMemNV(GLenum target, GLint layer, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLuint memory, GLuint64 offset, GLboolean commit);
MOBILEGL_GL_API void glTexParameterf(GLenum target, GLenum pname, GLfloat param);
MOBILEGL_GL_API void glTexParameteri(GLenum target, GLenum pname, GLint param);
MOBILEGL_GL_API void glTexStorage1DEXT(GLenum target, GLsizei levels, GLenum internalformat, GLsizei width);
MOBILEGL_GL_API void glTexStorage2D(GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height);
MOBILEGL_GL_API void glTexStorage2DMultisample(GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLboolean fixedsamplelocations);
MOBILEGL_GL_API void glTexStorage3D(GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth);
MOBILEGL_GL_API void glTexStorage3DMultisample(GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedsamplelocations);
MOBILEGL_GL_API void glTextureAttachMemoryNV(GLuint texture, GLuint memory, GLuint64 offset);
MOBILEGL_GL_API void glTextureBuffer(GLuint texture, GLenum internalformat, GLuint buffer);
MOBILEGL_GL_API void glTextureBufferEXT(GLuint texture, GLenum target, GLenum internalformat, GLuint buffer);
MOBILEGL_GL_API void glTextureBufferRange(GLuint texture, GLenum internalformat, GLuint buffer, GLintptr offset, GLsizeiptr size);
MOBILEGL_GL_API void glTextureBufferRangeEXT(GLuint texture, GLenum target, GLenum internalformat, GLuint buffer, GLintptr offset, GLsizeiptr size);
MOBILEGL_GL_API void glTexturePageCommitmentEXT(GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLboolean commit);
MOBILEGL_GL_API void glTexturePageCommitmentMemNV(GLuint texture, GLint layer, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLuint memory, GLuint64 offset, GLboolean commit);
MOBILEGL_GL_API void glTextureParameterf(GLuint texture, GLenum pname, GLfloat param);
MOBILEGL_GL_API void glTextureParameterfEXT(GLuint texture, GLenum target, GLenum pname, GLfloat param);
MOBILEGL_GL_API void glTextureParameteri(GLuint texture, GLenum pname, GLint param);
MOBILEGL_GL_API void glTextureParameteriEXT(GLuint texture, GLenum target, GLenum pname, GLint param);
MOBILEGL_GL_API void glTextureRenderbufferEXT(GLuint texture, GLenum target, GLuint renderbuffer);
MOBILEGL_GL_API void glTextureStorage1D(GLuint texture, GLsizei levels, GLenum internalformat, GLsizei width);
MOBILEGL_GL_API void glTextureStorage1DEXT(GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width);
MOBILEGL_GL_API void glTextureStorage2D(GLuint texture, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height);
MOBILEGL_GL_API void glTextureStorage2DEXT(GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height);
MOBILEGL_GL_API void glTextureStorage2DMultisample(GLuint texture, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLboolean fixedsamplelocations);
MOBILEGL_GL_API void glTextureStorage2DMultisampleEXT(GLuint texture, GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLboolean fixedsamplelocations);
MOBILEGL_GL_API void glTextureStorage3D(GLuint texture, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth);
MOBILEGL_GL_API void glTextureStorage3DEXT(GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth);
MOBILEGL_GL_API void glTextureStorage3DMultisample(GLuint texture, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedsamplelocations);
MOBILEGL_GL_API void glTextureStorage3DMultisampleEXT(GLuint texture, GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedsamplelocations);
MOBILEGL_GL_API void glTextureView(GLuint texture, GLenum target, GLuint origtexture, GLenum internalformat, GLuint minlevel, GLuint numlevels, GLuint minlayer, GLuint numlayers);
MOBILEGL_GL_API void glTransformFeedbackBufferBase(GLuint xfb, GLuint index, GLuint buffer);
MOBILEGL_GL_API void glTransformFeedbackBufferRange(GLuint xfb, GLuint index, GLuint buffer, GLintptr offset, GLsizeiptr size);
MOBILEGL_GL_API void glUniform1d(GLint location, GLdouble x);
MOBILEGL_GL_API void glUniform1dv(GLint location, GLsizei count, const GLdouble* value);
MOBILEGL_GL_API void glUniform1f(GLint location, GLfloat v0);
MOBILEGL_GL_API void glUniform1fv(GLint location, GLsizei count, const GLfloat* value);
MOBILEGL_GL_API void glUniform1i(GLint location, GLint v0);
MOBILEGL_GL_API void glUniform1i64ARB(GLint location, GLint64 x);
MOBILEGL_GL_API void glUniform1i64NV(GLint location, GLint64EXT x);
MOBILEGL_GL_API void glUniform1i64vARB(GLint location, GLsizei count, const GLint64* value);
MOBILEGL_GL_API void glUniform1i64vNV(GLint location, GLsizei count, const GLint64EXT* value);
MOBILEGL_GL_API void glUniform1iv(GLint location, GLsizei count, const GLint* value);
MOBILEGL_GL_API void glUniform1ui(GLint location, GLuint v0);
MOBILEGL_GL_API void glUniform1ui64ARB(GLint location, GLuint64 x);
MOBILEGL_GL_API void glUniform1ui64NV(GLint location, GLuint64EXT x);
MOBILEGL_GL_API void glUniform1ui64vARB(GLint location, GLsizei count, const GLuint64* value);
MOBILEGL_GL_API void glUniform1ui64vNV(GLint location, GLsizei count, const GLuint64EXT* value);
MOBILEGL_GL_API void glUniform1uiv(GLint location, GLsizei count, const GLuint* value);
MOBILEGL_GL_API void glUniform2d(GLint location, GLdouble x, GLdouble y);
MOBILEGL_GL_API void glUniform2dv(GLint location, GLsizei count, const GLdouble* value);
MOBILEGL_GL_API void glUniform2f(GLint location, GLfloat v0, GLfloat v1);
MOBILEGL_GL_API void glUniform2fv(GLint location, GLsizei count, const GLfloat* value);
MOBILEGL_GL_API void glUniform2i(GLint location, GLint v0, GLint v1);
MOBILEGL_GL_API void glUniform2i64ARB(GLint location, GLint64 x, GLint64 y);
MOBILEGL_GL_API void glUniform2i64NV(GLint location, GLint64EXT x, GLint64EXT y);
MOBILEGL_GL_API void glUniform2i64vARB(GLint location, GLsizei count, const GLint64* value);
MOBILEGL_GL_API void glUniform2i64vNV(GLint location, GLsizei count, const GLint64EXT* value);
MOBILEGL_GL_API void glUniform2iv(GLint location, GLsizei count, const GLint* value);
MOBILEGL_GL_API void glUniform2ui(GLint location, GLuint v0, GLuint v1);
MOBILEGL_GL_API void glUniform2ui64ARB(GLint location, GLuint64 x, GLuint64 y);
MOBILEGL_GL_API void glUniform2ui64NV(GLint location, GLuint64EXT x, GLuint64EXT y);
MOBILEGL_GL_API void glUniform2ui64vARB(GLint location, GLsizei count, const GLuint64* value);
MOBILEGL_GL_API void glUniform2ui64vNV(GLint location, GLsizei count, const GLuint64EXT* value);
MOBILEGL_GL_API void glUniform2uiv(GLint location, GLsizei count, const GLuint* value);
MOBILEGL_GL_API void glUniform3d(GLint location, GLdouble x, GLdouble y, GLdouble z);
MOBILEGL_GL_API void glUniform3dv(GLint location, GLsizei count, const GLdouble* value);
MOBILEGL_GL_API void glUniform3f(GLint location, GLfloat v0, GLfloat v1, GLfloat v2);
MOBILEGL_GL_API void glUniform3fv(GLint location, GLsizei count, const GLfloat* value);
MOBILEGL_GL_API void glUniform3i(GLint location, GLint v0, GLint v1, GLint v2);
MOBILEGL_GL_API void glUniform3i64ARB(GLint location, GLint64 x, GLint64 y, GLint64 z);
MOBILEGL_GL_API void glUniform3i64NV(GLint location, GLint64EXT x, GLint64EXT y, GLint64EXT z);
MOBILEGL_GL_API void glUniform3i64vARB(GLint location, GLsizei count, const GLint64* value);
MOBILEGL_GL_API void glUniform3i64vNV(GLint location, GLsizei count, const GLint64EXT* value);
MOBILEGL_GL_API void glUniform3iv(GLint location, GLsizei count, const GLint* value);
MOBILEGL_GL_API void glUniform3ui(GLint location, GLuint v0, GLuint v1, GLuint v2);
MOBILEGL_GL_API void glUniform3ui64ARB(GLint location, GLuint64 x, GLuint64 y, GLuint64 z);
MOBILEGL_GL_API void glUniform3ui64NV(GLint location, GLuint64EXT x, GLuint64EXT y, GLuint64EXT z);
MOBILEGL_GL_API void glUniform3ui64vARB(GLint location, GLsizei count, const GLuint64* value);
MOBILEGL_GL_API void glUniform3ui64vNV(GLint location, GLsizei count, const GLuint64EXT* value);
MOBILEGL_GL_API void glUniform3uiv(GLint location, GLsizei count, const GLuint* value);
MOBILEGL_GL_API void glUniform4d(GLint location, GLdouble x, GLdouble y, GLdouble z, GLdouble w);
MOBILEGL_GL_API void glUniform4dv(GLint location, GLsizei count, const GLdouble* value);
MOBILEGL_GL_API void glUniform4f(GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3);
MOBILEGL_GL_API void glUniform4fv(GLint location, GLsizei count, const GLfloat* value);
MOBILEGL_GL_API void glUniform4i(GLint location, GLint v0, GLint v1, GLint v2, GLint v3);
MOBILEGL_GL_API void glUniform4i64ARB(GLint location, GLint64 x, GLint64 y, GLint64 z, GLint64 w);
MOBILEGL_GL_API void glUniform4i64NV(GLint location, GLint64EXT x, GLint64EXT y, GLint64EXT z, GLint64EXT w);
MOBILEGL_GL_API void glUniform4i64vARB(GLint location, GLsizei count, const GLint64* value);
MOBILEGL_GL_API void glUniform4i64vNV(GLint location, GLsizei count, const GLint64EXT* value);
MOBILEGL_GL_API void glUniform4iv(GLint location, GLsizei count, const GLint* value);
MOBILEGL_GL_API void glUniform4ui(GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3);
MOBILEGL_GL_API void glUniform4ui64ARB(GLint location, GLuint64 x, GLuint64 y, GLuint64 z, GLuint64 w);
MOBILEGL_GL_API void glUniform4ui64NV(GLint location, GLuint64EXT x, GLuint64EXT y, GLuint64EXT z, GLuint64EXT w);
MOBILEGL_GL_API void glUniform4ui64vARB(GLint location, GLsizei count, const GLuint64* value);
MOBILEGL_GL_API void glUniform4ui64vNV(GLint location, GLsizei count, const GLuint64EXT* value);
MOBILEGL_GL_API void glUniform4uiv(GLint location, GLsizei count, const GLuint* value);
MOBILEGL_GL_API void glUniformBlockBinding(GLuint program, GLuint uniformBlockIndex, GLuint uniformBlockBinding);
MOBILEGL_GL_API void glUniformHandleui64ARB(GLint location, GLuint64 value);
MOBILEGL_GL_API void glUniformHandleui64NV(GLint location, GLuint64 value);
MOBILEGL_GL_API void glUniformMatrix2dv(GLint location, GLsizei count, GLboolean transpose, const GLdouble* value);
MOBILEGL_GL_API void glUniformMatrix2fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value);
MOBILEGL_GL_API void glUniformMatrix2x3dv(GLint location, GLsizei count, GLboolean transpose, const GLdouble* value);
MOBILEGL_GL_API void glUniformMatrix2x3fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value);
MOBILEGL_GL_API void glUniformMatrix2x4dv(GLint location, GLsizei count, GLboolean transpose, const GLdouble* value);
MOBILEGL_GL_API void glUniformMatrix2x4fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value);
MOBILEGL_GL_API void glUniformMatrix3dv(GLint location, GLsizei count, GLboolean transpose, const GLdouble* value);
MOBILEGL_GL_API void glUniformMatrix3fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value);
MOBILEGL_GL_API void glUniformMatrix3x2dv(GLint location, GLsizei count, GLboolean transpose, const GLdouble* value);
MOBILEGL_GL_API void glUniformMatrix3x2fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value);
MOBILEGL_GL_API void glUniformMatrix3x4dv(GLint location, GLsizei count, GLboolean transpose, const GLdouble* value);
MOBILEGL_GL_API void glUniformMatrix3x4fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value);
MOBILEGL_GL_API void glUniformMatrix4dv(GLint location, GLsizei count, GLboolean transpose, const GLdouble* value);
MOBILEGL_GL_API void glUniformMatrix4fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value);
MOBILEGL_GL_API void glUniformMatrix4x2dv(GLint location, GLsizei count, GLboolean transpose, const GLdouble* value);
MOBILEGL_GL_API void glUniformMatrix4x2fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value);
MOBILEGL_GL_API void glUniformMatrix4x3dv(GLint location, GLsizei count, GLboolean transpose, const GLdouble* value);
MOBILEGL_GL_API void glUniformMatrix4x3fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value);
MOBILEGL_GL_API void glUniformui64NV(GLint location, GLuint64EXT value);
MOBILEGL_GL_API GLboolean glUnmapBuffer(GLenum target);
MOBILEGL_GL_API GLboolean glUnmapNamedBuffer(GLuint buffer);
MOBILEGL_GL_API GLboolean glUnmapNamedBufferEXT(GLuint buffer);
MOBILEGL_GL_API void glUseProgram(GLuint program);
MOBILEGL_GL_API void glUseProgramStages(GLuint pipeline, GLbitfield stages, GLuint program);
MOBILEGL_GL_API void glUseShaderProgramEXT(GLenum type, GLuint program);
MOBILEGL_GL_API void glValidateProgram(GLuint program);
MOBILEGL_GL_API void glValidateProgramPipeline(GLuint pipeline);
MOBILEGL_GL_API void glVertexArrayAttribBinding(GLuint vaobj, GLuint attribindex, GLuint bindingindex);
MOBILEGL_GL_API void glVertexArrayAttribFormat(GLuint vaobj, GLuint attribindex, GLint size, GLenum type, GLboolean normalized, GLuint relativeoffset);
MOBILEGL_GL_API void glVertexArrayAttribIFormat(GLuint vaobj, GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset);
MOBILEGL_GL_API void glVertexArrayAttribLFormat(GLuint vaobj, GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset);
MOBILEGL_GL_API void glVertexArrayBindVertexBufferEXT(GLuint vaobj, GLuint bindingindex, GLuint buffer, GLintptr offset, GLsizei stride);
MOBILEGL_GL_API void glVertexArrayBindingDivisor(GLuint vaobj, GLuint bindingindex, GLuint divisor);
MOBILEGL_GL_API void glVertexArrayColorOffsetEXT(GLuint vaobj, GLuint buffer, GLint size, GLenum type, GLsizei stride, GLintptr offset);
MOBILEGL_GL_API void glVertexArrayEdgeFlagOffsetEXT(GLuint vaobj, GLuint buffer, GLsizei stride, GLintptr offset);
MOBILEGL_GL_API void glVertexArrayElementBuffer(GLuint vaobj, GLuint buffer);
MOBILEGL_GL_API void glVertexArrayFogCoordOffsetEXT(GLuint vaobj, GLuint buffer, GLenum type, GLsizei stride, GLintptr offset);
MOBILEGL_GL_API void glVertexArrayIndexOffsetEXT(GLuint vaobj, GLuint buffer, GLenum type, GLsizei stride, GLintptr offset);
MOBILEGL_GL_API void glVertexArrayMultiTexCoordOffsetEXT(GLuint vaobj, GLuint buffer, GLenum texunit, GLint size, GLenum type, GLsizei stride, GLintptr offset);
MOBILEGL_GL_API void glVertexArrayNormalOffsetEXT(GLuint vaobj, GLuint buffer, GLenum type, GLsizei stride, GLintptr offset);
MOBILEGL_GL_API void glVertexArraySecondaryColorOffsetEXT(GLuint vaobj, GLuint buffer, GLint size, GLenum type, GLsizei stride, GLintptr offset);
MOBILEGL_GL_API void glVertexArrayTexCoordOffsetEXT(GLuint vaobj, GLuint buffer, GLint size, GLenum type, GLsizei stride, GLintptr offset);
MOBILEGL_GL_API void glVertexArrayVertexAttribBindingEXT(GLuint vaobj, GLuint attribindex, GLuint bindingindex);
MOBILEGL_GL_API void glVertexArrayVertexAttribDivisorEXT(GLuint vaobj, GLuint index, GLuint divisor);
MOBILEGL_GL_API void glVertexArrayVertexAttribFormatEXT(GLuint vaobj, GLuint attribindex, GLint size, GLenum type, GLboolean normalized, GLuint relativeoffset);
MOBILEGL_GL_API void glVertexArrayVertexAttribIFormatEXT(GLuint vaobj, GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset);
MOBILEGL_GL_API void glVertexArrayVertexAttribIOffsetEXT(GLuint vaobj, GLuint buffer, GLuint index, GLint size, GLenum type, GLsizei stride, GLintptr offset);
MOBILEGL_GL_API void glVertexArrayVertexAttribLFormatEXT(GLuint vaobj, GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset);
MOBILEGL_GL_API void glVertexArrayVertexAttribLOffsetEXT(GLuint vaobj, GLuint buffer, GLuint index, GLint size, GLenum type, GLsizei stride, GLintptr offset);
MOBILEGL_GL_API void glVertexArrayVertexAttribOffsetEXT(GLuint vaobj, GLuint buffer, GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, GLintptr offset);
MOBILEGL_GL_API void glVertexArrayVertexBindingDivisorEXT(GLuint vaobj, GLuint bindingindex, GLuint divisor);
MOBILEGL_GL_API void glVertexArrayVertexBuffer(GLuint vaobj, GLuint bindingindex, GLuint buffer, GLintptr offset, GLsizei stride);
MOBILEGL_GL_API void glVertexArrayVertexOffsetEXT(GLuint vaobj, GLuint buffer, GLint size, GLenum type, GLsizei stride, GLintptr offset);
MOBILEGL_GL_API void glVertexAttrib1d(GLuint index, GLdouble x);
MOBILEGL_GL_API void glVertexAttrib1f(GLuint index, GLfloat x);
MOBILEGL_GL_API void glVertexAttrib1s(GLuint index, GLshort x);
MOBILEGL_GL_API void glVertexAttrib2d(GLuint index, GLdouble x, GLdouble y);
MOBILEGL_GL_API void glVertexAttrib2f(GLuint index, GLfloat x, GLfloat y);
MOBILEGL_GL_API void glVertexAttrib2s(GLuint index, GLshort x, GLshort y);
MOBILEGL_GL_API void glVertexAttrib3d(GLuint index, GLdouble x, GLdouble y, GLdouble z);
MOBILEGL_GL_API void glVertexAttrib3f(GLuint index, GLfloat x, GLfloat y, GLfloat z);
MOBILEGL_GL_API void glVertexAttrib3s(GLuint index, GLshort x, GLshort y, GLshort z);
MOBILEGL_GL_API void glVertexAttrib4Nub(GLuint index, GLubyte x, GLubyte y, GLubyte z, GLubyte w);
MOBILEGL_GL_API void glVertexAttrib4d(GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w);
MOBILEGL_GL_API void glVertexAttrib4f(GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
MOBILEGL_GL_API void glVertexAttrib4s(GLuint index, GLshort x, GLshort y, GLshort z, GLshort w);
MOBILEGL_GL_API void glVertexAttribBinding(GLuint attribindex, GLuint bindingindex);
MOBILEGL_GL_API void glVertexAttribDivisor(GLuint index, GLuint divisor);
MOBILEGL_GL_API void glVertexAttribFormat(GLuint attribindex, GLint size, GLenum type, GLboolean normalized, GLuint relativeoffset);
MOBILEGL_GL_API void glVertexAttribFormatNV(GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride);
MOBILEGL_GL_API void glVertexAttribI1i(GLuint index, GLint x);
MOBILEGL_GL_API void glVertexAttribI1ui(GLuint index, GLuint x);
MOBILEGL_GL_API void glVertexAttribI2i(GLuint index, GLint x, GLint y);
MOBILEGL_GL_API void glVertexAttribI2ui(GLuint index, GLuint x, GLuint y);
MOBILEGL_GL_API void glVertexAttribI3i(GLuint index, GLint x, GLint y, GLint z);
MOBILEGL_GL_API void glVertexAttribI3ui(GLuint index, GLuint x, GLuint y, GLuint z);
MOBILEGL_GL_API void glVertexAttribI4i(GLuint index, GLint x, GLint y, GLint z, GLint w);
MOBILEGL_GL_API void glVertexAttribI4ui(GLuint index, GLuint x, GLuint y, GLuint z, GLuint w);
MOBILEGL_GL_API void glVertexAttribIFormat(GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset);
MOBILEGL_GL_API void glVertexAttribIFormatNV(GLuint index, GLint size, GLenum type, GLsizei stride);
MOBILEGL_GL_API void glVertexAttribIPointer(GLuint index, GLint size, GLenum type, GLsizei stride, const void* pointer);
MOBILEGL_GL_API void glVertexAttribL1d(GLuint index, GLdouble x);
MOBILEGL_GL_API void glVertexAttribL1i64NV(GLuint index, GLint64EXT x);
MOBILEGL_GL_API void glVertexAttribL1ui64ARB(GLuint index, GLuint64EXT x);
MOBILEGL_GL_API void glVertexAttribL1ui64NV(GLuint index, GLuint64EXT x);
MOBILEGL_GL_API void glVertexAttribL2d(GLuint index, GLdouble x, GLdouble y);
MOBILEGL_GL_API void glVertexAttribL2i64NV(GLuint index, GLint64EXT x, GLint64EXT y);
MOBILEGL_GL_API void glVertexAttribL2ui64NV(GLuint index, GLuint64EXT x, GLuint64EXT y);
MOBILEGL_GL_API void glVertexAttribL3d(GLuint index, GLdouble x, GLdouble y, GLdouble z);
MOBILEGL_GL_API void glVertexAttribL3i64NV(GLuint index, GLint64EXT x, GLint64EXT y, GLint64EXT z);
MOBILEGL_GL_API void glVertexAttribL3ui64NV(GLuint index, GLuint64EXT x, GLuint64EXT y, GLuint64EXT z);
MOBILEGL_GL_API void glVertexAttribL4d(GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w);
MOBILEGL_GL_API void glVertexAttribL4i64NV(GLuint index, GLint64EXT x, GLint64EXT y, GLint64EXT z, GLint64EXT w);
MOBILEGL_GL_API void glVertexAttribL4ui64NV(GLuint index, GLuint64EXT x, GLuint64EXT y, GLuint64EXT z, GLuint64EXT w);
MOBILEGL_GL_API void glVertexAttribLFormat(GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset);
MOBILEGL_GL_API void glVertexAttribLFormatNV(GLuint index, GLint size, GLenum type, GLsizei stride);
MOBILEGL_GL_API void glVertexAttribLPointer(GLuint index, GLint size, GLenum type, GLsizei stride, const void* pointer);
MOBILEGL_GL_API void glVertexAttribP1ui(GLuint index, GLenum type, GLboolean normalized, GLuint value);
MOBILEGL_GL_API void glVertexAttribP2ui(GLuint index, GLenum type, GLboolean normalized, GLuint value);
MOBILEGL_GL_API void glVertexAttribP3ui(GLuint index, GLenum type, GLboolean normalized, GLuint value);
MOBILEGL_GL_API void glVertexAttribP4ui(GLuint index, GLenum type, GLboolean normalized, GLuint value);
MOBILEGL_GL_API void glVertexAttribPointer(GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const void* pointer);
MOBILEGL_GL_API void glVertexBindingDivisor(GLuint bindingindex, GLuint divisor);
MOBILEGL_GL_API void glVertexFormatNV(GLint size, GLenum type, GLsizei stride);
MOBILEGL_GL_API void glViewport(GLint x, GLint y, GLsizei width, GLsizei height);
MOBILEGL_GL_API void glViewportArrayv(GLuint first, GLsizei count, const GLfloat* v);
MOBILEGL_GL_API void glViewportIndexedf(GLuint index, GLfloat x, GLfloat y, GLfloat w, GLfloat h);
MOBILEGL_GL_API void glViewportPositionWScaleNV(GLuint index, GLfloat xcoeff, GLfloat ycoeff);
MOBILEGL_GL_API void glViewportSwizzleNV(GLuint index, GLenum swizzlex, GLenum swizzley, GLenum swizzlez, GLenum swizzlew);
MOBILEGL_GL_API void glWaitSync(GLsync sync, GLbitfield flags, GLuint64 timeout);
MOBILEGL_GL_API void glWaitVkSemaphoreNV(GLuint64 vkSemaphore);
namespace MobileGL::ClientTrampoline::Gen {
// Resolves a GL function name against the exported trampoline table
// (direct &glXxx references - no dlsym, mirroring monolith
// MobileGL::MG_Impl::GetProcAddress semantics).
void* LookupGeneratedProc(const char* name);
}
// End of File
-37
View File
@@ -11,11 +11,6 @@
#include <Init.h>
#include <MG_Backend/BackendObjects.h>
#include <MG_State/EGLState/Core.h>
#if MOBILEGL_BUILD_DISAGGREGATED
// MG_Config::ServerOwnedWindowSurfaces (P12, MOBILEGL_IPC_SURFACE). Split-only: the pull build's
// translation unit is unchanged (G1).
#include <Config.h>
#endif
#include <mutex>
#include <sstream>
#include <type_traits>
@@ -132,16 +127,7 @@ namespace MobileGL::MG_Impl::EGLImpl {
state->SetError(EGL_BAD_CONFIG);
return EGL_NO_SURFACE;
}
#if MOBILEGL_BUILD_DISAGGREGATED
// P12 (on-screen server window), D1. With MOBILEGL_IPC_SURFACE=server and a remote server,
// the window is the SERVER's: a headless client passes none, so NULL is not
// EGL_BAD_NATIVE_WINDOW here. Whatever the client passed never reaches the wire - the
// remote backend sends WindowKind::ServerOwned with token 0 (BackendObject_Remote).
const Bool serverOwnedWindow = MG_Config::ServerOwnedWindowSurfaces();
if (IsNullNativeHandle(window) && !serverOwnedWindow) {
#else
if (IsNullNativeHandle(window)) {
#endif
state->SetError(EGL_BAD_NATIVE_WINDOW);
return EGL_NO_SURFACE;
}
@@ -153,15 +139,7 @@ namespace MobileGL::MG_Impl::EGLImpl {
.Height = static_cast<Uint32>(std::max<EGLint>(GetAttribValue(attrib_list, EGL_HEIGHT, 0), 0)),
};
#if MOBILEGL_BUILD_DISAGGREGATED
EGLSurface surface = serverOwnedWindow
? state->CreateServerOwnedWindowSurface(
dpy, config, windowHandle.Handle, static_cast<EGLint>(windowHandle.Width),
static_cast<EGLint>(windowHandle.Height), /*platformWindow=*/false)
: state->CreateWindowSurface(dpy, config, window, attrib_list);
#else
EGLSurface surface = state->CreateWindowSurface(dpy, config, window, attrib_list);
#endif
if (surface == EGL_NO_SURFACE) {
return EGL_NO_SURFACE;
}
@@ -698,14 +676,7 @@ namespace MobileGL::MG_Impl::EGLImpl {
if (!state) {
return EGL_NO_SURFACE;
}
#if MOBILEGL_BUILD_DISAGGREGATED
// P12 (on-screen server window), D1: as CreateWindowSurface - with MOBILEGL_IPC_SURFACE=server
// the window is the server's, and a headless client's NULL is accepted.
const Bool serverOwnedWindow = MG_Config::ServerOwnedWindowSurfaces();
if (native_window == nullptr && !serverOwnedWindow) {
#else
if (native_window == nullptr) {
#endif
state->SetError(EGL_BAD_NATIVE_WINDOW);
return EGL_NO_SURFACE;
}
@@ -725,15 +696,7 @@ namespace MobileGL::MG_Impl::EGLImpl {
.Height = static_cast<Uint32>(std::max<EGLint>(GetAttribValueAttrib(attrib_list, EGL_HEIGHT, 0), 0)),
};
#if MOBILEGL_BUILD_DISAGGREGATED
EGLSurface surface = serverOwnedWindow
? state->CreateServerOwnedWindowSurface(
dpy, config, native_window, static_cast<EGLint>(windowHandle.Width),
static_cast<EGLint>(windowHandle.Height), /*platformWindow=*/true)
: state->CreatePlatformWindowSurface(dpy, config, native_window, attrib_list);
#else
EGLSurface surface = state->CreatePlatformWindowSurface(dpy, config, native_window, attrib_list);
#endif
if (surface == EGL_NO_SURFACE) {
return EGL_NO_SURFACE;
}
+1 -1
View File
@@ -174,7 +174,7 @@ namespace MobileGL::MG_Impl::GLXImpl {
}
struct ContextObject {
::Display* XDisplay = nullptr;
Display* XDisplay = nullptr;
EGLDisplay Display = EGL_NO_DISPLAY;
EGLConfig Config = nullptr;
EGLContext Context = EGL_NO_CONTEXT;
+81 -205
View File
@@ -582,25 +582,12 @@ namespace MobileGL::MG_Pipe {
Optional<MGPipeInputField> Corrupt;
String CorruptKnob; // the MOBILEGL_PIPE_VERIFY_CORRUPT value the last arm saw
std::atomic<Uint64> Divergences{0};
Uint64 Summarised = 0; // how many of them the summary line has reported so far
// THE SUMMARY IS WRITTEN FROM MobileGL::Destroy, NOT FROM HERE (V1 fix round 2). This
// is a namespace-scope static, so this destructor runs from __run_exit_handlers, AFTER
// DestroyImpl has called MG_Util::Debug::Close(). Close nulls the role's sink; Log.cpp's
// WriteToFile then re-runs InitFile() for the next line, and InitFile opens the role's
// file with "w". So the one line this destructor wrote was the only line the client half
// of every FATAL=0 run kept - 121 bytes, the summary itself, with the entry compare's
// own reports, the arming line and the config dump gone (and the monolith arm's
// VerifyCorrupted. log wiped the same way). MGPipeVerifyFlushSummary runs before Close,
// so by the time this destructor runs there is nothing new to say and it says nothing;
// the arm is kept for a process that never called Destroy, where no Close ran and the
// line lands in the still-open file as it always did.
~VerifyState() { FlushSummary(); }
void FlushSummary() {
~VerifyState() {
const Uint64 count = Divergences.load(std::memory_order_relaxed);
if (count == 0 || count == Summarised) return;
Summarised = count;
MGLOG_E("MGPipe: verify summary - %llu divergence(s) survived MOBILEGL_PIPE_VERIFY_FATAL=0",
static_cast<unsigned long long>(count));
if (count != 0) {
MGLOG_E("MGPipe: verify summary - %llu divergence(s) survived MOBILEGL_PIPE_VERIFY_FATAL=0",
static_cast<unsigned long long>(count));
}
}
};
VerifyState g_verify;
@@ -658,57 +645,6 @@ namespace MobileGL::MG_Pipe {
MGPipeInputField differing = MGPipeInputField::kFieldCount;
if (!MGPipeVerifyInputs(inputs, g_snapshot, mask, &differing)) ReportDivergence(differing, "entry");
}
#if MOBILEGL_BUILD_DISAGGREGATED
// ---- P7 wave 3 (V1): the compare-at-read oracle inside the server's read_pixels ----
//
// WHAT THE SPLIT ARM FOUND THE FIRST TIME VERIFY AND SPLIT SHARED A BUILD. Every
// glReadPixels on the inproc arm - 8530 reads over 220 of the lane's 1068 entries, and the
// VerifySplitArming. entries on both backends - aborted with
//
// MGPipe: verify read of GetPixelStoreParameters (index 0, 0) differs from the live context
// MGPipe: Fatal{PipeVerifyDiffer, "GetPixelStoreParameters@ReadPixels", verb=6, where=read}
//
// on the server's apply thread, and it was the ONLY field that diverged anywhere in the
// lane. The mechanism is ID-49 and is deliberate: the pack state never shapes the wire
// answer, so MG_Remote/Server/PipeApplier.cpp's read_pixels body writes a NEUTRAL pack
// into the applier's copy of the field (MGPipeApplySetPixelPackState), makes the backend
// read, and restores the pushed one; the client then scatters the tight reply through the
// application's own pack state. The frontend context - this comparator's oracle - still
// holds the application's pack (Alignment 4 by default), so the backend's read of the
// pack half answers {Alignment 1} where the live context says {Alignment 4}. On the
// monolith arm the same neutral window is opened on the frontend context itself
// (GL_Texture.cpp's ScopedNeutralPackState), which is why the monolith lane never saw it.
//
// SO THE ORACLE, NOT THE RULE, IS WHAT CHANGES, AND ONLY IN THAT WINDOW: under a server
// stamp, on the ReadPixels verb, the pack half's expected value is the neutral pack the
// applier reads with, and the UNPACK half and every other field keep the live context as
// their oracle. A server read of the pack half that is neither the application's value
// nor exactly the neutral one is still a divergence and still Fatal.
//
// WHAT THIS GIVES UP IS ONE VALUE, NOT THE FIELD (corrected in P7 wave 3's V1 fix round;
// the first statement of it here said the comparator could no longer see a client that
// pushed a WRONG pack state at all, which is too broad). PipeApplier.cpp's read_pixels
// reads `savedPack` THROUGH THE ACCESSOR - and therefore through this hook - BEFORE it
// installs the neutral value, so the pushed pack has already been compared against the
// live one by then: a correct push is equal and returns, and a wrong push that is not
// exactly the neutral pack fails both compares and is still Fatal. The blind spot is the
// single value {SwapBytes 0, LSBFirst 0, RowLength 0, ImageHeight 0, Skip* 0, Alignment 1},
// and only while the application's own pack differs from it. The client-side scatter that
// consumes the real pack is covered by the readback matrix cases, which compare bytes,
// not fields.
Bool ServerReadsInsideTheNeutralPackWindow(const PipeInputs& self, MGPipeInputField field) {
return field == MGPipeInputField::GetPixelStoreParameters && self.ServerStampedVerb() &&
self.CurrentVerb() == MGPipeVerb::ReadPixels;
}
// The constant itself is MG_Pipe's (MGPipeTypes.h's MGPipeNeutralReadPixelsPack), which is
// the same function MG_Remote/Server/PipeApplier.cpp's read_pixels installs. It used to be
// re-typed here, field for field, to avoid reaching into MG_Remote/Server from MG_Impl -
// but the owner of MGPPixelPackState is MG_Pipe, both sites already include it, and a
// drift between the two spellings would have cost a false divergence rather than a build
// break.
#endif // MOBILEGL_BUILD_DISAGGREGATED
#endif // MOBILEGL_PIPE_VERIFY
} // namespace
@@ -743,77 +679,13 @@ namespace MobileGL::MG_Pipe {
// never recurses (and never reports the inner read against a half-copied scratch).
g_verify.InHook = true;
MGPipeFillAccess::CopyField(g_readScratch, *ctx, field);
// P7 wave 3 (V1): NEGATIVE CONTROL A REACHES THIS ARM TOO. Until this line the knob only
// ever perturbed EntryCompare's snapshot, so every red it could produce said `where=entry`
// and was produced on the CLIENT thread - which left the compare-at-read hook, the arm
// that runs on the server's apply thread and does the whole of the split lane's per-read
// work, with no falsifier at all: a hook that had stopped comparing would have looked
// exactly like a hook with nothing to report. The perturbation goes on the ORACLE, for
// EntryCompare's reason: the arm under test is the stored value, so corrupting THAT would
// be testing the corruption.
//
// WHICH READ THIS BLOCK TURNS RED (V1 fix round 2). The server reads the pack field TWICE
// inside the ReadPixels verb window, and both reads sit inside
// ServerReadsInsideTheNeutralPackWindow below (the verb stamp is up for the whole apply):
// PipeApplier::read_pixels saves the application's pack through the accessor BEFORE it
// installs the neutral one, and the backend's ReadPixels reads the field AFTER. This block
// is what turns the FIRST of them red: at that read `self` still holds the application's
// pack, so the first compare only reaches the window if this perturbation made it differ,
// and inside the window the application's pack against the neutral oracle differs on its
// own. It does nothing for the second read - `self` IS the neutral pack there - which is
// what the re-application inside the window is for.
if (g_verify.Corrupt && *g_verify.Corrupt == field) {
MGPipeApplyVerifyCorruption(g_readScratch, field);
}
const Bool equal = MGPipeInputsFieldEqual(field, self, g_readScratch);
g_verify.InHook = false;
if (equal) return;
#if MOBILEGL_BUILD_DISAGGREGATED
if (ServerReadsInsideTheNeutralPackWindow(self, field)) {
// The live context is the application's pack state and the server is, by ID-49,
// reading with the neutral one; the oracle for THAT HALF is the neutral pack, and
// every other byte of the field still has to match the live context.
g_verify.InHook = true;
PipeInputs::VisitStorage(field, g_readScratch, g_readScratch, [](auto& live, auto&) {
if constexpr (std::is_same_v<std::remove_reference_t<decltype(live)>, PixelStoreParameters[2]>) {
live[0] = MGPipeNeutralReadPixelsPack().Pack;
}
return true;
});
// AND THE CONTROL IS RE-APPLIED, because the overwrite above replaces the pack half
// WHOLESALE - the corruption included, since CorruptStorage perturbs an array's FIRST
// ELEMENT and the pack half is element 0. This is the block for the POST-INSTALL read
// (the backend's ReadPixels, after PipeApplier::read_pixels installed the neutral pack
// into gPipeInputs): there `self` is the neutral pack, the overwrite just made the
// oracle equal to it, and only a perturbation applied AFTER the overwrite can make
// that compare differ - the block above cannot reach it. Without this line the one
// window in which this arm is most load-bearing (the server's read_pixels, 8530 reads
// over 220 of the lane's entries) would be the one window MOBILEGL_PIPE_VERIFY_CORRUPT=
// GetPixelStoreParameters cannot turn red - and a control that accepted ONE report
// would never notice, because the saved-pack read still reports through the block
// above. The VerifySplitReadCorrupted. entries and the CI step therefore require at
// least TWO `where=read` reports in the server half (V1 fix round 2). Measured: 3 on
// DirectGLES (its backend reads the field twice after the install) / 2 on
// DirectVulkan; without this block both drop to 1, without the block above
// DirectVulkan drops to 1 while DirectGLES's two post-install reports keep it at 2 -
// so this block is falsified on both backends and the one above on DirectVulkan.
if (g_verify.Corrupt && *g_verify.Corrupt == field) {
MGPipeApplyVerifyCorruption(g_readScratch, field);
}
const Bool equalToTheNeutralPack = MGPipeInputsFieldEqual(field, self, g_readScratch);
g_verify.InHook = false;
if (equalToTheNeutralPack) return;
}
#endif
MGLOG_E("MGPipe: verify read of %s (index %u, %u) differs from the live context", kMGPipeInputFieldNames[index],
index0, index1);
ReportDivergence(field, "read");
}
// PipeInputs.h. The FATAL=0 summary, written while the role's log is still open:
// MobileGL::Destroy calls this right before MG_Util::Debug::Close() - see VerifyState for why
// the static destructor cannot be the writer.
void MGPipeVerifyFlushSummary() { g_verify.FlushSummary(); }
#endif // MOBILEGL_PIPE_VERIFY
// ---- push on mutation (P1 lane finding F2) ----
@@ -1112,24 +984,8 @@ namespace MobileGL::MG_Pipe {
// below and this aborts by name on the first glBufferData that carries data.
const Uint64 before = MG_Remote::Client::ClientWireRecordsEmitted();
MGPipeEmitResourceSubData(buffer, 0, static_cast<SizeT>(buffer.GetSize()));
// EXCEPT ON A SESSION THAT HAS STOPPED CARRYING RECORDS (P12). Once the device-lost
// latch is set every verb is DECLINED by design (CONTRACT-P6 5.3, ClientSession.cpp
// :1837) - the resource_subdata above included - so "it emitted nothing" is the latch
// working, not bytes this client forgot to carry: there is no server left for them to
// exist on, and P12's own exit gate (a) is that killing the server gives a CLEAN
// device-lost latch rather than a corpse. Aborting here turned every clean loss into a
// client SIGABRT at its next glBufferData that carries data.
//
// THE SELF-CHECK KEEPS ITS FULL FORCE ON A LIVE SESSION, which is the case it was
// written for: there, a follow-up that emits nothing is still the R-13.3 gap it names
// - and DeviceLost() is false.
if (MG_Remote::Client::ClientWireRecordsEmitted() == before &&
!MG_Remote::Client::ClientSession::DeviceLost()) {
// UncarriedInitialBytes, not a second word for the same family: WireTables.cpp:418
// already dies of exactly this - a respecify that crossed with no initial bytes -
// under that name, and two words for one family is the vocabulary drift a6
// censused and 5.2's .def exists to bound (P7 wave 0).
MGLOG_F("MGPipe: Fatal{UncarriedInitialBytes, \"resource_respecify\"} - the "
if (MG_Remote::Client::ClientWireRecordsEmitted() == before) {
MGLOG_F("MGPipe: Fatal{InitialBytesNotCarried, \"resource_respecify\"} - the "
"respecify crossed with initialBytes = nullptr (R-13.3) and the "
"resource_subdata records that were supposed to follow it emitted "
"NOTHING, so %llu bytes of initial content exist on no side of the wire",
@@ -1217,14 +1073,6 @@ namespace MobileGL::MG_Pipe {
#endif
// The application's STAGING store, valid for the duration of the call only.
MGPipeRouteBufferSubDataResident(record, base + (at - offset), length);
// P7 wave 2 package C, OQ-10: `rsd=`, counted HERE rather than at the call
// above so that one glBufferSubData cut into N chunk records counts N. See
// PipeStats.h's CallClass::ResidentSubDataEmissions for why the count is the
// only thing that can tell this arm from the in-place memcpy beside it.
if (MG_Util::PipeStats::Enabled()) {
MG_Util::PipeStats::AddCalls(
MG_Util::PipeStats::CallClass::ResidentSubDataEmissions, 1);
}
}, MGPipeContentChunkCap());
if (!encodable) {
MGLOG_E_ONCE("MGPipe: buffer_subdata_resident range [%llu, +%llu) on buffer %u cannot be encoded",
@@ -1614,44 +1462,79 @@ namespace MobileGL::MG_Pipe {
// above: with a dependency unmet the client emits NOTHING for that family and the legacy
// pull path runs untouched, on both sides of the boundary.
//
// THE TABLE IS WRITTEN ONCE, IN MG_Pipe/SubsystemDeps.def, and every one of its rows is
// the client mirror of the refusal Espryt already implements, bit for bit and
// non-transitively - the two must say the SAME thing, because a client that withheld more
// than the server refuses would leave the server's handle arm live with no records to
// read, and a client that withheld less is the defect above.
//
// THIS FILE USED TO HOLD ITS OWN COPY of the four P4a rows (P3b/P4b R-5 found six
// statements of one rule and two of them drifted). The rows moved to the .def with R-5
// and this reader was left pointing at the copy deliberately, because PipeFill.cpp is the
// contract package's file for the phase; wave 2-D package D3 switches it over.
//
// THE ARGUMENT IS MASKED TO kMGPipeP4aFamilySubsystems, AND THAT IS THE WHOLE DIFFERENCE
// BETWEEN A REWRITE AND A BEHAVIOUR CHANGE. The .def carries SIX rows; the table deleted
// from here carried FOUR, and this predicate is `wants()`'s fourth conjunct for P4a's
// families only. Reading all six unmasked would make the CLIENT withhold bit 8's
// vertex-input emissions at a mask with bit 7 clear - P3a's own rule, which this gate has
// never narrowed and which TextureEmitTest's
// EveryDKTwoDependencyRowGatesItsOwnFamilyAndTheMirrorPairsStayLive pins by name ("bit 8
// alone, with bit 7 clear: P3a's own rule, which this table must not touch"). Bit 13 is
// not narrowed here either; it asks the table for itself in P5eFamilyIsLive below,
// because bit 13's conjunct is bit 13's own. So the ROWS now come from one place and WHO
// each gate speaks for is still each gate's.
//
// The P4a-specific COVERAGE assertion stays for the same reason: a fifth P4a family
// without a row in the .def has to be a compile error, not a silent "depends on nothing".
// THE TABLE IS WRITTEN ONCE, HERE, and every one of its rows is the client mirror of the
// refusal Espryt already implements, bit for bit and non-transitively - the two must say
// the SAME thing, because a client that withheld more than the server refuses would
// leave the server's handle arm live with no records to read, and a client that withheld
// less is the defect above.
struct P4aFamilyDependencyRow {
Uint64 Family; // exactly one bit, and it is one of kMGPipeP4aFamilySubsystems
Uint64 Requires; // the bits MOBILEGL_PIPE_PUSH must ALSO carry for it to be live
};
inline constexpr P4aFamilyDependencyRow kMGPipeP4aFamilyDependencies[] = {
// BIT 9 REQUIRES BIT 10. Every MGPSurface::Res in a set_framebuffer_state record
// names a Texture or a Renderbuffer handle, and only bit 10 populates those two slot
// tables (Managers.cpp ResolveFramebufferSubsystemArm).
{kMGPipeSubsystemFramebuffer, kMGPipeSubsystemTextureResources},
// BIT 10 REQUIRES BIT 7 - a buffer texture's MGPResourceDesc::BufferForTexBuffer
// names a Buffer handle and only bit 7 puts twins in the resource slot table (D-D1,
// ResolveTextureResourceSubsystemArm's first row) - AND BIT 11, which is D-K2's
// FOURTH row (ID-14/ID-15): MGPTextureParams::BuiltinSampler is a SamplerCso HANDLE,
// only bit 11 mints sampler CSOs (c0b's four unconditional mints deliberately
// exclude it), and the applier's verdict for a null one is Fatal{ProtocolCorruption}
// rather than a decline. The brief's original "bit 10 without 11 is fine" is
// WITHDRAWN for P4a as built.
{kMGPipeSubsystemTextureResources,
kMGPipeSubsystemResources | kMGPipeSubsystemSamplers},
// BIT 11 REQUIRES BIT 10. Every MGPBoundView::Texture and every MGPImageView::Res
// names a Texture handle and only bit 10 populates that slot table; without it every
// per-unit lookup would miss and the walk would `continue` WITHOUT unbinding
// (ResolveSamplerSubsystemArm). With the row above this is SYMMETRIC: bits 10 and 11
// are one arm with two switches, and the only two masks that reach either handle arm
// are "both set" and "neither set".
{kMGPipeSubsystemSamplers, kMGPipeSubsystemTextureResources},
// BIT 12 DEPENDS ON NOTHING, and that is a ROW rather than an absence so the table
// covers the four families exhaustively (the static_assert below): a ShaderCso handle
// names no texture and no buffer, the archive rides beside the record as a companion
// pointer, and the extra inputs the server specialises on are read from state the
// backend already holds (ResolveProgramSubsystemArm).
{kMGPipeSubsystemPrograms, 0},
};
// THE MIRROR PAIRS THAT STAY FINE, said out loud rather than left as an absence, because
// an unreachable branch that says something different is how the reachable one drifts
// (Managers.cpp's own words at :2377-2381) - and because the table is only trustworthy if
// what it does NOT contain was decided rather than forgotten:
// - bit 10 set, bit 9 clear: FINE. The legacy FBO sync reaches the texture twin through
// SyncTextureObjectToBackend, which dispatches to the handle arm by itself.
// - bit 11 set, bit 9 clear: FINE, for the same reason - a sampler view names a texture,
// never a framebuffer.
// - bit 7 set, bit 10 clear: FINE, and it is P3a's shipped configuration.
// - bit 12 set with any or none of 9/10/11: FINE, per the last row.
// - bit 10 set, bit 11 clear (and its mirror) is NOT fine and is the row above; this is
// the one sentence in the brief that P4a as built withdrew.
constexpr Uint64 P4aFamilyDependencyBits(Uint64 subsystem) {
return MGPipeSubsystemRequires(subsystem & kMGPipeP4aFamilySubsystems);
Uint64 required = 0;
for (const P4aFamilyDependencyRow& row : kMGPipeP4aFamilyDependencies) {
if ((subsystem & row.Family) != 0) required |= row.Requires;
}
return required;
}
// The table covers the four families this phase migrates and nothing else, so a fifth
// family added to kMGPipeP4aFamilySubsystems without a row here does not silently inherit
// "depends on nothing".
constexpr Uint64 P4aFamilyDependencyTableCoverage() {
Uint64 covered = 0;
for (const MGPipeSubsystemDependencyRow& row : kMGPipeSubsystemDependencies) covered |= row.Family;
for (const P4aFamilyDependencyRow& row : kMGPipeP4aFamilyDependencies) covered |= row.Family;
return covered;
}
static_assert((P4aFamilyDependencyTableCoverage() & kMGPipeP4aFamilySubsystems) ==
kMGPipeP4aFamilySubsystems,
"every P4a family needs a D-K2 dependency row in MG_Pipe/SubsystemDeps.def, "
"even an empty one");
static_assert(P4aFamilyDependencyTableCoverage() == kMGPipeP4aFamilySubsystems,
"every P4a family needs a D-K2 dependency row, even an empty one");
static_assert(P4aFamilyDependencyBits(kMGPipeSubsystemFramebuffer) ==
kMGPipeSubsystemTextureResources,
"bit 9 requires bit 10");
@@ -1707,18 +1590,14 @@ namespace MobileGL::MG_Pipe {
// server whose four binding-point walks still read the frontend, so a record sent to it
// would be stored and never looked at while the client latched its suppressor.
//
// AND BIT 13'S OWN DEPENDENCY ROW IS READ FROM MG_Pipe/SubsystemDeps.def, exactly as
// P4a's four are (P3b/P4b R-5, switched over by wave 2-D package D3). It used to be the
// hand-coded `(pushMask & kMGPipeSubsystemResources) == 0` below - the sixth statement of
// the rule, and the one that sat fifteen lines from the block stating the other three,
// which is how "THREE OF THEM" survived two phases. Its reason is the table's: every
// MGPBufferRange::Res names a Buffer handle and only bit 7 puts one in the resource slot
// table, so without it every EnsureBufferResourceForHandle on the server would mint a
// twin with no record behind it. Withholding the whole family is the safe direction - the
// legacy frontend walk runs untouched on both sides.
// AND BIT 13 REQUIRES BIT 7, for bit 11's reason one family over: every
// MGPBufferRange::Res names a Buffer handle and only bit 7 puts one in the resource
// slot table, so without it every EnsureBufferResourceForHandle on the server would
// mint a twin with no record behind it. Withholding the whole family is the safe
// direction - the legacy frontend walk runs untouched on both sides.
Bool P5eFamilyIsLive(Uint64 subsystem, Uint64 pushMask) {
if ((subsystem & kMGPipeSubsystemBufferBindings) == 0) return true;
if (!MGPipeSubsystemDependenciesAreSet(kMGPipeSubsystemBufferBindings, pushMask)) return false;
if ((pushMask & kMGPipeSubsystemResources) == 0) return false;
#if MOBILEGL_BUILD_DISAGGREGATED
if (MG_Config::Transport != MG_Config::TransportMode::Monolith) {
return MG_Remote::Client::CapsMirrorInstance().ServerConsumes(
@@ -2000,11 +1879,8 @@ namespace MobileGL::MG_Pipe {
//
// BACKEND-NEUTRAL FROM THE FIRST COMMIT, which is the whole point: before P3a's C-1 fix
// the only thing that ever returned a VertexElementsCso slot was DirectGLES'
// StateObjectDeathOps table, so under a backend that installed none every VAO leaked a slot
// and a ~1.3 KB applier record for the life of the process. It stays the point now that
// BOTH backends install one (P7 wave 2 package C gives Magma its own, CONTRACT-P7 §5.5):
// Magma's table EMITS the death record and frees nothing, so the slot still comes back
// from here and from nowhere else. P4a mints SIX kinds and there
// StateObjectDeathOps table, so under a backend that installs none every VAO leaked a slot
// and a ~1.3 KB applier record for the life of the process. P4a mints SIX kinds and there
// is no intermediate state in which a backend table is the only path for any of them.
//
// THE THREE-STEP ORDER IS FIXED and each position is load-bearing (see PipeMutation.h):
+3 -9
View File
@@ -61,15 +61,9 @@ namespace MobileGL::MG_Pipe {
// 47 DirectGLES cases at ID-41). With them the four families emit NOTHING in that state and
// the legacy pull path runs exactly as it does on a pull build.
//
// D-K2's ROWS ARE IN MG_Pipe/SubsystemDeps.def, ONCE (P3b/P4b R-5), and this comment no
// longer restates them - restating them here is half of how the rule ended up with six
// statements, two of which were wrong. PipeFill.cpp's kMGPipeP4aFamilyDependencies is still
// the client's own copy and is still the bit-for-bit mirror of the four
// `Resolve<Family>SubsystemArm()` refusals in DirectGLES/Managers.cpp; switching it to read
// the .def is the integrator's one-line change (PipeFill.cpp is the contract package's file
// for the whole phase, so the emitter packages do not edit it).
// MG_Test/Backend/DirectGLES/SubsystemDepsTest.cpp drives BOTH readers at every interesting
// mask and compares them against the .def, so the two cannot drift in the meantime.
// D-K2's TABLE IS IN PipeFill.cpp, ONCE: bit 9 requires bit 10, bit 10 requires bits 7 and
// 11, bit 11 requires bit 10, bit 12 depends on nothing - the client mirror, bit for bit, of
// the four `Resolve<Family>SubsystemArm()` refusals in DirectGLES/Managers.cpp.
//
// It is exported for the unit gate and for no other caller: the gate itself is
// FamilyIsLive() inside PipeFill.cpp, every birth hook and every `wants()` row resolves
-9
View File
@@ -186,15 +186,6 @@ namespace MobileGL::MG_Pipe {
// P5f (fr): these historical scope names remain greppable markers around
// monolith glue until P3b/P4b remove those bodies. They hold no state and grant
// no exemption: allocator and frontend-registry access always refuse apply.
//
// P7 wave 2-B2: MagmaP7AllocatorDebtScope has NO BACKEND USES LEFT. P5e ruling 12 named
// four Magma apply-thread allocator debts (VulkanRenderer.cpp x3, ResourceTracker.h x1);
// P5f fv and P5f fm retired two of them, and this package retires the surviving pair -
// ShutdownBlitResources and ShutdownDepthMipmapResources, where the objects the debt was
// about are simply never created off the monolith arm. The class stays because
// MG_Test/Wire/RemoteClientTest uses it as a NEGATIVE CONTROL: two RemoteGuards cases
// construct it on the apply thread and assert the allocator refuses anyway, which is the
// property P5f (fr) established and the only thing this name now asserts.
class MagmaP7AllocatorDebtScope {
public:
MagmaP7AllocatorDebtScope() = default;
+6 -68
View File
@@ -100,10 +100,9 @@ namespace MobileGL::MG_Pipe {
// THE FLIP IS THE WHOLE SWITCH AND NOTHING ELSE MOVES: PipeFill.cpp ORs this constant into
// kMGPipeWiredSubsystems, static_asserts it is 0-or-its-own-bit, gates every birth hook on
// FamilyIsLive(kMGPipeSubsystemTextureResources, this), and gates DrainTextureSubData on
// the same OR. D-K2's rows - including bit 9's dependency on this family - are in
// MG_Pipe/SubsystemDeps.def, once (P3b/P4b R-5), and are not restated here; what this
// comment still has to say is the consequence for INTEGRATION ORDER, which no table can
// carry: this package may never be integrated with only one of the two constants set.
// the same OR. Bit 9 (framebuffer) REQUIRES bit 10 (D-K2), because every MGPSurface::Res
// names a texture or renderbuffer handle the applier must hold a record for - so this
// package may never be integrated with only one of the two constants set.
inline constexpr Uint64 kMGPipeWiredTextureSubsystem = kMGPipeSubsystemTextureResources;
static_assert(kMGPipeWiredTextureSubsystem == 0 ||
kMGPipeWiredTextureSubsystem == kMGPipeSubsystemTextureResources,
@@ -901,18 +900,6 @@ namespace MobileGL::MG_Pipe {
MGPRespecifiedLevel key{};
key.UploadTarget = packedTarget;
key.Level = static_cast<Uint16>(firstLevel + i);
#if MOBILEGL_BUILD_DISAGGREGATED
const auto* mipmap = MG_State::GLState::AsMipmapTexture(&texture);
if (mipmap == nullptr) {
MGLOG_E_ONCE("MGPipe: a per-level texture respecify had no mipmap storage; it was not emitted");
return;
}
const IntVec3 exactLevelExtent = mipmap->GetMipmapTexelSize(
static_cast<TextureUploadTarget>(uploadTarget), key.Level);
key.Width = static_cast<Uint32>(exactLevelExtent.x());
key.Height = static_cast<Uint32>(exactLevelExtent.y());
key.Depth = static_cast<Uint32>(exactLevelExtent.z());
#endif
accepted = RespecifyOnce(texture, handle, entry, desc, &key, viewOf, bufferHandle, bufOffset,
bufSize);
if (!accepted) break;
@@ -921,35 +908,6 @@ namespace MobileGL::MG_Pipe {
NoteRespecified(entry, desc, accepted);
}
// Give an object the server never got its record back: a create with no storage for its
// identity, the storage if it has any, and the parameters once so they land on the record
// that now exists. Returns whether that send was accepted. ONE attempt per caller - the
// caller owns the "one retry, never a loop" rule.
// THE ENTRY IS FETCHED, NOT HANDED IN: Entry is declared further down the class, so a
// parameter list up here could not name it - while this body, which the compiler treats as
// following the complete class, can. It is also the safer shape: the table can grow inside
// this call (a view's owner is acquired), and a reference taken by the caller before it
// would dangle.
Bool HealUnpublishedRecord(ITextureObject& texture, MGPipeHandle handle, Uint16 bindMask,
const MGPTextureParams& params) {
Entry& entry = EntryFor(m_textures, handle);
const MGPResourceDesc healDesc = MGPipeBuildTextureResourceDesc(
texture, handle, bindMask, /*storageDefined=*/false, kMGPipeNullHandle,
kMGPipeNullHandle, 0, 0);
NoteDesc(healDesc, /*isCreate=*/true);
PublishCreate(MGPipeKind::Texture, handle, entry, healDesc);
const auto* mipmap = MG_State::GLState::AsMipmapTexture(&texture);
const Bool hasStorage = mipmap != nullptr
? mipmap->GetMipmapLevelCount() > 0
: texture.GetStorageType() == MobileGL::TextureStorageType::Buffer;
if (hasStorage) {
// Can grow the table (a view's owner is acquired inside): no Entry& is held
// across it - the caller re-fetches its own afterwards.
EmitResourceRespecify(texture, MGPipeTextureRespecifyScope::WholeResource, 0, 0);
}
return MGPipeRouteSetTextureParams(params);
}
void EmitTextureParams(ITextureObject& texture) {
const MGPipeHandle handle = AcquireTexture(texture.GetLifetimeId(), &texture);
Entry& entry = EntryFor(m_textures, handle);
@@ -1014,30 +972,10 @@ namespace MobileGL::MG_Pipe {
MGPipeBuildTextureParams(texture, handle, entry.BuiltinSampler, entry.ForceParamsResync);
m_lastParams = params;
++m_paramSets;
// THE FIRST USE OF AN OBJECT THE SERVER NEVER GOT (P12). The refusal branch below is
// the same repair, but it can only fire if the record was allowed to WAIT - and the
// point of this change is that a record for an object whose existence IS confirmed
// need not wait at all. So the check moves BEFORE the send: the confirming create is
// the one round trip an object owes, it is paid here at its first use, and every
// record after it is fire-and-forget (Wire_SetTextureParams reads the same latch).
//
// IT IS NOT A NEW MECHANISM: PublishCreate is what the respecify path already calls
// when !MGPipeHandleIsPublished (EmitResourceRespecify, above), and the body below is
// the one the refusal branch has always run. This runs it on the client's own
// knowledge instead of after a round trip that told the client nothing it could not
// already see.
Bool accepted = false;
Bool healed = false;
if constexpr (MGPipeTextureRecordsReachTheApplier()) {
if (!MGPipeHandleIsPublished(MGPipeKind::Texture, handle)) {
accepted = HealUnpublishedRecord(texture, handle, entry.BindMask, params);
healed = true;
}
}
// Not behind MGPipeTextureRecordsReachTheApplier() (see its comment): the call is
// dispatched whenever this emitter runs, so the answer is always a real one.
if (!healed) accepted = MGPipeRouteSetTextureParams(params);
if (!accepted && !healed) {
Bool accepted = MGPipeRouteSetTextureParams(params);
if (!accepted) {
// THE SELF-HEAL, the respecify path's shape, and the parameters are the one
// publication that may be a texture's FIRST: the context's default textures are
// constructed before the backend registers its consumer, so no create ever went
@@ -1062,7 +1000,7 @@ namespace MobileGL::MG_Pipe {
// across it - `entry` is re-fetched below.
EmitResourceRespecify(texture, MGPipeTextureRespecifyScope::WholeResource, 0, 0);
}
accepted = HealUnpublishedRecord(texture, handle, entry.BindMask, params);
accepted = MGPipeRouteSetTextureParams(params);
}
Entry& latched = EntryFor(m_textures, handle);
if (!accepted) {
File diff suppressed because it is too large. Load diff
@@ -13,19 +13,8 @@
// the leak it rules out is entirely inside the library, and it is invisible in pixels, in GL
// names and in `glGetError` - so the only honest observable is the allocator's own live count
// and high-water mark. Reading them is what makes the case fail on the backend it actually
// failed on (DirectVulkan, which at P3a installed no StateObjectDeathOps) rather than only on
// the one where a backend-owned free happened to exist.
//
// P7 wave 2 package C: DirectVulkan now installs a table of its own (CONTRACT-P7 §5.5), and
// the sentence above is history rather than the current state - but the reason this header
// exists is UNCHANGED and is worth spelling out, because the obvious reading of that news is
// wrong. Magma's table does not free a client slot and never could: the free is P4a's, it
// runs from the frontend object's own destructor on the client thread whatever backend is
// live (MG_Impl/Pipe/PipeFill.cpp's NotifyAndFree), and Magma's table is the EMIT arm that
// tells the SERVER to drop its twin. So the allocator is still the only observable of the
// client half, and a case that reads `deaths` alone would be blind to a slot that never came
// back. The two readings belong together, which is what CtWireScenario's framebuffer case now
// does.
// failed on (DirectVulkan, which installs no StateObjectDeathOps) rather than only on the one
// where a backend-owned free happened to exist.
//
// A separate translation unit for BackendCapsPeek.h's reason, verbatim: the scenario sources
// include the GL headers with prototypes and MobileGL's umbrella header is not meant to meet
@@ -147,20 +147,6 @@ namespace MGITest::PipeStatsWindow {
inline std::string ReadLaneLog() { return ReadLaneLogSince(LogMark{}); }
// THE SERVER HALF ALONE, for a claim whose whole content is WHICH ROLE said it. The
// concatenation above answers "did anyone report this", which is the right question for a
// diagnostic that could honestly come from either side; it is the wrong question for a
// control that exists to prove the SERVER's apply thread still runs the comparator, because
// the client's own entry compare reports the same field on the same verb and would satisfy a
// union search all by itself. Empty in a pull build (there is no server half), which a caller
// must read as "could not look" rather than as "the server said nothing".
inline std::string ReadServerLogSince(const LogMark& mark) {
#if MOBILEGL_BUILD_DISAGGREGATED
MGPipeSyncPeerLog();
#endif
return ReadFileSince(ServerLibraryLogPath(), mark.server);
}
// The last summary line in the log, verbatim. `found` is false when the library never emitted
// one, which is a different failure from "the counter read zero" and has to be reported as
// one: it means the stats channel never reached the process, not that the workload did
@@ -191,63 +177,6 @@ namespace MGITest::PipeStatsWindow {
return Last(ReadLaneLog());
}
// ---- ONE ROLE AT A TIME, and P3b/P4b wave 2-D package D2 is why it had to exist -----------
//
// LastFromLaneLog() concatenates and takes the LAST window, which is the right answer for a
// counter only ONE role ever increments. It is the wrong answer for a claim that compares two
// roles' readings of the SAME records - TextureUploadShape's `tex[emit=]` (the server's) and
// `ctu=` (the client's) - because under SPAWN and TCP the two roles are two PROCESSES with two
// independent sets of counters. The client's line then carries `ctu=N tex[emit=0]` and the
// server's carries `ctu=0 tex[emit=N]`, and whichever line happens to be last answers BOTH
// questions with one role's numbers. The comparison silently becomes `N == 0` or `0 == N`.
//
// Under INPROC it happens to work either way - one process, one set of atomic counters, two
// log FILES - and that is exactly why this had to be written against the spawn shape rather
// than discovered by reading the inproc lane.
//
// Both return `found == false` where that role has no log (the pull build has no server half;
// a lane that configured no MOBILEGL_LOG_FILE_PATH has neither), which a caller must treat as
// "could not look" rather than as a zero.
inline Window LastFromClientLog() {
#if MOBILEGL_BUILD_DISAGGREGATED
MGPipeSyncPeerLog();
#endif
return Last(ReadWholeFile(LibraryLogPath()));
}
inline Window LastFromServerLog() {
#if MOBILEGL_BUILD_DISAGGREGATED
MGPipeSyncPeerLog();
#endif
return Last(ReadWholeFile(ServerLibraryLogPath()));
}
// ...AND SINCE A MARK, which is the form a counted window actually wants.
//
// The two above take the LAST summary line in the role's whole log, and that is one shutdown
// away from being the wrong line: the server writes a final, EMPTY window at teardown
// (frames=N window=0 draws=0, every counter zero), so a reader that runs after it - or that
// is slowed down enough for it to land first - reads four zeroes and reports them as the
// workload's shape. It has not bitten yet only because the scenarios read before teardown.
//
// Marking the log before the counted workload and reading only what was appended after
// removes the race entirely: with MOBILEGL_PIPE_STATS_PERIOD=1 the one eglSwapBuffers that
// closes the window emits exactly one line into that span, so "the last line since the mark"
// is that line and cannot be a later one.
inline Window LastFromClientLogSince(const LogMark& mark) {
#if MOBILEGL_BUILD_DISAGGREGATED
MGPipeSyncPeerLog();
#endif
return Last(ReadFileSince(LibraryLogPath(), mark.client));
}
inline Window LastFromServerLogSince(const LogMark& mark) {
#if MOBILEGL_BUILD_DISAGGREGATED
MGPipeSyncPeerLog();
#endif
return Last(ReadFileSince(ServerLibraryLogPath(), mark.server));
}
// One counter out of that line, by its short name ("mpr", "draws", "csom"), or -1 when the
// line does not carry it. The search includes the SEPARATOR before the name and the `=` after
// it, so "draws" cannot match "draws/f=" and "mpr" cannot match a longer name ending in it -
@@ -1,7 +1,6 @@
# Included by CTest after all GoogleTest discovery files (ID-53).
# CTest appends ENVIRONMENT here; keep all previously discovered lane settings.
file(MAKE_DIRECTORY "@CMAKE_CURRENT_BINARY_DIR@/split-logs")
file(MAKE_DIRECTORY "@CMAKE_CURRENT_BINARY_DIR@/verify-split-logs")
# P5b t2's two lanes ride the same rule: one private log path per entry, or
# SplitLogPaths.PrivateAndDistinct is red for them (ID-53).
# P5e vi's client-array lane joins the same list for the same reason: its two entries are the
@@ -30,48 +29,6 @@ foreach(listName IN ITEMS @MGL_SPLIT_ARM_TEST_LISTS@)
endif()
endforeach()
endforeach()
# P7 package L tier 3: the whole-suite Magma census. A LIST OF ITS OWN, and the log path is the
# ONLY property it gets - the loop above also arms the strict-arming, pmap and server-counter
# lane markers by entry name, and a census is here to be READ, not to assert three unrelated
# oracles it never opted into. The path itself is not optional: these entries are
# DirectVulkan.{Split,Spawn,Tcp}. names, so split_log_paths.py's ownership gate requires exactly
# one absolute private path each, and on the spawn and tcp arms two processes append to it.
#
# ONE EXCEPTION, AND IT IS TELEMETRY RATHER THAN AN ORACLE: CtWireScenario reads the server's
# own control-record tallies, and without MOBILEGL_TEST_SERVER_COUNTERS=1 they are not published
# at all - the case then reds on `server control-record telemetry missing`, which says nothing
# about Magma. Measured: that is exactly what the spawn arm's ApplierReset case did on this
# tier's first run. A switch that makes a counter readable is not the same kind of thing as the
# strict-arming, pmap or persistent-map-arm markers above, which make a case ASSERT something it
# never opted into, and those stay out of the census.
foreach(listName IN ITEMS @MGL_MAGMA_FULL_TEST_LISTS@)
foreach(entry IN LISTS ${listName})
set_tests_properties("${entry}" PROPERTIES ENVIRONMENT
"MOBILEGL_LOG_FILE_PATH=@CMAKE_CURRENT_BINARY_DIR@/split-logs/${entry}.log")
if(entry MATCHES "CtWireScenario\\.")
set_tests_properties("${entry}" PROPERTIES ENVIRONMENT "MOBILEGL_TEST_SERVER_COUNTERS=1")
endif()
endforeach()
endforeach()
# P7 wave 3 (V1): the verify comparator on the split arm. A LIST OF ITS OWN, like tier 3's and
# for tier 3's reason - the first loop also arms the strict-arming, pmap and server-counter lane
# markers by entry name, and this lane is here to compare fields, not to opt three unrelated
# oracles into a whole-binary set.
#
# THE PATH IS WHAT MAKES THE LANE ARMED RATHER THAN MERELY GREEN. These entries carry no
# MGITEST_SPLIT_LANE marker (MG_IntegrationTest/CMakeLists.txt says why: it reds 13 query-only
# cases that never move a verb), so the proof that the transport really resolved to inproc and
# that the comparator really armed is READ FROM THESE FILES by test.yml's verify-split job -
# ConfigLoader's `MOBILEGL_TRANSPORT=inproc` line and `MGPipe: verify armed`, per entry, in the
# CLIENT role's log. A shared path would make both unattributable, and under inproc the server
# role writes its own half of the same base name.
foreach(listName IN ITEMS @MGL_VERIFY_SPLIT_TEST_LISTS@)
foreach(entry IN LISTS ${listName})
set_tests_properties("${entry}" PROPERTIES ENVIRONMENT
"MOBILEGL_LOG_FILE_PATH=@CMAKE_CURRENT_BINARY_DIR@/verify-split-logs/${entry}.log")
endforeach()
endforeach()
foreach(entry IN LISTS MGL_SPLIT_PA_STRICT_DRAW_TESTS MGL_SPLIT_PA_STRICT_DISPATCH_TESTS)
set_tests_properties("${entry}" PROPERTIES ENVIRONMENT
"MOBILEGL_LOG_FILE_PATH=@CMAKE_CURRENT_BINARY_DIR@/split-logs/${entry}.log")
@@ -17,7 +17,6 @@
#if defined(MGITEST_SPLIT_RUNTIME_PEEK) && !defined(__ANDROID__)
#include <Config.h>
#include <MG_Remote/Client/CapsMirror.h>
#include <MG_Remote/Client/ClientSession.h>
#include <MG_Remote/Client/EmitTables.h>
#include <MG_Remote/Server/ServerLoop.h>
@@ -141,12 +140,6 @@ namespace MGITest {
const MobileGL::MG_Remote::Wire::PipeWireEncoder& encoder = session->Encoder();
state.emitSeq = encoder.EmitSeq();
state.runAheadArmed = session->RunAheadArmed();
// P7 wave 2 package C, OQ-10: read through the SAME accessor the frontend's own
// MGPipeResourceOpsHaveSubDataResident reads (MG_Impl/Pipe/PipeFill.cpp), so a
// green case here and a resident emission there cannot disagree about the bit.
state.residentSubDataCap =
MobileGL::MG_Remote::Client::CapsMirrorInstance().HasCap(
MobileGL::MG_Pipe::kCapResidentSubData);
state.presentCredit = MobileGL::MG_Config::Ipc.PresentCredit;
state.presentCreditWaits = session->PresentCreditWaits();
if (const auto* control = session->Control()) {
@@ -73,16 +73,6 @@ namespace MGITest {
// Real session state/watermarks. Only the client thread reads this snapshot;
// the scheduling observer below reads producerParked separately.
bool runAheadArmed = false;
// P7 wave 2 package C, OQ-10 (CONTRACT-P7 §5.4): kCapResidentSubData, as the CLIENT's
// caps mirror received it. This is the wire-level half of the bit's proof - the unit
// pair asserts that the SERVER derives it from its own resource table, and this says
// the client got what the server published, which is the only thing the frontend's
// MGPipeResourceOpsHaveSubDataResident can read under a transport.
//
// FALSE where the peek cannot look, like every field here, so a reader must have
// passed SplitRuntimeSkipReason() first: "no mirror" and "the bit was withheld" are
// the same false and completely different facts.
bool residentSubDataCap = false;
unsigned int presentCredit = 0;
unsigned long long appliedSeq = 0;
unsigned long long retiredSeq = 0;
@@ -1,55 +0,0 @@
// MobileGL - MobileGL/MG_IntegrationTest/Harness/TextureEmitPeek.cpp
// Copyright (c) 2026 MobileGL-Dev
// Licensed under the GNU Lesser General Public License v3.0:
// https://www.gnu.org/licenses/gpl-3.0.txt
// https://www.gnu.org/licenses/lgpl-3.0.txt
// SPDX-License-Identifier: LGPL-3.0-only
// End of Source File Header
#include "TextureEmitPeek.h"
#if !defined(__ANDROID__)
#include <MG_Pipe/MGPipe.h>
#if MOBILEGL_PIPE_PUSH
#include <MG_Impl/Pipe/TextureEmit.h>
#define MGITEST_TEXTURE_EMIT_PEEK_LIVE 1
#endif
#endif
namespace MGITest {
#if defined(MGITEST_TEXTURE_EMIT_PEEK_LIVE)
bool PeekTextureEmitCounters(TextureEmitCountersPeek* out) {
if (out == nullptr) return false;
// A SEPARATE TRANSLATION UNIT for PipeSlotPeek.h's reason, verbatim: the scenario sources
// include the GL headers with prototypes and MobileGL's umbrella header is not meant to
// meet them in one file.
auto& emitter = MobileGL::MG_Pipe::MGPipeTextureEmitterInstance();
out->SubDataCount = static_cast<unsigned long long>(emitter.SubDataCount());
out->RefusedSubDataCount = static_cast<unsigned long long>(emitter.RefusedSubDataCount());
out->CreateCount = static_cast<unsigned long long>(emitter.CreateCount());
out->RespecifyCount = static_cast<unsigned long long>(emitter.RespecifyCount());
out->DrainListSize = static_cast<unsigned long long>(emitter.DrainListSize());
return true;
}
const char* TextureEmitPeekSkipReason() { return ""; }
#else
bool PeekTextureEmitCounters(TextureEmitCountersPeek*) { return false; }
const char* TextureEmitPeekSkipReason() {
#if defined(__ANDROID__)
return "this module links the shipping libMobileGL.so on Android, built "
"-fvisibility=hidden, so the client emitter's counters do not resolve";
#else
return "this is a PULL build: MGPipeTextureEmitter is compiled only under "
"MOBILEGL_PIPE_PUSH, so there is no emission cursor to read";
#endif
}
#endif
} // namespace MGITest
@@ -1,64 +0,0 @@
// MobileGL - MobileGL/MG_IntegrationTest/Harness/TextureEmitPeek.h
// Copyright (c) 2026 MobileGL-Dev
// Licensed under the GNU Lesser General Public License v3.0:
// https://www.gnu.org/licenses/gpl-3.0.txt
// https://www.gnu.org/licenses/lgpl-3.0.txt
// SPDX-License-Identifier: LGPL-3.0-only
// End of Source File Header
//
// THE CLIENT TEXTURE EMITTER'S OWN COUNTERS AND ITS DRAIN LIST, read from a scenario.
//
// WHY A WHITE-BOX READING EXISTS HERE AT ALL, and it is the same argument PipeApplyPeek.h makes
// for G9. The owner-keyed drain cursor (TextureEmit.h's "the drain list (D-D4)") is a statement
// about WHICH emission cursor an upload through a texture VIEW lands on. Its public-GL
// observable - the texels a later sample returns - is repaired by every other arm of the
// system: a level that never made it onto the drain list is still uploaded by the NEXT whole-
// level respecify, by a GenerateMipmap, or by the monolith sync path, and the picture comes out
// right one frame later than it should have. A scenario that only looked at pixels would
// therefore go green over a two-cursor regression on most trees and red on none of them
// reliably. The counters are where the claim actually lives:
//
// SubDataCount() how many resource_subdata records the drain put on the wire. A drain that
// ran and emitted NOTHING is the silent failure this peek exists to make
// loud - it looks exactly like a healthy drain from outside.
// DrainListSize() what is still owed after the drain. Non-zero after a validate point means
// a level bailed (no storage, no shadow, an empty box) and stayed on the
// list, which is the safe direction but not the expected one for a plain
// glTexSubImage of a texture with storage.
//
// EVERY ENTRY POINT RETURNS false, TOUCHING NOTHING, WHERE IT CANNOT LOOK, and a caller that
// gets false has learned NOTHING. Out of reach means: a PULL build (the emitter is
// `#if MOBILEGL_PIPE_PUSH` and does not exist there); and Android, where this module links the
// shipping libMobileGL.so built -fvisibility=hidden and no internal symbol resolves. It is NOT
// backend-dependent: the emitter is the CLIENT's, and the client is this process under every
// one of inproc / spawn / tcp as well as under monolith.
#pragma once
namespace MGITest {
// MGPipeTextureEmitterInstance()'s cumulative counters. They are process-global and the
// library never resets them, so every caller compares a DELTA across its own window rather
// than an absolute - the same rule the PipeStats window readers follow.
struct TextureEmitCountersPeek {
// resource_subdata records the drain emitted (m_subDatas).
unsigned long long SubDataCount;
// ...of which the applier REFUSED (m_refusedSubDatas). A refusal leaves the level dirty
// and on the list, so a case that expected an emission and sees a refusal instead has a
// different finding from one that sees no emission at all.
unsigned long long RefusedSubDataCount;
// resource_create / resource_respecify, for a message that can say whether the texture
// was even described to the applier before the upload was due.
unsigned long long CreateCount;
unsigned long long RespecifyCount;
// What is STILL owed: m_drain.size() right now. Read after the validate point, this is
// the "did every dirty level get emitted" answer.
unsigned long long DrainListSize;
};
bool PeekTextureEmitCounters(TextureEmitCountersPeek* out);
// Why the peek could not look, for a GTEST_SKIP message. Empty when it can.
const char* TextureEmitPeekSkipReason();
} // namespace MGITest
@@ -48,15 +48,8 @@ def paths(document):
props = {p["name"]: p["value"] for p in test.get("properties", [])}
values = [v.split("=", 1)[1] for v in props.get("ENVIRONMENT", [])
if v.startswith("MOBILEGL_LOG_FILE_PATH=")]
# P7 package L: the Magma arms are here for the reason the GLES ones are - on a spawn or
# tcp arm TWO PROCESSES append to the path, so two entries sharing one file does not
# merely blur attribution, it interleaves two sessions. Leaving the DirectVulkan spawn
# and tcp prefixes out would have exempted the half of the new lane that needs the rule
# most, and the exemption would have looked like a clean run of this gate.
is_split = test["name"].startswith(("DirectGLES.Split.", "DirectVulkan.Split.",
"DirectGLES.Spawn.", "DirectGLES.Tcp.",
"DirectGLES.TcpDevice.",
"DirectVulkan.Spawn.", "DirectVulkan.Tcp."))
"DirectGLES.Spawn.", "DirectGLES.Tcp.", "DirectGLES.TcpDevice."))
if is_split and (len(values) != 1 or not values[0]):
raise ValueError(f"{test['name']}: requires exactly one nonempty MOBILEGL_LOG_FILE_PATH")
for value in values:
@@ -153,7 +146,7 @@ def print_marker_table(title, table):
print(f" {len(table[pair]):4d} {pair}")
# The first six skips predate P5f closure. Match both the exact entry and its reason;
# These six skips predate P5f closure. Match both the exact entry and its reason;
# losing a GPU/preflight, a required lane marker, or either RSP probe is never allowed.
DUALBLOCK_ALLOWED_SKIPS = {
"DirectGLES.Split.TriangleScenario.TheServerStampedAVerbBoundaryOnThisDrawingFrame": "not the strict-arming lane:",
@@ -162,22 +155,6 @@ DUALBLOCK_ALLOWED_SKIPS = {
"DirectGLES.Split.SmallRing.PersistentCoherentMapScenario.TheMapLandsInTheArmItsLaneDeclares": "not the counting lane: MGITEST_PMAP_LANE",
"DirectVulkan.Split.Fm.ClipDistanceScenario.ADisabledClipDistanceRemovesNothing": "clips by a DISABLED gl_ClipDistance",
"DirectVulkan.Split.Fm.ClipDistanceScenario.TheEnablesAreIndependentPerDistance": "clips by every declared gl_ClipDistance regardless of the enables",
# P7 D1/B2 and the twelve-scenario census put these on the split arms; each skips by its own
# named reason (the spawn and tcp arms skip the same set). Backend-structural on DirectGLES:
"DirectGLES.Split.Xfb.XfbRepeatedCaptureScenario.AVertexOnlyAdjacencyCaptureRecords":
"DirectGLES cannot forward a geometry-shader-less adjacency draw",
"DirectGLES.Split.ForcedDs.DepthStencilReadbackMatrixScenario.AFlippedMultisampleResolveMirrorsTheBandsAndAScaleDeclines":
"does not produce this picture yet: a flipped multisample depth resolve writes nothing",
"DirectGLES.Split.Glsl420DeclarationScenario.AnArrayOfSamplerArraysIsHonouredOrDeclinedCleanly":
"the frontend's binding-qualifier seeding does not walk an array of arrays",
# ...and driver capabilities llvmpipe does not have (the runner and the host both skip them).
"DirectGLES.Split.ForcedDs.DepthStencilReadbackMatrixScenario.SeparateDepthAndStencilAttachmentsAreBothReadable":
"this driver cannot host separate DEPTH_COMPONENT24 and STENCIL_INDEX8 attachments",
"DirectGLES.Split.ImageTargetKindScenario.LoadsTexture2DMultisample": "GL_MAX_IMAGE_SAMPLES is 0",
"DirectGLES.Split.ImageTargetKindScenario.LoadsTexture2DMultisampleArray": "GL_MAX_IMAGE_SAMPLES is 0",
"DirectGLES.Split.ImageTargetKindScenario.StoresTexture2DMultisample": "GL_MAX_IMAGE_SAMPLES is 0",
"DirectGLES.Split.ImageTargetKindScenario.StoresTexture2DMultisampleArray": "GL_MAX_IMAGE_SAMPLES is 0",
"DirectGLES.Split.ImageTargetKindScenario.IgnoresLayerForTexture2DMultisample": "GL_MAX_IMAGE_SAMPLES is 0",
}
@@ -218,106 +195,6 @@ def require_green(document, junit_path, required):
print(f"SplitLogPaths require-green: {len(by_name)} PASS, 0 skip, 0 failed, complete discovery")
VERIFY_ARMED_LINE = "MGPipe: verify armed"
def verify_split_arming(logs_dir, junit_path, expected_path):
"""THE VERIFY-SPLIT LANE'S ARM PROOF, PER ENTRY (P7 wave 3, V1 fix round).
What this replaces: a COUNT. The landing shape of the lane's arm proof asserted that at
least 850 of at least 1000 per-entry client logs carried `MGPipe: verify armed`, which
leaves ~155 entries unnamed and therefore unaccounted (117 of them skips) - a lane can
lose fifty arms and gain fifty skips and the floor never moves. The census is the point
(dualblock-expected-fatals.txt's rule, ID-119), so this is the same two-sided ratchet
applied to arming:
* an entry whose client log carries the arming line is ARMED and needs nothing else;
* an entry that ctest reported SKIPPED is recognised without a name - a gtest skip is a
process that brought a session up and left before any verb, which is honestly unarmed,
and the skip set is driver-dependent (a GitHub runner's lavapipe/llvmpipe skips more
or fewer than the host's), so naming those would ratchet on the driver;
* every OTHER unarmed entry must be named in the committed expected file, which says why
each class is there.
Two-sided, and both directions are failures:
* an unlisted, unskipped entry that did not arm - the comparator stopped reaching it, or
a case stopped issuing a verb, and either way the lane is quieter than it looks;
* a LISTED entry that armed - the name is stale and the file must lose the row in the
commit that made it arm, or the exception set rots into a permanent amnesty;
* a LISTED entry with no client log in this run at all - the name no longer matches an
entry (a rename, a filter change), which would otherwise be an invisible amnesty too.
A listed entry that SKIPPED on this run is neither: it is reported and allowed, because a
driver difference is exactly what the skip recognition above exists to absorb."""
directory = Path(logs_dir)
logs = sorted(directory.glob("*.client.log"))
if not logs:
raise ValueError(f"verify-split arming: no *.client.log under {directory} - the per-entry "
f"private log paths did not take, so nothing here is a per-entry proof")
status = {}
for case in ET.parse(junit_path).getroot().iter("testcase"):
name = case.get("name")
if case.find("skipped") is not None:
status[name] = "skipped"
elif (case.find("failure") is not None or case.find("error") is not None
or case.get("status") == "fail"):
status[name] = "failed"
else:
status[name] = "passed"
expected = read_pair_set(expected_path)
armed, skipped, named, unnamed, listed_armed, no_result = [], [], [], [], [], []
for path in logs:
entry = path.name[: -len(".client.log")]
if entry not in status:
no_result.append(entry)
continue
if VERIFY_ARMED_LINE in path.read_text(errors="replace"):
armed.append(entry)
if entry in expected:
listed_armed.append(entry)
elif status[entry] == "skipped":
skipped.append(entry)
elif entry in expected:
named.append(entry)
else:
unnamed.append(entry)
seen = set(armed) | set(skipped) | set(named) | set(unnamed)
stale = sorted(expected - seen)
listed_and_skipped = sorted(expected & set(skipped))
print(f"SplitLogPaths verify-split-arming: {len(logs)} per-entry client log(s) - "
f"{len(armed)} armed, {len(skipped)} unarmed and skipped, "
f"{len(named)} unarmed and named in {Path(expected_path).name}")
if listed_and_skipped:
print(f"SplitLogPaths verify-split-arming: {len(listed_and_skipped)} named entrie(s) "
f"skipped on this driver instead of running unarmed (allowed): "
f"{', '.join(listed_and_skipped)}")
problems = []
if no_result:
problems.append("%d private log(s) have no entry in the JUnit result: %s. The glob and "
"the run disagree about the lane's members, so neither side is a census."
% (len(no_result), ", ".join(sorted(no_result)[:20])))
if unnamed:
problems.append("%d entrie(s) ran, did not skip, and never armed the comparator: %s. Each "
"is a process that reached no verb - add it to %s with the class it "
"belongs to, or find out why the fill stopped happening."
% (len(unnamed), ", ".join(sorted(unnamed)[:20]), Path(expected_path).name))
if listed_armed:
problems.append("%d entrie(s) are named in %s but DID arm: %s. Remove the row in the "
"commit that made them arm - an exception set that keeps rows nothing "
"needs any more is how this proof rots."
% (len(listed_armed), Path(expected_path).name,
", ".join(sorted(listed_armed)[:20])))
if stale:
problems.append("%d name(s) in %s match no per-entry client log in this run: %s. The "
"entry was renamed or filtered out; drop the row in the same commit."
% (len(stale), Path(expected_path).name, ", ".join(stale[:20])))
if problems:
raise ValueError("the verify-split arm proof: " + " | ".join(problems))
print(f"SplitLogPaths verify-split-arming: per-entry arm proof OK - every log armed, skipped "
f"or named ({len(expected)} name(s) in the expected set)")
def expect_fatal(document, junit_path, expected_path):
"""THE DUAL-BLOCK LANE'S CENSUS AND TWO-SIDED RATCHET (P5f f1, P5F §4/§6).
@@ -488,13 +365,6 @@ def main():
if mode == "expect-fatal":
expect_fatal(json.loads(Path(sys.argv[2]).read_text()), sys.argv[3], sys.argv[4])
return
if mode == "verify-split-arming":
# <logs dir> <junit xml> <expected names>. It takes the LOG DIRECTORY rather than the
# discovery JSON on purpose: the claim is about the files a run left on disk, and a
# helper that rebuilt the set from discovery could not notice a log that was never
# written.
verify_split_arming(sys.argv[2], sys.argv[3], sys.argv[4])
return
if mode == "require-green":
require_green(json.loads(Path(sys.argv[2]).read_text()), sys.argv[3], sys.argv[4:])
return
@@ -87,41 +87,15 @@ class ResultAccountingTest(unittest.TestCase):
self.census()
def test_known_skip_requires_its_exact_reason(self):
for name, reason in helper.DUALBLOCK_ALLOWED_SKIPS.items():
with self.subTest(name=name):
self.assertTrue(reason.strip(), "an allowed skip needs a non-empty reason")
self.document = self.discovery([name])
self.results([(name, "notrun", "skipped")])
with self.assertRaisesRegex(ValueError, "unexpected skip"):
self.census()
tree = ET.parse(self.xml)
ET.SubElement(tree.getroot().find("testcase"), "system-out").text = reason
tree.write(self.xml)
self.census()
def test_an_allowed_entry_skipping_for_another_reason_is_refused(self):
# The Glsl420 row names the DECLINE; a program that stopped building skips too, with a
# different sentence, and must not ride the same row. The accepted half is asserted
# FIRST: without it this case would pass on a helper that does not list the entry at all
# (CI's dual-block census went red on exactly that, run 35785685692 onward).
name = "DirectGLES.Split.Glsl420DeclarationScenario.AnArrayOfSamplerArraysIsHonouredOrDeclinedCleanly"
self.assertIn(name, helper.DUALBLOCK_ALLOWED_SKIPS)
for reason, accepted in [
("the frontend's binding-qualifier seeding does not walk an array of arrays, so "
"DirectGLES samples unit 0 for every element; the locations asserted above are "
"the half of this case it can answer", True),
("the frontend does not build an array of sampler arrays: link error", False)]:
with self.subTest(accepted=accepted):
self.document = self.discovery([name])
self.results([(name, "notrun", "skipped")])
tree = ET.parse(self.xml)
ET.SubElement(tree.getroot().find("testcase"), "system-out").text = "Skipped\n" + reason
tree.write(self.xml)
if accepted:
self.census()
else:
with self.assertRaisesRegex(ValueError, "unexpected skip"):
self.census()
name, reason = next(iter(helper.DUALBLOCK_ALLOWED_SKIPS.items()))
self.document = self.discovery([name])
self.results([(name, "notrun", "skipped")])
with self.assertRaisesRegex(ValueError, "unexpected skip"):
self.census()
tree = ET.parse(self.xml)
ET.SubElement(tree.getroot().find("testcase"), "system-out").text = reason
tree.write(self.xml)
self.census()
def test_admitted_or_fatal_on_passed_case_is_not_hidden(self):
for marker in ['Admitted{UnmigratedPipeInput, "GetProgramObject@Clear"}',
@@ -143,79 +117,5 @@ class ResultAccountingTest(unittest.TestCase):
helper.require_green(self.document, self.xml, [A, B])
class VerifySplitArmProofTest(unittest.TestCase):
"""The per-entry arm proof, BOTH SIDES (P7 wave 3, V1 fix round).
The thing it replaced was a count, and a count cannot be tested for the failure that
matters - "fifty arms became fifty skips" leaves it unmoved. These four cases are the four
ways the census can be wrong, and each one has to raise."""
ARMED = "DirectGLES.VerifySplit.TriangleScenario.DrawsATriangle"
QUIET = "DirectGLES.VerifySplit.AdvertisedLimitsScenario.EveryGL45CoreMinimumIsMet"
SKIPPED = "DirectVulkan.VerifySplit.F1WireScenario.SomethingLavapipeCannotDo"
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.root = Path(self.temp.name)
self.logs = self.root / "verify-split-logs"
self.logs.mkdir()
self.xml = self.root / "run.xml"
self.expected = self.root / "expected.txt"
self.expected.write_text("# the quiet one\n" + self.QUIET + "\n")
self.write_log(self.ARMED, helper.VERIFY_ARMED_LINE)
self.write_log(self.QUIET, "no fill here")
self.write_log(self.SKIPPED, "no fill here either")
self.results([(self.ARMED, "run", None), (self.QUIET, "run", None),
(self.SKIPPED, "notrun", "skipped")])
def tearDown(self):
self.temp.cleanup()
def write_log(self, entry, text):
(self.logs / (entry + ".client.log")).write_text(text + "\n")
def results(self, rows):
suite = ET.Element("testsuite")
for name, status, kind in rows:
case = ET.SubElement(suite, "testcase", name=name, status=status)
if kind:
ET.SubElement(case, kind)
ET.ElementTree(suite).write(self.xml)
def proof(self):
with contextlib.redirect_stdout(io.StringIO()):
helper.verify_split_arming(self.logs, self.xml, self.expected)
def test_armed_skipped_or_named_is_the_whole_rule(self):
self.proof()
def test_an_unlisted_quiet_entry_fails(self):
self.expected.write_text("# nobody\n")
with self.assertRaisesRegex(ValueError, "never armed"):
self.proof()
def test_a_listed_entry_that_armed_fails(self):
self.write_log(self.QUIET, helper.VERIFY_ARMED_LINE)
with self.assertRaisesRegex(ValueError, "DID arm"):
self.proof()
def test_a_listed_name_with_no_log_fails(self):
(self.logs / (self.QUIET + ".client.log")).unlink()
self.results([(self.ARMED, "run", None), (self.SKIPPED, "notrun", "skipped")])
with self.assertRaisesRegex(ValueError, "match no per-entry client log"):
self.proof()
def test_a_log_with_no_result_fails(self):
self.results([(self.ARMED, "run", None), (self.QUIET, "run", None)])
with self.assertRaisesRegex(ValueError, "no entry in the JUnit result"):
self.proof()
def test_an_empty_log_directory_is_not_a_green(self):
for path in self.logs.glob("*.client.log"):
path.unlink()
with self.assertRaisesRegex(ValueError, "did not take"):
self.proof()
if __name__ == "__main__":
unittest.main()
@@ -1,131 +0,0 @@
# THE VERIFY-SPLIT ENTRIES THAT HONESTLY NEVER ARM THE COMPARATOR, BY NAME.
#
# `MGPipe: verify armed` is latched at a process's FIRST FILL, so a process that reaches no verb
# never prints it. The lane's arm proof (.github/workflows/test.yml, integration-verify-split)
# used to allow that with a COUNT - "at least 850 of at least 1000 client logs carry the line" -
# which leaves the remainder unnamed: the lane could lose fifty arms, gain fifty skips, and the
# floor would not move. This file is the census instead, and split_log_paths.py's
# `verify-split-arming` mode is what reads it.
#
# THE RULE, PER ENTRY. Every verify-split-logs/*.client.log must either
# (a) carry the arming line, or
# (b) belong to an entry ctest reported SKIPPED - a gtest skip is a process that brought a
# session up and left before any verb, and the skip set is DRIVER-DEPENDENT (a GitHub
# runner's lavapipe/llvmpipe skips more or fewer cases than the host's), so naming those
# would ratchet on the driver rather than on the comparator, or
# (c) be named below.
#
# TWO-SIDED, the rule dualblock-expected-fatals.txt already rides (ID-119):
# * an unlisted, unskipped entry that did not arm FAILS - a case stopped issuing a verb, or
# the comparator stopped reaching it, and both are quieter lanes than they look;
# * a LISTED entry that ARMED fails - remove the row in the commit that made it arm;
# * a LISTED name with no client log in this run fails - the entry was renamed or filtered
# out, and the row is an amnesty nobody asked for.
# A listed entry that SKIPS on some driver is allowed and reported: that is (b) doing its job.
#
# HOW TO REFRESH (never by hand from a guess):
# ctest --test-dir build-split -L '^integration-verify-split$' -j 6 \
# --output-junit /tmp/verify-split.xml
# python3 MobileGL/MG_IntegrationTest/Harness/split_log_paths.py verify-split-arming \
# build-split/MobileGL/MG_IntegrationTest/verify-split-logs /tmp/verify-split.xml this-file
# and put the names it prints here, under the class they belong to.
#
# MEASURED ON THE HOST (WSL Arch + lavapipe, build-split, 1064 entries with a private log):
# 909 armed, 99 unarmed and skipped, 56 unarmed and named below.
# --------------------------------------------------------------------------------------------
# CAPS, LIMITS AND EXTENSION ADVERTISEMENT - answered from the client's CapsMirror, no verb (22)
# These call glGetIntegerv / glGetString / glGetInternalformativ and compare the answer
# against a floor or against the other width of the same query. Nothing in them reaches a fill
# point, so the arming line - latched at the process's FIRST fill - is honestly absent. This is
# the same property tier 3 measured from the other side: its 13 reds under MGITEST_SPLIT_LANE=1
# (AdvertisedLimitsScenario x8, SpirvShaderBinaryScenario x4, ProgramPipelineScenario's reserved
# name) were all queries answered without moving the encoder's record ordinal, and they are
# spread across this class and the next one - which is why this lane sets no such marker.
# --------------------------------------------------------------------------------------------
DirectGLES.VerifySplit.AdvertisedLimitsScenario.ComputeLocalSizeComesFromTheLinkedProgram
DirectGLES.VerifySplit.AdvertisedLimitsScenario.ComputeUniformBlocksIsAnAmountAnApplicationCouldActuallyAllocate
DirectGLES.VerifySplit.AdvertisedLimitsScenario.ComputeWorkGroupLimitsAreTheCapsBlocksAnswer
DirectGLES.VerifySplit.AdvertisedLimitsScenario.EveryBufferLimitIsWithinItsAdvertisedRange
DirectGLES.VerifySplit.AdvertisedLimitsScenario.EveryGL45CoreMinimumIsMet
DirectGLES.VerifySplit.AdvertisedLimitsScenario.IndexedBufferBindingsAreReportedVerbatimOnBothWidths
DirectGLES.VerifySplit.AdvertisedLimitsScenario.IndexedTargetSizeSurvivesDivisionByItsBindingCount
DirectGLES.VerifySplit.AdvertisedLimitsScenario.PerStageBlockCountsFitInTheirBindingPoints
DirectGLES.VerifySplit.AdvertisedLimitsScenario.ViewportArrayLimitsMeetTheirGL43Floors
DirectGLES.VerifySplit.DoublePrecisionScenario.TheFp64ExtensionIsNotAdvertised
DirectGLES.VerifySplit.SpirvShaderBinaryScenario.ShaderBinaryFormatIsAdvertisedExactlyOnce
DirectVulkan.VerifySplit.AdvertisedLimitsScenario.ComputeLocalSizeComesFromTheLinkedProgram
DirectVulkan.VerifySplit.AdvertisedLimitsScenario.ComputeUniformBlocksIsAnAmountAnApplicationCouldActuallyAllocate
DirectVulkan.VerifySplit.AdvertisedLimitsScenario.ComputeWorkGroupLimitsAreTheCapsBlocksAnswer
DirectVulkan.VerifySplit.AdvertisedLimitsScenario.EveryBufferLimitIsWithinItsAdvertisedRange
DirectVulkan.VerifySplit.AdvertisedLimitsScenario.EveryGL45CoreMinimumIsMet
DirectVulkan.VerifySplit.AdvertisedLimitsScenario.IndexedBufferBindingsAreReportedVerbatimOnBothWidths
DirectVulkan.VerifySplit.AdvertisedLimitsScenario.IndexedTargetSizeSurvivesDivisionByItsBindingCount
DirectVulkan.VerifySplit.AdvertisedLimitsScenario.PerStageBlockCountsFitInTheirBindingPoints
DirectVulkan.VerifySplit.AdvertisedLimitsScenario.ViewportArrayLimitsMeetTheirGL43Floors
DirectVulkan.VerifySplit.DoublePrecisionScenario.TheFp64ExtensionIsNotAdvertised
DirectVulkan.VerifySplit.SpirvShaderBinaryScenario.ShaderBinaryFormatIsAdvertisedExactlyOnce
# --------------------------------------------------------------------------------------------
# SHADER AND PROGRAM OBJECT SURFACES - compile, link, specialize, query, glGetError (16)
# glShaderBinary / glSpecializeShader / glCompileShader / glGetUniformdv / the compiler
# thread pool's settle-and-join, and the reserved-name pipeline case. Every one of them asserts on
# an error code or a program query; none issues a draw, a dispatch, a clear or a readback.
# --------------------------------------------------------------------------------------------
DirectGLES.VerifySplit.AsyncCompileScenario.CompletionStatusPollingThenForcedJoin
DirectGLES.VerifySplit.AsyncCompileScenario.ZeroCompilerThreadsSettlesEverythingImmediately
DirectGLES.VerifySplit.DoublePrecisionScenario.GetUniformdvReadsBackWhatWasStored
DirectGLES.VerifySplit.DoublePrecisionScenario.TheUniformIsStillReportedAsADouble
DirectGLES.VerifySplit.ProgramPipelineScenario.AReservedNameTakesStateBeforeItIsAProgramPipeline
DirectGLES.VerifySplit.SpirvShaderBinaryScenario.AnUnsupportedBinaryFormatIsRejectedInsteadOfSilentlyAccepted
DirectGLES.VerifySplit.SpirvShaderBinaryScenario.CompileShaderOnASpirvShaderIsInvalidOperationAndShaderSourceTakesItBack
DirectGLES.VerifySplit.SpirvShaderBinaryScenario.SpecializeShaderErrorSurfaceMatchesTheExtension
DirectVulkan.VerifySplit.AsyncCompileScenario.CompletionStatusPollingThenForcedJoin
DirectVulkan.VerifySplit.AsyncCompileScenario.ZeroCompilerThreadsSettlesEverythingImmediately
DirectVulkan.VerifySplit.DoublePrecisionScenario.GetUniformdvReadsBackWhatWasStored
DirectVulkan.VerifySplit.DoublePrecisionScenario.TheUniformIsStillReportedAsADouble
DirectVulkan.VerifySplit.ProgramPipelineScenario.AReservedNameTakesStateBeforeItIsAProgramPipeline
DirectVulkan.VerifySplit.SpirvShaderBinaryScenario.AnUnsupportedBinaryFormatIsRejectedInsteadOfSilentlyAccepted
DirectVulkan.VerifySplit.SpirvShaderBinaryScenario.CompileShaderOnASpirvShaderIsInvalidOperationAndShaderSourceTakesItBack
DirectVulkan.VerifySplit.SpirvShaderBinaryScenario.SpecializeShaderErrorSurfaceMatchesTheExtension
# --------------------------------------------------------------------------------------------
# OBJECT STATE WRITTEN AND READ BACK, OR A CALL REJECTED BEFORE IT BECOMES A VERB (14)
# glVertexAttribLFormat then glGetVertexAttribiv (the 64-bit format case does NOT draw - the
# comment above it names the Adreno null-deref that is why), glTexBufferRange then the level
# queries, glEnable then glIsEnabled, glGetIntegerv(GL_SAMPLE_MASK_WORDS) then glSampleMaski, the
# two glCopyImageSubData level-range REJECTIONS (the call errors out, so no verb is filled), and
# the arena readback, which is glBufferSubData + glGetBufferSubData and not a pipe verb.
# --------------------------------------------------------------------------------------------
DirectGLES.VerifySplit.BufferTextureScenario.LevelQueriesDescribeTheAttachedBufferRange
DirectGLES.VerifySplit.ClipDistanceScenario.EnableIsObservableThroughIsEnabled
DirectGLES.VerifySplit.CopyImageLevelRangeScenario.LevelOneOfASingleLevelTextureIsRejected
DirectGLES.VerifySplit.CopyImageLevelRangeScenario.LevelTwoOfATwoLevelTextureIsRejected
DirectGLES.VerifySplit.DoublePrecisionScenario.A64BitVertexFormatIsRecordedAndItsArrayIsDroppedAtDraw
DirectGLES.VerifySplit.LargeArenaAdoptionScenario.ReadbackSeesTheLatestCpuWrite
DirectGLES.VerifySplit.SampleMaskScopeScenario.TheAdvertisedSampleMaskWordCountMatchesWhatSampleMaskiAccepts
DirectVulkan.VerifySplit.BufferTextureScenario.LevelQueriesDescribeTheAttachedBufferRange
DirectVulkan.VerifySplit.ClipDistanceScenario.EnableIsObservableThroughIsEnabled
DirectVulkan.VerifySplit.CopyImageLevelRangeScenario.LevelOneOfASingleLevelTextureIsRejected
DirectVulkan.VerifySplit.CopyImageLevelRangeScenario.LevelTwoOfATwoLevelTextureIsRejected
DirectVulkan.VerifySplit.DoublePrecisionScenario.A64BitVertexFormatIsRecordedAndItsArrayIsDroppedAtDraw
DirectVulkan.VerifySplit.LargeArenaAdoptionScenario.ReadbackSeesTheLatestCpuWrite
DirectVulkan.VerifySplit.SampleMaskScopeScenario.TheAdvertisedSampleMaskWordCountMatchesWhatSampleMaskiAccepts
# --------------------------------------------------------------------------------------------
# FRAMEBUFFER COMPLETENESS QUERIES - attach and ask, never render (2)
# glCheckFramebufferStatus on an attachment of that format. Only the DirectGLES half is
# here: on DirectVulkan both cases SKIP (the format is not renderable on lavapipe), and a skip is
# recognised without a name.
# --------------------------------------------------------------------------------------------
DirectGLES.VerifySplit.SnormAttachmentScenario.SignedNormalizedColorAttachmentsReportComplete
DirectGLES.VerifySplit.ThreeChannelAttachmentScenario.ThreeChannelColorAttachmentsReportComplete
# --------------------------------------------------------------------------------------------
# THE POISON PARENT THAT ONLY FORKS (2)
# PoisonOmissionScenario.WithoutOmissionCompletes re-executes the binary and waits; the
# frame is drawn in the CHILD, which writes its own log (<base>.poison-child). The parent process
# brings a session up and forks, so it reaches no verb of its own.
# --------------------------------------------------------------------------------------------
DirectGLES.VerifySplit.PoisonOmissionScenario.WithoutOmissionCompletes
DirectVulkan.VerifySplit.PoisonOmissionScenario.WithoutOmissionCompletes
@@ -1,466 +0,0 @@
// MobileGL - MobileGL/MG_IntegrationTest/Scenarios/BandedReadbackScenario.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
//
// P7 gate 5, package g5-readback: readbacks LARGER THAN ONE REPLY SLOT.
//
// On every split arm a readback's answer travels back in one SEG_REPLY slot, and a slot carries
// at most MaxReplyBytes = 2 MiB - 16 = 2,097,136 bytes (ID-47). Until this package a
// glReadPixels whose tight answer was larger than that was Fatal{ReplyTooLarge} at the client -
// KHR-GL46.direct_state_access.renderbuffers_storage reads 256x512 RGBA/FLOAT = 2,097,152 bytes,
// sixteen over, and aborted on the inproc arm while the monolith passed. The client now splits
// such a read into row bands that each fit a slot (EmitTables.h PlanReadbackBands) and scatters
// every band under the application's GL_PACK_* state.
//
// THESE ARE ORDINARY GL CASES and run on the monolith arms too, which is the parity half: the
// same pixels must come back whichever side of the wire answers. Every shape below straddles
// the slot boundary on purpose - exactly 2 MiB, 2 MiB plus one row, more than the WHOLE 16 MiB
// SEG_REPLY - and every image is POSITION-DEPENDENT, so a band that landed at the wrong row,
// was dropped, or was read from the wrong box cannot look right.
//
// A row wider than a whole reply (the column-piece arm of the plan) is not reachable here: it
// needs a >131071-pixel RGBA/FLOAT row, wider than any attachment, and GL leaves the pixels
// outside the framebuffer undefined - so that arm is covered by the unit controls over the
// plan and the band scatter (MG_Test/Wire/RemoteClientTest.cpp, RemoteReadback.*).
#include <array>
#include <cmath>
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <limits>
#include <string>
#include <vector>
#include "../Harness/HeadlessGL.h"
#include "../Harness/ScenarioFixture.h"
#ifdef GLAPI
#undef GLAPI
#endif
#define GL_GLEXT_PROTOTYPES
#include <GL/gl.h>
#include <GL/glcorearb.h>
#undef GL_GLEXT_PROTOTYPES
namespace MGITest {
namespace {
// The shared-memory links' reply payload cap (ID-47). Named here only to state the
// arithmetic each shape straddles; the client reads the live number from its link.
constexpr std::size_t kReplySlotPayload = 2u * 1024u * 1024u - 16u;
// The whole SEG_REPLY segment: eight slots of 2 MiB.
constexpr std::size_t kReplySegmentBytes = 16u * 1024u * 1024u;
// A texel that names its own position, so a misplaced band cannot match.
std::array<GLubyte, 4> PatternRgba8(int x, int y) {
return {static_cast<GLubyte>(x & 0xFF),
static_cast<GLubyte>(((x >> 8) & 0x0F) | (((y >> 8) & 0x0F) << 4)),
static_cast<GLubyte>(y & 0xFF), static_cast<GLubyte>((x * 3 + y * 5) & 0xFF)};
}
// Every component an integer (or a half) below 2^24, so float storage is exact.
std::array<GLfloat, 4> PatternRgba32f(int x, int y) {
return {static_cast<GLfloat>(x), static_cast<GLfloat>(y),
static_cast<GLfloat>(x) * 0.5f + static_cast<GLfloat>(y) * 1024.0f,
static_cast<GLfloat>(1 + (x ^ y))};
}
struct PatternFormat {
const char* name;
GLenum internalFormat;
GLenum type;
std::size_t bytesPerPixel;
};
constexpr PatternFormat kRgba8{"RGBA8 / UNSIGNED_BYTE", GL_RGBA8, GL_UNSIGNED_BYTE, 4};
constexpr PatternFormat kRgba32f{"RGBA32F / FLOAT", GL_RGBA32F, GL_FLOAT, 16};
// The pattern's bytes for one texel, in the format's client layout.
void PatternBytes(const PatternFormat& format, int x, int y, GLubyte* out) {
if (format.type == GL_FLOAT) {
const auto texel = PatternRgba32f(x, y);
std::memcpy(out, texel.data(), sizeof(texel));
} else {
const auto texel = PatternRgba8(x, y);
std::memcpy(out, texel.data(), sizeof(texel));
}
}
class BandedReadbackScenario : public ScenarioTest {
protected:
void SetUp() override {
ScenarioTest::SetUp();
if (!Ready()) return;
DrainErrors();
glGenFramebuffers(1, &m_fbo);
glBindFramebuffer(GL_FRAMEBUFFER, m_fbo);
glDisable(GL_SCISSOR_TEST);
glDisable(GL_DEPTH_TEST);
glDisable(GL_STENCIL_TEST);
glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
glDepthMask(GL_TRUE);
glStencilMask(~0u);
ResetPack();
}
void TearDown() override {
if (!Ready()) return;
ResetPack();
glDisable(GL_SCISSOR_TEST);
glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);
if (m_pbo != 0) glDeleteBuffers(1, &m_pbo);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
if (m_fbo != 0) glDeleteFramebuffers(1, &m_fbo);
for (GLuint texture : m_textures) glDeleteTextures(1, &texture);
for (GLuint renderbuffer : m_renderbuffers) glDeleteRenderbuffers(1, &renderbuffer);
m_pbo = 0;
m_fbo = 0;
m_textures.clear();
m_renderbuffers.clear();
DrainErrors();
ScenarioTest::TearDown();
}
static void ResetPack() {
glPixelStorei(GL_PACK_ALIGNMENT, 4);
glPixelStorei(GL_PACK_ROW_LENGTH, 0);
glPixelStorei(GL_PACK_SKIP_ROWS, 0);
glPixelStorei(GL_PACK_SKIP_PIXELS, 0);
glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
}
static void DrainErrors() {
for (int i = 0; i < 16 && glGetError() != GL_NO_ERROR; ++i) {
}
}
// A texture holding the position pattern, attached as COLOR_ATTACHMENT0 and read.
void AttachPatternedTexture(const PatternFormat& format, int width, int height) {
std::vector<GLubyte> texels(static_cast<std::size_t>(width) * height * format.bytesPerPixel);
for (int y = 0; y < height; ++y) {
for (int x = 0; x < width; ++x) {
PatternBytes(format, x, y,
texels.data() + (static_cast<std::size_t>(y) * width + x) * format.bytesPerPixel);
}
}
GLuint texture = 0;
glGenTextures(1, &texture);
m_textures.push_back(texture);
glBindTexture(GL_TEXTURE_2D, texture);
glTexStorage2D(GL_TEXTURE_2D, 1, format.internalFormat, width, height);
glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, height, GL_RGBA, format.type, texels.data());
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture, 0);
glReadBuffer(GL_COLOR_ATTACHMENT0);
ASSERT_EQ(glCheckFramebufferStatus(GL_FRAMEBUFFER), static_cast<GLenum>(GL_FRAMEBUFFER_COMPLETE))
<< format.name << " " << width << "x" << height;
ASSERT_EQ(FirstGLError(), static_cast<GLenum>(GL_NO_ERROR)) << "pattern upload " << format.name;
}
// Every texel of a tight w*h read at (x0, y0), against the pattern.
static void ExpectTightPattern(const PatternFormat& format, const std::vector<GLubyte>& actual, int x0,
int y0, int width, int height) {
std::array<GLubyte, 16> expected{};
std::size_t bad = 0;
std::string first;
for (int y = 0; y < height; ++y) {
for (int x = 0; x < width; ++x) {
PatternBytes(format, x0 + x, y0 + y, expected.data());
const GLubyte* got =
actual.data() + (static_cast<std::size_t>(y) * width + x) * format.bytesPerPixel;
if (std::memcmp(got, expected.data(), format.bytesPerPixel) != 0) {
if (bad++ == 0) first = "(" + std::to_string(x) + "," + std::to_string(y) + ")";
}
}
}
EXPECT_EQ(bad, 0u) << format.name << " " << width << "x" << height << ": " << bad
<< " texels differ from the pattern, first at " << first;
}
void ReadWholeAndExpect(const PatternFormat& format, int width, int height) {
AttachPatternedTexture(format, width, height);
if (HasFatalFailure()) return;
std::vector<GLubyte> actual(static_cast<std::size_t>(width) * height * format.bytesPerPixel, 0xC3);
glReadPixels(0, 0, width, height, GL_RGBA, format.type, actual.data());
ASSERT_EQ(FirstGLError(), static_cast<GLenum>(GL_NO_ERROR)) << "glReadPixels " << format.name;
ExpectTightPattern(format, actual, 0, 0, width, height);
}
GLuint m_fbo = 0;
GLuint m_pbo = 0;
std::vector<GLuint> m_textures;
std::vector<GLuint> m_renderbuffers;
};
} // namespace
// THE CTS SHAPE, byte for byte: KHR-GL46.direct_state_access.renderbuffers_storage reads a
// 256x512 RGBA32F renderbuffer as GL_RGBA/GL_FLOAT - 2,097,152 bytes, sixteen more than a slot.
// A renderbuffer cannot be uploaded, so it is painted with scissored clears: 16 row stripes x 2
// column halves, each its own colour (every value a multiple of 1/32, exact in float and inside
// [0, 1] so no backend's clamping can move it). The last band is the single top row.
TEST_F(BandedReadbackScenario, RenderbufferReadOfExactlyTwoMiBIsBandedNotRefused) {
if (!Ready()) return;
constexpr int kWidth = 256;
constexpr int kHeight = 512;
static_assert(static_cast<std::size_t>(kWidth) * kHeight * 16 == kReplySlotPayload + 16,
"the CTS read is exactly 2 MiB, sixteen bytes over one reply slot");
GLuint renderbuffer = 0;
glGenRenderbuffers(1, &renderbuffer);
m_renderbuffers.push_back(renderbuffer);
glBindRenderbuffer(GL_RENDERBUFFER, renderbuffer);
glRenderbufferStorage(GL_RENDERBUFFER, GL_RGBA32F, kWidth, kHeight);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, renderbuffer);
glDrawBuffer(GL_COLOR_ATTACHMENT0);
glReadBuffer(GL_COLOR_ATTACHMENT0);
ASSERT_EQ(glCheckFramebufferStatus(GL_FRAMEBUFFER), static_cast<GLenum>(GL_FRAMEBUFFER_COMPLETE));
auto stripeColour = [](int x, int y) {
const int stripe = y / 32;
const int half = x / 128;
return std::array<GLfloat, 4>{static_cast<GLfloat>(stripe) / 16.0f, static_cast<GLfloat>(half),
static_cast<GLfloat>(stripe * 2 + half) / 32.0f,
0.25f + 0.5f * static_cast<GLfloat>(half)};
};
glEnable(GL_SCISSOR_TEST);
for (int stripe = 0; stripe < kHeight / 32; ++stripe) {
for (int half = 0; half < 2; ++half) {
const auto colour = stripeColour(half * 128, stripe * 32);
glScissor(half * 128, stripe * 32, 128, 32);
glClearColor(colour[0], colour[1], colour[2], colour[3]);
glClear(GL_COLOR_BUFFER_BIT);
}
}
glDisable(GL_SCISSOR_TEST);
ASSERT_EQ(FirstGLError(), static_cast<GLenum>(GL_NO_ERROR)) << "stripe clears";
std::vector<GLfloat> pixels(static_cast<std::size_t>(kWidth) * kHeight * 4, -7.0f);
glReadPixels(0, 0, kWidth, kHeight, GL_RGBA, GL_FLOAT, pixels.data());
ASSERT_EQ(FirstGLError(), static_cast<GLenum>(GL_NO_ERROR)) << "glReadPixels RGBA/FLOAT 256x512";
std::size_t bad = 0;
std::string first;
for (int y = 0; y < kHeight; ++y) {
for (int x = 0; x < kWidth; ++x) {
const auto expected = stripeColour(x, y);
const GLfloat* got = pixels.data() + (static_cast<std::size_t>(y) * kWidth + x) * 4;
if (std::memcmp(got, expected.data(), sizeof(expected)) != 0 && bad++ == 0) {
first = "(" + std::to_string(x) + "," + std::to_string(y) + ") = " + std::to_string(got[0]) +
"," + std::to_string(got[1]) + "," + std::to_string(got[2]) + "," +
std::to_string(got[3]);
}
}
}
EXPECT_EQ(bad, 0u) << bad << " of " << kWidth * kHeight << " texels are wrong, first " << first;
}
// One row over the slot: 1024x513 RGBA8 = 2 MiB + 4 KiB. Two bands, the second a single row.
TEST_F(BandedReadbackScenario, TwoMiBPlusOneRowIsBanded) {
if (!Ready()) return;
static_assert(1024u * 512u * 4u > kReplySlotPayload, "512 rows alone are already over a slot");
ReadWholeAndExpect(kRgba8, 1024, 513);
}
// Larger than the WHOLE reply segment, not just one slot: 2048x2100 RGBA8 = 17,203,200 bytes
// against a 16 MiB SEG_REPLY. A reply pool that merely grew could never answer this; nine bands
// through the same slot ring can.
TEST_F(BandedReadbackScenario, AReadLargerThanTheWholeReplySegmentIsBanded) {
if (!Ready()) return;
static_assert(2048u * 2100u * 4u > kReplySegmentBytes, "the read must outgrow SEG_REPLY itself");
ReadWholeAndExpect(kRgba8, 2048, 2100);
}
// The bounce path: a non-neutral pack state, for both a 4- and a 16-byte pixel, read from an
// offset box so every band's own box origin is exercised as well. PACK_ALIGNMENT 8 with an odd
// ROW_LENGTH pads every row, SKIP_ROWS / SKIP_PIXELS move the first byte - and the bytes GL does
// NOT name must keep their sentinel, which is what a band scattered on the wrong stride breaks.
TEST_F(BandedReadbackScenario, BandedReadsHonourPackAlignmentRowLengthAndSkips) {
if (!Ready()) return;
struct PackCase {
PatternFormat format;
int textureWidth, textureHeight;
int x0, y0, width, height;
int alignment, rowLength, skipRows, skipPixels;
};
const PackCase cases[] = {
{kRgba8, 1100, 700, 3, 5, 1023, 600, 8, 1025, 2, 5},
{kRgba32f, 320, 640, 1, 2, 300, 600, 8, 303, 1, 2},
};
for (const PackCase& c : cases) {
SCOPED_TRACE(c.format.name);
ASSERT_GT(static_cast<std::size_t>(c.width) * c.height * c.format.bytesPerPixel, kReplySlotPayload);
AttachPatternedTexture(c.format, c.textureWidth, c.textureHeight);
if (HasFatalFailure()) return;
const std::size_t bpp = c.format.bytesPerPixel;
const std::size_t stride =
(static_cast<std::size_t>(c.rowLength) * bpp + c.alignment - 1) / c.alignment * c.alignment;
const std::size_t first = static_cast<std::size_t>(c.skipRows) * stride + c.skipPixels * bpp;
const std::size_t size = first + static_cast<std::size_t>(c.height) * stride + 64;
constexpr GLubyte kSentinel = 0xA5;
std::vector<GLubyte> destination(size, kSentinel);
glPixelStorei(GL_PACK_ALIGNMENT, c.alignment);
glPixelStorei(GL_PACK_ROW_LENGTH, c.rowLength);
glPixelStorei(GL_PACK_SKIP_ROWS, c.skipRows);
glPixelStorei(GL_PACK_SKIP_PIXELS, c.skipPixels);
glReadPixels(c.x0, c.y0, c.width, c.height, GL_RGBA, c.format.type, destination.data());
ResetPack();
ASSERT_EQ(FirstGLError(), static_cast<GLenum>(GL_NO_ERROR));
std::vector<GLubyte> wanted(size, kSentinel);
for (int y = 0; y < c.height; ++y) {
for (int x = 0; x < c.width; ++x) {
PatternBytes(c.format, c.x0 + x, c.y0 + y, wanted.data() + first + y * stride + x * bpp);
}
}
std::size_t bad = 0, firstBad = 0;
for (std::size_t i = 0; i < size; ++i) {
if (destination[i] != wanted[i] && bad++ == 0) firstBad = i;
}
EXPECT_EQ(bad, 0u) << bad << " of " << size << " destination bytes differ, first at byte " << firstBad
<< " (row " << (firstBad >= first ? (firstBad - first) / stride : 0) << ")";
}
}
// A PIXEL_PACK_BUFFER destination at a non-zero offset: the bands are uploaded row by row into
// the buffer under the pack state, and the bytes around them are the application's.
TEST_F(BandedReadbackScenario, BandedReadIntoAPixelPackBufferKeepsItsPadding) {
if (!Ready()) return;
constexpr int kWidth = 1024;
constexpr int kHeight = 600;
constexpr int kRowLength = 1030;
constexpr int kSkipRows = 1;
constexpr std::size_t kOffset = 16;
static_assert(static_cast<std::size_t>(kWidth) * kHeight * 4 > kReplySlotPayload, "must band");
AttachPatternedTexture(kRgba8, kWidth, kHeight);
if (HasFatalFailure()) return;
const std::size_t stride = static_cast<std::size_t>(kRowLength) * 4;
const std::size_t first = kOffset + kSkipRows * stride;
const std::size_t size = first + static_cast<std::size_t>(kHeight) * stride + 32;
constexpr GLubyte kSentinel = 0x3C;
const std::vector<GLubyte> initial(size, kSentinel);
glGenBuffers(1, &m_pbo);
glBindBuffer(GL_PIXEL_PACK_BUFFER, m_pbo);
glBufferData(GL_PIXEL_PACK_BUFFER, static_cast<GLsizeiptr>(size), initial.data(), GL_DYNAMIC_READ);
glPixelStorei(GL_PACK_ROW_LENGTH, kRowLength);
glPixelStorei(GL_PACK_SKIP_ROWS, kSkipRows);
glReadPixels(0, 0, kWidth, kHeight, GL_RGBA, GL_UNSIGNED_BYTE, reinterpret_cast<void*>(kOffset));
ResetPack();
ASSERT_EQ(FirstGLError(), static_cast<GLenum>(GL_NO_ERROR));
std::vector<GLubyte> actual(size, 0);
glGetBufferSubData(GL_PIXEL_PACK_BUFFER, 0, static_cast<GLsizeiptr>(size), actual.data());
glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);
ASSERT_EQ(FirstGLError(), static_cast<GLenum>(GL_NO_ERROR));
std::vector<GLubyte> wanted = initial;
for (int y = 0; y < kHeight; ++y) {
for (int x = 0; x < kWidth; ++x) {
const auto texel = PatternRgba8(x, y);
std::memcpy(wanted.data() + first + y * stride + x * 4, texel.data(), 4);
}
}
std::size_t bad = 0, firstBad = 0;
for (std::size_t i = 0; i < size; ++i) {
if (actual[i] != wanted[i] && bad++ == 0) firstBad = i;
}
EXPECT_EQ(bad, 0u) << bad << " of " << size << " buffer bytes differ, first at byte " << firstBad;
}
// Depth and packed depth/stencil take the SAME banded path - the plan is about the layout,
// not the component. DEPTH_COMPONENT/FLOAT is 4 bytes a pixel (2 bands here), and
// DEPTH_STENCIL/FLOAT_32_UNSIGNED_INT_24_8_REV is 8 (3 bands). Depth is painted in row
// stripes and stencil in column quarters, so both axes of a band's placement are checked.
TEST_F(BandedReadbackScenario, BandedDepthAndDepthStencilReads) {
if (!Ready()) return;
constexpr int kWidth = 1024;
constexpr int kHeight = 640;
constexpr int kStripeRows = 40;
static_assert(static_cast<std::size_t>(kWidth) * kHeight * 4 > kReplySlotPayload, "depth must band");
GLuint texture = 0;
glGenTextures(1, &texture);
m_textures.push_back(texture);
glBindTexture(GL_TEXTURE_2D, texture);
glTexStorage2D(GL_TEXTURE_2D, 1, GL_DEPTH32F_STENCIL8, kWidth, kHeight);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_TEXTURE_2D, texture, 0);
glDrawBuffer(GL_NONE);
glReadBuffer(GL_NONE);
ASSERT_EQ(glCheckFramebufferStatus(GL_FRAMEBUFFER), static_cast<GLenum>(GL_FRAMEBUFFER_COMPLETE));
auto depthAt = [](int y) { return static_cast<GLfloat>(y / kStripeRows + 1) / 32.0f; };
auto stencilAt = [](int x) { return static_cast<unsigned>(10 + (x / (kWidth / 4)) * 20); };
glEnable(GL_SCISSOR_TEST);
for (int stripe = 0; stripe < kHeight / kStripeRows; ++stripe) {
glScissor(0, stripe * kStripeRows, kWidth, kStripeRows);
glClearDepth(depthAt(stripe * kStripeRows));
glClear(GL_DEPTH_BUFFER_BIT);
}
for (int quarter = 0; quarter < 4; ++quarter) {
glScissor(quarter * (kWidth / 4), 0, kWidth / 4, kHeight);
glClearStencil(static_cast<GLint>(stencilAt(quarter * (kWidth / 4))));
glClear(GL_STENCIL_BUFFER_BIT);
}
glDisable(GL_SCISSOR_TEST);
glClearDepth(1.0);
glClearStencil(0);
ASSERT_EQ(FirstGLError(), static_cast<GLenum>(GL_NO_ERROR)) << "depth/stencil stripe clears";
const std::size_t pixels = static_cast<std::size_t>(kWidth) * kHeight;
{
std::vector<GLfloat> depth(pixels, -3.0f);
glReadPixels(0, 0, kWidth, kHeight, GL_DEPTH_COMPONENT, GL_FLOAT, depth.data());
ASSERT_EQ(FirstGLError(), static_cast<GLenum>(GL_NO_ERROR)) << "DEPTH_COMPONENT/FLOAT";
std::size_t bad = 0, firstBad = 0;
for (std::size_t i = 0; i < pixels; ++i) {
const int y = static_cast<int>(i / kWidth);
if (std::fabs(depth[i] - depthAt(y)) > 1.0f / 4096.0f && bad++ == 0) firstBad = i;
}
EXPECT_EQ(bad, 0u) << bad << " depth values wrong, first at pixel " << firstBad << " = "
<< depth[firstBad];
}
{
struct D32fS8 {
GLfloat depth;
GLuint stencil;
};
static_assert(sizeof(D32fS8) == 8, "FLOAT_32_UNSIGNED_INT_24_8_REV is two 32-bit words");
std::vector<D32fS8> packed(pixels, D32fS8{-3.0f, 0xFFFFFFFFu});
glReadPixels(0, 0, kWidth, kHeight, GL_DEPTH_STENCIL, GL_FLOAT_32_UNSIGNED_INT_24_8_REV, packed.data());
ASSERT_EQ(FirstGLError(), static_cast<GLenum>(GL_NO_ERROR)) << "DEPTH_STENCIL/FLOAT_32_24_8_REV";
std::size_t bad = 0, firstBad = 0;
for (std::size_t i = 0; i < pixels; ++i) {
const int x = static_cast<int>(i % kWidth);
const int y = static_cast<int>(i / kWidth);
if ((std::fabs(packed[i].depth - depthAt(y)) > 1.0f / 4096.0f ||
(packed[i].stencil & 0xFFu) != stencilAt(x)) &&
bad++ == 0) {
firstBad = i;
}
}
EXPECT_EQ(bad, 0u) << bad << " packed depth/stencil pairs wrong, first at pixel " << firstBad
<< " = depth " << packed[firstBad].depth << " stencil "
<< (packed[firstBad].stencil & 0xFFu);
}
}
// THE OTHER READBACK THAT CROSSES THE REPLY SLOT. glGetTexImage was already windowed
// (TextureReadbackEmit.inc: DstOffset/DstSize windows of at most MaxReplyBytes), so this is
// the parity row that keeps it so beside the banded ReadPixels: 1024x1024 RGBA8 = 4 MiB.
TEST_F(BandedReadbackScenario, GetTexImageLargerThanAReplySlotIsWindowed) {
if (!Ready()) return;
constexpr int kWidth = 1024;
constexpr int kHeight = 1024;
AttachPatternedTexture(kRgba8, kWidth, kHeight);
if (HasFatalFailure()) return;
std::vector<GLubyte> actual(static_cast<std::size_t>(kWidth) * kHeight * 4, 0x77);
glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_BYTE, actual.data());
ASSERT_EQ(FirstGLError(), static_cast<GLenum>(GL_NO_ERROR)) << "glGetTexImage";
ExpectTightPattern(kRgba8, actual, 0, 0, kWidth, kHeight);
}
} // namespace MGITest
@@ -25,7 +25,6 @@
// half of that control is TheDirectApplierResetCallOnTheGLThreadIsRoleViolation below, and
// the guard's two non-Fatal arms are pinned in PipeWireCodecTest's CtWireFatals suite.
#include "../Harness/PipeSlotPeek.h"
#include "../Harness/PipeStatsWindow.h"
#include "../Harness/ScenarioFixture.h"
#include "../Harness/SplitRuntimePeek.h"
@@ -148,16 +147,13 @@ namespace {
TEST_F(CtWireScenario, TextureDeathCrossesAndTheRecycledSlotAnswersTheNewObject) {
if (!Ready()) return;
// P7 wave 2 package C: THE BACKEND GUARD IS GONE, and both halves of why it was here
// are answered rather than waived. The producer used to be Espryt-side only
// (OnFrontendStateObjectDestroyed, CONTRACT-P5C.md §5.2), so a DirectVulkan run had
// no death record to watch; Magma now installs its own StateObjectDeathOps
// (DirectVulkan.cpp, CONTRACT-P7 §5.5) and emits the same `object_death`. Package L
// measured that the SPAWN arm already passed once the WireTables install condition
// went backend-agnostic and that the INPROC arm failed here with `deaths` 0 vs 0
// (notes/p7/magma-two-process-first-run.md §6); the table is what closes the inproc
// half, and this case is the gate on it. It is also the RED-ONCE for that table: with
// the install site short-circuited, both cases red on the two EXPECT_GT below.
// 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};
@@ -179,36 +175,13 @@ namespace {
ASSERT_TRUE(beforeCounters.valid) << "server object-death telemetry missing";
const MobileGL::Uint64 deathsBefore = beforeCounters.deaths;
glDeleteTextures(1, &texture);
// THE FENCE, AND WHY IT IS NO LONGER A CLEAR.
//
// object_death is a kCtxObject value-class record whose wait class is kWaitNone, so
// under run-ahead the client publishes it and moves on, and the server-side tally below
// only moves at APPLY time. The clear this case used to fence on is kWaitNone TOO -
// PipeCalls.def's Clear row - so once the wait column governed (P5e's run-ahead), it
// waited for nothing and the read below raced the apply thread. Nothing had hidden that
// for a while except the per-record barriers the converted rows still took; P12 took
// those away on the wire arm (set_texture_params, respecify and the texture sub-data
// stop owning an answer), the client now runs further ahead, and the race stopped being
// a rarity. MEASURED on this entry under llvmpipe: 2 red of 5 runs (`deaths` 1 vs 1,
// the record applied a moment later) and 3 green of 3 with MOBILEGL_IPC_RUN_AHEAD=0. A
// timing race, never a lost record: the notice is emitted and applied either way.
//
// WHAT IS A REAL BOUNDARY, MEASURED ON ALL THREE ARMS RATHER THAN ASSUMED. The
// harness's applied-seq fence (WaitForSplitAppliedForTesting) is the right shape for
// inproc - and it is NOT usable here: this case is registered on the spawn and tcp arms
// too, the client's progress page there is advanced by frames rather than by the
// peer's own apply, and the wait times out. MEASURED with that fence in place: this
// case red at 5.0 s on DirectGLES.Tcp.Ct.
//
// A READBACK IS THE ONE BOUNDARY THAT HOLDS ON EVERY ARM. ReadPixels is
// kReplySlot|kWaitReply, so the client blocks on its answer, and an answer is posted
// only after its record has been APPLIED - and the ring applies in order, so the death
// published before it is applied too. (On the spawn and tcp arms the counter below
// comes from the peer's log, which ServerCounters() syncs before it reads - and that
// sync is itself a round trip the death has already crossed.)
GLubyte fencePixel[4]{};
glReadPixels(0, 0, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, fencePixel);
ASSERT_EQ(FirstGLError(), GLenum(GL_NO_ERROR)) << "the fence readback left a GL error behind";
// THE FENCE, the framebuffer case's exactly (MOBILEGL_IPC_BATCH_WAITS, default on):
// object_death is a kCtxObject value-class record, published WITHOUT waiting for its
// own apply, and the server-side tally only moves at apply time. Without a wait
// boundary this read races the apply thread - it passed by timing until P5d round 3's
// clock-free spin changed that timing, then failed 1 in 5. A clear is kCtxVerb and
// still waits, and its wait covers the death.
glClear(GL_COLOR_BUFFER_BIT);
const auto afterCounters = ServerCounters();
ASSERT_TRUE(afterCounters.valid) << "server object-death telemetry missing";
EXPECT_GT(afterCounters.deaths, deathsBefore)
@@ -229,76 +202,16 @@ namespace {
<< "Ct.TextureDeath.pixels - the recycled texture read back the dead twin's content";
}
// ------------------------------------------------------------------------------------
// P7 wave 2 package C, OQ-10 (CONTRACT-P7 §5.4): the resident-sub-data capability, read
// on the CLIENT, on a real session, on both backends and all three transports.
//
// WHAT IT PINS AND WHY IT IS HERE RATHER THAN IN A BUFFER SCENARIO. `kCapResidentSubData`
// is the one thing the frontend can ask, under a transport, about whether the side that
// will APPLY a write implements the resident arm: the client has no op table of its own
// to probe (MGPipeResourceOpsHaveSubDataResident says so in as many words) and reads this
// bit instead. Until this package nothing ever ORed it into the server's mask, so the
// answer was permanently "no" - which silently pinned BOTH backends to the ordered
// in-place host memcpy and made Magma's own SubDataResident arm
// (VkBufferManager.cpp's g_vulkanWireResourceOps) dead code on the wire. A capability
// that is never published is indistinguishable from one that does not exist, and no
// pixel, GL query or error can tell the two apart - so the bit itself is the assertion.
//
// THE SERVER HALF IS ASSERTED ELSEWHERE, deliberately: RemoteClientTest's
// MagmaTransportPublishesRealBufferConsumersWithoutRunAhead pins that the bit is DERIVED
// FROM THE SERVER'S OWN RESOURCE TABLE (`ops->SubDataResident != nullptr`) and never from
// a backend enum, which is ID-39's lesson. This case pins the other half - that what the
// server published actually reached the client - and the two together are what make the
// frontend's read of it mean anything.
//
// WHAT IT DOES NOT PIN, AND THE REASON IS R-6 RATHER THAN AN OMISSION. This does not
// assert that a `buffer_subdata_resident` record (opcode 49) crossed, because under a
// transport none can yet: the resident arm is reached only from a store that is GPU
// RESIDENT, residency comes only from AdoptPersistentMap, and every persistent-map
// acquisition declines under split by R-6 (PipeApply.cpp's MGPipeApplyMapPersistent:
// "A SPLIT BUILD RUNS AT TIER T2 AND DECLINES EVERY ACQUISITION, ALWAYS"; T0/T1 are
// P11's and AdoptTierIsEmulate is a named Fatal for them). So the capability is wired
// AHEAD of its consumer on purpose, and `rsd=` on the PipeStats line is the counter that
// will show the records the day P11 lands a tier that adopts. See notes/p7/magma-c.md.
TEST_F(CtWireScenario, TheServerPublishesTheResidentSubDataCapabilityFromItsOwnTable) {
if (!Ready()) return;
// A REAL WORKLOAD FIRST, and it is not decoration: ScenarioFixture's arming rule
// (ScenarioFixture.h:90) fails a case that runs in an armed split lane without moving
// the client encoder's record ordinal, because a case that emits nothing cannot tell
// "the transport resolved and carried this session" from "the emit table resolved and
// then put nothing on the wire". The bit below is a property OF that session, so the
// session has to have carried something before the reading means anything.
glClearColor(0.25f, 0.5f, 0.75f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
GLubyte pixel[4]{};
glReadPixels(1, 1, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, pixel);
ASSERT_EQ(FirstGLError(), GLenum(GL_NO_ERROR)) << "Ct.ResidentSubDataCap.workload";
const int expected[4] = {64, 128, 191, 255};
for (int i = 0; i < 4; ++i) EXPECT_NEAR(pixel[i], expected[i], 1)
<< "Ct.ResidentSubDataCap.pixels";
const auto runtime = PeekSplitRuntime();
if (!runtime.peekAvailable || !runtime.sessionActive) {
GTEST_SKIP() << "no split runtime peek or no live client session: 'could not look' "
"and 'the bit was withheld' are the same false";
}
EXPECT_TRUE(runtime.residentSubDataCap)
<< "the client's caps mirror did not receive kCapResidentSubData on a "
<< runtime.transportName << " session with backend " << Gl().BackendName()
<< ". The server publishes it in MG_Backend/Init.cpp's InitServerRoleCommon from "
"its own wire resource table; without it every resident write falls back to "
"the in-place memcpy and opcode 49 never crosses on either backend";
}
TEST_F(CtWireScenario, FramebufferDeathCrossesAndTheRecycledSlotAnswersTheNewObject) {
if (!Ready()) return;
// Backend-agnostic for the texture case's reason (P7 wave 2 package C): both
// backends now install a StateObjectDeathOps table and both emit `object_death`.
// 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) - which is exactly why the missing Magma table was
// a SERVER-side twin leak and not merely a missing counter: with no consumer for
// the notice, nothing on the wire ever told the server this framebuffer had died.
// The renderbuffer goes along so the FBO has storage.
// 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);
@@ -321,47 +234,18 @@ namespace {
const auto beforeCounters = ServerCounters();
ASSERT_TRUE(beforeCounters.valid) << "server object-death telemetry missing";
const MobileGL::Uint64 deathsBefore = beforeCounters.deaths;
// THE CLIENT'S OWN ACCOUNTING, read beside the server's (P7 wave 2 package C,
// CONTRACT-P7 §5.5's PipeSlotPeek clause). The two numbers answer DIFFERENT halves of
// one death and neither implies the other, which is exactly why both are read here:
// * `deaths` below says the SERVER was told - the half the missing Magma table
// broke, and the only delivery a framebuffer has (no wire delete opcode at all);
// * this one says the CLIENT returned the slot. That half has been backend-neutral
// since P4a (PipeFill.cpp's NotifyAndFree frees whatever the notice does), so it
// is a CONTROL rather than the subject: if it ever regressed, a green `deaths`
// would be measuring an object that never let go of its handle.
// `false` means the allocator is out of reach (a pull build, or Android's hidden
// symbols), and the peek is then simply not asserted - "could not look" is not
// "did not leak", so nothing is concluded from it either way.
unsigned fboSlotsBefore = 0;
const bool slotsReadable =
PeekPipeSlotLiveCount(PipeSlotKind::Framebuffer, &fboSlotsBefore);
glDeleteFramebuffers(1, &fbo);
// THE FENCE, the texture case's exactly: object_death is a kCtxObject value-class
// record with wait class kWaitNone, so under run-ahead it is published WITHOUT waiting
// for its own apply (production-safe: the in-order ring applies it before any record
// that recycles the slot), and the server-side counter this assertion reads only moves
// at apply time. A clear cannot be that boundary - its own class is kWaitNone too - so
// this waits on a READBACK, which is kWaitReply on every arm. The texture case carries
// the measurements, including the boundary that is right for inproc and wrong for
// spawn/tcp.
GLubyte fencePixel[4]{};
glReadPixels(0, 0, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, fencePixel);
ASSERT_EQ(FirstGLError(), GLenum(GL_NO_ERROR)) << "the fence readback left a GL error behind";
// THE FENCE (MOBILEGL_IPC_BATCH_WAITS, default on): object_death is a kCtxObject
// value-class record - published WITHOUT waiting for its own apply (production-safe:
// the in-order ring applies it before any record that recycles the slot). The
// server-side counter this assertion reads only moves at apply time, so it needs a
// wait boundary: a clear is kCtxVerb and still waits, and its wait covers the death.
glClear(GL_COLOR_BUFFER_BIT);
const auto afterCounters = ServerCounters();
ASSERT_TRUE(afterCounters.valid) << "server object-death telemetry missing";
EXPECT_GT(afterCounters.deaths, deathsBefore)
<< "the framebuffer's death produced no object_death record - and no other "
"opcode can carry it. Backend "
<< Gl().BackendName();
if (slotsReadable) {
unsigned fboSlotsAfter = 0;
ASSERT_TRUE(PeekPipeSlotLiveCount(PipeSlotKind::Framebuffer, &fboSlotsAfter));
EXPECT_LT(fboSlotsAfter, fboSlotsBefore)
<< "the dead framebuffer kept its client slot: live count " << fboSlotsBefore
<< " -> " << fboSlotsAfter << " across the delete. Backend "
<< Gl().BackendName();
}
"opcode can carry it";
glDeleteRenderbuffers(1, &renderbuffer);
// Recycle: a new FBO and a new backing store, cleared to a different colour. A stale
@@ -35,18 +35,14 @@
// only checked "no GL error" would pass against a readback that never touched the buffer,
// which is precisely how this whole cluster hid for so long.
#include <array>
#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <string>
#include <vector>
#include "../Harness/HeadlessGL.h"
#include "../Harness/PipeStatsWindow.h"
#include "../Harness/ScenarioFixture.h"
#include "../Harness/SplitLane.h"
#ifdef GLAPI
#undef GLAPI
@@ -230,110 +226,6 @@ namespace MGITest {
? " - which is the poison value, so nothing was written at all"
: "");
}
// P7 gate 5 (g5-msrbo review round, g5-msprobe): WHICH WIRE ARM RESOLVED, WHERE THE ENTRY
// SAYS WHICH ONE IT HAS TO BE. Lavapipe resolves a multisample depth/stencil aspect
// correctly through both of ResolveWireDepthStencil's arms, so the pixel assertions
// above cannot tell them apart - and the fix that made
// KHR-GL46.direct_state_access.renderbuffers_storage_multisample pass on the Redmi is
// exactly an arm ORDER, chosen by a resolve probe at the server's device bring-up (the
// shader pass first where the no-draw resolve render pass is measured leaving its target
// unwritten, as the Adreno 830's does). Three kinds of entry name the arm:
// - MsResolveBug. / MsFlipBug. set MGITEST_MAGMA_DEPTH_RESOLVE_PROBE=bug, which hands
// the server's arm choice a canned "the render pass wrote nothing" measurement in
// place of running the probe: the shader pass must resolve, the render pass never;
// - MsResolve1. / MsFlip1. set MGITEST_MAGMA_FORCE_SHADER_DEPTH_RESOLVE=1, which drops
// the render-pass arm altogether: same assertion;
// - MsResolveElide. sets MGITEST_MAGMA_DEPTH_RESOLVE_PROBE=elide-subject, which runs the
// REAL probe with its render-pass resolve left unrecorded: the measurement itself (not
// a canned one) must report the defect - a reading whose render pass kept the sentinel
// in every texel while the shader control resolved all of them - and the shader pass
// must then resolve, the render pass never. The Bug entries cannot see the real
// probe's recording, readback or tally stop detecting the defect; this one does;
// - MsResolve0. on split and spawn sets MGITEST_EXPECT_DEPTH_RESOLVE_PROBE=clean - a
// marker only this function reads - and asserts the REAL probe ran on the lane's
// device (lavapipe), found the render pass clean, and that the render pass resolved.
// Without it a probe that stopped working (or started reporting lavapipe as broken)
// would leave every pixel green.
// The claim is read off the SERVER's private log (the backend runs on the apply thread,
// the server role, on every arm), where ResolveWireDepthStencil says once per arm which
// one ran and ArmWireDepthResolveOrder states the verdict; keep the phrases in step with
// WireFramebuffer.inc and VulkanRenderer.cpp. Every other entry asserts nothing here.
//
// Red once (executed, reverted): EvaluateWireDepthResolveProbe answering Clean for every
// measurement fails the four Bug entries here (the render-pass line is in the log and
// the verdict line says clean) while their pixels stay green. The two Elide entries go
// red under that too, and ALONE go red when the real probe's tally counts every subject
// texel as resolved (the canned Bug readings never pass through it).
static void ExpectTheResolveArmWhereTheLaneAsks(const char* what) {
const std::string probe = SplitLane::MarkerValue("MGITEST_MAGMA_DEPTH_RESOLVE_PROBE");
const bool forcedBug = probe == "bug";
const bool elidedSubject = probe == "elide-subject";
const bool renderPassDropped = SplitLane::MarkerIsOne("MGITEST_MAGMA_FORCE_SHADER_DEPTH_RESOLVE");
const bool measuredClean = SplitLane::MarkerValue("MGITEST_EXPECT_DEPTH_RESOLVE_PROBE") == "clean";
if (!forcedBug && !elidedSubject && !renderPassDropped && !measuredClean) return;
if (PipeStatsWindow::ServerLibraryLogPath().empty()) {
ADD_FAILURE() << what << ": the entry names the resolve arm (probe=" << probe
<< ", force-shader=" << renderPassDropped << ", expect-clean=" << measuredClean
<< ") but configured no MOBILEGL_LOG_FILE_PATH, and the server's log "
"is the only place the arm is visible";
return;
}
glFinish();
const std::string server = PipeStatsWindow::ReadServerLogSince(PipeStatsWindow::LogMark{});
const bool shaderResolved =
server.find("ResolveWireDepthStencil: resolved by the shader pass") != std::string::npos;
const bool renderPassResolved =
server.find("ResolveWireDepthStencil: resolved by the VK_KHR_depth_stencil_resolve render pass") !=
std::string::npos;
if (forcedBug || elidedSubject || renderPassDropped) {
EXPECT_TRUE(shaderResolved) << what << ": the server never resolved with the shader pass (probe="
<< probe << ", force-shader=" << renderPassDropped << ")";
EXPECT_FALSE(renderPassResolved)
<< what << ": the server resolved with the no-draw render pass, the arm the probe verdict "
"(or the knob) rules out (probe=" << probe
<< ", force-shader=" << renderPassDropped << ")";
if (forcedBug) {
EXPECT_NE(server.find("verdict=render-pass-resolve-broken"), std::string::npos)
<< what << ": the forced `bug` measurement did not evaluate to the defect verdict";
}
if (elidedSubject) {
// The source phrase is the REAL measurement's (a canned one says "forced by"),
// and ArmWireDepthResolveOrder states it once per process.
EXPECT_NE(server.find("depth/stencil resolve probe (measured on this device with its render-pass "
"resolve elided by MGITEST_MAGMA_DEPTH_RESOLVE_PROBE=elide-subject) "
"verdict=render-pass-resolve-broken"),
std::string::npos)
<< what << ": the real probe, its render-pass resolve elided, did not report the defect";
// DescribeWireDepthResolveFormat's reading, one line per probed format: some
// format's render pass matched no texel and kept the sentinel in all 16, and its
// shader control resolved all 16.
bool sentinelKeptBesideAResolvedControl = false;
for (std::string::size_type at = server.find("depth/stencil resolve probe ");
at != std::string::npos && !sentinelKeptBesideAResolvedControl;
at = server.find("depth/stencil resolve probe ", at + 1)) {
const std::string::size_type end = server.find('\n', at);
const std::string line =
server.substr(at, end == std::string::npos ? std::string::npos : end - at);
sentinelKeptBesideAResolvedControl =
line.find(" x4: ") != std::string::npos &&
line.find("render pass 0/16 (first ") != std::string::npos &&
line.find("sentinel 16), shader control 16/16") != std::string::npos;
}
EXPECT_TRUE(sentinelKeptBesideAResolvedControl)
<< what << ": no real reading shows the elided render pass's sentinel kept beside a "
"shader control that resolved";
}
return;
}
EXPECT_NE(server.find("depth/stencil resolve probe (measured on this device) verdict=clean"),
std::string::npos)
<< what << ": the server's resolve probe did not measure this device's render pass clean";
EXPECT_TRUE(renderPassResolved)
<< what << ": a clean probe verdict must leave the render pass first, and it never resolved";
EXPECT_FALSE(shaderResolved) << what << ": the shader pass resolved although the probe found the "
"render pass clean";
}
};
// ---- glReadPixels across the source kinds -----------------------------------
@@ -505,7 +397,6 @@ namespace MGITest {
ExpectAllDepth(ReadDepthFloat(0, 0, kWidth, kHeight), 0.375f,
"stencil-only resolve preserves destination depth");
EXPECT_EQ(FirstGLError(), 0u);
ExpectTheResolveArmWhereTheLaneAsks("depth-only and stencil-only resolves");
DestroySource(resolved);
DestroySource(multisampled);
@@ -513,463 +404,6 @@ namespace MGITest {
Gl().EndFrame();
}
// P7 wave 2-B2 (review round): A MULTISAMPLE DEPTH RESOLVE THAT FLIPS, AND ONE THAT SCALES.
//
// GL 4.6 core 18.3.1 asks a multisample blit for identical rectangle DIMENSIONS, not for
// identical corners - Mesa compares absolute spans - so `glBlitFramebuffer(0, h, w, 0, ...)`
// out of a multisample framebuffer is legal and owes a mirrored picture, while a blit whose
// sizes differ is INVALID_OPERATION and owes nothing. The wire arm used to end the SESSION
// on both: `Magma:multisample-depth-resolve-region` covered the reversed rectangle and the
// scaled one under one Fatal.
//
// COLOUR AND DEPTH IN ONE CALL, because that is the shape that made this visible: the colour
// arm has handled a flip since P5f and handles a scale as of this package, so
// GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT resolved its colour correctly and then died on its
// depth. Asserting both aspects of the same blit is what pins them together.
//
// THE BANDS ARE UNEQUAL ON PURPOSE (0.25 bottom / 0.75 top): a flip that did not happen
// returns the bands the right way up, and a "flip" that merely reordered the readback would
// move the colour too - so colour and depth are checked to agree about which way up they are.
//
// THE CASE IS ARMED ON THE MAGMA WIRE ARM ONLY, and the two gates below say which of the
// other arms that discover it (the suite is registered whole on the monolith DirectVulkan
// arm and on every DirectGLES arm) owe this picture and do not yet produce it. Both are
// recorded debts (notes/p7/magma-b2.md §6), not agreements with the wrong answer:
// - Espryt (DirectGLES, monolith and split alike): the flipped resolve writes nothing and
// raises no error, and the scaled one raises no error either. P3b/P4b.
// - the monolith DirectVulkan arm: `VulkanRenderer.cpp` refuses a depth blit with a
// flipped rectangle ("depth blits with flipped rectangles are not supported yet" - the
// destination keeps its clear, no error) and scales a multisample depth blit that GL
// calls INVALID_OPERATION. The wire arm is the more correct one here; the monolith fix
// is P13/G1-bound.
// The backend gate runs first so a DirectGLES entry names the backend that owes the fix,
// whichever lane it sits in. The second gate is THE TRANSPORT THE PROCESS RESOLVED, read out
// of the process (SplitRuntimePeek.h), because that is the very fork that selects the wire
// arm: VulkanRenderer::BlitFramebuffer hands the call to BlitWireFramebuffers whenever
// MG_Config::Transport is not Monolith. MGITEST_SPLIT_LANE would be the wrong question
// (review round 3): it marks the CURATED lanes, not the transport - the whole-binary
// `DirectVulkan.{Split,Spawn,Tcp}.Full.` census and the `DirectVulkan.VerifySplit.` lane run
// inproc/spawn/tcp WITHOUT it on purpose (their CMake blocks say why), and a marker gate
// skipped this case there with a message about a monolith that was not running. The marker
// plays no part in this gate at all (review round 4): when it is set and the transport did
// not resolve, the fixture's SetUp has already skipped the case through
// SplitLane::SkipReasonForSplitOnlyAssertions() -> SplitRuntimeSkipReason() ("MG_Config::
// Transport resolved to 'monolith', not to a split transport"), so Ready() is false and this
// line is never reached - a `!IsSplitLane() &&` conjunct here could only ever be true, and
// round 3's comment described a branch nothing reaches.
TEST_F(DepthStencilReadbackMatrixScenario, AFlippedMultisampleResolveMirrorsTheBandsAndAScaleDeclines) {
if (!Ready()) return;
if (Gl().BackendName() != "DirectVulkan") {
GTEST_SKIP() << "Espryt (" << Gl().BackendName() << ") does not produce this picture yet: a "
"flipped multisample depth resolve writes nothing with no error and a scaled "
"one raises no INVALID_OPERATION - a P3b/P4b debt (notes/p7/magma-b2.md §6)";
}
if (!PeekSplitRuntime().transportResolved) {
GTEST_SKIP() << "the monolith DirectVulkan transport (this process resolved no split "
"transport, so BlitFramebuffer takes the monolith arm) refuses a flipped "
"depth blit (\"depth blits with flipped rectangles are not supported yet\", "
"destination untouched, no error) and scales a multisample depth blit GL "
"calls INVALID_OPERATION - a wire-vs-monolith divergence where the wire arm "
"is the correct one; the monolith fix is P13/G1-bound (notes/p7/magma-b2.md §6)";
}
DepthSource multisampled = MakeRenderbufferSource(GL_DEPTH24_STENCIL8, 4);
if (!SourceIsUsable()) {
DestroySource(multisampled);
GTEST_SKIP() << "this driver cannot host a 4x multisample DEPTH24_STENCIL8 renderbuffer";
}
constexpr int kBottomStencil = 11;
constexpr int kTopStencil = 99;
constexpr int kPrimeStencil = 3;
FirstGLError();
glDisable(GL_SCISSOR_TEST);
glViewport(0, 0, kWidth, kHeight);
glDepthMask(GL_TRUE);
glStencilMask(0xFFu);
glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
glEnable(GL_SCISSOR_TEST);
glScissor(0, 0, kWidth, kHeight / 2);
glClearDepth(0.25);
glClearStencil(kBottomStencil);
glClearColor(1, 0, 0, 1);
glClear(GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
glScissor(0, kHeight / 2, kWidth, kHeight - kHeight / 2);
glClearDepth(0.75);
glClearStencil(kTopStencil);
glClearColor(0, 1, 0, 1);
glClear(GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
glDisable(GL_SCISSOR_TEST);
ASSERT_EQ(FirstGLError(), 0u) << "banding the multisample source";
DepthSource resolved = MakeTextureSource(GL_DEPTH24_STENCIL8);
ASSERT_TRUE(SourceIsUsable());
ClearDepthStencil(GL_DEPTH24_STENCIL8, 0.5f, kPrimeStencil);
glClearColor(0, 0, 1, 1);
glClear(GL_COLOR_BUFFER_BIT);
ASSERT_EQ(FirstGLError(), 0u) << "priming the resolve destination";
// Y REVERSED ON THE SOURCE SIDE, identical dimensions.
glBindFramebuffer(GL_READ_FRAMEBUFFER, multisampled.fbo);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, resolved.fbo);
glDisable(GL_SCISSOR_TEST);
glBlitFramebuffer(0, kHeight, kWidth, 0, 0, 0, kWidth, kHeight,
GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT, GL_NEAREST);
glFinish();
EXPECT_EQ(FirstGLError(), 0u) << "a flipped multisample resolve is a legal blit";
glBindFramebuffer(GL_FRAMEBUFFER, resolved.fbo);
// The bands come back swapped: the destination's bottom rows hold what was the top.
const std::vector<float> bottom = ReadDepthFloat(0, 0, kWidth, kHeight / 4);
EXPECT_EQ(FirstGLError(), 0u);
ExpectAllDepth(bottom, 0.75f, "flipped resolve: the destination's bottom band");
const std::vector<float> top = ReadDepthFloat(0, kHeight - kHeight / 4, kWidth, kHeight / 4);
EXPECT_EQ(FirstGLError(), 0u);
ExpectAllDepth(top, 0.25f, "flipped resolve: the destination's top band");
// Colour went the same way up, through the arm that could already do this.
std::array<GLubyte, 4> colour{};
glReadPixels(kWidth / 2, 1, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, colour.data());
EXPECT_EQ(colour, (std::array<GLubyte, 4>{0, 255, 0, 255}))
<< "flipped resolve: colour and depth must agree about which way up the blit landed";
// THE STENCIL ASPECT, NARROW AND OFFSET ON BOTH SIDES. The copy-out moves one aspect
// through a buffer one row per region, and a depth/stencil buffer<->image copy wants
// every bufferOffset on a multiple of 4 (VUID-vkCmdCopyBufferToImage-pRegions-07978).
// A stencil texel is ONE byte, so a tightly packed row whose width is not a multiple
// of 4 puts every row but the first on an illegal offset - which the 64-wide depth
// leg above (4-byte texels) can never show. 29 is odd, so a 2-byte (D16) texel would
// miss the alignment too. The rectangle also sits away from the origin on both sides
// (source x 5, y 8; destination x 20, y 4), so a copy-out that forgot the min corner
// on either side lands the band somewhere else.
{
constexpr int kSx = 5, kSy = 8, kDx = 20, kDy = 4, kW = 29, kH = 32;
glBindFramebuffer(GL_READ_FRAMEBUFFER, multisampled.fbo);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, resolved.fbo);
glBlitFramebuffer(kSx, kSy + kH, kSx + kW, kSy, kDx, kDy, kDx + kW, kDy + kH,
GL_STENCIL_BUFFER_BIT, GL_NEAREST);
glFinish();
EXPECT_EQ(FirstGLError(), 0u) << "a flipped, narrow multisample stencil resolve is a legal blit";
glBindFramebuffer(GL_FRAMEBUFFER, resolved.fbo);
const std::vector<int> stencil = ReadStencilInt(0, 0, kWidth, kHeight);
EXPECT_EQ(FirstGLError(), 0u);
size_t bad = 0;
int firstX = -1, firstY = -1, firstGot = 0, firstWant = 0;
for (int y = 0; y < kHeight; ++y) {
for (int x = 0; x < kWidth; ++x) {
int want = kPrimeStencil;
if (x >= kDx && x < kDx + kW && y >= kDy && y < kDy + kH) {
const int sourceRow = kSy + kH - 1 - (y - kDy); // the mirror
want = sourceRow < kHeight / 2 ? kBottomStencil : kTopStencil;
}
const int got = stencil[static_cast<size_t>(y) * kWidth + x];
if (got != want) {
if (bad == 0) { firstX = x; firstY = y; firstGot = got; firstWant = want; }
++bad;
}
}
}
EXPECT_EQ(bad, 0u) << "flipped narrow stencil resolve: " << bad << " of " << stencil.size()
<< " stencil values are wrong; first at (" << firstX << ", " << firstY
<< "): got " << firstGot << ", want " << firstWant;
}
// The two flipped resolves above are the only ones in this case that reach an arm: every
// leg below declines on its shape first.
ExpectTheResolveArmWhereTheLaneAsks("flipped depth and narrow stencil resolves");
// A SCALE, which is INVALID_OPERATION and must leave the destination as it is.
ClearDepthStencil(GL_DEPTH24_STENCIL8, 0.5f, 3);
ASSERT_EQ(FirstGLError(), 0u);
glBindFramebuffer(GL_READ_FRAMEBUFFER, multisampled.fbo);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, resolved.fbo);
glBlitFramebuffer(0, 0, kWidth, kHeight, 0, 0, kWidth / 2, kHeight / 2,
GL_DEPTH_BUFFER_BIT, GL_NEAREST);
glFinish(); // the decline's error rides a later reply under a transport
EXPECT_EQ(FirstGLError(), GLenum(GL_INVALID_OPERATION))
<< "a scaled multisample resolve is INVALID_OPERATION, not a picture";
glBindFramebuffer(GL_FRAMEBUFFER, resolved.fbo);
ExpectAllDepth(ReadDepthFloat(0, 0, kWidth, kHeight), 0.5f,
"the declined scale must have left the destination alone");
EXPECT_EQ(FirstGLError(), 0u) << "the session survived the decline";
// THE SAME SCALE WITH COLOUR IN THE MASK. An erroring blit writes nothing (18.3.1), so
// the colour attachment must come through untouched too. The colour arm CAN scale a
// multisample resolve on its own, and it runs before the depth arm - so a decline
// decided per aspect scaled and wrote the colour and then raised the error on the
// depth. The shape is decided once, before any aspect, and this is what pins it.
glBindFramebuffer(GL_FRAMEBUFFER, resolved.fbo);
ClearDepthStencil(GL_DEPTH24_STENCIL8, 0.5f, kPrimeStencil);
glClearColor(0, 0, 1, 1);
glClear(GL_COLOR_BUFFER_BIT);
ASSERT_EQ(FirstGLError(), 0u);
glBindFramebuffer(GL_READ_FRAMEBUFFER, multisampled.fbo);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, resolved.fbo);
glBlitFramebuffer(0, 0, kWidth, kHeight, 0, 0, kWidth / 2, kHeight / 2,
GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT, GL_NEAREST);
glFinish();
EXPECT_EQ(FirstGLError(), GLenum(GL_INVALID_OPERATION))
<< "a scaled multisample COLOR|DEPTH blit is INVALID_OPERATION as a whole";
glBindFramebuffer(GL_FRAMEBUFFER, resolved.fbo);
std::array<GLubyte, 4> untouched{};
glReadPixels(1, 1, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, untouched.data());
EXPECT_EQ(untouched, (std::array<GLubyte, 4>{0, 0, 255, 255}))
<< "the declined COLOR|DEPTH scale must not have written its colour either";
ExpectAllDepth(ReadDepthFloat(0, 0, kWidth, kHeight), 0.5f,
"the declined COLOR|DEPTH scale must have left the depth alone");
EXPECT_EQ(FirstGLError(), 0u) << "the session survived the combined decline";
// AN EMPTY DESTINATION BEHIND A NON-EMPTY SOURCE is a size mismatch as well, not a
// no-op: 64x48 cannot reach 0x48.
glBindFramebuffer(GL_READ_FRAMEBUFFER, multisampled.fbo);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, resolved.fbo);
glBlitFramebuffer(0, 0, kWidth, kHeight, 0, 0, 0, kHeight, GL_DEPTH_BUFFER_BIT, GL_NEAREST);
glFinish();
EXPECT_EQ(FirstGLError(), GLenum(GL_INVALID_OPERATION))
<< "a multisample resolve onto an empty destination rectangle is a size mismatch";
glBindFramebuffer(GL_FRAMEBUFFER, resolved.fbo);
ExpectAllDepth(ReadDepthFloat(0, 0, kWidth, kHeight), 0.5f,
"the empty-destination decline must have left the depth alone");
EXPECT_EQ(FirstGLError(), 0u) << "the session survived the empty-destination decline";
// THE SAME SCALE ONTO THE WINDOW (review round 3). The default framebuffer was the one
// destination the round-2 pre-pass left to the per-aspect lambdas, on the belief that a
// default draw framebuffer behind a multisample read was the resolve arm's region Fatal
// whatever the shape - but that arm asks the shape question BEFORE its region check, so
// a scaled COLOR|DEPTH resolve onto the window scaled and wrote its colour through the
// swapchain blit and then recorded INVALID_OPERATION on its depth: the partial effect
// the previous leg pins for a user framebuffer, reproduced on the only other kind of
// destination there is. The window is primed MAGENTA at depth 0.625 - values no other
// surface in this test holds (review round 4): the user framebuffer above is blue at 0.5
// and still is after its own declined blit, and the source is red/green at 0.25/0.75.
// Round 3 primed the window blue at 0.5 as well, so a glBindFramebuffer(0) that landed
// on the user framebuffer, or a default-framebuffer readback that resolved the wrong
// surface, read the same priming and passed for nothing; pointing the probes at the
// user framebuffer now fails on both aspects, shown once and restored. The source (red
// below, green above) is blown up over the whole of the window, and three probes - a
// corner, the centre, the far corner - must all still read the priming on both
// aspects. The harness's pbuffer default framebuffer has no other way of being looked
// at than glReadPixels, which is what both probes use.
{
HeadlessGL& gl = Gl();
const int windowWidth = gl.Width();
const int windowHeight = gl.Height();
ASSERT_GE(windowWidth, 4);
ASSERT_GE(windowHeight, 4);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glDisable(GL_SCISSOR_TEST);
glViewport(0, 0, windowWidth, windowHeight);
glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
glDepthMask(GL_TRUE);
glClearColor(1, 0, 1, 1);
glClearDepth(0.625);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
ASSERT_EQ(FirstGLError(), 0u) << "priming the default framebuffer";
glBindFramebuffer(GL_READ_FRAMEBUFFER, multisampled.fbo);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
glBlitFramebuffer(0, 0, kWidth, kHeight, 0, 0, windowWidth, windowHeight,
GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT, GL_NEAREST);
glFinish();
EXPECT_EQ(FirstGLError(), GLenum(GL_INVALID_OPERATION))
<< "a scaled multisample COLOR|DEPTH blit onto the default framebuffer is INVALID_OPERATION as a whole";
glBindFramebuffer(GL_FRAMEBUFFER, 0);
const int probeX[3] = {1, windowWidth / 2, windowWidth - 2};
const int probeY[3] = {1, windowHeight / 2, windowHeight - 2};
for (int i = 0; i < 3; ++i) {
const int x = probeX[i], y = probeY[i];
std::array<GLubyte, 4> window{};
glReadPixels(x, y, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, window.data());
EXPECT_EQ(window, (std::array<GLubyte, 4>{255, 0, 255, 255}))
<< "the declined COLOR|DEPTH scale onto the window must not have written its colour at ("
<< x << ", " << y << ")";
float depth = kDepthPoison;
glReadPixels(x, y, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &depth);
EXPECT_NEAR(depth, 0.625f, 1.0f / 4096.0f)
<< "the declined COLOR|DEPTH scale onto the window must have left its depth alone at ("
<< x << ", " << y << ")";
}
EXPECT_EQ(FirstGLError(), 0u) << "the session survived the default-framebuffer decline";
}
DestroySource(resolved);
DestroySource(multisampled);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
Gl().EndFrame();
}
// P7 gate 5 (g5-msrbo): A SINGLE-SAMPLED DEPTH/STENCIL BLIT, EVERY FORMAT, EVERY ASPECT.
//
// KHR-GL46.direct_state_access.renderbuffers_storage_multisample reduced to its samples == 0
// leg: two renderbuffers of one depth/stencil format (glNamedRenderbufferStorageMultisample
// with samples 0, the conformance case's own call), clear the first, glBlitFramebuffer
// COLOR|DEPTH|STENCIL into the second at 1:1, read both aspects back from the second. The
// wire arm moved every depth/stencil aspect with vkCmdBlitImage, which needs BLIT_SRC/BLIT_DST
// (optional for depth/stencil formats: the Adreno 830 has no BLIT_DST on any of them) where
// the monolith arm copies at 1:1 - and for ONE aspect of a packed format the blit moved the
// whole native word.
//
// THE SUB-RECTANGLE LEG is the red one without the copy arm on lavapipe (the only host it was
// measured on): a depth-only blit of a packed DEPTH24_STENCIL8 replaced the destination's
// stencil there. A driver whose one-aspect blit keeps the other aspect stays green without
// the copy arm, so this leg is a lavapipe pin, not a universal one. It also pins
// the min corners on both sides and a 1-byte stencil row whose width is not a multiple of 4
// (the buffer round trip's padded stride). THE SCALED LEG is the shape that still takes
// vkCmdBlitImage, so the copy arm must not have swallowed it.
TEST_F(DepthStencilReadbackMatrixScenario, ASingleSampledDepthStencilBlitCopiesEveryAspect) {
if (!Ready()) return;
struct BlitFormat {
const char* name;
GLenum internalFormat;
};
const BlitFormat formats[] = {
{"GL_DEPTH_COMPONENT16", GL_DEPTH_COMPONENT16}, {"GL_DEPTH_COMPONENT24", GL_DEPTH_COMPONENT24},
{"GL_DEPTH_COMPONENT32F", GL_DEPTH_COMPONENT32F}, {"GL_DEPTH24_STENCIL8", GL_DEPTH24_STENCIL8},
{"GL_DEPTH32F_STENCIL8", GL_DEPTH32F_STENCIL8}, {"GL_STENCIL_INDEX8", GL_STENCIL_INDEX8},
};
struct Extent {
int width, height;
};
// The conformance case's three shapes ({1,1}, {max/2,1}, {1,max/2}), with strips short
// enough for a CPU rasterizer, plus the matrix's own rectangle.
const Extent extents[] = {{1, 1}, {256, 1}, {1, 256}, {kWidth, kHeight}};
const auto makePair = [](GLenum internalFormat, int width, int height, GLuint (&fbo)[2], GLuint (&rbo)[2]) {
glGenFramebuffers(2, fbo);
glCreateRenderbuffers(2, rbo);
for (int i = 0; i < 2; ++i) {
glNamedRenderbufferStorageMultisample(rbo[i], 0, internalFormat, width, height);
glBindFramebuffer(GL_FRAMEBUFFER, fbo[i]);
if (FormatHasDepth(internalFormat))
glNamedFramebufferRenderbuffer(fbo[i], GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, rbo[i]);
if (FormatHasStencil(internalFormat))
glNamedFramebufferRenderbuffer(fbo[i], GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, rbo[i]);
}
};
const auto clearBound = [](GLenum internalFormat, int width, int height, float depth, int stencil) {
glDisable(GL_SCISSOR_TEST);
glViewport(0, 0, width, height);
glDepthMask(GL_TRUE);
glStencilMask(0xFFu);
glClearDepth(depth);
glClearStencil(stencil);
GLbitfield mask = 0;
if (FormatHasDepth(internalFormat)) mask |= GL_DEPTH_BUFFER_BIT;
if (FormatHasStencil(internalFormat)) mask |= GL_STENCIL_BUFFER_BIT;
glClear(mask);
};
int exercised = 0;
for (const BlitFormat& format : formats) {
for (const Extent& extent : extents) {
SCOPED_TRACE(std::string(format.name) + " " + std::to_string(extent.width) + "x" +
std::to_string(extent.height));
GLuint fbo[2] = {0, 0};
GLuint rbo[2] = {0, 0};
makePair(format.internalFormat, extent.width, extent.height, fbo, rbo);
glBindFramebuffer(GL_FRAMEBUFFER, fbo[0]);
const bool usable = SourceIsUsable();
glBindFramebuffer(GL_FRAMEBUFFER, fbo[1]);
if (!usable || !SourceIsUsable()) {
glDeleteFramebuffers(2, fbo);
glDeleteRenderbuffers(2, rbo);
FirstGLError();
continue;
}
ASSERT_EQ(FirstGLError(), 0u) << "creating the renderbuffer pair";
glBindFramebuffer(GL_FRAMEBUFFER, fbo[1]);
clearBound(format.internalFormat, extent.width, extent.height, kDepthPoison, kStencilPoison);
glBindFramebuffer(GL_FRAMEBUFFER, fbo[0]);
clearBound(format.internalFormat, extent.width, extent.height, 0.5f, 7);
glBindFramebuffer(GL_READ_FRAMEBUFFER, fbo[0]);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo[1]);
glBlitFramebuffer(0, 0, extent.width, extent.height, 0, 0, extent.width, extent.height,
GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT, GL_NEAREST);
EXPECT_EQ(FirstGLError(), 0u) << "a 1:1 single-sampled depth/stencil blit";
glBindFramebuffer(GL_FRAMEBUFFER, fbo[1]);
if (FormatHasDepth(format.internalFormat))
ExpectAllDepth(ReadDepthFloat(0, 0, extent.width, extent.height), 0.5f, "blitted depth");
if (FormatHasStencil(format.internalFormat))
ExpectAllStencil(ReadStencilInt(0, 0, extent.width, extent.height), 7, "blitted stencil");
EXPECT_EQ(FirstGLError(), 0u);
++exercised;
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glDeleteFramebuffers(2, fbo);
glDeleteRenderbuffers(2, rbo);
}
}
// Six formats times four extents; a machine that hosts fewer than half is not a matrix.
EXPECT_GE(exercised, 12) << "too few depth/stencil renderbuffer pairs were usable";
// THE SUB-RECTANGLE LEG, packed DEPTH24_STENCIL8: a depth-only band, then a stencil-only
// band, each offset from the origin on both sides and narrow enough that a 1-byte stencil
// row is not a multiple of 4.
{
GLuint fbo[2] = {0, 0};
GLuint rbo[2] = {0, 0};
makePair(GL_DEPTH24_STENCIL8, kWidth, kHeight, fbo, rbo);
glBindFramebuffer(GL_FRAMEBUFFER, fbo[0]);
ASSERT_TRUE(SourceIsUsable());
clearBound(GL_DEPTH24_STENCIL8, kWidth, kHeight, 0.75f, 99);
glBindFramebuffer(GL_FRAMEBUFFER, fbo[1]);
clearBound(GL_DEPTH24_STENCIL8, kWidth, kHeight, 0.25f, 11);
ASSERT_EQ(FirstGLError(), 0u);
constexpr int kSx = 5, kSy = 8, kDx = 20, kDy = 4, kW = 29, kH = 32;
glBindFramebuffer(GL_READ_FRAMEBUFFER, fbo[0]);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo[1]);
glBlitFramebuffer(kSx, kSy, kSx + kW, kSy + kH, kDx, kDy, kDx + kW, kDy + kH, GL_DEPTH_BUFFER_BIT,
GL_NEAREST);
EXPECT_EQ(FirstGLError(), 0u) << "a depth-only sub-rectangle blit";
glBindFramebuffer(GL_FRAMEBUFFER, fbo[1]);
const std::vector<float> depth = ReadDepthFloat(0, 0, kWidth, kHeight);
const std::vector<int> stencil = ReadStencilInt(0, 0, kWidth, kHeight);
size_t badDepth = 0, badStencil = 0;
for (int y = 0; y < kHeight; ++y) {
for (int x = 0; x < kWidth; ++x) {
const bool inside = x >= kDx && x < kDx + kW && y >= kDy && y < kDy + kH;
const size_t at = static_cast<size_t>(y) * kWidth + x;
if (std::fabs(depth[at] - (inside ? 0.75f : 0.25f)) > 1.0f / 4096.0f) ++badDepth;
if (stencil[at] != 11) ++badStencil;
}
}
EXPECT_EQ(badDepth, 0u) << "the depth-only band landed somewhere other than its destination rectangle";
EXPECT_EQ(badStencil, 0u) << "a depth-only blit replaced the destination's stencil";
glBindFramebuffer(GL_READ_FRAMEBUFFER, fbo[0]);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo[1]);
glBlitFramebuffer(kSx, kSy, kSx + kW, kSy + kH, kDx, kDy, kDx + kW, kDy + kH, GL_STENCIL_BUFFER_BIT,
GL_NEAREST);
EXPECT_EQ(FirstGLError(), 0u) << "a stencil-only sub-rectangle blit";
glBindFramebuffer(GL_FRAMEBUFFER, fbo[1]);
const std::vector<float> depthAfter = ReadDepthFloat(0, 0, kWidth, kHeight);
const std::vector<int> stencilAfter = ReadStencilInt(0, 0, kWidth, kHeight);
badDepth = badStencil = 0;
for (int y = 0; y < kHeight; ++y) {
for (int x = 0; x < kWidth; ++x) {
const bool inside = x >= kDx && x < kDx + kW && y >= kDy && y < kDy + kH;
const size_t at = static_cast<size_t>(y) * kWidth + x;
if (std::fabs(depthAfter[at] - (inside ? 0.75f : 0.25f)) > 1.0f / 4096.0f) ++badDepth;
if (stencilAfter[at] != (inside ? 99 : 11)) ++badStencil;
}
}
EXPECT_EQ(badStencil, 0u) << "the stencil-only band landed somewhere other than its destination rectangle";
EXPECT_EQ(badDepth, 0u) << "a stencil-only blit replaced the destination's depth";
// THE SCALED LEG: half the source onto the whole destination - the shape that still
// takes vkCmdBlitImage.
glBindFramebuffer(GL_FRAMEBUFFER, fbo[1]);
clearBound(GL_DEPTH24_STENCIL8, kWidth, kHeight, 0.25f, 11);
glBindFramebuffer(GL_READ_FRAMEBUFFER, fbo[0]);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo[1]);
glBlitFramebuffer(0, 0, kWidth / 2, kHeight / 2, 0, 0, kWidth, kHeight, GL_DEPTH_BUFFER_BIT, GL_NEAREST);
glFinish();
EXPECT_EQ(FirstGLError(), 0u) << "a scaled depth blit with NEAREST is legal GL";
glBindFramebuffer(GL_FRAMEBUFFER, fbo[1]);
ExpectAllDepth(ReadDepthFloat(0, 0, kWidth, kHeight), 0.75f, "a scaled depth blit");
EXPECT_EQ(FirstGLError(), 0u) << "the session survived the scaled leg";
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glDeleteFramebuffers(2, fbo);
glDeleteRenderbuffers(2, rbo);
}
Gl().EndFrame();
}
// A read whose rectangle is NOT the whole attachment. The staging copy has to carry
// the requested rect (not the origin) and hand back its rows bottom-up, which a
// full-extent uniform read is a fixed point of and therefore cannot see.
@@ -1,149 +0,0 @@
// MobileGL - MobileGL/MG_IntegrationTest/Scenarios/EmptyTextureLevelScenario.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
//
// Scenario - A TEXTURE LEVEL DEFINED EMPTY IS LEGAL GL, AND IT MUST NOT END THE SESSION.
//
// glTexImage1D(width 0), glTexImage2D(0 x 0), glTexImage3D(0 x 0 x 0) define a level with no
// texels. dEQP's glu::resetStateGLCore issues exactly that for EVERY texture target on EVERY unit
// after EVERY case (gluStateReset.cpp), so a split arm that cannot carry an empty level cannot run
// a single KHR-GL case to completion.
//
// P7 PH-4 (f90afcd1) put each per-level respecify's exact extent on the wire and made the server
// refuse any zero component as a noncanonical carrier - Fatal{ProtocolCorruption,
// "ResourceRespecify.ExtentCarrier"} on the apply thread, from the reset that follows the case
// rather than the case itself. The two cases below are the reset's own sequence, then the
// round trip that proves a level can go empty and come back with texels the server really staged.
#include <array>
#include <vector>
#include "../Harness/HeadlessGL.h"
#include "../Harness/ScenarioFixture.h"
#ifdef GLAPI
#undef GLAPI
#endif
#define GL_GLEXT_PROTOTYPES
#include <GL/gl.h>
#include <GL/glcorearb.h>
#undef GL_GLEXT_PROTOTYPES
namespace MGITest {
namespace {
class EmptyTextureLevelScenario : public ScenarioTest {
protected:
void TearDown() override {
if (!Ready()) return;
glBindFramebuffer(GL_FRAMEBUFFER, 0);
if (m_fbo != 0) glDeleteFramebuffers(1, &m_fbo);
if (m_texture != 0) glDeleteTextures(1, &m_texture);
m_fbo = m_texture = 0;
while (glGetError() != GL_NO_ERROR) {
}
}
// Every target resetStateGLCore empties, in its order, on the default textures.
static void EmptyEveryDefaultTarget() {
glBindTexture(GL_TEXTURE_1D, 0);
glTexImage1D(GL_TEXTURE_1D, 0, GL_RGBA, 0, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr);
glBindTexture(GL_TEXTURE_2D, 0);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 0, 0, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr);
glBindTexture(GL_TEXTURE_CUBE_MAP, 0);
for (GLenum face = GL_TEXTURE_CUBE_MAP_POSITIVE_X; face <= GL_TEXTURE_CUBE_MAP_NEGATIVE_Z; ++face)
glTexImage2D(face, 0, GL_RGBA, 0, 0, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr);
glBindTexture(GL_TEXTURE_1D_ARRAY, 0);
glTexImage2D(GL_TEXTURE_1D_ARRAY, 0, GL_RGBA, 0, 0, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr);
glBindTexture(GL_TEXTURE_2D_ARRAY, 0);
glTexImage3D(GL_TEXTURE_2D_ARRAY, 0, GL_RGBA, 0, 0, 0, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr);
glBindTexture(GL_TEXTURE_3D, 0);
glTexImage3D(GL_TEXTURE_3D, 0, GL_RGBA, 0, 0, 0, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr);
glBindTexture(GL_TEXTURE_RECTANGLE, 0);
glTexImage2D(GL_TEXTURE_RECTANGLE, 0, GL_RGBA, 0, 0, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr);
}
GLuint m_texture = 0;
GLuint m_fbo = 0;
};
} // namespace
// dEQP's reset, verbatim in shape: every default texture target defined EMPTY at level 0,
// twice (the reset runs after every case), then an ordinary clear + readback. Before the fix
// the first glTexImage1D ended the session on every split arm; the readback is what proves
// the session is still the one the case started with.
TEST_F(EmptyTextureLevelScenario, TheCtsStateResetDefinesEveryDefaultTargetEmpty) {
if (!Ready()) return;
for (int pass = 0; pass < 2; ++pass) {
glActiveTexture(GL_TEXTURE0);
EmptyEveryDefaultTarget();
glActiveTexture(GL_TEXTURE1);
EmptyEveryDefaultTarget();
glActiveTexture(GL_TEXTURE0);
ASSERT_EQ(FirstGLError(), 0u) << "an empty level definition is legal GL (pass " << pass << ")";
}
HeadlessGL& gl = Gl();
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glViewport(0, 0, gl.Width(), gl.Height());
glDisable(GL_SCISSOR_TEST);
glClearColor(0.0f, 1.0f, 0.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
std::array<GLubyte, 4> pixel{};
glReadPixels(1, 1, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, pixel.data());
EXPECT_EQ(FirstGLError(), 0u);
// The default framebuffer's readback is not what this case is about (it reads zeros on some
// DirectVulkan hosts, tools/cts/README.md) - what matters is that the call RETURNED, i.e.
// the session that took the empty levels is still answering.
gl.EndFrame();
}
// A NAMED texture's level goes 4x4 (with texels) -> EMPTY -> 2x2 (with other texels), and the
// 2x2 content must be what a framebuffer readback of that level returns. This is the staged
// store's half: the empty definition must drop the 4x4 bytes and coverage (the coordinate
// system was replaced), and must not stand in the way of the next non-empty definition
// adopting its own bytes.
TEST_F(EmptyTextureLevelScenario, ALevelDefinedEmptyThenRedefinedCarriesTheNewTexels) {
if (!Ready()) return;
glGenTextures(1, &m_texture);
glBindTexture(GL_TEXTURE_2D, m_texture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
std::vector<GLubyte> redTexels(4 * 4 * 4, 0);
for (std::size_t i = 0; i < redTexels.size(); i += 4) {
redTexels[i] = 255;
redTexels[i + 3] = 255;
}
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, 4, 4, 0, GL_RGBA, GL_UNSIGNED_BYTE, redTexels.data());
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, 0, 0, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr); // empty
std::vector<GLubyte> greenTexels(2 * 2 * 4, 0);
for (std::size_t i = 0; i < greenTexels.size(); i += 4) {
greenTexels[i + 1] = 255;
greenTexels[i + 3] = 255;
}
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, 2, 2, 0, GL_RGBA, GL_UNSIGNED_BYTE, greenTexels.data());
ASSERT_EQ(FirstGLError(), 0u) << "4x4 -> empty -> 2x2 on one level is legal GL";
glGenFramebuffers(1, &m_fbo);
glBindFramebuffer(GL_FRAMEBUFFER, m_fbo);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, m_texture, 0);
ASSERT_EQ(glCheckFramebufferStatus(GL_FRAMEBUFFER), GLenum(GL_FRAMEBUFFER_COMPLETE));
std::vector<GLubyte> readBack(2 * 2 * 4, 7);
glPixelStorei(GL_PACK_ALIGNMENT, 1);
glReadPixels(0, 0, 2, 2, GL_RGBA, GL_UNSIGNED_BYTE, readBack.data());
EXPECT_EQ(FirstGLError(), 0u);
EXPECT_EQ(readBack, greenTexels)
<< "the level that went empty and came back must hold the 2x2 texels it was redefined with";
glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
glPixelStorei(GL_PACK_ALIGNMENT, 4);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
Gl().EndFrame();
}
} // namespace MGITest
@@ -481,66 +481,6 @@ TEST_F(F1WireScenario, GenerateMipmapPackedFloatPixels) {
for (int i = 0; i < 8; ++i) EXPECT_NEAR(rows[i], generated[i], 0.01f);
}
// P7 wave 2-B: THE ARM THE HOST CANNOT REACH ON ITS OWN.
//
// Two Iris cases (minecraft-1.21.4-fabric-iris-iterationt-in-world and its -nodsa twin) killed
// the server apply thread on a Redmi (Adreno 830v2) with
// MGPipe: Fatal{UnmigratedVerb, "Magma:mipmap-shader-format-or-shape"}
// deterministically, under both run-ahead and lockstep, while the monolith arm passed and the
// host lane stayed green. It stayed green because lavapipe reports BLIT_SRC|BLIT_DST for every
// colour format this scenario can create: `nativeBlit` is always true here, so NEITHER shader
// arm of GenerateWireMipmap has ever executed on the gate machine. A refusal no host lane can
// reach is a refusal that ships.
//
// MGITEST_MAGMA_FORCE_SHADER_MIPMAP is what makes them reachable, and it selects which one:
// 1 - drop the native blit only. The destination level is still a colour attachment, so the
// pass renders straight into it (the arm an Adreno takes for a format without BLIT_DST).
// 2 - also treat the destination as not attachable. The pass renders into owned scratch and
// copies the mip in (the arm it takes for a texture whose image never got
// COLOR_ATTACHMENT usage - which, before this package, was the refusal itself).
//
// The assertion is the ORDINARY mip result, per half: a shader mip that renders somewhere else
// is still wrong unless the level holds what a blit would have put there, in GL's row order.
// Red once (executed, reverted): drop the scratch arm (force `viaScratch` false) and the tier-2
// entry dies with Fatal{UnmigratedVerb, "Magma:mipmap-shader-format-or-shape ..."} by name.
TEST_F(F1WireScenario, GenerateMipmapWithoutNativeBlitPixels) {
if (!Ready()) return;
const std::string tier = SplitLane::MarkerValue("MGITEST_MAGMA_FORCE_SHADER_MIPMAP");
if (tier.empty())
GTEST_SKIP() << "MGITEST_MAGMA_FORCE_SHADER_MIPMAP is unset: this driver reports "
"BLIT_SRC|BLIT_DST for GL_RGBA8, so the shader mip arms under test are "
"not entered and this case would assert the native blit twice over";
Attach(GL_RGBA8, GL_COLOR_ATTACHMENT0, 4);
glDisable(GL_SCISSOR_TEST);
glClearColor(0.75f, 0.25f, 0.5f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
// Two different halves, not one flat colour: a pass that loses GL's row order averages to
// the same number everywhere and a single-colour assertion would call that correct.
glEnable(GL_SCISSOR_TEST);
glScissor(0, 0, 8, 4);
glClearColor(0.25f, 0.75f, 0.5f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
glDisable(GL_SCISSOR_TEST);
const auto before = PeekSplitRuntime().emitSeq;
glGenerateMipmap(GL_TEXTURE_2D);
ASSERT_GT(PeekSplitRuntime().emitSeq, before) << "F1.ShaderMip.wire";
// Level one is 4x4, and each of its rows averages two source rows from ONE half - the
// boundary never falls inside a destination texel, so the two colours survive unmixed.
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture, 1);
ASSERT_EQ(glCheckFramebufferStatus(GL_FRAMEBUFFER), GLenum(GL_FRAMEBUFFER_COMPLETE));
GLubyte rows[4][4]{};
glReadPixels(1, 0, 1, 4, GL_RGBA, GL_UNSIGNED_BYTE, rows);
ASSERT_EQ(FirstGLError(), GLenum(GL_NO_ERROR)) << "F1.ShaderMip.error";
const int bottom[4] = {64, 191, 128, 255};
const int top[4] = {191, 64, 128, 255};
for (int row = 0; row < 4; ++row) {
const int* expected = row < 2 ? bottom : top;
for (int channel = 0; channel < 4; ++channel)
EXPECT_NEAR(rows[row][channel], expected[channel], 2)
<< "F1.ShaderMip.pixels tier=" << tier << " row=" << row << " channel=" << channel;
}
}
TEST_F(F1WireScenario, GenerateMipmapDepthPixels) {
if (!Ready()) return;
std::array<GLfloat, 8 * 8> source{};
@@ -560,121 +500,6 @@ TEST_F(F1WireScenario, GenerateMipmapDepthPixels) {
EXPECT_NEAR(pixel, 0.375f, 0.00001f);
}
// P7 wave 2-B, CONTRACT-P7 §5.1 (A): the baked depth mip program, on the two GL depth formats
// that reach it as a depth-only Vulkan aspect (DEPTH_COMPONENT24 -> X8_D24_UNORM_PACK32,
// DEPTH_COMPONENT32F -> D32_SFLOAT). GenerateMipmapDepthPixels above passes on this host
// because lavapipe blits depth natively; the knob removes that arm, which is what an Adreno
// does by itself - VK_FORMAT_FEATURE_BLIT_DST is OPTIONAL for depth formats, so a depth chain
// through a shader is the ordinary case and not the exotic one.
//
// TWO HALVES AND A BAND THAT IS NOT ASSERTED. The generated level is read back through a real
// sampled attachment, so a flat fill would prove nothing: the source is split at its middle
// row instead. The ported filter takes a 2x2 box at ivec2(texCoord * srcTexelSize), which
// lands half a texel off the destination centre - the monolith's own arithmetic, kept
// deliberately (§3.2 retires a refusal by matching that arm, defects included). Under either
// reading of that half texel, destination rows 0..2 come only from the lower half and rows
// 4..7 only from the upper half; row 3 is the straddle and is the one row this case does not
// pin, because pinning it would assert the half-texel offset rather than the mip.
TEST_F(F1WireScenario, GenerateMipmapDepthWithoutNativeBlitPixels) {
if (!Ready()) return;
const std::string tier = SplitLane::MarkerValue("MGITEST_MAGMA_FORCE_SHADER_MIPMAP");
if (tier.empty())
GTEST_SKIP() << "MGITEST_MAGMA_FORCE_SHADER_MIPMAP is unset: this driver blits depth "
"natively, so the baked depth mip program under test is not entered";
for (const GLenum internalFormat : {GL_DEPTH_COMPONENT24, GL_DEPTH_COMPONENT32F}) {
GLuint depth = 0;
glGenTextures(1, &depth);
glBindTexture(GL_TEXTURE_2D, depth);
glTexStorage2D(GL_TEXTURE_2D, 5, internalFormat, 16, 16);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, depth, 0);
glDrawBuffer(GL_NONE);
glReadBuffer(GL_NONE);
ASSERT_EQ(glCheckFramebufferStatus(GL_FRAMEBUFFER), GLenum(GL_FRAMEBUFFER_COMPLETE))
<< "format 0x" << std::hex << internalFormat;
glDepthMask(GL_TRUE);
glDisable(GL_SCISSOR_TEST);
glClearDepth(0.75);
glClear(GL_DEPTH_BUFFER_BIT);
glEnable(GL_SCISSOR_TEST);
glScissor(0, 0, 16, 8);
glClearDepth(0.25);
glClear(GL_DEPTH_BUFFER_BIT);
glDisable(GL_SCISSOR_TEST);
const auto before = PeekSplitRuntime().emitSeq;
glGenerateMipmap(GL_TEXTURE_2D);
ASSERT_GT(PeekSplitRuntime().emitSeq, before) << "F1.DepthMip.wire";
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, depth, 1);
ASSERT_EQ(glCheckFramebufferStatus(GL_FRAMEBUFFER), GLenum(GL_FRAMEBUFFER_COMPLETE));
GLfloat rows[8]{};
glReadPixels(2, 0, 1, 8, GL_DEPTH_COMPONENT, GL_FLOAT, rows);
ASSERT_EQ(FirstGLError(), GLenum(GL_NO_ERROR)) << "F1.DepthMip.error";
for (int row = 0; row < 8; ++row) {
if (row == 3) continue;
const GLfloat expected = row < 3 ? 0.25f : 0.75f;
EXPECT_NEAR(rows[row], expected, 0.002f)
<< "F1.DepthMip.pixels tier=" << tier << " format=0x" << std::hex << internalFormat
<< std::dec << " row=" << row;
}
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
glDeleteTextures(1, &depth);
glBindTexture(GL_TEXTURE_2D, texture);
}
glClearDepth(1.0);
}
// The OTHER half of `depth-stencil-mipmap@P7`, and it is a decline rather than a retirement
// (CONTRACT-P7 §3.2): a combined depth/stencil texture has no mip generation on EITHER arm -
// the monolith's shader fallback asserts depth-only, and an assert is nothing in the release
// build both arms ship as. What this case pins is that the wire arm now says so and carries
// on, rather than taking the session down: no GL error, the session still alive afterwards,
// and level zero still holding what was cleared into it.
//
// No knob: the decline is decided on the ASPECT, before the blit-support question is asked,
// so it fires on every driver.
// Red once (executed, reverted): restore the MagmaWireFatal and this case dies with
// Fatal{UnmigratedVerb, "Magma:depth-stencil-mipmap@P7"}.
//
// MAGMA ONLY, like the three other `*Declines*` cases below. Rule I and §3.2 are MG_Backend/
// DirectVulkan's wire-arm contract, but the DirectGLES whole-binary entry discovers this case
// too and reaches its body whenever the process resolves a split transport - the primary
// integration lane runs every integration-gpu entry under MOBILEGL_TRANSPORT=inproc. Espryt
// answers this shape with GL_INVALID_OPERATION and leaves level zero and the session intact
// (measured, DirectGLES x inproc on lavapipe): a different answer, not a broken decline.
TEST_F(F1WireScenario, GenerateMipmapDepthStencilDeclinesAndKeepsTheSession) {
if (!Ready()) return;
if (Gl().BackendName() != "DirectVulkan")
GTEST_SKIP() << "Magma wire-arm decline (CONTRACT-P7 3.2, depth-stencil-mipmap): Espryt ("
<< Gl().BackendName()
<< ") answers a depth/stencil glGenerateMipmap with GL_INVALID_OPERATION and "
"leaves level 0 intact, which is not the no-error decline this case pins";
GLuint depthStencil = 0;
glGenTextures(1, &depthStencil);
glBindTexture(GL_TEXTURE_2D, depthStencil);
glTexStorage2D(GL_TEXTURE_2D, 4, GL_DEPTH24_STENCIL8, 8, 8);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_TEXTURE_2D, depthStencil, 0);
glDrawBuffer(GL_NONE);
glReadBuffer(GL_NONE);
ASSERT_EQ(glCheckFramebufferStatus(GL_FRAMEBUFFER), GLenum(GL_FRAMEBUFFER_COMPLETE));
glDepthMask(GL_TRUE);
glDisable(GL_SCISSOR_TEST);
glClearDepth(0.5);
glClear(GL_DEPTH_BUFFER_BIT);
glGenerateMipmap(GL_TEXTURE_2D);
EXPECT_EQ(FirstGLError(), GLenum(GL_NO_ERROR)) << "F1.DepthStencilMip.error";
// The session is what the retired Fatal used to take with it. A readback is a round trip
// through the server, so it answers that question and the level-zero one at once.
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_TEXTURE_2D, depthStencil, 0);
ASSERT_EQ(glCheckFramebufferStatus(GL_FRAMEBUFFER), GLenum(GL_FRAMEBUFFER_COMPLETE));
GLfloat level0 = 0;
glReadPixels(1, 1, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &level0);
EXPECT_EQ(FirstGLError(), GLenum(GL_NO_ERROR)) << "F1.DepthStencilMip.readback";
EXPECT_NEAR(level0, 0.5f, 0.002f) << "F1.DepthStencilMip.level0";
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
glDeleteTextures(1, &depthStencil);
glBindTexture(GL_TEXTURE_2D, texture);
glClearDepth(1.0);
}
TEST_F(F1WireScenario, GenerateMipmapHonorsMutableBaseAndMaxWithoutChangingOtherLevels) {
if (!Ready()) return;
const std::array<GLubyte, 4> colors[5] = {
@@ -1090,69 +915,6 @@ void main() { color = value + tail; }
glDeleteProgram(program);
}
TEST_F(F1WireScenario, SubWordUniformBufferRangePadsMissingBytes) {
if (!Ready()) return;
// The sibling of ShortUniformBufferRangePadsMissingBytes whose bound range does NOT
// end on a four-byte boundary. That window is what `uniform-buffer-byte-tail`
// used to refuse (a named Fatal that took the whole session with it), and it is the
// live boundary the Redmi Minecraft run reported (notes/p5f/magma-inproc-fix.md #5).
//
// Only the SIZE can land off a word here. glBindBufferRange constrains the offset to
// GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT and records GL_INVALID_VALUE otherwise
// (MG_Impl/GLImpl/Buffer/GL_Buffer.cpp ValidateBufferRangeOffsetAndSize), so an odd
// offset never reaches the backend through the public API - but GL 4.6 core 6.1.1
// puts no such rule on size, which is why 19 is a legal bind and 19 % 4 is not 0.
if (Gl().BackendName() != "DirectVulkan") GTEST_SKIP() << "Magma short-UBO compatibility policy";
Attach(GL_RGBA8);
const char* fragment = R"(#version 430 core
layout(std140, binding=3) uniform ShortColour { vec4 value; vec4 tail; };
layout(location=0) out vec4 color;
void main() { color = value + tail; }
)";
const GLuint program = BuildWireProgram({{GL_VERTEX_SHADER, kWireVertexIdTriangle},
{GL_FRAGMENT_SHADER, fragment}});
ASSERT_NE(program, 0u);
GLint alignment = 0;
glGetIntegerv(GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT, &alignment);
ASSERT_GT(alignment, 0);
const size_t offset = size_t(alignment);
const GLsizeiptr boundSize = 19; // 16 bytes of `value` plus three bytes of tail.x
std::vector<GLubyte> bytes(offset + 8 * sizeof(GLfloat), 0);
const GLfloat values[] = {0, 1, 0, 1, 0, 1, 1, 1};
std::memcpy(bytes.data() + offset, values, sizeof(values));
// The byte immediately past the bound range, and the reason this case is sharper than
// its four-byte sibling: rounding the read OUT to a word pulls byte 19 into the staging
// slice, and the block must still end at byte 19. If it leaks, tail.x reads 0.5f and
// the red channel comes back 127 instead of 0.
bytes[offset + 19] = 0x3F;
GLuint ubo = 0, vao = 0;
glGenBuffers(1, &ubo);
glBindBuffer(GL_UNIFORM_BUFFER, ubo);
glBufferData(GL_UNIFORM_BUFFER, GLsizeiptr(bytes.size()), bytes.data(), GL_STATIC_DRAW);
glBindBufferRange(GL_UNIFORM_BUFFER, 3, ubo, GLintptr(offset), boundSize);
ASSERT_EQ(FirstGLError(), GLenum(GL_NO_ERROR)) << "a 19-byte uniform range is a legal bind";
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
glUseProgram(program);
glViewport(0, 0, 8, 8);
glDisable(GL_DEPTH_TEST);
glClearColor(1, 0, 0, 1);
glClear(GL_COLOR_BUFFER_BIT);
glDrawArrays(GL_TRIANGLES, 0, 3);
std::array<GLubyte, 4> pixel{};
glReadPixels(4, 4, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, pixel.data());
ASSERT_EQ(FirstGLError(), GLenum(GL_NO_ERROR));
EXPECT_EQ(pixel, (std::array<GLubyte, 4>{0, 255, 0, 255}))
<< "the sub-word uniform range did not pad to the reflected block exactly";
glBindBufferBase(GL_UNIFORM_BUFFER, 3, 0);
glBindBuffer(GL_UNIFORM_BUFFER, 0);
glUseProgram(0);
glBindVertexArray(0);
glDeleteBuffers(1, &ubo);
glDeleteVertexArrays(1, &vao);
glDeleteProgram(program);
}
TEST_F(F1WireScenario, ComputeWrittenVertexAndIndexBuffersDrawAndReadBack) {
if (!Ready()) return;
Attach(GL_RGBA8);
@@ -1230,65 +992,6 @@ void main() { color = vec4(0, 1, 0, 1); }
glDeleteProgram(graphics);
}
TEST_F(F1WireScenario, UnalignedAtomicCounterRangeDeclinesAndTheSessionLives) {
if (!Ready()) return;
// The one shape in the P7 unaligned-range cluster an application can actually reach.
// GL 4.6 core 6.1.1 gives GL_ATOMIC_COUNTER_BUFFER no queryable offset alignment, so
// glBindBufferRange only enforces offset % 4 on it, while glslang lowers the counter
// block onto a storage buffer whose descriptor offset must be a multiple of
// GL_SHADER_STORAGE_BUFFER_OFFSET_ALIGNMENT (minStorageBufferOffsetAlignment: 16 on
// lavapipe, 64 on Adreno). Offset 4 is therefore a legal bind the backend cannot
// express. It used to take the session with it as a named Fatal; it is now a decline,
// and what this case pins is exactly that - the dispatch is lost, nothing else is.
if (Gl().BackendName() != "DirectVulkan") GTEST_SKIP() << "Magma descriptor-alignment decline";
GLint storageAlignment = 0;
glGetIntegerv(GL_SHADER_STORAGE_BUFFER_OFFSET_ALIGNMENT, &storageAlignment);
if (storageAlignment <= 4) GTEST_SKIP() << "this device can express a 4-byte-aligned counter range";
const char* compute = R"(#version 430 core
layout(local_size_x=1) in;
layout(binding=0, offset=0) uniform atomic_uint counter;
void main() { atomicCounterIncrement(counter); }
)";
const GLuint cs = BuildWireProgram({{GL_COMPUTE_SHADER, compute}});
ASSERT_NE(cs, 0u);
GLuint counters = 0;
glGenBuffers(1, &counters);
const std::array<GLuint, 4> seed{0x11111111u, 0x22222222u, 0x33333333u, 0x44444444u};
glBindBuffer(GL_ATOMIC_COUNTER_BUFFER, counters);
glBufferData(GL_ATOMIC_COUNTER_BUFFER, GLsizeiptr(seed.size() * sizeof(GLuint)), seed.data(), GL_DYNAMIC_COPY);
// Offset 4: a multiple of 4 and so a legal GL bind, but not a multiple of the storage
// alignment this device reports. The bind itself must NOT raise a GL error.
glBindBufferRange(GL_ATOMIC_COUNTER_BUFFER, 0, counters, GLintptr(4), GLsizeiptr(sizeof(GLuint)));
ASSERT_EQ(FirstGLError(), GLenum(GL_NO_ERROR)) << "offset 4 is a legal GL_ATOMIC_COUNTER_BUFFER range";
glUseProgram(cs);
glDispatchCompute(1, 1, 1);
glMemoryBarrier(GL_ATOMIC_COUNTER_BARRIER_BIT | GL_BUFFER_UPDATE_BARRIER_BIT);
// The session is still here - this is the whole point - and it still answers GL.
std::array<GLuint, 4> after{};
glGetBufferSubData(GL_ATOMIC_COUNTER_BUFFER, 0, GLsizeiptr(after.size() * sizeof(GLuint)), after.data());
ASSERT_EQ(FirstGLError(), GLenum(GL_NO_ERROR)) << "the declined dispatch must not poison the context";
// The dispatch was declined, so the counter is untouched; the bytes outside the bound
// range must be untouched either way. Both halves of that are worth pinning: a future
// copy-back implementation turns the first EXPECT into seed[1] + 1 and nothing else.
EXPECT_EQ(after[1], seed[1]) << "a declined counter dispatch must not have run";
EXPECT_EQ(after[0], seed[0]);
EXPECT_EQ(after[2], seed[2]);
EXPECT_EQ(after[3], seed[3]);
// And the context is still usable for ordinary work afterwards.
GLuint probe = 0;
glGenBuffers(1, &probe);
glBindBuffer(GL_ARRAY_BUFFER, probe);
glBufferData(GL_ARRAY_BUFFER, 16, seed.data(), GL_STATIC_DRAW);
EXPECT_EQ(FirstGLError(), GLenum(GL_NO_ERROR)) << "the session survived the decline";
glBindBuffer(GL_ARRAY_BUFFER, 0);
glDeleteBuffers(1, &probe);
glBindBufferBase(GL_ATOMIC_COUNTER_BUFFER, 0, 0);
glBindBuffer(GL_ATOMIC_COUNTER_BUFFER, 0);
glUseProgram(0);
glDeleteBuffers(1, &counters);
glDeleteProgram(cs);
}
TEST_F(F1WireScenario, SrgbDrawTracksFramebufferConversion) {
if (!Ready()) return;
Attach(GL_SRGB8_ALPHA8);
@@ -1566,646 +1269,4 @@ TEST_F(F1WireScenario, ColorBlitToDefaultHonorsScissorAndReversedRect) {
Gl().EndFrame();
}
// P7 wave 2-B, CONTRACT-P7 §3.2: `default-color-blit-shape@P7` RETIRES.
//
// One Fatal covered three unrelated situations. The shader pass it guarded exists for ROTATION
// and can only SAMPLE its source - sampler2D, a float result, one of two 2D view types - so a
// 3D slice or an integer attachment made it return false and the refusal fired EVEN ON A SURFACE
// WITH NO ROTATION, where the ordinary vkCmdBlitImage arm below it would have done the blit
// correctly and does handle those shapes. Identity now falls through to that arm; a rotated
// surface moves the region into an owned 2D float scratch and blits that; anything outside the
// four rotations declines by name.
//
// THE SOURCE IS A 3D TEXTURE SLICE, which is ordinary defined GL (a layer of a 3D texture is a
// legal colour attachment) and is exactly the shape the shader pass cannot sample. The same case
// runs twice on each arm: plain, taking the identity fall-through, and under
// MGITEST_MAGMA_FORCE_DEFAULT_BLIT_SCRATCH, taking the rotated arm's scratch path on an identity
// surface - where it must produce THE SAME PIXELS. That equality is what makes the scratch arm
// testable at all: every surface this lane can create is identity, and so is the Redmi pbuffer
// the cluster's evidence comes from.
//
// Red once (executed, reverted): restore MagmaWireFatal("default-color-blit-shape@P7") and both
// entries die by that name.
TEST_F(F1WireScenario, ColorBlitToDefaultFromANonSampleableSourceDegrades) {
if (!Ready()) return;
ASSERT_GE(Gl().Width(), 16);
ASSERT_GE(Gl().Height(), 16);
const int width = Gl().Width(), height = Gl().Height();
GLuint volume = 0, volumeFbo = 0;
glGenTextures(1, &volume);
glBindTexture(GL_TEXTURE_3D, volume);
glTexStorage3D(GL_TEXTURE_3D, 1, GL_RGBA8, 6, 4, 2);
glGenFramebuffers(1, &volumeFbo);
glBindFramebuffer(GL_FRAMEBUFFER, volumeFbo);
// Slice 1, not slice 0: a scratch copy that forgot the z origin would read the other slice
// and every quadrant assertion below would still be about SOME real texels.
glFramebufferTextureLayer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, volume, 0, 1);
ASSERT_EQ(glCheckFramebufferStatus(GL_FRAMEBUFFER), GLenum(GL_FRAMEBUFFER_COMPLETE));
constexpr GLfloat colors[4][4] = {{1, 0, 0, 1}, {0, 1, 0, 1}, {0, 0, 1, 1}, {1, 1, 0, 1}};
glEnable(GL_SCISSOR_TEST);
for (int quadrant = 0; quadrant < 4; ++quadrant) {
glScissor((quadrant % 2) * 3, (quadrant / 2) * 2, 3, 2);
glClearColor(colors[quadrant][0], colors[quadrant][1], colors[quadrant][2], colors[quadrant][3]);
glClear(GL_COLOR_BUFFER_BIT);
}
glDisable(GL_SCISSOR_TEST);
// The OTHER slice gets one flat colour that appears in no quadrant.
glFramebufferTextureLayer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, volume, 0, 0);
glClearColor(0, 1, 1, 1);
glClear(GL_COLOR_BUFFER_BIT);
glFramebufferTextureLayer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, volume, 0, 1);
ASSERT_EQ(FirstGLError(), GLenum(GL_NO_ERROR)) << "F1.DefaultBlitShape.setup";
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
glClearColor(1, 0, 1, 1);
glClear(GL_COLOR_BUFFER_BIT);
glBindFramebuffer(GL_READ_FRAMEBUFFER, volumeFbo);
const auto before = PeekSplitRuntime().emitSeq;
glBlitFramebuffer(0, 0, 6, 4, 0, 0, width, height, GL_COLOR_BUFFER_BIT, GL_NEAREST);
EXPECT_GT(PeekSplitRuntime().emitSeq, before) << "F1.DefaultBlitShape.wire";
glBindFramebuffer(GL_READ_FRAMEBUFFER, 0);
const std::string arm = SplitLane::MarkerValue("MGITEST_MAGMA_FORCE_DEFAULT_BLIT_SCRATCH");
EXPECT_EQ(ReadOnePixel(width / 4, height / 4), (std::array<GLubyte, 4>{255, 0, 0, 255}))
<< "F1.DefaultBlitShape bottom left (scratch arm=" << arm << ")";
EXPECT_EQ(ReadOnePixel(3 * width / 4, height / 4), (std::array<GLubyte, 4>{0, 255, 0, 255}))
<< "F1.DefaultBlitShape bottom right (scratch arm=" << arm << ")";
EXPECT_EQ(ReadOnePixel(width / 4, 3 * height / 4), (std::array<GLubyte, 4>{0, 0, 255, 255}))
<< "F1.DefaultBlitShape top left (scratch arm=" << arm << ")";
EXPECT_EQ(ReadOnePixel(3 * width / 4, 3 * height / 4), (std::array<GLubyte, 4>{255, 255, 0, 255}))
<< "F1.DefaultBlitShape top right (scratch arm=" << arm << ")";
EXPECT_EQ(FirstGLError(), GLenum(GL_NO_ERROR)) << "F1.DefaultBlitShape.error";
glBindFramebuffer(GL_FRAMEBUFFER, fbo);
glDeleteFramebuffers(1, &volumeFbo);
glBindTexture(GL_TEXTURE_3D, 0);
glDeleteTextures(1, &volume);
glBindTexture(GL_TEXTURE_2D, texture);
Gl().EndFrame();
}
namespace {
// An 8x4 RGBA8 colour renderbuffer at `samples`, bottom half red and top half green in GL row
// order. TWO HALVES AND NOT ONE COLOUR, for the reason the shader-mip case gives: a pass that
// loses GL's row order averages a flat fill back to the same number everywhere and a
// single-colour assertion calls that correct. Returns false when this driver cannot host the
// attachment, which is a skip and not a failure.
bool MakeMultisampleHalvesFbo(int samples, GLuint& fbo, GLuint& renderbuffer) {
glGenFramebuffers(1, &fbo);
glBindFramebuffer(GL_FRAMEBUFFER, fbo);
glGenRenderbuffers(1, &renderbuffer);
glBindRenderbuffer(GL_RENDERBUFFER, renderbuffer);
glRenderbufferStorageMultisample(GL_RENDERBUFFER, samples, GL_RGBA8, 8, 4);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, renderbuffer);
if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GLenum(GL_FRAMEBUFFER_COMPLETE)) return false;
while (glGetError() != GLenum(GL_NO_ERROR)) {}
glDisable(GL_SCISSOR_TEST);
glEnable(GL_SCISSOR_TEST);
glScissor(0, 0, 8, 2);
glClearColor(1, 0, 0, 1);
glClear(GL_COLOR_BUFFER_BIT);
glScissor(0, 2, 8, 2);
glClearColor(0, 1, 0, 1);
glClear(GL_COLOR_BUFFER_BIT);
glDisable(GL_SCISSOR_TEST);
return true;
}
// A single-sample RGBA8 destination of the given size, cleared to a colour that appears in no
// assertion below - so "the blit did nothing" and "the blit landed the wrong band" read
// differently from each other.
void MakeSingleSampleTarget(int width, int height, const GLfloat (&clear)[4], GLuint& fbo, GLuint& tex) {
glGenTextures(1, &tex);
glBindTexture(GL_TEXTURE_2D, tex);
glTexStorage2D(GL_TEXTURE_2D, 1, GL_RGBA8, width, height);
glGenFramebuffers(1, &fbo);
glBindFramebuffer(GL_FRAMEBUFFER, fbo);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, tex, 0);
glClearColor(clear[0], clear[1], clear[2], clear[3]);
glClear(GL_COLOR_BUFFER_BIT);
}
} // namespace
// P7 wave 2-B2, CONTRACT-P7 §3.2: `multisample-blit-shape@P7` RETIRES.
//
// vkCmdResolveImage carries ONE extent and one offset per side. It can neither scale nor flip,
// so the wire arm refused every multisample colour blit whose destination rectangle was a
// different size from its source - which glBlitFramebuffer names, and which the MONOLITH arm
// already reaches by the route this package gives the wire arm (VulkanRenderer.cpp's
// `regionWasTransformed` branch: resolve into a scratch at raw offsets, then blit the scratch).
// The scratch was already here for the flip; the two size equalities were the only thing
// keeping the scale out.
//
// THE SCALE AND THE FLIP IN ONE CASE, over the same source, because they fail differently: a
// blit that dropped the scale lands a 8x4 band in a 4x2 attachment (and the driver refuses the
// command), while one that dropped the flip returns the right two colours in the wrong order.
// The second blit's expectation is the first's, rows swapped, so neither can pass the other's
// assertion.
//
// Red once (executed, reverted): restore the two `width != |dx1-dx0|` clauses in
// WireFramebuffer.inc's colour resolve arm and both blits die as
// Fatal{UnmigratedVerb, "Magma:multisample-resolve-region"}.
TEST_F(F1WireScenario, MultisampleColorBlitScalesAndFlipsThroughTheResolveScratch) {
if (!Ready()) return;
GLuint msFbo = 0, msRenderbuffer = 0;
if (!MakeMultisampleHalvesFbo(4, msFbo, msRenderbuffer)) {
glBindFramebuffer(GL_FRAMEBUFFER, fbo);
glDeleteFramebuffers(1, &msFbo);
glDeleteRenderbuffers(1, &msRenderbuffer);
GTEST_SKIP() << "this driver cannot host a 4x multisample RGBA8 renderbuffer";
}
ASSERT_EQ(FirstGLError(), GLenum(GL_NO_ERROR)) << "F1.MsBlitShape.setup";
// Half the source in each axis: every destination texel is the resolve of a 2x2 source box
// that lies wholly inside ONE half, so the boundary never falls inside a destination texel
// and the two colours cannot mix.
constexpr GLfloat kBlue[4]{0, 0, 1, 1};
GLuint dstFbo = 0, dstTexture = 0;
MakeSingleSampleTarget(4, 2, kBlue, dstFbo, dstTexture);
ASSERT_EQ(glCheckFramebufferStatus(GL_FRAMEBUFFER), GLenum(GL_FRAMEBUFFER_COMPLETE));
ASSERT_EQ(FirstGLError(), GLenum(GL_NO_ERROR)) << "F1.MsBlitShape.target";
constexpr std::array<GLubyte, 4> kRed{255, 0, 0, 255};
constexpr std::array<GLubyte, 4> kGreen{0, 255, 0, 255};
glBindFramebuffer(GL_READ_FRAMEBUFFER, msFbo);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, dstFbo);
glDisable(GL_SCISSOR_TEST);
const auto before = PeekSplitRuntime().emitSeq;
glBlitFramebuffer(0, 0, 8, 4, 0, 0, 4, 2, GL_COLOR_BUFFER_BIT, GL_NEAREST);
EXPECT_GT(PeekSplitRuntime().emitSeq, before) << "F1.MsBlitShape.wire";
EXPECT_EQ(FirstGLError(), GLenum(GL_NO_ERROR)) << "F1.MsBlitShape.scaled.error";
glBindFramebuffer(GL_READ_FRAMEBUFFER, dstFbo);
for (int x = 0; x < 4; ++x) {
EXPECT_EQ(ReadOnePixel(x, 0), kRed) << "F1.MsBlitShape scaled bottom row, x=" << x;
EXPECT_EQ(ReadOnePixel(x, 1), kGreen) << "F1.MsBlitShape scaled top row, x=" << x;
}
// The same source, the same destination size, with the destination rectangle inverted on
// Y. The scratch holds the resolved band at its own origin either way; only the second leg
// sees the inversion, which is what vkCmdBlitImage's reversed offsets express.
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, dstFbo);
glClearColor(kBlue[0], kBlue[1], kBlue[2], kBlue[3]);
glClear(GL_COLOR_BUFFER_BIT);
glBindFramebuffer(GL_READ_FRAMEBUFFER, msFbo);
glBlitFramebuffer(0, 0, 8, 4, 0, 2, 4, 0, GL_COLOR_BUFFER_BIT, GL_NEAREST);
EXPECT_EQ(FirstGLError(), GLenum(GL_NO_ERROR)) << "F1.MsBlitShape.flipped.error";
glBindFramebuffer(GL_READ_FRAMEBUFFER, dstFbo);
for (int x = 0; x < 4; ++x) {
EXPECT_EQ(ReadOnePixel(x, 0), kGreen) << "F1.MsBlitShape flipped bottom row, x=" << x;
EXPECT_EQ(ReadOnePixel(x, 1), kRed) << "F1.MsBlitShape flipped top row, x=" << x;
}
glBindFramebuffer(GL_FRAMEBUFFER, fbo);
glDeleteFramebuffers(1, &dstFbo);
glDeleteTextures(1, &dstTexture);
glDeleteFramebuffers(1, &msFbo);
glDeleteRenderbuffers(1, &msRenderbuffer);
glBindTexture(GL_TEXTURE_2D, texture);
Gl().EndFrame();
}
// The surviving half of `multisample-blit-shape@P7`, and it is a DECLINE (rule I (a)).
//
// A MULTISAMPLE DESTINATION is the other side of the same guard and has no arm at all:
// vkCmdCopyImage is the only command that writes a multisampled image, it takes one extent, and
// GL 4.6 core 18.3.1 makes a blit whose rectangles differ in size INVALID_OPERATION when either
// framebuffer is multisampled - so there is no picture to get right, only a shape that used to
// end the session. What this case pins is that it no longer does, and that the destination is
// exactly as the clear left it.
//
// THE DESTINATION IS READ THROUGH A RESOLVE, because glReadPixels on a multisampled framebuffer
// is INVALID_OPERATION: the 1:1 resolve into a single-sample attachment is the retired arm
// above, so this case also proves the decline did not disturb the arm next to it.
//
// Red once (executed, reverted): restore MagmaWireFatal("multisample-blit-shape@P7") and this
// case dies as Fatal{UnmigratedVerb, "Magma:multisample-blit-shape@P7"}.
TEST_F(F1WireScenario, MultisampleBlitOntoAMultisampleDestinationDeclinesAndKeepsTheSession) {
if (!Ready()) return;
// Magma only (see GenerateMipmapDepthStencilDeclinesAndKeepsTheSession). Espryt on the split
// arm leaves the destination untouched but no GL_INVALID_OPERATION reaches the client, which
// GL 4.6 core 18.3.1 asks for here - an Espryt debt of the same class as
// DepthStencilReadbackMatrixScenario's scaled-resolve gate, not this decline's to pin.
if (Gl().BackendName() != "DirectVulkan")
GTEST_SKIP() << "Magma wire-arm decline (CONTRACT-P7 3.2, multisample-blit-shape): Espryt ("
<< Gl().BackendName()
<< ") writes nothing for a scaled blit onto a multisample destination but "
"records no GL_INVALID_OPERATION - a P3b/P4b debt, not this decline";
GLuint msFbo = 0, msRenderbuffer = 0;
glGenFramebuffers(1, &msFbo);
glBindFramebuffer(GL_FRAMEBUFFER, msFbo);
glGenRenderbuffers(1, &msRenderbuffer);
glBindRenderbuffer(GL_RENDERBUFFER, msRenderbuffer);
glRenderbufferStorageMultisample(GL_RENDERBUFFER, 4, GL_RGBA8, 4, 2);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, msRenderbuffer);
if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GLenum(GL_FRAMEBUFFER_COMPLETE)) {
glBindFramebuffer(GL_FRAMEBUFFER, fbo);
glDeleteFramebuffers(1, &msFbo);
glDeleteRenderbuffers(1, &msRenderbuffer);
GTEST_SKIP() << "this driver cannot host a 4x multisample RGBA8 renderbuffer";
}
while (glGetError() != GLenum(GL_NO_ERROR)) {}
glDisable(GL_SCISSOR_TEST);
glClearColor(1, 0, 1, 1); // magenta: the colour the declined blit must leave behind
glClear(GL_COLOR_BUFFER_BIT);
ASSERT_EQ(FirstGLError(), GLenum(GL_NO_ERROR)) << "F1.MsBlitDecline.setup";
// A single-sample 8x4 source, flat yellow, so a blit that ran at all is visible.
constexpr GLfloat kYellow[4]{1, 1, 0, 1};
GLuint srcFbo = 0, srcTexture = 0;
MakeSingleSampleTarget(8, 4, kYellow, srcFbo, srcTexture);
ASSERT_EQ(glCheckFramebufferStatus(GL_FRAMEBUFFER), GLenum(GL_FRAMEBUFFER_COMPLETE));
ASSERT_EQ(FirstGLError(), GLenum(GL_NO_ERROR)) << "F1.MsBlitDecline.source";
glBindFramebuffer(GL_READ_FRAMEBUFFER, srcFbo);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, msFbo);
const auto before = PeekSplitRuntime().emitSeq;
glBlitFramebuffer(0, 0, 8, 4, 0, 0, 4, 2, GL_COLOR_BUFFER_BIT, GL_NEAREST);
EXPECT_GT(PeekSplitRuntime().emitSeq, before) << "F1.MsBlitDecline.wire";
// THE glFinish IS LOAD-BEARING, and it is what the first run of this case measured: the
// decline records its error where the blit is PERFORMED - the server's apply thread - and
// that error reaches this client's queue with a later reply, not with the blit call. Without
// the round trip the check below reads GL_NO_ERROR and the INVALID_OPERATION surfaces at
// whatever the next synchronising call happens to be, which is how it first showed up:
// attached to the resolve twenty lines down, a call that is not wrong about anything.
glFinish();
EXPECT_EQ(FirstGLError(), GLenum(GL_INVALID_OPERATION))
<< "F1.MsBlitDecline: the decline must record the error GL names for the shape";
// Resolve the multisample destination 1:1 into a single-sample attachment and read THAT:
// the round trip is also the proof that the session is still answering.
constexpr GLfloat kBlue[4]{0, 0, 1, 1};
GLuint readFbo = 0, readTexture = 0;
MakeSingleSampleTarget(4, 2, kBlue, readFbo, readTexture);
ASSERT_EQ(glCheckFramebufferStatus(GL_FRAMEBUFFER), GLenum(GL_FRAMEBUFFER_COMPLETE));
glBindFramebuffer(GL_READ_FRAMEBUFFER, msFbo);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, readFbo);
glBlitFramebuffer(0, 0, 4, 2, 0, 0, 4, 2, GL_COLOR_BUFFER_BIT, GL_NEAREST);
EXPECT_EQ(FirstGLError(), GLenum(GL_NO_ERROR)) << "F1.MsBlitDecline.resolve";
glBindFramebuffer(GL_READ_FRAMEBUFFER, readFbo);
constexpr std::array<GLubyte, 4> kMagenta{255, 0, 255, 255};
for (int y = 0; y < 2; ++y)
for (int x = 0; x < 4; ++x)
EXPECT_EQ(ReadOnePixel(x, y), kMagenta)
<< "F1.MsBlitDecline: the declined blit wrote (" << x << "," << y << ")";
EXPECT_EQ(FirstGLError(), GLenum(GL_NO_ERROR)) << "F1.MsBlitDecline: the session survived";
glBindFramebuffer(GL_FRAMEBUFFER, fbo);
glDeleteFramebuffers(1, &readFbo);
glDeleteTextures(1, &readTexture);
glDeleteFramebuffers(1, &srcFbo);
glDeleteTextures(1, &srcTexture);
glDeleteFramebuffers(1, &msFbo);
glDeleteRenderbuffers(1, &msRenderbuffer);
glBindTexture(GL_TEXTURE_2D, texture);
Gl().EndFrame();
}
// P7 wave 2-B2, CONTRACT-P7 §3.2: the surviving half of `multisample-blit-aspect@P7`.
//
// The half WITH an arm is ResolveWireDepthStencil's: a multisample depth or stencil source now
// reaches a single-sample destination on every device - through VK_KHR_depth_stencil_resolve
// where it exists, through WireMultisampleResolve.inc's baked pass where it does not - and the
// two MsResolve entries on each arm are its reading. This is the half with none.
//
// ONE SAMPLE INTO FOUR, with rectangles that MATCH so the shape decline next door is not what
// fires. Vulkan has no command for it: vkCmdResolveImage only ever writes a single-sample
// destination, vkCmdBlitImage refuses a multisampled side outright, and vkCmdCopyImage needs
// the two counts to be equal. GL 4.6 core 18.3.1 calls this sample replication and the wire arm
// declines it by name rather than ending the session over it.
//
// Red once (executed, reverted): restore MagmaWireFatal("multisample-blit-aspect@P7") and this
// case dies as Fatal{UnmigratedVerb, "Magma:multisample-blit-aspect@P7"}.
TEST_F(F1WireScenario, MultisampleBlitFromASingleSampleSourceDeclinesAndKeepsTheSession) {
if (!Ready()) return;
// Magma only (see GenerateMipmapDepthStencilDeclinesAndKeepsTheSession). The decline itself
// is a recorded Magma debt (CONTRACT-P7 §12: a same-rectangle 1 -> N blit is legal sample
// replication in GL 4.6 core 18.3.1); Espryt on the split arm neither replicates nor
// records an error, which is neither answer this case can pin.
if (Gl().BackendName() != "DirectVulkan")
GTEST_SKIP() << "Magma wire-arm decline (CONTRACT-P7 3.2, multisample-blit-aspect): Espryt ("
<< Gl().BackendName()
<< ") writes nothing for a single-sample to multisample blit and records no "
"GL error - a P3b/P4b debt, not this decline";
GLuint msFbo = 0, msRenderbuffer = 0;
glGenFramebuffers(1, &msFbo);
glBindFramebuffer(GL_FRAMEBUFFER, msFbo);
glGenRenderbuffers(1, &msRenderbuffer);
glBindRenderbuffer(GL_RENDERBUFFER, msRenderbuffer);
glRenderbufferStorageMultisample(GL_RENDERBUFFER, 4, GL_RGBA8, 4, 2);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, msRenderbuffer);
if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GLenum(GL_FRAMEBUFFER_COMPLETE)) {
glBindFramebuffer(GL_FRAMEBUFFER, fbo);
glDeleteFramebuffers(1, &msFbo);
glDeleteRenderbuffers(1, &msRenderbuffer);
GTEST_SKIP() << "this driver cannot host a 4x multisample RGBA8 renderbuffer";
}
while (glGetError() != GLenum(GL_NO_ERROR)) {}
glDisable(GL_SCISSOR_TEST);
glClearColor(1, 0, 1, 1); // magenta: the colour the declined blit must leave behind
glClear(GL_COLOR_BUFFER_BIT);
ASSERT_EQ(FirstGLError(), GLenum(GL_NO_ERROR)) << "F1.MsAspectDecline.setup";
constexpr GLfloat kYellow[4]{1, 1, 0, 1};
GLuint srcFbo = 0, srcTexture = 0;
MakeSingleSampleTarget(4, 2, kYellow, srcFbo, srcTexture);
ASSERT_EQ(glCheckFramebufferStatus(GL_FRAMEBUFFER), GLenum(GL_FRAMEBUFFER_COMPLETE));
ASSERT_EQ(FirstGLError(), GLenum(GL_NO_ERROR)) << "F1.MsAspectDecline.source";
glBindFramebuffer(GL_READ_FRAMEBUFFER, srcFbo);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, msFbo);
const auto before = PeekSplitRuntime().emitSeq;
glBlitFramebuffer(0, 0, 4, 2, 0, 0, 4, 2, GL_COLOR_BUFFER_BIT, GL_NEAREST);
EXPECT_GT(PeekSplitRuntime().emitSeq, before) << "F1.MsAspectDecline.wire";
glFinish(); // the decline's error rides a later reply - see the shape case next door
EXPECT_EQ(FirstGLError(), GLenum(GL_INVALID_OPERATION))
<< "F1.MsAspectDecline: the decline must record the error GL names for the shape";
constexpr GLfloat kBlue[4]{0, 0, 1, 1};
GLuint readFbo = 0, readTexture = 0;
MakeSingleSampleTarget(4, 2, kBlue, readFbo, readTexture);
ASSERT_EQ(glCheckFramebufferStatus(GL_FRAMEBUFFER), GLenum(GL_FRAMEBUFFER_COMPLETE));
glBindFramebuffer(GL_READ_FRAMEBUFFER, msFbo);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, readFbo);
glBlitFramebuffer(0, 0, 4, 2, 0, 0, 4, 2, GL_COLOR_BUFFER_BIT, GL_NEAREST);
EXPECT_EQ(FirstGLError(), GLenum(GL_NO_ERROR)) << "F1.MsAspectDecline.resolve";
glBindFramebuffer(GL_READ_FRAMEBUFFER, readFbo);
constexpr std::array<GLubyte, 4> kMagenta{255, 0, 255, 255};
for (int y = 0; y < 2; ++y)
for (int x = 0; x < 4; ++x)
EXPECT_EQ(ReadOnePixel(x, y), kMagenta)
<< "F1.MsAspectDecline: the declined blit wrote (" << x << "," << y << ")";
EXPECT_EQ(FirstGLError(), GLenum(GL_NO_ERROR)) << "F1.MsAspectDecline: the session survived";
glBindFramebuffer(GL_FRAMEBUFFER, fbo);
glDeleteFramebuffers(1, &readFbo);
glDeleteTextures(1, &readTexture);
glDeleteFramebuffers(1, &srcFbo);
glDeleteTextures(1, &srcTexture);
glDeleteFramebuffers(1, &msFbo);
glDeleteRenderbuffers(1, &msRenderbuffer);
glBindTexture(GL_TEXTURE_2D, texture);
Gl().EndFrame();
}
namespace {
// One 8x8x2 RGBA8 array texture with two levels, filled so that EVERY subresource this pair
// of cases touches is distinguishable from every other one. A flat fill would let a copy that
// went to the wrong level, the wrong layer or nowhere at all read as correct.
// level 0 layer 0: four quadrants (GL row order: red/green on the bottom, blue/yellow up)
// level 0 layer 1: magenta
// level 1 layer 0: cyan level 1 layer 1: white
constexpr std::array<GLubyte, 4> kInPlaceRed{255, 0, 0, 255};
constexpr std::array<GLubyte, 4> kInPlaceGreen{0, 255, 0, 255};
constexpr std::array<GLubyte, 4> kInPlaceBlue{0, 0, 255, 255};
constexpr std::array<GLubyte, 4> kInPlaceYellow{255, 255, 0, 255};
constexpr std::array<GLubyte, 4> kInPlaceMagenta{255, 0, 255, 255};
constexpr std::array<GLubyte, 4> kInPlaceCyan{0, 255, 255, 255};
constexpr std::array<GLubyte, 4> kInPlaceWhite{255, 255, 255, 255};
std::array<GLubyte, 4> InPlaceQuadrant(int x, int y) {
if (y < 4) return x < 4 ? kInPlaceRed : kInPlaceGreen;
return x < 4 ? kInPlaceBlue : kInPlaceYellow;
}
GLuint MakeInPlaceCopyTexture() {
GLuint name = 0;
glGenTextures(1, &name);
glBindTexture(GL_TEXTURE_2D_ARRAY, name);
glTexStorage3D(GL_TEXTURE_2D_ARRAY, 2, GL_RGBA8, 8, 8, 2);
std::vector<GLubyte> level0(8 * 8 * 2 * 4);
for (int layer = 0; layer < 2; ++layer)
for (int y = 0; y < 8; ++y)
for (int x = 0; x < 8; ++x) {
const auto colour = layer == 0 ? InPlaceQuadrant(x, y) : kInPlaceMagenta;
const size_t at = (static_cast<size_t>(layer) * 64 + y * 8 + x) * 4;
std::copy(colour.begin(), colour.end(), level0.begin() + at);
}
glTexSubImage3D(GL_TEXTURE_2D_ARRAY, 0, 0, 0, 0, 8, 8, 2, GL_RGBA, GL_UNSIGNED_BYTE, level0.data());
std::vector<GLubyte> level1(4 * 4 * 2 * 4);
for (int layer = 0; layer < 2; ++layer)
for (int at = 0; at < 16; ++at) {
const auto colour = layer == 0 ? kInPlaceCyan : kInPlaceWhite;
std::copy(colour.begin(), colour.end(),
level1.begin() + (static_cast<size_t>(layer) * 16 + at) * 4);
}
glTexSubImage3D(GL_TEXTURE_2D_ARRAY, 1, 0, 0, 0, 4, 4, 2, GL_RGBA, GL_UNSIGNED_BYTE, level1.data());
return name;
}
// (level, side) -> the whole level, every layer, as glGetTexImage hands it back.
std::vector<GLubyte> ReadInPlaceLevel(GLint level, int side) {
std::vector<GLubyte> pixels(static_cast<size_t>(side) * side * 2 * 4, 17);
glGetTexImage(GL_TEXTURE_2D_ARRAY, level, GL_RGBA, GL_UNSIGNED_BYTE, pixels.data());
return pixels;
}
::testing::AssertionResult InPlaceTexelIs(const std::vector<GLubyte>& pixels, int side, int layer,
int x, int y, const std::array<GLubyte, 4>& expected) {
const size_t at = ((static_cast<size_t>(layer) * side * side) + static_cast<size_t>(y) * side + x) * 4;
if (at + 4 > pixels.size()) return ::testing::AssertionFailure() << "texel out of range";
for (int channel = 0; channel < 4; ++channel)
if (pixels[at + channel] != expected[channel])
return ::testing::AssertionFailure()
<< "layer " << layer << " (" << x << "," << y << ") channel " << channel
<< " is " << int(pixels[at + channel]) << ", expected " << int(expected[channel]);
return ::testing::AssertionSuccess();
}
} // namespace
// P7 wave 2-B, CONTRACT-P7 §3.2: `copy-image-in-place@P7` RETIRES.
//
// glCopyImageSubData between two subresources of ONE texture is ordinary, defined GL (4.6 core
// 18.3.2 even spells out that a texture and a view of it are two objects over one image and may
// be copied between). The wire arm took the session down for it, because the TRANSFER_SRC /
// TRANSFER_DST pair below it cannot describe one image: both endpoints share one tracked
// VkImageLayout and the second transition undoes the first. GENERAL can describe it.
//
// The monolith arm still DECLINES this shape outright, so this case is split-only in the
// strongest sense - there is no monolith reading of it to compare against, and that asymmetry
// is deliberate rather than an oversight (§3.2 asks the wire arm to perform the copy).
//
// Red once (executed, reverted): restore MagmaWireFatal("copy-image-in-place@P7") and this case
// dies by that name.
TEST_F(F1WireScenario, CopyImageInPlaceAcrossLevelsAndLayers) {
if (!Ready()) return;
const GLuint array = MakeInPlaceCopyTexture();
ASSERT_EQ(FirstGLError(), GLenum(GL_NO_ERROR)) << "F1.CopyInPlace.setup";
// LEVEL 0 -> LEVEL 1, same layer: the destination level is a different subresource of the
// same image, so one GENERAL transition has to cover both of them.
const auto before = PeekSplitRuntime().emitSeq;
glCopyImageSubData(array, GL_TEXTURE_2D_ARRAY, 0, 0, 0, 0,
array, GL_TEXTURE_2D_ARRAY, 1, 0, 0, 0, 4, 4, 1);
ASSERT_GT(PeekSplitRuntime().emitSeq, before) << "F1.CopyInPlace.wire";
ASSERT_EQ(FirstGLError(), GLenum(GL_NO_ERROR)) << "F1.CopyInPlace.levelCopy.error";
{
const auto level1 = ReadInPlaceLevel(1, 4);
ASSERT_EQ(FirstGLError(), GLenum(GL_NO_ERROR)) << "F1.CopyInPlace.levelCopy.readback";
for (int y = 0; y < 4; ++y)
for (int x = 0; x < 4; ++x) {
// The source rectangle is level 0's bottom-left quadrant, which is all red.
EXPECT_TRUE(InPlaceTexelIs(level1, 4, 0, x, y, kInPlaceRed))
<< "F1.CopyInPlace.level1.layer0";
EXPECT_TRUE(InPlaceTexelIs(level1, 4, 1, x, y, kInPlaceWhite))
<< "F1.CopyInPlace.level1.layer1 must not be touched";
}
}
// LAYER 0 -> LAYER 1 at level 0: the same level, disjoint slices. Defined GL, and the
// overlap decline must NOT catch it.
glCopyImageSubData(array, GL_TEXTURE_2D_ARRAY, 0, 0, 0, 0,
array, GL_TEXTURE_2D_ARRAY, 0, 0, 0, 1, 8, 8, 1);
ASSERT_EQ(FirstGLError(), GLenum(GL_NO_ERROR)) << "F1.CopyInPlace.layerCopy.error";
{
const auto level0 = ReadInPlaceLevel(0, 8);
ASSERT_EQ(FirstGLError(), GLenum(GL_NO_ERROR)) << "F1.CopyInPlace.layerCopy.readback";
for (int y = 0; y < 8; ++y)
for (int x = 0; x < 8; ++x) {
EXPECT_TRUE(InPlaceTexelIs(level0, 8, 0, x, y, InPlaceQuadrant(x, y)))
<< "F1.CopyInPlace.level0.layer0 is the source and must be unchanged";
EXPECT_TRUE(InPlaceTexelIs(level0, 8, 1, x, y, InPlaceQuadrant(x, y)))
<< "F1.CopyInPlace.level0.layer1 must carry the source's quadrants";
}
}
glBindTexture(GL_TEXTURE_2D_ARRAY, 0);
glDeleteTextures(1, &array);
glBindTexture(GL_TEXTURE_2D, texture);
}
// The one in-place shape that stays a DECLINE (§3.2): same image, same level, same layer,
// overlapping rectangles. GL 4.6 core 18.3.2 leaves that undefined, and GENERAL makes the
// command legal to RECORD rather than meaningful to execute - vkCmdCopyImage orders nothing
// between its own reads and writes inside one region. The case pins that nothing is recorded:
// no GL error, and the level still holds exactly what it held.
TEST_F(F1WireScenario, CopyImageInPlaceOverlapDeclinesAndLeavesTheLevelAlone) {
if (!Ready()) return;
// Magma only (see GenerateMipmapDepthStencilDeclinesAndKeepsTheSession). GL leaves this copy
// undefined and Espryt performs it; only the Magma wire arm promises to record nothing.
if (Gl().BackendName() != "DirectVulkan")
GTEST_SKIP() << "Magma wire-arm decline (CONTRACT-P7 3.2, copy-image-in-place): GL 4.6 core "
"18.3.2 leaves an overlapping same-subresource copy undefined and Espryt ("
<< Gl().BackendName() << ") performs it";
const GLuint array = MakeInPlaceCopyTexture();
ASSERT_EQ(FirstGLError(), GLenum(GL_NO_ERROR)) << "F1.CopyInPlaceOverlap.setup";
// (0,0)-(4,4) onto (2,2): four of the sixteen texels are in both rectangles.
glCopyImageSubData(array, GL_TEXTURE_2D_ARRAY, 0, 0, 0, 0,
array, GL_TEXTURE_2D_ARRAY, 0, 2, 2, 0, 4, 4, 1);
EXPECT_EQ(FirstGLError(), GLenum(GL_NO_ERROR)) << "F1.CopyInPlaceOverlap.error";
const auto level0 = ReadInPlaceLevel(0, 8);
ASSERT_EQ(FirstGLError(), GLenum(GL_NO_ERROR)) << "F1.CopyInPlaceOverlap.readback";
for (int y = 0; y < 8; ++y)
for (int x = 0; x < 8; ++x)
EXPECT_TRUE(InPlaceTexelIs(level0, 8, 0, x, y, InPlaceQuadrant(x, y)))
<< "F1.CopyInPlaceOverlap.level0 must be untouched by a declined copy";
glBindTexture(GL_TEXTURE_2D_ARRAY, 0);
glDeleteTextures(1, &array);
glBindTexture(GL_TEXTURE_2D, texture);
}
// ---- P7 wave 2 package B3, EXIT GATE 3: a streamed glBufferSubData -> draw pair is ordered --
//
// THE SHAPE OF THE OpenRA DEVICE DIVERGENCE, reduced to four quads. The application writes a
// batch of vertices over the SAME range of ONE dynamic buffer and immediately draws it, then
// writes the next batch over the same range and draws that, and so on - OpenRA does this ~24
// times per frame into GL buffer 1, and the picture that reached the Redmi was missing exactly
// the quads of one of those batches with the terrain under them intact.
//
// The server may answer such a write in two shapes: an ordered vkCmdCopyBuffer, or an immediate
// host memcpy when it believes the GPU is finished with the bytes. Believing that wrongly is
// silent and produces no log line and no GL error - the draw still executes, it just reads
// somebody else's vertices. So the case cannot assert "no error"; it has to assert the pixels.
//
// Registered TWICE per arm. The plain entry is a regression gate on every driver. The
// `StaleSerial.` entry (split and spawn only - the tcp arm's server never sees an entry's
// environment) carries MGITEST_MAGMA_FORCE_STALE_BUFFER_SERIAL=1, which forces the serial half
// of the busy predicate to answer "idle" - the state the unsound completed-serial floor put the
// wire arm into on the device. With the serial half forced to lie, only the submission-fence
// half can still order the copy, so the entry pins that DEFENCE term. The guarantee is the
// floor (VulkanRenderer::OnSubmitsCompletedUpTo), which the knob bypasses; its lane is the
// OpenRA split retrace's "MGWIRE-FLOOR unsound-serial-complete" red condition.
TEST_F(F1WireScenario, StreamedBufferSubDataBeforeEachDrawIsOrdered) {
if (!Ready()) return;
constexpr int kSize = 8, kBatches = 4, kColumn = kSize / kBatches;
Attach(GL_RGBA8);
const GLuint program = BuildWireProgram({
{GL_VERTEX_SHADER, R"(#version 430 core
layout(location = 0) in vec2 aPos;
layout(location = 1) in vec4 aColor;
out vec4 vColor;
void main() { gl_Position = vec4(aPos, 0.0, 1.0); vColor = aColor; }
)"},
{GL_FRAGMENT_SHADER, R"(#version 430 core
in vec4 vColor;
out vec4 fragColor;
void main() { fragColor = vColor; }
)"}});
ASSERT_NE(program, 0u);
// One vertical bar per batch, each in its own two-pixel column and its own colour, so a
// draw that read another batch's bytes lands in the wrong column AND the wrong colour.
constexpr GLfloat kColors[kBatches][4] = {{1, 0, 0, 1}, {0, 1, 0, 1}, {0, 0, 1, 1}, {1, 1, 0, 1}};
const auto batchVertices = [&](int batch) {
const GLfloat x0 = -1.0f + static_cast<GLfloat>(batch) * 0.5f;
const GLfloat x1 = x0 + 0.5f;
const GLfloat* c = kColors[batch];
return std::array<GLfloat, 36>{
x0, -1, c[0], c[1], c[2], c[3], x1, -1, c[0], c[1], c[2], c[3], x1, 1, c[0], c[1], c[2], c[3],
x0, -1, c[0], c[1], c[2], c[3], x1, 1, c[0], c[1], c[2], c[3], x0, 1, c[0], c[1], c[2], c[3]};
};
GLuint vao = 0, vbo = 0;
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
glGenBuffers(1, &vbo);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
// GL_DYNAMIC_DRAW and no orphaning: OpenRA's buffer 1 exactly.
glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * 36, nullptr, GL_DYNAMIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), reinterpret_cast<const void*>(0));
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat),
reinterpret_cast<const void*>(2 * sizeof(GLfloat)));
glUseProgram(program);
glViewport(0, 0, kSize, kSize);
glDisable(GL_DEPTH_TEST);
glDisable(GL_BLEND);
glClearColor(0, 0, 0, 1);
glClear(GL_COLOR_BUFFER_BIT);
for (int batch = 0; batch < kBatches; ++batch) {
const auto vertices = batchVertices(batch);
glBufferSubData(GL_ARRAY_BUFFER, 0, static_cast<GLsizeiptr>(sizeof(vertices)), vertices.data());
glDrawArrays(GL_TRIANGLES, 0, 6);
}
ASSERT_EQ(FirstGLError(), GLenum(GL_NO_ERROR)) << "F1.StreamedSubData.draw";
std::vector<GLubyte> pixels(static_cast<size_t>(kSize) * kSize * 4, 0);
glReadPixels(0, 0, kSize, kSize, GL_RGBA, GL_UNSIGNED_BYTE, pixels.data());
ASSERT_EQ(FirstGLError(), GLenum(GL_NO_ERROR)) << "F1.StreamedSubData.readback";
for (int batch = 0; batch < kBatches; ++batch) {
const GLubyte* want = nullptr;
const GLubyte expected[4] = {static_cast<GLubyte>(kColors[batch][0] * 255.0f),
static_cast<GLubyte>(kColors[batch][1] * 255.0f),
static_cast<GLubyte>(kColors[batch][2] * 255.0f),
static_cast<GLubyte>(kColors[batch][3] * 255.0f)};
want = expected;
for (int dx = 0; dx < kColumn; ++dx) {
const int x = batch * kColumn + dx;
const GLubyte* got = pixels.data() + (static_cast<size_t>(kSize / 2) * kSize + x) * 4;
EXPECT_EQ(got[0], want[0]) << "F1.StreamedSubData: batch " << batch << " column " << x
<< " lost its own vertices (r)";
EXPECT_EQ(got[1], want[1]) << "F1.StreamedSubData: batch " << batch << " column " << x
<< " lost its own vertices (g)";
EXPECT_EQ(got[2], want[2]) << "F1.StreamedSubData: batch " << batch << " column " << x
<< " lost its own vertices (b)";
}
}
glBindBuffer(GL_ARRAY_BUFFER, 0);
glDeleteBuffers(1, &vbo);
glBindVertexArray(0);
glDeleteVertexArrays(1, &vao);
glUseProgram(0);
glDeleteProgram(program);
}
} // namespace MGITest
@@ -1394,21 +1394,13 @@ void main() { oColor = texture(uTex, vUv); }
// back? Until C-1 the answer under DirectVulkan was NO. The mint is the client's
// (MGPipeVertexInputEmitter::EmitVertexElements acquires a VertexElementsCso slot at
// every validate point with a VAO bound) and the only free in the tree was Espryt's
// StateObjectDeathOps consumer - so under Magma, which installed none
// StateObjectDeathOps consumer - so under Magma, which installs none deliberately
// (MagmaPipeArms.h: "an allocator here would grow by one SlotState plus one map node
// per object EVER created, for the life of the process, on a platform with an LMK"),
// every VAO ever created held its slot and its ~1.3 KB applier record until the process
// died, on the shipped 0x1ff mask, until create_vertex_elements began tripping
// Fatal{ProtocolCorruption} permanently at kMGPipeMaxVertexElementsSlots.
//
// P7 WAVE 2 PACKAGE C DOES NOT RETIRE THIS CASE, and the reason is the whole point of
// C-1. Magma now installs a StateObjectDeathOps table (CONTRACT-P7 §5.5), but that
// table's one arm EMITS the `object_death` record so the SERVER drops its twin - it
// frees no client slot and could not: the free is the client's own, from the frontend
// destructor, on the client thread. So this case still measures the only thing that
// ever protected the allocator, and it would still be the case that goes red if that
// free were ever moved back behind a backend table.
//
// THE OBSERVABLE IS THE ALLOCATOR, not pixels: this leak produces correct pictures the
// whole way to the fatal, which is exactly why the four cases above ran green over it.
// It runs on BOTH backends' Handles lanes; DirectVulkan is where it was red.
@@ -1,599 +0,0 @@
// MobileGL - MobileGL/MG_IntegrationTest/Scenarios/InvalidImageUnitScenario.cpp
// Copyright (c) 2026 MobileGL-Dev
// Licensed under the GNU Lesser General Public License v3.0:
// https://www.gnu.org/licenses/gpl-3.0.txt
// https://www.gnu.org/licenses/lgpl-3.0.txt
// SPDX-License-Identifier: LGPL-3.0-only
// End of Source File Header
//
// Scenario - AN IMAGE UNIT NAMES A TEXTURE, BUT NOT A TEXEL THE TEXTURE HAS.
//
// UnboundImageDescriptorScenario's neighbour, one step further in: there the unit holds nothing,
// here it holds a real texture at a (level, layer) that texture does not have. GL 4.6 core 8.26
// makes every such access INVALID, and an invalid access is not an error at draw time: a load
// returns zero in R, G and B, a store has no effect. It is the same observable an empty unit has.
//
// KHR-GL46.shader_image_load_store.incomplete_textures is the conformance shape (case 1 below,
// once as a dispatch and once as the CTS's own fragment-shader draw): a texture with only level 0,
// GL_TEXTURE_MAX_LEVEL 7 and a mipmapping minification filter, bound at level 2. Magma's wire
// descriptor resolve looked the (level, layer) up in the texture's storage, found nothing, and
// died: Fatal{UnmigratedVerb, "Magma:image-view-window"} - a monolith Fail turned into a SIGABRT
// on the Redmi's inproc run (P7 gate 5 dry run). The other cases are the other ways the same
// lookup comes up empty: an immutable texture one level short, an array one slice short, a
// texture that has no storage at all, and a texture view whose own window is shorter than its
// owner's storage.
//
// Every case asserts all three halves of "invalid": the load through the invalid unit reads zero
// (it lands in a COMPLETE destination that started non-zero, so a lost dispatch is red as well),
// the store through the invalid unit changed no texel the invalid texture does have, and no GL
// error was raised.
//
// The two `AStoreThrough...` cases (codex closeout finding 2) store FIRST, through invalid unit A,
// then load through invalid unit B of the same shape and through A: a discarded store must never be
// loaded back. Magma's wire arm answered every invalid storage unit of one (format, target) from
// one shared placeholder image and failed both loads; it now binds a NULL storage descriptor
// (VK_EXT_robustness2 nullDescriptor), or, without one, a placeholder private to the (binding,
// unit) - forced on the host by MGITEST_MAGMA_FORCE_PRIVATE_IMAGE_PLACEHOLDER=1 (the
// `DirectVulkan.{Split,Spawn}.ImageUnitPrivate.` entries), where A's own load is the recorded
// CONTRACT-P7 §12 residual.
//
// Arms. Split/spawn/tcp on both backends. Espryt forwards the unit to the driver, which applies
// 8.26 itself. The MONOLITH DirectVulkan arm is skipped by name: it resolves the same binding to
// "no descriptor" and drops the whole draw (VkTextureManager::GetOrCreateStorageImageView's
// `mipLevel >= resource->mipLevels`), which is why the conformance case is a Fail there - that
// Fail is the P7 gate 5 BASE, and moving it would move the pull build's .text (G1).
#include <cstdint>
#include <cstdlib>
#include <string>
#include <vector>
#include "../Harness/HeadlessGL.h"
#include "../Harness/ScenarioFixture.h"
#include "../Harness/SplitLane.h"
#include "../Harness/SplitRuntimePeek.h"
#ifdef GLAPI
#undef GLAPI
#endif
#define GL_GLEXT_PROTOTYPES
#include <GL/gl.h>
#include <GL/glcorearb.h>
#undef GL_GLEXT_PROTOTYPES
namespace MGITest {
namespace {
constexpr int kEdge = 8;
constexpr GLubyte kCompleteDestinationMagic = 0x11;
constexpr GLubyte kCompleteSourceMagic = 0x22;
constexpr GLubyte kInvalidDestinationMagic = 0x33;
constexpr GLubyte kInvalidSourceMagic = 0x44;
// Units 0..3 and their roles are the conformance case's own.
constexpr const char* kComputeSource = R"(#version 430 core
layout(local_size_x = 8, local_size_y = 8) in;
layout(rgba8, binding = 0) writeonly uniform image2D u_completeDestination;
layout(rgba8, binding = 1) readonly uniform image2D u_completeSource;
layout(rgba8, binding = 2) writeonly uniform image2D u_invalidDestination;
layout(rgba8, binding = 3) readonly uniform image2D u_invalidSource;
void main() {
ivec2 p = ivec2(gl_GlobalInvocationID.xy);
imageStore(u_completeDestination, p, imageLoad(u_invalidSource, p));
imageStore(u_invalidDestination, p, imageLoad(u_completeSource, p));
}
)";
constexpr const char* kVertexSource = R"(#version 430 core
void main() {
vec2 positions[3] = vec2[3](vec2(-1.0, -1.0), vec2(3.0, -1.0), vec2(-1.0, 3.0));
gl_Position = vec4(positions[gl_VertexID], 0.0, 1.0);
}
)";
// Codex closeout finding 2: TWO INVALID UNITS MUST NOT ALIAS, AND AN INVALID STORE MUST NOT BE
// LOADED BACK. Magma's wire arm bound every invalid (and every empty) storage unit of one
// (format, target) to ONE shared placeholder image, cleared before the pass - so inside the
// pass a store through invalid unit A was there to be loaded through invalid unit B, and
// through A itself. 8.26: the store is discarded, both loads return zero. The store comes
// FIRST here (the four-unit shader above loads its invalid source before it stores to its
// invalid destination, so it could not see this), then an image barrier, then both loads,
// each into a complete destination that starts non-zero.
constexpr GLubyte kStoredThroughInvalid = 0x7F;
constexpr const char* kAliasComputeSource = R"(#version 430 core
layout(local_size_x = 8, local_size_y = 8) in;
layout(rgba8, binding = 0) writeonly uniform image2D u_loadedThroughB;
layout(rgba8, binding = 1) writeonly uniform image2D u_loadedThroughA;
layout(rgba8, binding = 2) coherent uniform image2D u_invalidA;
layout(rgba8, binding = 3) coherent readonly uniform image2D u_invalidB;
void main() {
ivec2 p = ivec2(gl_GlobalInvocationID.xy);
imageStore(u_invalidA, p, vec4(127.0 / 255.0));
memoryBarrierImage();
imageStore(u_loadedThroughB, p, imageLoad(u_invalidB, p));
imageStore(u_loadedThroughA, p, imageLoad(u_invalidA, p));
}
)";
// The conformance case's fragment shader, including its trailing discard.
constexpr const char* kFragmentSource = R"(#version 430 core
layout(rgba8, binding = 0) writeonly uniform image2D u_completeDestination;
layout(rgba8, binding = 1) readonly uniform image2D u_completeSource;
layout(rgba8, binding = 2) writeonly uniform image2D u_invalidDestination;
layout(rgba8, binding = 3) readonly uniform image2D u_invalidSource;
out vec4 o_color;
void main() {
ivec2 p = ivec2(gl_FragCoord.xy);
vec4 complete = imageLoad(u_completeSource, p);
vec4 invalid = imageLoad(u_invalidSource, p);
imageStore(u_completeDestination, p, invalid);
imageStore(u_invalidDestination, p, complete);
o_color = vec4(1.0);
discard;
}
)";
// Every byte non-zero, and distinct per texture, so "unchanged" and "zero" can never be
// the same answer.
std::vector<GLubyte> Pattern(int width, int height, int depth, GLubyte magic) {
std::vector<GLubyte> texels(static_cast<std::size_t>(width * height * depth) * 4u);
for (int z = 0; z < depth; ++z) {
for (int y = 0; y < height; ++y) {
for (int x = 0; x < width; ++x) {
const std::size_t at = static_cast<std::size_t>(((z * height + y) * width + x) * 4);
texels[at + 0] = magic;
texels[at + 1] = static_cast<GLubyte>(x + 1);
texels[at + 2] = static_cast<GLubyte>(y + 1 + 16 * z);
texels[at + 3] = 0xFF;
}
}
}
return texels;
}
enum class Invalidity {
MissingMipLevel, // mutable, level 0 only, MAX_LEVEL 7, bound at level 2 (the CTS shape)
PastImmutableLevels, // glTexStorage2D with 2 levels, bound at level 2
PastArrayLayers, // 2D array of 2 slices, bound non-layered at layer 2
NoStorage, // a named texture that was never given an image
PastViewWindow, // a 1-level view of a 3-level owner, bound at view level 1
};
class InvalidImageUnitScenario : public ScenarioTest {
protected:
void SetUp() override {
ScenarioTest::SetUp();
if (!Ready()) return;
m_wire = SplitRuntimeSkipReason().empty();
if (Gl().BackendName() == "DirectVulkan" && !m_wire) {
GTEST_SKIP() << "the monolith DirectVulkan arm resolves an image unit whose (level, layer) the "
"texture lacks to NO descriptor and drops the whole draw "
"(GetOrCreateStorageImageView: mipLevel >= resource->mipLevels), so the "
"valid half of the work never lands either. That is the P7 gate 5 BASE "
"(KHR-GL46.shader_image_load_store.incomplete_textures Fails there), and "
"changing it moves the pull build's .text (G1). Magma's wire arms and both "
"Espryt arms are the subject.";
}
FirstGLError();
}
void TearDown() override {
if (!Ready()) return;
glUseProgram(0);
for (GLuint unit = 0; unit < 4; ++unit) {
glBindImageTexture(unit, 0, 0, GL_FALSE, 0, GL_READ_ONLY, GL_RGBA8);
}
glBindTexture(GL_TEXTURE_2D, 0);
glBindTexture(GL_TEXTURE_2D_ARRAY, 0);
if (m_program != 0) glDeleteProgram(m_program);
if (!m_textures.empty()) {
glDeleteTextures(static_cast<GLsizei>(m_textures.size()), m_textures.data());
}
if (m_vao != 0) glDeleteVertexArrays(1, &m_vao);
if (m_target.fbo != 0) {
BindDefaultFramebuffer();
DestroyColorFbo(m_target);
glViewport(0, 0, Gl().Width(), Gl().Height());
}
FirstGLError();
}
static bool LimitIsAtLeast(GLenum limit, GLint wanted) {
GLint value = 0;
glGetIntegerv(limit, &value);
while (glGetError() != GL_NO_ERROR) {
}
return value >= wanted;
}
GLuint NewTexture() {
GLuint texture = 0;
glGenTextures(1, &texture);
m_textures.push_back(texture);
return texture;
}
GLuint MakeComplete2D(GLubyte magic) {
const GLuint texture = NewTexture();
glBindTexture(GL_TEXTURE_2D, texture);
glTexStorage2D(GL_TEXTURE_2D, 1, GL_RGBA8, kEdge, kEdge);
const auto texels = Pattern(kEdge, kEdge, 1, magic);
glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, kEdge, kEdge, GL_RGBA, GL_UNSIGNED_BYTE, texels.data());
return texture;
}
// The invalid texture for one reason, plus the (level, layer) to bind it at. The
// levels/layers it DOES have are recorded so the store half can be checked on all of
// them.
struct InvalidTexture {
GLuint texture = 0;
GLint bindLevel = 0;
GLint bindLayer = 0;
GLenum readTarget = GL_TEXTURE_2D;
GLuint readTexture = 0; // the texture whose texels are checked (a view's owner)
std::vector<int> definedLevels; // levels of readTexture that hold `magic`
int layers = 1;
GLubyte magic = 0;
};
InvalidTexture MakeInvalid(Invalidity why, GLubyte magic) {
InvalidTexture made{};
made.magic = magic;
switch (why) {
case Invalidity::MissingMipLevel: {
made.texture = NewTexture();
glBindTexture(GL_TEXTURE_2D, made.texture);
const auto texels = Pattern(kEdge, kEdge, 1, magic);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, kEdge, kEdge, 0, GL_RGBA, GL_UNSIGNED_BYTE,
texels.data());
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 7);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_LINEAR);
made.bindLevel = 2;
made.definedLevels = {0};
break;
}
case Invalidity::PastImmutableLevels: {
made.texture = NewTexture();
glBindTexture(GL_TEXTURE_2D, made.texture);
glTexStorage2D(GL_TEXTURE_2D, 2, GL_RGBA8, kEdge, kEdge);
for (int level = 0; level < 2; ++level) {
const int edge = kEdge >> level;
const auto texels = Pattern(edge, edge, 1, magic);
glTexSubImage2D(GL_TEXTURE_2D, level, 0, 0, edge, edge, GL_RGBA, GL_UNSIGNED_BYTE,
texels.data());
}
made.bindLevel = 2;
made.definedLevels = {0, 1};
break;
}
case Invalidity::PastArrayLayers: {
made.texture = NewTexture();
glBindTexture(GL_TEXTURE_2D_ARRAY, made.texture);
glTexStorage3D(GL_TEXTURE_2D_ARRAY, 1, GL_RGBA8, kEdge, kEdge, 2);
const auto texels = Pattern(kEdge, kEdge, 2, magic);
glTexSubImage3D(GL_TEXTURE_2D_ARRAY, 0, 0, 0, 0, kEdge, kEdge, 2, GL_RGBA, GL_UNSIGNED_BYTE,
texels.data());
made.bindLayer = 2;
made.readTarget = GL_TEXTURE_2D_ARRAY;
made.layers = 2;
made.definedLevels = {0};
break;
}
case Invalidity::NoStorage: {
made.texture = NewTexture();
// Bound once, so the name is an existing texture object glBindImageTexture accepts.
glBindTexture(GL_TEXTURE_2D, made.texture);
glBindTexture(GL_TEXTURE_2D, 0);
break;
}
case Invalidity::PastViewWindow: {
const GLuint owner = NewTexture();
glBindTexture(GL_TEXTURE_2D, owner);
glTexStorage2D(GL_TEXTURE_2D, 3, GL_RGBA8, kEdge, kEdge);
for (int level = 0; level < 3; ++level) {
const int edge = kEdge >> level;
const auto texels = Pattern(edge, edge, 1, magic);
glTexSubImage2D(GL_TEXTURE_2D, level, 0, 0, edge, edge, GL_RGBA, GL_UNSIGNED_BYTE,
texels.data());
}
made.texture = NewTexture();
// The view's one level is the owner's level 1. View level 1 would be the
// owner's level 2, which EXISTS - the window, not the storage, is what the
// binding falls outside of.
glTextureView(made.texture, GL_TEXTURE_2D, owner, GL_RGBA8, 1, 1, 0, 1);
made.bindLevel = 1;
made.readTexture = owner;
made.definedLevels = {0, 1, 2};
break;
}
}
if (made.readTexture == 0) made.readTexture = made.texture;
glBindTexture(GL_TEXTURE_2D, 0);
glBindTexture(GL_TEXTURE_2D_ARRAY, 0);
return made;
}
std::vector<GLubyte> ReadLevel(GLenum target, GLuint texture, int level, int layers) {
const int edge = kEdge >> level;
std::vector<GLubyte> texels(static_cast<std::size_t>(edge * edge * layers) * 4u, 0xA5);
glBindTexture(target, texture);
glGetTexImage(target, level, GL_RGBA, GL_UNSIGNED_BYTE, texels.data());
glBindTexture(target, 0);
return texels;
}
GLuint BuildCompute(const char* source = kComputeSource) {
const GLuint shader = glCreateShader(GL_COMPUTE_SHADER);
glShaderSource(shader, 1, &source, nullptr);
glCompileShader(shader);
GLint ok = GL_FALSE;
glGetShaderiv(shader, GL_COMPILE_STATUS, &ok);
if (ok == GL_FALSE) {
char log[4096] = {};
glGetShaderInfoLog(shader, sizeof(log) - 1, nullptr, log);
ADD_FAILURE() << "the compute shader did not compile: " << log;
glDeleteShader(shader);
return 0;
}
const GLuint program = glCreateProgram();
glAttachShader(program, shader);
glLinkProgram(program);
glDeleteShader(shader);
glGetProgramiv(program, GL_LINK_STATUS, &ok);
if (ok == GL_FALSE) {
char log[4096] = {};
glGetProgramInfoLog(program, sizeof(log) - 1, nullptr, log);
ADD_FAILURE() << "the compute program did not link: " << log;
glDeleteProgram(program);
return 0;
}
return program;
}
// The whole case: complete destination/source on units 0/1, the invalid texture on
// units 2/3 (two textures of the same shape, as in the conformance case), one pass,
// then the three halves of "invalid".
void ExpectInvalidAccess(Invalidity why, bool asDraw, const char* what) {
if (asDraw) {
if (!LimitIsAtLeast(GL_MAX_FRAGMENT_IMAGE_UNIFORMS, 4)) {
GTEST_SKIP() << "the fragment stage has fewer than four image uniforms";
}
} else if (!LimitIsAtLeast(GL_MAX_COMPUTE_IMAGE_UNIFORMS, 4)) {
GTEST_SKIP() << "the compute stage has fewer than four image uniforms";
}
const GLuint completeDestination = MakeComplete2D(kCompleteDestinationMagic);
const GLuint completeSource = MakeComplete2D(kCompleteSourceMagic);
const InvalidTexture invalidDestination = MakeInvalid(why, kInvalidDestinationMagic);
const InvalidTexture invalidSource = MakeInvalid(why, kInvalidSourceMagic);
ASSERT_EQ(FirstGLError(), 0u) << "building the textures raised a GL error (" << what << ")";
glBindImageTexture(0, completeDestination, 0, GL_FALSE, 0, GL_READ_WRITE, GL_RGBA8);
glBindImageTexture(1, completeSource, 0, GL_FALSE, 0, GL_READ_WRITE, GL_RGBA8);
glBindImageTexture(2, invalidDestination.texture, invalidDestination.bindLevel, GL_FALSE,
invalidDestination.bindLayer, GL_READ_WRITE, GL_RGBA8);
glBindImageTexture(3, invalidSource.texture, invalidSource.bindLevel, GL_FALSE,
invalidSource.bindLayer, GL_READ_WRITE, GL_RGBA8);
// A binding that is invalid at ACCESS time is still a legal bind (8.26 validates
// only the unit, the level's sign, the layer's sign, the access and the format).
ASSERT_EQ(FirstGLError(), 0u) << "glBindImageTexture raised a GL error (" << what << ")";
if (asDraw) {
std::string error;
m_program = CompileProgram(kVertexSource, kFragmentSource, &error);
ASSERT_NE(m_program, 0u) << error;
m_target = MakeColorFbo(kEdge, kEdge);
ASSERT_NE(m_target.fbo, 0u) << "could not create the render target";
BindFbo(m_target);
glGenVertexArrays(1, &m_vao);
glBindVertexArray(m_vao);
glUseProgram(m_program);
glDrawArrays(GL_TRIANGLES, 0, 3);
glBindVertexArray(0);
} else {
m_program = BuildCompute();
ASSERT_NE(m_program, 0u);
glUseProgram(m_program);
glDispatchCompute(1, 1, 1);
}
glMemoryBarrier(GL_ALL_BARRIER_BITS);
EXPECT_EQ(FirstGLError(), 0u) << "the pass raised a GL error (" << what << ")";
// (1) The load through the invalid unit read zero. The complete destination
// started at 0x11 everywhere, so a pass that never ran is red here too.
// ALL FOUR CHANNELS, which is stricter than 8.26 (it leaves the A of an invalid
// load undefined) and exactly what the conformance case compares: Espryt's driver
// answers (0, 0, 0, 0), and Magma's R32 placeholder used to answer (0, 0, 0, 1) -
// a green on R, G and B and a Fail on the CTS.
const auto loaded = ReadLevel(GL_TEXTURE_2D, completeDestination, 0, 1);
int nonZero = 0;
int firstX = -1, firstY = -1;
for (int y = 0; y < kEdge; ++y) {
for (int x = 0; x < kEdge; ++x) {
const std::size_t at = static_cast<std::size_t>((y * kEdge + x) * 4);
if (loaded[at] != 0 || loaded[at + 1] != 0 || loaded[at + 2] != 0 || loaded[at + 3] != 0) {
if (nonZero++ == 0) {
firstX = x;
firstY = y;
}
}
}
}
if (nonZero != 0) {
const std::size_t at = static_cast<std::size_t>((firstY * kEdge + firstX) * 4);
ADD_FAILURE() << nonZero << " of " << kEdge * kEdge << " texels loaded through the invalid "
<< what << " unit were not zero; first at (" << firstX << ", " << firstY << ") = ("
<< int(loaded[at]) << ", " << int(loaded[at + 1]) << ", " << int(loaded[at + 2])
<< ", " << int(loaded[at + 3]) << ") (R = 17 means the pass never ran)";
}
// (2) The store through the invalid unit changed nothing the texture has.
for (const int level : invalidDestination.definedLevels) {
const int edge = kEdge >> level;
const auto expected = Pattern(edge, edge, invalidDestination.layers, invalidDestination.magic);
const auto actual = ReadLevel(invalidDestination.readTarget, invalidDestination.readTexture, level,
invalidDestination.layers);
EXPECT_EQ(actual, expected) << "a store through the invalid " << what
<< " unit modified level " << level << " of the texture it names";
}
// (3) The valid half of the same pass is intact: the complete source was only read.
EXPECT_EQ(ReadLevel(GL_TEXTURE_2D, completeSource, 0, 1), Pattern(kEdge, kEdge, 1, kCompleteSourceMagic))
<< "the complete source changed (" << what << ")";
EXPECT_EQ(FirstGLError(), 0u) << "the readbacks raised a GL error (" << what << ")";
}
// Every texel of `texels` (one kEdge x kEdge RGBA8 level) loaded zero: R, G and B, which
// is what 8.26 fixes, and A as well where `strictAlpha` (the named-but-missing texel,
// whose conformance case compares all four; an EMPTY unit's placeholder on the arm
// without a null descriptor is the numeric-domain R32 one, which expands A to 1 - legal,
// 8.26 leaves A undefined). `storedAtOrigin` instead expects the stored 0x7F at (0, 0)
// in R, the one channel every placeholder format carries.
static void ExpectLoadedZero(const std::vector<GLubyte>& texels, bool storedAtOrigin, bool strictAlpha,
const char* through, const char* what) {
int wrong = 0;
int firstX = -1, firstY = -1;
for (int y = 0; y < kEdge; ++y) {
for (int x = 0; x < kEdge; ++x) {
const std::size_t at = static_cast<std::size_t>((y * kEdge + x) * 4);
const bool ok = storedAtOrigin && x == 0 && y == 0
? texels[at] == kStoredThroughInvalid
: texels[at] == 0 && texels[at + 1] == 0 && texels[at + 2] == 0 &&
(!strictAlpha || texels[at + 3] == 0);
if (!ok) {
if (wrong++ == 0) {
firstX = x;
firstY = y;
}
}
}
}
if (wrong != 0) {
const std::size_t at = static_cast<std::size_t>((firstY * kEdge + firstX) * 4);
ADD_FAILURE() << wrong << " of " << kEdge * kEdge << " texels loaded through " << through << " ("
<< what << ") were not what 8.26 gives; first at (" << firstX << ", " << firstY
<< ") = (" << int(texels[at]) << ", " << int(texels[at + 1]) << ", "
<< int(texels[at + 2]) << ", " << int(texels[at + 3]) << ") (127 is the value "
<< "stored through the invalid unit A, 17/34 means the pass never ran)";
}
}
// Units 2 (A) and 3 (B) are both invalid and of ONE shape - either both name the
// conformance case's missing mip level of a same-format texture, or both are empty.
// One dispatch stores 0x7F through A, barriers, and loads through B and through A.
void ExpectNoAliasThroughInvalidUnits(bool empty, const char* what) {
if (!LimitIsAtLeast(GL_MAX_COMPUTE_IMAGE_UNIFORMS, 4)) {
GTEST_SKIP() << "the compute stage has fewer than four image uniforms";
}
// The Magma wire arm without a null storage descriptor (a device lacking
// VK_EXT_robustness2 nullDescriptor; forced on the host by the knob): each invalid
// unit gets a placeholder private to its unit. B's load is still zero -
// the units no longer alias - but A's load of A's own store in the same pass is
// not: that is the CONTRACT-P7 §12 residual, and here it is what PROVES the knob
// reached the server (the null-descriptor arm would read zero there too).
const bool privatePlaceholderArm = m_wire && Gl().BackendName() == "DirectVulkan" &&
SplitLane::MarkerIsOne("MGITEST_MAGMA_FORCE_PRIVATE_IMAGE_PLACEHOLDER");
const GLuint loadedThroughB = MakeComplete2D(kCompleteDestinationMagic);
const GLuint loadedThroughA = MakeComplete2D(kCompleteSourceMagic);
InvalidTexture invalidA{};
InvalidTexture invalidB{};
if (!empty) {
invalidA = MakeInvalid(Invalidity::MissingMipLevel, kInvalidDestinationMagic);
invalidB = MakeInvalid(Invalidity::MissingMipLevel, kInvalidSourceMagic);
}
ASSERT_EQ(FirstGLError(), 0u) << "building the textures raised a GL error (" << what << ")";
glBindImageTexture(0, loadedThroughB, 0, GL_FALSE, 0, GL_READ_WRITE, GL_RGBA8);
glBindImageTexture(1, loadedThroughA, 0, GL_FALSE, 0, GL_READ_WRITE, GL_RGBA8);
glBindImageTexture(2, invalidA.texture, invalidA.bindLevel, GL_FALSE, 0, GL_READ_WRITE, GL_RGBA8);
glBindImageTexture(3, invalidB.texture, invalidB.bindLevel, GL_FALSE, 0, GL_READ_WRITE, GL_RGBA8);
ASSERT_EQ(FirstGLError(), 0u) << "glBindImageTexture raised a GL error (" << what << ")";
m_program = BuildCompute(kAliasComputeSource);
ASSERT_NE(m_program, 0u);
glUseProgram(m_program);
glDispatchCompute(1, 1, 1);
glMemoryBarrier(GL_ALL_BARRIER_BITS);
EXPECT_EQ(FirstGLError(), 0u) << "the pass raised a GL error (" << what << ")";
ExpectLoadedZero(ReadLevel(GL_TEXTURE_2D, loadedThroughB, 0, 1), false, !empty,
"invalid unit B after a store through invalid unit A of the same shape", what);
ExpectLoadedZero(ReadLevel(GL_TEXTURE_2D, loadedThroughA, 0, 1), privatePlaceholderArm, !empty,
privatePlaceholderArm
? "invalid unit A itself on the private-placeholder arm (0x7F at the origin "
"is the recorded same-unit residual AND the proof this arm ran; zero means "
"MGITEST_MAGMA_FORCE_PRIVATE_IMAGE_PLACEHOLDER did not reach the server)"
: "invalid unit A itself after its own store",
what);
if (!empty) {
// The discarded store changed nothing the texture has.
for (const InvalidTexture* invalid : {&invalidA, &invalidB}) {
EXPECT_EQ(ReadLevel(GL_TEXTURE_2D, invalid->texture, 0, 1),
Pattern(kEdge, kEdge, 1, invalid->magic))
<< "a store through an invalid unit modified the level its texture has (" << what << ")";
}
}
EXPECT_EQ(FirstGLError(), 0u) << "the readbacks raised a GL error (" << what << ")";
}
bool m_wire = false;
std::vector<GLuint> m_textures;
unsigned int m_program = 0;
GLuint m_vao = 0;
ColorFbo m_target{};
};
} // namespace
// The conformance shape, as the conformance case runs it: a fragment-shader draw.
TEST_F(InvalidImageUnitScenario, AMissingMipLevelOfAnIncompleteTextureReadsZeroInADraw) {
if (!Ready() || IsSkipped()) return;
ExpectInvalidAccess(Invalidity::MissingMipLevel, true, "missing-mip-level");
}
TEST_F(InvalidImageUnitScenario, AMissingMipLevelOfAnIncompleteTextureReadsZeroInADispatch) {
if (!Ready() || IsSkipped()) return;
ExpectInvalidAccess(Invalidity::MissingMipLevel, false, "missing-mip-level");
}
TEST_F(InvalidImageUnitScenario, ALevelPastAnImmutableTexturesStorageReadsZero) {
if (!Ready() || IsSkipped()) return;
ExpectInvalidAccess(Invalidity::PastImmutableLevels, false, "past-immutable-levels");
}
TEST_F(InvalidImageUnitScenario, ALayerPastAnArraysLastSliceReadsZero) {
if (!Ready() || IsSkipped()) return;
ExpectInvalidAccess(Invalidity::PastArrayLayers, false, "past-array-layers");
}
TEST_F(InvalidImageUnitScenario, ATextureWithNoStorageReadsZero) {
if (!Ready() || IsSkipped()) return;
ExpectInvalidAccess(Invalidity::NoStorage, false, "no-storage");
}
TEST_F(InvalidImageUnitScenario, ALevelPastATextureViewsWindowReadsZero) {
if (!Ready() || IsSkipped()) return;
if (Gl().BackendName() == "DirectGLES") {
const char* enabled = std::getenv("MOBILEGL_ESPRYT_ENABLE_TEXTURE_VIEW");
if (enabled == nullptr || std::string(enabled) != "1") {
GTEST_SKIP() << "Espryt withholds glTextureView unless MOBILEGL_ESPRYT_ENABLE_TEXTURE_VIEW=1";
}
}
ExpectInvalidAccess(Invalidity::PastViewWindow, false, "past-view-window");
}
// Codex closeout finding 2: a store through invalid unit A, an image barrier, then loads
// through invalid unit B of the same (format, target) and through A - both zero.
TEST_F(InvalidImageUnitScenario, AStoreThroughAnInvalidUnitIsLoadedThroughNeitherAnotherInvalidUnitNorItself) {
if (!Ready() || IsSkipped()) return;
ExpectNoAliasThroughInvalidUnits(false, "missing-mip-level units");
}
// The same through two EMPTY units (glBindImageTexture(unit, 0, ...)): 8.26 makes those
// accesses invalid too, and Magma's wire arm answered them from the same shared placeholder.
TEST_F(InvalidImageUnitScenario, AStoreThroughAnEmptyUnitIsLoadedThroughNeitherAnotherEmptyUnitNorItself) {
if (!Ready() || IsSkipped()) return;
ExpectNoAliasThroughInvalidUnits(true, "empty units");
}
} // namespace MGITest
@@ -1,220 +0,0 @@
// MobileGL - MobileGL/MG_IntegrationTest/Scenarios/MagmaVertexLayoutScenario.cpp
// Copyright (c) 2026 MobileGL-Dev
// Licensed under the GNU Lesser General Public License v3.0:
// https://www.gnu.org/licenses/gpl-3.0.txt
// https://www.gnu.org/licenses/lgpl-3.0.txt
// SPDX-License-Identifier: LGPL-3.0-only
// End of Source File Header
//
// P7 wave 2 package C, CONTRACT-P7 §3.2's `vertex-layout` row: THE ATTRIBUTE VULKAN CANNOT MAP.
//
// WHAT THIS EXISTS TO CATCH, and it is not a picture. Until this package
// VertexInputStateFactory::BuildWireVertexInput answered SEVEN different device/format
// conditions and one protocol condition with the same `false`, and the single caller answered
// that `false` with a P7-marked MagmaWireFatal - which, before wave 0 funnelled it, was a bare
// std::abort(). So a Magma split session that met a GL_FIXED array, a dvec on a device with
// native fp64, or any format without VK_FORMAT_FEATURE_VERTEX_BUFFER_BIT did not decline the
// draw: it KILLED THE PROCESS. The monolith arm on the very same device has always masked the
// attribute out of the vertex input state and then declined the draw loudly and once, which is
// the answer GL asks for. These cases pin that the two arms now agree.
//
// WHY GL_FIXED IS THE VEHICLE. It is the one unmappable shape that needs no device to cooperate:
// DataType::Fixed32 has no arm in ToVkVertexFormat at all, so the format map answers
// VK_FORMAT_UNDEFINED on every ICD including the lavapipe the host lanes run on. That matters
// because CONTRACT-P7 §2.5 records that host lavapipe reaches no other P7-marked refusal -
// the readback matrices and odd-offset uniform ranges that reach the rest need real hardware -
// so without this shape the whole `vertex-layout` retirement would have no host gate at all.
//
// DIRECTVULKAN ONLY, deliberately. The claim is about what Magma does with a format Vulkan
// cannot express; Espryt hands GL_FIXED straight to a driver that supports it and renders, so
// registering these on DirectGLES would assert a different fact under the same name.
#include "../Harness/ScenarioFixture.h"
#include "../Harness/SplitRuntimePeek.h"
#include <array>
#include <vector>
#ifdef GLAPI
#undef GLAPI
#endif
#define GL_GLEXT_PROTOTYPES
#include <GL/gl.h>
#include <GL/glcorearb.h>
#undef GL_GLEXT_PROTOTYPES
namespace MGITest {
namespace {
constexpr int kWidth = 16, kHeight = 16;
// Reads BOTH attributes, so an array masked out of the vertex input state is one the
// program actually consumes and the draw must decline rather than silently substitute the
// current attribute value.
constexpr const char* kVertexReadsBoth = R"(#version 430 core
layout(location=0) in vec2 inPos;
layout(location=1) in vec3 inTint;
out vec3 vTint;
void main() {
vTint = inTint;
gl_Position = vec4(inPos, 0.0, 1.0);
})";
// Reads ONLY location 0. An enabled-but-unread array is not part of this program's vertex
// input at all, so neither arm has anything to mask and the draw must land.
constexpr const char* kVertexReadsPositionOnly = R"(#version 430 core
layout(location=0) in vec2 inPos;
out vec3 vTint;
void main() {
vTint = vec3(0.0, 1.0, 0.0);
gl_Position = vec4(inPos, 0.0, 1.0);
})";
constexpr const char* kFragment = R"(#version 430 core
in vec3 vTint;
layout(location=0) out vec4 color;
void main() { color = vec4(vTint, 1.0); })";
class MagmaVertexLayoutScenario : public ScenarioTest {
protected:
GLuint m_vao = 0, m_positions = 0, m_fixedAttrib = 0, m_program = 0;
void SetUp() override {
ScenarioTest::SetUp();
if (!Ready()) return;
if (Gl().BackendName() != "DirectVulkan") {
GTEST_SKIP() << "the format map under test is Magma's; Espryt hands GL_FIXED to a "
"driver that supports it";
}
glDisable(GL_SCISSOR_TEST);
glDisable(GL_DEPTH_TEST);
glDisable(GL_STENCIL_TEST);
glViewport(0, 0, kWidth, kHeight);
}
void TearDown() override {
if (m_program) glDeleteProgram(m_program);
if (m_vao) glDeleteVertexArrays(1, &m_vao);
if (m_positions) glDeleteBuffers(1, &m_positions);
if (m_fixedAttrib) glDeleteBuffers(1, &m_fixedAttrib);
ScenarioTest::TearDown();
}
GLuint MakeProgram(const char* vertexSource) {
const GLuint vs = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vs, 1, &vertexSource, nullptr);
glCompileShader(vs);
GLint ok = GL_FALSE;
glGetShaderiv(vs, GL_COMPILE_STATUS, &ok);
EXPECT_EQ(ok, GL_TRUE) << "vertex shader did not compile";
const GLuint fs = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fs, 1, &kFragment, nullptr);
glCompileShader(fs);
glGetShaderiv(fs, GL_COMPILE_STATUS, &ok);
EXPECT_EQ(ok, GL_TRUE) << "fragment shader did not compile";
const GLuint program = glCreateProgram();
glAttachShader(program, vs);
glAttachShader(program, fs);
glLinkProgram(program);
glGetProgramiv(program, GL_LINK_STATUS, &ok);
EXPECT_EQ(ok, GL_TRUE) << "program did not link";
glDeleteShader(vs);
glDeleteShader(fs);
return program;
}
// A full-viewport triangle in location 0 and a GL_FIXED size-3 array in location 1.
// GL_FIXED is 16.16 fixed point; the bytes are never fetched on the arm under test
// (the attribute is masked out before any binding is built), so their VALUE matters
// only for the unread case, where nothing reads them either.
void BuildVaoWithAFixedAttribute() {
const float positions[6] = {-1.0f, -1.0f, 3.0f, -1.0f, -1.0f, 3.0f};
const GLint fixedTint[9] = {0, 1 << 16, 0, 0, 1 << 16, 0, 0, 1 << 16, 0};
glGenVertexArrays(1, &m_vao);
glBindVertexArray(m_vao);
glGenBuffers(1, &m_positions);
glBindBuffer(GL_ARRAY_BUFFER, m_positions);
glBufferData(GL_ARRAY_BUFFER, sizeof(positions), positions, GL_STATIC_DRAW);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, nullptr);
glEnableVertexAttribArray(0);
glGenBuffers(1, &m_fixedAttrib);
glBindBuffer(GL_ARRAY_BUFFER, m_fixedAttrib);
glBufferData(GL_ARRAY_BUFFER, sizeof(fixedTint), fixedTint, GL_STATIC_DRAW);
// THE SHAPE UNDER TEST: size 3, GL_FIXED. ToVkVertexFormat has no Fixed32 arm, so
// this resolves to VK_FORMAT_UNDEFINED and the wire builder's `format-map` reason
// fires - the reason that used to abort the session.
glVertexAttribPointer(1, 3, GL_FIXED, GL_FALSE, 0, nullptr);
glEnableVertexAttribArray(1);
glBindBuffer(GL_ARRAY_BUFFER, 0);
}
std::array<GLubyte, 4> ClearDrawRead(GLuint program) {
glClearColor(0.0f, 0.0f, 1.0f, 1.0f); // blue: the "the draw did not land" colour
glClear(GL_COLOR_BUFFER_BIT);
glUseProgram(program);
glBindVertexArray(m_vao);
glDrawArrays(GL_TRIANGLES, 0, 3);
std::array<GLubyte, 4> pixel{};
glReadPixels(kWidth / 2, kHeight / 2, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, pixel.data());
glBindVertexArray(0);
glUseProgram(0);
return pixel;
}
};
// ------------------------------------------------------------------------------------
// THE RETIREMENT ITSELF. The program READS the unmappable array, so the attribute is
// masked out of the vertex input state and the draw is then declined - loudly, once, and
// without touching the session. Before this package the same GL killed the process.
//
// THE ASSERTION IS THAT THE PROCESS IS STILL HERE and that the framebuffer still holds the
// clear, which together say "declined" rather than "rendered wrong pixels". A gtest case
// cannot assert the absence of an abort any more directly than by reaching its next
// statement: the old behaviour took the whole binary down, so every case after this one in
// the lane was equally the control.
TEST_F(MagmaVertexLayoutScenario, AnUnmappableVertexFormatDeclinesTheDrawInsteadOfEndingTheSession) {
if (!Ready() || IsSkipped()) return;
m_program = MakeProgram(kVertexReadsBoth);
BuildVaoWithAFixedAttribute();
const auto pixel = ClearDrawRead(m_program);
EXPECT_EQ(FirstGLError(), GLenum(GL_NO_ERROR))
<< "a declined draw must not invent a GL error: GL has no error for 'this "
"implementation cannot fetch that array', and the monolith arm raises none";
const int blue[4] = {0, 0, 255, 255};
for (int i = 0; i < 4; ++i) {
EXPECT_NEAR(pixel[i], blue[i], 1)
<< "component " << i << ": the draw was expected to DECLINE (leaving the clear "
"colour) because location 1 is an enabled GL_FIXED array the program reads "
"and Vulkan has no format for it. A non-clear pixel means the attribute was "
"silently replaced by the current vertex attribute value, which is the exact "
"wrong-pixels outcome the monolith arm's pre-flight refuses.";
}
}
// ------------------------------------------------------------------------------------
// THE OTHER HALF, and it is what keeps the case above from being satisfied by "decline
// every draw that mentions GL_FIXED". The array is still enabled and still unmappable; the
// program simply does not read it, so it is not part of this program's vertex input on
// either arm and the draw must land normally.
TEST_F(MagmaVertexLayoutScenario, AnUnreadUnmappableArrayDoesNotStopTheRestOfTheDraw) {
if (!Ready() || IsSkipped()) return;
m_program = MakeProgram(kVertexReadsPositionOnly);
BuildVaoWithAFixedAttribute();
const auto pixel = ClearDrawRead(m_program);
EXPECT_EQ(FirstGLError(), GLenum(GL_NO_ERROR)) << "the draw should have been ordinary";
const int green[4] = {0, 255, 0, 255};
for (int i = 0; i < 4; ++i) {
EXPECT_NEAR(pixel[i], green[i], 1)
<< "component " << i << ": an enabled but UNREAD GL_FIXED array must not cost "
"the draw. Blue here means the whole draw was declined for an attribute "
"that is not part of this program's vertex input at all.";
}
}
} // namespace
} // namespace MGITest
@@ -1,578 +0,0 @@
// MobileGL - MobileGL/MG_IntegrationTest/Scenarios/MagmaWireReclaimScenario.cpp
// Copyright (c) 2026 MobileGL-Dev
// Licensed under the GNU Lesser General Public License v3.0:
// https://www.gnu.org/licenses/gpl-3.0.txt
// https://www.gnu.org/licenses/lgpl-3.0.txt
// SPDX-License-Identifier: LGPL-3.0-only
// End of Source File Header
//
// P7 wave 4 package M2 (ID-P7-27 / ID-P7-32): THE MAGMA WIRE ARM MUST RECLAIM ORPHANED BUFFER
// STORES INSIDE A FRAME.
//
// THE DEFECT. Every glBufferData that crosses the wire reaches VkBufferManager::
// RespecifyWireBuffer, which orphans the old VkBuffer (legitimately - a recorded draw may still
// name it) and mints a new one. Before this package the orphan went into a per-frame-slot bucket
// that only a FRAME BOUNDARY emptied, and minecraft-1.21.4-fabric-iris-bsl-esc-menu-854 has two
// eglSwapBuffers in 1,303,535 calls - the server sees one present per replay. On lavapipe the
// split server held 25,923 dead stores against 28 live wire buffers and 41k mappings; on the
// Redmi it died in scudo at 1.2 GiB while the monolith passed at 807 MiB.
//
// WHAT THE CASES PIN, all inside ONE frame (no swap between the first and the last
// respecify), because that is the only shape in which the bug existed:
// * RespecifiesWithNoDrawBetween... - the stores no GPU command ever named. They are dead the
// moment they are orphaned, so the live store count must stay a small multiple of the wire
// buffers alive (k = 4 here; the mechanism gives 1).
// * RespecifyAndDrawEachStore... - every orphan was drawn from, so it is named by recorded,
// unsubmitted work and nothing retires it inside the frame except the
// MOBILEGL_IPC_WIRE_DEFERRED_MB watermark's forced sync point. The parked bytes must stay
// within the budget plus one store, and every draw must still land on its own strip - a
// store destroyed while its draw was pending shows up as a wrong strip (or a dead lavapipe).
// * ManySmallRespecifyAndDrawRounds... - the same with stores too small to reach any byte
// budget; the fixed 1024-store ceiling on the same sync point is what bounds them.
// * ADrawAfterTheEarlyReclaim... (round 2, ID-P7-43) - the reclaim's own hazard: a store that
// dies mid-frame frees a VkBuffer handle value the descriptor memos still map to a set baked
// to its memory, and the next mint can get that value back. The pixel of a draw made
// through the re-minted handle must follow the new store's bytes.
//
// READ FROM THE SERVER, NOT THE PICTURE. The numbers are the wbuf[] gauges the server role's
// VkBufferManager publishes (PipeStats.h, Gauge::WireBuffers..WireDeferredSyncs): RUN MAXIMA,
// because the peak lives inside the frame and a swap-time sample would read after the frame
// boundary's own sweep. They reach this process through the server's `MGPipe stats:` line, so
// the lane pins MOBILEGL_PIPE_STATS=1 and a private log path, and the entries are registered on
// the inproc and spawn arms ONLY: the tcp arm's server is the pre-started fixture supervisor,
// whose environment the lane cannot set and whose log this process cannot read
// (scripts/ci/spawn_lane_parity.py names the exception).
#include <algorithm>
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <string>
#include <vector>
#include "../Harness/HeadlessGL.h"
#include "../Harness/PipeStatsWindow.h"
#include "../Harness/ScenarioFixture.h"
#include "../Harness/SplitRuntimePeek.h"
#ifdef GLAPI
#undef GLAPI
#endif
#define GL_GLEXT_PROTOTYPES
#include <GL/gl.h>
#include <GL/glcorearb.h>
#undef GL_GLEXT_PROTOTYPES
namespace MGITest {
namespace {
// Set by the MagmaWireReclaim ctest entries and by nothing else; a harness marker, never
// read by the library. The whole-binary informational lanes run this file without it and
// without the stats channel, and skip.
constexpr const char* kLaneMarker = "MGITEST_MAGMA_RECLAIM_LANE";
constexpr int kWidth = 64;
constexpr int kHeight = 16;
constexpr std::uint64_t kMiB = 1024u * 1024u;
// Case 1: many small respecifies of ONE buffer and no draw between them.
constexpr int kUndrawnRespecifies = 1024;
constexpr std::size_t kUndrawnStoreBytes = 4096;
constexpr long long kLivePerWireBuffer = 4;
// Case 2: respecify-and-draw, one strip per store. 48 stores of 1 MiB is six times the
// 8 MiB budget the lane sets, so the watermark has to fire several times in the frame.
constexpr int kDrawnRespecifies = 48;
constexpr std::size_t kDrawnStoreBytes = static_cast<std::size_t>(kMiB);
// Case 3: many SMALL respecify-and-draw rounds - 3000 x 256 B is 750 KB, nowhere near
// the byte budget, so only the store-count ceiling (VkBufferManager::
// kWireDeferredCountCeiling, 1024) can bound them inside the frame.
constexpr int kSmallDrawnRespecifies = 3000;
constexpr std::size_t kSmallDrawnStoreBytes = 256;
constexpr long long kDeferredCountCeiling = 1024;
// Case 4: the memo ABA. The store that dies is SMALL and the one minted through its
// handle afterwards is LARGE, with a pinned 1 MiB store minted right after the small one
// so its hole stays a hole: a same-size mint would take the just-freed memory range back
// (VMA's best-fit bucket) and the stale descriptor would read the new bytes by aliasing
// accident, which is a green that proves nothing. 64 KiB cannot land in a 256-byte hole.
constexpr std::size_t kAbaDeadStoreBytes = 256;
constexpr std::size_t kAbaPinStoreBytes = static_cast<std::size_t>(kMiB);
constexpr std::size_t kAbaNewStoreBytes = 64 * 1024;
constexpr GLuint64 kAbaWaitNs = 2000000000ull; // 2 s: a 64x16 draw on lavapipe retires in ms
constexpr int kDescriptorDraws = 2049; // one past UniformManager's wire epoch budget
constexpr const char* kVertex = R"(#version 330 core
layout(location = 0) in vec2 aPos;
void main() { gl_Position = vec4(aPos, 0.0, 1.0); })";
constexpr const char* kFragment = R"(#version 330 core
uniform vec4 uColor;
out vec4 fragColor;
void main() { fragColor = uColor; })";
// Case 4 paints from a uniform BLOCK, because a block bound through glBindBufferBase is
// what the wire arm binds directly - the descriptor names the store's own VkBuffer
// (UniformManager::ResolveWireUniformBufferPayload) - while a plain uniform goes
// through a transient slice that no store handle can alias.
constexpr const char* kBlockFragment = R"(#version 330 core
layout(std140) uniform Block { vec4 color; };
out vec4 fragColor;
void main() { fragColor = color; })";
constexpr const char* kStorageVertex = R"(#version 430 core
layout(location = 0) in vec2 aPos;
void main() { gl_Position = vec4(aPos, 0.0, 1.0); })";
constexpr const char* kStorageFragment = R"(#version 430 core
layout(std430, binding = 0) readonly buffer Colors { vec4 color[]; };
out vec4 fragColor;
void main() { fragColor = color[0]; })";
// Two triangles covering pixel columns [x0, x1) over the whole height, in NDC.
void WriteStripQuad(float* out, int x0, int x1) {
const float l = -1.0f + 2.0f * static_cast<float>(x0) / kWidth;
const float r = -1.0f + 2.0f * static_cast<float>(x1) / kWidth;
const float quad[12] = {l, -1.0f, r, -1.0f, r, 1.0f, l, -1.0f, r, 1.0f, l, 1.0f};
for (int i = 0; i < 12; ++i) out[i] = quad[i];
}
// A colour per strip that no neighbour shares and the clear (all zero) is not.
Rgba8 StripColor(int strip) {
Rgba8 c;
c.r = static_cast<std::uint8_t>(40 + (strip * 37) % 200);
c.g = static_cast<std::uint8_t>(40 + (strip * 91) % 200);
c.b = static_cast<std::uint8_t>(255 - strip);
c.a = 255;
return c;
}
bool Near(const Rgba8& a, const Rgba8& b) {
return std::abs(int(a.r) - int(b.r)) <= 1 && std::abs(int(a.g) - int(b.g)) <= 1 &&
std::abs(int(a.b) - int(b.b)) <= 1 && std::abs(int(a.a) - int(b.a)) <= 1;
}
std::uint64_t DeferredBudgetBytes() {
const char* value = std::getenv("MOBILEGL_IPC_WIRE_DEFERRED_MB");
const std::uint64_t mb = (value != nullptr && *value != '\0') ? std::strtoull(value, nullptr, 10) : 64u;
return mb * kMiB;
}
class MagmaWireReclaimScenario : public ScenarioTest {
protected:
GLuint m_program = 0, m_vao = 0, m_buffer = 0;
GLint m_colorLocation = -1;
ColorFbo m_target{};
void SetUp() override {
ScenarioTest::SetUp();
if (!Ready()) return;
if (Gl().BackendName() != "DirectVulkan") {
GTEST_SKIP() << "the reclaim under test is the Magma wire arm's VkBufferManager";
}
if (std::getenv(kLaneMarker) == nullptr) {
GTEST_SKIP() << kLaneMarker << " is not set: this run has no private stats "
"channel to read the server's wbuf[] gauges from";
}
const SplitRuntimeState runtime = PeekSplitRuntime();
if (!runtime.transportResolved || !runtime.sessionActive) {
GTEST_SKIP() << "not a split run (" << runtime.transportName
<< "): the monolith arm has no wire buffer stores";
}
std::string error;
m_program = CompileProgram(kVertex, kFragment, &error);
ASSERT_NE(m_program, 0u) << error;
m_colorLocation = glGetUniformLocation(m_program, "uColor");
ASSERT_GE(m_colorLocation, 0);
m_target = MakeColorFbo(kWidth, kHeight);
ASSERT_NE(m_target.fbo, 0u);
BindFbo(m_target);
glDisable(GL_SCISSOR_TEST);
glDisable(GL_DEPTH_TEST);
glDisable(GL_BLEND);
ClearTo(0.0f, 0.0f, 0.0f, 0.0f);
glGenVertexArrays(1, &m_vao);
glBindVertexArray(m_vao);
glGenBuffers(1, &m_buffer);
glBindBuffer(GL_ARRAY_BUFFER, m_buffer);
}
void TearDown() override {
if (Ready()) {
if (m_buffer) glDeleteBuffers(1, &m_buffer);
if (m_vao) glDeleteVertexArrays(1, &m_vao);
if (m_program) glDeleteProgram(m_program);
if (m_target.fbo) DestroyColorFbo(m_target);
}
ScenarioTest::TearDown();
}
// glBufferData of `bytes` (a strip quad at offset 0, zeros after) and the attribute
// pointer re-armed on the new store.
void Respecify(std::vector<std::uint8_t>& bytes, int x0, int x1) {
WriteStripQuad(reinterpret_cast<float*>(bytes.data()), x0, x1);
glBufferData(GL_ARRAY_BUFFER, static_cast<GLsizeiptr>(bytes.size()), bytes.data(), GL_STREAM_DRAW);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, nullptr);
glEnableVertexAttribArray(0);
}
void DrawStrip(int strip) {
const Rgba8 c = StripColor(strip);
glUseProgram(m_program);
glUniform4f(m_colorLocation, c.r / 255.0f, c.g / 255.0f, c.b / 255.0f, 1.0f);
glDrawArrays(GL_TRIANGLES, 0, 6);
}
// The swap that closes the counted frame, and the server's line for it.
PipeStatsWindow::Window CloseFrameAndReadServerWindow(const PipeStatsWindow::LogMark& mark) {
Gl().EndFrame();
if (const SplitRuntimeState runtime = PeekSplitRuntime(); runtime.transportResolved) {
EXPECT_TRUE(WaitForSplitAppliedForTesting(runtime.emitSeq));
}
PipeStatsWindow::Window window = PipeStatsWindow::LastFromServerLogSince(mark);
if (window.found) RecordProperty("stats_line_server", window.line.c_str());
return window;
}
// A setup frame that draws once from the buffer, so the first orphan of the counted
// frame is a store the GPU really named, then the mark the counted window starts at.
PipeStatsWindow::LogMark SetupFrame() {
std::vector<std::uint8_t> bytes(kUndrawnStoreBytes, 0);
Respecify(bytes, 0, kWidth);
DrawStrip(0);
Gl().EndFrame();
BindFbo(m_target);
if (const SplitRuntimeState runtime = PeekSplitRuntime(); runtime.transportResolved) {
EXPECT_TRUE(WaitForSplitAppliedForTesting(runtime.emitSeq));
}
return PipeStatsWindow::MarkLaneLog();
}
};
// --------------------------------------------------------------------------------------
// CASE 1. 1024 glBufferData of one 4 KiB buffer and no draw between them: 1023 of the
// orphans were never named by a GPU command and are dead the moment they are orphaned.
// Before M2 every one of them waited for the frame boundary, so the peak was ~1025 live
// VkBuffers for one wire buffer.
TEST_F(MagmaWireReclaimScenario, RespecifiesWithNoDrawBetweenKeepTheLiveStoreCountBounded) {
if (!Ready() || IsSkipped()) return;
const PipeStatsWindow::LogMark mark = SetupFrame();
std::vector<std::uint8_t> bytes(kUndrawnStoreBytes, 0);
for (int i = 0; i < kUndrawnRespecifies; ++i) {
// Only the LAST store's quad covers the target; the rest are never drawn.
const bool last = (i + 1 == kUndrawnRespecifies);
Respecify(bytes, 0, last ? kWidth : 1);
}
ClearTo(0.0f, 0.0f, 0.0f, 0.0f);
DrawStrip(7);
const Image image = ReadPixels(kWidth, kHeight);
ASSERT_EQ(FirstGLError(), GLenum(GL_NO_ERROR));
EXPECT_TRUE(Near(image.At(kWidth / 2, kHeight / 2), StripColor(7)))
<< "read " << image.At(kWidth / 2, kHeight / 2) << ", wanted " << StripColor(7)
<< ": the draw from the last of " << kUndrawnRespecifies << " respecified stores did "
"not land - the store it names was reclaimed, or never reached";
const PipeStatsWindow::Window window = CloseFrameAndReadServerWindow(mark);
ASSERT_TRUE(window.found) << "no 'MGPipe stats:' window in the server log "
<< PipeStatsWindow::ServerLibraryLogPath();
const long long wireBuffers = PipeStatsWindow::CounterOrAbsent(window, "wbufs");
const long long livePeak = PipeStatsWindow::CounterOrAbsent(window, "wlivepk");
ASSERT_GT(wireBuffers, 0) << "the server published no wbufs= gauge: " << window.line;
ASSERT_GE(livePeak, 0) << window.line;
RecordProperty("wire_buffers", static_cast<int>(wireBuffers));
RecordProperty("wire_stores_peak", static_cast<int>(livePeak));
EXPECT_LE(livePeak, kLivePerWireBuffer * wireBuffers)
<< "the Magma server held " << livePeak << " VkBuffers at once for " << wireBuffers
<< " wire buffer record(s) inside one frame of " << kUndrawnRespecifies
<< " glBufferData calls. Orphans no GPU command named are dead at the park; a count "
"that tracks the respecifies is the bsl-esc-menu-854 leak (ID-P7-32). " << window.line;
}
// --------------------------------------------------------------------------------------
// CASE 2. 48 respecify-and-draw rounds of a 1 MiB store, one strip each, in one frame.
// Every orphan is named by recorded, unsubmitted work; only the watermark's forced sync
// point can retire it before the frame ends. Before M2: 48 MiB parked against the lane's
// 8 MiB budget. The strips are the soundness half: a store destroyed while its draw was
// still pending does not leave its own colour behind.
TEST_F(MagmaWireReclaimScenario, RespecifyAndDrawEachStoreInOneFrameStaysWithinTheDeferredBudget) {
if (!Ready() || IsSkipped()) return;
const PipeStatsWindow::LogMark mark = SetupFrame();
ClearTo(0.0f, 0.0f, 0.0f, 0.0f);
std::vector<std::uint8_t> bytes(kDrawnStoreBytes, 0);
for (int strip = 0; strip < kDrawnRespecifies; ++strip) {
Respecify(bytes, strip, strip + 1);
DrawStrip(strip);
}
const Image image = ReadPixels(kWidth, kHeight);
ASSERT_EQ(FirstGLError(), GLenum(GL_NO_ERROR));
int wrongStrips = 0;
for (int strip = 0; strip < kDrawnRespecifies; ++strip) {
const Rgba8 got = image.At(strip, kHeight / 2);
if (!Near(got, StripColor(strip))) {
++wrongStrips;
ADD_FAILURE() << "strip " << strip << " reads " << got << ", wanted " << StripColor(strip)
<< ": the draw from that strip's own store did not land";
}
if (wrongStrips > 4) break;
}
const PipeStatsWindow::Window window = CloseFrameAndReadServerWindow(mark);
ASSERT_TRUE(window.found) << "no 'MGPipe stats:' window in the server log "
<< PipeStatsWindow::ServerLibraryLogPath();
const long long wireBuffers = PipeStatsWindow::CounterOrAbsent(window, "wbufs");
const long long livePeak = PipeStatsWindow::CounterOrAbsent(window, "wlivepk");
const long long deferredPeak = PipeStatsWindow::CounterOrAbsent(window, "wdefpk");
const long long syncs = PipeStatsWindow::CounterOrAbsent(window, "wdefsync");
ASSERT_GT(wireBuffers, 0) << "the server published no wbufs= gauge: " << window.line;
ASSERT_GE(deferredPeak, 0) << window.line;
RecordProperty("wire_buffers", static_cast<int>(wireBuffers));
RecordProperty("wire_stores_peak", static_cast<int>(livePeak));
RecordProperty("wire_deferred_bytes_peak", std::to_string(deferredPeak).c_str());
RecordProperty("wire_deferred_syncs", static_cast<int>(syncs));
// MOBILEGL_IPC_WIRE_DEFERRED_MB=0 is the knob's negative control (no forced sync). Such
// a run is held to the lane's own 8 MiB, so that what goes red is the server's
// numbers and not a precondition of this case.
const std::uint64_t configured = DeferredBudgetBytes();
const std::uint64_t budget = configured != 0 ? configured : 8u * kMiB;
// One store past the budget is the most a park can add before the watermark answers it.
const long long deferredBound = static_cast<long long>(budget + kDrawnStoreBytes);
EXPECT_LE(deferredPeak, deferredBound)
<< "the Magma server parked " << deferredPeak << " bytes of orphaned stores inside one "
"frame against a MOBILEGL_IPC_WIRE_DEFERRED_MB budget of " << budget
<< " bytes (+ one " << kDrawnStoreBytes << "-byte store). " << window.line;
const long long liveBound =
wireBuffers + static_cast<long long>(budget / kDrawnStoreBytes) + 2;
EXPECT_LE(livePeak, liveBound)
<< "the Magma server held " << livePeak << " VkBuffers at once; the records ("
<< wireBuffers << ") plus a budget's worth of parked stores allow " << liveBound
<< ". " << window.line;
}
// --------------------------------------------------------------------------------------
// CASE 3. 3000 respecify-and-draw rounds of a 256-byte store in one frame. The byte
// budget never trips (750 KB against 8 MiB), which is the bsl-esc-menu-854 shape the
// count ceiling exists for: one stretch there parked 12,498 stores in 39.5 MB. Before M2
// every one of the 3000 was alive at the end of the loop.
TEST_F(MagmaWireReclaimScenario, ManySmallRespecifyAndDrawRoundsStayUnderTheStoreCountCeiling) {
if (!Ready() || IsSkipped()) return;
const PipeStatsWindow::LogMark mark = SetupFrame();
ClearTo(0.0f, 0.0f, 0.0f, 0.0f);
std::vector<std::uint8_t> bytes(kSmallDrawnStoreBytes, 0);
for (int i = 0; i < kSmallDrawnRespecifies; ++i) {
Respecify(bytes, 0, kWidth);
DrawStrip(i % 200);
}
const Image image = ReadPixels(kWidth, kHeight);
ASSERT_EQ(FirstGLError(), GLenum(GL_NO_ERROR));
const Rgba8 want = StripColor((kSmallDrawnRespecifies - 1) % 200);
EXPECT_TRUE(Near(image.At(kWidth / 2, kHeight / 2), want))
<< "read " << image.At(kWidth / 2, kHeight / 2) << ", wanted " << want
<< ": the last of " << kSmallDrawnRespecifies << " draws did not land on top";
const PipeStatsWindow::Window window = CloseFrameAndReadServerWindow(mark);
ASSERT_TRUE(window.found) << "no 'MGPipe stats:' window in the server log "
<< PipeStatsWindow::ServerLibraryLogPath();
const long long wireBuffers = PipeStatsWindow::CounterOrAbsent(window, "wbufs");
const long long livePeak = PipeStatsWindow::CounterOrAbsent(window, "wlivepk");
const long long syncs = PipeStatsWindow::CounterOrAbsent(window, "wdefsync");
ASSERT_GT(wireBuffers, 0) << "the server published no wbufs= gauge: " << window.line;
// An absent gauge reads -1, which would pass the one-sided bound below as a leak that
// never happened; the peak has to be a reading before it can be a small one.
ASSERT_GE(livePeak, 0) << "the server published no wlivepk= gauge: " << window.line;
RecordProperty("wire_buffers", static_cast<int>(wireBuffers));
RecordProperty("wire_stores_peak", static_cast<int>(livePeak));
RecordProperty("wire_deferred_syncs", static_cast<int>(syncs));
// The ceiling is checked after the park that crosses it, so one store past it plus the
// records is the most the arm can hold.
const long long liveBound = wireBuffers + kDeferredCountCeiling + 2;
EXPECT_LE(livePeak, liveBound)
<< "the Magma server held " << livePeak << " VkBuffers at once after "
<< kSmallDrawnRespecifies << " small respecify-and-draw rounds in one frame; the "
"records plus the " << kDeferredCountCeiling << "-store ceiling allow " << liveBound
<< ". A count that tracks the rounds is the bsl-esc-menu-854 shape. " << window.line;
}
// --------------------------------------------------------------------------------------
// CASE 4 (round 2, ID-P7-43). THE EARLY RECLAIM MUST NOT LEAVE A DESCRIPTOR MEMO NAMING
// THE DEAD STORE'S HANDLE. UniformManager memoizes descriptor sets by VkBuffer handle
// (m_descriptorReuseMemo's signature hashes the VkDescriptorBufferInfo words,
// FastRebindMemo compares uboBuffer) and clears them at the frame boundary - before M2
// the only point a wire store could die. With M2 a store dies at a park mid-frame, the
// next mint gets its handle value back (a heap pointer under lavapipe; glibc's tcache
// hands the last chunk freed to the next same-size malloc), and a draw that resolves the
// SAME (handle, range) reuses a set baked to the dead store's memory: wrong bytes, no
// Fatal. The fix folds VkBufferManager's wire-store destroy epoch into both memos.
//
// THE SHAPE, all in one frame, every step deterministic (no sleep, no fence poll race):
// 1. D1 draws with UBO store S1 (256 B, colour A): the memo now maps S1's handle to
// D1's descriptor set.
// 2. glBufferData(U, 0) orphans S1 - parked, tagged for the batch D1 is recorded in -
// and mints nothing in its place, so the handle value stays free once S1 dies.
// 3. glClientWaitSync(fence, FLUSH_COMMANDS, 0) SUBMITS that batch without waiting:
// the review's "flush without wait".
// 4. glBufferSubData on the vertex store D1 named records a staged copy, so the
// recording is pending again and the wait in 5 CANNOT take the frame-boundary
// drain that would clear the memos (TryDrainFrameTransients refuses with work
// pending).
// 5. glClientWaitSync(fence, 0, 2 s): D1's batch has retired; the memos are intact.
// 6. glBufferData(V, 0) parks the vertex store, and THAT park's sweep finds S1's
// batch complete and destroys S1: its handle value is free, its memory a 256-byte
// hole bounded by the pin store minted right after it.
// 7. glBufferData(U, 64 KiB, colour B) mints through the freed handle value; 64 KiB
// cannot land in the hole, so the dead store's bytes stay where D1's set points.
// 8. D2 draws with U: it resolves (S1's handle value, 16 bytes) - a memo hit before
// the fix, and D1's set reads A off the dead store.
// The pixel is the whole assertion: it has to be B, the bytes the live store holds.
TEST_F(MagmaWireReclaimScenario, ADrawAfterTheEarlyReclaimFollowsTheNewStoreNotTheMemoizedHandle) {
if (!Ready() || IsSkipped()) return;
std::string error;
const GLuint program = CompileProgram(kVertex, kBlockFragment, &error);
ASSERT_NE(program, 0u) << error;
const GLuint block = glGetUniformBlockIndex(program, "Block");
ASSERT_NE(block, GLuint(GL_INVALID_INDEX));
glUniformBlockBinding(program, block, 0);
const PipeStatsWindow::LogMark mark = SetupFrame();
ClearTo(0.0f, 0.0f, 0.0f, 0.0f);
const Rgba8 colourA{200, 60, 30, 255};
const Rgba8 colourB{60, 200, 90, 255};
const auto blockBytes = [](std::size_t size, const Rgba8& c) {
// The block's vec4 at offset 0; every other slot holds a colour no step draws, so a
// read off any other offset is as visible as a read off the dead store.
std::vector<std::uint8_t> bytes(size, 0);
float* f = reinterpret_cast<float*>(bytes.data());
for (std::size_t i = 0; i + 4 <= size / sizeof(float); i += 4) {
f[i] = 1.0f, f[i + 1] = 0.0f, f[i + 2] = 1.0f, f[i + 3] = 1.0f;
}
f[0] = c.r / 255.0f, f[1] = c.g / 255.0f, f[2] = c.b / 255.0f, f[3] = 1.0f;
return bytes;
};
// Step 1's stores, in this order: S1, then the pin right after it, then the vertex
// quad D1 names (m_buffer, a store this frame's recording will name and step 6 parks).
GLuint ubo = 0, pin = 0;
glGenBuffers(1, &ubo);
glGenBuffers(1, &pin);
glBindBuffer(GL_UNIFORM_BUFFER, ubo);
const std::vector<std::uint8_t> bytesA = blockBytes(kAbaDeadStoreBytes, colourA);
glBufferData(GL_UNIFORM_BUFFER, GLsizeiptr(bytesA.size()), bytesA.data(), GL_DYNAMIC_DRAW);
glBindBufferBase(GL_UNIFORM_BUFFER, 0, ubo);
glBindBuffer(GL_COPY_WRITE_BUFFER, pin);
glBufferData(GL_COPY_WRITE_BUFFER, GLsizeiptr(kAbaPinStoreBytes), nullptr, GL_STATIC_DRAW);
std::vector<std::uint8_t> quad(kUndrawnStoreBytes, 0);
glBindBuffer(GL_ARRAY_BUFFER, m_buffer);
Respecify(quad, 0, kWidth);
glUseProgram(program);
glDrawArrays(GL_TRIANGLES, 0, 6);
// Step 2: S1 orphaned, nothing minted.
glBindBuffer(GL_UNIFORM_BUFFER, ubo);
glBufferData(GL_UNIFORM_BUFFER, 0, nullptr, GL_DYNAMIC_DRAW);
// Step 3: the batch D1 is in, submitted and not waited for.
GLsync fence = glFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0);
ASSERT_NE(fence, nullptr);
const GLenum flushed = glClientWaitSync(fence, GL_SYNC_FLUSH_COMMANDS_BIT, 0);
RecordProperty("flush_wait_result", static_cast<int>(flushed));
// Step 4: a recorded copy into the busy vertex store keeps the recording pending.
glBindBuffer(GL_ARRAY_BUFFER, m_buffer);
glBufferSubData(GL_ARRAY_BUFFER, 0, 4, quad.data());
// Step 5: D1's batch retires; the memos survive because step 4 is still recorded.
const GLenum waited = glClientWaitSync(fence, 0, kAbaWaitNs);
ASSERT_TRUE(waited == GL_ALREADY_SIGNALED || waited == GL_CONDITION_SATISFIED)
<< "glClientWaitSync returned " << waited << ": the batch that drew from the first "
"store did not retire within " << (kAbaWaitNs / 1000000) << " ms";
// Step 6: the vertex store's park sweeps S1 out - the destroy the memos must notice.
glBufferData(GL_ARRAY_BUFFER, 0, nullptr, GL_STREAM_DRAW);
// Step 7: a new store through the freed handle value, holding B.
glBindBuffer(GL_UNIFORM_BUFFER, ubo);
const std::vector<std::uint8_t> bytesB = blockBytes(kAbaNewStoreBytes, colourB);
glBufferData(GL_UNIFORM_BUFFER, GLsizeiptr(bytesB.size()), bytesB.data(), GL_DYNAMIC_DRAW);
glBindBufferBase(GL_UNIFORM_BUFFER, 0, ubo);
glBindBuffer(GL_ARRAY_BUFFER, m_buffer);
Respecify(quad, 0, kWidth);
// Step 8.
glUseProgram(program);
glDrawArrays(GL_TRIANGLES, 0, 6);
const Image image = ReadPixels(kWidth, kHeight);
ASSERT_EQ(FirstGLError(), GLenum(GL_NO_ERROR));
const Rgba8 got = image.At(kWidth / 2, kHeight / 2);
EXPECT_TRUE(Near(got, colourB))
<< "read " << got << ", wanted " << colourB << " (the live store's bytes). " << colourA
<< " is the DEAD store's colour: the draw through the re-minted VkBuffer handle reused a "
"descriptor set memoized under the first store's handle and read its freed memory "
"(ID-P7-43); anything else is that memory already reused";
glDeleteSync(fence);
glDeleteBuffers(1, &pin);
glDeleteBuffers(1, &ubo);
glDeleteProgram(program);
const PipeStatsWindow::Window window = CloseFrameAndReadServerWindow(mark);
if (window.found) RecordProperty("wire_stores_peak",
static_cast<int>(PipeStatsWindow::CounterOrAbsent(window, "wlivepk")));
}
// M3: a fixed SSBO store and one live layout, but 2049 distinct aligned
// windows force 2049 descriptor writes before a present. M2's buffer-store
// ceiling cannot help: no store is orphaned. The first 2048 sets must be
// retired by submit index before their per-layout cursor rewinds, and the
// last draw must read the last window rather than a set still in flight.
TEST_F(MagmaWireReclaimScenario, DescriptorSetsRewindInsideOneLongFrameAfterTheirSubmitRetires) {
if (!Ready() || IsSkipped()) return;
std::string error;
const GLuint program = CompileProgram(kStorageVertex, kStorageFragment, &error);
ASSERT_NE(program, 0u) << error;
const PipeStatsWindow::LogMark mark = SetupFrame();
ClearTo(0.0f, 0.0f, 0.0f, 0.0f);
std::vector<std::uint8_t> quad(kUndrawnStoreBytes, 0);
glBindBuffer(GL_ARRAY_BUFFER, m_buffer);
Respecify(quad, 0, kWidth);
GLint alignment = 0;
glGetIntegerv(GL_SHADER_STORAGE_BUFFER_OFFSET_ALIGNMENT, &alignment);
ASSERT_GT(alignment, 0);
const std::size_t stride = static_cast<std::size_t>(std::max(alignment, 16));
std::vector<std::uint8_t> bytes(stride * kDescriptorDraws, 0);
const Rgba8 last{60, 200, 90, 255};
for (int i = 0; i < kDescriptorDraws; ++i) {
const float color[4] = {i + 1 == kDescriptorDraws ? last.r / 255.0f : 200.0f / 255.0f,
i + 1 == kDescriptorDraws ? last.g / 255.0f : 60.0f / 255.0f,
i + 1 == kDescriptorDraws ? last.b / 255.0f : 30.0f / 255.0f, 1.0f};
std::memcpy(bytes.data() + stride * i, color, sizeof(color));
}
GLuint storage = 0;
glGenBuffers(1, &storage);
glBindBuffer(GL_SHADER_STORAGE_BUFFER, storage);
glBufferData(GL_SHADER_STORAGE_BUFFER, static_cast<GLsizeiptr>(bytes.size()), bytes.data(), GL_STATIC_DRAW);
glUseProgram(program);
for (int i = 0; i < kDescriptorDraws; ++i) {
glBindBufferRange(GL_SHADER_STORAGE_BUFFER, 0, storage,
static_cast<GLintptr>(stride * i), 16);
glDrawArrays(GL_TRIANGLES, 0, 6);
}
const Image image = ReadPixels(kWidth, kHeight);
EXPECT_EQ(FirstGLError(), GLenum(GL_NO_ERROR));
EXPECT_TRUE(Near(image.At(kWidth / 2, kHeight / 2), last))
<< "the last SSBO window was not read after descriptor recycling";
(void)CloseFrameAndReadServerWindow(mark);
const std::string serverLog = PipeStatsWindow::ReadServerLogSince(mark);
const std::string marker = "Magma descriptor rewind:";
const std::size_t rewind = serverLog.find(marker);
ASSERT_NE(rewind, std::string::npos) << "2049 distinct descriptor writes in one frame did not rewind";
const std::size_t cachedAt = serverLog.find(" cached=", rewind);
ASSERT_NE(cachedAt, std::string::npos) << serverLog.substr(rewind, 160);
const unsigned long long cached = std::strtoull(serverLog.c_str() + cachedAt + 8, nullptr, 10);
EXPECT_LE(cached, 2080ull) << "the fixed-layout cache grew beyond the 2048-set epoch: "
<< serverLog.substr(rewind, 160);
RecordProperty("descriptor_cached_at_rewind", static_cast<int>(cached));
glDeleteBuffers(1, &storage);
glDeleteProgram(program);
}
} // namespace
} // namespace MGITest
@@ -188,21 +188,11 @@ void main() { oColor = texture(uTex, vUv); }
// ORDER - see the direction check below.
//
// Espryt's text is one MGLOG_E from the helper the three dependent families share
// (Managers.cpp, PipeSubsystemDependencyMissing). Since P3b/P4b wave 2-D package D3
// (1c36987e, ID-P7-28) that helper reads the family's row from MG_Pipe/SubsystemDeps.def
// instead of taking one hand-written dependency bit, and it computes the missing bits
// rather than naming them: "MGPipe: <A> (bit N) is set but MOBILEGL_PIPE_PUSH=0x<mask>
// does not carry every bit MG_Pipe/SubsystemDeps.def says it requires (requires 0x<R>,
// missing 0x<M>): <why> - REFUSING the dependent bit and running the legacy arm. Set every
// bit of the row, or clear the family's own". The SET bit is accepted in three spellings -
// the constant's name, "(bit N)", and the hexadecimal mask - and the NEEDED bit is read
// from the one place the helper names it, the "missing 0x<M>)" field, so the assertion
// pins the DECISION and the DIRECTION, and not the family-specific prose in <why>.
//
// THE OLD SENTENCE ("<A> (bit N) is set but <B> (bit M) is clear; ...") IS GONE FROM THE
// TREE, and this matcher used to require its " is clear": after D3 both refusal lanes went
// red with the refusal sitting on the ERROR line the lane was reading (CI run
// 35792628470 onward). Nothing about the decision changed - only the wording did.
// (Managers.cpp, PipeSubsystemDependencyMissing): "MGPipe: <A> (bit N) is set but <B>
// (bit M) is clear; <why> - REFUSING the dependent bit and running the legacy arm. Set
// both bits, or clear both". Three spellings are accepted per bit - the constant's name,
// "(bit N)", and the hexadecimal mask - so the assertion pins the DECISION and the
// DIRECTION, and not the family-specific prose in <why>.
//
// THE DIRECTION IS THE HALF THIS FILE USED TO BE MISSING (review F-v2-m1). The first form
// of the matcher asked "does the line name bit A?" AND "does the line name bit B?", which
@@ -217,18 +207,12 @@ void main() { oColor = texture(uTex, vUv); }
// away at all times.
//
// What makes the direction readable is the sentence's own shape: the SET bit is named
// before " is set but " and the NEEDED bit in the "missing 0x<M>)" field after it. So the
// check is three offsets in strictly increasing order, and it is the sentence Espryt
// emits rather than a re-statement of it. The field is matched WITH its closing
// parenthesis, so "missing 0x400)" cannot be satisfied by "missing 0x4000)" (bit 14), and
// the mirror sentence cannot satisfy it either: there the SET-bit spellings first occur
// inside that field, after " is set but ".
// before " is set but " and the NEEDED bit between that and " is clear". So the check is
// four offsets in strictly increasing order, and it is the sentence Espryt emits rather
// than a re-statement of it.
constexpr const char* kSaysItRefused = "REFUSING the dependent bit and running the legacy arm";
constexpr const char* kSaysWhichIsSet = " is set but ";
std::string SaysWhichIsMissing(const std::string& neededMaskHex) {
return "missing " + neededMaskHex + ")";
}
constexpr const char* kSaysWhichIsClear = " is clear";
// The earliest offset at which any accepted spelling of one bit appears, or npos. The
// EARLIEST rather than any: a spelling that also occurs later in <why> (Espryt's
@@ -250,8 +234,7 @@ void main() { oColor = texture(uTex, vUv); }
// what it found: a reader of a green refusal lane must be able to see the sentence.
std::string FindTheRefusalLine(const std::string& log,
const std::vector<std::string>& bitThatWasSet,
const std::string& neededMaskHex) {
const std::string missingField = SaysWhichIsMissing(neededMaskHex);
const std::vector<std::string>& bitThatWasNeeded) {
std::size_t pos = 0;
while (pos <= log.size()) {
const std::size_t newline = log.find('\n', pos);
@@ -261,15 +244,18 @@ void main() { oColor = texture(uTex, vUv); }
const std::size_t refusedAt = line.find(kSaysItRefused);
const std::size_t setAt = EarliestSpellingOffset(line, bitThatWasSet);
const std::size_t setClauseAt = line.find(kSaysWhichIsSet);
const std::size_t missingAt = line.find(missingField);
const std::size_t neededAt = EarliestSpellingOffset(line, bitThatWasNeeded);
const std::size_t clearClauseAt = line.find(kSaysWhichIsClear);
const bool everyPartIsThere =
refusedAt != std::string::npos && setAt != std::string::npos &&
setClauseAt != std::string::npos && missingAt != std::string::npos;
// "<set bit> ... is set but ... missing <needed bit>)", strictly in that order.
// Swapping the caller's two arguments breaks the chain, which is the whole of
// F-v2-m1.
setClauseAt != std::string::npos && neededAt != std::string::npos &&
clearClauseAt != std::string::npos;
// "<set bit> ... is set but ... <needed bit> ... is clear", strictly in that
// order. Swapping the caller's two arguments breaks the chain, which is the
// whole of F-v2-m1.
const bool inTheRightDirection =
everyPartIsThere && setAt < setClauseAt && setClauseAt < missingAt;
everyPartIsThere && setAt < setClauseAt && setClauseAt < neededAt &&
neededAt < clearClauseAt;
if (atErrorSeverity && inTheRightDirection) {
return line;
}
@@ -280,18 +266,14 @@ void main() { oColor = texture(uTex, vUv); }
}
// The three accepted spellings of each of the two P4a bits this file's two refusal lanes
// are about, when the bit is the one that was SET; the mask alone when it is the one that
// was NEEDED (the helper prints `required & ~mask` with %llx). MGPipe.h: bit 10 =
// kMGPipeSubsystemTextureResources = 0x400, bit 11 = kMGPipeSubsystemSamplers = 0x800.
constexpr const char* kSamplerBitMask = "0x800";
constexpr const char* kTextureResourceBitMask = "0x400";
// are about. MGPipe.h: bit 10 = kMGPipeSubsystemTextureResources = 0x400,
// bit 11 = kMGPipeSubsystemSamplers = 0x800.
std::vector<std::string> SamplerBitSpellings() {
return {"kMGPipeSubsystemSamplers", "(bit 11)", kSamplerBitMask};
return {"kMGPipeSubsystemSamplers", "(bit 11)", "0x800"};
}
std::vector<std::string> TextureResourceBitSpellings() {
return {"kMGPipeSubsystemTextureResources", "(bit 10)", kTextureResourceBitMask};
return {"kMGPipeSubsystemTextureResources", "(bit 10)", "0x400"};
}
class ObjectSubsystemControlScenario : public ScenarioTest {
@@ -644,16 +626,15 @@ void main() { oColor = texture(uTex, vUv); }
// FindTheRefusalLine: a substring search over the whole file cannot go red for the
// reason this case claims (F-M6).
const std::string refusal =
FindTheRefusalLine(log, SamplerBitSpellings(), kTextureResourceBitMask);
FindTheRefusalLine(log, SamplerBitSpellings(), TextureResourceBitSpellings());
EXPECT_FALSE(refusal.empty())
<< "MOBILEGL_PIPE_PUSH=0x9ff sets the sampler subsystem (bit 11) without the texture "
"resource subsystem (bit 10) it depends on, and no single ERROR line of the "
"library's log both says it REFUSED and names the two bits. D-K2 requires ONE "
"MGLOG_E naming both and a fall back to the legacy sampler arm; a mask that is "
"silently half-honoured is the failure this case exists to catch, and it is "
"invisible in the pixels by construction. The set bit may be spelled by the "
"constant's name, '(bit 11)' or '0x800', before ' is set but '; the needed bit "
"must be the helper's 'missing 0x400)' field after it. The log was "
"invisible in the pixels by construction. Accepted spellings per bit are the "
"constant's name, '(bit 11)' / '(bit 10)', and '0x800' / '0x400'. The log was "
<< log.size() << " bytes and is at " << PipeStatsWindow::LibraryLogPath() << ".";
if (!refusal.empty()) {
// Printed on the pass as well: a reader of a green refusal lane must be able to
@@ -761,17 +742,15 @@ void main() { oColor = texture(uTex, vUv); }
// The same line shape as the 0x9ff arm, with the two bits' roles swapped: the bit that
// was SET is the texture-resource one and the bit it NEEDED is the sampler one. The
// swap is now a REAL difference between the two cases: FindTheRefusalLine requires the
// set bit to be named before " is set but " and the needed bit in the "missing 0x<M>)"
// field after it (F-v2-m1), so this call and the 0x9ff one above accept disjoint
// sentences. Espryt's is "kMGPipeSubsystemTextureResources (bit 10) is set but
// MOBILEGL_PIPE_PUSH=0x5ff does not carry every bit MG_Pipe/SubsystemDeps.def says it
// requires (requires 0x880, missing 0x800): <the row's why> - REFUSING the dependent
// bit and running the legacy arm. Set every bit of the row, or clear the family's own"
// (Managers.cpp, PipeSubsystemDependencyMissing via
// ResolveTextureResourceSubsystemArm). The row requires bit 7 as well; 0x5ff carries
// it, so the missing field is bit 11 alone.
// set bit to be named before " is set but " and the needed bit after it (F-v2-m1), so
// this call and the 0x9ff one above accept disjoint sentences. Espryt's is
// "kMGPipeSubsystemTextureResources (bit 10) is set but kMGPipeSubsystemSamplers
// (bit 11) is clear; MGPTextureParams::BuiltinSampler is a SamplerCso handle, only
// bit 11 mints sampler CSOs, and the applier's verdict for a null one is
// Fatal{ProtocolCorruption} - REFUSING the dependent bit and running the legacy arm.
// Set both bits, or clear both" (Managers.cpp, ResolveTextureResourceSubsystemArm).
const std::string refusal =
FindTheRefusalLine(log, TextureResourceBitSpellings(), kSamplerBitMask);
FindTheRefusalLine(log, TextureResourceBitSpellings(), SamplerBitSpellings());
EXPECT_FALSE(refusal.empty())
<< "MOBILEGL_PIPE_PUSH=0x5ff sets the texture resource subsystem (bit 10) without "
"the sampler subsystem (bit 11) that MGPTextureParams::BuiltinSampler depends on, "
@@ -779,9 +758,8 @@ void main() { oColor = texture(uTex, vUv); }
"two bits. Only bit 11 mints sampler CSOs, so every set_texture_params emitted "
"under this mask would carry a null BuiltinSampler and the applier's Fatal is the "
"next thing that happens - which is why this pair is a refusal at bring-up and "
"not the harmless mirror of the 0x9ff one. The set bit may be spelled by the "
"constant's name, '(bit 10)' or '0x400', before ' is set but '; the needed bit "
"must be the helper's 'missing 0x800)' field after it. The log was "
"not the harmless mirror of the 0x9ff one. Accepted spellings per bit are the "
"constant's name, '(bit 10)' / '(bit 11)', and '0x400' / '0x800'. The log was "
<< log.size() << " bytes and is at " << PipeStatsWindow::LibraryLogPath() << ".";
if (!refusal.empty()) {
std::cout << "[ ObjectSubsystemControl ] refusal line: " << refusal << std::endl;
@@ -215,32 +215,6 @@ void main() { oColor = texture(uTex, vUv); }
<< " (" << image.ColorName(cx, cy) << ")" << std::endl;
}
// A REAL BOUNDARY BEFORE ANY WHITE-BOX READ OF THE APPLIER (P12).
//
// The reads below (RecordIsReadable and its callers) read state that lives in the
// APPLIER, and the records they assert about are the mask moves a sticky-bit change
// produces - `resource_respecify` rows. P12 made that row FIRE-AND-FORGET for a texture
// whose existence is already confirmed (PipeRoute.h's
// MGPipeResourceRespecifyWantsItsReply: the answer only ever said "the applier holds a
// record for this handle", which the client's own publication latch already answers), so
// the client no longer waits, and a read taken immediately after the setter now races
// the apply thread. MEASURED: DirectGLES.P4aFinalFixScenario's DSA case red with
// `Serial` 7 vs 7 and the RENDER_TARGET bit clear, twice in a row, on the inproc arm -
// and it is exactly the failure the CtWireScenario death gates had, from the same cause.
//
// A READBACK IS THE BOUNDARY THAT HOLDS ON EVERY ARM: ReadPixels is
// kReplySlot|kWaitReply, the client blocks on its answer, and an answer is posted only
// after its record has been APPLIED - so every record published before it, the mask move
// included, is applied too. (The harness's applied-seq fence would be the other choice
// and it is right for inproc only; it times out on the spawn/tcp arms, which this file
// has no registrations on today but may grow.)
void FenceTheApplierRead() {
GLubyte fencePixel[4]{};
glReadPixels(0, 0, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, fencePixel);
ASSERT_EQ(FirstGLError(), GLenum(GL_NO_ERROR))
<< "the applier-read fence left a GL error behind";
}
// The white-box gate of the M-A case: true when the applier holds a record for the
// texture in this process. Prints the decline.
bool RecordIsReadable(unsigned glTextureName, const char* what, PipeTextureResourceRecordPeek* out) {
@@ -589,7 +563,6 @@ void main() { oColor = texture(uTex, vUv); }
(void)uploadsReadable;
glBindImageTexture(0, texture, 0, GL_FALSE, 0, GL_READ_ONLY, GL_RGBA8);
ASSERT_EQ(FirstGLError(), GLenum(GL_NO_ERROR));
FenceTheApplierRead();
if (readable) {
ASSERT_TRUE(PeekPipeTextureResourceRecord(texture, &record));
EXPECT_EQ(record.ImageBindableHint, 1u)
@@ -664,7 +637,6 @@ void main() { oColor = texture(uTex, vUv); }
glCreateFramebuffers(1, &namedFbo);
glNamedFramebufferTexture(namedFbo, GL_COLOR_ATTACHMENT0, early, 0);
ASSERT_EQ(FirstGLError(), GLenum(GL_NO_ERROR));
FenceTheApplierRead();
if (earlyReadable) {
ASSERT_TRUE(PeekPipeTextureResourceRecord(early, &earlyRecord));
EXPECT_NE(earlyRecord.BindMask & (1u << 7), 0u)
@@ -25,15 +25,6 @@
// perturbed before the entry compare, so a comparator that works must
// report Fatal{PipeVerifyDiffer, "<Field>@<Verb>"}. A comparator that
// compares nothing stays quiet and this case goes red.
// CorruptedFieldIsReportedOnTheServerRead
// - the same control aimed at the OTHER comparator (P7 wave 3, V1).
// The entry compare runs on the client thread at a verb boundary; the
// compare-at-read hook runs on the server's apply thread at every
// backend read, and until this case existed nothing could tell a hook
// that had stopped comparing from a hook with nothing to say. It
// reads the SERVER role's half of the log, because with the knob
// armed the client reports the same field and a union search would be
// satisfied by the arm that is not under test.
//
// The observable is the library's own log, because MG_Config is not reachable from this module
// (on Android it links the SHIPPING libMobileGL.so, built -fvisibility=hidden) and the arming
@@ -111,25 +102,6 @@ void main() { o_color = vec4(0.25, 0.5, 0.75, 1.0); }
return value != nullptr && *value != '\0';
}
// The number of LINES in `text` that carry `needle` and `where=read`: one per backend read
// the compare-at-read hook reported for that field and verb (ReportDivergence is a single
// MGLOG_F, so a report never spans lines and two reports never share one).
std::size_t CountReadReports(const std::string& text, const std::string& needle) {
std::size_t count = 0;
std::size_t pos = 0;
while (pos < text.size()) {
const std::size_t eol = text.find('\n', pos);
const std::string line =
text.substr(pos, eol == std::string::npos ? std::string::npos : eol - pos);
if (line.find(needle) != std::string::npos && line.find("where=read") != std::string::npos) {
++count;
}
if (eol == std::string::npos) break;
pos = eol + 1;
}
return count;
}
class PipeVerifyArmingScenario : public ScenarioTest {
protected:
// The library log this process is writing, or an empty path when none was configured.
@@ -293,107 +265,5 @@ void main() { o_color = vec4(0.25, 0.5, 0.75, 1.0); }
<< appended;
}
// NEGATIVE CONTROL A ON THE OTHER ARM (P7 wave 3, V1): the COMPARE-AT-READ hook, on the
// SERVER's apply thread, inside the ID-49 neutral pack window.
//
// WHY THE CASE ABOVE DOES NOT COVER IT. MOBILEGL_PIPE_VERIFY_CORRUPT used to perturb only
// EntryCompare's snapshot, so every red it could produce came from the CLIENT thread at a
// verb boundary and said `where=entry`. The hook that runs on every backend read - the
// whole of the split lane's per-read work, and the only comparator the server's apply
// thread ever runs - had no falsifier: a hook that had stopped comparing looked exactly
// like a hook with nothing to report, and the lane would have been just as green.
//
// WHY THIS FIELD AND THIS VERB. GetPixelStoreParameters@ReadPixels is where the hook does
// its one piece of ARM-SPECIFIC reasoning (PipeFill.cpp's
// ServerReadsInsideTheNeutralPackWindow): the applier reads the backend with the neutral
// pack, so inside that window the oracle for the pack half is the neutral pack rather than
// the live context. A control aimed anywhere else would leave exactly that branch unproven.
//
// THE SERVER HALF, NOT THE UNION. With this knob armed the client's own entry compare
// reports `GetPixelStoreParameters@...` too, in the client's log, so a whole-lane search
// would be satisfied without the server having run anything at all. The assertion below
// reads the server role's half and nothing else.
//
// MOBILEGL_PIPE_VERIFY_FATAL=0, for CorruptedFieldIsReported's reason and one more: the
// client's entry compare on the ReadPixels verb fires FIRST (kReadback's fill mask carries
// this field, FillPoints.def), so with FATAL at its default the process would abort before
// the server ever reached the read.
TEST_F(PipeVerifyArmingScenario, CorruptedFieldIsReportedOnTheServerRead) {
if (!Ready()) return;
constexpr const char* kPackField = "GetPixelStoreParameters";
const char* knob = std::getenv("MOBILEGL_PIPE_VERIFY_CORRUPT");
if (knob == nullptr || std::string(knob) != kPackField) {
GTEST_SKIP() << "this case is the compare-at-read hook's negative control and needs "
"MOBILEGL_PIPE_VERIFY_CORRUPT=" << kPackField << " for the whole "
"process, which is what the VerifySplitReadCorrupted. ctest entries "
"set; no other field is read by the server inside a window whose "
"oracle the hook rewrites";
}
if (AmbientQuirkFromEnvironment("MOBILEGL_PIPE_VERIFY") != AmbientQuirk::On) {
GTEST_SKIP() << "MOBILEGL_PIPE_VERIFY_CORRUPT is set but MOBILEGL_PIPE_VERIFY is not, so "
"the comparator is dormant and there is nothing to corrupt";
}
if (LibraryLogPath().empty()) {
GTEST_SKIP() << "MOBILEGL_LOG_FILE_PATH is not set, so the library has nowhere to report "
"the divergence; the VerifySplitReadCorrupted. ctest entries set both";
}
if (MGITest::PipeStatsWindow::ServerLibraryLogPath().empty()) {
GTEST_SKIP() << "this build writes no server-role log, so there is no half in which the "
"server's own report could be told apart from the client's; the hook's "
"read arm is registered on the split (inproc) lane only";
}
const MGITest::PipeStatsWindow::LogMark before = LibraryLogMark();
ASSERT_NO_FATAL_FAILURE(DrawOneFrame());
const std::string server = MGITest::PipeStatsWindow::ReadServerLogSince(before);
const std::string expected =
std::string(kDifferPrefix) + ", \"" + kPackField + "@ReadPixels\"";
const std::size_t at = server.find(expected);
ASSERT_NE(at, std::string::npos)
<< "MOBILEGL_PIPE_VERIFY_CORRUPT=" << kPackField << " perturbs the hook's ORACLE at "
"every backend read of that field, and the server's read_pixels reads it under "
"the server's own stamp - so the server role's log had to carry " << expected
<< ", ...}. It carried nothing: either the compare-at-read hook is not running on "
"the apply thread, or the neutral-pack window swallowed the perturbation, and "
"in both cases every per-read green in this lane is green for no reason. Server "
"half of the log appended by this case:\n"
<< server;
const std::size_t eol = server.find('\n', at);
const std::string line =
server.substr(at, eol == std::string::npos ? std::string::npos : eol - at);
EXPECT_NE(line.find("where=read"), std::string::npos)
<< "the server half reported the corrupted field, but not from the compare-at-read "
"arm - `where=` says which comparator spoke, and only `read` is this case's "
"subject. Line:\n"
<< line;
// TWO REPORTS, NOT ONE (V1 fix round 2) - the count is what makes BOTH perturbation
// blocks in the hook load-bearing. The server reads this field twice inside the
// ReadPixels window, and both reads sit inside the hook's neutral-pack branch:
// PipeApplier::read_pixels saves the application's pack BEFORE it installs the neutral
// one, and the backend's ReadPixels reads the field AFTER. The hook's first perturbation
// is what turns the saved-pack read red (past the first compare, the application's
// pack against the neutral oracle differs on its own); only the perturbation re-applied
// after the window's overwrite can turn the post-install read red, because there the
// stored value IS the neutral pack. A control satisfied by ONE line is satisfied by
// either block alone and so falsified neither. Measured at landing the server half
// carries 3 (DirectGLES: the saved-pack read and TWO post-install reads) / 2
// (DirectVulkan: one of each). Removing the re-applied block drops both backends to
// 1; removing the first block drops DirectVulkan to 1 and leaves DirectGLES at 2, so
// the first block's falsifier is the DirectVulkan entry - which is why the CI step
// runs both backends and needs both.
const std::size_t reads = CountReadReports(server, expected);
EXPECT_GE(reads, std::size_t{2})
<< "the server half carries " << reads << " `where=read` report(s) for " << expected
<< ", ...}. The server reads that field twice inside the ReadPixels window (the "
"applier's saved-pack read and the backend's post-install read) and the hook "
"perturbs the oracle once per read, so fewer than two means one perturbation has "
"stopped reaching its read. Server half of the log appended by this case:\n"
<< server;
}
} // namespace
} // namespace MGITest
@@ -31,7 +31,6 @@
// and DirectVulkan is the built-in control.
#include <cstdint>
#include <cstring>
#include <string>
#include <vector>
@@ -258,117 +257,6 @@ namespace MGITest {
glDeleteTextures(1, &texture);
}
// THE ONE READBACK DESTINATION NOTHING COVERED (P3b/P4b espryt D1 slice 4): a bound
// GL_PIXEL_PACK_BUFFER, with a non-default GL_PACK_* state, read back afterwards through
// glMapBufferRange.
//
// The case above reads into a CLIENT POINTER, which under a transport is served by
// ScatterTightReadbackIntoPackState - a pure function with unit cover of its own. A PBO
// destination is a different half of the same seam and had none: the server reads with
// NEUTRAL pack state into a tight w*h*bpp reply (ID-49), and the CLIENT then services the
// PBO itself after the reply lands, uploading the tight rows one at a time at the stride the
// application's pack state implies (EmitTables.cpp's `if (pbo)` branch). Nothing in the tree
// ran that branch, and it is arithmetic - a stride, an alignment round-up, two skips and a
// buffer offset - which is the kind of code that is either exactly right or quietly wrong.
//
// WHAT MAKES IT A TEST RATHER THAN A SMOKE CHECK is the poison. Every byte of the buffer
// starts 0xCD; the rows land where the pack state says and NOTHING ELSE MOVES. A branch that
// uploaded the reply whole, or ignored the buffer offset, or rounded the stride the other
// way, writes over poison that this asserts is still there.
//
// The numbers are chosen so each term does something: ROW_LENGTH 5 at 4 bytes per pixel is
// 20, which ALIGNMENT 8 rounds up to a 24-byte stride (a stride equal to the row length would
// not tell a missing round-up from a present one); SKIP_ROWS 1 and SKIP_PIXELS 2 move the
// first pixel to byte 24 + 8 = 32 of the image; and the read is issued at buffer offset 16,
// so the first pixel lands at 48 and a branch that dropped the offset would land at 32.
TEST_F(PixelStoreSweepScenario, ReadPixelsIntoAPackBufferHonoursPackStateAndLeavesTheGapsAlone) {
if (!Ready()) return;
ResetAllPixelStoreModes();
constexpr int kW = 2;
constexpr int kH = 2;
constexpr GLint kAlignment = 8;
constexpr GLint kRowLength = 5;
constexpr GLint kSkipRows = 1;
constexpr GLint kSkipPixels = 2;
constexpr std::size_t kBpp = 4;
constexpr std::size_t kOffset = 16;
constexpr std::size_t kPboBytes = 256;
constexpr std::uint8_t kPoison = 0xCD;
// The same arithmetic GL defines and EmitTables.cpp implements, written out here rather
// than borrowed, so the test cannot agree with the code by construction.
constexpr std::size_t kStride = ((kRowLength * kBpp) + kAlignment - 1) / kAlignment * kAlignment;
constexpr std::size_t kFirst = kOffset + kSkipRows * kStride + kSkipPixels * kBpp;
static_assert(kStride == 24, "the alignment round-up must actually round");
static_assert(kFirst == 48, "the skips and the buffer offset must all move the first pixel");
// Four distinct opaque colours, so a row or a pixel landing in the wrong place is a
// wrong VALUE and not just a wrong offset.
const std::uint8_t texels[kW * kH * kBpp] = {
0x11, 0x22, 0x33, 0xFF, 0x44, 0x55, 0x66, 0xFF,
0x77, 0x88, 0x99, 0xFF, 0xAA, 0xBB, 0xCC, 0xFF,
};
GLuint texture = 0, framebuffer = 0, pbo = 0;
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, kW, kH, 0, GL_RGBA, GL_UNSIGNED_BYTE, texels);
glGenFramebuffers(1, &framebuffer);
glBindFramebuffer(GL_FRAMEBUFFER, framebuffer);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture, 0);
ASSERT_EQ(glCheckFramebufferStatus(GL_FRAMEBUFFER), GLenum(GL_FRAMEBUFFER_COMPLETE));
ASSERT_EQ(FirstGLError(), 0u);
const std::vector<std::uint8_t> poison(kPboBytes, kPoison);
glGenBuffers(1, &pbo);
glBindBuffer(GL_PIXEL_PACK_BUFFER, pbo);
glBufferData(GL_PIXEL_PACK_BUFFER, static_cast<GLsizeiptr>(kPboBytes), poison.data(), GL_STREAM_READ);
ASSERT_EQ(FirstGLError(), 0u);
glPixelStorei(GL_PACK_ALIGNMENT, kAlignment);
glPixelStorei(GL_PACK_ROW_LENGTH, kRowLength);
glPixelStorei(GL_PACK_SKIP_ROWS, kSkipRows);
glPixelStorei(GL_PACK_SKIP_PIXELS, kSkipPixels);
glReadPixels(0, 0, kW, kH, GL_RGBA, GL_UNSIGNED_BYTE,
reinterpret_cast<void*>(static_cast<std::uintptr_t>(kOffset)));
EXPECT_EQ(FirstGLError(), 0u);
ResetAllPixelStoreModes();
std::vector<std::uint8_t> readback(kPboBytes, 0);
const void* mapped =
glMapBufferRange(GL_PIXEL_PACK_BUFFER, 0, static_cast<GLsizeiptr>(kPboBytes), GL_MAP_READ_BIT);
ASSERT_NE(mapped, nullptr) << "the pack buffer could not be mapped for readback";
std::memcpy(readback.data(), mapped, kPboBytes);
glUnmapBuffer(GL_PIXEL_PACK_BUFFER);
// Every byte the pack state names carries its texel; every other byte is still poison.
std::vector<bool> written(kPboBytes, false);
for (int y = 0; y < kH; ++y) {
for (int x = 0; x < kW; ++x) {
for (std::size_t c = 0; c < kBpp; ++c) {
const std::size_t at = kFirst + static_cast<std::size_t>(y) * kStride +
static_cast<std::size_t>(x) * kBpp + c;
ASSERT_LT(at, kPboBytes);
written[at] = true;
EXPECT_EQ(readback[at], texels[(y * kW + x) * kBpp + c])
<< "pixel (" << x << ", " << y << ") component " << c << " at buffer byte " << at
<< (readback[at] == kPoison ? " is still the poison: nothing was written here" : "");
}
}
}
for (std::size_t i = 0; i < kPboBytes; ++i) {
if (written[i]) continue;
EXPECT_EQ(readback[i], kPoison)
<< "buffer byte " << i << " is outside every row the pack state names and must not have moved";
}
glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glDeleteBuffers(1, &pbo);
glDeleteFramebuffers(1, &framebuffer);
glDeleteTextures(1, &texture);
}
// The leak regression. Each iteration is one complete CTS inner step, and every readback has
// to be exactly the gradient THIS iteration uploaded - never the previous one's. Before the
// missing destructors were added, the driver-side framebuffer count grew without bound here.
@@ -81,38 +81,11 @@ extern char** environ;
namespace MGITest {
namespace {
// What the PoisonOmitted. ctest entries and the CI negative-control steps name. Each pair is
// What the PoisonOmitted. ctest entry and the CI negative-control step name. The pair is
// spelled here so the assertion below is about the exact string the poison contracts to
// print (ARCHITECTURE.md 9.2: Fatal{UnmigratedPipeInput, "<Field>@<Verb>"}).
//
// TWO PAIRS SINCE P7 WAVE 3, ONE PER ARM, because the first one is structurally inert on
// the split arm. GenerateMipmap:GetActiveTextureUnit is the monolith control: the monolith
// backend resolves the texture to mip through the active unit. Under a transport it does
// not - since P5c hd the server's generate_mipmap resolves the texture from the verb's own
// handle (MGPipeApplier().VerbMipRes) and never reads the active unit - so omitting that
// stamp is omitting a stamp nobody reads, and the child exits 0 (measured on
// integration-verify-split, both backends). ReadPixels:GetPixelStoreParameters is the
// split control: the server's read_pixels backend call DOES read the pack half through the
// accessor, under the server's own stamp, which honours the knob in a verify build
// (MG_Backend/MGPipe/PipeInputs.cpp's ServerPoisonOmission).
//
// AND EACH PAIR SAYS WHICH ROLE HAS TO FIRE (`FiresOnTheServer`), which is the whole point
// of the split pair and was not checked at all until P7 wave 3's V1 fix round. The reader
// below concatenates the child's two role halves and the assertion searched the union, so
// `VerifySplitPoisonOmitted.` would have been just as green if the stamp the knob withheld
// had been the CLIENT's - which is the case it exists to rule out, because the mechanism
// under test is MG_Backend/MGPipe/PipeInputs.cpp's server-side stamp honouring the knob.
// The monolith pair has one role and one log half, so it keeps the union.
struct OmittedPair {
const char* Verb;
const char* Field;
const char* EarlierVerbs[2]; // verbs the sequence runs BEFORE this one, which must not trip
bool FiresOnTheServer; // the Fatal must be in the child's SERVER half, not merely present
};
constexpr OmittedPair kOmittedPairs[] = {
{"GenerateMipmap", "GetActiveTextureUnit", {"@DrawArrays", "@DrawArrays"}, false},
{"ReadPixels", "GetPixelStoreParameters", {"@DrawArrays", "@GenerateMipmap"}, true},
};
constexpr const char* kOmittedVerb = "GenerateMipmap";
constexpr const char* kOmittedField = "GetActiveTextureUnit";
constexpr const char* kFatalPrefix = "Fatal{UnmigratedPipeInput";
// Set only in the re-executed child, so the worker case below runs in that process and skips
@@ -144,41 +117,10 @@ void main() { o_color = vec4(0.25, 0.5, 0.75, 1.0); }
// Where the child is told to write ITS log. Empty when the lane configured no log path at
// all, in which case the signal is the only evidence and the text assertions are skipped.
//
// P7 WAVE 3 (V1): THIS IS A BASE NAME AND NOT A RESOLVED ONE, and the difference only
// became visible when verify and split first shared a build. It used to be
// LibraryLogPath() + ".poison-child" - and LibraryLogPath() is this lane's CLIENT half,
// which in a monolith verify build IS the raw MOBILEGL_LOG_FILE_PATH (so nothing moves
// there) but in a DISAGGREGATED one is already `<base>.client.log`. Handing that to the
// child as its own MOBILEGL_LOG_FILE_PATH made the child's library apply the role rule a
// SECOND time, so the child wrote `<base>.client.client.log.poison-child` while this
// parent read `<base>.client.log.poison-child` and found nothing. The result was
// `the child aborted, but not with Fatal{UnmigratedPipeInput, "..."}. Child log:` followed
// by silence - in a run where the abort had happened exactly as designed. Measured on
// build-split with -DMOBILEGL_PIPE_VERIFY=ON, both backends, 2/1136 red in the monolith
// verify lane; there is no CI job today that configures both options at once.
std::string ChildLogBasePath() {
const char* base = std::getenv("MOBILEGL_LOG_FILE_PATH");
if (base == nullptr || *base == '\0') return {};
return std::string(base) + ".poison-child";
}
// The library's own role rule, applied to an arbitrary base. It is PipeStatsWindow.h's
// copy of Log.cpp's RoleLogPath, for the reason stated there (the helpers are hidden in
// the shipping .so and this module links that), differing only in taking the base as an
// argument rather than reading the environment. Keep all three in step.
std::string ChildRoleLogPath(const std::string& base, const char* roleSuffix) {
#if MOBILEGL_BUILD_DISAGGREGATED
const std::string::size_type slash = base.find_last_of("/\\");
const std::string::size_type dot = base.find_last_of('.');
if (dot == std::string::npos || (slash != std::string::npos && dot < slash)) {
return base + "." + roleSuffix;
}
return base.substr(0, dot) + "." + roleSuffix + base.substr(dot);
#else
(void)roleSuffix;
return base;
#endif
std::string ChildLogPath() {
const std::filesystem::path parent = LibraryLogPath();
if (parent.empty()) return {};
return (parent.string() + ".poison-child");
}
std::string ReadWholeFile(const std::string& path) {
@@ -188,35 +130,6 @@ void main() { o_color = vec4(0.25, 0.5, 0.75, 1.0); }
return std::string((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
}
// BOTH HALVES, because under a transport the poison can fire on either side of the seam:
// the fill is the client's and the read is the backend's, and in a split build the
// backend runs on the server role's thread. A reader that took the client half alone
// would report "the child aborted with no Fatal" for every server-side firing.
//
// THE HALVES ARE ALSO KEPT APART (P7 wave 3, V1), because "did anyone report this" and
// "did the SERVER report this" are different questions and only the first one survives
// concatenation. Server is empty in a monolith build, which a caller must read as "there
// is no such half" rather than as "the server said nothing".
struct ChildLog {
std::string Client;
std::string Server;
std::string All; // Client + Server, the union every role-agnostic assertion wants
};
ChildLog ReadChildLogHalves() {
ChildLog log;
const std::string base = ChildLogBasePath();
if (base.empty()) return log;
log.Client = ReadWholeFile(ChildRoleLogPath(base, "client"));
#if MOBILEGL_BUILD_DISAGGREGATED
log.Server = ReadWholeFile(ChildRoleLogPath(base, "server"));
#endif
log.All = log.Client + log.Server;
return log;
}
std::string ReadChildLog() { return ReadChildLogHalves().All; }
class PoisonOmissionScenario : public ScenarioTest {
protected:
// The sequence under test. Deliberately in this order: the DRAW comes first and must
@@ -270,12 +183,6 @@ void main() { o_color = vec4(0.25, 0.5, 0.75, 1.0); }
glFinish();
std::fprintf(stderr, "[itest] poison worker: glGenerateMipmap returned\n");
// The split arm's verb (kOmittedPairs[1]): a readback, which is a round trip, so
// the server has applied it - and read the pack state - before this returns.
unsigned char centre[4] = {};
glReadPixels(gl.Width() / 2, gl.Height() / 2, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, centre);
std::fprintf(stderr, "[itest] poison worker: glReadPixels returned\n");
// The sequence is the WHOLE datum this child reports, so a GL error in it must be
// part of the answer rather than something only a human reading stderr would see.
// WithoutOmissionCompletes reads the child's exit status, and the status is built
@@ -304,14 +211,10 @@ void main() { o_color = vec4(0.25, 0.5, 0.75, 1.0); }
env.push_back(text);
}
env.push_back(std::string(kChildMarker) + "=1");
const std::string childLog = ChildLogBasePath();
const std::string childLog = ChildLogPath();
if (!childLog.empty()) {
// BOTH halves, for TruncateRoleLogs' reason one file over: a previous run's
// server log left standing would be concatenated into this run's read and a
// stale Fatal would answer for a child that never logged one.
std::error_code ec;
std::filesystem::remove(ChildRoleLogPath(childLog, "client"), ec);
std::filesystem::remove(ChildRoleLogPath(childLog, "server"), ec);
std::filesystem::remove(childLog, ec);
env.push_back("MOBILEGL_LOG_FILE_PATH=" + childLog);
}
@@ -406,25 +309,19 @@ void main() { o_color = vec4(0.25, 0.5, 0.75, 1.0); }
"is what the PoisonOmitted. ctest entries set";
}
const std::string knob = std::getenv("MOBILEGL_PIPE_POISON_OMIT");
const OmittedPair* pair = nullptr;
for (const OmittedPair& candidate : kOmittedPairs) {
if (knob == std::string(candidate.Verb) + ":" + candidate.Field) pair = &candidate;
}
if (pair == nullptr) {
const std::string expectedPair = std::string(kOmittedField) + "@" + kOmittedVerb;
if (knob != std::string(kOmittedVerb) + ":" + kOmittedField) {
GTEST_SKIP() << "MOBILEGL_PIPE_POISON_OMIT is " << knob << ", but this case only knows "
<< "how to provoke " << kOmittedPairs[0].Verb << ":" << kOmittedPairs[0].Field
<< " and " << kOmittedPairs[1].Verb << ":" << kOmittedPairs[1].Field;
<< "how to provoke " << kOmittedVerb << ":" << kOmittedField;
}
const std::string expectedPair = std::string(pair->Field) + "@" + pair->Verb;
int status = 0;
std::string reason;
ASSERT_TRUE(RunSequenceInAChildProcess(status, reason)) << reason;
const ChildLog halves = ReadChildLogHalves();
const std::string& childLog = halves.All;
const std::string childLog = ReadWholeFile(ChildLogPath());
ASSERT_TRUE(WIFSIGNALED(status))
<< "with the stamp of " << expectedPair << " omitted, the " << pair->Verb << " in the child "
<< "with the stamp of " << expectedPair << " omitted, the glGenerateMipmap in the child "
<< "had to read a field its verb never filled and abort. It " << DescribeStatus(status)
<< " instead - the poison is not armed (a build without MOBILEGL_PIPE_POISON, a filler "
"that stamps what it was told to skip, or a backend that no longer reads the field "
@@ -436,41 +333,20 @@ void main() { o_color = vec4(0.25, 0.5, 0.75, 1.0); }
"Child log:\n"
<< childLog;
if (ChildLogBasePath().empty()) {
if (ChildLogPath().empty()) {
GTEST_SKIP() << "the abort happened, but the lane set no MOBILEGL_LOG_FILE_PATH, so the "
"Fatal's text cannot be read back; the PoisonOmitted. ctest entries set it";
}
const std::string expectedFatal = std::string(kFatalPrefix) + ", \"" + expectedPair + "\"";
EXPECT_NE(childLog.find(expectedFatal), std::string::npos)
EXPECT_NE(childLog.find(std::string(kFatalPrefix) + ", \"" + expectedPair + "\""),
std::string::npos)
<< "the child aborted, but not with Fatal{UnmigratedPipeInput, \"" << expectedPair
<< "\"} - that message is the whole diagnostic value of the poison. Child log:\n"
<< childLog;
#if MOBILEGL_BUILD_DISAGGREGATED
// WHICH ROLE, for the split pair (P7 wave 3, V1). The union above answers "did the
// poison fire", which is all the monolith pair can be asked; this pair exists to prove
// that the SERVER'S OWN verb stamp honours MOBILEGL_PIPE_POISON_OMIT
// (MG_Backend/MGPipe/PipeInputs.cpp's ServerPoisonOmission) - the thing that was NOT
// true before wave 3 and made the control silently green. A client-side firing would
// satisfy the union and prove the opposite of what the entry claims, so the half is
// named here.
if (pair->FiresOnTheServer) {
EXPECT_NE(halves.Server.find(expectedFatal), std::string::npos)
<< "the child aborted with " << expectedFatal << ", but NOT in its server-role log. "
"This pair is the split arm's control and its whole claim is that the stamp the "
"SERVER writes at the verb boundary honours the omission - a firing anywhere "
"else means the withheld stamp was the client's and the server-side half is "
"untested. Client half:\n"
<< halves.Client << "\nServer half:\n"
<< halves.Server;
}
#endif
for (const char* earlier : pair->EarlierVerbs) {
EXPECT_EQ(childLog.find(earlier), std::string::npos)
<< "a verb that ran BEFORE the omitted one (" << earlier << ") also tripped the "
"poison, so the omission is not scoped to its verb: the fill classes are wrong, "
"or the stamps are global. Child log:\n"
<< childLog;
}
EXPECT_EQ(childLog.find("@DrawArrays"), std::string::npos)
<< "the draw that ran BEFORE the omitted verb also tripped the poison, so the omission "
"is not scoped to its verb: the fill classes are wrong, or the stamps are global. "
"Child log:\n"
<< childLog;
}
// The sibling control, in the ambient Verify. lanes: the same sequence with the knob UNSET
@@ -494,7 +370,7 @@ void main() { o_color = vec4(0.25, 0.5, 0.75, 1.0); }
std::string reason;
ASSERT_TRUE(RunSequenceInAChildProcess(status, reason)) << reason;
const std::string childLog = ReadChildLog();
const std::string childLog = ReadWholeFile(ChildLogPath());
const std::string note =
omissionArmed
? std::string(
@@ -6,76 +6,55 @@
// SPDX-License-Identifier: LGPL-3.0-only
// End of Source File Header
//
// Scenario - THE TEXTURE UPLOAD SHAPE, GATED (BRIEF-P4A.md D-D4; P3b/P4b R-11, wave 2-D).
// Scenario - THE TEXTURE UPLOAD SHAPE, RECORDED (BRIEF-P4A.md D-D4). NOT A GATE IN P4a.
//
// WHAT IT IS FOR. SSIM is completely blind to the difference between "one union box" and "N
// separate rects", and that difference is the Mali upload cliff: Mali prices an upload by the
// number of JOBS, and ~100 one-rect sprite jobs against one union box measured +6 ms/frame
// (ARCHITECTURE.md:249-251). Every gate in the phase can be green while the emission shape has
// silently inverted, so the shape needs a number - and there are TWO numbers, deliberately:
// (ARCHITECTURE.md:249-251). Every P4a gate can be green while the emission shape has silently
// inverted, so the shape needs a number - and there are TWO numbers, deliberately:
//
// tex[emit= box= rect= jobs=] the SERVER's count, Espryt's own, which has existed since P2
// emit[ctu=] the CLIENT's count of the same records (CallClass::
// ClientTextureUploadEmissions)
// ClientTextureUploadEmissions, minted by the P4a contract commit)
//
// The two agreeing is the whole reason both are printed (D-L). An emission-shape divergence
// between the client that decides the rect model and the server that pays the GPU cost is then a
// difference of two published numbers rather than something only a device can see.
// The two agreeing is the whole reason both are printed (D-L). An emission-shape divergence between
// the client that decides the rect model and the server that pays the GPU cost is then a difference
// of two published numbers rather than something only a device can see.
//
// ---------------------------------------------------------------------------------------------
// WHY IT IS A GATE NOW, AND WHAT CHANGED SINCE P4a. The P4a header said, correctly for its tree:
// "the per-storage-owner emission cursor with view/owner index remapping - which is what actually
// decides the shape for a texture uploaded through a VIEW - is the next phase's", and gating a
// shape the phase had not finished deciding would have pinned a non-answer. THAT WORK LANDED:
// the cursor is keyed on the storage owner (TextureEmit.h's drain list), the remap is
// TextureObjectView::ToOwner*, and TextureViewAliasScenario is its behavioural gate. So the
// numbers are no longer provisional and the RecordProperty block became EXPECT_EQ against the
// table below.
// WHY IT IS RECORDED AND NOT GATED, and this is a scope decision rather than a hedge. ROADMAP.md:23
// puts "dirty 归属反转(按存储属主键控的发射游标)" in the P3b/P4b cell: P4a lands the flat drain
// list, and the per-storage-owner emission cursor with view/owner index remapping - which is what
// actually decides the shape for a texture uploaded through a VIEW - is the next phase's. Gating a
// shape the phase has not finished deciding would either pin today's shape as if it were the
// answer, or fail on a change that is the point of the next phase. So P4a BUILDS the scenario (it
// is meaningless without P4a's records) and runs it as a RECORDED comparison; P3b/P4b turns it into
// a gate with the Mali frame-time delta published beside it (D-D4).
//
// THE CLIENT EMITTER LANDED TOO, and three places in the tree said otherwise until this commit:
// this header, the CMake probe's comment, and notes/p4a/p4a-results/gates-v1.md's re-run table.
// MG_Impl/Pipe/TextureEmit.h's EmitOneLevel increments CallClass::ClientTextureUploadEmissions on
// every piece it emits, so `ctu=` is a live reading and `ctu == emit` is a live assertion. The
// CMake probe's `else()` arm is kept - it is what makes the arming decision falsifiable - but it
// is unreachable on this tree.
//
// THE MALI FRAME-TIME DELTA IS NOT PUBLISHED BESIDE THESE NUMBERS AND WILL NOT BE IN THIS PHASE.
// D-D4 asks for the +6 ms/frame reading next to the shape gold. It is NOT SCHEDULABLE: the phase
// has one device, a Redmi with an Adreno, and no Mali part at all. Recorded as a DECLARED
// DEVIATION here and in docs/Disaggregated/MEASUREMENTS.md ("Adreno-only; Mali delta deferred")
// rather than faked from a model or copied from the 2026 measurement's conditions. What the gate
// therefore pins is the SHAPE, on the reasoning that the shape is the cliff's cause and the frame
// time is its consequence on one vendor's hardware.
// ---------------------------------------------------------------------------------------------
//
// WHAT IT ASSERTS:
// WHAT IT THEREFORE ASSERTS, and it is not nothing:
//
// 1. the numbers could be READ AT ALL - the counters exist, the window covers the workload, and
// the workload really uploaded (a run that uploaded nothing would read four zeroes and look
// the workload really uploaded (a run that uploaded nothing would record four zeroes and look
// exactly like a healthy run whose emitter had been switched off);
// 2. the internal ARITHMETIC of the server's own bracket holds: emit == box + rect, and
// jobs >= emit, because a box emission is one job and a rect-list emission is N;
// 3. the client and the server agree on the RECORD COUNT (ctu == emit);
// 4. THE GOLD TABLE: emit / box / rect / jobs are exactly kGold's, which is the assertion the
// other three cannot make - they are all satisfied by a shape that inverted wholesale.
// 3. the client and the server agree on the RECORD COUNT when both are non-zero (ctu == emit).
// Not "when the client is non-zero": on the P4a contract tree the client emits nothing and
// that is a SKIP-shaped observation, not a divergence.
//
// THE WORKLOAD is the shape the decision is about, in three textures:
// * MANY SMALL SCATTERED SUB-REGIONS per frame (the sprite-atlas / chunk-renderer shape). This
// is where the box-versus-rect choice is made - MipmapStorage's 96-rect cascade and the
// summedArea*4 >= unionArea*3 union-box fallback;
// * one large CONTIGUOUS region, the control that must always be one box whatever the policy is;
// * the same scattered pattern written THROUGH A glTextureView of the third texture's level 1,
// so the view/owner index remap is inside the counted window. Without it the gold table would
// pin a shape for exactly the input the P3b/P4b work changed and say nothing about the input
// it changed it for.
// Everything else - which shape each texture took, and whether that is the right shape - is
// RECORDED with RecordProperty and printed, for MEASUREMENTS.md and for the P3b/P4b gate to be
// written against.
//
// THE WORKLOAD is the shape the decision is about: one texture receiving MANY SMALL SCATTERED
// SUB-REGIONS per frame (the sprite-atlas / chunk-renderer shape), and one receiving a single large
// contiguous one. The first is where the box-versus-rect choice is made - MipmapStorage's 96-rect
// cascade and the summedArea*4 >= unionArea*3 union-box fallback - and the second is the control
// that must always be one box whatever the policy is.
//
// DIRECTGLES ONLY. The server-side counters are Espryt's (Managers.cpp:6360-6395); Magma's upload
// path is P7 and contributes nothing to them, so a DirectVulkan lane would record a bracket of
// zeroes and call it a shape.
//
// VIEWS ARE OPT-IN ON ESPRYT, so every lane that runs this case sets
// MOBILEGL_ESPRYT_ENABLE_TEXTURE_VIEW=1. A lane without it SKIPS rather than dropping the third
// texture: a conditional workload behind a fixed gold table is a gate that passes by shrinking.
#include <cstdint>
#include <cstdlib>
@@ -87,7 +66,6 @@
#include "../Harness/PipeStatsWindow.h"
#include "../Harness/ScenarioFixture.h"
#include "../Harness/SplitRuntimePeek.h"
#include "../Harness/TextureEmitPeek.h"
#ifdef GLAPI
#undef GLAPI
@@ -100,8 +78,8 @@
namespace MGITest {
namespace {
// Set by the TextureUploadShape. ctest entries and by nothing else; a harness marker,
// never read by the library.
// Set by the TextureUploadShape. ctest entry and by nothing else; a harness marker, never
// read by the library.
constexpr const char* kLaneMarker = "MGITEST_TEXTURE_UPLOAD_SHAPE_LANE";
constexpr int kInset = 2;
@@ -113,89 +91,6 @@ namespace MGITest {
constexpr int kScatteredRects = 40;
constexpr int kRectSize = 2;
constexpr int kFrames = 3;
// THE SCATTER IS INSET BY ONE RECT, AND WITHOUT IT THIS GATE MEASURED NOTHING.
//
// The original stride was x = ((i*7) % (kAtlasSize/kRectSize)) * kRectSize and the same
// with 5 for y. Both are surjective onto 0..31 over 40 iterations (rect 9 lands at x=62,
// rect 19 at y=62), so the rects' UNION BOX is the whole 64x64 level - and the server's
// subRectEligible (Managers.cpp:8486-8491) requires !dirtyRegion.CoversWholeLevel, a
// BOUNDING-BOX test (MipmapStorage.h:30-33). Both scatter textures were therefore
// rect-INELIGIBLE on every arm, before any policy about rect lists was consulted: the
// box-versus-rect decision this scenario exists to pin was never reached, and the only
// texture that could move was the contiguous control band.
//
// Insetting by one rect keeps the same 40 writes and the same coarse stride but bounds
// the union box at (kRectSize, kRectSize)..(62, 54), which covers no level. The decision
// point is now live for the two scatter textures, which is what makes the gold row below
// a statement about the emission shape rather than about the workload's bounding box.
constexpr int kScatterMargin = kRectSize;
constexpr int kScatterCells = kAtlasSize / kRectSize - 2 * (kScatterMargin / kRectSize);
static_assert(kScatterMargin + (kScatterCells - 1) * kRectSize + kRectSize < kAtlasSize,
"the inset scatter must not reach the level's far edge, or its union box "
"covers the level again and the server stops looking at the rect list");
// The viewed texture's OWNER is twice the atlas so that its level 1 - which is what the
// view opens onto - is exactly kAtlasSize and the same scattered pattern applies to it.
constexpr int kViewedOwnerSize = kAtlasSize * 2;
constexpr int kViewedOwnerLevels = 2;
constexpr int kViewMinLevel = 1;
// ---- THE GOLD TABLE -------------------------------------------------------------------
//
// MEASURED ON THIS CURSOR, not inherited. The P4a record for the two-texture workload was
// `emit=6 box=6 rect=0 jobs=6` with `ctu=0`; this row is the three-texture workload's own
// reading taken after the client emitter and the owner-keyed cursor landed, and the P4a
// numbers are quoted only so that a reader can see they are not the same claim.
//
// KEYED ON THE WORKLOAD CONSTANTS, and the static_assert below is the key: change
// kScatteredRects, kFrames, the number of contiguous bands or the number of textures and
// these numbers describe a workload that no longer exists. The assert makes that a compile
// error rather than a mysterious red.
//
// WHY box IS THE WHOLE OF emit ON THIS TREE, and this paragraph was WRONG in its first
// version - the correction is worth keeping because the wrong version is the one a reader
// reaches for.
//
// The client really does build a rect list here: MipmapStorage's cascade merges only
// rects that overlap or abut (RegionsTouch, MipmapStorage.cpp:88-91), the inset scatter
// leaves 2-texel gaps, and GetDirtyRects hands back THIRTY rects whose summed area (120
// texels) is far under 3/4 of the union box - so neither the 2..maxRects test nor the
// summedArea*4 >= unionArea*3 fallback takes the box arm. The record carries all thirty.
//
// THE SERVER DECIDES, and it decides BOX, at Managers.cpp:8649:
//
// if (BufferImpl::UnpackRingAvailable()) dirtyRectCount = 0;
//
// "through the unpack ring every glTexSubImage is a GPU copy job (Mali), so ~100 sprite
// rects become ~100 jobs whose fixed cost dwarfs the union box's extra bytes - measured
// +6 ms/frame... One box, one job." That is the existing Mali-cliff mitigation, and
// box=9 rect=0 is its INTENDED OUTPUT rather than an accident of this workload. Pinning
// it is the point: a change that starts emitting rect lists through the ring is exactly
// the +6 ms/frame inversion, and disabling the ring is what the red-once does.
//
// WHAT THE FIRST VERSION GOT WRONG, because the trap is easy to fall into twice: the
// original scatter stride reached x=62 and y=62 in a 64-px atlas, so the union box
// covered the whole level - and the server's subRectEligible (Managers.cpp:8486-8491)
// requires !dirtyRegion.CoversWholeLevel, a BOUNDING-BOX test (MipmapStorage.h:30-33).
// Both scatter textures were rect-INELIGIBLE before the ring policy was ever consulted,
// so the gold looked identical while measuring something else entirely, and the only
// texture that could move under any red-once was the contiguous control band. The
// kScatterMargin inset above is what makes this paragraph true.
struct UploadShapeGold {
long long Emissions;
long long BoxEmissions;
long long RectEmissions;
long long Jobs;
};
constexpr int kTexturesInTheWindow = 3;
constexpr UploadShapeGold kGold{9, 9, 0, 9};
static_assert(kScatteredRects == 40 && kFrames == 3 && kTexturesInTheWindow == 3,
"the gold table is keyed on the workload constants: re-measure before "
"changing kScatteredRects, kFrames or the texture count");
static_assert(kGold.Emissions == kGold.BoxEmissions + kGold.RectEmissions,
"the gold row must itself satisfy the arithmetic the case asserts");
static_assert(kGold.Emissions == kTexturesInTheWindow * kFrames,
"one emission per texture per frame is the shape; a gold row that does not "
"say so is pinning an accident");
constexpr const char* kVS = R"(#version 330 core
in vec2 aPos;
@@ -251,8 +146,6 @@ void main() { oColor = texture(uTex, vUv); }
glBindBuffer(GL_ARRAY_BUFFER, 0);
if (m_scattered != 0) glDeleteTextures(1, &m_scattered);
if (m_contiguous != 0) glDeleteTextures(1, &m_contiguous);
if (m_view != 0) glDeleteTextures(1, &m_view);
if (m_viewedOwner != 0) glDeleteTextures(1, &m_viewedOwner);
if (m_vao != 0) glDeleteVertexArrays(1, &m_vao);
if (m_quadBuffer != 0) glDeleteBuffers(1, &m_quadBuffer);
if (m_program != 0) glDeleteProgram(m_program);
@@ -291,46 +184,6 @@ void main() { oColor = texture(uTex, vUv); }
"PipeStats";
return;
}
if (!TextureViewUsable()) {
// A SKIP AND NOT A SMALLER WORKLOAD. The gold table has one row; dropping the
// third texture here would leave a case that asserts emit==9 against a
// six-emission workload, i.e. a gate that fails for the wrong reason - or,
// worse, a second gold row that nobody re-measures.
GTEST_SKIP() << "GL_ARB_texture_view is not advertised on this backend, so the "
"third texture - the one whose upload goes through a "
"glTextureView, which is the input the P3b/P4b emission cursor "
"work changed - cannot be built. Every lane this case is "
"registered in sets MOBILEGL_ESPRYT_ENABLE_TEXTURE_VIEW=1.";
return;
}
}
bool TextureViewUsable() {
GLuint storage = 0;
glGenTextures(1, &storage);
glBindTexture(GL_TEXTURE_2D, storage);
glTexStorage2D(GL_TEXTURE_2D, 1, GL_RGBA8, 1, 1);
glBindTexture(GL_TEXTURE_2D, 0);
GLuint view = 0;
glGenTextures(1, &view);
while (glGetError() != GL_NO_ERROR) {
}
glTextureView(view, GL_TEXTURE_2D, storage, GL_RGBA8, 0, 1, 0, 1);
const bool usable = glGetError() == GL_NO_ERROR;
glDeleteTextures(1, &view);
glDeleteTextures(1, &storage);
return usable;
}
static std::vector<std::uint8_t> GreenTexels(int width, int height) {
std::vector<std::uint8_t> texels(static_cast<std::size_t>(width) * height * 4);
for (std::size_t i = 0; i < texels.size(); i += 4) {
texels[i] = 0;
texels[i + 1] = 255;
texels[i + 2] = 0;
texels[i + 3] = 255;
}
return texels;
}
GLuint MakeAtlas(std::uint8_t r, std::uint8_t g, std::uint8_t b) {
@@ -353,57 +206,6 @@ void main() { oColor = texture(uTex, vUv); }
return texture;
}
// The third texture's OWNER: immutable, two levels, seeded green on both. glTextureView
// requires immutable storage, so this one cannot be a MakeAtlas.
GLuint MakeViewedOwner() {
GLuint texture = 0;
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);
glTexStorage2D(GL_TEXTURE_2D, kViewedOwnerLevels, GL_RGBA8, kViewedOwnerSize,
kViewedOwnerSize);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
for (int level = 0; level < kViewedOwnerLevels; ++level) {
const int size = kViewedOwnerSize >> level;
const std::vector<std::uint8_t> green = GreenTexels(size, size);
glTexSubImage2D(GL_TEXTURE_2D, level, 0, 0, size, size, GL_RGBA, GL_UNSIGNED_BYTE,
green.data());
}
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glBindTexture(GL_TEXTURE_2D, 0);
return texture;
}
// A view of the owner's LEVEL 1, which is kAtlasSize square: the view's own level 0.
// Every glTexSubImage2D through this name has to be remapped to the owner's level 1 by
// TextureObjectView::ToOwnerLevel before it reaches the drain list, and the emission it
// produces has to land on the OWNER's cursor.
GLuint MakeLevelView(GLuint owner) {
GLuint view = 0;
glGenTextures(1, &view);
glTextureView(view, GL_TEXTURE_2D, owner, GL_RGBA8, kViewMinLevel, 1, 0, 1);
EXPECT_EQ(glGetError(), static_cast<GLenum>(GL_NO_ERROR))
<< "a single-level 2D view of a 2D texture is a legal view pair";
glBindTexture(GL_TEXTURE_2D, view);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glBindTexture(GL_TEXTURE_2D, 0);
return view;
}
void ScatterRectsInto(GLuint texture) {
glBindTexture(GL_TEXTURE_2D, texture);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
const std::uint8_t patch[kRectSize * kRectSize * 4] = {
0, 255, 0, 255, 0, 255, 0, 255, 0, 255, 0, 255, 0, 255, 0, 255};
for (int rect = 0; rect < kScatteredRects; ++rect) {
const int x = kScatterMargin + ((rect * 7) % kScatterCells) * kRectSize;
const int y = kScatterMargin + ((rect * 5) % kScatterCells) * kRectSize;
glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, kRectSize, kRectSize, GL_RGBA,
GL_UNSIGNED_BYTE, patch);
}
}
Image DrawSampled(GLuint texture) {
BindDefaultFramebuffer();
glViewport(0, 0, Gl().Width(), Gl().Height());
@@ -421,8 +223,6 @@ void main() { oColor = texture(uTex, vUv); }
GLuint m_quadBuffer = 0;
GLuint m_scattered = 0;
GLuint m_contiguous = 0;
GLuint m_viewedOwner = 0;
GLuint m_view = 0;
};
TEST_F(TextureUploadShapeScenario, TheEmittedUploadShapeIsRecordedAndTheTwoSidesAgree) {
@@ -432,13 +232,10 @@ void main() { oColor = texture(uTex, vUv); }
m_scattered = MakeAtlas(0, 255, 0);
m_contiguous = MakeAtlas(0, 255, 0);
m_viewedOwner = MakeViewedOwner();
m_view = MakeLevelView(m_viewedOwner);
// The first draw of each texture uploads its whole level, which is not the shape this
// scenario is about; it happens in the SETUP window, before the one that is read.
DrawSampled(m_scattered);
DrawSampled(m_contiguous);
DrawSampled(m_view);
BindDefaultFramebuffer();
Gl().EndFrame();
// The server closes/resets the stats window inside Present. Under
@@ -450,237 +247,118 @@ void main() { oColor = texture(uTex, vUv); }
}
// ---- the counted window ----
//
// THE CLIENT HALF IS READ FROM THE EMITTER, NOT FROM ctu=, and that is a correction
// this package had to make rather than a preference. MEASURED on all four arms:
//
// monolith one role, one log: the window line carries tex[emit=9] AND ctu=9.
// inproc two log FILES, one process, one set of counters: the SERVER's line
// carries both, and the client's log holds only the "counters ON" banner
// at the moment this case reads it.
// spawn/tcp two PROCESSES with two counter sets. The server's line carries
// tex[emit=9] ctu=0; the client process emits its own summary on a
// DIFFERENT Present cadence and had written only the banner by the time
// this case reads - and when it does write one, its window covers the
// setup emissions too (measured ctu=13 against emit=9), so the two
// numbers are not windowed on the same work and `ctu == emit` is not a
// well-posed comparison there at all.
//
// So the log's ctu= is kept as a RECORD (printed, and asserted where it is
// window-aligned) and the ASSERTION reads MGPipeTextureEmitter's own counter through
// the in-process peek. That is the same counter's SOURCE - EmitOneLevel increments
// both on the same line - and the test process is the CLIENT under every one of
// monolith / inproc / spawn / tcp, so the delta below is the client's true count of
// the records this workload produced, in every arm. D-L asks for the two sides to
// agree; this is what makes that a real question outside monolith.
TextureEmitCountersPeek emitBefore{};
const bool emitPeekLive = PeekTextureEmitCounters(&emitBefore);
// The log mark the two role readings are taken against, so that a teardown window
// cannot be mistaken for the workload's (see PipeStatsWindow.h).
const PipeStatsWindow::LogMark statsMark = PipeStatsWindow::MarkLaneLog();
Image lastScattered;
Image lastContiguous;
Image lastViewed;
for (int frame = 0; frame < kFrames; ++frame) {
// MANY SMALL SCATTERED RECTS: the shape whose box-versus-rect decision is the whole
// subject. They are spread over the atlas on a coarse stride so that their union
// box is most of the texture and their summed area is a small fraction of it -
// which is the input the summedArea*4 >= unionArea*3 fallback is written for.
ScatterRectsInto(m_scattered);
glBindTexture(GL_TEXTURE_2D, m_scattered);
const std::uint8_t patch[kRectSize * kRectSize * 4] = {
0, 255, 0, 255, 0, 255, 0, 255, 0, 255, 0, 255, 0, 255, 0, 255};
for (int rect = 0; rect < kScatteredRects; ++rect) {
const int x = ((rect * 7) % (kAtlasSize / kRectSize)) * kRectSize;
const int y = ((rect * 5) % (kAtlasSize / kRectSize)) * kRectSize;
glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, kRectSize, kRectSize, GL_RGBA,
GL_UNSIGNED_BYTE, patch);
}
lastScattered = DrawSampled(m_scattered);
// ONE LARGE CONTIGUOUS REGION: the control. Whatever the policy is, this is one
// box and one job, and a reading where it is not says the policy has stopped
// looking at the region at all.
glBindTexture(GL_TEXTURE_2D, m_contiguous);
const std::vector<std::uint8_t> band = GreenTexels(kAtlasSize, 8);
std::vector<std::uint8_t> band(static_cast<std::size_t>(kAtlasSize) * 8 * 4);
for (std::size_t i = 0; i < band.size(); i += 4) {
band[i] = 0;
band[i + 1] = 255;
band[i + 2] = 0;
band[i + 3] = 255;
}
glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, kAtlasSize, 8, GL_RGBA, GL_UNSIGNED_BYTE,
band.data());
lastContiguous = DrawSampled(m_contiguous);
// THE SAME SCATTERED PATTERN THROUGH A VIEW. The writes name the view's level 0;
// the drain has to key them on the OWNER at the owner's level 1, and the shape the
// emitter then chooses has to be the same one the owner's own name would have got.
// A cursor that keyed on the view would show up here as a DIFFERENT emit count,
// not as a wrong picture.
ScatterRectsInto(m_view);
lastViewed = DrawSampled(m_view);
}
ASSERT_EQ(FirstGLError(), GLenum(GL_NO_ERROR)) << "the upload workload left a GL error behind";
TextureEmitCountersPeek emitAfter{};
const bool emitPeekClosed = emitPeekLive && PeekTextureEmitCounters(&emitAfter);
Gl().EndFrame(); // the swap that emits the window covering exactly the work above
if (const auto runtime = PeekSplitRuntime(); runtime.transportResolved) {
ASSERT_TRUE(runtime.sessionActive);
ASSERT_TRUE(WaitForSplitAppliedForTesting(runtime.emitSeq));
}
// ---- READING TWO ROLES, NOT ONE LINE --------------------------------------------
//
// Under SPAWN and TCP the client and the server are two PROCESSES with two independent
// sets of counters: the client's summary line carries `ctu=N tex[emit=0]` and the
// server's carries `ctu=0 tex[emit=N]`. A single concatenated read takes whichever line
// came last and answers BOTH questions with one role's numbers, which turns the
// two-sided comparison into `N == 0`. So each side is read from ITS OWN role's log, and
// the server bracket falls back to the client log only where there is no server half -
// the pull build and the monolith lane, where one file IS the whole run.
const PipeStatsWindow::Window clientWindow =
PipeStatsWindow::LastFromClientLogSince(statsMark);
const PipeStatsWindow::Window serverWindow =
PipeStatsWindow::LastFromServerLogSince(statsMark);
const PipeStatsWindow::Window& shapeWindow =
(serverWindow.found && PipeStatsWindow::CounterOrAbsent(serverWindow, "emit") > 0)
? serverWindow
: clientWindow;
// THE ASSERTION IS ON THE WINDOW THAT CARRIES THE BRACKET, not on the client's, and
// moving to a marked read is what showed why. The client role emits NO summary window
// of its own under inproc/spawn/tcp at the point this case reads - only the
// "counters ON" banner, which also contains the marker string. Asserting
// clientWindow.found over the whole file therefore passed on the BANNER in all three
// split arms and claimed a window had been read when none had. Since the mark there
// is no banner to hide behind, so the claim has to be made about the role that
// actually published the counters.
ASSERT_TRUE(shapeWindow.found)
<< "no 'MGPipe stats:' window was appended to either role's log by the swap that "
"closes the counted window. client="
<< PipeStatsWindow::LibraryLogPath()
<< " server=" << PipeStatsWindow::ServerLibraryLogPath()
<< ". The shape could not be read at all - which is a different finding from a "
"shape that read zero.";
RecordProperty("stats_line_client", clientWindow.line.c_str());
if (serverWindow.found) RecordProperty("stats_line_server", serverWindow.line.c_str());
const PipeStatsWindow::Window window = PipeStatsWindow::LastFromLaneLog();
ASSERT_TRUE(window.found)
<< "no 'MGPipe stats:' line in " << PipeStatsWindow::LibraryLogPath()
<< ", so the shape could not be read at all";
RecordProperty("stats_line", window.line.c_str());
const long long emissions = PipeStatsWindow::CounterOrAbsent(shapeWindow, "emit");
const long long box = PipeStatsWindow::CounterOrAbsent(shapeWindow, "box");
const long long rect = PipeStatsWindow::CounterOrAbsent(shapeWindow, "rect");
const long long jobs = PipeStatsWindow::CounterOrAbsent(shapeWindow, "jobs");
// The log's ctu=, from whichever role's window carries it. Under monolith and inproc
// that is the same window the tex[] bracket came from; under spawn and tcp it is a
// different process's differently-windowed counter, so it is RECORDED and only
// asserted where the two are window-aligned (see the note over the counted window).
const long long shapeWindowCtu = PipeStatsWindow::CounterOrAbsent(shapeWindow, "ctu");
const long long clientWindowCtu = PipeStatsWindow::CounterOrAbsent(clientWindow, "ctu");
// ALIGNED IS A PROPERTY OF THE TRANSPORT, NOT OF THE NUMBER, and asking the number
// was this case's first mistake: `shapeWindowCtu >= 0` is TRUE under spawn, where the
// server's line publishes a perfectly readable ctu=0 that belongs to a process which
// emitted nothing, and the comparison became 0 == 9. Asking the process which
// transport it resolved cannot be satisfied by a counter that happens to read zero -
// and a single-process arm whose ctu= really did collapse to 0 still reds, which is
// the failure the alignment check must not swallow.
const SplitRuntimeState statsRuntime = PeekSplitRuntime();
const bool oneProcessForCounters =
!statsRuntime.transportResolved || statsRuntime.transportName == "inproc";
const bool ctuIsWindowAligned = oneProcessForCounters && shapeWindowCtu >= 0;
const long long clientEmissions =
emitPeekClosed
? static_cast<long long>(emitAfter.SubDataCount - emitBefore.SubDataCount)
: shapeWindowCtu;
ASSERT_GE(emissions, 0) << "the summary line carries no tex[emit=]: " << shapeWindow.line;
ASSERT_GE(box, 0) << "no box=: " << shapeWindow.line;
ASSERT_GE(rect, 0) << "no rect=: " << shapeWindow.line;
ASSERT_GE(jobs, 0) << "no jobs=: " << shapeWindow.line;
const long long emissions = PipeStatsWindow::CounterOrAbsent(window, "emit");
const long long box = PipeStatsWindow::CounterOrAbsent(window, "box");
const long long rect = PipeStatsWindow::CounterOrAbsent(window, "rect");
const long long jobs = PipeStatsWindow::CounterOrAbsent(window, "jobs");
const long long clientEmissions = PipeStatsWindow::CounterOrAbsent(window, "ctu");
ASSERT_GE(emissions, 0) << "the summary line carries no tex[emit=]: " << window.line;
ASSERT_GE(box, 0) << "no box=: " << window.line;
ASSERT_GE(rect, 0) << "no rect=: " << window.line;
ASSERT_GE(jobs, 0) << "no jobs=: " << window.line;
// THE RECORD. This is the deliverable of this scenario in P4a: a number, in the ctest
// XML and in the log, for MEASUREMENTS.md and for the P3b/P4b gate to be written
// against. Printed as well as recorded, because a RecordProperty is invisible in a
// console run.
std::cout << "[ TextureUploadShape ] backend=" << Gl().BackendName() << " frames=" << kFrames
<< " scattered_rects_per_frame=" << kScatteredRects
<< " textures=" << kTexturesInTheWindow
<< " server[emit=" << emissions << " box=" << box << " rect=" << rect
<< " jobs=" << jobs << "] client[emitter=" << clientEmissions
<< " ctu_shape_window=" << shapeWindowCtu
<< " ctu_client_window=" << clientWindowCtu << "]" << std::endl;
RecordProperty("ctu_shape_window", static_cast<int>(shapeWindowCtu));
RecordProperty("ctu_client_window", static_cast<int>(clientWindowCtu));
RecordProperty("ctu_is_window_aligned", ctuIsWindowAligned ? 1 : 0);
<< " jobs=" << jobs << "] client[ctu=" << clientEmissions << "]" << std::endl;
RecordProperty("server_emissions", static_cast<int>(emissions));
RecordProperty("server_box_emissions", static_cast<int>(box));
RecordProperty("server_rect_emissions", static_cast<int>(rect));
RecordProperty("server_upload_jobs", static_cast<int>(jobs));
RecordProperty("client_emissions", static_cast<int>(clientEmissions));
// 1. the workload really uploaded. Without this the assertions below are all 0 == 0 and
// a run whose emitter was switched off records the same "healthy" shape as one that
// worked.
// 1. the workload really uploaded. Without this the three assertions below are all
// 0 == 0 and a run whose emitter was switched off records the same "healthy" shape
// as one that worked.
ASSERT_GT(emissions, 0)
<< "the server counted no texture upload emission at all over " << kFrames
<< " frames of " << kScatteredRects
<< " sub-regions each, plus a contiguous band and a view write. Either the uploads "
"never reached the backend or the counter stopped counting; in both cases every "
"shape number below would be a zero that means nothing. "
<< shapeWindow.line;
<< " sub-regions each plus a contiguous band. Either the uploads never reached the "
"backend or the counter stopped counting; in both cases every shape number below "
"would be a zero that means nothing. "
<< window.line;
// 2. the server bracket's own arithmetic.
EXPECT_EQ(box + rect, emissions)
<< "tex[box=] + tex[rect=] must be tex[emit=]: every emission takes exactly one of "
"the two shapes. " << shapeWindow.line;
"the two shapes. " << window.line;
EXPECT_GE(jobs, emissions)
<< "tex[jobs=] must be at least tex[emit=]: a box emission is one driver upload job "
"and a rect-list emission is N. " << shapeWindow.line;
"and a rect-list emission is N. " << window.line;
// 3. THE GOLD TABLE (R-11 / D-D4). This is the assertion the three around it cannot
// make: emit == box + rect and jobs >= emit are both satisfied by a shape that
// inverted wholesale from N boxes to N rect lists, which is the +6 ms/frame
// direction on Mali and is invisible to SSIM.
EXPECT_EQ(emissions, kGold.Emissions)
<< "the emission COUNT moved. One resource_subdata per (storage owner, upload "
"target, level) per frame is " << kTexturesInTheWindow << " textures x " << kFrames
<< " frames = " << kGold.Emissions
<< ". A count above this says a level is being emitted more than once per validate "
"point - the two-cursor shape, if the extra one is the viewed texture; a count "
"below says a level's record was dropped. " << shapeWindow.line;
EXPECT_EQ(box, kGold.BoxEmissions)
<< "the BOX/RECT split moved: " << box << " box emissions against a gold of "
<< kGold.BoxEmissions << ". " << shapeWindow.line;
EXPECT_EQ(rect, kGold.RectEmissions)
<< "the BOX/RECT split moved: " << rect << " rect-list emissions against a gold of "
<< kGold.RectEmissions
<< ". This is the direction that costs ~+6 ms/frame on Mali (ARCHITECTURE.md:249-"
"251): the driver is handed N upload jobs where it used to be handed one, and no "
"SSIM case can see it. If this is intended, re-measure the row and say so in "
"docs/Disaggregated/MEASUREMENTS.md. " << shapeWindow.line;
EXPECT_EQ(jobs, kGold.Jobs)
<< "the JOB count moved: " << jobs << " against a gold of " << kGold.Jobs
<< ". Jobs are what Mali prices the upload by. " << shapeWindow.line;
// 4. the two sides agree, WHEN THERE ARE TWO SIDES - and "there are two sides" is
// 3. the two sides agree, WHEN THERE ARE TWO SIDES - and "there are two sides" is
// answered by the BUILD, not by the number (review F-m7).
//
// ctu= IS ALWAYS PRESENT IN A PUSH BUILD: PipeStats.cpp writes the field whether or
// not anything ever incremented the counter, so `clientEmissions > 0` conflated
// three different trees - "no client emitter exists", "the emitter exists and
// emitted nothing", and "the counter was not published at all" - into one branch
// that asserts nothing. So the discriminator is
// MGITEST_PIPE_CLIENT_TEXTURE_UPLOAD_EMITTER_PRESENT, the build's own content probe
// for a MG_Impl/Pipe source that emits CallClass::ClientTextureUploadEmissions.
// that asserts nothing and prints a sentence that is only true of the first. Once
// package B's texture emitter lands, an emitter that STOPPED emitting would read
// exactly like no emitter at all and this case would have gone green over it, which
// is the failure mode the whole scenario exists to make impossible.
//
// THAT PROBE HITS ON THIS TREE: MG_Impl/Pipe/TextureEmit.h's EmitOneLevel increments
// it on every piece. The else-arm below is retained because it is what makes the
// arming decision falsifiable in both directions, not because it is reachable here.
// So the discriminator is MGITEST_PIPE_CLIENT_TEXTURE_UPLOAD_EMITTER_PRESENT, the
// build's own content probe for a MG_Impl/Pipe source that emits
// CallClass::ClientTextureUploadEmissions - the same mechanism as every other arming
// decision in this package - and each side of it asserts something real.
const bool clientEmitterExists =
BuildMarkerIsSet("MGITEST_PIPE_CLIENT_TEXTURE_UPLOAD_EMITTER_PRESENT");
ASSERT_GE(clientEmissions, 0)
<< "the client half of the comparison could not be read at all. The in-process "
"emitter peek "
<< (emitPeekLive ? "opened but did not close" : TextureEmitPeekSkipReason())
<< ", and no role's summary line carried a ctu= field either. client="
<< clientWindow.line << " shape=" << shapeWindow.line;
<< "the summary line carries no ctu= field at all, in a push build, where PipeStats "
"publishes it unconditionally. The client half of the comparison cannot be read: "
<< window.line;
RecordProperty("client_emitter_present", clientEmitterExists ? 1 : 0);
RecordProperty("client_half_source", emitPeekClosed ? "emitter peek" : "ctu= field");
if (ctuIsWindowAligned) {
// Where the two roles ARE one window, the published field must agree with the
// emitter it is published from. A divergence here is PipeStats mis-publishing,
// which is a different defect from an emission-shape divergence and has to stay
// distinguishable from it.
EXPECT_EQ(shapeWindowCtu, clientEmissions)
<< "the published ctu= field and MGPipeTextureEmitter's own SubDataCount "
"disagree in a window that covers the same work. EmitOneLevel increments "
"both on the same line, so this is the counter's publication and not the "
"emission shape. " << shapeWindow.line;
} else {
RecordProperty("ctu_note",
"the client's summary window is not aligned with the server's in "
"this arm (two processes, two Present cadences), so ctu= is "
"recorded and the assertion reads the in-process emitter instead");
}
if (clientEmitterExists) {
EXPECT_GT(clientEmissions, 0)
<< "a MG_Impl/Pipe source emits CallClass::ClientTextureUploadEmissions on this "
@@ -688,18 +366,15 @@ void main() { oColor = texture(uTex, vUv); }
<< " texture upload emissions for this workload, but the client counted NONE. An "
"emitter that has stopped emitting reads exactly like no emitter at all in "
"this field, which is why this case asks the build rather than the number. "
<< clientWindow.line;
<< window.line;
EXPECT_EQ(clientEmissions, emissions)
<< "the CLIENT counted " << clientEmissions
<< " texture upload records and the SERVER counted " << emissions
<< " for the same workload in the same window. The two counting the same records "
"is the entire reason both are published (D-L): a divergence here is an "
"emission-shape divergence that SSIM is blind to and that costs ~+6 ms/frame "
"on Mali when it goes the wrong way. client=" << clientWindow.line
<< " server=" << shapeWindow.line;
EXPECT_EQ(clientEmissions, kGold.Emissions)
<< "the client's own count against the gold row, so that a run where BOTH sides "
"moved together is still red. " << clientWindow.line;
"on Mali when it goes the wrong way. "
<< window.line;
} else {
// Not merely "not asserted": on a tree with no client emitter the counter must be
// ZERO, and a non-zero one would mean the probe is looking for the wrong symbol -
@@ -710,7 +385,12 @@ void main() { oColor = texture(uTex, vUv); }
"tree, yet the client counted " << clientEmissions
<< " of them. Something is incrementing that counter which this build's probe "
"cannot see, so the probe is looking for the wrong symbol and this case's "
"arming decision is unreliable in both directions. " << clientWindow.line;
"arming decision is unreliable in both directions. " << window.line;
std::cout << "[ TextureUploadShape ] no P4a client emitter has landed on this tree "
"(the build's ClientTextureUploadEmissions probe found none), so this "
"run records the SERVER shape only and pins ctu=0. That is the expected "
"reading on the contract tree and it is not a divergence."
<< std::endl;
RecordProperty("client_side", "absent");
}
@@ -722,9 +402,6 @@ void main() { oColor = texture(uTex, vUv); }
EXPECT_TRUE(RegionIsMostly(lastContiguous, kInset, lastContiguous.Width() - kInset, kInset,
lastContiguous.Height() - kInset, "green", 0.0,
"the contiguous-band atlas"));
EXPECT_TRUE(RegionIsMostly(lastViewed, kInset, lastViewed.Width() - kInset, kInset,
lastViewed.Height() - kInset, "green", 0.0,
"the atlas written through a glTextureView"));
}
} // namespace
@@ -1,570 +0,0 @@
// MobileGL - MobileGL/MG_IntegrationTest/Scenarios/TextureViewAliasScenario.cpp
// Copyright (c) 2026 MobileGL-Dev
// Licensed under the GNU Lesser General Public License v3.0:
// https://www.gnu.org/licenses/gpl-3.0.txt
// https://www.gnu.org/licenses/lgpl-3.0.txt
// SPDX-License-Identifier: LGPL-3.0-only
// End of Source File Header
//
// Scenario - THE OWNER-KEYED EMISSION CURSOR (P3b/P4b, wave 2-D; ROADMAP's "dirty 归属反转 -
// 按存储属主键控的发射游标"). THE VERIFICATION HALF.
//
// THE CODE HALF ALREADY LANDED and this file is the gate it never had:
//
// * the drain cursor is keyed on the STORAGE OWNER - MG_Impl/Pipe/TextureEmit.h's
// NoteLevelDirty acquires a handle for whatever ITextureObject& reaches it, and what
// reaches it is the owner because TextureObjectView forwards MarkStorageDirty /
// MarkStorageDirtyRegion to the owner's methods (TextureObjectView.cpp:314-329);
// * the index remap is TextureObjectView::ToOwnerLevel / ToOwnerUploadTarget /
// ToOwnerRegionOffset (TextureObjectView.h:105-132), so a write through a level- or
// layer-restricted view names the OWNER's level and the OWNER's layer;
// * the wire half is MGPSamplerView + MGPResourceDesc::ViewOf (P5e tx2).
//
// WHAT GOES WRONG WITHOUT IT, which is why a scenario is owed rather than a unit case. A view
// and its owner share ONE set of dirty flags (the view owns no MipmapStorage at all) but would
// carry TWO emission cursors if the drain were keyed on the texture the application named.
// Whichever cursor drained first would clear the flag the other still needed, or both would
// ship the same texels twice. Neither failure is visible in the next frame's picture on most
// trees: the level that lost its record is uploaded again by the NEXT whole-level respecify,
// by a glGenerateMipmap, or by the monolith sync path, so the image is right one frame late.
// That is exactly the shape SSIM and every ordinary pixel case go green over.
//
// SO THE CLAIM IS ASSERTED ON BOTH CHANNELS AT ONCE, and neither alone is the gate
// (notes/recovered/wf2/final/part3.md 7.3, "门:新增场景,通过 view 上传、经属主采样(以及反
// 向),跨 draw 边界各一次"):
//
// PIXELS an upload through one name must be visible through the other name, in the SAME
// frame it was issued - and the layers the view does not address must not move.
// COUNTERS MGPipeTextureEmitter::SubDataCount() must have moved across the drain, and
// DrainListSize() must be back to zero after it. A SILENTLY EMPTY DRAIN - the
// two-cursor regression's actual signature - reads as a perfectly healthy run
// from the pixel side alone, because the repair paths above hide it.
//
// THE FOUR CASES are the two directions, each in a one-drain and a two-drain shape:
// (a) upload through a layer-restricted VIEW, sample through the OWNER;
// (b) upload through the OWNER, sample through the VIEW;
// (c) (a) across a draw boundary - draw, upload, draw, upload, draw - so the drain runs
// three times and the counters are read at each one;
// (d) (b) across the same boundary.
//
// THE RED-ONCE (R-16) this file was written against: make TextureObjectView::
// MarkStorageDirtyRegion call PipeNoteLevelDirty on ITSELF instead of forwarding to the owner -
// i.e. build the two-cursor shape the design rejects. Case (a) then goes red on stale OWNER
// texels AND on a SubDataCount that did not move, which is the pair this file exists to make
// simultaneous. Recorded in docs/Disaggregated/notes/p34b/espryt-d2.md.
//
// VIEWS ARE OPT-IN ON ESPRYT. DirectGLES withholds GL_ARB_texture_view unless
// MOBILEGL_ESPRYT_ENABLE_TEXTURE_VIEW=1 (ConfigLoader.cpp:213, Config.h:72), so every lane that
// runs this file sets it; a lane that does not green-skips through TextureViewUsable() rather
// than failing, the same shape TextureViewScenario uses.
#include <cstdint>
#include <cstdlib>
#include <string>
#include <vector>
#include "../Harness/HeadlessGL.h"
#include "../Harness/ScenarioFixture.h"
#include "../Harness/TextureEmitPeek.h"
#ifdef GLAPI
#undef GLAPI
#endif
#define GL_GLEXT_PROTOTYPES
#include <GL/gl.h>
#include <GL/glcorearb.h>
#undef GL_GLEXT_PROTOTYPES
namespace MGITest {
namespace {
constexpr int kSize = 64;
constexpr int kLayers = 4;
// Deliberately NOT 0: a view whose layer origin was dropped lands on layer 0, and the
// per-layer seeding below makes that land on a layer this file also reads back.
constexpr int kViewLayer = 2;
// The quad covers the whole surface; the inset keeps the assertions off the primitive
// edge, which is HeadlessGL.h's standing rule for a full-surface draw.
constexpr int kInset = 2;
constexpr const char* kVS = R"(#version 330 core
in vec2 aPos;
out vec2 vUv;
void main() {
vUv = aPos * 0.5 + 0.5;
gl_Position = vec4(aPos, 0.0, 1.0);
}
)";
// The VIEW's sampler: an ordinary 2D name over one of the owner's layers.
constexpr const char* kFS2D = R"(#version 330 core
in vec2 vUv;
uniform sampler2D uTex;
out vec4 oColor;
void main() { oColor = texture(uTex, vUv); }
)";
// The OWNER's sampler: the array, with the layer named by a uniform so one program
// serves every layer read-back below.
constexpr const char* kFSArray = R"(#version 330 core
in vec2 vUv;
uniform sampler2DArray uTex;
uniform int uLayer;
out vec4 oColor;
void main() { oColor = texture(uTex, vec3(vUv, float(uLayer))); }
)";
struct Vertex {
float x, y;
};
std::string Describe(const Rgba8& c) {
return "rgba(" + std::to_string(c.r) + "," + std::to_string(c.g) + "," + std::to_string(c.b) +
"," + std::to_string(c.a) + ")";
}
class TextureViewAliasScenario : public ScenarioTest {
protected:
void SetUp() override {
ScenarioTest::SetUp();
if (!Ready()) return;
if (!TextureViewUsable()) {
GTEST_SKIP() << "glTextureView is unavailable on backend " << Gl().BackendName()
<< " (GL_ARB_texture_view not advertised). On DirectGLES that is "
"the MOBILEGL_ESPRYT_ENABLE_TEXTURE_VIEW=1 opt-in this lane "
"did not set; every lane this scenario is registered in sets it.";
return;
}
std::string error;
m_program2D = CompileProgram(kVS, kFS2D, &error);
ASSERT_NE(m_program2D, 0u) << error;
m_programArray = CompileProgram(kVS, kFSArray, &error);
ASSERT_NE(m_programArray, 0u) << error;
static const Vertex quad[6] = {{-1.0f, -1.0f}, {1.0f, -1.0f}, {1.0f, 1.0f},
{-1.0f, -1.0f}, {1.0f, 1.0f}, {-1.0f, 1.0f}};
glGenBuffers(1, &m_quadBuffer);
glBindBuffer(GL_ARRAY_BUFFER, m_quadBuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(quad), quad, GL_STATIC_DRAW);
glGenVertexArrays(1, &m_vao);
glBindVertexArray(m_vao);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), nullptr);
glBindVertexArray(0);
glDisable(GL_DEPTH_TEST);
glDisable(GL_STENCIL_TEST);
ASSERT_EQ(FirstGLError(), GLenum(GL_NO_ERROR)) << "the fixture setup left a GL error behind";
}
void TearDown() override {
if (!Ready()) return;
glUseProgram(0);
glBindVertexArray(0);
glBindTexture(GL_TEXTURE_2D, 0);
glBindTexture(GL_TEXTURE_2D_ARRAY, 0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
for (const GLuint texture : m_textures) {
glDeleteTextures(1, &texture);
}
m_textures.clear();
if (m_vao != 0) glDeleteVertexArrays(1, &m_vao);
if (m_quadBuffer != 0) glDeleteBuffers(1, &m_quadBuffer);
if (m_program2D != 0) glDeleteProgram(m_program2D);
if (m_programArray != 0) glDeleteProgram(m_programArray);
}
// TextureViewScenario's probe, verbatim in intent: a trivial same-format full-range
// view. A backend that simply does not have the feature skips rather than failing
// every case in the file.
bool TextureViewUsable() {
GLuint storage = 0;
glGenTextures(1, &storage);
glBindTexture(GL_TEXTURE_2D, storage);
glTexStorage2D(GL_TEXTURE_2D, 1, GL_RGBA8, 1, 1);
glBindTexture(GL_TEXTURE_2D, 0);
GLuint view = 0;
glGenTextures(1, &view);
while (glGetError() != GL_NO_ERROR) {
}
glTextureView(view, GL_TEXTURE_2D, storage, GL_RGBA8, 0, 1, 0, 1);
const bool usable = glGetError() == GL_NO_ERROR;
glDeleteTextures(1, &view);
glDeleteTextures(1, &storage);
return usable;
}
GLuint MakeTexture() {
GLuint texture = 0;
glGenTextures(1, &texture);
m_textures.push_back(texture);
return texture;
}
// An immutable RGBA8 array with NEAREST filtering and one level, seeded per layer by
// CPU SUB-IMAGE rather than by rendering. Seeding through the GPU would additionally
// depend on a CPU sub-image reaching a layer whose content the GPU wrote, which is a
// different question and would make a failure here unattributable - the reason
// TextureViewScenario.cpp:717-721 gives for the same choice.
GLuint MakeSeededArray() {
const GLuint texture = MakeTexture();
glBindTexture(GL_TEXTURE_2D_ARRAY, texture);
glTexStorage3D(GL_TEXTURE_2D_ARRAY, 1, GL_RGBA8, kSize, kSize, kLayers);
glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glBindTexture(GL_TEXTURE_2D_ARRAY, 0);
for (int layer = 0; layer < kLayers; ++layer) {
UploadLayerThroughOwner(texture, layer, LayerSeed(layer));
}
return texture;
}
static Rgba8 LayerSeed(int layer) {
return Rgba8{static_cast<std::uint8_t>(10 + layer * 20),
static_cast<std::uint8_t>(200 - layer * 20), 30, 255};
}
static std::vector<std::uint8_t> Fill(Rgba8 colour) {
std::vector<std::uint8_t> texels(static_cast<std::size_t>(kSize) * kSize * 4);
for (std::size_t i = 0; i < texels.size(); i += 4) {
texels[i + 0] = colour.r;
texels[i + 1] = colour.g;
texels[i + 2] = colour.b;
texels[i + 3] = colour.a;
}
return texels;
}
void UploadLayerThroughOwner(GLuint owner, int layer, Rgba8 colour) {
const std::vector<std::uint8_t> texels = Fill(colour);
glBindTexture(GL_TEXTURE_2D_ARRAY, owner);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glTexSubImage3D(GL_TEXTURE_2D_ARRAY, 0, 0, 0, layer, kSize, kSize, 1, GL_RGBA,
GL_UNSIGNED_BYTE, texels.data());
glBindTexture(GL_TEXTURE_2D_ARRAY, 0);
}
// THE VIEW-SIDE WRITE. A single-layer GL_TEXTURE_2D view of the array: its own level 0
// is the owner's level <minLevel>, and its own layer 0 is the owner's layer
// kViewLayer. glTexSubImage2D here is what ToOwnerRegionOffset has to move.
void UploadThroughView(GLuint view, Rgba8 colour) {
const std::vector<std::uint8_t> texels = Fill(colour);
glBindTexture(GL_TEXTURE_2D, view);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, kSize, kSize, GL_RGBA, GL_UNSIGNED_BYTE,
texels.data());
glBindTexture(GL_TEXTURE_2D, 0);
}
GLuint MakeLayerView(GLuint owner) {
const GLuint view = MakeTexture();
glTextureView(view, GL_TEXTURE_2D, owner, GL_RGBA8, 0, 1, kViewLayer, 1);
EXPECT_EQ(glGetError(), static_cast<GLenum>(GL_NO_ERROR))
<< "2D_ARRAY -> 2D is a legal view pair";
glBindTexture(GL_TEXTURE_2D, view);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glBindTexture(GL_TEXTURE_2D, 0);
return view;
}
// ---- the two sampling draws. Both go to the default framebuffer, which is what
// makes them ordinary draws that reach the validate point and run the drain. ----
Image SampleThroughTheView(GLuint view) {
BindDefaultFramebuffer();
glViewport(0, 0, Gl().Width(), Gl().Height());
glUseProgram(m_program2D);
glUniform1i(glGetUniformLocation(m_program2D, "uTex"), 0);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, view);
glBindVertexArray(m_vao);
glDrawArrays(GL_TRIANGLES, 0, 6);
return ReadPixels(Gl().Width(), Gl().Height());
}
Image SampleThroughTheOwner(GLuint owner, int layer) {
BindDefaultFramebuffer();
glViewport(0, 0, Gl().Width(), Gl().Height());
glUseProgram(m_programArray);
glUniform1i(glGetUniformLocation(m_programArray, "uTex"), 0);
glUniform1i(glGetUniformLocation(m_programArray, "uLayer"), layer);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D_ARRAY, owner);
glBindVertexArray(m_vao);
glDrawArrays(GL_TRIANGLES, 0, 6);
return ReadPixels(Gl().Width(), Gl().Height());
}
// Whole-region rather than a spot check, for the reason HeadlessGL.h gives: three of
// four vertices carrying stale data still paints a correct centre pixel.
void ExpectWholeSurface(const Image& image, Rgba8 expected, const char* what) {
int offenders = 0;
Rgba8 firstOffender{};
int firstX = -1;
int firstY = -1;
const int x1 = image.Width() - kInset;
const int y1 = image.Height() - kInset;
int total = 0;
for (int y = kInset; y < y1; ++y) {
for (int x = kInset; x < x1; ++x) {
++total;
const Rgba8 actual = image.At(x, y);
const bool ok = std::abs(int(actual.r) - int(expected.r)) <= 2 &&
std::abs(int(actual.g) - int(expected.g)) <= 2 &&
std::abs(int(actual.b) - int(expected.b)) <= 2 &&
std::abs(int(actual.a) - int(expected.a)) <= 2;
if (!ok) {
if (offenders == 0) {
firstOffender = actual;
firstX = x;
firstY = y;
}
++offenders;
}
}
}
EXPECT_EQ(offenders, 0) << what << ": " << offenders << " of " << total
<< " pixels disagree; first at (" << firstX << ", " << firstY
<< ") is " << Describe(firstOffender) << ", expected "
<< Describe(expected) << " +/- 2";
}
// ---- the emitter half -------------------------------------------------------------
//
// WHY "THE EMITTER NEVER SAW ANY TEXTURE" IS A SKIP AND "IT SAW TEXTURES BUT EMITTED
// NO SUB-DATA" IS RED, and the distinction is the whole value of the reading. In a
// PULL build the emitter does not exist, and in a lane whose MOBILEGL_PIPE_PUSH mask
// has the texture-resource bit clear (D-K2's rows; the 0x5ff / 0x7ff refusal lanes)
// it exists but is deliberately not wired - in both the counters are flat and nothing
// is being claimed. The moment ANY create or respecify has been counted, the emitter
// is live for this process, and a drain that then put nothing on the wire is the
// two-cursor regression itself.
struct EmitWindow {
bool live = false;
TextureEmitCountersPeek before{};
TextureEmitCountersPeek after{};
unsigned long long SubDataDelta() const { return after.SubDataCount - before.SubDataCount; }
unsigned long long RefusedDelta() const {
return after.RefusedSubDataCount - before.RefusedSubDataCount;
}
unsigned long long DescribedDelta() const {
return (after.CreateCount - before.CreateCount) +
(after.RespecifyCount - before.RespecifyCount);
}
};
bool OpenEmitWindow(EmitWindow& window) {
window.live = PeekTextureEmitCounters(&window.before);
return window.live;
}
void CloseEmitWindow(EmitWindow& window) {
if (!window.live) return;
window.live = PeekTextureEmitCounters(&window.after);
}
// The emitter is armed in THIS process if it has ever described a texture to the
// applier. Checked on the window's `after` reading, because the seeding uploads that
// arm it happen inside the window.
bool EmitterIsArmed(const EmitWindow& window) const {
return window.live && (window.after.CreateCount != 0 || window.after.RespecifyCount != 0);
}
void ExpectTheDrainEmitted(const EmitWindow& window, const char* what) {
if (!window.live) {
RecordProperty("emit_counters", TextureEmitPeekSkipReason());
return;
}
if (!EmitterIsArmed(window)) {
// Not "not asserted": a lane where the emitter never described a single
// texture cannot have an emission cursor at all, so there is no cursor claim
// to make. Recorded so a run where the whole file quietly stopped asserting
// is visible in the ctest XML rather than invisible.
RecordProperty("emit_cursor", "the client texture emitter described no texture in "
"this process - the texture-resource subsystem bit "
"is clear in this lane");
return;
}
EXPECT_GT(window.SubDataDelta(), 0u)
<< what << ": the client texture emitter described "
<< window.DescribedDelta()
<< " texture(s) across this draw and put NO resource_subdata on the wire. A "
"drain that runs and emits nothing is exactly what a per-NAME emission "
"cursor produces when a view and its owner each hold one: whichever cursor "
"drained first cleared the dirty flag the other still needed. The picture "
"can still be right - the next whole-level respecify, a glGenerateMipmap or "
"the monolith sync path re-uploads the level one frame later - which is why "
"this counter and not the pixels is the load-bearing half here.";
EXPECT_EQ(window.RefusedDelta(), 0u)
<< what << ": the applier REFUSED " << window.RefusedDelta()
<< " of this drain's resource_subdata records. A refusal leaves the level dirty "
"and on the drain list (D-D5 step 1), which is the safe direction but not "
"the expected one for a glTexSubImage of a texture that has storage.";
EXPECT_EQ(window.after.DrainListSize, 0u)
<< what << ": " << window.after.DrainListSize
<< " (storage owner, upload target, level) key(s) are STILL owed after the "
"validate point. A level that bailed - no storage, no shadow, an empty box - "
"stays on the list; for this workload every level has immutable storage and "
"a non-empty dirty box, so nothing should have bailed.";
}
GLuint m_program2D = 0;
GLuint m_programArray = 0;
GLuint m_vao = 0;
GLuint m_quadBuffer = 0;
std::vector<GLuint> m_textures;
};
// ------------------------------------------------------------------------------------
// (a) UPLOAD THROUGH THE VIEW, SAMPLE THROUGH THE OWNER.
//
// The direction that pins ToOwnerRegionOffset: the view's own layer 0 is the owner's
// layer kViewLayer, so a remap that was dropped marks - and uploads - the owner's layer 0
// instead, and the two reads below catch it from both sides at once.
// ------------------------------------------------------------------------------------
TEST_F(TextureViewAliasScenario, SubImageThroughAViewIsSampledThroughTheOwner) {
if (!Ready() || IsSkipped()) return;
constexpr Rgba8 kPainted{255, 0, 255, 255};
EmitWindow window;
OpenEmitWindow(window);
const GLuint owner = MakeSeededArray();
const GLuint view = MakeLayerView(owner);
UploadThroughView(view, kPainted);
ASSERT_EQ(FirstGLError(), GLenum(GL_NO_ERROR)) << "writing through the view raised a GL error";
const Image throughOwner = SampleThroughTheOwner(owner, kViewLayer);
CloseEmitWindow(window);
ASSERT_EQ(FirstGLError(), GLenum(GL_NO_ERROR)) << "the sampling draw raised a GL error";
ExpectWholeSurface(throughOwner, kPainted,
"the owner's layer kViewLayer must carry the texels written through "
"the view's own layer 0");
ExpectTheDrainEmitted(window, "upload through a layer-restricted view");
// THE NEGATIVE HALF, and it is what separates "the remap was dropped" from "the
// upload never arrived": a lost layer origin writes the owner's layer 0, which this
// read would see as an untouched layer that moved.
const Image layerZero = SampleThroughTheOwner(owner, 0);
ExpectWholeSurface(layerZero, LayerSeed(0),
"the owner's layer 0 is outside the view's window and must not have "
"been written");
}
// ------------------------------------------------------------------------------------
// (b) UPLOAD THROUGH THE OWNER, SAMPLE THROUGH THE VIEW.
//
// The reverse direction, and the one that fails when the VIEW holds a cursor of its own:
// the owner's cursor drains and clears the shared flag, and the view's sampler then
// resolves a resource the record never reached.
// ------------------------------------------------------------------------------------
TEST_F(TextureViewAliasScenario, SubImageThroughTheOwnerIsSampledThroughTheView) {
if (!Ready() || IsSkipped()) return;
constexpr Rgba8 kPainted{0, 0, 255, 255};
EmitWindow window;
OpenEmitWindow(window);
const GLuint owner = MakeSeededArray();
const GLuint view = MakeLayerView(owner);
UploadLayerThroughOwner(owner, kViewLayer, kPainted);
ASSERT_EQ(FirstGLError(), GLenum(GL_NO_ERROR)) << "writing through the owner raised a GL error";
const Image throughView = SampleThroughTheView(view);
CloseEmitWindow(window);
ASSERT_EQ(FirstGLError(), GLenum(GL_NO_ERROR)) << "the sampling draw raised a GL error";
ExpectWholeSurface(throughView, kPainted,
"the view must read the texels written through the owner's own name "
"into the layer the view addresses");
ExpectTheDrainEmitted(window, "upload through the storage owner");
}
// ------------------------------------------------------------------------------------
// (c) THE SAME, ACROSS DRAW BOUNDARIES, so the drain runs more than once.
//
// WHY THE SECOND AND THIRD DRAINS ARE THE POINT. The first drain of a texture's life
// carries the whole level anyway - the storage definition made it dirty - so a cursor
// that is keyed on the wrong object still ships the right texels by accident. It is the
// NEXT drain, where only the sub-region written since the last validate point is owed,
// that can lose a record and look healthy.
// ------------------------------------------------------------------------------------
TEST_F(TextureViewAliasScenario, TheViewUploadDrainRunsAgainAfterADrawBoundary) {
if (!Ready() || IsSkipped()) return;
constexpr Rgba8 kFirst{255, 0, 255, 255};
constexpr Rgba8 kSecond{0, 255, 255, 255};
const GLuint owner = MakeSeededArray();
const GLuint view = MakeLayerView(owner);
// Drain 1: the storage definition's own upload. Read only to close the window.
const Image seeded = SampleThroughTheOwner(owner, kViewLayer);
ExpectWholeSurface(seeded, LayerSeed(kViewLayer), "the seeded layer before any view write");
Gl().EndFrame();
EmitWindow second;
OpenEmitWindow(second);
UploadThroughView(view, kFirst);
const Image afterFirst = SampleThroughTheOwner(owner, kViewLayer);
CloseEmitWindow(second);
ExpectWholeSurface(afterFirst, kFirst, "the first view write, through the owner");
ExpectTheDrainEmitted(second, "the SECOND drain (first view write after a draw boundary)");
Gl().EndFrame();
EmitWindow third;
OpenEmitWindow(third);
UploadThroughView(view, kSecond);
const Image afterSecond = SampleThroughTheOwner(owner, kViewLayer);
CloseEmitWindow(third);
ExpectWholeSurface(afterSecond, kSecond, "the second view write, through the owner");
ExpectTheDrainEmitted(third, "the THIRD drain (second view write after a draw boundary)");
ASSERT_EQ(FirstGLError(), GLenum(GL_NO_ERROR)) << "the workload left a GL error behind";
const Image layerZero = SampleThroughTheOwner(owner, 0);
ExpectWholeSurface(layerZero, LayerSeed(0),
"two writes through the view must still have left layer 0 alone");
}
// ------------------------------------------------------------------------------------
// (d) the owner direction across the same boundary.
// ------------------------------------------------------------------------------------
TEST_F(TextureViewAliasScenario, TheOwnerUploadDrainRunsAgainAfterADrawBoundary) {
if (!Ready() || IsSkipped()) return;
constexpr Rgba8 kFirst{0, 0, 255, 255};
constexpr Rgba8 kSecond{255, 255, 0, 255};
const GLuint owner = MakeSeededArray();
const GLuint view = MakeLayerView(owner);
const Image seeded = SampleThroughTheView(view);
ExpectWholeSurface(seeded, LayerSeed(kViewLayer),
"the view must read its layer's seed before any owner write");
Gl().EndFrame();
EmitWindow second;
OpenEmitWindow(second);
UploadLayerThroughOwner(owner, kViewLayer, kFirst);
const Image afterFirst = SampleThroughTheView(view);
CloseEmitWindow(second);
ExpectWholeSurface(afterFirst, kFirst, "the first owner write, through the view");
ExpectTheDrainEmitted(second, "the SECOND drain (first owner write after a draw boundary)");
Gl().EndFrame();
EmitWindow third;
OpenEmitWindow(third);
UploadLayerThroughOwner(owner, kViewLayer, kSecond);
const Image afterSecond = SampleThroughTheView(view);
CloseEmitWindow(third);
ExpectWholeSurface(afterSecond, kSecond, "the second owner write, through the view");
ExpectTheDrainEmitted(third, "the THIRD drain (second owner write after a draw boundary)");
ASSERT_EQ(FirstGLError(), GLenum(GL_NO_ERROR)) << "the workload left a GL error behind";
}
} // namespace
} // namespace MGITest
@@ -331,56 +331,9 @@ void main (void)
constexpr unsigned kSkipComponentCount = 4 * 4 + (1 + 2 + 3 + 4 + 1 + 2); // 16 values + 13 skipped
constexpr unsigned kSkipVertexCount = 6;
// HOW THE CAPTURE BUFFER'S STORE IS DECLARED, which is the whole subject of the two
// orphan cases at the end of this file (P3b/P4b espryt D1 slice 1).
//
// glBufferData(size, data) DECLARES the content: the application supplied every byte,
// and under a transport those bytes reach the server as resource_subdata records behind
// the respecify, so a gap in the staged coverage is a MISSING RECORD. glBufferData(size,
// NULL) ORPHANS the store instead: the application has said, in the API, that every byte
// it does not upload afterwards is UNDEFINED. Both are ordinary - "orphan, upload part of
// it, capture into it" is the streaming idiom - and the scatter is a read-modify-write, so
// the two shapes are the difference between "read the old bytes" and "there are no old
// bytes to read, and the API says nobody may look".
enum class CaptureStoreShape {
Declared, // glBufferData(size, prefill): every byte declared and staged.
OrphanedPartial, // glBufferData(size, NULL) + glBufferSubData over the FIRST HALF.
OrphanedWhole, // glBufferData(size, NULL) and nothing staged at all.
};
// The floats the OrphanedPartial shape uploads: the first half of the records, so the
// buffer has a staged region and an unstaged one and the assertions can tell them apart.
constexpr unsigned kOrphanStagedFloats = (kSkipVertexCount / 2) * kSkipComponentCount;
// Is this component's offset WITHIN one record a captured varying rather than one of the
// gl_SkipComponents holes? The holes keep whatever the destination held, which past the
// staged region is undefined by the application's own declaration and must not be
// asserted; the varyings are the capture and must be there whatever the store's shape.
bool SkipComponentsIndexIsCaptured(unsigned indexInRecord) {
static const unsigned kValueOffsets[4] = {1, 8, 17, 25};
for (const unsigned offset : kValueOffsets) {
if (indexInRecord >= offset && indexInRecord < offset + 4) return true;
}
return false;
}
// The capture RANGE the writeback has to cross when the point of a case is that range's
// SIZE rather than its contents (P3b/P4b espryt D1 slice 2). One SEG_EVENT record may be
// at most half the event ring, which defaults to 256 KiB - so 1 MiB is about eight times
// what a whole-range post can ever carry, and no reasonable retuning of the ring makes it
// fit.
constexpr GLsizeiptr kLargeCaptureRangeBytes = 1024 * 1024;
// Runs skip_components and reports what came back. `outCaptured` is the raw
// readback so a failure can say whether anything was written at all.
//
// `storeBytes` widens the capture BUFFER without widening the capture: the records are the
// same six, but glBindBufferBase binds the whole store, so the range the backend mirrors
// back is `storeBytes` wide. That is the only way to reach a writeback of a given size
// from a test without drawing a proportional number of primitives.
void RunSkipComponentsCapture(std::vector<float>& outCaptured, std::string* buildLog,
CaptureStoreShape shape = CaptureStoreShape::Declared,
GLsizeiptr storeBytes = 0) {
void RunSkipComponentsCapture(std::vector<float>& outCaptured, std::string* buildLog) {
outCaptured.clear();
const GLuint program = BuildProgram(kXfbVertexSource, kXfbFragmentSource, SkipComponentsVaryings(),
@@ -409,39 +362,21 @@ void main (void)
const unsigned floatCount = kSkipVertexCount * kSkipComponentCount;
const GLsizeiptr byteSize = static_cast<GLsizeiptr>(sizeof(float) * floatCount);
// The STORE, which is what glBindBufferBase binds and therefore what the backend
// mirrors back; the capture itself is `byteSize` of it either way.
const GLsizeiptr storeSize = storeBytes > byteSize ? storeBytes : byteSize;
const unsigned storeFloats = static_cast<unsigned>(storeSize / sizeof(float));
GLuint captureBuffer = 0;
glGenBuffers(1, &captureBuffer);
glBindBuffer(GL_ARRAY_BUFFER, captureBuffer);
glBufferData(GL_ARRAY_BUFFER, storeSize, nullptr, GL_STATIC_READ);
glBufferData(GL_ARRAY_BUFFER, byteSize, nullptr, GL_STATIC_READ);
glBindBufferBase(GL_TRANSFORM_FEEDBACK_BUFFER, 0, captureBuffer);
glBindBuffer(GL_ARRAY_BUFFER, 0);
// The pre-fill that makes "nothing was captured" recognisable.
std::vector<float> prefill(storeFloats);
for (unsigned i = 0; i < storeFloats; ++i) {
std::vector<float> prefill(floatCount);
for (unsigned i = 0; i < floatCount; ++i) {
prefill[i] = -1.0f - static_cast<float>(i);
}
glBindBuffer(GL_ARRAY_BUFFER, captureBuffer);
switch (shape) {
case CaptureStoreShape::Declared:
glBufferData(GL_ARRAY_BUFFER, storeSize, prefill.data(), GL_STATIC_DRAW);
break;
case CaptureStoreShape::OrphanedPartial:
// The streaming idiom: orphan the store, then upload only the part the
// application cares about keeping.
glBufferData(GL_ARRAY_BUFFER, storeSize, nullptr, GL_STATIC_DRAW);
glBufferSubData(GL_ARRAY_BUFFER, 0,
static_cast<GLsizeiptr>(sizeof(float) * kOrphanStagedFloats), prefill.data());
break;
case CaptureStoreShape::OrphanedWhole:
glBufferData(GL_ARRAY_BUFFER, storeSize, nullptr, GL_STATIC_DRAW);
break;
}
glBufferData(GL_ARRAY_BUFFER, byteSize, prefill.data(), GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glEnable(GL_RASTERIZER_DISCARD);
@@ -533,141 +468,6 @@ void main (void)
return ::testing::AssertionSuccess();
}
// The orphaned store's weaker contract, checked exactly as far as the API allows.
//
// Below `stagedFloats` the destination's bytes are the application's - it uploaded them -
// so the FULL assertion holds: the varyings are the capture and the gl_SkipComponents
// holes still carry the pre-fill, which is the read-modify-write actually having read
// something. Above it the application declared the bytes undefined, so only the captured
// varyings are asserted; the holes are whatever the server had and are nobody's to check.
//
// WHAT THIS CATCHES, and it is the whole point of the two cases: the failure mode is not a
// wrong number, it is the pre-fill surviving where a varying belongs - the capture target
// silently dropped and the buffer left holding its pre-draw bytes under GL_NO_ERROR.
::testing::AssertionResult CheckSkipComponentsOrphaned(const std::vector<float>& captured,
unsigned stagedFloats) {
const std::vector<float> expected = SkipComponentsExpected();
if (captured.size() != expected.size()) {
return ::testing::AssertionFailure()
<< "readback size " << captured.size() << " != " << expected.size();
}
for (std::size_t i = 0; i < expected.size(); ++i) {
const bool isCaptured =
SkipComponentsIndexIsCaptured(static_cast<unsigned>(i) % kSkipComponentCount);
if (i >= stagedFloats && !isCaptured) continue;
if (std::fabs(captured[i] - expected[i]) > 0.0125f) {
::testing::AssertionResult failure = ::testing::AssertionFailure();
failure << (isCaptured ? "captured varying" : "preserved hole") << " at index " << i
<< (i < stagedFloats ? " (inside the uploaded region)" : " (past the uploaded region)")
<< ": got " << captured[i] << ", expected " << expected[i];
if (isCaptured && std::fabs(captured[i] - (-1.0f - static_cast<float>(i))) <= 0.0125f) {
failure << " - this component is still the PRE-FILL, so the capture never reached this "
"target at all";
}
return failure;
}
}
return ::testing::AssertionSuccess();
}
// THE OTHER WRITEBACK PRODUCER (P3b/P4b espryt D1 slice 2).
//
// A capture list with no gl_SkipComponents and one buffer is expressible on ES directly,
// so the driver writes the application's buffer itself and the mirror-back is
// ReadbackCapturedRanges' rather than ScatterCapturedRecords'. That is a DIFFERENT
// OnBufferWriteback call site - it posts from a live glMapBufferRange mapping instead of a
// staged vector - with the same unbounded record behind it, so it needs its own case or
// half the fix is untested. `value1` alone is a 16-byte record; the bound range is the
// whole store, which is what the writeback crosses.
void RunPlainCaptureIntoLargeRange(std::vector<float>& outCaptured, std::string* buildLog) {
outCaptured.clear();
const GLuint program = BuildProgram(kXfbVertexSource, kXfbFragmentSource, {"value1"},
GL_INTERLEAVED_ATTRIBS, buildLog);
ASSERT_NE(program, 0u) << "plain capture program failed to link: " << (buildLog ? *buildLog : "");
glUseProgram(program);
const std::vector<float> vertices = {
-1.0f, -1.0f, -1.0f, 1.0f, 1.0f, -1.0f, -2.0f, 1.0f, -1.0f, 1.0f, -3.0f, 1.0f,
1.0f, 1.0f, 4.0f, 1.0f, -1.0f, 1.0f, 5.0f, 1.0f, 1.0f, -1.0f, 6.0f, 1.0f,
};
GLuint vao = 0;
GLuint vbo = 0;
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
glGenBuffers(1, &vbo);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, static_cast<GLsizeiptr>(sizeof(float) * vertices.size()), vertices.data(),
GL_STATIC_DRAW);
const GLint location = glGetAttribLocation(program, "vertex");
if (location >= 0) {
glEnableVertexAttribArray(static_cast<GLuint>(location));
glVertexAttribPointer(static_cast<GLuint>(location), 4, GL_FLOAT, GL_FALSE, 0, nullptr);
}
const unsigned capturedFloats = kSkipVertexCount * 4;
const unsigned storeFloats = static_cast<unsigned>(kLargeCaptureRangeBytes / sizeof(float));
std::vector<float> prefill(storeFloats);
for (unsigned i = 0; i < storeFloats; ++i) prefill[i] = -1.0f - static_cast<float>(i);
GLuint captureBuffer = 0;
glGenBuffers(1, &captureBuffer);
glBindBuffer(GL_ARRAY_BUFFER, captureBuffer);
glBufferData(GL_ARRAY_BUFFER, kLargeCaptureRangeBytes, prefill.data(), GL_STATIC_READ);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glEnable(GL_RASTERIZER_DISCARD);
glBindBufferBase(GL_TRANSFORM_FEEDBACK_BUFFER, 0, captureBuffer);
glBeginTransformFeedback(GL_TRIANGLES);
glDrawArrays(GL_TRIANGLES, 0, static_cast<GLsizei>(kSkipVertexCount));
glEndTransformFeedback();
glDisable(GL_RASTERIZER_DISCARD);
outCaptured.resize(capturedFloats);
const GLsizeiptr capturedBytes = static_cast<GLsizeiptr>(sizeof(float) * capturedFloats);
glBindBufferRange(GL_TRANSFORM_FEEDBACK_BUFFER, 0, captureBuffer, 0, capturedBytes);
const void* mapped = glMapBufferRange(GL_TRANSFORM_FEEDBACK_BUFFER, 0, capturedBytes, GL_MAP_READ_BIT);
if (mapped != nullptr) {
std::memcpy(outCaptured.data(), mapped, static_cast<std::size_t>(capturedBytes));
glUnmapBuffer(GL_TRANSFORM_FEEDBACK_BUFFER);
}
glDisableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glDeleteBuffers(1, &vbo);
glDeleteBuffers(1, &captureBuffer);
glBindVertexArray(0);
glDeleteVertexArrays(1, &vao);
glUseProgram(0);
glDeleteProgram(program);
glBindBufferBase(GL_TRANSFORM_FEEDBACK_BUFFER, 0, 0);
}
// value1 == |vertex| * 1, one tight vec4 record per vertex.
::testing::AssertionResult CheckPlainCapture(const std::vector<float>& captured) {
const std::vector<float> vertices = {
-1.0f, -1.0f, -1.0f, 1.0f, 1.0f, -1.0f, -2.0f, 1.0f, -1.0f, 1.0f, -3.0f, 1.0f,
1.0f, 1.0f, 4.0f, 1.0f, -1.0f, 1.0f, 5.0f, 1.0f, 1.0f, -1.0f, 6.0f, 1.0f,
};
if (captured.size() != vertices.size()) {
return ::testing::AssertionFailure()
<< "readback size " << captured.size() << " != " << vertices.size();
}
for (std::size_t i = 0; i < vertices.size(); ++i) {
const float expected = std::fabs(vertices[i]);
if (std::fabs(captured[i] - expected) > 0.0125f) {
::testing::AssertionResult failure = ::testing::AssertionFailure();
failure << "capture mismatch at index " << i << ": got " << captured[i] << ", expected "
<< expected;
if (std::fabs(captured[i] - (-1.0f - static_cast<float>(i))) <= 0.0125f) {
failure << " - still the pre-fill, so nothing was mirrored back";
}
return failure;
}
}
return ::testing::AssertionSuccess();
}
// The harness turns "no context came up" into a clean skip, and a skip is
// indistinguishable from a pass in a ctest summary. For this scenario that
// is a hole rather than a courtesy: the defect it pins is DirectVulkan's
@@ -702,85 +502,6 @@ void main (void)
}
};
// ------------------------------------------- P3b/P4b espryt D1 slice 1: orphaned targets
//
// AN ORPHANED CAPTURE TARGET IS A LEGAL TARGET, and under a transport it was being thrown
// away. The scattered capture is a read-modify-write of the destination's PRE-CAPTURE
// bytes (the gl_SkipComponents holes have to keep them), and under split those bytes are
// the SERVER's staged shadow rather than a frontend MappedData(). A buffer the
// application orphaned and then only partly uploaded has no staged bytes for the rest -
// legitimately, because it declared them undefined - and the scatter read that as "this
// target has no pre-capture bytes, discard it", which is a total loss of the varyings
// under GL_NO_ERROR. The whole-store case (no upload at all) discarded silently; the
// partial one asked the staged-coverage assertion for a range wider than anything staged
// and died on Fatal{StageSnapshotTooNarrow, "xfb_scatter_pre_capture"}.
//
// The monolith arm has always been right here: `staged` is a value-initialised
// Vector<Uint8>, so an unreadable source means the scatter runs over zeroes and uploads
// them - which is byte for byte what it gets from a fresh MappedData(). Skipping the COPY
// is the whole of the difference between the two arms; skipping the TARGET was the bug.
//
// Both cases run on the split arms, where they are the red-once, and on the ambient
// monolith arms, where they are the control that says the expectation itself is right.
TEST_F(XfbAfterClipDistanceScenario, OrphanedCaptureTargetWithAPartialUploadKeepsItsVaryings) {
if (!Ready()) return;
std::vector<float> captured;
std::string log;
RunSkipComponentsCapture(captured, &log, CaptureStoreShape::OrphanedPartial);
EXPECT_TRUE(CheckSkipComponentsOrphaned(captured, kOrphanStagedFloats));
EXPECT_EQ(glGetError(), static_cast<GLenum>(GL_NO_ERROR));
}
TEST_F(XfbAfterClipDistanceScenario, OrphanedCaptureTargetWithNoUploadAtAllKeepsItsVaryings) {
if (!Ready()) return;
std::vector<float> captured;
std::string log;
RunSkipComponentsCapture(captured, &log, CaptureStoreShape::OrphanedWhole);
// Nothing was ever staged, so every hole is undefined and only the varyings are
// checked - which is still the entire capture.
EXPECT_TRUE(CheckSkipComponentsOrphaned(captured, 0));
EXPECT_EQ(glGetError(), static_cast<GLenum>(GL_NO_ERROR));
}
// ------------------------------------- P3b/P4b espryt D1 slice 2: a capture range that
// does not fit one reverse-channel record
//
// Under a transport the captured bytes go back to the client INLINE in a SEG_EVENT
// record, and a ring producer refuses any record above half its capacity OUTRIGHT -
// always, not "when full", because above half a capacity a record is placeable at some
// head offsets and not at others and waiting for room would be a hang. SEG_EVENT defaults
// to 256 KiB. Both XFB writeback producers posted the WHOLE bound range as one record, so
// a capture target wider than ~128 KiB was Fatal{EventRingOverflow} and the server
// process died - on a buffer size, with nothing else wrong.
//
// A megabyte is about eight times what one record can ever be. The capture is still six
// records; it is glBindBufferBase over the whole store that makes the MIRRORED RANGE a
// megabyte, which is what a real capture buffer looks like and what the producer has to
// survive.
//
// TWO CASES BECAUSE THERE ARE TWO PRODUCERS. The skip_components layout is not
// expressible on ES, so it goes through ScatterCapturedRecords and posts from a staged
// vector; the plain single-varying layout is, so the driver writes the application's
// buffer and ReadbackCapturedRanges posts from a live glMapBufferRange mapping. They are
// different call sites with the same defect behind them.
TEST_F(XfbAfterClipDistanceScenario, AScatteredCaptureIntoAMegabyteRangeReachesTheApplication) {
if (!Ready()) return;
std::vector<float> captured;
std::string log;
RunSkipComponentsCapture(captured, &log, CaptureStoreShape::Declared, kLargeCaptureRangeBytes);
EXPECT_TRUE(CheckSkipComponents(captured));
EXPECT_EQ(glGetError(), static_cast<GLenum>(GL_NO_ERROR));
}
TEST_F(XfbAfterClipDistanceScenario, APlainCaptureIntoAMegabyteRangeReachesTheApplication) {
if (!Ready()) return;
std::vector<float> captured;
std::string log;
RunPlainCaptureIntoLargeRange(captured, &log);
EXPECT_TRUE(CheckPlainCapture(captured));
EXPECT_EQ(glGetError(), static_cast<GLenum>(GL_NO_ERROR));
}
// Control: the capture on its own must work.
TEST_F(XfbAfterClipDistanceScenario, SkipComponentsCaptureAlone) {
if (!Ready()) return;
+13 -99
View File
@@ -112,30 +112,17 @@ namespace MobileGL::MG_Pipe {
// path that regressed are four different findings, and clearing one must not disarm the
// other three.
//
// FOUR OF THE SIX FAMILIES CARRY A DEPENDENCY and it is diagnosed at the first use, never
// half-run - one Resolve<Family>SubsystemArm per family beside the backend's existing
// ResolveResourceSubsystemArm, and lazy rather than at bring-up because a pre-flight child
// dying on a signal makes a whole lane SKIP green.
//
// THE ROWS ARE IN SubsystemDeps.def, ONCE (P3b/P4b R-5), and this comment no longer
// restates them. It used to, and it was WRONG in two ways that nothing could fail: it said
// "THREE OF THEM" when there are six rows, and it said "the mirror pairs (10 without 11,
// 10 without 9, 7 without 10) are all fine" when 10-without-11 is precisely D-K2's FOURTH
// row (ID-14/ID-15) - refused by the server and withheld by the client, with PipeFill.cpp
// saying so out loud: "The brief's original 'bit 10 without 11 is fine' is WITHDRAWN for
// P4a as built." The audit found the same pair of defects repeated in
// MG_Backend/DirectGLES/Managers.h's header, i.e. in the header of the file that
// implements the refusal.
//
// THE MIRROR PAIRS THAT REALLY ARE FINE, said out loud rather than left as an absence,
// because a table is only trustworthy if what it does NOT contain was decided:
// - bit 10 set, bit 9 clear: FINE. The legacy FBO sync reaches the texture twin through
// SyncTextureObjectToBackend, which dispatches to the handle arm by itself.
// - bit 11 set, bit 9 clear: FINE, for the same reason - a sampler view names a texture,
// never a framebuffer.
// - bit 7 set, bit 10 clear: FINE, and it is P3a's shipped configuration.
// - bit 12 set with any or none of 9/10/11: FINE, per its own row.
// - bit 10 set, bit 11 clear and its mirror are NOT fine; that is the fourth row.
// THREE OF THEM HAVE A DEPENDENCY and it is diagnosed at the first use, never half-run -
// one Resolve<Family>SubsystemArm per family beside the backend's existing
// ResolveResourceSubsystemArm, modelled on the bit-8-requires-bit-7 refusal it already
// ships, and lazy rather than at bring-up because a pre-flight child dying on a signal
// makes a whole lane SKIP green: bit 11 requires bit 10 because
// every MGPBoundView::Texture and MGPImageView::Res names a Texture handle and only bit 10
// puts one in the slot table; bit 9 requires bit 10 because MGPSurface::Res does; and bit
// 10 requires bit 7 because a buffer texture's BufferForTexBuffer names a Buffer handle.
// The mirror pairs (10 without 11, 10 without 9, 7 without 10) are all fine, and are
// stated as such because an unreachable branch that says something different is how the
// reachable one drifts. Bit 12 depends on nothing.
inline constexpr Uint64 kMGPipeSubsystemFramebuffer = 1ull << 9; // set_framebuffer_state
inline constexpr Uint64 kMGPipeSubsystemTextureResources = 1ull << 10; // texture + renderbuffer
// resource_*, set_texture_params
@@ -150,9 +137,8 @@ namespace MobileGL::MG_Pipe {
// path that regressed and a buffer path that regressed are different findings, and
// clearing one must not disarm the other.
//
// Its dependency row is in SubsystemDeps.def with the other five (P3b/P4b R-5). It used to
// be stated here instead, fifteen lines away from the block that stated the other three -
// which is how "THREE OF THEM" above stayed wrong through two phases.
// BIT 13 REQUIRES BIT 7, and for bit 11's reason: every MGPBufferRange::Res names a Buffer
// handle, and only bit 7 puts one in the slot table.
inline constexpr Uint64 kMGPipeSubsystemBufferBindings = 1ull << 13;
// bits 14..62 reserved for the later phases, allocated in ROADMAP order.
// NOT a subsystem, a BEHAVIOUR: turn OFF client-side content addressing of CSOs, so
@@ -180,78 +166,6 @@ namespace MobileGL::MG_Pipe {
(kMGPipeSubsystemsMigratedAtP4a | kMGPipeSubsystemBufferBindings),
"the P5e phase constant and P5e's subsystem bit have drifted");
// ---- D-K2's dependency rule, in ONE place (P3b/P4b R-5) --------------------------------
//
// The rows, their reasons and the argument for a table rather than six comments are in
// SubsystemDeps.def. This is the expansion both readers are meant to end up on; the
// anti-drift property is already live through
// MG_Test/Backend/DirectGLES/SubsystemDepsTest.cpp, which drives the client check and the
// server gate at every interesting mask and compares both against these rows.
#include "SubsystemDeps.def"
struct MGPipeSubsystemDependencyRow {
Uint64 Family; // exactly one kMGPipeSubsystem* bit
Uint64 Requires; // the bits MOBILEGL_PIPE_PUSH must ALSO carry; 0 is a row, not a gap
const char* Why;
};
#define MGL_SUBSYSTEM_DEPENDENCY_ROW(family, requires_, why) {family, requires_, why},
inline constexpr MGPipeSubsystemDependencyRow kMGPipeSubsystemDependencies[] = {
MGL_SUBSYSTEM_DEPENDENCY_LIST(MGL_SUBSYSTEM_DEPENDENCY_ROW)};
#undef MGL_SUBSYSTEM_DEPENDENCY_ROW
// The bits `subsystem` additionally needs, or 0 for a family with no row. A family with no
// row and a family whose row says 0 are the same answer ON PURPOSE: both mean "nothing else
// is required", and the table covers its families exhaustively so the two cannot be
// confused for "I forgot to look".
inline constexpr Uint64 MGPipeSubsystemRequires(Uint64 subsystem) {
Uint64 required = 0;
for (const MGPipeSubsystemDependencyRow& row : kMGPipeSubsystemDependencies) {
if ((subsystem & row.Family) != 0) required |= row.Requires;
}
return required;
}
// NOT TRANSITIVE, and that is load-bearing: each reader tests the required BITS against
// MOBILEGL_PIPE_PUSH alone and never the other family's liveness, because Espryt's
// resolvers classify their arms from that mask alone (PipeFill.cpp's own argument;
// TextureEmitTest.cpp pins it). A transitive closure here would make the two sides disagree
// at some mask - the failure this table exists to prevent.
inline constexpr Bool MGPipeSubsystemDependenciesAreSet(Uint64 subsystem, Uint64 pushMask) {
const Uint64 required = MGPipeSubsystemRequires(subsystem);
return (pushMask & required) == required;
}
// The ROW'S OWN REASON, so a reader that refuses prints the table's sentence instead of a
// copy of it (P3b/P4b wave 2-D package D3). Empty for a family whose row requires nothing,
// which is the same answer as "there is nothing to explain": a reader only asks after
// MGPipeSubsystemDependenciesAreSet has already said no, and that cannot happen for a row
// that requires 0.
inline constexpr const char* MGPipeSubsystemDependencyWhy(Uint64 subsystem) {
for (const MGPipeSubsystemDependencyRow& row : kMGPipeSubsystemDependencies) {
if ((subsystem & row.Family) != 0 && row.Requires != 0) return row.Why;
}
return "";
}
// Rows 1 and 6 became live behaviour when D3 made every reader read the table (before that
// the bit-7 tests were hard-coded in Managers.cpp and DirectGLES.cpp and these rows were
// dead data). An edit that drops either row now makes BOTH readers agree, so nothing
// downstream can catch it; these two lines can.
static_assert(MGPipeSubsystemRequires(kMGPipeSubsystemVertexInput) == kMGPipeSubsystemResources,
"D-K2's vertex-input row (bit 8 requires bit 7) has gone missing");
static_assert(MGPipeSubsystemRequires(kMGPipeSubsystemBufferBindings) == kMGPipeSubsystemResources,
"D-K2's buffer-bindings row (bit 13 requires bit 7) has gone missing");
static_assert(MGPipeSubsystemRequires(kMGPipeSubsystemTextureResources) ==
(kMGPipeSubsystemResources | kMGPipeSubsystemSamplers),
"D-K2's fourth row (bit 10 requires bit 11) has gone missing again");
static_assert(MGPipeSubsystemRequires(kMGPipeSubsystemPrograms) == 0,
"bit 12 depends on nothing, and that is a row rather than an absence");
static_assert(!MGPipeSubsystemDependenciesAreSet(kMGPipeSubsystemTextureResources, 0x7ffull),
"0x7ff is the mask whose texture family Espryt refuses; the table must agree");
static_assert(MGPipeSubsystemDependenciesAreSet(kMGPipeSubsystemTextureResources, 0x1fffull),
"0x1fff is P4a's own arm and every row of it must be satisfied");
// The catalogue itself. Only macros, so it is safe to expand inside the namespace, and
// consumers (the unit test, later the transport) get MGP_CALL_LIST from this header.
#include "PipeCalls.def"
+6 -53
View File
@@ -17,20 +17,9 @@
// Today this traffic is 95 call sites across 17 methods poked directly into frontend
// objects. gallium has no vocabulary for shadow writeback, GPU-write notification, texture
// re-send requests or default-framebuffer geometry, because in Mesa the state tracker and
// the driver share an address space. Naming them as nine callbacks plus one forward
// the driver share an address space. Naming them as ten callbacks plus one forward
// terminator (MGPipeContext::ResourceSubDataComplete) is the deliberate deviation (D8).
//
// NINE, NOT THE TEN PLAN B WROTE. The tenth was OnXfbScatterReady, and it went with the
// design it belonged to: plan B put the XFB scatter on the CLIENT (the server would hand
// back the packed scratch and the client would run the patch loop over its own shadow), so
// there had to be a callback that told the client the layout. P5c/P5f went the other way -
// the server reads its OWN staged shadow, scatters there and returns the reconciled range
// through OnBufferWriteback, which needs no second callback - and the declaration was left
// behind with zero producers, zero consumers and no EventKind of its own. Deleted here
// (P3b/P4b espryt D1 slice 3) rather than carried: an entry that cannot fire is one every
// reader of this file has to rule out by hand, and the size assertion below made it look
// load-bearing.
//
// Installed at context creation. In a monolith these are direct calls; under split they are
// records on the reverse channel, and their ORDER is a correctness requirement rather than
// an optimization (section 7.4).
@@ -57,53 +46,17 @@ namespace MobileGL::MG_Pipe {
void (*OnCapsInvalidated)();
// <= WARN is lossy, >= ERROR is lossless and rate limited.
void (*OnLog)(Uint8 level, const char* text);
// The XFB scatter is a read-modify-write of the CLIENT's shadow, so the server
// hands back the packed scratch and the client scatters (section 7.2.1).
void (*OnXfbScatterReady)(MGPipeHandle scratch, Uint64 packedStride, Uint64 vertices);
};
// Nine, and the count is asserted so a tenth cannot be added without touching the
// Ten, and the count is asserted so an eleventh cannot be added without touching the
// transport's reverse-channel record table.
inline constexpr SizeT kMGPipeCallbackCount = 9;
inline constexpr SizeT kMGPipeCallbackCount = 10;
static_assert(sizeof(MGPipeCallbacks) == kMGPipeCallbackCount * sizeof(void (*)()),
"MGPipeCallbacks gained or lost a callback");
// Null-initialized: a backend that installs nothing sends nothing.
inline MGPipeCallbacks gMGPipeCallbacks{};
#if MOBILEGL_BUILD_DISAGGREGATED
// HOW MUCH OF ITSELF ONE REVERSE-CHANNEL RECORD MAY BE, and it is not a tuning knob: a
// producer that ignores it kills the server process.
//
// OnBufferWriteback's bytes travel INLINE in one SEG_EVENT record, and a ring producer
// refuses any record above Capacity()/2 OUTRIGHT (Transport/Ring.h) - not "when full", but
// always, because above half a capacity a record is placeable at some head offsets and not
// at others, so waiting for room would be a hang. The server's answer to a refusal is
// Fatal{EventRingOverflow}, and SEG_EVENT defaults to 256 KiB, so ANY producer that posts a
// whole range wider than ~128 KiB is a server that dies on a large enough buffer.
//
// THE PRODUCERS ARE IN MG_Backend, which cannot reach MG_Remote::Client's
// BufferWritebackSliceBytes (that one is the CLIENT-linkage answer to the same question,
// for requests going the other way) and must not reach ServerSession either. So the
// transport publishes the one number through this hook, exactly as it publishes segment
// resolution through gMGPipeSegmentResolver: the SERVER role installs it at Accept and
// releases it at Close, and a monolith build leaves it null.
using MGPipeEventRingCapacityQuery = Uint64 (*)();
inline MGPipeEventRingCapacityQuery gMGPipeEventRingCapacityBytes = nullptr;
// 0 means "do not slice": no transport is installed, so the callback is a direct call with
// no ring under it and cutting the range would only multiply the calls.
//
// A QUARTER of the ring rather than the MaxRecordBytes half, which is the same number and
// the same reasoning the client side uses (MG_Remote/Client/GpuWritePending.cpp): the record
// carries its own header and an EventBufferWritebackHead beside the payload, and the ring may
// still hold small events posted earlier in the same verb's apply. The 4 KiB floor is there so
// that a pathologically small operator-supplied ring cannot make a slicing loop spin at zero
// width; such a ring is broken anyway and the producer's Fatal{EventRingOverflow} names it on
// the first post.
inline Uint64 MGPipeBufferWritebackSliceBytes() {
if (gMGPipeEventRingCapacityBytes == nullptr) return 0;
const Uint64 capacity = gMGPipeEventRingCapacityBytes();
if (capacity == 0) return 0;
const Uint64 quarter = capacity / 4;
return quarter < 4096 ? 4096 : quarter;
}
#endif
} // namespace MobileGL::MG_Pipe
+14 -85
View File
@@ -342,19 +342,16 @@ namespace MobileGL::MG_Pipe {
// It exists because the applier ALREADY takes that scope - as a trailing
// const MGPRespecifiedLevel* (PipeApply.h:792-795) - and MGPResourceDesc could not
// express it, so it was the second of resource_respecify's two companions with no wire
// carrier. PH-4 extends that carrier with exact W/H/D for the named level, which the
// server validates before staging bytes. The difference is not cosmetic: a null scope drops EVERY pending upload,
// carrier. The difference is not cosmetic: a null scope drops EVERY pending upload,
// because every level's coordinate system has just been replaced, while a per-level
// one drops only that key. Crossing without the scope would make every mutable
// per-level glTexImage*D on the far side look like a whole-resource redefinition and
// silently eat the texels of every other level - exactly the loss the server-side
// pending-upload set exists to prevent.
//
// READ IT THROUGH THE HELPERS BELOW, never by touching the fields: the presence byte,
// target/level pair and exact per-level extent form one value. For a named image level,
// BufOffset/BufSize temporarily carry W/H/D; the target makes this safe because a
// texture-buffer range cannot legally name a mip level. The applier clears that carrier
// before storing the descriptor.
// READ IT THROUGH THE THREE HELPERS BELOW, never by touching the fields: the
// presence byte and the pair are one value in three pieces, and an open-coded reader
// that forgets the presence byte reads level 0 of upload target 0 as a real scope.
//
// NOT STORAGE-DEFINING, and not metadata either: it does not describe the resource at
// all, it describes what this CALL replaces. MGPipeResourceRespecifyNeedsAck and the
@@ -381,9 +378,7 @@ namespace MobileGL::MG_Pipe {
Uint16 RespecifiedLevel;
MGPipeHandle ViewOf; // storage owner for a texture view
MGPipeHandle BufferForTexBuffer; // texture-buffer backing store
// TexBuffer's backing range; on a named non-buffer mip respecify the same words carry
// exact width/height/depth until the applier accepts and normalizes the descriptor.
Uint64 BufOffset, BufSize;
Uint64 BufOffset, BufSize; // kWholeBuffer == ~0, resolved live
};
MGP_ASSERT_POD(MGPResourceDesc, 88);
// The scope fields went into the two existing pads, so the descriptor did not grow and this
@@ -406,9 +401,9 @@ namespace MobileGL::MG_Pipe {
return desc.HasRespecifiedLevel == 0;
}
// The single (uploadTarget, level, width, height, depth) a per-level respecify replaces.
// Reading any component of a whole-resource descriptor is a caller error; helpers answer
// zero so a misuse is deterministic rather than whatever the pad/range held.
// The single (uploadTarget, level) a per-level respecify replaces. Reading either half of a
// whole-resource descriptor is a caller error; both answer 0 so that a misuse is at least
// deterministic rather than whatever the pad happened to hold.
inline constexpr Uint16 MGPipeRespecifiedUploadTargetOf(const MGPResourceDesc& desc) {
return MGPipeRespecifyIsWholeResource(desc) ? Uint16(0) : desc.RespecifiedUploadTarget;
}
@@ -416,54 +411,16 @@ namespace MobileGL::MG_Pipe {
return MGPipeRespecifyIsWholeResource(desc) ? Uint16(0) : desc.RespecifiedLevel;
}
// A producer sets the scope and its exact mutable-level extent with one call so the
// presence byte cannot be left behind, and clears scope with the other. A descriptor built
// by value-initialization is already whole-resource, which is the safe default.
inline constexpr Uint32 MGPipeRespecifiedWidthOf(const MGPResourceDesc& desc) {
return MGPipeRespecifyIsWholeResource(desc) ? 0u : static_cast<Uint32>(desc.BufOffset >> 32);
}
inline constexpr Uint32 MGPipeRespecifiedHeightOf(const MGPResourceDesc& desc) {
return MGPipeRespecifyIsWholeResource(desc) ? 0u : static_cast<Uint32>(desc.BufOffset);
}
inline constexpr Uint32 MGPipeRespecifiedDepthOf(const MGPResourceDesc& desc) {
return MGPipeRespecifyIsWholeResource(desc) ? 0u : static_cast<Uint32>(desc.BufSize);
}
// A ZERO COMPONENT IS CANONICAL. glTexImage1D(width 0), glTexImage2D(0 x 0) and friends are
// legal GL that define an EMPTY level - dEQP's resetStateGLCore issues exactly that for every
// texture target after every case - and the frontend reports the level's exact extent as
// e.g. {0, 1, 1}. Requiring nonzero components made that legal call a session Fatal on every
// split arm. The carrier's only noncanonical shape is a depth word past 32 bits; whether an
// extent is USABLE is the staged store's question (an empty level has no byte bound, so any
// resource_subdata against it is refused there).
inline constexpr Bool MGPipeRespecifiedExtentCarrierIsCanonical(const MGPResourceDesc& desc) {
return MGPipeRespecifyIsWholeResource(desc) || (desc.BufSize >> 32) == 0;
}
// The two writers. A producer sets the scope with one call so the presence byte cannot be
// left behind, and clears it with the other; a descriptor built by value-initialization is
// already whole-resource, which is the safe default and the only one P5 produces.
inline constexpr void MGPipeSetRespecifiedLevel(MGPResourceDesc& desc, Uint16 uploadTarget,
Uint16 level, Uint32 width = 0, Uint32 height = 0,
Uint32 depth = 0) {
Uint16 level) {
desc.HasRespecifiedLevel = 1;
desc.RespecifiedUploadTarget = uploadTarget;
desc.RespecifiedLevel = level;
#if MOBILEGL_BUILD_DISAGGREGATED
// Non-buffer texture targets leave this descriptor range unused. A named-level
// respecify repurposes it as exact W/H/D; TexBuffer cannot legally name a mip level.
desc.BufOffset = (static_cast<Uint64>(width) << 32) | static_cast<Uint64>(height);
desc.BufSize = depth;
#else
(void)width;
(void)height;
(void)depth;
#endif
}
inline constexpr void MGPipeClearRespecifiedLevel(MGPResourceDesc& desc) {
#if MOBILEGL_BUILD_DISAGGREGATED
if (desc.HasRespecifiedLevel != 0 &&
desc.Target != static_cast<Uint8>(MGPipeResourceTarget::TexBuffer)) {
desc.BufOffset = 0;
desc.BufSize = 0;
}
#endif
desc.HasRespecifiedLevel = 0;
desc.RespecifiedUploadTarget = 0;
desc.RespecifiedLevel = 0;
@@ -1182,31 +1139,6 @@ namespace MobileGL::MG_Pipe {
static_assert(sizeof(MGPPixelPackState) == 28,
"MGPPixelPackState changed size; update the wire format and this assertion");
// ID-49's NEUTRAL PACK, in one place. The server's read_pixels reads the backend with this
// state and scatters the tight reply through the application's own pack on the client side
// (MG_Remote/Server/PipeApplier.cpp), so the pack state never shapes the wire answer.
//
// ONE SPELLING, because there are two readers of the same constant and they are in different
// libraries: the applier that installs it, and (in a verify build) the compare-at-read hook in
// MG_Impl/Pipe/PipeFill.cpp, whose oracle for the pack half inside that window IS this value.
// Two hand-typed copies would drift silently in the ONE direction that matters - the hook
// would stop recognising the window and start reporting a divergence that is not one - so
// MG_Pipe, which owns MGPPixelPackState, owns the constant as well.
//
// Value-initialised and then the five fields the applier sets: RowLength / SkipRows /
// SkipPixels / SkipImages are already 0 by PixelStoreParameters' own defaults and are spelled
// out anyway, because "neutral" is a statement about every member rather than about the ones
// whose default happens to be right.
inline MGPPixelPackState MGPipeNeutralReadPixelsPack() {
MGPPixelPackState neutral{};
neutral.Pack.RowLength = 0;
neutral.Pack.SkipRows = 0;
neutral.Pack.SkipPixels = 0;
neutral.Pack.SkipImages = 0;
neutral.Pack.Alignment = 1;
return neutral;
}
// Also a shader-variant input: both backends bake these into the synthesized
// pass-through control stage.
struct MGPPatchState {
@@ -1740,11 +1672,8 @@ namespace MobileGL::MG_Pipe {
};
MGP_ASSERT_POD(MGPStreamOutputBegin, 120);
// end_stream_output carries the accounting the client owns. THE SCATTER ITSELF IS THE
// SERVER'S, and this sentence used to say the opposite: plan B section 7.2.1 put the
// read-modify-write on the client's shadow, P5c/P5f put it on the server's own staged
// shadow, and the reconciled range comes back as an ordinary OnBufferWriteback. Nothing
// about the scatter crosses in this record.
// end_stream_output carries the accounting the client owns; the scatter itself is a
// read-modify-write of the client's shadow and lives there (section 7.2.1).
struct MGPXfbAccounting {
Uint64 CapturedVertices;
Uint64 PrimitivesWritten;
+33 -179
View File
@@ -33,9 +33,6 @@
#endif
#if MOBILEGL_BUILD_DISAGGREGATED
// P7 wave 0: the seam the Magma wire funnels in MG_Backend die through. Declared in MG_Pipe and
// DEFINED below, so MG_Backend names no MG_Remote symbol of its own to reach Session::Fail.
#include <MG_Pipe/PipeSessionFail.h>
// R-6's tier gate. One spelling, asked at the one place the decline is decided. Outside the
// MOBILEGL_PIPE_VERIFY block above on purpose: the tier is a property of the BUILD, not of the
// comparator, and a split build without the comparator still declines every acquisition.
@@ -54,8 +51,6 @@
#include <algorithm>
#include <cmath>
#include <cstdarg>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <utility>
@@ -113,49 +108,6 @@
X(ProgramPointSize)
namespace MobileGL::MG_Pipe {
#if MOBILEGL_BUILD_DISAGGREGATED
// ----------------------------------------------------------------------------
// THE BACKEND-SIDE SESSION-FAIL SEAM (P7 wave 0). PipeSessionFail.h holds the argument;
// this is the whole implementation.
//
// It lives in this file for the reason MGP_TRIP_WIRE_REPORT does, forty lines up: this is
// where MG_Pipe already states "the verdict of every trip wire, in one place", and a seam
// whose default is an abort belongs next to the other one rather than in a file of its own
// that a reader has to be told about. Split-only, so a pull build gains nothing (G1) and a
// push-monolith build - where the three Magma wire funnels are not compiled either - gains
// nothing to call.
namespace {
MGPipeSessionFailHook g_sessionFailHook = nullptr;
} // namespace
void MGPipeInstallSessionFailHook(MGPipeSessionFailHook hook) { g_sessionFailHook = hook; }
MGPipeSessionFailHook MGPipeSessionFailHookInstalled() { return g_sessionFailHook; }
void MGPipeSessionFail(MGPipeFatalFamily family, const char* fmt, ...) {
// The same 512-byte buffer and the same fallback SessionFail and WireLogFatal use, so a
// death that travels this seam reads identically to one that did not.
char line[512];
va_list args;
va_start(args, fmt);
const int written = std::vsnprintf(line, sizeof(line), fmt, args);
va_end(args);
if (written < 0) {
std::snprintf(line, sizeof(line),
"MGPipe: unformattable Fatal diagnostic (format=%s)", fmt);
}
if (g_sessionFailHook != nullptr) g_sessionFailHook(family, line);
// NO HOOK: exactly what the three funnels did before this seam existed - the line, then
// the abort. Reached in a server image whose role init has not run (a unit case that
// drives the applier headless) and in the client process, where there is no session to
// fail. The abort carries no `Fatal{` of its own because `line` already does;
// fatal_census.py's FUNNEL_SITES names this function for that reason.
MGLOG_F("%s", line);
std::abort();
}
#endif
namespace {
// ----------------------------------------------------------------------------
// WHICH CHUNKS EACH DERIVATION READS.
@@ -947,74 +899,27 @@ namespace MobileGL::MG_Pipe {
#endif
#if MOBILEGL_PIPE_VERIFY
// P5's pin, RELAXED BY P7 WAVE 3 (CONTRACT-P7 §6) - and relaxed rather than deleted,
// because the thing it was guarding is now reachable instead of hypothetical.
// P5's pin, the same shape and for the same reason. The respecify SCOPE now has a wire
// carrier (MGPResourceDesc's HasRespecifiedLevel + the pair) and no producer: every
// descriptor P5 builds is whole-resource, and the per-level scope still arrives the old
// way, as the trailing MGPRespecifiedLevel* this function does not look at.
//
// WHAT IT USED TO SAY. "The respecify SCOPE has a wire carrier (MGPResourceDesc's
// HasRespecifiedLevel + the pair) and NO PRODUCER: every descriptor P5 builds is
// whole-resource, and the per-level scope still arrives the old way, as the trailing
// MGPRespecifiedLevel* this function does not look at." So any descriptor arriving with
// the carrier set was, by definition, a producer nobody had announced, and a verify
// build refused it.
//
// WHY THAT IS NOW WRONG, AND EXACTLY HOW FAR. The producer landed:
// Wire_Escape_ResourceRespecify (Client/WireTables.cpp:425-433) writes the carrier from
// the pointer through MGPipeSetRespecifiedLevel, and the server codec
// (Wire/PipeWireCodec.cpp:1677-1683) rebuilds the pointer from the carrier. So under a
// split transport EVERY per-level glTexImage*D arrives here with the carrier set, and
// the old pin made verify x split unmeasurable - it fired on the server's apply thread
// during bring-up, before a single verify case could arm:
//
// Fatal{PipeRespecifyScope} resource_respecify {slot=12, gen=0}: the descriptor
// carries a per-level respecify scope (target=258, level=0), and no path in this
// phase may set one
//
// WHAT SURVIVES, AND IT IS THE WHOLE INVARIANT. The pin never cared that the carrier
// was set; it cared that THE TWO HALVES OF THE SCOPE COULD DISAGREE - "the first thing
// that can go wrong is exactly one of the two moving". That hazard did not go away when
// the producer landed, it became LIVE, and it is silent: the applier below drops pending
// uploads by the POINTER, so a descriptor that declares (target, level) while this call
// hands over a null pointer takes the WHOLE-RESOURCE arm and eats every other level's
// texels, and one that hands over a different pair erases the wrong key and keeps the
// one the client stopped owing. Neither shows up as anything but missing pixels, a
// frame later, on whichever level the wire dropped.
//
// So the rule becomes CONTRACT-P7 §6's: A PRODUCER OF A PER-LEVEL SCOPE MUST COVER THE
// RANGE IT DECLARES. Carrier set => the call passes a pointer, and that pointer names
// exactly the declared (uploadTarget, level).
//
// ONE-DIRECTIONAL ON PURPOSE. A whole-resource descriptor says NOTHING about the
// pointer, and must not: that is the monolith shape and it is still the majority of the
// calls in the tree. MG_Impl/Pipe/TextureEmit.h builds a value-initialized descriptor
// (carrier clear, by MGPipeClearRespecifiedLevel's own "the safe default") and states
// the scope in the trailing pointer alone, which is legal, load-bearing and untouched
// here. Checking that direction too would red every monolith glTexImage*D in the tree
// and would be asserting a convention, not an invariant - the pointer is the caller's
// statement, and a caller that has not been converted to the carrier has not lied.
void PinRespecifyScopeCoversItsDeclaration(const MGPResourceDesc& desc,
const MGPRespecifiedLevel* level, MGPipeHandle res,
const char* call) {
// The two must not disagree, and when a later package wires the carrier it will set the
// fields at a call site that also still passes the pointer - so the first thing that can
// go wrong is exactly one of the two moving. A verify build refuses to let that arrive
// unannounced, because a descriptor that says "whole resource" while the pointer says
// "level 1" drops every other level's pending upload with nothing saying so.
void PinWholeResourceRespecifyScope(const MGPResourceDesc& desc, MGPipeHandle res, const char* call) {
if (MGPipeRespecifyIsWholeResource(desc)) return;
const Uint16 declaredTarget = MGPipeRespecifiedUploadTargetOf(desc);
const Uint16 declaredLevel = MGPipeRespecifiedLevelOf(desc);
if (level != nullptr && level->UploadTarget == declaredTarget &&
level->Level == declaredLevel) {
return;
}
MGP_TRIP_WIRE_REPORT("MGPipe: " MGP_TRIP_WIRE_TAG("PipeRespecifyScope")
" %s {slot=%u, gen=%u}: the descriptor declares a per-level respecify "
"scope (target=%u, level=%u) and this call covers %s(target=%u, "
"level=%u), so a per-level producer is not covering the range it "
"declares",
call, res.Slot, res.Gen, static_cast<unsigned>(declaredTarget),
static_cast<unsigned>(declaredLevel),
level == nullptr ? "NOTHING " : "",
level == nullptr ? 0u : static_cast<unsigned>(level->UploadTarget),
level == nullptr ? 0u : static_cast<unsigned>(level->Level));
" %s {slot=%u, gen=%u}: the descriptor carries a per-level respecify "
"scope (target=%u, level=%u), and no path in this phase may set one",
call, res.Slot, res.Gen,
static_cast<unsigned>(MGPipeRespecifiedUploadTargetOf(desc)),
static_cast<unsigned>(MGPipeRespecifiedLevelOf(desc)));
}
#else
void PinRespecifyScopeCoversItsDeclaration(const MGPResourceDesc&, const MGPRespecifiedLevel*,
MGPipeHandle, const char*) {}
void PinWholeResourceRespecifyScope(const MGPResourceDesc&, MGPipeHandle, const char*) {}
#endif
#if MOBILEGL_PIPE_VERIFY
@@ -1138,22 +1043,18 @@ namespace MobileGL::MG_Pipe {
if (MG_Config::Transport == MG_Config::TransportMode::Monolith) return;
auto& store = MG_Remote::Server::ServerStagedTexture();
const Uint64 key = MG_Remote::Server::StagedTextureStore::KeyForHandle(desc.Resource);
const auto define = [&](Uint16 target, Uint16 mip, const IntVec3& extent) {
store.NoteLevelDefined(key, target, mip, extent, desc.Target, desc.InternalFormat);
const auto define = [&](Uint16 target, Uint16 mip) {
store.NoteLevelDefined(key, target, mip, MG_Remote::Server::StagedTextureMipExtent(
desc.Target, desc.Width, desc.Height, desc.Depth, mip));
};
if (level) {
define(MGPipeSubDataUploadTargetOf(level->UploadTarget), level->Level,
IntVec3{static_cast<Int>(level->Width), static_cast<Int>(level->Height),
static_cast<Int>(level->Depth)});
define(MGPipeSubDataUploadTargetOf(level->UploadTarget), level->Level);
return;
}
store.ResetLevels(key);
if (!desc.Immutable || !desc.Levels) return;
const auto defineChain = [&](TextureUploadTarget target) {
for (Uint32 mip = 0; mip < desc.Levels; ++mip)
define(static_cast<Uint16>(target), static_cast<Uint16>(mip),
MG_Remote::Server::StagedTextureMipExtent(desc.Target, desc.Width,
desc.Height, desc.Depth, mip));
for (Uint32 mip = 0; mip < desc.Levels; ++mip) define(static_cast<Uint16>(target), static_cast<Uint16>(mip));
};
switch (static_cast<MGPipeResourceTarget>(desc.Target)) {
case MGPipeResourceTarget::Tex1D: defineChain(TextureUploadTarget::Texture1D); break;
@@ -1671,22 +1572,10 @@ namespace MobileGL::MG_Pipe {
void MGPipeApplyCreateRenderState(const MGPRenderStateDesc& desc, const void* chunkBytes) {
MOBILEGL_ASSERT(desc.Cso.Slot >= kMGPipeFirstAllocatableSlot,
"create_render_state named the reserved slot 0");
MGPipeRenderStateCsoRecord* recordAt =
RecordAt(g_applier.RenderStateCsos, desc.Cso.Slot, kMGPipeMaxRenderStateCsoSlots);
if (recordAt == nullptr) {
#if MOBILEGL_BUILD_DISAGGREGATED
MGPipeSessionFail(MGPipeFatalFamily::ProtocolCorruption,
"MGPipe: Fatal{ProtocolCorruption, \"CreateRenderState.Cso.Slot\"} - "
"create_render_state {slot=%u, gen=%u} is outside the record table bound (%u)",
desc.Cso.Slot, desc.Cso.Gen, kMGPipeMaxRenderStateCsoSlots);
#else
MGP_TRIP_WIRE_REPORT("MGPipe: " MGP_TRIP_WIRE_TAG("ProtocolCorruption")
" create_render_state {slot=%u, gen=%u} is outside the record table bound (%u)",
desc.Cso.Slot, desc.Cso.Gen, kMGPipeMaxRenderStateCsoSlots);
#endif
return;
if (desc.Cso.Slot >= g_applier.RenderStateCsos.size()) {
g_applier.RenderStateCsos.resize(desc.Cso.Slot + 1);
}
MGPipeRenderStateCsoRecord& record = *recordAt;
MGPipeRenderStateCsoRecord& record = g_applier.RenderStateCsos[desc.Cso.Slot];
// NEITHER BRANCH MAY LEAVE ITS BAD CASE TO MOBILEGL_ASSERT. The slot the client is
// naming may be a RECYCLED one whose record still holds the previous occupant's 396
@@ -1979,17 +1868,6 @@ namespace MobileGL::MG_Pipe {
// ================================================================================
Bool MGPipeApplyResourceCreate(const MGPResourceDesc& desc) {
#if MOBILEGL_BUILD_DISAGGREGATED
if (!MGPipeRespecifyIsWholeResource(desc)) {
MGP_TRIP_WIRE_REPORT("MGPipe: Fatal{ProtocolCorruption, \"ResourceCreate.RespecifyScope\"} - "
"resource_create cannot carry a per-level respecify extent");
}
if (desc.Target != static_cast<Uint8>(MGPipeResourceTarget::TexBuffer) &&
(desc.BufOffset != 0 || desc.BufSize != 0)) {
MGP_TRIP_WIRE_REPORT("MGPipe: Fatal{ProtocolCorruption, \"ResourceCreate.BufferRange\"} - "
"only a texture-buffer resource may carry BufOffset/BufSize");
}
#endif
MOBILEGL_ASSERT(desc.Resource.Slot >= kMGPipeFirstAllocatableSlot,
"resource_create named the reserved slot 0");
if (desc.Resource.Slot < kMGPipeFirstAllocatableSlot) return false;
@@ -2069,26 +1947,7 @@ namespace MobileGL::MG_Pipe {
MGPipeResourceRecord* record = ResolveResourceIn(*table, "resource_respecify", desc.Resource);
if (record == nullptr) return false;
PinNoLiveHostWrites(*record, desc.Resource, "resource_respecify");
PinRespecifyScopeCoversItsDeclaration(desc, level, desc.Resource, "resource_respecify");
#if MOBILEGL_BUILD_DISAGGREGATED
if (level != nullptr &&
(desc.Target == kMGPipeResourceTargetBuffer ||
desc.Target == static_cast<Uint8>(MGPipeResourceTarget::Renderbuffer) ||
desc.Target == static_cast<Uint8>(MGPipeResourceTarget::TexBuffer))) {
MGP_TRIP_WIRE_REPORT("MGPipe: Fatal{ProtocolCorruption, \"ResourceRespecify.Target\"} - "
"this resource target cannot name a texture mip level");
}
if (!MGPipeRespecifyIsWholeResource(desc) &&
!MGPipeRespecifiedExtentCarrierIsCanonical(desc)) {
MGP_TRIP_WIRE_REPORT("MGPipe: Fatal{ProtocolCorruption, \"ResourceRespecify.ExtentCarrier\"} - "
"a named image level's depth word must fit in 32 bits (no high BufSize bits)");
}
if (level == nullptr && desc.Target != static_cast<Uint8>(MGPipeResourceTarget::TexBuffer) &&
(desc.BufOffset != 0 || desc.BufSize != 0)) {
MGP_TRIP_WIRE_REPORT("MGPipe: Fatal{ProtocolCorruption, \"ResourceRespecify.BufferRange\"} - "
"a whole non-buffer resource may not carry BufOffset/BufSize");
}
#endif
PinWholeResourceRespecifyScope(desc, desc.Resource, "resource_respecify");
// IS THIS A REDEFINITION AT ALL? Asked BEFORE the descriptor is replaced, because the
// stored one is the only thing there is to compare against (ID-18 M4). See
@@ -2103,14 +1962,6 @@ namespace MobileGL::MG_Pipe {
// asking a frontend object for them. A metadata update replaces it too - that is how
// the mask arrives - and by construction only the non-storage fields differ.
record->Desc = desc;
#if MOBILEGL_BUILD_DISAGGREGATED
if (level != nullptr && desc.Target != static_cast<Uint8>(MGPipeResourceTarget::TexBuffer)) {
// Scope and BufOffset/BufSize are transient respecify carriers, not resource state.
MGPipeClearRespecifiedLevel(record->Desc);
record->Desc.BufOffset = 0;
record->Desc.BufSize = 0;
}
#endif
// THE SERIAL MOVES EITHER WAY, and for a metadata update it is the entire publication:
// 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.
@@ -2149,11 +2000,14 @@ namespace MobileGL::MG_Pipe {
// glTexSubImage2D and the sync that consumes it; eating those texels there would be
// C1's bug with a different trigger, and just as silent.
//
// - A NAMED LEVEL IS DROPPED WHETHER OR NOT THE base descriptor moved (P4a final
// review C-1). The companion scope now carries that level's exact W/H/D as well as
// its (uploadTarget, level) key, so the texture twin and staged-byte store update the
// same coordinate system. A metadata-only mask republish passes null and therefore
// cannot consume a standing upload on its behalf.
// - A NAMED LEVEL IS DROPPED WHETHER OR NOT THE DESCRIPTOR MOVED (P4a final review
// C-1, refining wire's W11 clause). The level pointer is the CALLER's statement that
// it reallocated that level, and the descriptor cannot contradict it: a non-base
// level redefined at a new size moves no descriptor field at all (the descriptor
// carries the base extent and the level count), so "identical storage fields" says
// nothing about that level's coordinate system, and a box kept against the old
// level would be uploaded past the end of the new one. The client's mask republish
// passes null, so this arm can never eat a standing upload on its behalf.
//
// A buffer never has a pending upload at all, so all three arms are inert for P3a's
// half - which is also why a buffer is never classified as metadata-only (below).
-28
View File
@@ -162,9 +162,6 @@ namespace MobileGL::MG_Pipe {
// bounded by kMGPipeMaxResourceSlots and each grows only to its own dense high-water mark.
inline constexpr Uint32 kMGPipeMaxResourceSlots = 1u << 20;
inline constexpr Uint32 kMGPipeMaxVertexElementsSlots = 1u << 16;
// create_render_state records retain one 396-byte pipeline half each. Keep their
// slot-indexed table bounded independently so a peer cannot request a huge resize.
inline constexpr Uint32 kMGPipeMaxRenderStateCsoSlots = 1u << 16;
// P4a's three, and the argument is written out for each because the records differ in
// size. None is ever allocated by being named: the tables grow to the client's own dense
// high-water mark and no further, so the bound costs nothing until a record is corrupt.
@@ -1141,33 +1138,8 @@ namespace MobileGL::MG_Pipe {
struct MGPRespecifiedLevel {
Uint16 UploadTarget = 0;
Uint16 Level = 0;
#if MOBILEGL_BUILD_DISAGGREGATED
// P7 PH-4: mutable mip dimensions do not follow from the base descriptor. These fields
// are carried by the split resource_respecify record; the pull helper remains 4 bytes.
Uint32 Width = 0;
Uint32 Height = 0;
Uint32 Depth = 0;
#endif
};
inline MGPRespecifiedLevel MGPipeMakeRespecifiedLevel(Uint16 uploadTarget, Uint16 level,
Uint32 width = 0, Uint32 height = 0,
Uint32 depth = 0) {
MGPRespecifiedLevel value{};
value.UploadTarget = uploadTarget;
value.Level = level;
#if MOBILEGL_BUILD_DISAGGREGATED
value.Width = width;
value.Height = height;
value.Depth = depth;
#else
(void)width;
(void)height;
(void)depth;
#endif
return value;
}
// THE THREE ACCEPTANCE RETURNS, AND WHY ALL THREE (ID-18 M3, clientfb review M3). D-D5
// step 1 says the client clears a level's dirty flags "for the levels whose record the
// applier ACCEPTED", and the emitter cannot answer that for itself: an `if constexpr` that
+2 -3
View File
@@ -139,9 +139,8 @@ namespace MobileGL::MG_Pipe {
// THE VERTEX-ELEMENTS CSO's DEATH, and it is BACKEND-NEUTRAL - which is the whole point.
// Before this, the only thing that ever returned a VertexElementsCso slot was DirectGLES'
// StateObjectDeathOps table; under a backend that installed none - DirectVulkan/Magma at
// P3a, which keeps its own age-reclaimed identity table on purpose and which P7 wave 2
// package C gave an EMIT-only table that still frees no slot - every VAO ever created
// StateObjectDeathOps table; under any backend that installs none - DirectVulkan/Magma,
// which keeps its own age-reclaimed identity table on purpose - every VAO ever created
// held its slot and its ~1.3 KB applier record for the life of the process, on the shipped
// 0x1ff mask, and past 65536 slots every create_vertex_elements became a permanent
// Fatal{ProtocolCorruption}. The client mints the slot, so the client is where the death
+3 -79
View File
@@ -88,8 +88,6 @@
#include "MGPipe.h"
#include "PipeApply.h"
// P12: MGPipeHandleIsPublished, the latch the respecify predicate below reads.
#include "PipeMutation.h"
namespace MobileGL::MG_Pipe {
@@ -273,38 +271,6 @@ namespace MobileGL::MG_Pipe {
MGP_ResourceCreate(&desc, &reply);
return MGPipeTakeReplyBool(reply, "resource_create");
}
// P12: WHICH RESPECIFIES STILL WAIT - one predicate, read by the wire emitter, so the two
// halves of this row cannot disagree about whether an answer is owed.
//
// THE BUFFER HALF NEVER DOES. Both call sites discard its Bool outright
// (PipeFill.cpp:1105 and :1142: `MGPipeRouteResourceRespecify(desc, nullptr);`), so the wait
// bought a value that was thrown away - on the device run this row was the second largest
// source of round trips in one frame, at ~5 ms each.
//
// THE TEXTURE HALF WAITS EXACTLY UNTIL THE OBJECT IS CONFIRMED, and "confirmed" is
// MGPipeHandleIsPublished: the latch is set only when the object's create was ACCEPTED, and
// the applier keeps texture records across a make-current (PipeFill.cpp:3756-3759), so for a
// published object the acceptance this row asks for is a fact the client already holds. The
// confirmation itself is paid once, at first use: EmitResourceRespecify sends a create when
// the latch is clear (TextureEmit.h:869-879), and that create is blocking.
//
// AND WHEN THE LATCH IS CLEAR THIS RETURNS TRUE, which is the whole fallback. It also covers
// the one place the two ends' consumer gates are worded differently - the client asks
// "any bit of the family" (PipeFill.cpp:1577-1595) while the applier asks "bit 10"
// (PipeApply.cpp:1408-1419) - because a create refused by the narrower server gate leaves the
// latch clear, so every later row for that object keeps taking the real answer. The cost of
// that case is throughput, never silence.
inline Bool MGPipeResourceRespecifyWantsItsReply(const MGPResourceDesc& desc) {
#if MOBILEGL_BUILD_DISAGGREGATED
if (MGPipeInstalledArm() != MGPipeRouteArm::kClientWire) return true;
if (static_cast<MGPipeResourceTarget>(desc.Target) == MGPipeResourceTarget::Buffer)
return false;
return !MGPipeHandleIsPublished(MGPipeKind::Texture, desc.Resource);
#else
(void)desc;
return true;
#endif
}
inline Bool MGPipeRouteResourceRespecify(const MGPResourceDesc& desc, const void* initialBytes,
const MGPRespecifiedLevel* level = nullptr) {
return gMGPipeRouteEscapes.ResourceRespecify(&desc, initialBytes, level);
@@ -332,56 +298,14 @@ namespace MobileGL::MG_Pipe {
// THE BUFFER HALF DOES NOT: its Bool is discarded at the only call site there is
// (MGPipeEmitResourceSubData), and because the row carries kReplySlot the client used to
// wait for it anyway - one full round trip per 64 KB persistent-map block, whose answer
// nobody looked at.
//
// THE TEXTURE HALF DOES NOT EITHER, ON THE WIRE ARM (P12, the handoff's item B), and the
// argument is that its answer is DERIVABLE there - not that anybody stopped reading it.
// DrainTextureSubData still clears the level's dirty flag on an accepted answer (D-D5), and
// it still gets one; what it does not get any more is a ROUND TRIP for it:
//
// * THE EMISSION IS ALREADY GATED ON THE ANSWER'S CONTENT. A texture record is produced
// only where FamilyIsLive(kMGPipeSubsystemTextureResources, ...) holds, and under split
// that gate IS CapsMirrorInstance().ServerConsumes(bit 10) (PipeFill.cpp:1719-1740) - the
// same published fact the applier's own acceptance belt reads (PipeApply.cpp:1408-1419,
// NoP4aConsumer). So the one server-side refusal this acceptance exists to carry - "no
// consumer", the ID-39 / D-D5 / ID-18 M3 case that is WHY the texture half ever asked -
// cannot be the answer to a record this client emitted.
// * WHAT REMAINS IS A BUG CLASS, AND IT IS LOUD ALREADY. A record whose resource target
// names no texture, or that declares no texels or no bytes, is an MGP_TRIP_WIRE_REPORT on
// the server (PipeApply.cpp:1201-1218, :2245-2252); a record for a handle the applier
// does not hold is counted and named (ResolveResourceIn, :721-728), and the client's own
// tracker prevents it by creating before it ever sends sub-data (PipeFill.cpp:1045-1051).
// * AND EVERY ANSWER THE CLIENT CAN STILL GET FOR FREE, IT STILL GETS: the emitter reads
// this route's Bool exactly as before, so a record the CLIENT cancelled (the device-lost
// latch, an exhausted stage) still answers "not accepted" and the level stays dirty and
// is retried - D-D5's safe direction, unchanged.
//
// THE WAIT DOES NOT DISAPPEAR, IT MOVES TO THE STAGE. A record whose run does not fit
// SEG_STAGE reclaims retired bytes and parks on the stage doorbell (PipeWireCodec.cpp
// StageAllocate / ReclaimStagedBytes) - the one wait a run-ahead client owes, and the one
// that is proportional to the WINDOW rather than to the call count. That is the whole of item
// B: on Minecraft 26.2's atlas frame, 55,428 reply waits at ~4.4 ms each (96 MiB of uploads
// through a 32 MiB window) become the handful of stage retirements those same 96 MiB need.
// (Measured on the host by RemoteClientControls.TextureUploadsStopOwningAReplyOnTheWireArm,
// which counts the reply slots the client opens for a batch of uploads: N -> 0.)
//
// MONOLITH IS UNTOUCHED, and the arm test is what says so: there the applier's answer is
// returned by Mono_ResourceSubData on the calling thread and costs nothing, so there is
// nothing to stop waiting for and the predicate keeps its old answer.
// nobody looked at. THE TEXTURE HALF DOES: DrainTextureSubData clears the level's dirty
// flag on an ACCEPTED reply, so its answer is load-bearing (D-D5; making that half
// fire-and-forget is a trailing item, not this package's).
//
// The test is MGPSubData::Target == kMGPipeResourceTargetBuffer, whole field, which is the
// invariant MGPipeTypes.h asserts beside the packer and which the applier's own
// SubDataNamesABuffer already reads.
inline Bool MGPipeSubDataWantsItsReply(const MGPSubData& record) {
#if MOBILEGL_BUILD_DISAGGREGATED
// THE WIRE ARM ONLY. Everything above is an argument about a client talking to a server
// over SEG_CMD/SEG_STAGE; a monolith run inside a split build (every unit and
// integration-gpu lane is one) keeps the answer it always gave.
if (MGPipeInstalledArm() == MGPipeRouteArm::kClientWire) return false;
#endif
// THE PULL BUILD PREPROCESSES TO EXACTLY THIS LINE AND NOTHING ELSE, which is what G1
// compares: the arm test above sits inside the build switch, so the pull arm emits the
// expression this function has always had.
return record.Target != kMGPipeResourceTargetBuffer;
}
-85
View File
@@ -1,85 +0,0 @@
// MobileGL - MobileGL/MG_Pipe/PipeSessionFail.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
// P7 wave 0 (plan section 1.3's P7-marked refusal row, item (0); Ph slice (2)). HOW A BACKEND DEATH REACHES
// Session::Fail WITHOUT THE BACKEND KNOWING MG_Remote EXISTS.
//
// The three Magma wire funnels - MagmaWireFatal (Renderer/WireFramebuffer.inc),
// WireDescriptorFatal (Renderer/UniformManager.cpp) and WireBufferLegacyFatal
// (Renderer/WireDraw.inc) - each logged their line and raised their OWN std::abort(). Fifteen
// P7-marked refusals (the grep key is the at-sign form, not spelled here) and two more sites die through them, and every one of those deaths:
//
// * published NO SessionFault frame, so the peer read a bare EOF and could not name what
// ended the session (CONTRACT-P6 5.2's whole point);
// * bumped NO SessionFaultCount(), so exit gate S8's "zero faults over a good run" could
// neither confirm nor falsify them;
// * carried a HAND-TYPED family word with no path to FatalFamilies.def's projection, so
// nothing checked that `UnmigratedVerb` in the string still meant UnmigratedVerb.
//
// Calling SessionFail() from the .inc files directly would be the obvious fix and is the wrong
// one: MG_Backend's renderer would then name an MG_Remote symbol on its own account rather than
// through the two staging headers it already borrows under `#if MOBILEGL_BUILD_DISAGGREGATED`,
// and the layering that P13's module boundaries have to establish would be one more edge worse.
//
// So the shape is MGP_TRIP_WIRE_REPORT's (PipeApply.cpp:66): MG_Pipe owns the entry point, the
// DEFAULT behaviour is exactly what the site did before (same log line, same abort), and the
// richer behaviour is a function pointer that a layer above installs. MG_Remote installs
// InstallPipeSessionFailHook() at server-role init (MG_Backend/Init.cpp's InitServerRoleCommon,
// which both the inproc server role and the spawn child run), and from then on these deaths go
// through SessionFail like every other one.
//
// THE MESSAGE STRING IS PASSED VERBATIM, family word and all - the same rule FatalFunnel.h
// states. The lines these three funnels write are already counted by name in the retrace refusal
// census and in every recorded P7-refusal measurement, so they are byte-identical before and after.
#pragma once
namespace MobileGL::MG_Pipe {
// THE FAMILIES THAT CROSS THIS BOUNDARY, AND ONLY THOSE. Not `MGFatalFamily` cast to an
// integer: the .def's enumerators are positional, and a row inserted in the middle of it
// would silently re-point every hook call at a different family. Two words is what the three
// funnels use today, and a third one costs a row here and an arm in the adapter - which is
// the point, because that arm is where the choice gets argued.
enum class MGPipeFatalFamily : unsigned {
// The Magma wire arms' refusal to honour a verb/shape the split path does not implement.
// Deliberately the SAME word the sites already print: `Magma:` in the detail is what
// separates them from the GLES `UnmigratedVerb` deaths, and renaming the family would
// invalidate every census number recorded against it since P5b.
UnmigratedVerb,
// A call that reached an arm this build did not compile, or ran on the wrong role.
RoleViolation,
#if MOBILEGL_BUILD_DISAGGREGATED
// A malformed peer record rejected by the server-side applier.
ProtocolCorruption,
#endif
};
// What the layer above installs. `line` is the FULLY FORMATTED message, so the hook forwards
// it rather than re-formatting it - a second vsnprintf is a second chance to disagree about
// what the death said. A hook is expected not to return; MGPipeSessionFail aborts anyway if
// one does, because a death that keeps running is the one outcome nothing downstream handles.
using MGPipeSessionFailHook = void (*)(MGPipeFatalFamily family, const char* line);
// Idempotent and last-writer-wins. Installed once per process at server-role init; a unit
// case installs its own and restores nullptr afterwards.
void MGPipeInstallSessionFailHook(MGPipeSessionFailHook hook);
// The installed hook, or nullptr. A test reads it to prove installation happened without
// having to die to find out.
MGPipeSessionFailHook MGPipeSessionFailHookInstalled();
// Formats `fmt`, hands the line to the hook if one is installed, and otherwise does exactly
// what the three funnels used to do on their own: MGLOG_F the line and std::abort().
[[noreturn]]
#if defined(__GNUC__) || defined(__clang__)
__attribute__((format(printf, 2, 3)))
#endif
void MGPipeSessionFail(MGPipeFatalFamily family, const char* fmt, ...);
} // namespace MobileGL::MG_Pipe
-3
View File
@@ -33,9 +33,6 @@ namespace MobileGL::MG_Pipe {
}
inline constexpr Uint64 kMGPipeWireMemberLayoutDigest = WireMemberLayoutDigest(
kMGPipeWireLayoutMembers, sizeof(kMGPipeWireLayoutMembers) / sizeof(WireLayoutMember));
// Bump when a fixed-layout pipe carrier keeps its bytes but changes their meaning. The
// mutable-level extent carrier reuses BufOffset/BufSize only on named image respecifies.
inline constexpr Uint32 kMGPipeResourceRespecifyExtentCarrierRevision = 1;
constexpr Uint64 WireCatalogueDigest() {
Uint64 hash = 1469598103934665603ull;
Loaded 100 of 876 files, more files were not shown because too many files have changed in this diff. Show more