mirror of
https://github.com/MobileGL-Dev/MobileGL
synced 2026-11-16 22:43:24 +09:00
[Docs] (docs/Disaggregated, MG_Remote, MG_Remote/Client, MG_Remote/Protocol, MG_Remote/Server, MG_Remote/Transport, MG_Remote/Wire): shorten long comments and move their design arguments into docs
This commit is contained in:
@@ -6,22 +6,14 @@
|
||||
// SPDX-License-Identifier: LGPL-3.0-only
|
||||
// End of Source File Header
|
||||
|
||||
// P11 B2 (docs/archive/contracts/CONTRACT-P11.md B2): the server's end of T0's descriptor channel.
|
||||
//
|
||||
// WHO READS THE FD, AND WHY IT CANNOT DEADLOCK THE APPLY THREAD. The APPLY THREAD reads it,
|
||||
// inline, when it decodes the map_persistent record whose seq the Offer names - nothing else reads
|
||||
// a session's aux socket after the handshake, so there is no second reader to race. The wait
|
||||
// cannot deadlock because of the client's order: it queues the Offer (ShareFd returns once the
|
||||
// kernel - or the in-process queue - holds it) BEFORE it publishes the record, so when the apply
|
||||
// thread sees the record the descriptor is already there, and the wait depends on nothing the
|
||||
// client has still to do. A client emits at most one T0 map_persistent at a time (the row blocks
|
||||
// on its reply), so at most one Offer is ever outstanding and the aux queue (10 datagrams on an
|
||||
// Android kernel) cannot fill. The wait is still bounded (AdoptT0::kOfferWaitMs): an Offer that
|
||||
// never comes is a named DECLINED, never a hang.
|
||||
//
|
||||
// Offers are matched by seq, not by arrival order. One that arrives for a LATER record is kept
|
||||
// for it; one for an EARLIER record (its record already timed out and was declined) is closed
|
||||
// and counted as stale.
|
||||
// The server's end of the aux-socket descriptor channel: T0 map_persistent Offers and shared-image
|
||||
// descriptors, matched by record seq and told apart by their sideband's magic. Only the apply
|
||||
// thread reads it, inline, when it decodes the record the descriptor belongs to. It cannot
|
||||
// deadlock: the client queues the descriptor before it publishes the record, and a T0
|
||||
// map_persistent blocks on its reply, so at most one Offer is outstanding (an Android aux queue
|
||||
// holds 10). The wait is still bounded (AdoptT0::kOfferWaitMs); a missing Offer is a named
|
||||
// DECLINED. A descriptor for a later record is kept for it; one for an earlier, already declined
|
||||
// record is closed and counted as stale.
|
||||
|
||||
#pragma once
|
||||
|
||||
|
||||
@@ -6,36 +6,14 @@
|
||||
// SPDX-License-Identifier: LGPL-3.0-only
|
||||
// End of Source File Header
|
||||
|
||||
// P11 B1 (CONTRACT-P11 B1): WHERE THE APPLY THREAD RUNS AND HOW LONG IT SPINS, CHOSEN PER SESSION
|
||||
// FROM WHO THE CLIENT IS AND WHICH DATA PLANE IT USES.
|
||||
//
|
||||
// `auto` used to mean one thing for every session: the apply thread pinned to every big core
|
||||
// (DetectBigCoreMask, 0xc0 on the workload device) and spinning MOBILEGL_IPC_SPIN_US before each
|
||||
// park. That is right for inproc and the same-app fork spawn (A4's measured shapes), and for a client
|
||||
// on the stream plane, whose records an io thread feeds to the apply thread. It is wrong for a
|
||||
// client that DIALLED IN from another process over SHARED SEGMENTS - an app_process-launched
|
||||
// program (the fd: endpoint), a Termux one, a root or same-app one on `unix:`: the apply thread
|
||||
// spins on the ring that client writes directly, the client's GL thread lands on the same two prime
|
||||
// cores, and on the Redmi rd12 ran 23-26 fps over shared memory against 45-54 over tcp, 118 when the
|
||||
// two were placed apart by hand (B0-CROSS-APP.md, HSPIKE.md). So `auto` now reads the peer's Hello:
|
||||
//
|
||||
// peer, plane `auto` resolves to
|
||||
// in-process (No) every big core, the configured spin - unchanged
|
||||
// forked (Fork) every big core, the configured spin - unchanged
|
||||
// dialled in (Connect), stream every big core, the configured spin - unchanged
|
||||
// dialled in, shared segments ONE core, ReservedApplyCore's: the lowest of several prime cores,
|
||||
// a big core beside a lone prime core, or none - never the only
|
||||
// prime core - and kConnectedPeerSpinUs unless MOBILEGL_IPC_SPIN_US
|
||||
//
|
||||
// The lowest prime core, not the highest, by measurement (CONTRACT-P11 B1): the scheduler puts a
|
||||
// foreground app's hot GL thread on the HIGHEST prime core (cpu7 in 43 of 44 samples); pinning the
|
||||
// apply thread there shared that core with it (rd12 6.5 fps), pinning it to the lowest gave 120. A
|
||||
// client launched through ExternalClientHelper is also kept off the reserved core (the supervisor
|
||||
// announces it, the broker hands it to the helper), so a client the scheduler would otherwise place
|
||||
// on it - an adb-shell one - is not starved either.
|
||||
//
|
||||
// An explicit mask or `off` wins for every peer, exactly as before: the operator's word is the
|
||||
// policy. A pure function, so the unit suite can hold every row without a thread or a cpufreq tree.
|
||||
// Where the apply thread runs and how long it spins before parking, chosen per session from the
|
||||
// peer (the Hello's DialMode) and the data plane. With MOBILEGL_IPC_SERVER_AFFINITY=auto an
|
||||
// in-process, forked or stream-plane peer gets every big core and the configured spin; a peer
|
||||
// that dialled in over shared segments gets at most one core (ReservedApplyCore), never the only
|
||||
// prime core, and kConnectedPeerSpinUs unless MOBILEGL_IPC_SPIN_US is set, because it writes the
|
||||
// ring the apply thread spins on and its GL thread wants a prime core. An explicit mask or `off`
|
||||
// wins for every peer. Pure functions, so the unit suite covers every row; the measurements are
|
||||
// in ARCHITECTURE.md §14.1.
|
||||
|
||||
#pragma once
|
||||
|
||||
|
||||
@@ -6,35 +6,14 @@
|
||||
// SPDX-License-Identifier: LGPL-3.0-only
|
||||
// End of Source File Header
|
||||
|
||||
// P12 (on-screen server window), D3/D5/D6/D7. THE JNI GLUE OF THE IN-PROCESS DISPLAY SERVER.
|
||||
//
|
||||
// The APK's MobileGLDisplayActivity (android:process=":mglwin") owns a SurfaceView and runs
|
||||
// the TCP server on a thread of its own process, so a headless client (MOBILEGL_IPC_SURFACE=server)
|
||||
// renders straight onto that SurfaceView. This file is the whole native half of that Activity:
|
||||
//
|
||||
// nativeInstallDisplay ServerDisplayInstance().Install(): ANativeWindow acquire/release plus the
|
||||
// geometry up-call below. Before the server serves.
|
||||
// nativeServe mobilegl_server_serve_inprocess(listen) on the CALLING (Java) thread;
|
||||
// returns its exit code when the server stops or fails.
|
||||
// nativeStop mobilegl_server_stop_inprocess(): non-blocking, safe on the UI thread.
|
||||
// nativeAttachWindow surfaceCreated / surfaceChanged: ANativeWindow_fromSurface, Attach (which
|
||||
// takes its OWN reference), then this call's reference is released.
|
||||
// nativeDetachWindow surfaceDestroyed: ServerDisplay::Detach, which BLOCKS (bounded) until the
|
||||
// session rendering into the window has released its backend surface on the
|
||||
// apply thread. Returns the result's name for the Activity's log.
|
||||
// nativeUninstallDisplay after the server returned: the display is gone.
|
||||
//
|
||||
// THE GEOMETRY UP-CALL. ServerDisplay calls RequestGeometry on the APPLY THREAD, from AcquireFor,
|
||||
// during a ServerOwned CreateWindowSurface, with the size the client asked for. That thread is a
|
||||
// native thread the JVM does not know, so it is attached for the call and detached after it (a
|
||||
// native thread that exits while still attached aborts the runtime). The Java side only POSTS the
|
||||
// request to the UI thread (SurfaceHolder.setFixedSize / setSizeFromLayout must run there) and
|
||||
// returns: this must not block and must not call back into ServerDisplay. The class and method are
|
||||
// resolved here, on the Java thread that installs the display, because a native thread's FindClass
|
||||
// would search the system class loader, not the app's.
|
||||
//
|
||||
// Compiled only for Android with MOBILEGL_BUILD_DISAGGREGATED (CMakeLists.txt, beside
|
||||
// DriverPostJni.cpp); the guard keeps it inert anywhere else.
|
||||
// The JNI glue of the in-process display server: the native half of MobileGLDisplayActivity
|
||||
// (process ":mglwin"), which owns a SurfaceView and runs the TCP server in its own process so a
|
||||
// headless client (MOBILEGL_IPC_SURFACE=server) renders onto it. nativeInstallDisplay and
|
||||
// nativeUninstallDisplay bracket nativeServe (blocking, on the calling Java thread); nativeStop
|
||||
// does not block; nativeDetachWindow blocks (bounded) until the session releases the window.
|
||||
// RequestGeometry runs on the apply thread, attached to the JVM for the call only, and must not
|
||||
// block or call back into ServerDisplay (Java only posts to the UI thread). Its class and method
|
||||
// are resolved at install: a native thread's FindClass would miss the app's classes.
|
||||
#ifdef __ANDROID__
|
||||
|
||||
#include "InProcessServer.h"
|
||||
|
||||
@@ -6,27 +6,14 @@
|
||||
// SPDX-License-Identifier: LGPL-3.0-only
|
||||
// End of Source File Header
|
||||
|
||||
// P12 (on-screen server window), D5. THE IN-PROCESS DISPLAY SERVER'S ENTRY POINTS.
|
||||
//
|
||||
// The on-screen server cannot be the exec'd supervisor that forks a child per session: the window
|
||||
// it renders into (the display Activity's SurfaceView) is an ANativeWindow in the APP's process, and
|
||||
// neither exec nor fork carries one. So the Activity's own process serves: a thread it starts calls
|
||||
// mobilegl_server_serve_inprocess, which is `libMobileGLServer.so tcp://... --serve` with THREADS
|
||||
// instead of fork - the same pre-auth, the same Busy for an authenticated second Hello while a
|
||||
// session is live, one session at a time, each session a thread of this process, the latch reset
|
||||
// between sessions and the backend pinned for the process lifetime. Crash isolation is what it
|
||||
// gives up: a session's abort (an unarmed SessionFail) takes this process - the Activity - with it.
|
||||
//
|
||||
// PRECONDITIONS, the same as mobilegl_server_main's, set in the environment BEFORE libMobileGL is
|
||||
// loaded (Os.setenv from Java): MOBILEGL_IPC_DIAL=no (else 64), none of MOBILEGL_TRANSPORT /
|
||||
// MOBILEGL_IPC_SERVER_PATH / MOBILEGL_IPC_RING_MB / MOBILEGL_IPC_STAGE_MB (else 65),
|
||||
// MOBILEGL_IPC_ROLE=server (forced if missing, as the supervisor does), MOBILEGL_IPC_TOKEN (required
|
||||
// for a non-loopback listen; >= the minimum length), optionally MOBILEGL_BACKEND_TYPE (the pin),
|
||||
// MOBILEGL_IPC_LOG_FORWARD, MOBILEGL_LOG_FILE_PATH.
|
||||
//
|
||||
// THE DISPLAY is separate: the JNI glue installs ServerDisplayInstance() (ServerDisplay.h) and
|
||||
// attaches/detaches the window from the SurfaceHolder callbacks. A server with no display installed
|
||||
// serves offscreen sessions only and refuses a ServerOwned surface by name.
|
||||
// Entry points of the in-process display server (ARCHITECTURE.md §15.2). Its window lives in the
|
||||
// app's process and survives neither fork nor exec, so a thread of that process serves, with a
|
||||
// thread per session instead of a fork: tcp:// runs the --serve supervisor (pre-auth, one session,
|
||||
// Busy), a unix endpoint up to MOBILEGL_IPC_INPROC_MAX_SESSIONS at once. Latches reset between
|
||||
// sessions, the backend is pinned for the process, and there is no crash isolation.
|
||||
// Set before libMobileGL loads: MOBILEGL_IPC_DIAL=no (else 64); none of MOBILEGL_TRANSPORT,
|
||||
// MOBILEGL_IPC_SERVER_PATH, _RING_MB or _STAGE_MB (else 65); MOBILEGL_IPC_TOKEN for a non-loopback
|
||||
// listen. The JNI glue installs ServerDisplayInstance(); without one, ServerOwned is refused.
|
||||
|
||||
#pragma once
|
||||
|
||||
|
||||
@@ -6,38 +6,13 @@
|
||||
// SPDX-License-Identifier: LGPL-3.0-only
|
||||
// End of Source File Header
|
||||
|
||||
// P11 PAIR. A SOCKET CLIENT'S TWO CONNECTIONS ARE PAIRED BY WHO THEY ARE, NOT BY WHEN THEY ARRIVED.
|
||||
//
|
||||
// SocketTransport::ConnectTo opens two connections to one listener - control, then aux (the
|
||||
// SCM_RIGHTS socket; on tcp:// the data connection). The server used to take "the next two accepted
|
||||
// connections, first is control" (SocketTransport::AcceptPair). That was a protocol only while
|
||||
// nothing else could reach the listener, and on the device it was not (B0-CROSS-APP.md F2): the
|
||||
// server app's readiness probe - one connect() and close() - became the next client's control
|
||||
// connection, that session read the probe's socket and ended ("control peer closed before sending
|
||||
// a first frame"), and the client got no Welcome. Two clients connecting at the same moment could
|
||||
// just as well swap halves.
|
||||
//
|
||||
// Now each connection's first frame is a PairBind (protocol.fbs, control revision 4): the client's
|
||||
// nonce, the same on both, and which half it is. This acceptor keeps every accepted connection in a
|
||||
// small set until it has presented one, and hands out a control and an aux connection only when
|
||||
// their nonces match. What it does with everything else:
|
||||
// - a connection that closes having sent nothing (a readiness probe) is closed, quietly;
|
||||
// - a first frame that is not a PairBind is refused by name. A Hello is a client from before
|
||||
// PairBind: it is asked what the session would ask, in the session's order - the token, then the
|
||||
// wire (Handshake.h) - so it hears Refuse{WireFingerprint} as it would from any session, and one
|
||||
// that passes both is still refused, because it cannot be paired;
|
||||
// - a connection that has not presented a PairBind, or whose partner has not presented the same
|
||||
// nonce, within the budget is dropped - a control connection with a refusal, an aux connection
|
||||
// (whose client reads descriptors there, not frames) by closing it - and nobody else's
|
||||
// connection is touched;
|
||||
// - past kPairMaxUnpaired connections the oldest one that has not identified itself (else the
|
||||
// oldest) is dropped the same way.
|
||||
//
|
||||
// It never reads a byte past a PairBind (FirstFrameAssembler): on control the Hello follows it, and
|
||||
// the session reads that itself; on aux the descriptors follow it.
|
||||
//
|
||||
// Stateful because pairs complete out of order: with A-control, B-control, B-aux, A-aux, B is
|
||||
// handed out first and A-control has to still be here for the call that hands out A.
|
||||
// Pairs a socket client's two connections (control, then aux: the SCM_RIGHTS socket, or the data
|
||||
// connection on tcp://) by nonce rather than arrival order, so a readiness probe or two clients
|
||||
// connecting at once cannot be mispaired. Each connection's first frame is a PairBind with the
|
||||
// client's nonce and its half; nothing past it is read. A connection that closes having sent
|
||||
// nothing is closed quietly; a Hello is checked token then wire, as a session would, then refused;
|
||||
// one unpaired after the budget, or the oldest unidentified one past kPairMaxUnpaired, is dropped
|
||||
// without touching others. Stateful because pairs complete out of order.
|
||||
|
||||
#pragma once
|
||||
|
||||
|
||||
@@ -206,22 +206,14 @@ namespace MobileGL::MG_Remote::Server {
|
||||
m_unreportedFences.clear();
|
||||
}
|
||||
|
||||
// P10 (CONTRACT-P10.md §1): WHICH OF THE CLIENT'S FENCES HAS THE GPU FINISHED.
|
||||
//
|
||||
// The client answers a poll of a fence it knows is signaled without asking - that is the
|
||||
// whole of package A - and it learns what is signaled only from here. Walked in CREATION
|
||||
// order and stopped at the first one still pending: one context's GPU work completes in
|
||||
// the order it was submitted, so a later fence cannot be done while an earlier one is not,
|
||||
// and the steady-state cost is one status query per drain batch. (Were a backend ever to
|
||||
// finish them out of order, the later fence would only be reported late - an answer the
|
||||
// client then gets by its own round trip - never early.)
|
||||
//
|
||||
// `flush`: the apply thread is about to go idle. A fence whose commands the driver still
|
||||
// holds never signals on its own, and an idle server submits nothing more, so the first
|
||||
// pending fence is asked through ClientWaitSync(GL_SYNC_FLUSH_COMMANDS_BIT, 0) - the one
|
||||
// backend-neutral way both backends take to submit what they hold - instead of the plain
|
||||
// status query. Only when idle: mid-stream the next records flush soon enough, and a
|
||||
// submit per batch would cost Magma its command-buffer batching.
|
||||
// Reports which of the client's fences the GPU has finished; the client answers a poll of a
|
||||
// reported fence without a round trip. Walked in creation order and stopped at the first
|
||||
// pending one: one context's work completes in submission order, so this costs one status
|
||||
// query per drain batch, and an out-of-order finish would be reported late, never early.
|
||||
// `flush`: the apply thread is about to go idle, and a fence whose commands the driver still
|
||||
// holds never signals on its own, so the first pending fence is queried with
|
||||
// ClientWaitSync(GL_SYNC_FLUSH_COMMANDS_BIT, 0). Only when idle: a submit per batch would
|
||||
// break Magma's command-buffer batching.
|
||||
Uint32 ServerVerbSink::ReportSignaledFences(Bool flush) {
|
||||
if (m_unreportedFences.empty()) return 0;
|
||||
ServerSession* session = ServerSession::Active();
|
||||
@@ -719,44 +711,14 @@ namespace MobileGL::MG_Remote::Server {
|
||||
// dropped before this function returns, and s1's SessionConsumer::ApplyOne publishes
|
||||
// appliedSeq only after that - so by the time the client is runnable the flag is down.
|
||||
const Client::ClientSession::ScopedApplierEntry insideApplier;
|
||||
// P5e (id), CONTRACT-P5E §2.1 / §4.4: STAMP WHETHER THE CLIENT IS PARKED BEHIND THIS
|
||||
// RECORD, before anything can ask. It is the input to the allocator guard's exemption
|
||||
// (SlotAllocator.cpp) and to every frontend-keyed twin member that survives as monolith
|
||||
// glue (SlotTables.h), and it has to be up before DecodeAndApply because the sinks those
|
||||
// reach are exactly the askers. MGPipeBarriered answers true for every record until ra
|
||||
// lands the wait rule, so this line changes nothing this phase and is the line ra
|
||||
// rebases onto rather than adds.
|
||||
//
|
||||
// AND THE STAMP IS `true` UNTIL ra LANDS THE CLIENT'S HALF (ID-103). The predicate
|
||||
// describes what the client WILL do once EmitAndWaitTails follows the wait classes;
|
||||
// today it still blocks after every record, so a `false` stamp here would withdraw the
|
||||
// §4.4 exemptions from a probe the client's own wait still makes safe - a refusal with
|
||||
// no defect behind it. The predicate is computed on every record all the same, so it is
|
||||
// exercised for the whole phase rather than first run on the day it starts deciding.
|
||||
//
|
||||
// AND THE SERVER'S OWN CAPABILITY IS THE SECOND CONJUNCT (P5e gl, ID-111). The constant
|
||||
// above says what the CLIENT will do once ra's wait rule is live; it says nothing about
|
||||
// which server this is. kCapRunAheadApply is never published on DirectVulkan (ID-90,
|
||||
// MGPipeRunAheadCapBitsFor), yet draw_vbo / blit / clear / launch_grid are all
|
||||
// kWaitNone - so a stamp that read the build constant alone would, on the day it flips,
|
||||
// have a MAGMA server mark every draw record UNBARRIERED while its client is still
|
||||
// lockstep. CountBarrierPull (PipeInputs.cpp) is an unconditional Fatal on an
|
||||
// unbarriered pull, no knob involved, and Magma's residual fill is its ONLY source for
|
||||
// the seven pointer-backed fields: Magma would die on its first draw and take
|
||||
// MagmaP7AllocatorDebtScope's exemption with it.
|
||||
//
|
||||
// BOTH PREDICATES ARE COMPUTED UNCONDITIONALLY, as arguments rather than as the arms of
|
||||
// a short-circuit, which is ID-103's reason extended to the capability probe: they are
|
||||
// exercised on every record for the whole phase rather than first running on the day
|
||||
// they start deciding.
|
||||
//
|
||||
// PH-1 (3): BUT NOT BEFORE THE RECORD HAS BEEN ADMITTED. MGPipeBarriered reads payload
|
||||
// fields (a DrawVbo's MGPDrawInfo::Flags) and the stamps index per-opcode tables, so a
|
||||
// record whose ring header is shorter than its own type - or names no opcode - would be
|
||||
// read past its end here, before DecodeAndApply's pre-gate could refuse it. In an armed
|
||||
// session child the pre-gate therefore runs FIRST: a refused record latches by name and
|
||||
// is declined with nothing stamped (ServerLoopTest's short-record case reads the stamp).
|
||||
// Unarmed it admits everything and the generated gate keeps its death, as before.
|
||||
// Stamp whether the client is parked behind this record before anything can ask: the
|
||||
// barrier-pull check (PipeInputs.cpp) and the deferred-destroy queue (PipeFill.cpp) read
|
||||
// it from inside DecodeAndApply. It is MGPipeBarriered's answer only when this server
|
||||
// publishes run-ahead; otherwise its client waits after every record, so every record is
|
||||
// stamped barriered. Both inputs are computed on every record so they stay exercised.
|
||||
// Admission runs first: MGPipeBarriered reads payload fields and the stamps index
|
||||
// per-opcode tables, so in a session that latches faults a short or unknown record is
|
||||
// declined before anything is stamped.
|
||||
if (!m_decoder.AdmitOrDecline(record)) return false;
|
||||
const Bool wireSaysBarriered = MG_Pipe::MGPipeBarriered(
|
||||
static_cast<MG_Pipe::MGPWireOp>(record.kind), record.payload, MG_Pipe::MGPipeApplier());
|
||||
@@ -779,23 +741,10 @@ namespace MobileGL::MG_Remote::Server {
|
||||
// before it aborts on the FIRST field inside SyncRenderState.
|
||||
StampVerbBoundary(static_cast<MG_Pipe::MGPWireOp>(record.kind));
|
||||
const Bool applied = m_decoder.DecodeAndApply(record);
|
||||
// AND THE CLEAR IS INSIDE ApplyOne, NOT AFTER THE DRAIN BATCH. That is not tidiness,
|
||||
// it is the barrier invariant. s1's SessionConsumer::ApplyOne publishes appliedSeq the
|
||||
// instant this returns, and publishing appliedSeq is what makes the CLIENT runnable
|
||||
// again (R-1: the barrier waits on exactly that watermark). A clear that ran after the
|
||||
// batch would therefore be a second writer of gPipeInputs while the client is already
|
||||
// touching it - the one thing table 3 says may not be introduced before the barrier
|
||||
// retires - and the first version of this file had it there. It was caught by
|
||||
// AClearRecordCrossesAndIsStampedAsAVerbBoundary failing INTERMITTENTLY, which is what
|
||||
// a race looks like from the outside.
|
||||
//
|
||||
// THE COST, STATED: a record that is NOT a verb boundary now applies with the flag
|
||||
// disarmed, so a sticky forward pulled from inside such a record's applier is not
|
||||
// counted in `rsp`. Closing that needs an "enter the applier" entry point beside
|
||||
// MGPipeServerStampVerbBoundary that arms the flag WITHOUT re-stamping - re-stamping on
|
||||
// a non-verb op is what p1 forbids outright - and PipeInputs.cpp is p1's file. Left for
|
||||
// the integrator to sequence; it makes `rsp` larger, never smaller, so the number this
|
||||
// phase reports is a floor.
|
||||
// LeaveApplier runs here, inside ApplyOne, and not after the drain batch:
|
||||
// SessionConsumer::ApplyOne publishes appliedSeq as soon as this returns, which makes the
|
||||
// client runnable, so a later clear would write gPipeInputs while the client uses it.
|
||||
// How a record that is not a verb boundary is read-checked: ARCHITECTURE.md §9.2.1.
|
||||
LeaveApplier();
|
||||
return applied;
|
||||
}
|
||||
|
||||
@@ -6,36 +6,14 @@
|
||||
// SPDX-License-Identifier: LGPL-3.0-only
|
||||
// End of Source File Header
|
||||
|
||||
// The server's applier bridge. Owner: package v1, with p1 for the stamp rule. Signatures by c0.
|
||||
//
|
||||
// IT IS A BRIDGE, NOT AN APPLIER. The applier already exists and is not edited by this phase:
|
||||
// MG_Pipe/PipeApply.{h,cpp}, 37 MGPipeApply* free functions. This class owns the three things
|
||||
// that only exist once records arrive over a wire rather than by direct call:
|
||||
//
|
||||
// 1. THE VERB STAMP. This is the phase's prerequisite, and it is not in the ROADMAP row.
|
||||
// MGPipeApplyAccess deliberately does not stamp the poison generations
|
||||
// (PipeInputs.h:612-618): "a stamp says the filler published this for THIS verb, which is
|
||||
// the walk's statement, not the applier's". Under split the filler is in another role, so
|
||||
// NOTHING stamps, every FilledGen[] stays 0, MGPipeInputFieldIsFresh returns false for
|
||||
// everything, and a pure server aborts on the FIRST read inside SyncRenderState with
|
||||
// Fatal{UnmigratedPipeInput, "GetRenderStateParameters@<none>"} - before reaching any
|
||||
// interesting case. So: the server stamps at the verb boundary. p1 defines what is
|
||||
// stamped and for which verb; v1 places the call. Neither half works alone.
|
||||
//
|
||||
// 2. ACCEPTANCE. Four applier entry points return Bool - ResourceCreate, ResourceRespecify,
|
||||
// ResourceSubData, SetTextureParams - and MapPersistent returns void*. Those returns are
|
||||
// what the CLIENT gates destructive state changes on (clearing per-level dirty flags,
|
||||
// latching parameters, adopting a pointer). They go back through the reply slot, id =
|
||||
// record seq (R-3), and are collected in the barrier's existing wait (R-5). The client
|
||||
// may not recompute any of them.
|
||||
//
|
||||
// 3. R-11, THE BORROWED-POINTER RULE. A SEG_STAGE run is valid from publish until retiredSeq
|
||||
// passes the record naming it. NO APPLIER ENTRY POINT MAY HOLD A POINTER PAST ITS RETURN.
|
||||
// The tree has exactly one violation and it is named: GLESBufferResource::hostBytes
|
||||
// (Managers.h:839), written by Ops_H_SubData (Managers.cpp:1980-1983) and Ops_H_FlushRange
|
||||
// (:2035), read by six later drains (:2000, :2062, :2080, :2111, :2741, :2843). Under split
|
||||
// those two must copy into server-owned storage. MOBILEGL_IPC_AUDIT=1's 0xDD fill (R-2.5)
|
||||
// is the mechanical control that says whether they did.
|
||||
// The server's applier bridge. The appliers are MG_Pipe/PipeApply's MGPipeApply* functions; this
|
||||
// class adds what exists only when records arrive over a wire:
|
||||
// - the verb stamp: the server stamps PipeInputs itself at each verb boundary
|
||||
// (StampVerbBoundary); the client's stamps cannot stand in for it (ARCHITECTURE.md §9.2.1);
|
||||
// - acceptance: the Bool appliers and MapPersistent answer through the record's reply slot, and
|
||||
// the client gates destructive state changes on that answer, never on its own guess;
|
||||
// - borrowed pointers: a SEG_STAGE run is valid until retiredSeq passes its record, so no applier
|
||||
// keeps a pointer past its return; MOBILEGL_IPC_AUDIT=1 poisons retired bytes to prove it.
|
||||
|
||||
#pragma once
|
||||
#include <Includes.h>
|
||||
@@ -63,22 +41,12 @@ namespace MobileGL::MG_Remote::Server {
|
||||
// action under test is the probe itself).
|
||||
Bool MGPipeServerPublishesRunAhead();
|
||||
|
||||
// ---- the barriered stamp, AS A PURE FUNCTION (ID-111) ---------------------------------
|
||||
//
|
||||
// ApplyOne stamps "is the client parked behind this record" before anything can ask
|
||||
// (CONTRACT-P5E §2.1 / §4.4). Until the P5e integration commit the answer is `true` for
|
||||
// every record whatever the wire says, because the client still blocks after each one
|
||||
// (ID-103) - but the day the constant flips, the answer must ALSO ask whether this server
|
||||
// published the run-ahead bit at all. It is `wireSaysBarriered` only when BOTH halves of
|
||||
// the run-ahead arm are true; Magma publishes no bit 10, so a Magma server keeps stamping
|
||||
// `true` and its lockstep client keeps being safe. Without the second conjunct a Magma
|
||||
// server would stamp every draw_vbo / blit / clear / launch_grid UNBARRIERED (they are all
|
||||
// kWaitNone) while its client is still parked, and CountBarrierPull aborts unconditionally
|
||||
// on an unbarriered pull - Magma dies on its first draw, no knob involved.
|
||||
//
|
||||
// IT IS A PURE FUNCTION for MGPipeRunAheadCapBitsFor's reason: "Magma never runs ahead" is
|
||||
// then something a unit case can hold AT THE POST-FLIP VALUE of the constant, rather than a
|
||||
// claim that first becomes testable on the day the integration commit throws the switch.
|
||||
// The barriered stamp, as a pure function: ApplyOne stamps whether the client is parked
|
||||
// behind this record before anything can ask. The wire's answer is used only when the
|
||||
// client's wait rule is in force and this server publishes kCapRunAheadApply; otherwise every
|
||||
// record is barriered. A server without that bit has a lockstep client, and stamping its
|
||||
// kWaitNone draws unbarriered while that client is parked would make CountBarrierPull abort.
|
||||
// Pure so a unit test can pin "no run-ahead bit, never runs ahead" for any input.
|
||||
constexpr Bool MGPipeApplierStampsBarriered(Bool clientWaitRuleLanded,
|
||||
Bool serverPublishesRunAhead,
|
||||
Bool wireSaysBarriered) {
|
||||
|
||||
@@ -6,49 +6,13 @@
|
||||
// SPDX-License-Identifier: LGPL-3.0-only
|
||||
// End of Source File Header
|
||||
|
||||
// PH-7 (5), CONTRACT-P7 §12, docs/archive/notes/p7/ph-f.md §6.4. THE TCP SUPERVISOR AUTHENTICATES BEFORE IT
|
||||
// FORKS, AND AN UNAUTHENTICATED PEER'S WORK IS BOUNDED.
|
||||
//
|
||||
// Two exposures were on the tree before wave 2-F and were recorded by its review:
|
||||
// (a) the supervisor forked a session child for every accepted TCP connection and let the child
|
||||
// read the Hello - so any peer that could reach the port cost the server a fork, and a
|
||||
// silent one held that child for up to 10 s;
|
||||
// (b) the child ran ValidatePeerHandshake before AuthenticatePeerToken, so an unauthenticated
|
||||
// peer that sent a Hello with a wrong fingerprint was answered with Refuse{WireFingerprint}
|
||||
// carrying THIS build's wire fingerprint (and Refuse{BuildFingerprint} its build stamp).
|
||||
//
|
||||
// The supervisor now reads every new connection's FIRST FRAME itself, without blocking on any one
|
||||
// peer, under a short deadline; a Hello is authenticated there, token first, and only an
|
||||
// authenticated Hello is ever forked for. The pieces that decide are here, free of I/O policy and
|
||||
// of the supervisor's loop, so they are unit-testable (PreAuthGateTest):
|
||||
//
|
||||
// PreAuthKnobs the four knobs, read once from the environment;
|
||||
// ClassifyFirstFrame what a complete first frame IS - the fuzz arm 1 malformations each land
|
||||
// on a named shape here, and the identifier is asked before the verifier;
|
||||
// FirstFrameAssembler reads EXACTLY one frame off a non-blocking socket, a few bytes at a time,
|
||||
// and never a byte past it: a DataBind is followed on its connection by
|
||||
// StreamLink's own frames, which belong to the session child;
|
||||
// AuthBackoff failures per peer address, and the exponentially growing window during
|
||||
// which that address is refused at accept, before a byte of it is read.
|
||||
//
|
||||
// What a failure IS, for the backoff: a Hello whose token did not match, a first frame that is not
|
||||
// a well-formed control frame, a connection that let the deadline pass, and a connection that HELD
|
||||
// its pending slot for kPreAuthProbeGraceMs or longer and then closed (or was displaced, below)
|
||||
// without completing a frame. What it is NOT: a connection that closed within kPreAuthProbeGraceMs
|
||||
// of its accept without sending a byte (a port probe costs the server an accept and nothing else),
|
||||
// a DataBind that names no live session (a stale data connection of a session that just ended is a
|
||||
// legitimate client's), and a refusal the backoff itself issued (counting those would let anybody
|
||||
// behind a shared address keep that address locked out for ever).
|
||||
//
|
||||
// Fix round (the f2-auth critic's reproduction). The first cut counted no silent close at all, and
|
||||
// the pending slots were one pool for everybody: one address could open MOBILEGL_IPC_PREAUTH_MAX
|
||||
// silent connections, close them just before the deadline, open them again, and every Hello from
|
||||
// anywhere was refused Busy for as long as it liked - no failure counted, no backoff ever. Two
|
||||
// rules close that: a silent connection that held its slot past the grace is a failure (so the
|
||||
// holder is backed off after MOBILEGL_IPC_AUTH_BACKOFF_AFTER of them), and a full queue is SHARED
|
||||
// (ChoosePendingToDisplace): a newcomer from an address that holds fewer slots than the busiest
|
||||
// address displaces the busiest address's oldest pending connection, so no one address can keep
|
||||
// another out.
|
||||
// Pre-authentication for the TCP supervisor. It reads each new connection's first frame itself,
|
||||
// without blocking on any one peer and under a short deadline, checks the token first, and forks
|
||||
// a session child only for an authenticated Hello. The deciding pieces are free of I/O policy so
|
||||
// PreAuthGateTest can drive them: PreAuthKnobs (the environment knobs), ClassifyFirstFrame,
|
||||
// FirstFrameAssembler (reads exactly one frame and never a byte past it: a DataBind's connection
|
||||
// goes on with StreamLink frames that belong to the session child) and AuthBackoff. What counts
|
||||
// as a failure and how the pending queue is shared: ARCHITECTURE.md §15.1.1.
|
||||
|
||||
#pragma once
|
||||
|
||||
|
||||
@@ -6,54 +6,14 @@
|
||||
// SPDX-License-Identifier: LGPL-3.0-only
|
||||
// End of Source File Header
|
||||
|
||||
// P12 (on-screen server window), D3/D6. THE SERVER'S OWN WINDOW, AS ONE PROCESS-WIDE HOLDER.
|
||||
//
|
||||
// WHAT IT IS FOR. A client that sets MOBILEGL_IPC_SURFACE=server is headless: it asks the server to
|
||||
// create its window surface on the SERVER's window (WindowKind::ServerOwned) and learns the
|
||||
// surface's geometry back from the server. That window belongs to the in-process display server -
|
||||
// on Android the display Activity's SurfaceView, handed in through JNI (the next stage's glue) -
|
||||
// and this class is where it is held between the UI thread that owns the window's lifecycle
|
||||
// (surfaceCreated / surfaceChanged / surfaceDestroyed) and the apply thread that renders into it.
|
||||
//
|
||||
// WHO HAS A DISPLAY. Nobody, until Install(): the Linux host server, the exec'd supervisor and
|
||||
// every session child it forks never call it, so HasDisplay() is false there and a ServerOwned
|
||||
// request is refused by name (ServerLoop.cpp's ServerOwned arm, SurfaceRefusal::NoServerDisplay).
|
||||
// Only the in-process display server installs one.
|
||||
//
|
||||
// THE WINDOW IS OPAQUE HERE. It is a `void*` with three hooks - acquire and release (Android:
|
||||
// ANativeWindow_acquire / ANativeWindow_release) and a geometry request (the native -> Java
|
||||
// up-call: SurfaceHolder.setFixedSize(w, h) for w, h > 0, setSizeFromLayout() for 0/0). That is
|
||||
// what lets the host unit tests drive attach / wait / detach with a fake handle, and it keeps this
|
||||
// file free of any platform header.
|
||||
//
|
||||
// THE LEASE. The apply thread that substitutes the window into a backend takes a LEASE on it
|
||||
// (AcquireFor) and names a hook that asks it to let go. Detach() - the surfaceDestroyed path -
|
||||
// calls that hook and then BLOCKS, bounded, until the holder has released its backend surface and
|
||||
// ended the lease (EndLease); only then is the window's reference released. That ordering is the
|
||||
// GLSurfaceView contract: after surfaceDestroyed returns nothing may render into the window. A
|
||||
// holder that does not answer in time does not get the window pulled out from under it - the
|
||||
// reference is kept and released when the lease finally ends - and Detach returns TimedOut, by
|
||||
// name, so the UI thread is never held longer than its bound.
|
||||
//
|
||||
// A LEASE THAT IS ENDING IS WAITED FOR, NOT REFUSED. A holder whose session is over - it latched a
|
||||
// fault (a device loss among them) or is stopping - says so (MarkLeaseEnding) before its client can
|
||||
// learn of it; its lease still lasts until its backend has let go of the window. A client that loses
|
||||
// its session re-creates its window surface on a fresh session at once, typically while the old
|
||||
// session's apply thread is still tearing its backend down: that request waits for the old lease
|
||||
// to end, bounded by its own timeout, instead of being refused as LeasedElsewhere. A holder whose
|
||||
// session goes on keeps the window exclusively, as before.
|
||||
//
|
||||
// SUSPEND, NOT END (screen off / lock). A holder whose backend can let go of the window and keep
|
||||
// everything else - its contexts, objects and device - ends its lease with SuspendLease instead of
|
||||
// EndLease and names a second hook: the next Attach of a NEW window calls it, so the holder can
|
||||
// lease that window (AcquireFor) and rebuild its surface on it. The registration lasts until that
|
||||
// AcquireFor succeeds or the holder cancels it (CancelResume, at the session's end).
|
||||
//
|
||||
// THREADS. Every method is thread-safe. The hooks are called from the thread that called the
|
||||
// method: acquire from Attach's caller, release from Detach's / EndLease's caller, requestGeometry
|
||||
// from the apply thread (AcquireFor), the lost hook from Detach's caller and the attached hook from
|
||||
// Attach's (or SuspendLease's) caller, both WITH THIS OBJECT'S LOCK HELD - so they must not block and
|
||||
// must not call back into this object (ServerLoop's set an atomic and ring its doorbell).
|
||||
// The server's own on-screen window, held process-wide between the UI thread that owns its
|
||||
// lifecycle (Attach / Detach on surfaceCreated, surfaceChanged, surfaceDestroyed) and the apply
|
||||
// thread that renders into it under a lease (AcquireFor / EndLease). Only the in-process display
|
||||
// server calls Install(); elsewhere a ServerOwned surface is refused (NoServerDisplay). The window
|
||||
// is an opaque `void*` driven through ServerDisplayHooks, so no platform header is needed here.
|
||||
// Nothing may render into the window after surfaceDestroyed returns, so Detach asks the holder to
|
||||
// let go and waits, bounded, for EndLease; on timeout it returns TimedOut and EndLease releases
|
||||
// the window later. A lease marked ending is waited for, not refused. See ARCHITECTURE.md §15.2.
|
||||
|
||||
#pragma once
|
||||
#include <Includes.h>
|
||||
|
||||
@@ -6,66 +6,13 @@
|
||||
// SPDX-License-Identifier: LGPL-3.0-only
|
||||
// End of Source File Header
|
||||
|
||||
// The apply thread and the server's private backend object. Owner: package v1 - the highest
|
||||
// risk item in P5. Signatures by c0.
|
||||
//
|
||||
// WHY THE THREAD IS THE POINT. DirectGLES has 16 IsBackendContextCurrentOnThisThread() guards
|
||||
// (DirectGLES.cpp:12034..12428) and Managers.cpp has 16 CanTouchGLNow() guards (:1494..:3428);
|
||||
// every one of them DEGRADES when the answer is false - fences become always-signaled, queries
|
||||
// return null handles, Present creates no frame fence so the buffer pool's recycle watermark
|
||||
// never advances, and the two persistent-map acquisitions (Managers.cpp:1494, :2170) DECLINE,
|
||||
// which would make PersistentCoherentMapScenario unreachable. Making the apply thread the
|
||||
// context owner for life turns all 32 of those answers true on the server and removes the
|
||||
// whole degradation class at once. It is also exactly the shape P6's spawned server inherits.
|
||||
//
|
||||
// P5 BUILDS ONE THREAD, NOT TWO. No mgl-srv-io: inproc's control plane is in the same process.
|
||||
// P6 splits it.
|
||||
//
|
||||
// PARKING AND SHUTDOWN. The thread parks on Doorbell::Wait(consumerParked, ready, spinUs,
|
||||
// kWaitForever) and shuts down when Wait returns false with Dead() set. TWO things can un-park a
|
||||
// kWaitForever waiter, not one, and the difference is the whole of review m-4: for the STOP case a
|
||||
// plain Doorbell::Notify() is sufficient, because m_stopRequested is in the park predicate and
|
||||
// Stop() publishes it BEFORE it rings (Doorbell.h re-tests ready() after every Park return);
|
||||
// Doorbell::Kill() (Doorbell.h, CondVarDoorbell::Kill) is load-bearing only for a predicate
|
||||
// that has NOTHING to see, which is why the redcheck's park-predicate-loses-control entry - the one that drops the
|
||||
// control flag FROM the predicate - is the case that actually times out. Kill BEFORE join; join
|
||||
// before the client frees any emitter-owned Vector; and the join must be bounded (that test uses
|
||||
// 5 s) so a regression is a red test and not a hung CI job.
|
||||
//
|
||||
// THE EGL OWNERSHIP MOVE, AS MEASURED (ID-54; review v2 item 10 and N-3). The native
|
||||
// eglMakeCurrent for a surface runs ONCE PER CONTEXT LIFETIME on this thread and the context is
|
||||
// then held for life. That "once" lives in TWO layers, because one is not enough:
|
||||
// DirectGLES::MakeCurrent always calls native eglMakeCurrent and rewrites the owner (codex C7),
|
||||
// and it is reached twice per bring-up - once from InitPbufferSurface/InitWindowSurface when the
|
||||
// surface is CREATED, and once more from the client's first eglMakeCurrent. So (1)
|
||||
// ServerMakeEGLCurrent classifies the request against the tuple it last bound
|
||||
// (ClassifyEglMakeCurrent): an identical repeat is a no-op, and the R-12 republish decision for
|
||||
// it is "nothing to republish" (ID-67: the client's mirror generation must not move); a different
|
||||
// tuple is a real forwarded bind AND a caps republish; a client release-current is RECORDED
|
||||
// (ClientReleaseCount) and NOT forwarded. And (2) BackendObject_DirectGLES::MakeEGLCurrent, under
|
||||
// an active transport only, skips the native call when the requested draw surface is the one
|
||||
// already natively current on this thread (IsBackendContextCurrentOnThisThread, which is EGL
|
||||
// ground truth) AND the virtual tuple is the one that bind was for - or the bind is the surface's
|
||||
// own creation, which the first tuple adopts; a different virtual context onto the same surface
|
||||
// binds natively again, because MakeCurrent's invalidations describe the frontend context that
|
||||
// changed (ID-67). Measured at the EGL function
|
||||
// table by ServerLoopTest's C7 control on a real llvmpipe context: surface creation + two
|
||||
// identical make-currents + a client release + a bind after the release = ONE native
|
||||
// eglMakeCurrent, ZERO native releases, and the apply thread still the owner afterwards. So
|
||||
// DirectGLES.cpp's six cache invalidations run once per context lifetime rather than once per
|
||||
// client make-current, and the 16 IsBackendContextCurrentOnThisThread() / 16 CanTouchGLNow()
|
||||
// sites answer TRUE on the server. The tuple is FORGOTTEN (N-3) on every event after which the
|
||||
// native context it names may be gone - ReleaseEGLResources, ReleaseEGLSurface of the surface it
|
||||
// names, a surface (re)creation, backend destruction - so a recycled handle value after a destroy
|
||||
// is a real bind again and never a silent no-context-current. The client's nine EGL virtuals
|
||||
// become BLOCKING control requests executed here. ReleaseEGLResources and
|
||||
// ~BackendObject_DirectGLES MUST be blocking: MobileGL::Destroy() (MobileGL/Init.cpp:68)
|
||||
// otherwise walks on while the server still holds the context.
|
||||
//
|
||||
// THE FALLBACK IS PRE-DECLARED, NOT INVENTED UNDER PRESSURE (R-1). If the context migration is
|
||||
// still not running ClearThenReadPixels at the end of v1's fourth working day, the integrator -
|
||||
// not the package - declares `inproc-inline`: the client thread drains the ring itself, no
|
||||
// thread is created, no context migrates, and a second package picks up the thread arm.
|
||||
// The apply thread (mgl-srv-apply) and the server's private backend object. The apply thread
|
||||
// owns the backend's native EGL context for the context's whole life, so the backend's
|
||||
// IsBackendContextCurrentOnThisThread() / CanTouchGLNow() guards answer true on the server
|
||||
// instead of degrading. The client's EGL calls reach it as blocking control requests (the
|
||||
// Server* forwarders below); ARCHITECTURE.md §15.5 has the make-current dedup and teardown rules.
|
||||
// Stop() publishes m_stopRequested, which is in the park predicate, before it rings, so a plain
|
||||
// Notify un-parks the thread; the join is bounded so a lost wakeup fails instead of hanging.
|
||||
|
||||
#pragma once
|
||||
#include <Includes.h>
|
||||
@@ -85,60 +32,14 @@
|
||||
|
||||
namespace MobileGL::MG_Remote::Server {
|
||||
|
||||
// ---------------------------------------------------------------------------------
|
||||
// THE APPLY-THREAD IDENTITY, AS ONE INTEGER (P5d round 3, package D)
|
||||
// ---------------------------------------------------------------------------------
|
||||
//
|
||||
// OnApplyThread() is the predicate under EVERY role guard on both hot paths -
|
||||
// RefuseLegacyBufferArmFromApplyThread in BufferObject's accessors, MG_Record::PersistentMapTracker::
|
||||
// OnServerRole, ClientSession::RefusePipeInputsTouchWhileApplierOwnsIt, RunsAsTheServerRole,
|
||||
// MGPipeRefuseAllocatorFromApplyThread, RefuseLegacyTextureArmFromApplyThread. simpleperf at
|
||||
// head 56a77348 (FCL + Minecraft, VD12, Adreno 830) measured it at 2.66% self / 3.64%
|
||||
// inclusive ON THE CLIENT THREAD, for an answer that is "no" every single time.
|
||||
//
|
||||
// The old body paid five times over for that "no": ServerLoopInstance()'s function-static
|
||||
// guard byte, an acquire load of m_running, an acquire load of an atomic<std::thread::id>,
|
||||
// std::this_thread::get_id(), and a thread::id comparison that is an out-of-line
|
||||
// pthread_equal through the PLT (@plt was 6.1% of the apply thread). None of it carries
|
||||
// information the guard needs. A live thread's identity is already sitting in a
|
||||
// register-cheap place - the thread pointer, TPIDR_EL0 on aarch64 - so the loop publishes
|
||||
// ITS identity as a plain integer here and every caller compares one relaxed load against
|
||||
// one register read, inline, with no call and no singleton.
|
||||
//
|
||||
// ZERO MEANS "NO APPLY THREAD IS RUNNING", which is exactly the answer m_running == false
|
||||
// used to give: the key is published as the apply thread's FIRST act (ApplyThreadMain) and
|
||||
// cleared in the same m_controlMutex critical section that clears m_running on the way out
|
||||
// (ApplyThreadMain's C2 exit block), so "key != 0" and "m_running" move together and the
|
||||
// window in which a live-but-exiting apply thread answers true is byte-for-byte the old
|
||||
// one. The ServerLoop object still OWNS the key - nothing but ApplyThreadMain writes it -
|
||||
// it simply no longer has to be reached through the singleton to be read.
|
||||
// P14 S2: AND THE ANSWER IS PER THREAD NOW, NOT PER PROCESS. One word cannot hold N apply
|
||||
// threads: two sessions' threads would each publish their own key and the second store would
|
||||
// make the FIRST thread answer "no" to every role guard it owns - which is not a slower guard
|
||||
// but a dead one (a draw would take the client arm on the apply thread, and
|
||||
// RunSurfaceControlFrame would lose its re-entrancy shortcut and deadlock the EGL teardown).
|
||||
// The question is "am I an apply thread", a fact about the CALLER, so it is asked in the
|
||||
// caller's own TLS - one constant-initialized word, no guard, no atomic:
|
||||
//
|
||||
// t_onApplyThread the calling thread IS an apply thread.
|
||||
// g_applyThreadKey HOW MANY are running in this process. Kept because
|
||||
// MG_Backend/DirectGLES/Managers.cpp (outside this package's file set)
|
||||
// reads this name `!= 0` - "an apply thread is running somewhere" - which
|
||||
// is the count's zero-ness exactly. It is no longer a key and nothing on
|
||||
// the hot paths reads it.
|
||||
//
|
||||
// ZERO MEANS "NO APPLY THREAD IS RUNNING" still: t_onApplyThread is raised as the apply
|
||||
// thread's FIRST act and lowered in the same m_controlMutex critical section that clears
|
||||
// m_running on the way out, so the window in which a live-but-exiting apply thread answers
|
||||
// true is byte-for-byte the old one.
|
||||
//
|
||||
// WHAT WENT WITH IT, so nobody re-derives it: the aarch64 TPIDR_EL0 fast path, the
|
||||
// std::thread::id fallback with its no-padding static_assert, the MOBILEGL_DETAIL_
|
||||
// APPLY_THREAD_POINTER build knob and the relaxed-load argument about a recycled TLS block.
|
||||
// They existed to make "is the process's one apply thread mine" cheap; the question is now
|
||||
// "is the caller an apply thread", whose cheap answer is the caller's own word - and a word
|
||||
// cannot be recycled, because the thread that inherits a dead apply thread's TLS block is
|
||||
// not an apply thread until it runs ApplyThreadMain.
|
||||
// The apply-thread identity. OnApplyThread() sits under every role guard on the per-draw hot
|
||||
// paths, so it is one inline read of the caller's own TLS word: no call, atomic or singleton.
|
||||
// It is a per-thread fact because a process runs one apply thread per served session.
|
||||
// t_onApplyThread the calling thread is an apply thread. ApplyThreadMain raises it before
|
||||
// it applies anything and lowers it in the m_controlMutex section that
|
||||
// clears m_running.
|
||||
// g_applyThreadKey how many apply threads this process runs; Managers.cpp reads `!= 0` as
|
||||
// "an apply thread is running somewhere". No hot path reads it.
|
||||
namespace Detail {
|
||||
// A fresh thread's TLS word is zero-initialized, so a thread that inherits the exited
|
||||
// apply thread's TLS block - the recycling case the old relaxed-load argument was about -
|
||||
@@ -152,27 +53,13 @@ namespace MobileGL::MG_Remote::Server {
|
||||
inline std::atomic<Uint64> g_applyThreadKey{0};
|
||||
} // namespace Detail
|
||||
|
||||
// ---------------------------------------------------------------------------------
|
||||
// P12 (on-screen server window), D4: ONE SURFACE MODE PER SESSION
|
||||
// ---------------------------------------------------------------------------------
|
||||
//
|
||||
// "Only one of the two rendering paths is active at a time, decided at context creation": a
|
||||
// session's mode latches at its FIRST successful surface creation - a ServerOwned window makes
|
||||
// it on-screen, a pbuffer makes it offscreen - and a later surface of the OTHER kind in the same
|
||||
// session is refused by name (SurfaceRefusal::SurfaceModeMismatch: reply ok=false, logged, the
|
||||
// session NOT latched). Windows the client names itself (the X11/Win32/None tokens CONTRACT-P6
|
||||
// D8 has yet to close) are neither kind and neither latch nor are refused: nothing about them
|
||||
// changes here. Reset by ServerLoop::Start, i.e. per session.
|
||||
//
|
||||
// P14 S2: AND THE LATCH IS PER SESSION, WHICH IS ALL THIS SLICE NEEDS. The mode is a member of
|
||||
// the loop and a served session owns its loop, so two sessions in one process latch
|
||||
// independently and neither's first surface decides the other's - the semantics above are
|
||||
// otherwise unchanged (design/11-state-ownership.md §4.5: the latch stays at the session layer
|
||||
// and is never hoisted to the process). A mode DECLARED before a session's first surface would
|
||||
// have to travel on the wire - the Hello, or a SurfaceOp the client sends - because one
|
||||
// process's MOBILEGL_IPC_SURFACE cannot speak for the several sessions a unified server runs;
|
||||
// that is P14d's. Reading that env here instead refused a dialled-in ServerOwned client with
|
||||
// SurfaceModeMismatch before the display was ever consulted (ServerOwnedSurfaceTest).
|
||||
// One surface mode per session. It latches at the session's first successful surface
|
||||
// creation: a ServerOwned window makes it on-screen, a pbuffer offscreen. A later surface of
|
||||
// the other kind is refused with SurfaceModeMismatch (reply ok=false, nothing latched).
|
||||
// Client-named windows (X11/Win32/None) and the surfaceless stand-in pbuffer neither latch
|
||||
// nor are refused. The mode is a loop member reset by ServerLoop::Start, so each session
|
||||
// latches on its own; it is not read from MOBILEGL_IPC_SURFACE, because one process's
|
||||
// environment cannot speak for every session a unified server runs.
|
||||
enum class SessionSurfaceMode : Uint8 { None, OnScreen, Offscreen };
|
||||
const char* SessionSurfaceModeName(SessionSurfaceMode mode);
|
||||
// The decision, pure, so a unit case can drive all six pairs without a backend.
|
||||
@@ -221,30 +108,14 @@ namespace MobileGL::MG_Remote::Server {
|
||||
// two files, and it is why no thread-keyed shim is needed for MOBILEGL_BUILD_DISAGGREGATED_INPROC.
|
||||
MG_Backend::BackendObject* Backend();
|
||||
|
||||
// Run one blocking control request on the apply thread and wait for it. This is how all
|
||||
// nine EGL lifecycle virtuals cross; it is deliberately NOT a queue of async messages,
|
||||
// because every one of them has a return value the caller acts on immediately.
|
||||
//
|
||||
// THE REQUEST IS A VALUE FRAME (P5f, package fc). It used to be a raw function pointer
|
||||
// plus a void* to a stack-local Args struct - neither has a meaning across a process
|
||||
// boundary, which is the whole of P5c audit row G4. Now the slot carries one
|
||||
// SurfaceControlFrame BY VALUE: the op's identity is the frame's `kind`, its arguments
|
||||
// are scalars, and its reply fields come back in the same value when the wait returns.
|
||||
// What did NOT move: the blocking handshake, the one slot, and the apply-thread
|
||||
// ownership. Under spawn the same frame is what SurfaceOpCodec encodes into a
|
||||
// Wire::SurfaceOp - this signature is the seam both transports share.
|
||||
// P6 `cp`: where a control frame goes when the server is ANOTHER PROCESS.
|
||||
//
|
||||
// All twelve Server* forwarders funnel through RunSurfaceControlFrame, so
|
||||
// this is ONE seam rather than twelve (a6 row A4-13 counted them). The
|
||||
// client installs a sink at handshake; with none installed the behaviour
|
||||
// is exactly what it was - post into the one-slot mailbox, or run inline
|
||||
// when we are already on the apply thread.
|
||||
//
|
||||
// A HOOK RATHER THAN A CALL INTO ClientSession, deliberately: the server
|
||||
// half calling the client half is four of the six symbols a6 found
|
||||
// MG_Remote owes itself (a6-link-experiment §5), and this is the one
|
||||
// place that would have added a fifth.
|
||||
// Runs one blocking control request on the apply thread and waits for it; every Server*
|
||||
// EGL forwarder funnels through here. Blocking rather than async, because each caller
|
||||
// acts on the reply at once. The frame crosses by value: `kind` names the op and the
|
||||
// reply fields come back in the same frame; under spawn SurfaceOpCodec encodes it as a
|
||||
// Wire::SurfaceOp. When the server is another process the client installs a
|
||||
// RemoteControlSink at handshake; with none, the frame goes to the one-slot mailbox, or
|
||||
// runs inline when already on the apply thread. A hook rather than a call into
|
||||
// ClientSession, so the server half does not depend on the client half.
|
||||
using RemoteControlSink = MobileGLResult (*)(void* user, SurfaceControlFrame& frame);
|
||||
void SetRemoteControlSink(RemoteControlSink sink, void* user);
|
||||
|
||||
@@ -388,31 +259,14 @@ namespace MobileGL::MG_Remote::Server {
|
||||
void ForgetCurrentTuple();
|
||||
void ForgetCurrentTupleIfItNames(EGLSurface surface);
|
||||
|
||||
// Part of the apply thread's park predicate: a posted control request must be able to
|
||||
// un-park a thread waiting on kWaitForever, which a Notify alone cannot do.
|
||||
//
|
||||
// IT READS ONE ATOMIC AND TAKES NO LOCK (P5d round 3, package T item 1). It used to
|
||||
// take m_controlMutex on every call, and the idle poll calls it on every iteration -
|
||||
// once inside the `ready` lambda and once more through PumpControlRequest - which
|
||||
// simpleperf at head 56a77348 measured as ~49% of the whole apply thread's cycles
|
||||
// (mutex::lock 12.4 + mutex::unlock 13.6 + the two pthread_* halves, 58-60% of them
|
||||
// with ApplyThreadMain as the DIRECT caller). An idle poll on an empty ring must cost
|
||||
// loads, not a futex-backed critical section. m_controlPosted is that load; the
|
||||
// mailbox's own fields stay under the mutex and the handshake below is unchanged.
|
||||
//
|
||||
// PUBLIC because ServerLoopTest reads it: the clear side of the shadow has a failure
|
||||
// mode - a shadow left set makes `ready` permanently true and the loop never parks
|
||||
// again - that no other public surface can see.
|
||||
//
|
||||
// READ THE PREDICATE LITERALLY: "a request is POSTED AND NOT YET TAKEN", which is
|
||||
// narrower than the name's "a control request is in flight". The shadow is cleared
|
||||
// when the pump takes the work, not when the work returns, so for the whole duration
|
||||
// of `work(user)` this answers false although m_controlPending is still true and the
|
||||
// poster is still blocked in RunSurfaceControlFrame. That is deliberate - it is a PARK
|
||||
// PREDICATE, and the thread that would act on it is the one running the work - but it
|
||||
// means this is not a liveness query and must not be used as one. The only in-tree
|
||||
// reader outside the test is the apply thread's own `ready` lambda, which by
|
||||
// construction cannot be inside that window.
|
||||
// Part of the apply thread's park predicate: a posted control request must un-park a
|
||||
// thread waiting on kWaitForever, which a Notify alone cannot do. It reads only
|
||||
// m_controlPosted, without the lock, because the idle poll calls it on every iteration and
|
||||
// a mutex here cost about half the apply thread's cycles. It means "posted and not yet
|
||||
// taken": the pump clears it when it takes the work, so it reads false while the work runs
|
||||
// and the poster still waits. Not a liveness query; the only reader is the apply thread's
|
||||
// `ready` lambda. Public so ServerLoopTest can catch a flag left set, which would stop the
|
||||
// loop from ever parking.
|
||||
Bool ControlIsPending() const;
|
||||
|
||||
// ---- P12 (on-screen server window), D3/D6 -------------------------------------------
|
||||
@@ -672,43 +526,14 @@ namespace MobileGL::MG_Remote::Server {
|
||||
// The supervisor announces it at start-up; the server app's broker relays it to the helper.
|
||||
Uint64 ReservedApplyCoreForThisProcess(const char** outRule);
|
||||
|
||||
// ---------------------------------------------------------------------------------
|
||||
// THE EGL OWNERSHIP MOVE - the part that can sink the phase, expressed as twelve calls
|
||||
// ---------------------------------------------------------------------------------
|
||||
//
|
||||
// Under split the app thread must never reach the driver's eglMakeCurrent. Today it does:
|
||||
// EGLImpl.cpp:284 -> BackendObject_DirectGLES.cpp:963 -> DirectGLES.cpp:11925, and the
|
||||
// owner slot g_backendContextOwnerThread (DirectGLES.cpp:11865) is stamped with whatever
|
||||
// thread got there. So BackendObject_Remote's nine EGL virtuals - package c1's - call these
|
||||
// twelve, each of which is a BLOCKING control request that runs the SERVER's backend object
|
||||
// on mgl-srv-apply. The native eglMakeCurrent then runs once per context lifetime on that
|
||||
// thread (the surface's own creation binds; the client's make-currents onto that surface
|
||||
// are deduped at both layers, header block above) and a client release is never forwarded,
|
||||
// so g_backendContextOwnerThread is written once per context lifetime, DirectGLES.cpp's six
|
||||
// cache invalidations run once per context lifetime rather than once per client
|
||||
// make-current, the per-frame EGL re-verification stamp holds, and the 16
|
||||
// IsBackendContextCurrentOnThisThread() sites plus the 16 CanTouchGLNow() sites answer TRUE
|
||||
// on the server instead of silently degrading. Measured, not assumed: ServerLoopTest's C7
|
||||
// control counts the driver's eglMakeCurrent calls at the EGL function table.
|
||||
//
|
||||
// TWO OF THEM MUST BLOCK OR THE PROCESS TEARS ITS OWN CONTEXT DOWN UNDER ITSELF:
|
||||
// ReleaseEGLResources (reached from EGLImpl.cpp:326, which for DirectGLES runs
|
||||
// DestroyEGLContext) and ~BackendObject_DirectGLES (reached from
|
||||
// pActiveBackendObject.reset() at MobileGL/Init.cpp:68). Both are blocking here - the first
|
||||
// by being one of these calls, the second because ServerLoop::Stop() destroys the private
|
||||
// backend ON the apply thread before that thread exits and Stop() itself waits.
|
||||
//
|
||||
// WHY THEY ARE FREE FUNCTIONS AND NOT MEMBERS: c1 needs exactly this surface and nothing
|
||||
// else of the server, so the seam between the two packages is a list of twelve signatures
|
||||
// rather than a class with a lifecycle.
|
||||
//
|
||||
// P5f (package fc): each of the twelve packs its arguments into a SurfaceControlFrame and
|
||||
// posts it through RunSurfaceControlFrame - the wire-shaped value channel that replaced the
|
||||
// function-pointer mailbox (P5c audit row G4). Nine of them map onto the ten wire ops of
|
||||
// protocol.fbs's SurfaceOp; ServerSwapEGLBuffers, ServerInitCapabilities and
|
||||
// ServerInitWindowSurface ride the same channel as inproc-only kinds (present travels as a
|
||||
// record, capabilities are answered by the CapsSnapshot frame, and the third has no caller -
|
||||
// f0-egl's census, findings F8/§4.2).
|
||||
// The EGL control forwarders. BackendObject_Remote's EGL virtuals call these, so the app
|
||||
// thread never reaches the driver's eglMakeCurrent: each packs its arguments into a
|
||||
// SurfaceControlFrame and blocks in RunSurfaceControlFrame while mgl-srv-apply runs it against
|
||||
// the server's backend (ARCHITECTURE.md §15.5). ServerReleaseEGLResources must block, and so
|
||||
// must ~BackendObject_DirectGLES, which ServerLoop::Stop() runs on the apply thread before it
|
||||
// exits; otherwise teardown runs on while the server still holds the context. Free functions,
|
||||
// because the client needs only these calls. SwapBuffers and InitWindowSurface are
|
||||
// inproc-only frame kinds with no wire op: present travels as a record.
|
||||
Bool ServerInitializeEGLDisplay(EGLDisplay dpy, EGLint* major, EGLint* minor);
|
||||
Bool ServerCreateEGLWindowSurface(EGLSurface surface, const MG_Backend::WindowHandle& handle);
|
||||
Bool ServerResizeEGLWindowSurface(EGLSurface surface, Uint32 width, Uint32 height);
|
||||
|
||||
@@ -361,26 +361,14 @@ void DelaySessionHandshakeForTest() {
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(std::min<long>(ms, 60000)));
|
||||
}
|
||||
|
||||
// Called only after fork (or, in the single-session shape, instead of it): the supervisor never
|
||||
// creates a backend or EGL context. `dataSource` is set on TCP (PH-7 (4)) and empty on a unix
|
||||
// endpoint, whose second connection is the SCM_RIGHTS socket PairAcceptor already paired.
|
||||
// `sourceFd` is the descriptor that source reads from - the child's end of the hand-off
|
||||
// socketpair under --serve, the listener itself in the single-session shape - and -1 when there
|
||||
// is none; it is let go of the moment Accept returns, and on every exit before that
|
||||
// (ExitBeforeAccept, ID-P7-44).
|
||||
//
|
||||
// `helloFrame` is the first frame when somebody has already read and authenticated it - the TCP
|
||||
// supervisor always has (PH-7 (5)) - and empty when this function reads it itself, within
|
||||
// `helloWaitMs`.
|
||||
//
|
||||
// P12 (D5): IT RETURNS THE SESSION'S EXIT CODE, and never exits. A forked child and a
|
||||
// single-session process pass the code straight to ExitSessionProcess - so every one of those shapes
|
||||
// ends with the `_exit` code it always had - while `inProcess` (the in-process display server's
|
||||
// session thread) returns it to the supervisor thread and the process lives on. What a process exit
|
||||
// used to clean up for free, `inProcess` cleans up by hand on every way out: the backend (the loop's
|
||||
// Stop drops one no thread owns), the session singleton, the stats window, the log forwarder and the
|
||||
// progress sink, both of which point at `control`. The latch is reset by the supervisor between
|
||||
// sessions (ResetSessionLatch).
|
||||
// Runs one served session; the supervisor never creates a backend or EGL context. `dataSource` is
|
||||
// set on TCP and empty on a unix endpoint, whose aux connection PairAcceptor already paired.
|
||||
// `sourceFd` (the hand-off socketpair end under --serve, the listener in the single-session shape,
|
||||
// or -1) is released when Accept returns and on every earlier exit (LeaveBeforeAccept).
|
||||
// `helloFrame` holds the first frame if the caller already read and authenticated it; otherwise it
|
||||
// is read here within `helloWaitMs`. Returns the session's exit code and never exits; with
|
||||
// `inProcess` (a session thread of the in-process display server) every way out cleans up by hand
|
||||
// what a process exit would, and the supervisor resets the latch between sessions.
|
||||
int RunSession(std::unique_ptr<SocketTransport> control, std::vector<std::uint8_t> helloFrame,
|
||||
Server::ServerSession::DataConnectionSource dataSource, int sourceFd, DataSource sourceKind,
|
||||
std::uint32_t helloWaitMs, bool inProcess = false) {
|
||||
@@ -481,23 +469,13 @@ int RunSession(std::unique_ptr<SocketTransport> control, std::vector<std::uint8_
|
||||
MobileGL::MG_Config::Transport = MobileGL::MG_Config::TransportMode::Spawn;
|
||||
MobileGL::MG_Pipe::MGPipeSetServerProcessRole(true);
|
||||
});
|
||||
// PH-1 (3), ID-P7-1: THIS PROCESS IS THE SESSION, so a named fault on the peer's bytes may end
|
||||
// it cleanly instead of aborting it (FatalFunnel.h's latch block). Armed here and nowhere
|
||||
// else: inproc keeps every Fatal (client and server share that process), and the supervisor
|
||||
// that forked this child never applies a record.
|
||||
//
|
||||
// P12 (D5): and the in-process display server arms it for EVERY session, here, the same way.
|
||||
// P14 S2: "IT" IS PER SESSION NOW - the scope below binds this thread to this session's latch
|
||||
// domain (FatalFunnel.h), so the arm that follows arms THAT domain and no other: a session
|
||||
// that latched cannot decline its neighbour, and the supervisor's ResetSessionLatch touches
|
||||
// only its own (process-default) domain.
|
||||
// P14 S2: THIS SESSION'S OWN RUNTIME, AND BOTH OF ITS THREADS ON IT. The object holds the
|
||||
// session, the apply loop and the PipeInputs block; the scope makes them what this thread's
|
||||
// reads of ServerSessionInstance()/ServerLoopInstance()/gPipeInputs resolve to, and binds this
|
||||
// session's latch domain and segment resolver. Everything below - the backend bring-up, the
|
||||
// arm, the EGL frames - therefore runs against THIS session, which is what lets one process
|
||||
// serve several at once. The apply thread opens the same scope as its first act
|
||||
// (ServerLoop::ApplyThreadMain, via SetRuntime below).
|
||||
// A served session's process (or in-process thread) is the session, so a named fault on the
|
||||
// peer's bytes may end it cleanly instead of aborting (FatalFunnel.h's latch); inproc keeps
|
||||
// every Fatal, and the supervisor applies no record. SessionRuntime holds this session's
|
||||
// session object, apply loop and PipeInputs block; the scope binds this thread's
|
||||
// ServerSessionInstance(), ServerLoopInstance(), gPipeInputs, latch domain and segment
|
||||
// resolver to it, so ArmSessionLatch arms this session's domain only. The apply thread opens
|
||||
// the same scope first (ServerLoop::ApplyThreadMain).
|
||||
auto runtime = std::make_unique<Server::SessionRuntime>();
|
||||
Server::Detail::ThreadSessionScope threadScope(*runtime);
|
||||
ArmSessionLatch();
|
||||
@@ -705,30 +683,12 @@ int RunSession(std::unique_ptr<SocketTransport> control, std::vector<std::uint8_
|
||||
WireLogError("MG_Remote server: pid=%d transport=spawn role=server ready control=%s data=%s",
|
||||
selfPid, tcp ? "tcp" : "unix", tcp ? "stream" : "shm");
|
||||
std::vector<std::uint8_t> buffer(64 * 1024);
|
||||
// PH-6 (ID-P7-2): THE CONTROL WAIT IS BOUNDED, SO A SESSION CAN END FROM THE SERVER'S SIDE.
|
||||
// It used to be kWaitForever, which left exactly one way out: the peer closing its control
|
||||
// connection. A peer that forfeited the reverse channel is by definition one that stopped
|
||||
// reading, and it may well keep that connection open - so the apply thread would stop and
|
||||
// this child would sit here, holding the supervisor's one session slot, answering every
|
||||
// later client Busy. Now each quiet interval asks whether the apply thread is still there;
|
||||
// when it is not (forfeit, or a dead data bell), the session takes the ordinary exit below:
|
||||
// Stop, Close, _exit(0). (PH-6 used the supervisor's 250 ms accept poll as the interval; the
|
||||
// PH-1 note below says why the slice is now 100 ms.)
|
||||
//
|
||||
// ASKED AT THE TOP OF EVERY TURN, NOT ONLY WHEN A WAIT TIMES OUT (PH-6 fix round). A peer that
|
||||
// forfeited the reverse channel but keeps TALKING - a LogFlush or a surface op more often than
|
||||
// every 250 ms, each of which this loop answers - never let ReceiveFrame time out, so the
|
||||
// question was never asked and the session, with the supervisor's one slot, lived as long as
|
||||
// the peer kept chattering.
|
||||
//
|
||||
// PH-1 (3): the same wait is also how a LATCH raised on the apply thread (the decoder, the
|
||||
// applier, DrainRing) ends this loop within one slice while the peer is silent. ReceiveFrame
|
||||
// keeps a partial frame in its reassembler across a timeout, so slicing loses no bytes; a
|
||||
// latched session is then closed below with kSessionLatchedExitCode. The latch is asked
|
||||
// BEFORE the apply thread's liveness because a latch also stops that thread (it leaves its
|
||||
// loop and clears m_running), and the session must be named by its latch, not as a stopped
|
||||
// apply thread. One slice serves both: the latch's 100 ms (PH-6 had 250 ms; the shorter wait
|
||||
// only asks the question more often).
|
||||
// The control wait is sliced so a session can end from the server's side. Each turn first asks
|
||||
// whether the session latched (a fault on the apply thread, which also stops that thread, so
|
||||
// the latch is asked first and names the end), then whether the apply thread still runs (it
|
||||
// stops on a forfeited reverse channel or a dead data bell). Both are asked every turn, not
|
||||
// only on timeout, so a peer that keeps sending frames cannot hold the supervisor's session
|
||||
// slot. ReceiveFrame keeps a partial frame across a timeout, so slicing loses no bytes.
|
||||
constexpr std::uint32_t kControlSliceMs = 100;
|
||||
for (;;) {
|
||||
if (SessionLatched()) break;
|
||||
@@ -765,23 +725,10 @@ int RunSession(std::unique_ptr<SocketTransport> control, std::vector<std::uint8_
|
||||
static_cast<unsigned long long>(control->BufferedBytes()));
|
||||
break;
|
||||
}
|
||||
// THE FILE IDENTIFIER, ASKED FIRST AND SAID OUT LOUD (P7 wave 0).
|
||||
//
|
||||
// The plan asked for CtrlEnvelopeBufferHasIdentifier here because ServerSession::
|
||||
// ParseEnvelope (:109) asks it and this loop did not. MEASURED, THE PREMISE IS WRONG:
|
||||
// the generated VerifyCtrlEnvelopeBuffer is
|
||||
// `verifier.VerifyBuffer<CtrlEnvelope>(CtrlEnvelopeIdentifier())`
|
||||
// (protocol_generated.h:2378), so a wrong identifier was ALREADY refused - and so is
|
||||
// ParseEnvelope's second call. Recorded for the integrator: the gap that row names does
|
||||
// not exist.
|
||||
//
|
||||
// What DID exist is that both refusals were silent. A peer whose post-Welcome frame was
|
||||
// garbage got its session ended with no line in the log at all, which is the half of a
|
||||
// fuzz arm that matters - an arm that cannot tell "refused, by name" from "the child
|
||||
// went away" measures nothing. So the identifier is now asked FIRST, because it is the
|
||||
// specific diagnosis ("that is not our schema") where the verifier's is the general one,
|
||||
// and both say so. Asking it first needs the length guard the verifier would otherwise
|
||||
// have provided: BufferHasIdentifier reads bytes [4, 8).
|
||||
// The identifier is checked before the verifier, which would also reject a wrong one, so
|
||||
// the log names the specific cause; every refusal here is logged, because a silent end
|
||||
// cannot be told apart from a crashed child. BufferHasIdentifier reads bytes [4, 8),
|
||||
// hence the length guard.
|
||||
if (size < 8) {
|
||||
WireLogError("MG_Remote server: control frame is %llu bytes, too short to carry a "
|
||||
"CtrlEnvelope root and identifier; ending the session",
|
||||
@@ -926,37 +873,11 @@ void LogSupervisorSummary(unsigned long sessionsFaulted) {
|
||||
static_cast<int>(::getpid()), sessionsFaulted);
|
||||
}
|
||||
|
||||
// PH-7 (5), ID-P7-3, ph-f.md §6.4, CONTRACT-P7 §12. THE TCP SUPERVISOR: AUTHENTICATE, THEN FORK.
|
||||
//
|
||||
// Until this package the --serve loop accepted a TCP connection and forked a session child for
|
||||
// it before a byte had been read; the child read the Hello (10 s budget), checked the wire and
|
||||
// only then the token. So anybody who could reach the port cost the server a fork per connection
|
||||
// and a child held for up to 10 s, and an unauthenticated Hello with a wrong fingerprint was
|
||||
// answered with this build's fingerprint. Now:
|
||||
//
|
||||
// - every new connection is PENDING until its first frame is complete. The supervisor reads it
|
||||
// itself, a few bytes per wakeup, from all pending connections at once (one poll loop - no
|
||||
// unauthenticated peer can make it wait for another; the one wait left is up to 50 ms for an
|
||||
// exiting session before an AUTHENTICATED Hello is told Busy), and never a byte past the frame;
|
||||
// - a pending connection has MOBILEGL_IPC_PREAUTH_MS (default 2000) to complete it, and at most
|
||||
// MOBILEGL_IPC_PREAUTH_MAX (default 8) are pending at once. The queue is SHARED between
|
||||
// addresses: when it is full a newcomer displaces the oldest connection of the address holding
|
||||
// the most slots, and is itself refused Busy only when its own address already holds as many;
|
||||
// - a Hello is AUTHENTICATED HERE, token first; an unauthenticated one is answered
|
||||
// Refuse{Authentication} and nothing else. Only an authenticated Hello is forked for, and the
|
||||
// child is handed the frame it would otherwise have read;
|
||||
// - a failure (wrong token, malformed first frame, deadline, a silent connection that held its
|
||||
// slot past kPreAuthProbeGraceMs before it closed or was displaced) is counted against the
|
||||
// peer's address; after MOBILEGL_IPC_AUTH_BACKOFF_AFTER (default 5) of them that address is refused
|
||||
// at accept, before a byte is read, for MOBILEGL_IPC_AUTH_BACKOFF_MS doubling per further
|
||||
// failure up to a minute. An authenticated Hello from the address clears it;
|
||||
// - a DataBind is routed exactly as PH-7 (4) routed it: to the live session's child over the
|
||||
// hand-off with the nonce as sideband (the child compares), or refused by name when there is
|
||||
// no live session - here now, instead of in a child forked to say so.
|
||||
//
|
||||
// What is unchanged: one session at a time (an AUTHENTICATED second client is Busy), the child's
|
||||
// own ValidatePeerHandshake / Accept / BindDataConnection, the hand-off and its refusals, the
|
||||
// reap lines and sessionsFaulted.
|
||||
// The TCP supervisor reads every new connection's first frame itself without blocking on any
|
||||
// one peer, authenticates a Hello (token first) and only then hands the session off (fork or
|
||||
// thread); it routes DataBinds to the live session and backs off failing addresses
|
||||
// (ARCHITECTURE.md §15.1.1, PreAuthGate.h). One session at a time: an authenticated second Hello
|
||||
// is answered Busy.
|
||||
class TcpSupervisor {
|
||||
public:
|
||||
using Clock = std::chrono::steady_clock;
|
||||
|
||||
@@ -46,25 +46,12 @@
|
||||
namespace MobileGL::MG_Remote::Server {
|
||||
|
||||
namespace {
|
||||
// F1 (P7 wave 2). THE ONLY KNOB THAT CAN MAKE THE FIRST CapsSnapshot LATE.
|
||||
//
|
||||
// MOBILEGL_TEST_DELAY_FIRST_CAPS_MS delays the server's FIRST publication, and only
|
||||
// it - a re-send (R-12) is never delayed, because the question is about the window
|
||||
// before the client has any mask at all. Read once, on the first Accept, so a lane
|
||||
// that does not set it pays one getenv per session and nothing else.
|
||||
//
|
||||
// WHAT IT PROVES, AND WHERE. Under spawn / unix: / tcp:// the publication happens in
|
||||
// the SERVER's process, so the delay is a genuinely late snapshot from the client's
|
||||
// point of view and it exercises the client's step-7 wait (ClientSession.cpp:1284).
|
||||
// Under inproc there is no second process: Accept runs inside ClientSession::Start on
|
||||
// the client's own thread, so the delay simply makes Start slower - which is itself
|
||||
// the proof that under inproc the first snapshot CANNOT be late relative to session
|
||||
// start, and therefore that the only window in which the client could read a
|
||||
// placeholder is the one BEFORE Start is called. That window is F1's defect, and
|
||||
// MobileGL::Initialize closes it by ordering rather than by waiting.
|
||||
//
|
||||
// It is a TEST knob: it exists only in a disaggregated build and does nothing at all
|
||||
// unless it is set, so no production path can reach a delay it did not ask for.
|
||||
// MOBILEGL_TEST_DELAY_FIRST_CAPS_MS: a test-only knob (disaggregated builds, inert unless
|
||||
// set) that delays the server's first CapsSnapshot only; re-sends are never delayed. Read
|
||||
// once per process. Across processes it makes the snapshot genuinely late and exercises the
|
||||
// client's wait for it; under inproc Accept runs inside ClientSession::Start, so it only
|
||||
// slows Start, showing the first snapshot cannot be late relative to session start there
|
||||
// (the window before Start is closed by ordering in MobileGL::Initialize).
|
||||
void DelayFirstCapsSnapshotForTest() {
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
static Bool spent = false;
|
||||
@@ -228,28 +215,14 @@ namespace MobileGL::MG_Remote::Server {
|
||||
eventName, static_cast<unsigned long long>(payloadBytes));
|
||||
}
|
||||
|
||||
// ---- P5e (ra), CONTRACT-P5E §2.6: the ring stops being a Fatal and becomes a queue --
|
||||
//
|
||||
// THE FATAL'S PREMISE DIES WITH THE LOCKSTEP. "A full ring is a producer burst no
|
||||
// workload has" was true because the client drained at EVERY verb: the ring was empty
|
||||
// whenever the server started a record, so filling 256 KiB inside one apply meant a
|
||||
// defect. A run-ahead client drains at its waits, which on the steady path are one
|
||||
// present apart, so a full ring is now an ordinary backlog and aborting on it would
|
||||
// turn the reverse channel's capacity into a workload limit.
|
||||
//
|
||||
// SO THE PRODUCER BLOCKS. It publishes what is already in the ring and rings the
|
||||
// client (a client that has not yet noticed cannot drain), then parks on its own bell
|
||||
// until the client's Drained() clears the latch and rings back. The deadlock argument
|
||||
// is the contract's, and it needs BOTH halves: the server blocks only here, the client
|
||||
// blocks only on watermarks the server advances, and every client park breaks on
|
||||
// `eventRingFull` as well (SessionProducer::WaitFor*OrEventBacklog) - so a parked
|
||||
// client is always wakeable by the server that is waiting for it.
|
||||
//
|
||||
// ONE NAMED REFUSAL SURVIVES, the impossible case: a single event larger than the ring
|
||||
// can EVER hold (no amount of draining helps). The two BUSY refusals that used to sit
|
||||
// beside it - a wait that ran out of patience, and two rounds against a ring the record
|
||||
// fits - are the PEER's behaviour and became the forfeit latch below (PH-6, ID-P7-2).
|
||||
// A server that does not publish kCapRunAheadApply keeps P5C's Fatal unchanged.
|
||||
// With run-ahead the client drains SEG_EVENT only at its waits, so a full event ring is an
|
||||
// ordinary backlog: the producer publishes what it has, rings the client and parks on its
|
||||
// own bell until the client's Drained() clears the latch and rings back. No deadlock: the
|
||||
// server blocks only here, and every client park also breaks on `eventRingFull`
|
||||
// (SessionProducer::WaitFor*OrEventBacklog). One event larger than the ring can ever hold
|
||||
// is still Fatal; a client that does not drain forfeits the reverse channel
|
||||
// (ServerSession::ForfeitReverseChannel). A server without kCapRunAheadApply keeps the
|
||||
// overflow Fatal. See ARCHITECTURE.md §11.7.
|
||||
Bool ServerPublishesRunAhead(const ServerSession& session) {
|
||||
if (!session.CallMaskIsSet()) return false;
|
||||
return (session.CallMask() & static_cast<Uint64>(MG_Pipe::kCapRunAheadApply)) != 0;
|
||||
|
||||
@@ -6,38 +6,14 @@
|
||||
// SPDX-License-Identifier: LGPL-3.0-only
|
||||
// End of Source File Header
|
||||
|
||||
// The server half of a session: the consumer side of the rings, the handshake reply, the caps
|
||||
// snapshot. Owner: package s1. Signatures by c0.
|
||||
//
|
||||
// The four segment sizes are already pinned by ProtocolSmokeTest.cpp:72 and are not up for
|
||||
// re-derivation here: SEG_CMD 8 MiB, SEG_STAGE 32 MiB, SEG_REPLY 8 MiB, SEG_EVENT 256 KiB.
|
||||
// MOBILEGL_IPC_RING_MB and MOBILEGL_IPC_STAGE_MB move the first two; the ring caps ONE record
|
||||
// at half its size (R-10). See SessionRings.h's header for why the ring inside SEG_CMD is 4 MiB
|
||||
// rather than 8 - the control page takes the head and the capacity must be a power of two -
|
||||
// and why that deviation from CONTRACT-P5 §5's arithmetic is in the safe direction.
|
||||
//
|
||||
// THE TWO DOORBELL ACCESSORS ARE ON THE CONCRETE CLASS, NOT ON ITransport
|
||||
// (InProcessTransport.h:64-68). P5 decides this now rather than letting P6 discover it: the
|
||||
// SESSION owns the pair and hands out references, so ITransport stays the dumb control-plane
|
||||
// interface its header says it is and SocketTransport does not have to grow two accessors it
|
||||
// has no natural home for. Discovering this in P6 would mean re-laying one package's call sites.
|
||||
//
|
||||
// WHO CREATES THE SEGMENTS: this side. Welcome announces all four SegmentRefs and Welcome is
|
||||
// server -> client, so the server allocates and the client attaches. "Client-owned" in
|
||||
// protocol.fbs's comments is about who WRITES a segment, not who allocates it.
|
||||
//
|
||||
// WHAT Accept() DOES, IN ORDER. The ABI assertion is FIRST, before a single record is decoded
|
||||
// and before any segment exists, because its whole purpose is to refuse to interpret the peer's
|
||||
// bytes at all:
|
||||
// 1. receive Hello;
|
||||
// 2. compare abiMajor/abiMinor and CapsAbiFingerprint() - Fatal{AbiMismatch} on a difference,
|
||||
// never a downgrade;
|
||||
// 3. create and map the four segments, initialise both control pages, clear the reply pool;
|
||||
// 4. send Welcome with the four SegmentRefs;
|
||||
// 5. publish the first CapsSnapshot, IF a backend has been handed over (SetBackend). Without
|
||||
// one the session is accepted and the snapshot is deferred with a loud line: the caps
|
||||
// blob codecs are w1's and the server's private BackendObject is v1's, and a session that
|
||||
// refused to exist until both landed would block every other package's bring-up.
|
||||
// The server half of a session: the consumer side of the rings, the doorbell pair (handed out
|
||||
// here, not by ITransport, which stays control-plane only), the handshake reply and the caps
|
||||
// snapshot. The server allocates the segments and the client attaches; "client-owned" in
|
||||
// protocol.fbs means who writes a segment. Accept, in order: receive Hello; authenticate the peer
|
||||
// and refuse any ABI, fingerprint or link-terms mismatch before any shared memory exists or any
|
||||
// record is decoded; create the segments; send Welcome; bind the stream data connection, if any;
|
||||
// install the segment resolver and the reverse-channel callbacks; publish the first CapsSnapshot
|
||||
// if SetBackend was called, else defer it with a warning.
|
||||
|
||||
#pragma once
|
||||
#include "../Transport/ILink.h"
|
||||
@@ -146,30 +122,14 @@ namespace MobileGL::MG_Remote::Server {
|
||||
// PublishCapsSnapshot yourself.
|
||||
void SetBackend(MG_Backend::BackendObject* backend);
|
||||
|
||||
// MGPCaps::CallMask's two halves. BOTH ARE MANDATORY AND NEITHER HAS A DEFAULT.
|
||||
//
|
||||
// The first version of this file derived a default for each. That was the phase's
|
||||
// marquee defect committed from the server's side: the consumer default read
|
||||
// MGPipeGetResourceOps(), a PROCESS-WIDE global (PipeApply.cpp), so under inproc the
|
||||
// server answered with whatever the client half of the same process had registered,
|
||||
// and under spawn it collapsed to P2's 0x7f. Either way CapsMirror::ServerConsumes
|
||||
// then answers a client-side liveness gate with a guess: the client stops emitting
|
||||
// five P4a families, CLEARS ITS DIRTY FLAGS ON ACCEPTANCE ANYWAY, and the lane goes
|
||||
// green with the uploads lost - ID-39's 66 lost uploads, reflected. R-8's whole point
|
||||
// is that a client-side gate may never be answered by a server-side fact; a
|
||||
// server-side gate answered by a PROCESS-wide fact is the same defect one level down.
|
||||
//
|
||||
// So there is no derivation at all. An unset mask is a programming error and
|
||||
// CallMask() is a named Fatal on one - loud at the first snapshot instead of silent
|
||||
// for a phase. Flagging it in a report was not a mechanism; this is.
|
||||
//
|
||||
// BITS 0..8, THE MGPCapBit FEATURE BITS. What each one answers belongs to the package
|
||||
// that owns the question (kCapTimerQuery to the query family, kCapResidentSubData to
|
||||
// b1, and so on). `SetCapabilityBits(0)` is a legitimate and explicit answer - "this
|
||||
// server offers no optional capability" - and is the right call while those packages
|
||||
// land. kCapNeedsHostIndexBytes / kCapNeedsHostUboBytes / kCapViewportArray are RESERVED
|
||||
// (P8-F; CONTRACT-P5 table 0 first held the two host-byte bits at 0): the first two are
|
||||
// the only things that ask for an MGHostSpan, and 0 keeps every one of them off the wire.
|
||||
// MGPCaps::CallMask's two halves; both are mandatory and neither has a default. The client
|
||||
// decides from the consumer bits which record families to emit and still clears its dirty
|
||||
// flags on acceptance, so a guessed mask (a process-wide registration, a fixed value) loses
|
||||
// uploads silently; CallMask() is Fatal{UnsetCallMask} until both setters have run. This
|
||||
// one takes the MGPCapBit feature bits, each answered by the subsystem that owns it;
|
||||
// SetCapabilityBits(0) is an explicit "no optional capability". kCapViewportArray and the
|
||||
// two host-byte bits (kCapNeedsHost*Bytes, the only thing that asks for an MGHostSpan) are
|
||||
// reserved and stay 0.
|
||||
void SetCapabilityBits(Uint64 capBits);
|
||||
|
||||
// BITS 32..47, THE CONSUMER MASK (R-8 / C-4): which MGPipe subsystems this server has
|
||||
@@ -236,24 +196,13 @@ namespace MobileGL::MG_Remote::Server {
|
||||
Bool EventRingHasRoom() const;
|
||||
Transport::ITransport* Control_Plane();
|
||||
|
||||
// ---- PH-6 (ID-P7-2): THE REVERSE CHANNEL IS FORFEITED, NOT FATAL -------------------
|
||||
//
|
||||
// A run-ahead producer that finds SEG_EVENT full parks until the client drains room
|
||||
// (CONTRACT-P5E §2.6). What a client that does not drain used to cost was two Fatals
|
||||
// inside ReserveEventOrBlock - "waited 30000 ms", twice, and "a drained ring that still
|
||||
// refuses a record it fits is a corrupt cursor set", which a peer that drains one slot at
|
||||
// a time reaches in milliseconds. Both are the PEER's behaviour, not a defect of this
|
||||
// process, so neither may abort it.
|
||||
//
|
||||
// What replaces them is a LATCH on this session. The first event that cannot be placed
|
||||
// within MOBILEGL_IPC_EVENT_WAIT_MS raises it (ForfeitReverseChannel, which logs
|
||||
// `ReverseChannelForfeit{<cause>}` once); that event and every later one is a counted
|
||||
// drop (CountDrop on the shared page, ForfeitDrops() here) into scratch the producer may
|
||||
// fill and forget; the apply loop's park predicate sees the latch and takes the ordinary
|
||||
// stop path; ServerMain's control loop sees the apply thread gone and ends the session.
|
||||
// The process exits 0 and the supervisor welcomes the next connection. The latch is
|
||||
// set, read and reset on the apply thread's side of Accept/Close only, and read with
|
||||
// acquire elsewhere (the control loop, tests).
|
||||
// Reverse-channel forfeit: a client that does not drain SEG_EVENT is the peer's fault and
|
||||
// must not abort this process. The first event that cannot be placed within
|
||||
// MOBILEGL_IPC_EVENT_WAIT_MS raises this session's latch (ForfeitReverseChannel logs
|
||||
// `ReverseChannelForfeit{<cause>}` once); that event and every later one is a counted drop
|
||||
// into scratch; the apply loop sees the latch and stops, and ServerMain ends the session
|
||||
// with status 0, not as a fault. The latch is written only on the apply thread (reset by
|
||||
// Accept) and read with acquire elsewhere. See ARCHITECTURE.md §11.7.
|
||||
Bool ReverseChannelForfeited() const {
|
||||
return m_reverseChannelForfeit.load(std::memory_order_acquire);
|
||||
}
|
||||
|
||||
@@ -77,34 +77,13 @@ namespace MobileGL::MG_Remote::Server {
|
||||
return std::string();
|
||||
}
|
||||
|
||||
// Every MOBILEGL_TRANSPORT and MOBILEGL_IPC_* goes. Built BEFORE fork:
|
||||
// between fork and execve only async-signal-safe calls are allowed, and
|
||||
// allocating a vector of strings is not one of them.
|
||||
//
|
||||
// EXCEPT A KNOB THE SERVER READS, named here one by one. P7 wave 4 M2's
|
||||
// MOBILEGL_IPC_WIRE_DEFERRED_MB bounds the server's own orphaned wire buffer stores;
|
||||
// nothing in the client reads it, so scrubbing it did not make the child safer - it made
|
||||
// the knob mean something under inproc and silently nothing under spawn, the worst of
|
||||
// the three states (the tcp server reads its supervisor's environment, as for every
|
||||
// knob). It names no endpoint, no role and no segment size, so neither anti-recursion
|
||||
// catch has anything to say about it.
|
||||
//
|
||||
// M2 round 2 (review): three more the server reads and that were silently defaulting in
|
||||
// the spawned child for the same reason - MOBILEGL_IPC_SPIN_US (the doorbell spin budget,
|
||||
// read by BOTH roles, so the child should spin as the parent was told to),
|
||||
// MOBILEGL_IPC_SERVER_AFFINITY (the apply thread's CPU mask, read only by the server) and
|
||||
// MOBILEGL_IPC_AUDIT (the server's 0xDD fill of retired stage bytes). Each is a tuning or
|
||||
// audit value, none names an endpoint, a role, a path or a segment size, and ServerMain's
|
||||
// catch (b) keeps verifying the four it verifies (TRANSPORT, SERVER_PATH, RING_MB,
|
||||
// STAGE_MB). Everything else under the prefix still goes.
|
||||
//
|
||||
// PH-6 (ID-P7-2) adds MOBILEGL_IPC_EVENT_WAIT_MS on the same argument: it is the server's
|
||||
// patience with a client that has stopped draining SEG_EVENT, nothing on the client reads
|
||||
// it, and scrubbing it would make a spawned server wait the default whatever the lane set.
|
||||
//
|
||||
// P11 B2 adds MOBILEGL_IPC_ALLOW_ADOPT_T0, the server's own T0 allow switch: only the server
|
||||
// reads it, and scrubbing it would make "allow switch off" unreachable on the spawn arm.
|
||||
// MOBILEGL_IPC_ADOPT_TIER itself still goes - the client's ask travels in its Hello.
|
||||
// Scrubs MOBILEGL_TRANSPORT and every MOBILEGL_IPC_* from the child's environment; built
|
||||
// before fork, because allocating is not async-signal-safe between fork and execve.
|
||||
// kServerOwned lists the exceptions, knobs the server itself reads (wire
|
||||
// deferred budget, spin budget, apply-thread affinity, stage audit fill, event wait, T0
|
||||
// allow switch): scrubbing them would silently default them under spawn. None names an
|
||||
// endpoint, role, path or segment size, so ServerMain's environment catch is unaffected.
|
||||
// MOBILEGL_IPC_ADOPT_TIER is scrubbed: the client's ask travels in its Hello.
|
||||
bool ShouldScrub(const char* entry) {
|
||||
static constexpr const char* kServerOwned[] = {
|
||||
"MOBILEGL_IPC_WIRE_DEFERRED_MB=", "MOBILEGL_IPC_SPIN_US=", "MOBILEGL_IPC_SERVER_AFFINITY=",
|
||||
@@ -149,26 +128,11 @@ namespace MobileGL::MG_Remote::Server {
|
||||
// §3.1 is the whole argument for why those are two axes.
|
||||
env.storage.emplace_back("MOBILEGL_IPC_ROLE=server");
|
||||
env.storage.emplace_back("MOBILEGL_IPC_DIAL=no");
|
||||
// LD_LIBRARY_PATH, BECAUSE THE SERVER IS EXEC'd AND NOT dlopen'd.
|
||||
//
|
||||
// It links libMobileGL.so, and an exec'd process gets a FRESH linker
|
||||
// namespace with the default search path - not the one the app built
|
||||
// for its own libraries. An APK's lib/<abi>/ is not on that path, and
|
||||
// the failure is total and immediate:
|
||||
//
|
||||
// CANNOT LINK EXECUTABLE ".../libMobileGLServer.so":
|
||||
// library "libMobileGL.so" not found: needed by main executable
|
||||
//
|
||||
// It is invisible on desktop, where CMake gives build-tree targets an
|
||||
// absolute RPATH of their own - so the WSL server had been resolving
|
||||
// its dependency through a path no phone has.
|
||||
//
|
||||
// $ORIGIN WOULD BE THE TIDIER ANSWER and the target asks for it, but
|
||||
// the NDK toolchain drops RPATH from the link: measured with readelf
|
||||
// on the APK's own copy, which carries NEEDED libMobileGL.so and no
|
||||
// RUNPATH at all. So the launcher states it instead - 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.
|
||||
// LD_LIBRARY_PATH: the server is exec'd, not dlopen'd, so the linker uses its default
|
||||
// search path, which lacks the APK's lib/<abi>/, and libMobileGL.so is not found.
|
||||
// Desktop builds hide this behind CMake's absolute build-tree RPATH. $ORIGIN would be
|
||||
// tidier, but the NDK link drops RPATH (the APK's copy has no RUNPATH), so the
|
||||
// launcher, which already resolved the image's directory, states it.
|
||||
if (!imageDir.empty()) {
|
||||
env.storage.emplace_back("LD_LIBRARY_PATH=" + imageDir);
|
||||
}
|
||||
|
||||
@@ -6,35 +6,14 @@
|
||||
// SPDX-License-Identifier: LGPL-3.0-only
|
||||
// End of Source File Header
|
||||
|
||||
// LAUNCHING a server process, and the process discipline around it.
|
||||
// Package `sm` (CONTRACT-P6.md §3).
|
||||
//
|
||||
// IT LAUNCHES; IT DOES NOT COUPLE. The two processes are independent: this
|
||||
// hands the child an endpoint NAME and nothing else - no inherited descriptors,
|
||||
// no shared memory, no handshake. The child listens on that name and the client
|
||||
// connects to it, exactly as it would to a server someone started by hand or
|
||||
// that an Android Service started minutes earlier.
|
||||
//
|
||||
// An earlier shape of this file forked the server and handed it fds 3..6.
|
||||
// Inheritance works and is less code, but it can only ever produce a server
|
||||
// that is a CHILD OF ITS CLIENT - which the end state cannot use, because there
|
||||
// the server is a standing application and the client is elsewhere, possibly on
|
||||
// another kernel. So fork/execve survives here only as A WAY TO START A
|
||||
// PROCESS, which is all it ever needed to be, and every fd it used to carry is
|
||||
// gone.
|
||||
//
|
||||
// ANTI-RECURSION IS STILL TWO INDEPENDENT CATCHES, and CONTRACT-P6 §3.1 is why
|
||||
// neither is the original ARCHITECTURE.md §15.1 rule. 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 of them in MG_Backend,
|
||||
// so obeying it flips the whole backend to frontend glue in the one process
|
||||
// with no frontend. Instead:
|
||||
// (a) STRUCTURAL: MOBILEGL_IPC_DIAL=no, a separate axis from which role the
|
||||
// process plays;
|
||||
// (b) ENVIRONMENTAL: MOBILEGL_TRANSPORT and every MOBILEGL_IPC_* removed
|
||||
// from the child's envp.
|
||||
// The child refuses with exit 64 for (a) and 65 for (b), so the two safeties
|
||||
// are distinguishable - two that cannot be told apart are one.
|
||||
// Launches a server process. The child gets an endpoint name and nothing else (no inherited
|
||||
// descriptors, no shared memory) and listens on it like a server started by hand or by an Android
|
||||
// Service, so a spawned server never depends on being its client's child.
|
||||
// Anti-recursion is two independent catches (ARCHITECTURE.md §15.1), not forcing Transport to
|
||||
// Monolith, which would turn off the server arms selected by `Transport != Monolith`:
|
||||
// (a) MOBILEGL_IPC_DIAL=no, separate from the process's role; (b) MOBILEGL_TRANSPORT and the
|
||||
// MOBILEGL_IPC_* knobs scrubbed from the child's environment. The child exits 64 for (a) and 65
|
||||
// for (b), so the two are distinguishable.
|
||||
|
||||
#pragma once
|
||||
|
||||
|
||||
@@ -6,30 +6,14 @@
|
||||
// SPDX-License-Identifier: LGPL-3.0-only
|
||||
// End of Source File Header
|
||||
|
||||
// P14 S2 (docs/Disaggregated/design/11-state-ownership.md): ONE SERVED SESSION'S PROCESS-LOCAL
|
||||
// STATE, and the routing that lets the rest of the tree keep spelling the singletons.
|
||||
//
|
||||
// WHAT THE SINGLETONS WERE. ServerSessionInstance()/ServerLoopInstance() were the session, so one
|
||||
// session per process was a property of every file that named them. This slice gives each served
|
||||
// session its own {ServerSession, ServerLoop, PipeInputs} triple, held here, and resolves the two
|
||||
// singleton accessors through the CALLING THREAD's session - which is what makes the ~900 sites
|
||||
// that spell gPipeInputs, gPipeInputs, ServerSession::Active() or ServerLoopInstance() find the right
|
||||
// one without one line of any of them moving.
|
||||
//
|
||||
// WHO IS A SESSION THREAD. Two threads per session, both created by the session itself:
|
||||
// * the CONTROL thread - ServerMain::RunSession's own thread, which reads the Hello, drives the
|
||||
// blocking control pump and ends the session (a std::thread per session in the supervisors, a
|
||||
// forked process in the `--serve` worker shape);
|
||||
// * the APPLY thread - ServerLoop's mgl-srv-apply, which applies the ring and owns the backend.
|
||||
// ThreadSessionScope is installed on both, first thing. A thread with no scope resolves to the
|
||||
// process-wide defaults, which is exactly the old behaviour and is what the CLIENT process, the
|
||||
// inproc one-process client+server shape and every unit case keep getting.
|
||||
//
|
||||
// THE INPROC CLIENT+SERVER SHAPE IS DELIBERATELY UNTOUCHED. ClientSession::Start calls
|
||||
// ServerLoopInstance().Start(ServerSessionInstance()) and never opens a scope, so its applier and
|
||||
// its app thread still share the one process-wide PipeInputs block - the verb barrier's premise
|
||||
// (one block two roles alternate on) is a property of that shape and this file must not break it.
|
||||
// Only ServerMain::RunSession, which serves a session with its own transport, opens a scope.
|
||||
// One served session's process-local state ({ServerSession, ServerLoop, PipeInputs}) and the
|
||||
// per-thread routing behind the singletons: on a thread inside a ThreadSessionScope,
|
||||
// ServerSessionInstance(), ServerLoopInstance() and gPipeInputs resolve to that thread's session;
|
||||
// elsewhere they resolve to the process-wide defaults. ServerMain::RunSession opens the scope on
|
||||
// its control thread and ServerLoop on the session's apply thread. The in-process client+server
|
||||
// shape (ClientSession::Start) opens none, so its app thread and applier keep sharing the one
|
||||
// PipeInputs block the verb barrier relies on; keep it that way.
|
||||
// See docs/Disaggregated/design/11-state-ownership.md.
|
||||
|
||||
#pragma once
|
||||
#include <Includes.h>
|
||||
|
||||
@@ -6,34 +6,14 @@
|
||||
// SPDX-License-Identifier: LGPL-3.0-only
|
||||
// End of Source File Header
|
||||
|
||||
// P5f, package fc: the EGL/surface control plane, framed.
|
||||
//
|
||||
// WHAT THIS REPLACES. The twelve Server* forwarders used to cross to the apply thread through a
|
||||
// one-slot mailbox carrying a raw FUNCTION POINTER plus a void* to a stack-local Args struct
|
||||
// (P5c audit row G4). Both halves are meaningless across a process boundary, which is the whole
|
||||
// reason P5f exists. The frame below is the seam f0-egl's census prescribed: every forwarder's
|
||||
// arguments converge into one pure-value struct; inproc the struct crosses the (retained,
|
||||
// blocking, one-slot) channel by value; under spawn the SAME struct is what SurfaceOpCodec
|
||||
// encodes into a Wire::SurfaceOp. The thread model does not move - only the payload's shape.
|
||||
//
|
||||
// THE FRAME CARRIES NO POINTERS, and that is enforced by the exhaustive member check below:
|
||||
// adding a member requires updating its structured binding; pointer types fail the assertion.
|
||||
// The three places the old Args structs held client addresses map onto values:
|
||||
//
|
||||
// ServerInitializeEGLDisplay's major/minor out-pointers -> the reply fields eglMajor/eglMinor;
|
||||
// ServerCreateEGLWindowSurface / ServerSetWindowHandle's const WindowHandle* -> windowBackend +
|
||||
// nativeToken + width/height (WindowHandle::Handle as an integer);
|
||||
// every EGL handle (display/surface/context) -> a Uint64 token. Inproc the token IS the handle
|
||||
// value bit-cast (same process, same driver, and the N-3 tuple bookkeeping compares them);
|
||||
// under spawn the client mints dense tokens instead (P6-CONTRACT-DRAFT table 0) - the field
|
||||
// width is already the token's, so nothing here changes shape on that day.
|
||||
//
|
||||
// PROCESS-LOCAL WINDOW OBJECTS ARE REFUSED BY NAME on the wire: ANativeWindow* and
|
||||
// CAMetalLayer* mean nothing in the server process. SurfaceOpCodec names their refusals
|
||||
// AndroidNativeWindow:use-MOBILEGL_IPC_SURFACE=server and MetalLayer:use-MOBILEGL_IPC_SURFACE=server,
|
||||
// and they are permanent (Rule H): a client's window never crosses, a windowed client uses
|
||||
// MOBILEGL_IPC_SURFACE=server, which gives the SERVER a window of its own (kServerOwnedWindowBackend
|
||||
// below, WindowKind::ServerOwned on the wire).
|
||||
// The EGL/surface control plane as a value frame. Every Server* forwarder packs its arguments
|
||||
// into one SurfaceControlFrame: inproc it crosses the blocking one-slot channel to the apply
|
||||
// thread by value, and under spawn SurfaceOpCodec encodes the same struct as a Wire::SurfaceOp.
|
||||
// The frame holds no pointers (the exhaustive member check below enforces it): out-pointers
|
||||
// become reply fields, a WindowHandle becomes windowBackend + nativeToken + size, and EGL
|
||||
// handles travel as Uint64 tokens (inproc, the handle value itself). Process-local windows
|
||||
// (ANativeWindow*, CAMetalLayer*) never cross: SurfaceOpCodec refuses them by name, and a
|
||||
// windowed client uses MOBILEGL_IPC_SURFACE=server (kServerOwnedWindowBackend).
|
||||
|
||||
#pragma once
|
||||
#include <Includes.h>
|
||||
|
||||
Reference in New Issue
Block a user