[Feature] (P14): state ownership - multi-session, multi-context, share groups

Breaks the one process = one server = one session = one context equation
that the whole stack's correctness used to rest on. Design and per-slice
shape: docs/Disaggregated/design/11-state-ownership.md.

S1 wire: bind_context ring record (opcode 84) announces the current
context at the make-current edge; CreateContext/DestroyContext join the
SurfaceOp control frames; control revision 5 -> 6; the server keeps a
per-session token table and refuses unknown tokens by name.

S2 server: SessionRuntime per session with thread-scoped resolution
(singletons become fallbacks), per-thread gPipeInputs, per-session latch
domains, per-thread segment resolvers; the in-process unix supervisor
serves up to MOBILEGL_IPC_INPROC_MAX_SESSIONS (16) concurrent sessions;
surface mode is declared per session and the display lease refuses a
second on-screen session by name.

S3 frontend: ShareGroupState owns the shared object stores and name
generators (buffer/texture/renderbuffer/sampler/program), GLContext keeps
per-context bindings/errors/container objects; pGLContext becomes
thread-local with a process default context preserving the single-context
world verbatim; eglCreateContext builds a real GLContext and joins the
sharing context's group.

S4 backend: native EGL tuples keyed by (session, context token);
InitDisplayAndContext's unconditional teardown is gone - creating a
second context or surface no longer destroys the first; eglCreateContext
sharing is wired to the native driver; bind_context is the native switch
point.

S5 applier: MGPipeApplierState splits into MGPipeObjectRecords (per
share group) and MGPipeWorkingState (per context), resolved through a
{session, token} registry with a thread-local cached fast path.

Tests: MultiSessionTest (incl. two sessions x two contexts interleaved
with real clear/readback witnesses), ApplierOwnershipTest (with a
null-resolver negative control), ContextStateOwnershipTest,
ServerLoopEglTest native-context liveness; 99/99 of the acceptance set
green on the host build.

Known debts (documented in the design doc): twin registries still keyed
by handle alone, no per-record ContextSlot, process-global backend
generations, MakeCurrent dedup per current binding.
This commit is contained in:
2026-10-01 19:16:41 -04:00
parent ebc552a048
commit 4ed1c9cef2
80 changed files with 4677 additions and 949 deletions
+47
View File
@@ -1462,6 +1462,53 @@ namespace MobileGL::MG_Remote::Server {
return true;
}
// P14 S1. THE RING'S DOOR INTO THE SESSION'S CONTEXT TABLE.
//
// The record carries the client's current context token and this is where a session's
// attribution moves. It is deliberately NOT an assertion like OnApplierReset's serial: the
// client's EGL layer mints the token and the server has no second count to compare against,
// so what is checked is a FACT ABOUT THIS SESSION'S OWN TABLE - a token that CreateContext
// never created is corruption, not a late record. Token 0 is the release edge and is always
// legal (a session whose client released its context has no context, which is exactly the
// value a session that never bound one already answers).
Bool ServerVerbSink::OnBindContext(const MG_Pipe::MGPBindContext& bind) {
// NO SESSION IS A DECLINE, NOT A FAULT, and it is the one case here that a peer's bytes
// cannot cause: a bind is answered by the session's own table, so with no accepted
// session there is nothing to attribute the record to and nothing to refuse. (The window
// is Close() clearing the active session while the apply thread is still draining.)
ServerSession* session = ServerSession::Active();
if (session == nullptr) return false;
// PH-1 (3): the refusal latches in an armed session child (the peer wrote the token);
// unarmed it dies, like every other contract fact about a peer.
if (!session->BindContext(bind.ClientContextToken)) {
return SessionLatch(MGFatalFamily::ProtocolCorruption, "MGPipe: Fatal{ProtocolCorruption, \"BindContext.ClientContextToken\"} - the "
"record binds token %llu, which this session never created; a bind_context "
"names a context CreateContext put in the session's table, and 0 (the "
"release) is the only token that needs no entry",
static_cast<unsigned long long>(bind.ClientContextToken));
}
++m_bindContexts;
#if MOBILEGL_BUILD_DISAGGREGATED
// P14 S4 (docs/Disaggregated/design/11-state-ownership.md). THE NATIVE HALF OF THE SWITCH.
//
// `bind_context` is where the session's context attribution moves, and it is also the ONLY
// point at which the apply thread's native context may move: the MakeCurrent control frame
// that precedes it still carries the OLD context (the client emits the binding after the
// binding has taken effect, which is the ordering S1 chose on purpose), so a native switch
// driven from there would bind the context the client just left. Frontend GL state is the
// backend's per-tuple business; this call makes the tuple the resolver now names current.
//
// It is a no-op for the shapes S4 did not change: with no resolver installed (monolith, a
// unit case, the inproc one-process shape) the key is {0,0}, and the single-context world's
// bind does not move the native context - MakeNativeContextCurrentForBoundToken returns
// without a driver call when the context it resolves to is already the one bound here.
if (MG_Config::Transport != MG_Config::TransportMode::Monolith) {
(void)MG_Backend::DirectGLES::MakeNativeContextCurrentForBoundToken();
}
#endif
return true;
}
Bool ServerVerbSink::OnObjectDeath(const MG_Pipe::MGPHandleOnly& death) {
// §1's zero ruling: a null handle means "the object never crossed", and the client
// emits NOTHING in that case (§5.2) - so a null handle arriving here is corruption,
+15
View File
@@ -245,11 +245,21 @@ namespace MobileGL::MG_Remote::Server {
Bool OnApplierReset(const MG_Pipe::MGPApplierReset& reset) override;
Bool OnObjectDeath(const MG_Pipe::MGPHandleOnly& death) override;
// ---- P14 S1 (docs/Disaggregated/design/11-state-ownership.md): bind_context, opcode 84.
//
// The session's current context token becomes the record's, on the apply thread. Unlike
// OnApplierReset's serial the token is NOT an assertion about a count the two ends both
// hold - the client mints it and the server keeps the table CreateContext built - so the
// refusal here is "this session never created that token", a named ProtocolCorruption
// rather than a silent bind. Token 0 (the release) is always legal.
Bool OnBindContext(const MG_Pipe::MGPBindContext& bind) override;
// P5c ct's tallies, for the same reason every other row's tally exists (R-16: a probe
// may not arm against a stub). ApplierResets counts the records ACCEPTED (serial
// checked, reset run); ObjectDeaths counts every record the sink dispatched.
Uint64 ApplierResets() const { return m_applierResets; }
Uint64 ObjectDeaths() const { return m_objectDeaths; }
Uint64 BindContexts() const { return m_bindContexts; }
// The ContextSerial the NEXT applier_reset record must carry. Exposed so a case can
// assert the sequence rather than only the count.
Uint64 ExpectedApplierResetSerial() const { return m_applierResetSerial; }
@@ -377,6 +387,11 @@ namespace MobileGL::MG_Remote::Server {
Uint64 m_applierResetSerial = 0;
Uint64 m_applierResets = 0;
Uint64 m_objectDeaths = 0;
// P14 S1. BindContexts counts the records the sink dispatched and bound on the session;
// the token itself lives on the session (ServerSession::CurrentContextToken), which is
// the object the control plane's CreateContext/DestroyContext also own - one table, one
// owner, and the sink is only the ring's door into it.
Uint64 m_bindContexts = 0;
// ReadPixels' destination. The pixels go into the reply slot, but GLFunctionsTable::
// ReadPixels writes into a caller buffer, so one staging vector per session sits
// between them. Grown, never shrunk, and never handed out past the call.
+4 -1
View File
@@ -82,7 +82,10 @@ namespace MobileGL::MG_Remote::Server {
NoWindow, // a display, but no window was attached within the wait
Cancelled, // the caller's cancel predicate said so
Interrupted, // Interrupt() (the in-process server is stopping)
LeasedElsewhere, // another holder has the window (sessions are sequential: a bug if seen)
// P14 S2: NOT A BUG ANY MORE. Several sessions share one process and the display's window
// is one window, so a second ON-SCREEN session asking for it is refused by name here
// (ServerLoop logs the holder); offscreen sessions take no lease and are unaffected.
LeasedElsewhere, // another session in this process holds the window: see the note above
};
enum class ServerWindowDetach : Uint8 {
+113 -10
View File
@@ -10,12 +10,14 @@
#include "ServerLoop.h"
#include "ApplyThreadPolicy.h"
#include "SessionRuntime.h"
#include <MG_Remote/FatalFunnel.h>
#include <MG_Remote/Transport/LinkMetrics.h>
#include <MG_Backend/MGPipe/PipeInputs.h>
#include <Config.h>
#include <MG_Backend/BackendObjects.h>
#include <MG_Backend/DirectGLES/DirectGLES.h>
#include <MG_Util/Debug/Log.h>
#include <MG_Util/Metrics/PipeStats.h>
@@ -284,6 +286,8 @@ namespace MobileGL::MG_Remote::Server {
m_haveCurrentTuple = false;
// P12 (D4, D6): a new session decides its own surface mode, holds no window lease yet and
// has no window-lost request pending. The apply thread that reads these is not started yet.
// P14 S2: and it is THIS session's latch - the loop is the session's, so a second session
// in the same process starts here too and neither's first surface decides the other's.
m_surfaceMode = SessionSurfaceMode::None;
m_holdsWindowLease = false;
m_serverOwnedSurfaces.clear();
@@ -345,6 +349,11 @@ namespace MobileGL::MG_Remote::Server {
// Apply thread only (RunSurfaceControlFrame's dispatch put us here), so
// m_haveCurrentTuple/m_cur* need no
// lock. The counters are atomic for the reader on the test thread.
//
// P14 S4 left this classification alone on purpose - ServerLoop.h states the argument (the
// currently bound tuple IS the unit ID-67 is about, and only one EGLContext can be current on
// this thread). What S4 changed is one layer down: the tuple now names the (session, context)
// registry's native context instead of the process's one.
MakeCurrentOutcome outcome;
const EglBindAction action = ClassifyEglMakeCurrent(m_haveCurrentTuple, m_curDpy, m_curDraw,
m_curRead, m_curCtx, dpy, draw, read, ctx);
@@ -409,9 +418,18 @@ namespace MobileGL::MG_Remote::Server {
// THE IDENTITY IS PUBLISHED FIRST, BEFORE THE THREAD HAS A NAME OR AN AFFINITY. Every
// role guard in the tree reads it, and the very first record this thread applies must
// already answer "yes" to OnApplyThread() - otherwise the applier's own reads would
// look like client reads to the guards. Relaxed for the reason stated beside the key's
// declaration: it is an identity, not a handshake, and this thread is the only writer.
Detail::g_applyThreadKey.store(Detail::CurrentThreadKey(), std::memory_order_relaxed);
// look like client reads to the guards.
//
// P14 S2: two words, both about THIS thread. t_onApplyThread is the guard's answer; the
// process counter beside it is what MG_Backend/DirectGLES/Managers.cpp reads as "an apply
// thread is running" (ServerLoop.h's block). The scope is opened BEFORE either, because
// every read below - the session's peer, its rings, the applier it attaches - must already
// resolve to this session rather than to the process's default.
ServerSession& session = *m_session;
std::unique_ptr<Detail::ThreadSessionScope> scope;
if (m_runtime != nullptr) scope = std::make_unique<Detail::ThreadSessionScope>(*m_runtime);
Detail::t_onApplyThread = true;
Detail::g_applyThreadKey.fetch_add(1, std::memory_order_relaxed);
NameThisThread("mgl-srv-apply");
// P6: THIS THREAD IS THE SERVER, and saying so is what sends its lines to the server's
// own log. Under spawn the process role already answers this; under INPROC it is the
@@ -426,7 +444,6 @@ namespace MobileGL::MG_Remote::Server {
// "an affinity that silently did nothing looks exactly like one that worked"
// (CONTRACT-P5 5). P11 B1: `auto` now depends on who the client is (ApplyThreadPolicy.h),
// and so does the spin before each park.
ServerSession& session = *m_session;
const char* raw = AffinityStringFromConfig();
const Bool automatic = raw == nullptr || raw[0] == '\0' || std::strcmp(raw, "auto") == 0;
Uint64 bigCores = 0, primeCores = 0;
@@ -691,7 +708,12 @@ namespace MobileGL::MG_Remote::Server {
// thread could ever give. The integration lane - a real EGL teardown - is the only
// thing that would catch that, and it would catch it as a hang, not as a failed
// assertion.
Detail::g_applyThreadKey.store(0, std::memory_order_relaxed);
//
// P14 S2: the guard's own word is lowered here too, and for the same reason - with
// N sessions it can only ever have been this thread's, and the thread is about to
// stop being an apply thread. The scope is destroyed by this function's frame.
Detail::t_onApplyThread = false;
Detail::g_applyThreadKey.fetch_sub(1, std::memory_order_relaxed);
}
m_controlDone.notify_all();
@@ -1189,6 +1211,10 @@ namespace MobileGL::MG_Remote::Server {
}
ServerLoop& ServerLoopInstance() {
// P14 S2: the session of the CALLING THREAD, else the process's one instance. The client
// process (the forwarders, whose sink makes them cross the wire), the inproc one-process
// client+server shape and every unit case have no thread session and keep this instance.
if (ServerLoop* const own = Detail::CurrentLoop()) return *own;
// ID-8: leak at exit, like every MG_Remote singleton.
static ServerLoop& instance = *new ServerLoop{};
return instance;
@@ -1360,7 +1386,9 @@ namespace MobileGL::MG_Remote::Server {
return MOBILEGL_OK;
case SurfaceControlOp::CreatePbufferSurface:
// P12 (D4): a pbuffer in a session that went on-screen is the other mode, refused by
// name and not latched - the session and its window surface carry on.
// name and not latched - the session and its window surface carry on. P14 S2: the mode
// is the session's own - latched by its first surface, on its own loop - and never
// another session's.
if (!SessionSurfaceModeAdmits(m_surfaceMode, /*serverOwnedWindow=*/false)) {
frame.ok = false;
frame.refusal = static_cast<Uint8>(SurfaceRefusalCode::SurfaceModeMismatch);
@@ -1437,6 +1465,48 @@ namespace MobileGL::MG_Remote::Server {
frame.ok = outcome.ok;
return MOBILEGL_OK;
}
case SurfaceControlOp::CreateContext: {
// P14 S1 built the session's table entry; P14 S4 gives it its NATIVE context. The
// share group is what makes two client contexts see one set of buffer/texture objects:
// a group whose leader already has a native EGLContext hands it to eglCreateContext as
// the share argument, so this arm is the whole of "server-side sharing".
//
// An `ok = false` here is a named refusal the client's eglCreateContext turns into
// EGL_NO_CONTEXT, which is what a server that declined to table the token must produce -
// a token the server never heard of is worse than no context at all. A native context
// that could not be built rolls the table entry back, or the session would hold a token
// whose every MakeCurrent fails one layer down.
ServerSession* session = ServerSession::Active();
if (session == nullptr) {
frame.ok = false;
return MOBILEGL_ERR_NOT_INITIALIZED;
}
frame.ok = session->CreateContext(frame.context, frame.shareGroupToken, frame.contextFlags);
if (frame.ok && backend != nullptr &&
backend->GetBackendType() == BackendType::DirectGLES) {
if (!MG_Backend::DirectGLES::CreateNativeContextFor(frame.context, frame.shareGroupToken)) {
(void)session->DestroyContext(frame.context);
frame.ok = false;
}
}
return MOBILEGL_OK;
}
case SurfaceControlOp::DestroyContext: {
ServerSession* session = ServerSession::Active();
if (session == nullptr) {
frame.ok = false;
return MOBILEGL_ERR_NOT_INITIALIZED;
}
frame.ok = session->DestroyContext(frame.context);
// P14 S4: the native context goes with the entry, and ONLY that one - the session's
// other contexts, and every other session's, are untouched. The display is terminated
// only when the last native context in the process has gone.
if (frame.ok && backend != nullptr &&
backend->GetBackendType() == BackendType::DirectGLES) {
MG_Backend::DirectGLES::DestroyNativeContextFor(frame.context);
}
return MOBILEGL_OK;
}
case SurfaceControlOp::SetSwapInterval:
backend->SetEGLSwapInterval(frame.swapInterval);
frame.ok = true;
@@ -1590,10 +1660,17 @@ namespace MobileGL::MG_Remote::Server {
break;
}
if (refusal != nullptr) *refusal = SurfaceRefusalCode::NoServerWindow;
// P14 S2: LeasedElsewhere IS NOT A BUG ANY MORE. The display's window has one holder at a
// time and a session per holder, so a second ON-SCREEN session asking for it is refused -
// by name, not latched, exactly as a display with no window up. Offscreen (pbuffer)
// sessions take no lease at all and are unaffected.
MGLOG_E("MG_Remote server: Refuse ServerOwned: this server owns a display but no window for a %ux%u surface "
"(%s after at most %u ms) - the display's surface is not up. Refused (NoServerWindow); the "
"session is not latched",
width, height, ServerWindowAcquireName(acquired), timeoutMs);
"(%s after at most %u ms)%s. Refused (NoServerWindow); the session is not latched",
width, height, ServerWindowAcquireName(acquired), timeoutMs,
acquired == ServerWindowAcquire::LeasedElsewhere
? " - the server's window is leased by another session, and one on-screen session at a time is "
"the display's own rule"
: " - the display's surface is not up");
return MOBILEGL_ERR_TIMEOUT;
}
@@ -1603,7 +1680,9 @@ namespace MobileGL::MG_Remote::Server {
frame.refusal = static_cast<Uint8>(SurfaceRefusalCode::None);
const Uint32 wantWidth = frame.width > 0 ? static_cast<Uint32>(frame.width) : 0u;
const Uint32 wantHeight = frame.height > 0 ? static_cast<Uint32>(frame.height) : 0u;
// D4 FIRST: an offscreen session may not go on-screen, display or no display.
// D4 FIRST: an offscreen session may not go on-screen, display or no display. P14 S2: the
// refusal is against THIS session's own latch - a second on-screen session in the same
// process is a different refusal (no free window), never a mode mismatch.
if (!SessionSurfaceModeAdmits(m_surfaceMode, /*serverOwnedWindow=*/true)) {
frame.refusal = static_cast<Uint8>(SurfaceRefusalCode::SurfaceModeMismatch);
MGLOG_E("MG_Remote server: SurfaceModeMismatch - a ServerOwned CreateWindowSurface (seq %llu, %ux%u) in a "
@@ -1824,6 +1903,30 @@ namespace MobileGL::MG_Remote::Server {
return rc == MOBILEGL_OK && frame.ok;
}
// P14 S1. A context creation is a frame like any other: `context` IS the client token (the
// schema's field, not a bit-cast handle - a context has no handle the server could name),
// `shareGroupToken` and `contextFlags` the two values CreateContext adds to it. Same blocking
// handshake, so eglCreateContext cannot return a token the server has not tabled - which is
// what keeps bind_context's "this session never created that token" refusal unreachable on
// the well-behaved path.
Bool ServerCreateEGLContext(Uint64 clientContextToken, Uint64 shareGroupToken, Uint32 flags) {
SurfaceControlFrame frame;
frame.kind = SurfaceControlOp::CreateContext;
frame.context = clientContextToken;
frame.shareGroupToken = shareGroupToken;
frame.contextFlags = flags;
const MobileGLResult rc = ServerLoopInstance().RunSurfaceControlFrame(frame);
return rc == MOBILEGL_OK && frame.ok;
}
Bool ServerDestroyEGLContext(Uint64 clientContextToken) {
SurfaceControlFrame frame;
frame.kind = SurfaceControlOp::DestroyContext;
frame.context = clientContextToken;
const MobileGLResult rc = ServerLoopInstance().RunSurfaceControlFrame(frame);
return rc == MOBILEGL_OK && frame.ok;
}
Bool ServerSwapEGLBuffers(EGLDisplay dpy, EGLSurface draw) {
SurfaceControlFrame frame;
frame.kind = SurfaceControlOp::SwapBuffersInprocOnly;
+84 -79
View File
@@ -112,81 +112,44 @@ namespace MobileGL::MG_Remote::Server {
// 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.
namespace Detail {
// RELAXED ON BOTH SIDES, and that is a claim about recycling, not a shrug. The only
// dangerous outcome would be a NEW thread that reuses the exited apply thread's TLS
// block (hence its thread pointer) while still reading the pre-clear key. It cannot
// happen: the clear is sequenced before the apply thread's exit, the exit releases the
// TLS block under libc's own lock, and the thread that later receives that block takes
// the same lock - so the clear happens-before any load the new thread performs, and
// coherence forbids a relaxed load from reading a value that a happens-before store
// overwrote. A stale ZERO is harmless in the other direction: a thread that is not the
// apply thread wants "false" anyway, and the apply thread always reads its own store.
//
// No acquire is needed for a second reason: this is an IDENTITY, not a handshake. No
// caller publishes data through it; the real ordering lives in the ring, the doorbell
// and m_controlMutex.
inline std::atomic<Uint64> g_applyThreadKey{0};
// 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 -
// starts out answering false and can only become the apply thread by running
// ApplyThreadMain. There is no stale value to read and nothing to order.
inline thread_local Bool t_onApplyThread = false;
// The calling thread's identity as the same integer. aarch64 - the split's only
// measured target - reads TPIDR_EL0 with a single instruction and no call. Everywhere
// else falls back to std::this_thread::get_id() memcpy'd into the key: still one libc
// call, but the atomic<thread::id> load and the out-of-line pthread_equal that
// dominated the old body are gone either way. x86_64 is deliberately NOT on the
// builtin path - __builtin_thread_pointer only grew x86 support in clang 17 / GCC 11
// and older toolchains accept __has_builtin for it and then fail in codegen, which is
// a build break on the desktop ctest lane for a target whose frame rate nobody
// measures.
//
// A LIVE THREAD'S KEY IS NEVER 0 on either path (a thread pointer is a real TLS
// address; std::this_thread::get_id() on a running thread is never the
// default-constructed id, whose object representation is the all-zero one on every
// library in scope), which is what lets 0 mean "nobody".
//
// THE SELECTOR IS A BUILD KNOB, NOT A HEADER SECRET (review round 3). This header is
// pulled into MG_State, MG_Impl and MG_Test translation units now, so the name carries
// the MOBILEGL_DETAIL_ prefix to read as internal, it is #ifndef-guarded so a toolchain
// whose __has_builtin(__builtin_thread_pointer) answers 1 and then fails in codegen can
// be steered off the path with -DMOBILEGL_DETAIL_APPLY_THREAD_POINTER=0 instead of a
// header edit, and it is always DEFINED - to 0 when unavailable - and tested with #if
// rather than #ifdef, so that a -D...=0 really disables it instead of being ignored.
#ifndef MOBILEGL_DETAIL_APPLY_THREAD_POINTER
#if defined(__aarch64__) && defined(__has_builtin)
#if __has_builtin(__builtin_thread_pointer)
#define MOBILEGL_DETAIL_APPLY_THREAD_POINTER 1
#endif
#endif
#endif
#ifndef MOBILEGL_DETAIL_APPLY_THREAD_POINTER
#define MOBILEGL_DETAIL_APPLY_THREAD_POINTER 0
#endif
inline Uint64 CurrentThreadKey() {
#if MOBILEGL_DETAIL_APPLY_THREAD_POINTER
return static_cast<Uint64>(reinterpret_cast<std::uintptr_t>(__builtin_thread_pointer()));
#else
const std::thread::id id = std::this_thread::get_id();
static_assert(sizeof(std::thread::id) <= sizeof(Uint64),
"std::thread::id does not fit the apply-thread key; this fallback has "
"to hash rather than copy on that platform");
// AND IT MUST HAVE NO PADDING (review round 3). Copying the OBJECT REPRESENTATION of
// a type that has padding bytes would let two calls ON THE SAME THREAD return
// different keys, and OnApplyThread() would then answer FALSE ON THE APPLY THREAD -
// a role guard that has stopped guarding, which is the one direction CONTRACT-P5C
// rule E says a guard may never fail in (RunSurfaceControlFrame would also lose its
// re-entrancy shortcut and the EGL teardown post would deadlock on m_controlDone).
// Every library this fallback is built against today wraps a single scalar
// (libstdc++ __gthread_t, libc++ __libcpp_thread_id, MSVC unsigned int) and
// satisfies this; one that did not is a BUILD ERROR here rather than a silently
// dead guard at run time.
static_assert(std::has_unique_object_representations_v<std::thread::id>,
"std::thread::id has padding on this platform: copying its object "
"representation would make the apply-thread key unstable within one "
"thread. Hash the id (std::hash<std::thread::id>) instead.");
Uint64 key = 0;
std::memcpy(&key, &id, sizeof(id));
return key;
#endif
}
// The count of live apply threads, as a relaxed atomic: an identity-like gauge, not a
// handshake (the real ordering lives in the ring, the doorbell and m_controlMutex), and
// its one reader wants "is it zero".
inline std::atomic<Uint64> g_applyThreadKey{0};
} // namespace Detail
// ---------------------------------------------------------------------------------
@@ -200,11 +163,26 @@ namespace MobileGL::MG_Remote::Server {
// 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).
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.
Bool SessionSurfaceModeAdmits(SessionSurfaceMode current, Bool serverOwnedWindow);
// P14 S2 (SessionRuntime.h): WHICH SESSION THIS LOOP IS, when it is one of several served by
// the process. Set by ServerMain::RunSession before Start(); null for every other shape (the
// inproc one-process client+server, a unit case), which is what keeps those byte-for-byte.
class SessionRuntime;
class ServerLoop {
public:
// Creates the apply thread, names it mgl-srv-apply, applies
@@ -214,6 +192,11 @@ namespace MobileGL::MG_Remote::Server {
// landing on fast cores.
MobileGLResult Start(ServerSession& session);
// P14 S2. The session this loop belongs to, so its apply thread can open the same thread
// scope the control thread has (session/loop/inputs/latch domain/segment resolver).
void SetRuntime(SessionRuntime& runtime) { m_runtime = &runtime; }
SessionRuntime* Runtime() const { return m_runtime; }
// Kill the doorbell, join the thread (bounded), then destroy the private backend object
// ON THAT THREAD before it exits. Blocking by contract - see the header note.
void Stop();
@@ -327,11 +310,9 @@ namespace MobileGL::MG_Remote::Server {
// or more per draw, so the call itself - a cross-library PLT hop - was a measurable
// share of the cost of the answer.
static Bool OnApplyThread() {
const Uint64 key = Detail::g_applyThreadKey.load(std::memory_order_relaxed);
// Short-circuit ON PURPOSE: with TransportMode::Monolith, and in every process
// before Start() and after Stop(), the key is 0 and the caller pays one relaxed
// load and one branch - it never even reads its own identity.
return key != 0 && key == Detail::CurrentThreadKey();
// P14 S2: the caller's own TLS word. One constant-initialized load, no atomic, no
// comparison and - unlike the process-wide key - the right answer with N sessions.
return Detail::t_onApplyThread;
}
// The CPU mask MOBILEGL_IPC_SERVER_AFFINITY resolved to and sched_setaffinity accepted.
@@ -476,8 +457,11 @@ namespace MobileGL::MG_Remote::Server {
static void ServerWindowLostThunk(void* self);
// AcquireFor's cancel predicate: the loop is stopping, or the session latched.
static Bool ServerWindowWaitCancelled(void* self);
// D4: latched at the session's first successful surface creation; reset by Start().
// D4: latched at the session's first successful surface creation; reset by Start(). Per
// session, because the loop is (P14 S2).
SessionSurfaceMode m_surfaceMode = SessionSurfaceMode::None;
// P14 S2: the session this loop serves, when the process serves several; see SetRuntime.
SessionRuntime* m_runtime = nullptr;
// Apply thread only: this loop holds the display's lease.
Bool m_holdsWindowLease = false;
// Set by ServerWindowLostThunk (any thread), taken by the apply thread. Part of the park
@@ -576,6 +560,18 @@ namespace MobileGL::MG_Remote::Server {
// C7 / ID-54: the (dpy, draw, read, ctx) currently bound on the apply thread. Written and
// read ONLY on the apply thread inside ApplyMakeCurrent, so it needs no lock; the two
// counters beside it are atomic because a test reads them from another thread.
//
// P14 S4 LOOKED AT MAKING THIS A PER-CONTEXT TABLE AND DID NOT, with the reason recorded
// here rather than in a review thread: ID-67's pinned control
// (ServerLoopEglTest.ADifferentTupleBindsNativelyAndRepublishesAnIdenticalRepeatDoesNeither)
// defines "a different tuple" as a change of the CURRENTLY BOUND tuple, and asserts that
// A -> B -> A costs three native binds. A table that remembered each context's tuple would
// make the third one a RepeatNoOp - and it would be wrong for a real reason, not just for
// the assertion: only ONE EGLContext can be current on the apply thread, so coming back to A
// really does have to run the driver call that DirectGLES' seven frontend-context
// invalidations hang off. "Each context holds its own native triple" is satisfied by the
// backend's per-(session, token) registry; the dedup here is about the thread's CURRENT
// binding and stays one tuple.
Bool m_haveCurrentTuple = false;
EGLDisplay m_curDpy = EGL_NO_DISPLAY;
EGLSurface m_curDraw = EGL_NO_SURFACE;
@@ -668,6 +664,15 @@ namespace MobileGL::MG_Remote::Server {
// and a SECOND arrival IS the invalidation signal, which is how DirectGLES, which has no
// OnCapsInvalidated producer at all, tells the client without a dev-shaped backend edit.
Bool ServerMakeEGLCurrent(EGLDisplay dpy, EGLSurface draw, EGLSurface read, EGLContext ctx);
// P14 S1 (docs/Disaggregated/design/11-state-ownership.md). The EGL CONTEXT LIFECYCLE's two
// frames, on the same channel and with the same blocking handshake as the twelve above.
// `clientContextToken` is the token EGLState minted for the new context (never 0), and
// `shareGroupToken` the group it joins - the sharing context's group, or a fresh one.
// S1 creates a PLACEHOLDER server-side runtime: the token enters the session's table and
// nothing native is built (S4 is what gives the entry a native context). DestroyContext
// drops the entry and unbinds it if it was the current one.
Bool ServerCreateEGLContext(Uint64 clientContextToken, Uint64 shareGroupToken, Uint32 flags);
Bool ServerDestroyEGLContext(Uint64 clientContextToken);
Bool ServerSwapEGLBuffers(EGLDisplay dpy, EGLSurface draw);
void ServerSetEGLSwapInterval(Int interval);
void ServerReleaseEGLSurface(EGLSurface surface);
+116 -55
View File
@@ -14,6 +14,7 @@
#include "ServerDisplay.h"
#include "ServerLoop.h"
#include "ServerSession.h"
#include "SessionRuntime.h"
#include "SurfaceControlFrame.h"
#include <Config.h>
#include <Init.h>
@@ -343,7 +344,7 @@ std::atomic<int> g_inProcessBackendPin{-1};
// in the disaggregated server, does nothing unless set, and says so when it is.
void DelaySessionHandshakeForTest() {
const char* text = std::getenv("MOBILEGL_TEST_DELAY_SESSION_HANDSHAKE_MS");
if (text == nullptr || *text == '\0') return;
if (text == nullptr || text[0] == 0) return;
const long ms = std::strtol(text, nullptr, 10);
if (ms <= 0) return;
WireLogError("MG_Remote server: pid=%d MOBILEGL_TEST_DELAY_SESSION_HANDSHAKE_MS=%ld - this session child "
@@ -468,14 +469,25 @@ int RunSession(std::unique_ptr<SocketTransport> control, std::vector<std::uint8_
// 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;
// its supervisor resets it between sessions (ResetSessionLatch), so a session that latched does
// not decline the next one.
// 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).
auto runtime = std::make_unique<Server::SessionRuntime>();
Server::Detail::ThreadSessionScope threadScope(*runtime);
ArmSessionLatch();
// The child bypasses MobileGL::Initialize: arm its own role counters.
MobileGL::MG_Util::PipeStats::Init();
auto& session = Server::ServerSessionInstance();
auto& loop = Server::ServerLoopInstance();
auto& session = runtime->Session();
auto& loop = runtime->Loop();
// P12 (D5): WHAT A PROCESS EXIT CLEANED UP FOR FREE, THE IN-PROCESS SHAPE CLEANS UP BY HAND,
// on every way out from here - so the next session in this process starts where a fresh
// session child would. A no-op for every forked / single-session shape: those `_exit` with the
@@ -659,6 +671,9 @@ int RunSession(std::unique_ptr<SocketTransport> control, std::vector<std::uint8_
// below) and is the one that says "still running" while the apply thread runs it. Cleared
// after the loop, on this same thread, so no post can be in flight when it goes.
loop.SetControlProgressSink(&SendSurfaceProgress, control.get());
// P14 S2: the apply thread opens the same scope this thread is on, so its reads of the
// session, this loop and the PipeInputs block resolve to THIS session's.
loop.SetRuntime(*runtime);
if (loop.Start(session) != MOBILEGL_OK) return endSession(70);
WireLogError("MG_Remote server: pid=%d transport=spawn role=server ready control=%s data=%s",
selfPid, tcp ? "tcp" : "unix", tcp ? "stream" : "shm");
@@ -1327,17 +1342,44 @@ private:
// shm segments' descriptors cross by SCM_RIGHTS, so there is no DataBind to route and no pre-auth
// gate - both are TCP exposure machinery, and a unix peer is local by construction (the forked
// unix supervisor runs without either). Sessions take the TCP in-process shape's thread hand-off:
// one at a time, Busy for a second client, the latch reset between sessions, stop by
// g_inProcessStop.
// a thread per session, up to MOBILEGL_IPC_INPROC_MAX_SESSIONS (default 16) and Refuse{Busy}
// over it, the latch per session, stop by
// g_inProcessStop. P14 S2: THE SESSIONS ARE CONCURRENT - each one owns its ServerSession, its
// ServerLoop and its PipeInputs block through its own ThreadSessionScope (SessionRuntime.h), so a
// session's close, latch or fault reaches no other, and the server's own stop waits for all of
// them rather than for the one.
class UnixInProcessSupervisor {
public:
UnixInProcessSupervisor(int listener, unsigned long& sessionsFaulted)
: m_listener(listener), m_pairs(listener), m_sessionsFaulted(sessionsFaulted) {}
// P14 S2: MAX SESSIONS AT ONCE. Each live session is one control thread (RunSession) plus its
// own mgl-srv-apply, both carrying their own ServerSession/ServerLoop/PipeInputs block, so the
// cap is a resource limit and not a correctness one. The default is the display server's
// (mobilegl_server_serve_inprocess), which is where this class is used.
static constexpr unsigned kDefaultMaxSessions = 16;
// MOBILEGL_IPC_INPROC_MAX_SESSIONS, capped, 0/unset/invalid = the default. An environment
// knob rather than a new argument to mobilegl_server_serve_inprocess: the embedded ABI has one
// parameter (the endpoint) and the display server passes none of this, exactly as it passes
// none of the transport knobs.
static unsigned MaxSessionsFromEnvironment() {
const char* text = std::getenv("MOBILEGL_IPC_INPROC_MAX_SESSIONS");
if (text == nullptr || text[0] == 0) return kDefaultMaxSessions;
char* end = nullptr;
const long parsed = std::strtol(text, &end, 10);
if (end == text || parsed <= 0) return kDefaultMaxSessions;
return static_cast<unsigned>(std::min<long>(parsed, 256));
}
UnixInProcessSupervisor(int listener, unsigned long& sessionsFaulted,
unsigned maxSessions = kDefaultMaxSessions)
: m_listener(listener), m_pairs(listener), m_sessionsFaulted(sessionsFaulted),
m_maxSessions(maxSessions == 0 ? kDefaultMaxSessions : maxSessions) {}
~UnixInProcessSupervisor() {
// Run() only returns with the session thread joined; a listener failure (73) is the
// one way out with it live, and it is never left running behind the supervisor.
if (m_sessionThread.joinable()) m_sessionThread.join();
// Run() only returns with every session thread joined; a listener failure (73) is the one
// way out with one live, and a session is never left running behind the supervisor.
for (auto& session : m_live) {
if (session->thread.joinable()) session->thread.join();
}
}
int Run() {
@@ -1352,15 +1394,11 @@ public:
static_cast<int>(accepted));
return 73;
}
// exit_group's close window, as the forked loop's: a client reconnecting the moment
// its session ended must not be told Busy by a session that is exiting.
const auto reapDeadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(50);
while (m_active > 0 && std::chrono::steady_clock::now() < reapDeadline) {
if (Reap()) break;
::usleep(1000);
}
if (m_active > 0) {
RefuseBusy(*control, "one session is already active");
// P14 S2: THE CAP, NOT "ONE AT A TIME". A peer over the limit is refused by the same
// words the forked `--max-sessions` supervisor uses, and is not a latch: the sessions
// already running carry on and the connection is simply closed.
if (m_live.size() >= m_maxSessions) {
RefuseBusy(*control, "the session limit is reached");
continue;
}
StartSessionThread(std::move(control));
@@ -1368,48 +1406,71 @@ public:
}
private:
// The same reap as the TCP shape's ReapSessionThread: join, count faults, reset the latch
// for the next session in this process.
bool Reap() {
if (m_active <= 0 || !m_sessionDone.load(std::memory_order_acquire)) return false;
if (m_sessionThread.joinable()) m_sessionThread.join();
const int code = m_sessionExit.load(std::memory_order_acquire);
m_active = -1;
if (code != 0) ++m_sessionsFaulted;
ResetSessionLatch();
WireLogError("MG_Remote server: in-process unix session #%lu pid=%d reaped exit=%d%s sessionsFaulted=%lu",
m_sessionOrdinal, static_cast<int>(::getpid()), code,
code == kSessionLatchedExitCode ? " (latched fault)" : "", m_sessionsFaulted);
return true;
// One live session: its control thread, and the two facts the reap needs from it. The session
// itself (its ServerSession, its apply thread, its PipeInputs block) is owned by RunSession's
// own frame, on that thread - nothing here reaches into it.
struct LiveSession {
std::thread thread;
std::atomic<bool> done{false};
std::atomic<int> exit{0};
unsigned long long ordinal = 0;
};
// The same reap as the TCP shape's ReapSessionThread: join, count faults, reset the latch for
// the next session in this process. Every finished session is reaped, in whatever order they
// finished.
void Reap() {
for (auto session = m_live.begin(); session != m_live.end();) {
LiveSession& live = **session;
if (!live.done.load(std::memory_order_acquire)) {
++session;
continue;
}
if (live.thread.joinable()) live.thread.join();
const int code = live.exit.load(std::memory_order_acquire);
if (code != 0) ++m_sessionsFaulted;
ResetSessionLatch();
WireLogError("MG_Remote server: in-process unix session #%llu pid=%d reaped exit=%d%s "
"sessionsFaulted=%lu (live %zu)",
static_cast<unsigned long long>(live.ordinal),
static_cast<int>(::getpid()), code,
code == kSessionLatchedExitCode ? " (latched fault)" : "", m_sessionsFaulted,
m_live.size() - 1);
session = m_live.erase(session);
}
}
void StartSessionThread(std::unique_ptr<SocketTransport> connection) {
if (m_sessionThread.joinable()) m_sessionThread.join(); // reaped already; never live here
m_sessionDone.store(false, std::memory_order_release);
m_sessionExit.store(0, std::memory_order_release);
++m_sessionOrdinal;
// No hand-off pair and no pre-read Hello: the session reads its own first frame and binds
// its shm segments from the fds the pair's second connection carries.
auto live = std::make_unique<LiveSession>();
live->ordinal = ++m_sessionOrdinal;
try {
// No hand-off pair and no pre-read Hello: the session reads its own first frame and
// binds its shm segments from the fds the pair's second connection carries.
m_sessionThread = std::thread([this, conn = std::move(connection)]() mutable {
live->thread = std::thread([live = live.get(), conn = std::move(connection)]() mutable {
const int code = RunSession(std::move(conn), {}, {}, -1, DataSource::None, 10000,
/*inProcess=*/true);
m_sessionExit.store(code, std::memory_order_release);
m_sessionDone.store(true, std::memory_order_release);
live->exit.store(code, std::memory_order_release);
live->done.store(true, std::memory_order_release);
});
} catch (...) {
WireLogError("MG_Remote server: could not start the in-process unix session thread; the "
"connection is closed (it cannot be refused: it moved into the failed thread)");
return;
}
m_active = ::getpid();
WireLogError("MG_Remote server: in-process unix session #%lu started on a thread (pid=%d)",
m_sessionOrdinal, static_cast<int>(::getpid()));
m_live.push_back(std::move(live));
WireLogError("MG_Remote server: in-process unix session #%llu started on a thread (pid=%d, "
"%zu live of at most %u; %u accepted in this process)",
static_cast<unsigned long long>(m_sessionOrdinal),
static_cast<int>(::getpid()), m_live.size(), m_maxSessions,
Server::LiveServerSessionCount());
}
int StopServing() {
while (m_active > 0) {
if (!Reap()) ::usleep(10000);
// P14 S2: EVERY live session, not one. Each reads g_inProcessStop on its own control
// slice, so this is the same orderly end the single-session shape had, N times over.
while (!m_live.empty()) {
Reap();
if (!m_live.empty()) ::usleep(10000);
}
WireLogError("MG_Remote server: pid=%d in-process display server stopped", static_cast<int>(::getpid()));
return 0;
@@ -1419,11 +1480,10 @@ private:
// The connections that have not been paired yet live here between Accept calls.
Server::PairAcceptor m_pairs;
unsigned long& m_sessionsFaulted;
std::thread m_sessionThread;
std::atomic<bool> m_sessionDone{false};
std::atomic<int> m_sessionExit{0};
unsigned long m_sessionOrdinal = 0;
pid_t m_active = -1;
unsigned m_maxSessions;
// P14 S2: every live session, not one. Reaped by Run()'s Reap and by StopServing.
std::vector<std::unique_ptr<LiveSession>> m_live;
unsigned long long m_sessionOrdinal = 0;
};
// The server's environment preconditions, shared by the exec'd supervisor and the in-process
@@ -1638,7 +1698,8 @@ extern "C" __attribute__((visibility("default"))) int mobilegl_server_serve_inpr
TcpSupervisor::Handoff::Thread, &g_inProcessStop);
result = supervisor.Run();
} else {
UnixInProcessSupervisor supervisor(listener, sessionsFaulted);
UnixInProcessSupervisor supervisor(listener, sessionsFaulted,
UnixInProcessSupervisor::MaxSessionsFromEnvironment());
result = supervisor.Run();
}
LogSupervisorSummary(sessionsFaulted);
+131 -21
View File
@@ -10,6 +10,7 @@
#include "../Transport/SocketTransport.h"
#include "ServerSession.h"
#include "SessionRuntime.h"
#include <MG_Remote/FatalFunnel.h>
#include "../CapsCodec.h"
@@ -528,11 +529,24 @@ namespace MobileGL::MG_Remote::Server {
// One callback table and one process segment resolver: an in-progress Accept
// reserves their owner too. CAS closes the race between distinct session objects
// without making concurrent sessions a supported mode.
//
// P14 S2: THE TABLE IS STILL ONE PER PROCESS, and that is now deliberate rather than a
// limit. Its entries are the same five functions for every session; what makes them route
// to the right session is that they resolve it per calling thread
// (ServerSession::Active()), and every one of them is called by a backend that runs on a
// session's own apply thread. So the owner word below is a CLAIM on a shared, idempotent
// installation, not a claim on "the session".
std::atomic<ServerSession*> g_sessionOwner{nullptr};
// P14 S2: accepted and not yet closed. The claim above is released by a Close only when
// this reaches zero - one session ending may not uninstall the table another is using.
std::atomic<Uint32> g_liveSessions{0};
} // namespace
Uint32 ServerSessionCount() { return g_liveSessions.load(std::memory_order_acquire); }
ServerSession& ServerSessionInstance() {
if (ServerSession* const own = Detail::CurrentSession()) return *own;
// Leak at exit, deliberately and per ID-8: frontend destructors reach pipe and backend
// state from exit handlers, and a session destroyed before them would be a
// use-after-free rather than a tidy teardown.
@@ -540,7 +554,10 @@ namespace MobileGL::MG_Remote::Server {
return *instance;
}
ServerSession* ServerSession::Active() { return g_active.load(std::memory_order_acquire); }
ServerSession* ServerSession::Active() {
if (ServerSession* const own = Detail::CurrentSession()) return own;
return g_active.load(std::memory_order_acquire);
}
ServerSession::ServerSession() {
m_link = Transport::CreateSharedLink(Transport::TransportRoleTag::ServerConsumer);
@@ -584,8 +601,17 @@ namespace MobileGL::MG_Remote::Server {
MobileGLResult ServerSession::Accept(Transport::ITransport& transport,
const std::vector<Uint8>* firstFrame) {
// P14 S2: A SERVED SESSION DOES NOT CLAIM THE PROCESS TABLE, because the table is SHARED.
// Its entries are the same five functions for every session and they route by the calling
// thread (ServerSession::Active()), so a second session installing them is the idempotent
// repeat InstallReverseCallback already allows - and a second session REFUSING to install
// them is what a one-session process would have. The claim below therefore belongs to the
// shapes whose process really is one session (the inproc client+server role, FvSession and
// its peers in ServerLoopTest): there a second ServerSession object is still the named
// Fatal{callback-double-install} the single-session ruling asks for.
const Bool sharedTable = Detail::CurrentSession() == this;
ServerSession* expectedOwner = nullptr;
if (!g_sessionOwner.compare_exchange_strong(expectedOwner, this,
if (!sharedTable && !g_sessionOwner.compare_exchange_strong(expectedOwner, this,
std::memory_order_acq_rel, std::memory_order_acquire)) {
if (expectedOwner == this) return MOBILEGL_ERR_INVALID_ARGUMENT;
SessionFail(MGFatalFamily::RoleViolation, "MGPipe: Fatal{RoleViolation, \"callback-double-install\"} - another "
@@ -702,6 +728,19 @@ namespace MobileGL::MG_Remote::Server {
m_t0Stores = m_t0Bytes = m_t0Declined = m_t0Refusals = 0;
m_adoptInbox.Clear();
m_adoptInbox.Attach(&transport);
// P14 S1: the context registry is the session's, so it is emptied with the rest of the
// per-session state this Accept resets. A session that never crossed a bind_context
// leaves the current token at 0, which is the single-context shape's answer.
//
// P14 S5: the APPLIERS of those contexts go with them - one registry entry per context
// and one per share group, released here because a session that is re-accepted must not
// inherit the previous client's object records. Accept can run on the control thread
// while nothing is applying (this is the accept path, before the first Hello is
// answered), so the release is safe here in a way it would not be mid-session.
MG_Pipe::MGPipeApplierReleaseSession(reinterpret_cast<Uint64>(this));
m_contexts.clear();
m_currentContextToken.store(0, std::memory_order_release);
m_contextsCreated = m_contextsDestroyed = m_contextBinds = 0;
// ---- 3. the four segments, both control pages, the rings.
MobileGLResult created = MOBILEGL_ERR_UNSUPPORTED;
@@ -844,6 +883,10 @@ namespace MobileGL::MG_Remote::Server {
m_segments.InstallProcessResolver();
m_accepted = true;
m_closed = false;
// P14 S2: this session is live. The reverse-channel table and the segment resolver are
// process-wide and shared; they are released by whichever Close finds this back at zero.
g_liveSessions.fetch_add(1, std::memory_order_acq_rel);
// ---- P5c ev: the four reverse-channel producers are THIS session's (CONTRACT-P5C
// §4.1), installed before the apply thread can apply a record that produces one and
@@ -1006,29 +1049,41 @@ namespace MobileGL::MG_Remote::Server {
}
void ServerSession::Close() {
// P14 S2: idempotent (ServerSession.h). A served session is a stack object whose owner
// closes it explicitly and whose destructor closes it again.
if (m_closed) return;
m_closed = true;
ServerSession* expectedActive = this;
g_active.compare_exchange_strong(expectedActive, nullptr,
std::memory_order_acq_rel, std::memory_order_acquire);
if (m_accepted) {
// Uninstall AFTER the apply thread has joined, never before: a record still in
// flight can still resolve a segment offset (table 3's fourth column).
Wire::SegmentTable::UninstallProcessResolver();
// The reverse-channel producers go with the session that owns them - release
// only the entries that are still OURS, never one a later owner installed.
if (MG_Pipe::gMGPipeCallbacks.OnGlError == &ServerOnGlError) {
MG_Pipe::gMGPipeCallbacks.OnGlError = nullptr;
}
if (MG_Pipe::gMGPipeCallbacks.OnBufferWriteback == &ServerOnBufferWriteback) {
MG_Pipe::gMGPipeCallbacks.OnBufferWriteback = nullptr;
}
if (MG_Pipe::gMGPipeCallbacks.OnGpuWritten == &ServerOnGpuWritten) {
MG_Pipe::gMGPipeCallbacks.OnGpuWritten = nullptr;
}
if (MG_Pipe::gMGPipeCallbacks.OnSurfaceChanged == &ServerOnSurfaceChanged) {
MG_Pipe::gMGPipeCallbacks.OnSurfaceChanged = nullptr;
}
if (MG_Pipe::gMGPipeEventRingCapacityBytes == &ServerEventRingCapacityBytes) {
MG_Pipe::gMGPipeEventRingCapacityBytes = nullptr;
// P14 S2: DROP THIS SESSION FIRST, THEN ASK WHETHER ANY IS LEFT. The two process-wide
// hooks below (the segment resolver and the reverse-channel table) are shared by every
// session in the process, so a session that ends while another is live must leave both
// installed - its own threads are done with them (the apply thread is joined above and
// this control thread unbinds its own binding on the way out of RunSession).
const Uint32 remaining = g_liveSessions.fetch_sub(1, std::memory_order_acq_rel) - 1;
if (remaining == 0) {
// Uninstall AFTER the apply thread has joined, never before: a record still in
// flight can still resolve a segment offset (table 3's fourth column).
Wire::SegmentTable::UninstallProcessResolver();
// The reverse-channel producers go with the session that owns them - release
// only the entries that are still OURS, never one a later owner installed.
if (MG_Pipe::gMGPipeCallbacks.OnGlError == &ServerOnGlError) {
MG_Pipe::gMGPipeCallbacks.OnGlError = nullptr;
}
if (MG_Pipe::gMGPipeCallbacks.OnBufferWriteback == &ServerOnBufferWriteback) {
MG_Pipe::gMGPipeCallbacks.OnBufferWriteback = nullptr;
}
if (MG_Pipe::gMGPipeCallbacks.OnGpuWritten == &ServerOnGpuWritten) {
MG_Pipe::gMGPipeCallbacks.OnGpuWritten = nullptr;
}
if (MG_Pipe::gMGPipeCallbacks.OnSurfaceChanged == &ServerOnSurfaceChanged) {
MG_Pipe::gMGPipeCallbacks.OnSurfaceChanged = nullptr;
}
if (MG_Pipe::gMGPipeEventRingCapacityBytes == &ServerEventRingCapacityBytes) {
MG_Pipe::gMGPipeEventRingCapacityBytes = nullptr;
}
}
}
// P11 B2: the T0 arm's proof for this session, then the inbox's leftovers (an Offer whose
@@ -1205,6 +1260,61 @@ namespace MobileGL::MG_Remote::Server {
return true;
}
// ---- P14 S1: the context registry ------------------------------------------------------
//
// ALL THREE RUN ON THE APPLY THREAD. CreateContext/DestroyContext are the control plane's
// frames, dispatched through RunSurfaceControlFrame; BindContext is a ring record, dispatched
// through the decoder's verb sink. Neither ever runs anywhere else, which is what makes the
// map lock-free here.
Bool ServerSession::CreateContext(Uint64 token, Uint64 shareGroupToken, Uint32 flags) {
if (token == 0) return false;
if (m_contexts.find(token) != m_contexts.end()) return false;
ContextRuntime runtime;
runtime.Token = token;
runtime.ShareGroupToken = shareGroupToken;
runtime.Flags = flags;
m_contexts.emplace(token, runtime);
++m_contextsCreated;
// P14 S5: and the applier this context's records are applied through - its own working
// state, in the share group `shareGroupToken` names (0 = one it starts itself). The key
// is THIS object's address, which is what the session's key resolver
// (SessionRuntime.cpp) hands back, so registration and lookup agree by construction.
// Registering here rather than inferring at lookup time is what keeps the resolver a
// two-word read: this runs on the apply thread, where the frame channel delivers, and
// is the only writer of the contexts map.
MG_Pipe::MGPipeApplierRegisterContext(reinterpret_cast<Uint64>(this), token, shareGroupToken);
return true;
}
Bool ServerSession::DestroyContext(Uint64 token) {
if (token == 0) return false;
const auto it = m_contexts.find(token);
if (it == m_contexts.end()) return false;
m_contexts.erase(it);
++m_contextsDestroyed;
// P14 S5: the working state goes with it, and this group's object records go when its
// last context does.
MG_Pipe::MGPipeApplierUnregisterContext(reinterpret_cast<Uint64>(this), token);
// A destroyed context cannot stay current: leaving the token bound would attribute every
// record after the destroy to a context the session no longer has. The client's own
// eglDestroyContext is refused while the context is current (EGL_BAD_ACCESS), so this
// arm is reached with the token already released in the well-behaved sequence - and with
// the release MISSING it is still the safe direction.
Uint64 expected = token;
m_currentContextToken.compare_exchange_strong(expected, 0, std::memory_order_acq_rel);
return true;
}
Bool ServerSession::BindContext(Uint64 token) {
// 0 is the release edge and is always legal: the client has context A current, releases
// it, and a verb on the app thread follows - the session binds "nothing" rather than
// answering to a stale token.
if (token != 0 && m_contexts.find(token) == m_contexts.end()) return false;
m_currentContextToken.store(token, std::memory_order_release);
++m_contextBinds;
return true;
}
Transport::RingConsumer& ServerSession::CommandRing() { return *m_commands; }
Transport::RingControl& ServerSession::Control() {
+68
View File
@@ -65,6 +65,10 @@ namespace MobileGL::MG_Remote::Server {
class ServerSession {
public:
// P14 S2: THE SESSION OF THE CALLING THREAD, else the process's active one. Every
// server-role caller that matters (the reverse-channel producers, the applier's role
// guards, the decoder, ServerMain's control loop) runs on a session's own thread and
// therefore gets ITS session - which is what makes one process able to serve several.
static ServerSession* Active();
ServerSession();
@@ -190,6 +194,11 @@ namespace MobileGL::MG_Remote::Server {
Bool PeerSharedSegments() const { return m_peerSharedSegments; }
// Teardown: after the apply thread has been joined, never before - a record still in
// flight can still resolve a segment offset (table 3's fourth column).
//
// P14 S2: AND IT IS IDEMPOTENT, because a served session is now a stack object. A session
// that has been closed once (RunSession closes it explicitly) is closed again by its
// destructor; the second call must not run the teardown twice. Accept re-opens it, so the
// in-process display server's accept/close/accept cycle is unchanged.
void Close();
Transport::SessionSegments& Shm();
@@ -322,6 +331,45 @@ namespace MobileGL::MG_Remote::Server {
Bool AdoptT0Quiet() const { return m_adoptT0Quiet; }
AdoptInbox& T0Inbox() { return m_adoptInbox; }
// ---- P14 S1 (docs/Disaggregated/design/11-state-ownership.md): the session's contexts -
//
// THE PLACEHOLDER TABLE. `CreateContext`/`DestroyContext` on the control plane build and
// destroy an entry per client token; `BindContext` on the ring makes one of them the
// session's current context. What lives in an entry in THIS slice is the token and the
// share group it was derived from - no native EGLContext, no GLContext, no working state
// (that is S4's). The table exists so that a token the client names can be proved to
// have been created before anything is attributed to it, and so that the S4 slice has a
// place to put the runtime it will own.
//
// WRITES ARE THE APPLY THREAD'S. CreateContext/DestroyContext arrive as control frames
// dispatched through the frame channel, BindContext as a record through the decoder, and
// both run on mgl-srv-apply - so the table needs no lock. CurrentContextToken() is
// atomic because a test reads it from the case's own thread.
struct ContextRuntime {
Uint64 Token = 0; // the client's context token, dense from 1
Uint64 ShareGroupToken = 0; // 0 = this context started a share group
Uint32 Flags = 0; // reserved; the control frame's `flags` field, carried verbatim
};
// False when a context with this token already exists, or when the token is 0 (0 is
// "no context" everywhere on both planes and is never a creatable context).
Bool CreateContext(Uint64 token, Uint64 shareGroupToken, Uint32 flags);
// False when no such token exists - a destroy the peer did not create is the control
// frame's own refusal to make, not a silent no-op.
Bool DestroyContext(Uint64 token);
// Binds the session's current context. Token 0 is legal and means "no context" (the
// release edge); any other token must have been created, or this is a named refusal.
Bool BindContext(Uint64 token);
// 0 = no context is bound. Every record the session has applied so far belongs to this
// token; a session that never crossed a bind_context has never bound one.
Uint64 CurrentContextToken() const { return m_currentContextToken.load(std::memory_order_acquire); }
Bool HasContext(Uint64 token) const { return m_contexts.find(token) != m_contexts.end(); }
Uint64 ContextCount() const { return static_cast<Uint64>(m_contexts.size()); }
Uint64 ContextsCreated() const { return m_contextsCreated; }
Uint64 ContextsDestroyed() const { return m_contextsDestroyed; }
// The per-session tallies the sink keeps for the two control frames it dispatched.
Uint64 ContextBinds() const { return m_contextBinds; }
private:
MobileGLResult BindDataConnection(Transport::ITransport& control, Transport::ILink& link,
const Uint8* nonce);
@@ -347,6 +395,9 @@ namespace MobileGL::MG_Remote::Server {
Bool m_consumedSet = false;
Bool m_sizesSet = false;
Bool m_accepted = false;
// P14 S2: Close() has run for the current accept. Cleared by Accept, which is what keeps
// the in-process display server's accept/close/accept cycle working.
Bool m_closed = false;
ApplyPeer m_peer = ApplyPeer::InProcess;
Bool m_peerSharedSegments = true;
// PH-6. Written by the apply thread (the only SEG_EVENT producer), reset by Accept.
@@ -369,10 +420,27 @@ namespace MobileGL::MG_Remote::Server {
Uint64 m_t0Bytes = 0;
Uint64 m_t0Declined = 0;
Uint64 m_t0Refusals = 0;
// P14 S1. Apply-thread-only map (see ContextRuntime); the current token is atomic for
// the reader on a test thread. Reset by Accept.
UnorderedMap<Uint64, ContextRuntime> m_contexts;
std::atomic<Uint64> m_currentContextToken{0};
Uint64 m_contextsCreated = 0;
Uint64 m_contextsDestroyed = 0;
Uint64 m_contextBinds = 0;
};
// Leak-at-exit like every other MG_Remote singleton (ID-8): no frontend destructor may
// reach pipe or backend state from an exit handler.
//
// P14 S2 (SessionRuntime.h): THE SINGLETON IS THE FALLBACK, NOT THE SESSION. On a thread that
// belongs to a served session (ServerMain::RunSession's control thread, or that session's
// mgl-srv-apply) this answers with THAT session; every other thread - the client process, the
// inproc one-process client+server shape, a unit case - keeps getting the leaked instance.
ServerSession& ServerSessionInstance();
// P14 S2: sessions accepted and not yet closed in this process. A process-wide fact that must
// outlive one session (the reverse-channel callback table, the segment resolver) is released
// only when this reaches zero.
Uint32 ServerSessionCount();
} // namespace MobileGL::MG_Remote::Server
@@ -0,0 +1,127 @@
// MobileGL - MobileGL/MG_Remote/Server/SessionRuntime.cpp
// Copyright (c) 2025-2026 MobileGL-Dev
// Licensed under the GNU Lesser General Public License v3.0:
// https://www.gnu.org/licenses/gpl-3.0.txt
// https://www.gnu.org/licenses/lgpl-3.0.txt
// SPDX-License-Identifier: LGPL-3.0-only
// End of Source File Header
// P14 S2: the per-session runtime and the thread routing (SessionRuntime.h states the shape).
#include "SessionRuntime.h"
#include <MG_Backend/DirectGLES/DirectGLES.h>
#include <MG_Remote/FatalFunnel.h>
#include <MG_Remote/Wire/PipeWireCodec.h>
#include <atomic>
namespace MobileGL::MG_Remote::Server {
namespace {
// The calling thread's session. nullptr on every thread that is not one of a session's own
// two, which is the whole of the fallback rule.
thread_local SessionRuntime* t_runtime = nullptr;
// The resolver MG_Pipe asks per thread. Installing it is a single store of a function
// pointer that is never replaced, so it needs no lock and no teardown: the server role
// lives for the process (ID-8).
MG_Pipe::PipeInputs* ResolveThreadInputs() {
SessionRuntime* runtime = t_runtime;
return runtime != nullptr ? &runtime->Inputs() : nullptr;
}
// P14 S4 (docs/Disaggregated/design/11-state-ownership.md). THE NATIVE TUPLE'S KEY. The
// backend keys its per-context native state - the EGLContext, its config, the draw/read
// binding - on (session, client context token); this is the one place that answers the pair
// for the calling thread. The session half is the runtime's ADDRESS, which is stable for the
// session's whole life and unique among live sessions in the process; the token half is what
// `bind_context` last set on the ring. False (== the {0,0} key) on any thread that is not a
// session's own, which is the client process, the inproc one-process shape and every unit
// case - i.e. exactly the single-context world the backend still serves unchanged.
Bool ResolveThreadNativeContextKey(Uint64* outSessionKey, Uint64* outContextToken) {
SessionRuntime* runtime = t_runtime;
if (runtime == nullptr) return false;
*outSessionKey = reinterpret_cast<Uint64>(runtime);
*outContextToken = runtime->Session().CurrentContextToken();
return true;
}
// P14 S5 (docs/Disaggregated/design/11-state-ownership.md). WHOSE APPLIER IS THIS THREAD
// IN? The same two-word answer as the native key above, and deliberately the same
// spelling: the session half is the ServerSession's own address - which is the key the
// registration side uses (ServerSession::CreateContext passes `this`), so the two agree
// by construction rather than by two conventions - and the token half is what
// `bind_context` last set on this session's ring. A thread that is not a session's
// answers false and gets the process-wide applier, i.e. the single-context world every
// other shape in this tree still runs.
Bool ResolveThreadApplierKey(MG_Pipe::MGPipeApplierKey* outKey) {
SessionRuntime* runtime = t_runtime;
if (runtime == nullptr) return false;
outKey->SessionKey = reinterpret_cast<Uint64>(&runtime->Session());
outKey->ContextToken = runtime->Session().CurrentContextToken();
return true;
}
} // namespace
void Detail::InstallSessionRuntimeHooks() {
if (MG_Pipe::g_pipeInputsThreadResolver != &ResolveThreadInputs) {
MG_Pipe::g_pipeInputsThreadResolver = &ResolveThreadInputs;
}
MG_Backend::DirectGLES::SetNativeContextKeyResolver(&ResolveThreadNativeContextKey);
MG_Pipe::MGPipeSetApplierKeyResolver(&ResolveThreadApplierKey);
}
SessionRuntime* Detail::CurrentRuntime() { return t_runtime; }
ServerSession* Detail::CurrentSession() {
SessionRuntime* runtime = t_runtime;
return runtime != nullptr ? &runtime->Session() : nullptr;
}
ServerLoop* Detail::CurrentLoop() {
SessionRuntime* runtime = t_runtime;
return runtime != nullptr ? &runtime->Loop() : nullptr;
}
MG_Pipe::PipeInputs* Detail::CurrentInputs() { return ResolveThreadInputs(); }
Detail::ThreadSessionScope::ThreadSessionScope(SessionRuntime& runtime) {
InstallSessionRuntimeHooks();
m_previous = t_runtime;
t_runtime = &runtime;
m_previousLatchDomain = FatalLatchDomainBind(runtime.LatchDomain());
// The segment resolver is the OTHER process-wide hook that used to mean "one session": the
// thunk is one function pointer for the process, and which TABLE it answers from is now
// per thread (PipeWireCodec.h). Bound before anything on this thread can decode a record.
runtime.Session().Segments().BindThreadResolver();
}
Detail::ThreadSessionScope::~ThreadSessionScope() {
if (m_previous != nullptr) {
m_previous->Session().Segments().BindThreadResolver();
} else {
Wire::SegmentTable::UnbindThreadResolver();
}
FatalLatchDomainBind(m_previousLatchDomain);
t_runtime = m_previous;
}
SessionRuntime::SessionRuntime()
: m_latchDomain(FatalLatchDomainOpen()) {}
SessionRuntime::~SessionRuntime() {
// P14 S5: this runtime's session is the key every applier it registered was filed
// under, so the last act of the session is to drop them. Safe here for the reason the
// latch domain is (SessionLoop::Stop has joined the apply thread; the control thread's
// scope outlives this object), and idempotent against Accept's own release.
MG_Pipe::MGPipeApplierReleaseSession(reinterpret_cast<Uint64>(&m_session));
// No thread may still be bound to this domain: the apply thread is joined by
// ServerLoop::Stop and the control thread's scope outlives this object.
FatalLatchDomainClose(m_latchDomain);
m_latchDomain = 0;
}
Uint32 LiveServerSessionCount() { return ServerSessionCount(); }
} // namespace MobileGL::MG_Remote::Server
+103
View File
@@ -0,0 +1,103 @@
// MobileGL - MobileGL/MG_Remote/Server/SessionRuntime.h
// Copyright (c) 2025-2026 MobileGL-Dev
// Licensed under the GNU Lesser General Public License v3.0:
// https://www.gnu.org/licenses/gpl-3.0.txt
// https://www.gnu.org/licenses/lgpl-3.0.txt
// SPDX-License-Identifier: LGPL-3.0-only
// End of Source File Header
// 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, MGB_CTX, 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.
#pragma once
#include <Includes.h>
#include <MG_Backend/MGPipe/PipeInputs.h>
#include "ServerLoop.h"
#include "ServerSession.h"
#include <cstdint>
namespace MobileGL::MG_Remote::Server {
class SessionRuntime {
public:
SessionRuntime();
~SessionRuntime();
SessionRuntime(const SessionRuntime&) = delete;
SessionRuntime& operator=(const SessionRuntime&) = delete;
ServerSession& Session() { return m_session; }
ServerLoop& Loop() { return m_loop; }
MG_Pipe::PipeInputs& Inputs() { return m_inputs; }
// The latch domain this session owns (FatalFunnel.h). A named fault latched by one session
// must not end another, and must not be cleared by another's reap.
int LatchDomain() const { return m_latchDomain; }
private:
ServerSession m_session;
ServerLoop m_loop;
MG_Pipe::PipeInputs m_inputs;
int m_latchDomain = 0;
};
namespace Detail {
// The session of the CALLING thread, or nullptr when it is not a session's own thread.
SessionRuntime* CurrentRuntime();
ServerSession* CurrentSession();
ServerLoop* CurrentLoop();
// What MG_Pipe's per-thread resolver asks for: the calling thread's block, or nullptr for
// "use the process-wide one".
MG_Pipe::PipeInputs* CurrentInputs();
// Installs the process-wide hooks the per-session blocks need (the PipeInputs resolver).
// Idempotent, and called by ThreadSessionScope itself so no bring-up order can miss it.
void InstallSessionRuntimeHooks();
// THE SCOPE. Makes `runtime` the calling thread's session for as long as it lives: the
// session/loop the singleton accessors answer with, the PipeInputs block MGB_CTX reads,
// this session's segment resolver and this session's latch domain. Restores what was there
// before on the way out (two nested scopes are not a shape anything uses, but a thread that
// served one session and is then reused must not keep answering with the dead one).
class ThreadSessionScope {
public:
explicit ThreadSessionScope(SessionRuntime& runtime);
~ThreadSessionScope();
ThreadSessionScope(const ThreadSessionScope&) = delete;
ThreadSessionScope& operator=(const ThreadSessionScope&) = delete;
private:
SessionRuntime* m_previous = nullptr;
int m_previousLatchDomain = 0;
};
} // namespace Detail
// Sessions accepted and not yet closed in THIS process. 1 is the old shape; more is this
// slice's. ServerSession::Close gates the process-wide hooks (the reverse-channel table, the
// segment resolver) on it, and ServerMain logs it beside each session it starts.
Uint32 LiveServerSessionCount();
} // namespace MobileGL::MG_Remote::Server
@@ -24,6 +24,8 @@ namespace MobileGL::MG_Remote::Server {
case SurfaceControlOp::ReleaseResources: return "ReleaseResources";
case SurfaceControlOp::SetWindowHandle: return "SetWindowHandle";
case SurfaceControlOp::InitCapabilities: return "InitCapabilities";
case SurfaceControlOp::CreateContext: return "CreateContext";
case SurfaceControlOp::DestroyContext: return "DestroyContext";
case SurfaceControlOp::SwapBuffersInprocOnly: return "SwapBuffersInprocOnly";
case SurfaceControlOp::InitWindowSurfaceInprocOnly: return "InitWindowSurfaceInprocOnly";
case SurfaceControlOp::ProbeForTesting: return "ProbeForTesting";
@@ -47,6 +49,11 @@ namespace MobileGL::MG_Remote::Server {
// frame, which is why this row was missing; the request still has to
// cross, because under spawn the apply thread is in another process.
case SurfaceControlOp::InitCapabilities:
// P14 S1: the context lifecycle. The client's eglCreateContext/eglDestroyContext have a
// live caller under spawn (EGLImpl), so unlike the inproc-only trio beside them these two
// MUST cross - the server it is asking is in another process.
case SurfaceControlOp::CreateContext:
case SurfaceControlOp::DestroyContext:
return true;
default:
return false;
@@ -65,13 +65,25 @@ namespace MobileGL::MG_Remote::Server {
// every spawned eglMakeCurrent died at "surface op kind 11 cannot cross
// the wire (InprocOnlyOpOnTheWire)", one call after the backend came up.
InitCapabilities = 11,
// P14 S1 (docs/Disaggregated/design/11-state-ownership.md). The EGL context lifecycle,
// appended to the schema and to this enum together so the identity cast below stays the
// whole mapping: the client's eglCreateContext/eglDestroyContext reach the server through
// THE SAME frame channel the nine surface forwarders use, on the same thread, in the same
// order - which is the property this slice needs and a second channel would not give.
CreateContext = 12,
DestroyContext = 13,
// INPROC-ONLY kinds: legal inside this process's frame channel, NEVER encodable onto the
// wire (SurfaceOpCodec refuses them by name). f0-egl's census found no production caller
// for the two dead forwarders; they ride the same frame channel because the
// function-pointer mailbox is GONE, not because they are wire ops.
SwapBuffersInprocOnly = 12, // present travels as a record (the class-B Present emitter)
InitWindowSurfaceInprocOnly = 13,// a client-side no-op; kept for the inproc test lane
ProbeForTesting = 14, // MG_Test's arbitrary-work seam through the same channel
//
// THEIR VALUES MOVED 12/13/14 -> 14/15/16 when P14 S1 appended the two context ops. That
// is safe by construction: these three never cross a process boundary and are named
// symbolically everywhere they are used, so nothing outside this build could have pinned
// them - where the eleven above and the two below are wire ABI and may never move.
SwapBuffersInprocOnly = 14, // present travels as a record (the class-B Present emitter)
InitWindowSurfaceInprocOnly = 15,// a client-side no-op; kept for the inproc test lane
ProbeForTesting = 16, // MG_Test's arbitrary-work seam through the same channel
};
// P12 (on-screen server window), D2. THE SERVER-OWNED WINDOW, AS A FRAME-LOCAL TAG.
@@ -119,6 +131,11 @@ namespace MobileGL::MG_Remote::Server {
Int width = 0;
Int height = 0;
Int swapInterval = 0;
// P14 S1. CreateContext's two values beyond `context` (which is the client context token
// itself): the share group the context was derived into, and the reserved flags word the
// schema carries so a later attribute has a slot. 0 on every other op.
Uint64 shareGroupToken = 0;
Uint32 contextFlags = 0;
// The reply half: written by the dispatch on the apply thread, read by the poster after
// the blocking handshake returns. `ok` is the forwarder's Bool answer; eglMajor/eglMinor
// are InitializeDisplay's out values.
@@ -144,14 +161,16 @@ namespace MobileGL::MG_Remote::Server {
// Exhaustive by the language's aggregate decomposition rule: adding ANY member
// without extending this binding is a compile error, so new fields cannot evade it.
const auto& [kind, seq, display, surface, readSurface, context, windowBackend,
nativeToken, width, height, swapInterval, ok, eglMajor, eglMinor, eventHead,
refusal] = frame;
nativeToken, width, height, swapInterval, shareGroupToken, contextFlags, ok,
eglMajor, eglMinor, eventHead, refusal] = frame;
return IsSurfaceControlValue<decltype(kind)> && IsSurfaceControlValue<decltype(seq)> &&
IsSurfaceControlValue<decltype(display)> && IsSurfaceControlValue<decltype(surface)> &&
IsSurfaceControlValue<decltype(readSurface)> && IsSurfaceControlValue<decltype(context)> &&
IsSurfaceControlValue<decltype(windowBackend)> && IsSurfaceControlValue<decltype(nativeToken)> &&
IsSurfaceControlValue<decltype(width)> && IsSurfaceControlValue<decltype(height)> &&
IsSurfaceControlValue<decltype(swapInterval)> && IsSurfaceControlValue<decltype(ok)> &&
IsSurfaceControlValue<decltype(swapInterval)> &&
IsSurfaceControlValue<decltype(shareGroupToken)> &&
IsSurfaceControlValue<decltype(contextFlags)> && IsSurfaceControlValue<decltype(ok)> &&
IsSurfaceControlValue<decltype(eglMajor)> && IsSurfaceControlValue<decltype(eglMinor)> &&
IsSurfaceControlValue<decltype(eventHead)> && IsSurfaceControlValue<decltype(refusal)>;
}