[Chore] (MG_Backend, MG_Backend/DirectGLES, MG_Backend/DirectVulkan, MG_Backend/MGPipe, MG_Backend/Record, MG_Benchmark/Buffer, MG_Benchmark/Container, MG_Benchmark/Driver, MG_Benchmark/Program, MG_Benchmark/ShaderCache, MG_Benchmark/Transpile, MG_Gbm, MG_Impl, MG_Impl/CGLImpl, MG_Impl/DyldInterpose, MG_Impl/EGLImpl, MG_Impl/GLImpl, MG_Impl/GLXImpl, MG_Impl/NSOpenGLImpl, MG_Impl/Pipe, MG_Impl/WGLImpl, MG_IntegrationTest, MG_IntegrationTest/Harness, MG_IntegrationTest/Scenarios, MG_Pipe, MG_Remote, MG_Remote/Client, MG_Remote/Protocol, MG_Remote/Server, MG_Remote/Transport, MG_Remote/Wire, MG_State/EGLState, MG_State/GLState, MG_Test, MG_Test/Backend, MG_Test/BackendLoader, MG_Test/Buffer, MG_Test/EGLState, MG_Test/Framebuffer, MG_Test/Gbm, MG_Test/Pipe, MG_Test/Pipeline, MG_Test/Program, MG_Test/Query, MG_Test/SelfTest, MG_Test/ShaderTranspiler, MG_Test/State, MG_Test/Swapchain, MG_Test/Texture, MG_Test/Util, MG_Test/VertexArray, MG_Test/Wire, MG_Util/Async, MG_Util/BackendLoaders, MG_Util/Converters, MG_Util/Damage, MG_Util/Debug, MG_Util/Math, MG_Util/Metrics, MG_Util/SelfTest, MG_Util/ShaderTranspiler, MG_Util/Texture, MG_Util/X11, MobileGL, scripts/data, tools/cts, tools/device_bench, tools/spikes, tools/trace_replay, tools/wgl-smoke): clang-format every C and C++ source

- Layout only: token streams match up to split literals, continuations and using order
- The size totals fall, so the structure baseline is lowered
This commit is contained in:
2026-10-16 06:30:38 -04:00
parent 76b10cc35b
commit f4994ee36e
747 changed files with 35842 additions and 36261 deletions
+13 -8
View File
@@ -32,15 +32,18 @@ namespace MobileGL::MG_Remote::Server {
}
} // namespace
AdoptInbox::~AdoptInbox() { Clear(); }
AdoptInbox::~AdoptInbox() {
Clear();
}
void AdoptInbox::Clear() {
for (auto& [seq, kept] : m_kept) CloseFd(kept.fd);
for (auto& [seq, kept] : m_kept)
CloseFd(kept.fd);
m_kept.clear();
}
AdoptInbox::Outcome AdoptInbox::Take(Uint64 seq, Uint32 timeoutMs, int* outFd,
Transport::AdoptT0::Offer* outOffer, std::string& why) {
AdoptInbox::Outcome AdoptInbox::Take(Uint64 seq, Uint32 timeoutMs, int* outFd, Transport::AdoptT0::Offer* outOffer,
std::string& why) {
return TakeKind(Kind::T0, seq, timeoutMs, outFd, outOffer, why);
}
@@ -71,13 +74,15 @@ namespace MobileGL::MG_Remote::Server {
const auto deadline = Clock::now() + std::chrono::milliseconds(timeoutMs);
for (;;) {
const auto now = Clock::now();
const Uint32 left = now >= deadline ? 0u
: static_cast<Uint32>(std::chrono::duration_cast<std::chrono::milliseconds>(deadline - now).count());
const Uint32 left =
now >= deadline ? 0u
: static_cast<Uint32>(
std::chrono::duration_cast<std::chrono::milliseconds>(deadline - now).count());
int fd = -1;
Uint8 sideband[Transport::FdPassing::kMaxSidebandBytes] = {};
std::uint64_t sidebandSize = 0;
const MobileGLResult received = m_transport->ReceiveFd(
&fd, MobileGLMutableByteSpan{sideband, sizeof(sideband)}, &sidebandSize, left);
const MobileGLResult received =
m_transport->ReceiveFd(&fd, MobileGLMutableByteSpan{sideband, sizeof(sideband)}, &sidebandSize, left);
if (received == MOBILEGL_ERR_TIMEOUT) {
why = std::string(kind == Kind::T0 ? "no store" : "no shared-image descriptor") +
" arrived on the aux socket within " + std::to_string(timeoutMs) + " ms of its record";
+10 -4
View File
@@ -29,7 +29,11 @@ namespace MobileGL::MG_Remote::Server {
class AdoptInbox {
public:
enum class Outcome : Uint8 { Taken, TimedOut, Closed };
enum class Outcome : Uint8 {
Taken,
TimedOut,
Closed
};
AdoptInbox() = default;
~AdoptInbox();
@@ -40,8 +44,7 @@ namespace MobileGL::MG_Remote::Server {
// The Offer for record `seq` and its hop descriptor (owned by the caller on Taken). Waits
// at most `timeoutMs` for it; `why` names what went wrong otherwise.
Outcome Take(Uint64 seq, Uint32 timeoutMs, int* outFd, Transport::AdoptT0::Offer* outOffer,
std::string& why);
Outcome Take(Uint64 seq, Uint32 timeoutMs, int* outFd, Transport::AdoptT0::Offer* outOffer, std::string& why);
// A shared image's descriptor for record `seq` (an Import; sideband MGPSharedImageFdOffer).
// Same matching and the same bound as Take; the two kinds share the aux socket and are kept
@@ -56,7 +59,10 @@ namespace MobileGL::MG_Remote::Server {
SizeT Kept() const { return m_kept.size(); }
private:
enum class Kind : Uint8 { T0, SharedImage };
enum class Kind : Uint8 {
T0,
SharedImage
};
struct KeptOffer {
int fd = -1;
Transport::AdoptT0::Offer offer{};
+13 -7
View File
@@ -41,26 +41,32 @@ namespace MobileGL::MG_Remote::Server {
struct ApplyThreadPolicy {
Uint64 requestedMask = 0; // 0 = make no affinity call
Uint32 spinUs = 0;
Bool recognised = true; // false: the affinity text was not `auto`, `off` or a number
const char* rule = ""; // what the log line names
Bool recognised = true; // false: the affinity text was not `auto`, `off` or a number
const char* rule = ""; // what the log line names
};
inline const char* ApplyPeerName(ApplyPeer peer) {
switch (peer) {
case ApplyPeer::InProcess: return "in-process";
case ApplyPeer::Forked: return "forked";
case ApplyPeer::Connected: return "connected";
case ApplyPeer::InProcess:
return "in-process";
case ApplyPeer::Forked:
return "forked";
case ApplyPeer::Connected:
return "connected";
}
return "unknown";
}
inline Uint32 PopCount64(Uint64 mask) {
Uint32 count = 0;
for (; mask != 0; mask &= mask - 1) ++count;
for (; mask != 0; mask &= mask - 1)
++count;
return count;
}
inline Uint64 LowestBit64(Uint64 mask) { return mask & (~mask + 1); }
inline Uint64 LowestBit64(Uint64 mask) {
return mask & (~mask + 1);
}
// Why ReservedApplyCore answered what it did - the log line names it.
enum class ReservedCoreReason : Uint8 {
@@ -95,7 +95,7 @@ namespace {
} // namespace
extern "C" JNIEXPORT void JNICALL Java_top_mobilegl_plugin_MobileGLDisplayActivity_nativeInstallDisplay(JNIEnv* env,
jclass clazz) {
jclass clazz) {
JavaVM* vm = nullptr;
if (env->GetJavaVM(&vm) != JNI_OK) vm = nullptr;
jmethodID onGeometryRequest = env->GetStaticMethodID(clazz, "onGeometryRequest", "(II)V");
@@ -117,7 +117,7 @@ extern "C" JNIEXPORT void JNICALL Java_top_mobilegl_plugin_MobileGLDisplayActivi
}
extern "C" JNIEXPORT jint JNICALL Java_top_mobilegl_plugin_MobileGLDisplayActivity_nativeServe(JNIEnv* env, jclass,
jstring listen) {
jstring listen) {
if (listen == nullptr) return mobilegl_server_serve_inprocess(nullptr);
const char* endpoint = env->GetStringUTFChars(listen, nullptr);
if (endpoint == nullptr) return 71; // OutOfMemoryError pending
@@ -147,13 +147,13 @@ extern "C" JNIEXPORT jboolean JNICALL Java_top_mobilegl_plugin_MobileGLDisplayAc
}
extern "C" JNIEXPORT jstring JNICALL Java_top_mobilegl_plugin_MobileGLDisplayActivity_nativeDetachWindow(JNIEnv* env,
jclass) {
jclass) {
const ServerWindowDetach detached = ServerDisplayInstance().Detach();
return env->NewStringUTF(ServerWindowDetachName(detached));
}
extern "C" JNIEXPORT void JNICALL Java_top_mobilegl_plugin_MobileGLDisplayActivity_nativeUninstallDisplay(JNIEnv* env,
jclass) {
jclass) {
ServerDisplayInstance().Uninstall();
const std::lock_guard<std::mutex> lock(g_upcallMutex);
if (g_activityClass != nullptr) env->DeleteGlobalRef(g_activityClass);
+11 -7
View File
@@ -18,14 +18,18 @@ namespace {
int DetachResult(ServerWindowDetach result) {
switch (result) {
case ServerWindowDetach::NoWindow: return MOBILEGL_SERVER_WINDOW_NO_WINDOW;
case ServerWindowDetach::Released: return MOBILEGL_SERVER_WINDOW_RELEASED;
case ServerWindowDetach::ReleasedBySession: return MOBILEGL_SERVER_WINDOW_RELEASED_BY_SESSION;
case ServerWindowDetach::TimedOut: return MOBILEGL_SERVER_WINDOW_TIMED_OUT;
case ServerWindowDetach::NoWindow:
return MOBILEGL_SERVER_WINDOW_NO_WINDOW;
case ServerWindowDetach::Released:
return MOBILEGL_SERVER_WINDOW_RELEASED;
case ServerWindowDetach::ReleasedBySession:
return MOBILEGL_SERVER_WINDOW_RELEASED_BY_SESSION;
case ServerWindowDetach::TimedOut:
return MOBILEGL_SERVER_WINDOW_TIMED_OUT;
}
return MOBILEGL_SERVER_WINDOW_TIMED_OUT;
}
}
} // namespace
extern "C" int mobilegl_server_display_install(const struct mobilegl_server_display_hooks* hooks) {
if (hooks == nullptr || hooks->acquire == nullptr || hooks->release == nullptr)
@@ -45,8 +49,8 @@ extern "C" int mobilegl_server_display_install(const struct mobilegl_server_disp
extern "C" int mobilegl_server_display_install_android(mobilegl_server_geometry_callback request_geometry, void* user) {
#if defined(__ANDROID__)
const auto androidHooks = AndroidNativeWindowHooks(request_geometry, user);
const mobilegl_server_display_hooks hooks{androidHooks.acquire, androidHooks.release,
androidHooks.requestGeometry, androidHooks.user};
const mobilegl_server_display_hooks hooks{androidHooks.acquire, androidHooks.release, androidHooks.requestGeometry,
androidHooks.user};
return mobilegl_server_display_install(&hooks);
#else
(void)request_geometry;
+53 -52
View File
@@ -18,68 +18,69 @@
#endif
#ifdef __cplusplus
extern "C" {
extern "C"
{
#endif
struct ANativeWindow;
struct ANativeWindow;
typedef void (*mobilegl_server_geometry_callback)(void* user, uint32_t width, uint32_t height);
typedef void (*mobilegl_server_geometry_callback)(void* user, uint32_t width, uint32_t height);
// Opaque-window hooks also let non-Android hosts embed the display without depending on
// MobileGL's C++ headers. Both reference callbacks are required. Geometry may be null.
struct mobilegl_server_display_hooks {
void (*acquire)(void* user, void* window);
void (*release)(void* user, void* window);
mobilegl_server_geometry_callback request_geometry;
void* user;
};
// Opaque-window hooks also let non-Android hosts embed the display without depending on
// MobileGL's C++ headers. Both reference callbacks are required. Geometry may be null.
struct mobilegl_server_display_hooks {
void (*acquire)(void* user, void* window);
void (*release)(void* user, void* window);
mobilegl_server_geometry_callback request_geometry;
void* user;
};
enum mobilegl_server_display_result {
MOBILEGL_SERVER_DISPLAY_OK = 0,
MOBILEGL_SERVER_DISPLAY_INVALID_ARGUMENT = -1,
MOBILEGL_SERVER_DISPLAY_ALREADY_INSTALLED = -2,
MOBILEGL_SERVER_DISPLAY_NOT_INSTALLED = -3,
MOBILEGL_SERVER_DISPLAY_UNSUPPORTED_PLATFORM = -4
};
enum mobilegl_server_display_result {
MOBILEGL_SERVER_DISPLAY_OK = 0,
MOBILEGL_SERVER_DISPLAY_INVALID_ARGUMENT = -1,
MOBILEGL_SERVER_DISPLAY_ALREADY_INSTALLED = -2,
MOBILEGL_SERVER_DISPLAY_NOT_INSTALLED = -3,
MOBILEGL_SERVER_DISPLAY_UNSUPPORTED_PLATFORM = -4
};
enum mobilegl_server_window_detach {
MOBILEGL_SERVER_WINDOW_NO_WINDOW = 0,
MOBILEGL_SERVER_WINDOW_RELEASED = 1,
MOBILEGL_SERVER_WINDOW_RELEASED_BY_SESSION = 2,
MOBILEGL_SERVER_WINDOW_TIMED_OUT = 3
};
enum mobilegl_server_window_detach {
MOBILEGL_SERVER_WINDOW_NO_WINDOW = 0,
MOBILEGL_SERVER_WINDOW_RELEASED = 1,
MOBILEGL_SERVER_WINDOW_RELEASED_BY_SESSION = 2,
MOBILEGL_SERVER_WINDOW_TIMED_OUT = 3
};
// Install once before serving; owner lifecycle calls must be serialized. A live display or
// an old lease awaiting release refuses a replacement, so its window always uses its original
// reference hooks. The geometry callback runs on the apply thread and must return promptly.
// A positive size requests fixed buffer dimensions; 0/0 requests the host's layout dimensions.
// Report the resulting dimensions with attach, for example from SurfaceHolder.surfaceChanged.
// Callback user data must live until uninstall has returned and any timed-out lease has ended.
MOBILEGL_SERVER_EXPORT int mobilegl_server_display_install(const struct mobilegl_server_display_hooks* hooks);
MOBILEGL_SERVER_EXPORT int mobilegl_server_display_install_android(mobilegl_server_geometry_callback request_geometry,
void* user);
// Install once before serving; owner lifecycle calls must be serialized. A live display or
// an old lease awaiting release refuses a replacement, so its window always uses its original
// reference hooks. The geometry callback runs on the apply thread and must return promptly.
// A positive size requests fixed buffer dimensions; 0/0 requests the host's layout dimensions.
// Report the resulting dimensions with attach, for example from SurfaceHolder.surfaceChanged.
// Callback user data must live until uninstall has returned and any timed-out lease has ended.
MOBILEGL_SERVER_EXPORT int mobilegl_server_display_install(const struct mobilegl_server_display_hooks* hooks);
MOBILEGL_SERVER_EXPORT int mobilegl_server_display_install_android(
mobilegl_server_geometry_callback request_geometry, void* user);
// Attach retains its own reference. Attaching the same window updates its dimensions without
// another retain. A different window detaches the previous one first (up to 3 seconds).
// Android attach uses ANativeWindow_getWidth/Height for zero dimensions; the caller may release
// its ANativeWindow_fromSurface reference immediately after this call.
MOBILEGL_SERVER_EXPORT int mobilegl_server_display_attach(void* window, uint32_t width, uint32_t height);
MOBILEGL_SERVER_EXPORT int mobilegl_server_display_attach_android(struct ANativeWindow* window, uint32_t width,
uint32_t height);
// Attach retains its own reference. Attaching the same window updates its dimensions without
// another retain. A different window detaches the previous one first (up to 3 seconds).
// Android attach uses ANativeWindow_getWidth/Height for zero dimensions; the caller may release
// its ANativeWindow_fromSurface reference immediately after this call.
MOBILEGL_SERVER_EXPORT int mobilegl_server_display_attach(void* window, uint32_t width, uint32_t height);
MOBILEGL_SERVER_EXPORT int mobilegl_server_display_attach_android(struct ANativeWindow* window, uint32_t width,
uint32_t height);
// Returns mobilegl_server_window_detach. A timeout never drops a reference while the backend
// is rendering: release happens when the apply thread ends its lease. Surface loss currently
// ends the live split session; a fresh client session can use a newly attached window.
MOBILEGL_SERVER_EXPORT int mobilegl_server_display_detach(uint32_t timeout_ms);
MOBILEGL_SERVER_EXPORT int mobilegl_server_display_uninstall(uint32_t timeout_ms);
// Returns mobilegl_server_window_detach. A timeout never drops a reference while the backend
// is rendering: release happens when the apply thread ends its lease. Surface loss currently
// ends the live split session; a fresh client session can use a newly attached window.
MOBILEGL_SERVER_EXPORT int mobilegl_server_display_detach(uint32_t timeout_ms);
MOBILEGL_SERVER_EXPORT int mobilegl_server_display_uninstall(uint32_t timeout_ms);
// Blocking serve on the caller's thread; stop is non-blocking and safe on the UI thread.
// Endpoint: filesystem path, @abstract AF_UNIX name (SCM_RIGHTS + shared-memory rings), or
// tcp://host:port. One client session per process; independent workers need distinct endpoints.
// Before loading libMobileGL set MOBILEGL_IPC_ROLE=server and MOBILEGL_IPC_DIAL=no, and unset
// MOBILEGL_TRANSPORT, MOBILEGL_IPC_SERVER_PATH, MOBILEGL_IPC_RING_MB, MOBILEGL_IPC_STAGE_MB.
MOBILEGL_SERVER_EXPORT int mobilegl_server_serve_inprocess(const char* endpoint);
MOBILEGL_SERVER_EXPORT void mobilegl_server_stop_inprocess(void);
// Blocking serve on the caller's thread; stop is non-blocking and safe on the UI thread.
// Endpoint: filesystem path, @abstract AF_UNIX name (SCM_RIGHTS + shared-memory rings), or
// tcp://host:port. One client session per process; independent workers need distinct endpoints.
// Before loading libMobileGL set MOBILEGL_IPC_ROLE=server and MOBILEGL_IPC_DIAL=no, and unset
// MOBILEGL_TRANSPORT, MOBILEGL_IPC_SERVER_PATH, MOBILEGL_IPC_RING_MB, MOBILEGL_IPC_STAGE_MB.
MOBILEGL_SERVER_EXPORT int mobilegl_server_serve_inprocess(const char* endpoint);
MOBILEGL_SERVER_EXPORT void mobilegl_server_stop_inprocess(void);
#ifdef __cplusplus
}
+15 -14
View File
@@ -17,21 +17,22 @@
#pragma once
extern "C" {
extern "C"
{
// Serves `endpoint` on the CALLING thread until mobilegl_server_stop_inprocess is called and the
// live session (if any) has ended, then returns 0. The endpoint is tcp://host:port, or - for a
// same-device client - a unix @abstract name or filesystem path, whose control+data pair and
// SCM_RIGHTS shm segments make it the fastest on-device shape. Other returns, all logged by
// name: 64 / 65 (the environment preconditions above), 71 (empty endpoint), 72 (could not
// listen - EADDRINUSE is retried for up to ~5 s first, the previous server may still be dying),
// 73 (the listener failed), 74 (a server is already serving in this process). Re-callable after
// it returned.
__attribute__((visibility("default"))) int mobilegl_server_serve_inprocess(const char* endpoint);
// Serves `endpoint` on the CALLING thread until mobilegl_server_stop_inprocess is called and the
// live session (if any) has ended, then returns 0. The endpoint is tcp://host:port, or - for a
// same-device client - a unix @abstract name or filesystem path, whose control+data pair and
// SCM_RIGHTS shm segments make it the fastest on-device shape. Other returns, all logged by
// name: 64 / 65 (the environment preconditions above), 71 (empty endpoint), 72 (could not
// listen - EADDRINUSE is retried for up to ~5 s first, the previous server may still be dying),
// 73 (the listener failed), 74 (a server is already serving in this process). Re-callable after
// it returned.
__attribute__((visibility("default"))) int mobilegl_server_serve_inprocess(const char* endpoint);
// Asks the in-process server to stop and returns at once (it does not wait: call it from a UI
// thread). The live session ends within one control slice (~100 ms) - or when the op it is running
// returns (a ServerOwned wait for a window is interrupted too) - and then serve returns 0.
__attribute__((visibility("default"))) void mobilegl_server_stop_inprocess(void);
// Asks the in-process server to stop and returns at once (it does not wait: call it from a UI
// thread). The live session ends within one control slice (~100 ms) - or when the op it is running
// returns (a ServerOwned wait for a window is interrupted too) - and then serve returns 0.
__attribute__((visibility("default"))) void mobilegl_server_stop_inprocess(void);
} // extern "C"
+24 -23
View File
@@ -70,7 +70,8 @@ namespace MobileGL::MG_Remote::Server {
PairAcceptor::PairAcceptor(int listenFd, std::uint32_t budgetMs) : m_listener(listenFd), m_budgetMs(budgetMs) {}
PairAcceptor::~PairAcceptor() {
for (auto& waiting : m_waiting) Drop(waiting, true, kPairStopped);
for (auto& waiting : m_waiting)
Drop(waiting, true, kPairStopped);
for (const auto& pair : m_ready) {
RefuseAndClose(pair.first, Protocol::RefuseCode::Busy, kPairStopped);
::close(pair.second);
@@ -176,25 +177,25 @@ namespace MobileGL::MG_Remote::Server {
void PairAcceptor::Read(Waiting& waiting) {
switch (waiting.frame.Pump(waiting.fd)) {
case Step::NeedMore:
return;
case Step::Complete:
Judge(waiting);
return;
case Step::EndedEmpty:
// A readiness probe - a connect() and a close() - costs an accept and nothing else.
MGLOG_D("MG_Remote server: a connection closed before presenting a PairBind (a probe); dropped");
::close(waiting.fd);
waiting.fd = -1;
return;
case Step::NotAFrame:
RefuseAndClose(waiting.fd, Protocol::RefuseCode::MalformedHello, kFirstFrameNotAFrame);
waiting.fd = -1;
return;
case Step::EndedPartial:
RefuseAndClose(waiting.fd, Protocol::RefuseCode::MalformedHello, kFirstFrameTruncated);
waiting.fd = -1;
return;
case Step::NeedMore:
return;
case Step::Complete:
Judge(waiting);
return;
case Step::EndedEmpty:
// A readiness probe - a connect() and a close() - costs an accept and nothing else.
MGLOG_D("MG_Remote server: a connection closed before presenting a PairBind (a probe); dropped");
::close(waiting.fd);
waiting.fd = -1;
return;
case Step::NotAFrame:
RefuseAndClose(waiting.fd, Protocol::RefuseCode::MalformedHello, kFirstFrameNotAFrame);
waiting.fd = -1;
return;
case Step::EndedPartial:
RefuseAndClose(waiting.fd, Protocol::RefuseCode::MalformedHello, kFirstFrameTruncated);
waiting.fd = -1;
return;
}
}
@@ -281,9 +282,9 @@ namespace MobileGL::MG_Remote::Server {
}
void PairAcceptor::Compact() {
m_waiting.erase(std::remove_if(m_waiting.begin(), m_waiting.end(),
[](const Waiting& waiting) { return waiting.fd < 0; }),
m_waiting.end());
m_waiting.erase(
std::remove_if(m_waiting.begin(), m_waiting.end(), [](const Waiting& waiting) { return waiting.fd < 0; }),
m_waiting.end());
}
} // namespace MobileGL::MG_Remote::Server
+2 -2
View File
@@ -96,8 +96,8 @@ namespace MobileGL::MG_Remote::Server {
int m_listener;
std::uint32_t m_budgetMs;
std::vector<Waiting> m_waiting; // accept order, oldest first
std::deque<std::pair<int, int>> m_ready; // {control, aux}, not yet handed out
std::vector<Waiting> m_waiting; // accept order, oldest first
std::deque<std::pair<int, int>> m_ready; // {control, aux}, not yet handed out
Clock::time_point m_acceptResumeAt{};
};
+70 -50
View File
@@ -96,7 +96,9 @@ namespace MobileGL::MG_Remote::Server {
++m_posted;
}
Uint32 ReplyPool::SlotBytes() const { return m_slotBytes; }
Uint32 ReplyPool::SlotBytes() const {
return m_slotBytes;
}
// -----------------------------------------------------------------------------------
// ServerVerbSink - the five class-B verbs
@@ -109,8 +111,7 @@ namespace MobileGL::MG_Remote::Server {
ServerVerbSink::FenceEntry& ServerVerbSink::FindFence(MG_Pipe::MGPipeHandle handle) {
const auto it = m_fences.find(handle.Slot);
if (handle.Slot == 0 || it == m_fences.end() ||
!it->second.Live || it->second.Gen != handle.Gen) {
if (handle.Slot == 0 || it == m_fences.end() || !it->second.Live || it->second.Gen != handle.Gen) {
Wire::WireProtocolFatal("Fence.handle", "missing, destroyed or stale fence handle");
}
return it->second;
@@ -163,8 +164,7 @@ namespace MobileGL::MG_Remote::Server {
auto& entry = FindFence(desc.Handle);
const auto* table = Table("FenceStatus");
if (table == nullptr) return false;
result = entry.Native == nullptr || table->GL.GetSyncStatus == nullptr ||
table->GL.GetSyncStatus(entry.Native);
result = entry.Native == nullptr || table->GL.GetSyncStatus == nullptr || table->GL.GetSyncStatus(entry.Native);
return true;
}
@@ -296,10 +296,11 @@ namespace MobileGL::MG_Remote::Server {
if (present.FrameSerial == 0 && MGPipeServerPublishesRunAhead()) {
// PH-1 (3): latches in an armed session child - no credit is returned for it, the
// session closes and the peer's credit wait ends on the hang-up.
return SessionLatch(MGFatalFamily::ProtocolCorruption, "MGPipe: Fatal{ProtocolCorruption, \"Present.FrameSerial\"} - a run-ahead "
"server was handed present serial 0. The client mints this 1-based and "
"waits on it for its credit (CONTRACT-P5E §2.4); returning a credit for "
"serial 0 would release a wait that is asking about frame N");
return SessionLatch(MGFatalFamily::ProtocolCorruption,
"MGPipe: Fatal{ProtocolCorruption, \"Present.FrameSerial\"} - a run-ahead "
"server was handed present serial 0. The client mints this 1-based and "
"waits on it for its credit (CONTRACT-P5E §2.4); returning a credit for "
"serial 0 would release a wait that is asking about frame N");
}
m_lastPresentSerial = present.FrameSerial != 0 ? present.FrameSerial : m_presents;
// §2.4's other half, and the reason ServerSession::ReturnPresentCredit has had no
@@ -335,12 +336,13 @@ namespace MobileGL::MG_Remote::Server {
// about how many make-current edges have crossed, which no backend answer can fix.
// PH-1 (3): latches in an armed session child (the peer wrote the serial); dies unarmed.
if (reset.ContextSerial != m_applierResetSerial) {
return SessionLatch(MGFatalFamily::ProtocolCorruption, "MGPipe: Fatal{ProtocolCorruption, \"ApplierReset.ContextSerial\"} - the "
"record carries %llu and this session has accepted %llu reset(s); the "
"serial is asserted against the session's own count, not dispatched on "
"(one context per session in P5c)",
static_cast<unsigned long long>(reset.ContextSerial),
static_cast<unsigned long long>(m_applierResetSerial));
return SessionLatch(MGFatalFamily::ProtocolCorruption,
"MGPipe: Fatal{ProtocolCorruption, \"ApplierReset.ContextSerial\"} - the "
"record carries %llu and this session has accepted %llu reset(s); the "
"serial is asserted against the session's own count, not dispatched on "
"(one context per session in P5c)",
static_cast<unsigned long long>(reset.ContextSerial),
static_cast<unsigned long long>(m_applierResetSerial));
}
++m_applierResetSerial;
// THE WHOLE POINT OF THE RECORD: the reset runs HERE, on the apply thread, against
@@ -357,7 +359,9 @@ namespace MobileGL::MG_Remote::Server {
return *this;
}
ServerVerbSink::OwnedFd::~OwnedFd() { Reset(-1); }
ServerVerbSink::OwnedFd::~OwnedFd() {
Reset(-1);
}
void ServerVerbSink::OwnedFd::Reset(int next) {
#if !defined(_WIN32)
@@ -521,7 +525,8 @@ namespace MobileGL::MG_Remote::Server {
case MG_Pipe::kMGPSharedImageQueryBufferAge: {
MG_Backend::BackendObject* backend = ServerLoopInstance().Backend();
if (backend == nullptr) return false;
reply.BufferAge = backend->QueryCurrentBufferAge((op.Format & MG_Pipe::kMGPBufferAgeDamageRegionFollows) != 0);
reply.BufferAge =
backend->QueryCurrentBufferAge((op.Format & MG_Pipe::kMGPBufferAgeDamageRegionFollows) != 0);
return true;
}
case MG_Pipe::kMGPSharedImageSetDamageRegion: {
@@ -596,11 +601,12 @@ namespace MobileGL::MG_Remote::Server {
// 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));
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
@@ -634,22 +640,24 @@ namespace MobileGL::MG_Remote::Server {
// not a no-op.
// PH-1 (3): both refusals latch in an armed session child; unarmed they die as before.
if (MG_Pipe::MGPipeHandleIsNull(death.Handle)) {
return SessionLatch(MGFatalFamily::ProtocolCorruption, "MGPipe: Fatal{ProtocolCorruption, \"ObjectDeath.Handle\"} - a null "
"handle never crosses: the client emits nothing for an object its own "
"allocator cannot resolve (CONTRACT-P5C.md §5.2)");
return SessionLatch(MGFatalFamily::ProtocolCorruption,
"MGPipe: Fatal{ProtocolCorruption, \"ObjectDeath.Handle\"} - a null "
"handle never crosses: the client emits nothing for an object its own "
"allocator cannot resolve (CONTRACT-P5C.md §5.2)");
}
if (death.Kind >= static_cast<Uint32>(MG_Pipe::MGPipeKind::KindCount)) {
return SessionLatch(MGFatalFamily::ProtocolCorruption, "MGPipe: Fatal{ProtocolCorruption, \"ObjectDeath.Kind\"} - %u is not an "
"MGPipeKind",
static_cast<unsigned>(death.Kind));
return SessionLatch(MGFatalFamily::ProtocolCorruption,
"MGPipe: Fatal{ProtocolCorruption, \"ObjectDeath.Kind\"} - %u is not an "
"MGPipeKind",
static_cast<unsigned>(death.Kind));
}
// The per-kind release, keyed by the handle the record carried. A false answer is
// NOT a decline: the kind's own delete opcode may already have released the twin
// (the idempotent second path every notice arm documents), and a kind this backend
// does not twin (Buffer, whose death crosses as resource_destroy) legally resolves
// to nothing.
MG_Backend::DirectGLES::ReleaseTwinsForWireObjectDeath(
death.Handle, static_cast<MG_Pipe::MGPipeKind>(death.Kind));
MG_Backend::DirectGLES::ReleaseTwinsForWireObjectDeath(death.Handle,
static_cast<MG_Pipe::MGPipeKind>(death.Kind));
++m_objectDeaths;
return true;
}
@@ -663,19 +671,22 @@ namespace MobileGL::MG_Remote::Server {
void PipeApplier::Attach(Transport::ILink* link, MG_Backend::BackendObject* backend) {
if (!link || !link->Attached() || !m_segments)
SessionFail(MGFatalFamily::ProtocolCorruption, "MGPipe: Fatal{ProtocolCorruption, PipeApplier::Attach missing link}");
SessionFail(MGFatalFamily::ProtocolCorruption,
"MGPipe: Fatal{ProtocolCorruption, PipeApplier::Attach missing link}");
m_verbs.SetBackend(backend);
m_verbs.SetMaxReplyBytes(link->Capabilities().MaxReplyBytes);
m_decoder = Wire::PipeWireDecoder(link, m_segments, m_replies);
m_decoder.SetVerbSink(&m_verbs);
MG_Pipe::MGPipeServerBlockNoteIdentity(); m_attached = true;
MG_Pipe::MGPipeServerBlockNoteIdentity();
m_attached = true;
}
void PipeApplier::Attach(Transport::RingControl* control, MG_Backend::BackendObject* backend) {
if (control == nullptr || m_segments == nullptr) {
SessionFail(MGFatalFamily::ProtocolCorruption, "MGPipe: Fatal{ProtocolCorruption, \"PipeApplier::Attach\"} - no control "
"page or no segment table; ServerSession::Accept builds both before the "
"apply thread starts");
SessionFail(MGFatalFamily::ProtocolCorruption,
"MGPipe: Fatal{ProtocolCorruption, \"PipeApplier::Attach\"} - no control "
"page or no segment table; ServerSession::Accept builds both before the "
"apply thread starts");
}
m_verbs.SetBackend(backend);
m_decoder = Wire::PipeWireDecoder(control, m_segments, m_replies);
@@ -695,13 +706,16 @@ namespace MobileGL::MG_Remote::Server {
m_attached = false;
}
Bool PipeApplier::Attached() const { return m_attached; }
Bool PipeApplier::Attached() const {
return m_attached;
}
Bool PipeApplier::ApplyOne(const Transport::RingRecordView& record) {
if (!m_attached) {
SessionFail(MGFatalFamily::ProtocolCorruption, "MGPipe: Fatal{ProtocolCorruption, \"PipeApplier::ApplyOne before Attach\"} "
"- a record reached the applier with no decoder; the apply thread calls "
"Attach once before its first pop");
SessionFail(MGFatalFamily::ProtocolCorruption,
"MGPipe: Fatal{ProtocolCorruption, \"PipeApplier::ApplyOne before Attach\"} "
"- a record reached the applier with no decoder; the apply thread calls "
"Attach once before its first pop");
}
// R-1's INVARIANT, THE SERVER'S HALF (table 3's gPipeInputs row, c1-v1 8.1). The flag
// is raised for the WHOLE of this function and not only around DecodeAndApply: the
@@ -720,11 +734,10 @@ namespace MobileGL::MG_Remote::Server {
// 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());
MG_Pipe::MGPipeApplierSetCurrentRecordBarriered(
MGPipeApplierStampsBarriered(MG_Pipe::kMGPipeP5eClientWaitRuleLanded,
MGPipeServerPublishesRunAhead(), wireSaysBarriered));
const Bool wireSaysBarriered = MG_Pipe::MGPipeBarriered(static_cast<MG_Pipe::MGPWireOp>(record.kind),
record.payload, MG_Pipe::MGPipeApplier());
MG_Pipe::MGPipeApplierSetCurrentRecordBarriered(MGPipeApplierStampsBarriered(
MG_Pipe::kMGPipeP5eClientWaitRuleLanded, MGPipeServerPublishesRunAhead(), wireSaysBarriered));
// P5e (gl), ID-128: AND WHETHER IT WAS BARRIERED BY ESCALATION RATHER THAN BY ITS CLASS.
// The predicate above is the static wait class plus two payload-derived escalations
// (ID-83: an open transform-feedback span, a draw carrying client vertex arrays), so the
@@ -734,8 +747,7 @@ namespace MobileGL::MG_Remote::Server {
// client arrays (ID-82) owes, neither of which is this one.
MG_Pipe::MGPipeApplierSetCurrentRecordBarrieredByEscalation(
wireSaysBarriered &&
MG_Pipe::MGPipeWaitClassFor(static_cast<MG_Pipe::MGPWireOp>(record.kind)) ==
MG_Pipe::kWaitNone);
MG_Pipe::MGPipeWaitClassFor(static_cast<MG_Pipe::MGPWireOp>(record.kind)) == MG_Pipe::kWaitNone);
// ORDER IS THE CONTRACT'S: stamp, then apply. The stamp is what makes any server-side
// read of gPipeInputs legal at all (PipeApplier.h's block 1), so a record applied
// before it aborts on the FIRST field inside SyncRenderState.
@@ -764,9 +776,13 @@ namespace MobileGL::MG_Remote::Server {
MG_Pipe::MGPipeServerStampVerbBoundary(verb);
}
void PipeApplier::LeaveApplier() { MG_Pipe::MGPipeServerClearVerbBoundary(); }
void PipeApplier::LeaveApplier() {
MG_Pipe::MGPipeServerClearVerbBoundary();
}
Uint64 PipeApplier::ResidualPullCount() const { return MG_Pipe::MGPipeResidualPullCount(); }
Uint64 PipeApplier::ResidualPullCount() const {
return MG_Pipe::MGPipeResidualPullCount();
}
// The decoder poisons EXACTLY the runs it resolved, from inside DecodeAndApply, once the
// applier has returned - so this entry point is the manual one, for a caller that knows a
@@ -783,8 +799,12 @@ namespace MobileGL::MG_Remote::Server {
std::memset(const_cast<void*>(run), 0xDD, static_cast<SizeT>(size));
}
Uint64 PipeApplier::PoisonedStageBytes() const { return m_decoder.PoisonedStageBytes(); }
Uint64 PipeApplier::PoisonedStageBytes() const {
return m_decoder.PoisonedStageBytes();
}
Uint64 PipeApplier::DecoderAppliedSeq() const { return m_decoder.AppliedSeq(); }
Uint64 PipeApplier::DecoderAppliedSeq() const {
return m_decoder.AppliedSeq();
}
} // namespace MobileGL::MG_Remote::Server
+1 -2
View File
@@ -47,8 +47,7 @@ namespace MobileGL::MG_Remote::Server {
// 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,
constexpr Bool MGPipeApplierStampsBarriered(Bool clientWaitRuleLanded, Bool serverPublishesRunAhead,
Bool wireSaysBarriered) {
return (clientWaitRuleLanded && serverPublishesRunAhead) ? wireSaysBarriered : true;
}
+28 -12
View File
@@ -70,7 +70,8 @@ namespace MobileGL::MG_Remote::Server {
inline constexpr const char* kFirstFrameBadDataBind = "first frame is a DataBind without a 16-byte nonce";
inline constexpr const char* kPreAuthDeadline = "no authenticated first frame within the pre-auth deadline";
inline constexpr const char* kPreAuthFull = "too many connections are awaiting authentication";
inline constexpr const char* kPreAuthDisplaced = "displaced from the pre-auth queue by a connection from another address";
inline constexpr const char* kPreAuthDisplaced =
"displaced from the pre-auth queue by a connection from another address";
inline constexpr const char* kAuthBackoffRefusal = "too many failed authentications from this address; retry later";
struct PreAuthKnobs {
@@ -118,7 +119,14 @@ namespace MobileGL::MG_Remote::Server {
// verify", and a peer speaking some other schema deserves the specific answer. msg_as_Hello()
// and msg_as_DataBind() are part of the guard, not consequences of it: flatbuffers verifies a
// NULL union member as valid, so a 24-byte envelope whose tag says Hello carries no Hello.
enum class FirstFrameShape { NoIdentifier, Unverifiable, Hello, DataBind, BadDataBind, NotAHello };
enum class FirstFrameShape {
NoIdentifier,
Unverifiable,
Hello,
DataBind,
BadDataBind,
NotAHello
};
inline FirstFrameShape ClassifyFirstFrame(const std::uint8_t* payload, std::size_t size) {
if (payload == nullptr || size < 8 || !::MobileGL::Wire::CtrlEnvelopeBufferHasIdentifier(payload))
@@ -128,8 +136,7 @@ namespace MobileGL::MG_Remote::Server {
const auto* envelope = ::MobileGL::Wire::GetCtrlEnvelope(payload);
if (envelope->msg_type() == ::MobileGL::Wire::CtrlMsg::DataBind) {
const auto* bind = envelope->msg_as_DataBind();
return bind != nullptr && bind->nonce() != nullptr &&
bind->nonce()->size() == Transport::kDataNonceBytes
return bind != nullptr && bind->nonce() != nullptr && bind->nonce()->size() == Transport::kDataNonceBytes
? FirstFrameShape::DataBind
: FirstFrameShape::BadDataBind;
}
@@ -142,12 +149,17 @@ namespace MobileGL::MG_Remote::Server {
// shapes that are not malformed.
inline const char* FirstFrameRefusalDetail(FirstFrameShape shape) {
switch (shape) {
case FirstFrameShape::NoIdentifier: return kFirstFrameNoIdentifier;
case FirstFrameShape::Unverifiable: return kFirstFrameUnverifiable;
case FirstFrameShape::BadDataBind: return kFirstFrameBadDataBind;
case FirstFrameShape::NotAHello: return kFirstFrameNotAHello;
case FirstFrameShape::Hello:
case FirstFrameShape::DataBind: return nullptr;
case FirstFrameShape::NoIdentifier:
return kFirstFrameNoIdentifier;
case FirstFrameShape::Unverifiable:
return kFirstFrameUnverifiable;
case FirstFrameShape::BadDataBind:
return kFirstFrameBadDataBind;
case FirstFrameShape::NotAHello:
return kFirstFrameNotAHello;
case FirstFrameShape::Hello:
case FirstFrameShape::DataBind:
return nullptr;
}
return kFirstFrameNotAHello;
}
@@ -166,7 +178,8 @@ namespace MobileGL::MG_Remote::Server {
inline std::size_t ChoosePendingToDisplace(const std::vector<std::string>& pending, const std::string& newcomer) {
std::unordered_map<std::string, std::size_t> held;
std::size_t most = 0;
for (const auto& address : pending) most = std::max(most, ++held[address]);
for (const auto& address : pending)
most = std::max(most, ++held[address]);
const auto own = held.find(newcomer);
if (own != held.end() && own->second >= most) return pending.size();
for (std::size_t index = 0; index < pending.size(); ++index)
@@ -238,7 +251,10 @@ namespace MobileGL::MG_Remote::Server {
auto victim = m_peers.end();
for (auto it = m_peers.begin(); it != m_peers.end(); ++it) {
const bool expired = it->second.until <= now;
if (victim == m_peers.end()) { victim = it; continue; }
if (victim == m_peers.end()) {
victim = it;
continue;
}
const bool victimExpired = victim->second.until <= now;
if (expired != victimExpired) {
if (expired) victim = it;
+27 -19
View File
@@ -32,22 +32,32 @@ namespace MobileGL::MG_Remote::Server {
const char* ServerWindowAcquireName(ServerWindowAcquire result) {
switch (result) {
case ServerWindowAcquire::Acquired: return "Acquired";
case ServerWindowAcquire::NoDisplay: return "NoDisplay";
case ServerWindowAcquire::NoWindow: return "NoWindow";
case ServerWindowAcquire::Cancelled: return "Cancelled";
case ServerWindowAcquire::Interrupted: return "Interrupted";
case ServerWindowAcquire::LeasedElsewhere: return "LeasedElsewhere";
case ServerWindowAcquire::Acquired:
return "Acquired";
case ServerWindowAcquire::NoDisplay:
return "NoDisplay";
case ServerWindowAcquire::NoWindow:
return "NoWindow";
case ServerWindowAcquire::Cancelled:
return "Cancelled";
case ServerWindowAcquire::Interrupted:
return "Interrupted";
case ServerWindowAcquire::LeasedElsewhere:
return "LeasedElsewhere";
}
return "<unknown ServerWindowAcquire>";
}
const char* ServerWindowDetachName(ServerWindowDetach result) {
switch (result) {
case ServerWindowDetach::NoWindow: return "NoWindow";
case ServerWindowDetach::Released: return "Released";
case ServerWindowDetach::ReleasedBySession: return "ReleasedBySession";
case ServerWindowDetach::TimedOut: return "TimedOut";
case ServerWindowDetach::NoWindow:
return "NoWindow";
case ServerWindowDetach::Released:
return "Released";
case ServerWindowDetach::ReleasedBySession:
return "ReleasedBySession";
case ServerWindowDetach::TimedOut:
return "TimedOut";
}
return "<unknown ServerWindowDetach>";
}
@@ -164,8 +174,8 @@ namespace MobileGL::MG_Remote::Server {
m_lostRequested = true;
if (m_onLost != nullptr) m_onLost(m_leaseHolder);
}
const Bool released = m_cv.wait_for(lock, std::chrono::milliseconds(timeoutMs),
[this] { return m_leaseHolder == nullptr; });
const Bool released =
m_cv.wait_for(lock, std::chrono::milliseconds(timeoutMs), [this] { return m_leaseHolder == nullptr; });
if (!released) {
// NOT RELEASED UNDER IT. The holder may still reference the window (Magma keeps the
// raw pointer until the swapchain is built), so the reference stays until it ends
@@ -265,11 +275,10 @@ namespace MobileGL::MG_Remote::Server {
m_lostRequested = false;
m_leaseEnding = false;
// A suspended holder that leased a window again waits for no other.
m_suspended.erase(std::remove_if(m_suspended.begin(), m_suspended.end(),
[holder](const SuspendedHolder& entry) {
return entry.holder == holder;
}),
m_suspended.end());
m_suspended.erase(
std::remove_if(m_suspended.begin(), m_suspended.end(),
[holder](const SuspendedHolder& entry) { return entry.holder == holder; }),
m_suspended.end());
if (out != nullptr) {
out->window = m_window;
out->width = m_width;
@@ -322,8 +331,7 @@ namespace MobileGL::MG_Remote::Server {
void ServerDisplay::ReleaseAfterLease(const ServerDisplayHooks& hooks, const std::vector<void*>& releases) const {
for (void* window : releases) {
ReleaseOutsideLock(hooks, window);
MGLOG_I("MG_Remote server: server window %p released after its session let go (a late Detach)",
window);
MGLOG_I("MG_Remote server: server window %p released after its session let go (a late Detach)", window);
}
}
+7 -8
View File
@@ -48,7 +48,7 @@ namespace MobileGL::MG_Remote::Server {
struct ServerWindowLease {
void* window = nullptr;
Uint32 width = 0; // the window's extent when the lease was taken
Uint32 width = 0; // the window's extent when the lease was taken
Uint32 height = 0;
Uint64 generation = 0;
// False when a size was requested and the window had not reached it within the geometry
@@ -58,10 +58,10 @@ namespace MobileGL::MG_Remote::Server {
enum class ServerWindowAcquire : Uint8 {
Acquired,
NoDisplay, // this process owns no display (HasDisplay() is false)
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)
NoDisplay, // this process owns no display (HasDisplay() is false)
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)
// 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. A holder
@@ -115,9 +115,8 @@ namespace MobileGL::MG_Remote::Server {
// may lease again while it holds the lease (a surface re-created at a new size). `onResized`, when
// given, is called whenever the leased window changes size while the lease lasts.
ServerWindowAcquire AcquireFor(Uint32 width, Uint32 height, Uint32 timeoutMs, void* holder,
ServerWindowLostHook onLost, ServerWindowWaitCancel cancel,
void* cancelUser, ServerWindowLease* out,
ServerWindowResizedHook onResized = nullptr);
ServerWindowLostHook onLost, ServerWindowWaitCancel cancel, void* cancelUser,
ServerWindowLease* out, ServerWindowResizedHook onResized = nullptr);
// THE WINDOW'S EXTENT AS THE PLATFORM LAST REPORTED IT (surfaceCreated / surfaceChanged): the one
// source of truth for the size a session publishes to its client. False unless `holder` holds
// the lease on an attached window.
+3 -1
View File
@@ -16,4 +16,6 @@
extern "C" int mobilegl_server_main(int argc, char** argv);
int main(int argc, char** argv) { return mobilegl_server_main(argc, argv); }
int main(int argc, char** argv) {
return mobilegl_server_main(argc, argv);
}
+140 -121
View File
@@ -148,7 +148,9 @@ namespace MobileGL::MG_Remote::Server {
// resolves ServerLoopInstance to that session's loop): a session that latched is over, and
// its lease on the server window, if it holds one, ends once its apply thread has torn the
// backend down - which a fresh session of the same client waits for (MarkLeaseEnding).
void MarkLatchedSessionsLeaseEnding() { ServerDisplayInstance().MarkLeaseEnding(&ServerLoopInstance()); }
void MarkLatchedSessionsLeaseEnding() {
ServerDisplayInstance().MarkLeaseEnding(&ServerLoopInstance());
}
// The bounded join. InProcessTransportTest.cpp:344 uses five seconds for the same
// reason: a lost wakeup must be a RED TEST and not a hung CI job.
@@ -174,8 +176,7 @@ namespace MobileGL::MG_Remote::Server {
Uint64 ReadCpuMaxFrequencyKHz(const Uint cpu) {
char path[128];
std::snprintf(path, sizeof(path),
"/sys/devices/system/cpu/cpu%u/cpufreq/cpuinfo_max_freq", cpu);
std::snprintf(path, sizeof(path), "/sys/devices/system/cpu/cpu%u/cpufreq/cpuinfo_max_freq", cpu);
std::FILE* file = std::fopen(path, "r");
if (file == nullptr) return 0;
unsigned long long value = 0;
@@ -199,7 +200,8 @@ namespace MobileGL::MG_Remote::Server {
if (frequencies[cpu] == 0) return;
}
Uint64 peak = 0;
for (Uint cpu = 0; cpu < cpuCount; ++cpu) peak = std::max(peak, frequencies[cpu]);
for (Uint cpu = 0; cpu < cpuCount; ++cpu)
peak = std::max(peak, frequencies[cpu]);
if (peak == 0) return;
const Uint64 threshold = peak * kBigCoreFrequencyPercent / 100;
for (Uint cpu = 0; cpu < cpuCount; ++cpu) {
@@ -387,7 +389,9 @@ namespace MobileGL::MG_Remote::Server {
return MOBILEGL_OK;
}
MG_Backend::BackendObject* ServerLoop::Backend() { return m_backend.get(); }
MG_Backend::BackendObject* ServerLoop::Backend() {
return m_backend.get();
}
MobileGLResult ServerLoop::InstallBackendForTesting(UniquePtr<MG_Backend::BackendObject> backend) {
if (m_backend != nullptr || backend == nullptr || m_running.load(std::memory_order_acquire)) {
@@ -463,20 +467,30 @@ namespace MobileGL::MG_Remote::Server {
return MOBILEGL_OK;
}
Bool ServerLoop::Running() const { return m_running.load(std::memory_order_acquire); }
Bool ServerLoop::Running() const {
return m_running.load(std::memory_order_acquire);
}
// OnApplyThread() is inline in the header now (P5d round 3, package D). Its whole body is
// one relaxed load of Detail::g_applyThreadKey and one comparison against the caller's own
// thread pointer; the two writes to that key are in ApplyThreadMain, below.
Uint64 ServerLoop::ResolvedAffinityMask() const { return m_affinityMask; }
Uint64 ServerLoop::DrainedRecords() const { return m_drained.load(std::memory_order_acquire); }
Uint64 ServerLoop::ParkCount() const { return m_parks.load(std::memory_order_acquire); }
Uint64 ServerLoop::ResolvedAffinityMask() const {
return m_affinityMask;
}
Uint64 ServerLoop::DrainedRecords() const {
return m_drained.load(std::memory_order_acquire);
}
Uint64 ServerLoop::ParkCount() const {
return m_parks.load(std::memory_order_acquire);
}
Uint64 ServerLoop::ParkBlockCount() const {
return m_parkBlocks.load(std::memory_order_relaxed);
}
Uint64 ServerLoop::NativeBindCount() const { return m_nativeBinds.load(std::memory_order_acquire); }
Uint64 ServerLoop::NativeBindCount() const {
return m_nativeBinds.load(std::memory_order_acquire);
}
Uint64 ServerLoop::ClientReleaseCount() const {
return m_clientReleases.load(std::memory_order_acquire);
}
@@ -491,9 +505,9 @@ namespace MobileGL::MG_Remote::Server {
// test in BackendObject_DirectGLES.cpp) is a ClientRelease the server records but does not
// forward. Otherwise an identical (dpy, draw, read, ctx) already held is a RepeatNoOp, and
// anything else is a real NativeBind. Pure: a unit case drives it with no EGL context.
EglBindAction ClassifyEglMakeCurrent(Bool haveCurrent, EGLDisplay curDpy, EGLSurface curDraw,
EGLSurface curRead, EGLContext curCtx, EGLDisplay dpy,
EGLSurface draw, EGLSurface read, EGLContext ctx) {
EglBindAction ClassifyEglMakeCurrent(Bool haveCurrent, EGLDisplay curDpy, EGLSurface curDraw, EGLSurface curRead,
EGLContext curCtx, EGLDisplay dpy, EGLSurface draw, EGLSurface read,
EGLContext ctx) {
if (draw == EGL_NO_SURFACE && read == EGL_NO_SURFACE && ctx == EGL_NO_CONTEXT) {
return EglBindAction::ClientRelease;
}
@@ -503,9 +517,8 @@ namespace MobileGL::MG_Remote::Server {
return EglBindAction::NativeBind;
}
ServerLoop::MakeCurrentOutcome ServerLoop::ApplyMakeCurrent(MG_Backend::BackendObject* backend,
EGLDisplay dpy, EGLSurface draw,
EGLSurface read, EGLContext ctx) {
ServerLoop::MakeCurrentOutcome ServerLoop::ApplyMakeCurrent(MG_Backend::BackendObject* backend, EGLDisplay dpy,
EGLSurface draw, EGLSurface read, EGLContext ctx) {
// 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.
@@ -515,8 +528,8 @@ namespace MobileGL::MG_Remote::Server {
// 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);
const EglBindAction action =
ClassifyEglMakeCurrent(m_haveCurrentTuple, m_curDpy, m_curDraw, m_curRead, m_curCtx, dpy, draw, read, ctx);
switch (action) {
case EglBindAction::ClientRelease:
// Recorded, NOT forwarded (ID-54): the context stays current on this thread until
@@ -694,9 +707,7 @@ namespace MobileGL::MG_Remote::Server {
// would park this thread inside the post, and the ring test below already says "not now".
ServerVerbSink& verbs = session.Applier().Verbs();
constexpr Uint32 kFenceIdlePollMs = 1;
const auto eventRingHasRoom = [signals] {
return signals.EventRingFull->load(std::memory_order_acquire) == 0;
};
const auto eventRingHasRoom = [signals] { return signals.EventRingFull->load(std::memory_order_acquire) == 0; };
for (;;) {
std::optional<ScopedBackendTurn> turn(std::in_place);
@@ -779,8 +790,7 @@ namespace MobileGL::MG_Remote::Server {
const Bool fencePending = verbs.HasUnreportedFences();
m_applyParked.store(true, std::memory_order_release);
const bool woke = bell.Wait(*signals.ConsumerParked, ready, spinUs,
fencePending ? kFenceIdlePollMs : Transport::kWaitForever,
&m_parkBlocks);
fencePending ? kFenceIdlePollMs : Transport::kWaitForever, &m_parkBlocks);
m_applyParked.store(false, std::memory_order_release);
if (!woke) {
// Wait returns false only on a dead bell or an expired deadline. A dead bell IS the
@@ -994,14 +1004,15 @@ namespace MobileGL::MG_Remote::Server {
// frame's reply half; the reply is then published back into the slot under the lock so
// the poster's copy-out after m_controlDone sees it.
const auto dispatchStart = std::chrono::steady_clock::now();
const MobileGLResult result = ApplySurfaceControlFrame(
frame, m_controlProbeHook.load(std::memory_order_acquire),
m_controlProbeUser.load(std::memory_order_acquire));
const MobileGLResult result =
ApplySurfaceControlFrame(frame, m_controlProbeHook.load(std::memory_order_acquire),
m_controlProbeUser.load(std::memory_order_acquire));
// p7/spawnhang: A SLOW DISPATCH NAMES ITSELF. The first surface creation / MakeCurrent is
// where a lazy native bring-up runs, and on a cold CI runner it outran the client's whole
// reply budget with nothing in this log to say so - the investigation had to infer it.
const auto dispatchMs = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now() - dispatchStart).count();
const auto dispatchMs =
std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - dispatchStart)
.count();
if (dispatchMs >= static_cast<long long>(kSlowControlDispatchMs)) {
MGLOG_W("MG_Remote server: %s seq %llu ran %lld ms on mgl-srv-apply (a lazy native "
"bring-up runs inside the first surface creation or MakeCurrent)",
@@ -1108,8 +1119,8 @@ namespace MobileGL::MG_Remote::Server {
// report - used to be popped and applied unpolled, and a GUILTY context ran one more record
// (ServerLoopEglLatchTest under CPU load). `polledHead` is the command ring's head as loaded
// just BEFORE the last poll (the apply loop's own, handed in): every record below it was
// visible when that poll ran. A record at or past it re-loads the head and polls first. While the client stays ahead this is one
// poll per batch the drain catches up to, never more than one per record.
// visible when that poll ran. A record at or past it re-loads the head and polls first. While the client stays
// ahead this is one poll per batch the drain catches up to, never more than one per record.
Transport::LinkSignals signals{};
if (auto* link = session.DataLink()) signals = link->Signals();
for (;;) {
@@ -1141,10 +1152,10 @@ namespace MobileGL::MG_Remote::Server {
if (timed) {
const auto applyStarted = std::chrono::steady_clock::now();
applier.ApplyOne(record);
sFrameApplyNs += static_cast<std::uint64_t>(
std::chrono::duration_cast<std::chrono::nanoseconds>(
std::chrono::steady_clock::now() - applyStarted)
.count());
sFrameApplyNs +=
static_cast<std::uint64_t>(std::chrono::duration_cast<std::chrono::nanoseconds>(
std::chrono::steady_clock::now() - applyStarted)
.count());
} else {
applier.ApplyOne(record);
}
@@ -1154,8 +1165,7 @@ namespace MobileGL::MG_Remote::Server {
if (record.kind == static_cast<std::uint16_t>(MG_Pipe::MGPWireOp::Present)) {
const auto now = std::chrono::steady_clock::now();
const auto wallNs = static_cast<std::uint64_t>(
std::chrono::duration_cast<std::chrono::nanoseconds>(now - sFrameWallStart)
.count());
std::chrono::duration_cast<std::chrono::nanoseconds>(now - sFrameWallStart).count());
const double applyMs = static_cast<double>(sFrameApplyNs) / 1e6;
const double wallMs = static_cast<double>(wallNs) / 1e6;
// AND THE STAGE NOTHING ELSE COVERS: the io thread's socket reads, which
@@ -1170,16 +1180,14 @@ namespace MobileGL::MG_Remote::Server {
"outside_ms=%.1f | read: %llu B in %llu recv(%llu reads) "
"recv_ms=%.1f total_ms=%.1f (%.0f%% blocked, %.1f MB/s)",
static_cast<unsigned long long>(++sFrameIndex),
static_cast<unsigned long long>(sFrameRecords), applyMs, wallMs,
wallMs - applyMs,
static_cast<unsigned long long>(sFrameRecords), applyMs, wallMs, wallMs - applyMs,
static_cast<unsigned long long>(read.bytes),
static_cast<unsigned long long>(read.calls),
static_cast<unsigned long long>(read.reads),
static_cast<double>(read.nsInRecv) / 1e6,
static_cast<double>(read.nsTotal) / 1e6,
read.nsTotal ? 100.0 * static_cast<double>(read.nsInRecv) /
static_cast<double>(read.nsTotal)
: 0.0,
static_cast<double>(read.nsInRecv) / 1e6, static_cast<double>(read.nsTotal) / 1e6,
read.nsTotal
? 100.0 * static_cast<double>(read.nsInRecv) / static_cast<double>(read.nsTotal)
: 0.0,
read.nsTotal ? static_cast<double>(read.bytes) /
(static_cast<double>(read.nsTotal) / 1e9) / 1e6
: 0.0);
@@ -1210,9 +1218,10 @@ namespace MobileGL::MG_Remote::Server {
// for ever; skipping desynchronises seq, and seq IS the reply-slot id. PH-1 (3):
// the header is the peer's bytes, so an armed session child latches here and
// stops reading the ring - neither a retry nor a skip.
(void)SessionLatch(MGFatalFamily::ProtocolCorruption, "MGPipe: Fatal{ProtocolCorruption, \"SEG_CMD record header\"} - the "
"consumer refused a record header at applied seq %llu",
static_cast<unsigned long long>(consumer.AppliedSeq()));
(void)SessionLatch(MGFatalFamily::ProtocolCorruption,
"MGPipe: Fatal{ProtocolCorruption, \"SEG_CMD record header\"} - the "
"consumer refused a record header at applied seq %llu",
static_cast<unsigned long long>(consumer.AppliedSeq()));
break;
}
if (!popped) break;
@@ -1242,12 +1251,13 @@ namespace MobileGL::MG_Remote::Server {
if (applier.DecoderAppliedSeq() != consumer.AppliedSeq()) {
// PH-1 (3): latched, and nothing is retired against a watermark this side no
// longer believes.
(void)SessionLatch(MGFatalFamily::ProtocolCorruption, "MGPipe: Fatal{ProtocolCorruption, \"appliedSeq batched\"} - the "
"session's watermark is %llu and the decoder applied %llu records. P5 "
"forbids batching appliedSeq (R-9): the verb barrier's waiter reads it, "
"and a watermark ahead of the decoder promises work that has not run",
static_cast<unsigned long long>(consumer.AppliedSeq()),
static_cast<unsigned long long>(applier.DecoderAppliedSeq()));
(void)SessionLatch(MGFatalFamily::ProtocolCorruption,
"MGPipe: Fatal{ProtocolCorruption, \"appliedSeq batched\"} - the "
"session's watermark is %llu and the decoder applied %llu records. P5 "
"forbids batching appliedSeq (R-9): the verb barrier's waiter reads it, "
"and a watermark ahead of the decoder promises work that has not run",
static_cast<unsigned long long>(consumer.AppliedSeq()),
static_cast<unsigned long long>(applier.DecoderAppliedSeq()));
return applied;
}
// RETIRE. MANDATORY, not optional: RingProducer::FreeBytes() reclaims against
@@ -1311,12 +1321,13 @@ namespace MobileGL::MG_Remote::Server {
// render correctly with the context on the wrong thread - the one outcome R-1
// exists to make impossible. Fatal by name, never a fallback; compare
// CreateBackend's default: arm, which also refuses rather than substitutes.
SessionFail(MGFatalFamily::ApplyThreadNotRunning, "MGPipe: Fatal{ApplyThreadNotRunning, \"EGL on the app thread\"} - a "
"control frame reached RunSurfaceControlFrame with the server's backend "
"built but no mgl-srv-apply thread running (ClientSession::Start failed "
"after ServerLoop::CreateBackend). Dispatching it inline would make the "
"context current on the APP thread - the split lane's whole premise. "
"Refusing by name rather than falling back to monolith");
SessionFail(MGFatalFamily::ApplyThreadNotRunning,
"MGPipe: Fatal{ApplyThreadNotRunning, \"EGL on the app thread\"} - a "
"control frame reached RunSurfaceControlFrame with the server's backend "
"built but no mgl-srv-apply thread running (ClientSession::Start failed "
"after ServerLoop::CreateBackend). Dispatching it inline would make the "
"context current on the APP thread - the split lane's whole premise. "
"Refusing by name rather than falling back to monolith");
}
// Backend already gone (post-Stop teardown, or the pre-Init window): the dispatch's
// null-backend arm would answer NOT_INITIALIZED anyway, so that is the honest result
@@ -1361,11 +1372,11 @@ namespace MobileGL::MG_Remote::Server {
const ControlProgressSink sink = m_progressSink;
void* const user = m_progressUser;
if (!running || sink == nullptr) continue;
const auto elapsedMs = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now() - postedAt).count();
const auto elapsedMs =
std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - postedAt)
.count();
lock.unlock();
sink(user, frame.kind, frame.seq,
static_cast<Uint32>(std::min<long long>(elapsedMs, 0xFFFFFFFFll)));
sink(user, frame.kind, frame.seq, static_cast<Uint32>(std::min<long long>(elapsedMs, 0xFFFFFFFFll)));
lock.lock();
}
frame = m_controlFrame; // the reply half, written by the dispatch
@@ -1405,7 +1416,9 @@ namespace MobileGL::MG_Remote::Server {
m_exitCv.notify_all();
}
void ServerLoop::AbandonQueuedRecords() { m_abandonQueue.store(true, std::memory_order_release); }
void ServerLoop::AbandonQueuedRecords() {
m_abandonQueue.store(true, std::memory_order_release);
}
void ServerLoop::Stop() {
if (!m_thread.joinable()) {
@@ -1445,8 +1458,7 @@ namespace MobileGL::MG_Remote::Server {
Bool exited = false;
{
std::unique_lock<std::mutex> lock(m_exitMutex);
exited = m_exitCv.wait_for(lock, std::chrono::milliseconds(kJoinTimeoutMs),
[this] { return m_exited; });
exited = m_exitCv.wait_for(lock, std::chrono::milliseconds(kJoinTimeoutMs), [this] { return m_exited; });
}
if (!exited && !m_applyParked.load(std::memory_order_acquire)) {
// BUSY, NOT LOST (kBusyJoinTimeoutMs): the thread is applying, most likely blocked on
@@ -1466,15 +1478,16 @@ namespace MobileGL::MG_Remote::Server {
// run on into the client's teardown, reading rings the client is about to unmap -
// a use-after-free whose only symptom is an intermittent crash somewhere else.
// Aborting here is red, immediate, and names the cause.
SessionFail(MGFatalFamily::ApplyThreadJoinTimeout, "MGPipe: Fatal{ApplyThreadJoinTimeout} - mgl-srv-apply did not exit within "
"%u ms of Stop(). Stop() published m_stopRequested (in the park predicate) "
"BEFORE it rang, so a plain Notify should already have un-parked the thread; "
"Doorbell::Kill() (Doorbell.h, CondVarDoorbell::Kill; table 3 step 2) is "
"the belt to that "
"Notify's braces. If the thread is still parked after both, the wakeup was "
"lost, not slow. Aborting rather than detaching: a detached apply thread still "
"owns the context and would read rings the client is about to unmap",
kJoinTimeoutMs);
SessionFail(MGFatalFamily::ApplyThreadJoinTimeout,
"MGPipe: Fatal{ApplyThreadJoinTimeout} - mgl-srv-apply did not exit within "
"%u ms of Stop(). Stop() published m_stopRequested (in the park predicate) "
"BEFORE it rang, so a plain Notify should already have un-parked the thread; "
"Doorbell::Kill() (Doorbell.h, CondVarDoorbell::Kill; table 3 step 2) is "
"the belt to that "
"Notify's braces. If the thread is still parked after both, the wakeup was "
"lost, not slow. Aborting rather than detaching: a detached apply thread still "
"owns the context and would read rings the client is about to unmap",
kJoinTimeoutMs);
}
m_thread.join();
// The identity is NOT cleared here any more: the thread clears it itself, under
@@ -1563,9 +1576,11 @@ namespace MobileGL::MG_Remote::Server {
Bool WindowBackendFromFrameValue(Int value, MG_Backend::WindowBackend* out) {
if (value < static_cast<Int>(MG_Backend::WindowBackend::Unknown) ||
value >= static_cast<Int>(MG_Backend::WindowBackend::WindowBackendCount)) {
return SessionLatch(MGFatalFamily::ProtocolCorruption, "MGPipe: Fatal{ProtocolCorruption, \"SurfaceOp.windowBackend\"} - a "
"control frame carried window backend tag %d, which names no "
"WindowBackend", value);
return SessionLatch(MGFatalFamily::ProtocolCorruption,
"MGPipe: Fatal{ProtocolCorruption, \"SurfaceOp.windowBackend\"} - a "
"control frame carried window backend tag %d, which names no "
"WindowBackend",
value);
}
*out = static_cast<MG_Backend::WindowBackend>(value);
return true;
@@ -1618,8 +1633,8 @@ namespace MobileGL::MG_Remote::Server {
} // namespace
MobileGLResult ServerLoop::ApplySurfaceControlFrame(SurfaceControlFrame& frame,
ControlProbeHook probeHook, void* probeUser) {
MobileGLResult ServerLoop::ApplySurfaceControlFrame(SurfaceControlFrame& frame, ControlProbeHook probeHook,
void* probeUser) {
// The frame channel's own tally, bumped for EVERY dispatch including probes: a forwarder
// that stopped posting frames (the fc red-once revert shape) leaves this unmoved, which
// is what ServerLoopTest's AVoidForwarderCrossesAsOneDispatchedFrame reads.
@@ -1641,8 +1656,7 @@ namespace MobileGL::MG_Remote::Server {
// process boundary, so the version numbers travel back in the frame's value.
EGLint major = 0;
EGLint minor = 0;
frame.ok = backend->InitializeEGLDisplay(HandleFromToken<EGLDisplay>(frame.display),
&major, &minor);
frame.ok = backend->InitializeEGLDisplay(HandleFromToken<EGLDisplay>(frame.display), &major, &minor);
frame.eglMajor = major;
frame.eglMinor = minor;
return MOBILEGL_OK;
@@ -1656,8 +1670,7 @@ namespace MobileGL::MG_Remote::Server {
frame.ok = false;
return MOBILEGL_ERR_PROTOCOL_MISMATCH; // PH-1 (3): latched
}
frame.ok = backend->CreateEGLWindowSurface(HandleFromToken<EGLSurface>(frame.surface),
window);
frame.ok = backend->CreateEGLWindowSurface(HandleFromToken<EGLSurface>(frame.surface), window);
// N-3: BackendObject_DirectGLES destroys and recreates the native context to create
// a DIFFERENT surface, so whatever tuple was bound names a dead context.
if (frame.ok) ForgetCurrentTuple();
@@ -1667,9 +1680,9 @@ namespace MobileGL::MG_Remote::Server {
// P12 review fix: a server-owned surface is resized by resizing the SERVER's window.
if (IsServerOwnedSurface(HandleFromToken<EGLSurface>(frame.surface)))
return ApplyServerOwnedWindowResize(backend, frame);
frame.ok = backend->ResizeEGLWindowSurface(HandleFromToken<EGLSurface>(frame.surface),
static_cast<Uint32>(frame.width),
static_cast<Uint32>(frame.height));
frame.ok =
backend->ResizeEGLWindowSurface(HandleFromToken<EGLSurface>(frame.surface),
static_cast<Uint32>(frame.width), static_cast<Uint32>(frame.height));
return MOBILEGL_OK;
case SurfaceControlOp::CreatePbufferSurface: {
// A surfaceless stand-in (kPbufferFlagSurfacelessStandIn) is no rendering path: it is
@@ -1690,8 +1703,8 @@ namespace MobileGL::MG_Remote::Server {
SessionSurfaceModeName(m_surfaceMode));
return MOBILEGL_ERR_INVALID_ARGUMENT;
}
frame.ok = backend->CreateEGLPbufferSurface(HandleFromToken<EGLSurface>(frame.surface),
frame.width, frame.height);
frame.ok =
backend->CreateEGLPbufferSurface(HandleFromToken<EGLSurface>(frame.surface), frame.width, frame.height);
// N-3: as for the window surface - a (re)creation may have destroyed the context the
// held tuple named. The surface's own creation binds natively, so the client's
// make-current that follows is forwarded and deduped one layer down (ID-54).
@@ -1724,11 +1737,9 @@ namespace MobileGL::MG_Remote::Server {
// current with ITS context and not attached to a neighbour's. A frame from a client
// that sends a handle names no token and leaves the binding alone.
if (m_session != nullptr && frame.context != 0) (void)m_session->BindContext(frame.context);
const MakeCurrentOutcome outcome =
ApplyMakeCurrent(backend, HandleFromToken<EGLDisplay>(frame.display),
HandleFromToken<EGLSurface>(frame.surface),
HandleFromToken<EGLSurface>(frame.readSurface),
HandleFromToken<EGLContext>(frame.context));
const MakeCurrentOutcome outcome = ApplyMakeCurrent(
backend, HandleFromToken<EGLDisplay>(frame.display), HandleFromToken<EGLSurface>(frame.surface),
HandleFromToken<EGLSurface>(frame.readSurface), HandleFromToken<EGLContext>(frame.context));
frame.ok = outcome.ok;
if (!outcome.ok || !outcome.boundNatively) return MOBILEGL_OK;
// R-12, arm (a): the caps snapshot is REPUBLISHED because InitCapabilities has now
@@ -1765,9 +1776,8 @@ namespace MobileGL::MG_Remote::Server {
// current on this thread until ~BackendObject_DirectGLES or context loss, so
// forwarding would unbind and reinstate the off-thread degradation the phase
// removes). A client release never republishes: nothing ran that could move caps.
const MakeCurrentOutcome outcome =
ApplyMakeCurrent(backend, HandleFromToken<EGLDisplay>(frame.display),
EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
const MakeCurrentOutcome outcome = ApplyMakeCurrent(backend, HandleFromToken<EGLDisplay>(frame.display),
EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
frame.ok = outcome.ok;
return MOBILEGL_OK;
}
@@ -1788,8 +1798,7 @@ namespace MobileGL::MG_Remote::Server {
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 (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;
@@ -1807,8 +1816,7 @@ namespace MobileGL::MG_Remote::Server {
// 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) {
if (frame.ok && backend != nullptr && backend->GetBackendType() == BackendType::DirectGLES) {
MG_Backend::DirectGLES::DestroyNativeContextFor(frame.context);
}
return MOBILEGL_OK;
@@ -1894,8 +1902,10 @@ namespace MobileGL::MG_Remote::Server {
// PH-1 (3): latched in an armed session child (under spawn SurfaceOpCodec has already
// refused an unknown wire kind, so this is defence in depth); unarmed it dies.
frame.ok = false;
(void)SessionLatch(MGFatalFamily::ProtocolCorruption, "MGPipe: Fatal{ProtocolCorruption, \"SurfaceOp.kind\"} - the control slot held "
"kind %d, which names no dispatchable op", static_cast<int>(frame.kind));
(void)SessionLatch(MGFatalFamily::ProtocolCorruption,
"MGPipe: Fatal{ProtocolCorruption, \"SurfaceOp.kind\"} - the control slot held "
"kind %d, which names no dispatchable op",
static_cast<int>(frame.kind));
return MOBILEGL_ERR_PROTOCOL_MISMATCH;
}
@@ -1905,18 +1915,24 @@ namespace MobileGL::MG_Remote::Server {
const char* SessionSurfaceModeName(SessionSurfaceMode mode) {
switch (mode) {
case SessionSurfaceMode::None: return "undecided";
case SessionSurfaceMode::OnScreen: return "on-screen";
case SessionSurfaceMode::Offscreen: return "offscreen";
case SessionSurfaceMode::None:
return "undecided";
case SessionSurfaceMode::OnScreen:
return "on-screen";
case SessionSurfaceMode::Offscreen:
return "offscreen";
}
return "<unknown SessionSurfaceMode>";
}
Bool SessionSurfaceModeAdmits(SessionSurfaceMode current, Bool serverOwnedWindow) {
switch (current) {
case SessionSurfaceMode::None: return true;
case SessionSurfaceMode::OnScreen: return serverOwnedWindow;
case SessionSurfaceMode::Offscreen: return !serverOwnedWindow;
case SessionSurfaceMode::None:
return true;
case SessionSurfaceMode::OnScreen:
return serverOwnedWindow;
case SessionSurfaceMode::Offscreen:
return !serverOwnedWindow;
}
return false;
}
@@ -2008,7 +2024,7 @@ namespace MobileGL::MG_Remote::Server {
}
MobileGLResult ServerLoop::ApplyServerOwnedWindowSurface(MG_Backend::BackendObject* backend,
SurfaceControlFrame& frame) {
SurfaceControlFrame& frame) {
frame.ok = false;
frame.refusal = static_cast<Uint8>(SurfaceRefusalCode::None);
const Uint32 wantWidth = frame.width > 0 ? static_cast<Uint32>(frame.width) : 0u;
@@ -2027,7 +2043,8 @@ namespace MobileGL::MG_Remote::Server {
}
ServerWindowLease lease;
SurfaceRefusalCode refusal = SurfaceRefusalCode::None;
const MobileGLResult acquired = AcquireServerWindow(wantWidth, wantHeight, kServerWindowWaitMs, &lease, &refusal);
const MobileGLResult acquired =
AcquireServerWindow(wantWidth, wantHeight, kServerWindowWaitMs, &lease, &refusal);
if (acquired != MOBILEGL_OK) {
frame.refusal = static_cast<Uint8>(refusal);
return acquired;
@@ -2072,10 +2089,11 @@ namespace MobileGL::MG_Remote::Server {
frame.width = static_cast<Int>(lease.width);
frame.height = static_cast<Int>(lease.height);
// THE ARM PROOF (ID-124), once per surface: which of the two paths ran, and at what size.
MGLOG_I("MG_Remote server: surface=window %ux%u owner=server (ServerOwned seq %llu, window %p generation %llu%s)",
lease.width, lease.height, static_cast<unsigned long long>(frame.seq), lease.window,
static_cast<unsigned long long>(lease.generation),
lease.sizeAsRequested ? "" : ", NOT the size the client asked for");
MGLOG_I(
"MG_Remote server: surface=window %ux%u owner=server (ServerOwned seq %llu, window %p generation %llu%s)",
lease.width, lease.height, static_cast<unsigned long long>(frame.seq), lease.window,
static_cast<unsigned long long>(lease.generation),
lease.sizeAsRequested ? "" : ", NOT the size the client asked for");
return MOBILEGL_OK;
}
@@ -2096,7 +2114,7 @@ namespace MobileGL::MG_Remote::Server {
// for (the same lease, re-taken by its holder), the backend surface follows the window's REAL
// extent, and that extent is the reply's width/height - which the client adopts.
MobileGLResult ServerLoop::ApplyServerOwnedWindowResize(MG_Backend::BackendObject* backend,
SurfaceControlFrame& frame) {
SurfaceControlFrame& frame) {
frame.ok = false;
frame.refusal = static_cast<Uint8>(SurfaceRefusalCode::None);
const Uint32 wantWidth = frame.width > 0 ? static_cast<Uint32>(frame.width) : 0u;
@@ -2116,7 +2134,8 @@ namespace MobileGL::MG_Remote::Server {
}
ServerWindowLease lease;
SurfaceRefusalCode refusal = SurfaceRefusalCode::None;
const MobileGLResult acquired = AcquireServerWindow(wantWidth, wantHeight, kServerWindowWaitMs, &lease, &refusal);
const MobileGLResult acquired =
AcquireServerWindow(wantWidth, wantHeight, kServerWindowWaitMs, &lease, &refusal);
if (acquired != MOBILEGL_OK) {
frame.refusal = static_cast<Uint8>(refusal);
return acquired;
@@ -2124,7 +2143,8 @@ namespace MobileGL::MG_Remote::Server {
m_serverWindowWantWidth = wantWidth;
m_serverWindowWantHeight = wantHeight;
NoteServerWindowExtent(lease.window, lease.width, lease.height);
frame.ok = backend->ResizeEGLWindowSurface(HandleFromToken<EGLSurface>(frame.surface), lease.width, lease.height);
frame.ok =
backend->ResizeEGLWindowSurface(HandleFromToken<EGLSurface>(frame.surface), lease.width, lease.height);
frame.width = static_cast<Int>(lease.width);
frame.height = static_cast<Int>(lease.height);
MGLOG_I("MG_Remote server: surface=window %ux%u owner=server resized (ServerOwned seq %llu, %ux%u requested%s)",
@@ -2238,10 +2258,9 @@ namespace MobileGL::MG_Remote::Server {
ServerWindowAcquire acquired = ServerWindowAcquire::NoDisplay;
{
const ScopedBackendTurnYield yield;
acquired = ServerDisplayInstance().AcquireFor(m_serverWindowWantWidth, m_serverWindowWantHeight,
ServerDisplay::kGeometryGraceMs, this, &ServerWindowLostThunk,
&ServerWindowWaitCancelled, this, &lease,
&ServerWindowResizedThunk);
acquired = ServerDisplayInstance().AcquireFor(
m_serverWindowWantWidth, m_serverWindowWantHeight, ServerDisplay::kGeometryGraceMs, this,
&ServerWindowLostThunk, &ServerWindowWaitCancelled, this, &lease, &ServerWindowResizedThunk);
}
if (acquired != ServerWindowAcquire::Acquired) {
// Still registered: the next new window wakes this again.
+19 -11
View File
@@ -60,7 +60,11 @@ namespace MobileGL::MG_Remote::Server {
// 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 };
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);
@@ -242,8 +246,8 @@ namespace MobileGL::MG_Remote::Server {
Bool ok = false; // the request was honoured
Bool boundNatively = false; // a native eglMakeCurrent ran (=> republish caps)
};
MakeCurrentOutcome ApplyMakeCurrent(MG_Backend::BackendObject* backend, EGLDisplay dpy,
EGLSurface draw, EGLSurface read, EGLContext ctx);
MakeCurrentOutcome ApplyMakeCurrent(MG_Backend::BackendObject* backend, EGLDisplay dpy, EGLSurface draw,
EGLSurface read, EGLContext ctx);
// N-3: forget the tuple ApplyMakeCurrent last bound. Apply thread only, like the tuple
// itself (the forwarders that call these run their Args::Run there). Called on every
@@ -281,8 +285,8 @@ namespace MobileGL::MG_Remote::Server {
// (NoServerWindow). The ServerOwned arm of the dispatch is its production caller; a test
// reaches it through RunProbeOnApplyThreadForTesting. The lease is held until the backend
// has let go of the window: ServerDisplay::Detach's lost hook (D6) or the session's end.
MobileGLResult AcquireServerWindow(Uint32 width, Uint32 height, Uint32 timeoutMs,
ServerWindowLease* out, SurfaceRefusalCode* refusal);
MobileGLResult AcquireServerWindow(Uint32 width, Uint32 height, Uint32 timeoutMs, ServerWindowLease* out,
SurfaceRefusalCode* refusal);
// APPLY THREAD ONLY: this session's surface mode (D4).
SessionSurfaceMode SurfaceMode() const { return m_surfaceMode; }
// How many times this loop released a lost server window and latched ServerWindowLost (D6) -
@@ -396,8 +400,8 @@ namespace MobileGL::MG_Remote::Server {
// The dispatch, on the apply thread (or inline for a re-entrant post): executes the
// frame's op against the private backend and fills the frame's reply half. The eleven
// wire+inproc op bodies from the old forwarder Args structs live here now.
MobileGLResult ApplySurfaceControlFrame(SurfaceControlFrame& frame,
ControlProbeHook probeHook = nullptr, void* probeUser = nullptr);
MobileGLResult ApplySurfaceControlFrame(SurfaceControlFrame& frame, ControlProbeHook probeHook = nullptr,
void* probeUser = nullptr);
// The caller already holds m_callerMutex; shared by normal and test-probe posting so
// the probe's metadata is protected for the same lifetime as its frame.
MobileGLResult PostSurfaceControlFrameWithCallerLock(SurfaceControlFrame& frame);
@@ -515,10 +519,14 @@ namespace MobileGL::MG_Remote::Server {
// (the native bind itself needs the joint lane). Given the tuple currently held on the apply
// thread and the request, is this a native bind, an identical no-op repeat, or a client
// release-current the server must record without forwarding?
enum class EglBindAction { NativeBind, RepeatNoOp, ClientRelease };
EglBindAction ClassifyEglMakeCurrent(Bool haveCurrent, EGLDisplay curDpy, EGLSurface curDraw,
EGLSurface curRead, EGLContext curCtx, EGLDisplay dpy,
EGLSurface draw, EGLSurface read, EGLContext ctx);
enum class EglBindAction {
NativeBind,
RepeatNoOp,
ClientRelease
};
EglBindAction ClassifyEglMakeCurrent(Bool haveCurrent, EGLDisplay curDpy, EGLSurface curDraw, EGLSurface curRead,
EGLContext curCtx, EGLDisplay dpy, EGLSurface draw, EGLSurface read,
EGLContext ctx);
// P11 B1 (CONTRACT-P11 B1): the cpu core this process's `auto` policy reserves for a dialled-in
// shared-segment client's apply thread (ApplyThreadPolicy.h ReservedApplyCoreForConfig over this
File diff suppressed because it is too large Load Diff
+192 -175
View File
@@ -109,8 +109,7 @@ namespace MobileGL::MG_Remote::Server {
// belong in shm, never here), so one stack-free vector sized from PeekFrameSize is
// the whole reader. The BUFFER_TOO_SMALL half of ReceiveFrame's contract is what
// makes the two-step safe: a short buffer leaves the message queued.
MobileGLResult ReceiveEnvelope(Transport::ITransport& transport, std::vector<Uint8>& out,
Uint32 timeoutMs) {
MobileGLResult ReceiveEnvelope(Transport::ITransport& transport, std::vector<Uint8>& out, Uint32 timeoutMs) {
Uint64 size = 0;
MobileGLMutableByteSpan empty{nullptr, 0};
const MobileGLResult probe = transport.ReceiveFrame(empty, &size, timeoutMs);
@@ -124,10 +123,8 @@ namespace MobileGL::MG_Remote::Server {
return transport.ReceiveFrame(span, &size, 0);
}
MobileGLResult SendEnvelope(Transport::ITransport& transport,
::flatbuffers::FlatBufferBuilder& builder) {
return transport.SendFrame(
MobileGLByteSpan{builder.GetBufferPointer(), builder.GetSize()});
MobileGLResult SendEnvelope(Transport::ITransport& transport, ::flatbuffers::FlatBufferBuilder& builder) {
return transport.SendFrame(MobileGLByteSpan{builder.GetBufferPointer(), builder.GetSize()});
}
// Every message from the peer is verified before a single field is read: the control
@@ -181,16 +178,16 @@ namespace MobileGL::MG_Remote::Server {
// SetCapabilityBits / SetConsumedSubsystems for why the one that used to be here was
// the phase's marquee defect committed from the server's side.
[[noreturn]] void FatalUnsetCallMask(Bool capBitsSet, Bool consumedSet) {
SessionFail(MGFatalFamily::UnsetCallMask, "MGPipe: Fatal{UnsetCallMask} - %s%s%s was never set on this ServerSession, "
"and there is no default: a guessed consumer mask makes the client's R-8 "
"liveness gates answer from a server-side fact the server never stated. The "
"client would stop emitting whole record families, clear its dirty flags on "
"acceptance anyway, and the lane would go green with the uploads lost "
"(ID-39, reflected). Call SetConsumedSubsystems() and SetCapabilityBits() "
"before Accept(); SetCapabilityBits(0) is a legitimate explicit answer",
capBitsSet ? "" : "SetCapabilityBits",
(!capBitsSet && !consumedSet) ? " and " : "",
consumedSet ? "" : "SetConsumedSubsystems");
SessionFail(MGFatalFamily::UnsetCallMask,
"MGPipe: Fatal{UnsetCallMask} - %s%s%s was never set on this ServerSession, "
"and there is no default: a guessed consumer mask makes the client's R-8 "
"liveness gates answer from a server-side fact the server never stated. The "
"client would stop emitting whole record families, clear its dirty flags on "
"acceptance anyway, and the lane would go green with the uploads lost "
"(ID-39, reflected). Call SetConsumedSubsystems() and SetCapabilityBits() "
"before Accept(); SetCapabilityBits(0) is a legitimate explicit answer",
capBitsSet ? "" : "SetCapabilityBits", (!capBitsSet && !consumedSet) ? " and " : "",
consumedSet ? "" : "SetConsumedSubsystems");
}
// ---- P5c ev: the reverse channel's PRODUCER callbacks (CONTRACT-P5C §4.1) --------
@@ -208,11 +205,12 @@ namespace MobileGL::MG_Remote::Server {
// a Reserve that returns nullptr is Fatal{EventRingOverflow}. CountDrop and the
// eventRingFull latch stay built and stay unused-by-policy; P9 owns the policy.
[[noreturn]] void FatalEventRingOverflow(const char* eventName, Uint64 payloadBytes) {
SessionFail(MGFatalFamily::EventRingOverflow, "MGPipe: Fatal{EventRingOverflow} - the producer of %s could not reserve "
"%llu bytes on SEG_EVENT. P5c's events are lossless and a full ring under "
"lockstep is a producer burst no measured workload has, so this is a "
"defect, not a drop (CONTRACT-P5C §4.4; the drop policy is P9's)",
eventName, static_cast<unsigned long long>(payloadBytes));
SessionFail(MGFatalFamily::EventRingOverflow,
"MGPipe: Fatal{EventRingOverflow} - the producer of %s could not reserve "
"%llu bytes on SEG_EVENT. P5c's events are lossless and a full ring under "
"lockstep is a producer burst no measured workload has, so this is a "
"defect, not a drop (CONTRACT-P5C §4.4; the drop policy is P9's)",
eventName, static_cast<unsigned long long>(payloadBytes));
}
// With run-ahead the client drains SEG_EVENT only at its waits, so a full event ring is an
@@ -240,13 +238,13 @@ namespace MobileGL::MG_Remote::Server {
}
Uint32 MillisecondsSince(std::chrono::steady_clock::time_point start) {
const auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now() - start).count();
const auto elapsed =
std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - start).count();
return elapsed <= 0 ? 0u : static_cast<Uint32>(elapsed);
}
void* ReserveEventOrBlock(ServerSession& session, Transport::EventKind kind,
const char* eventName, Uint64 payloadBytes) {
void* ReserveEventOrBlock(ServerSession& session, Transport::EventKind kind, const char* eventName,
Uint64 payloadBytes) {
// FORFEITED: every event after the first drop is a drop too, at once - no Reserve and
// no second wait. The session is on its way down, and the peer has already shown it
// does not read this ring.
@@ -260,28 +258,25 @@ namespace MobileGL::MG_Remote::Server {
// be a hang with a comment on it.
const Uint64 cap = session.Events().Ring().MaxRecordBytes();
if (payloadBytes + sizeof(Transport::RingRecordHeader) > cap) {
SessionFail(MGFatalFamily::EventRingOverflow, "MGPipe: Fatal{EventRingOverflow} - %s needs %llu bytes and SEG_EVENT "
"caps ONE record at %llu (half its capacity). Flow control cannot help: "
"no amount of draining makes a record fit a ring that is too small for "
"it. SEG_EVENT's size is fixed (SessionSegmentSizes::EventRingBytes; the "
"MOBILEGL_IPC_EVENT_KB knob P5e proposed was never built), so slice the "
"event at its producer, as the writeback path already does",
eventName, static_cast<unsigned long long>(payloadBytes),
static_cast<unsigned long long>(cap));
SessionFail(MGFatalFamily::EventRingOverflow,
"MGPipe: Fatal{EventRingOverflow} - %s needs %llu bytes and SEG_EVENT "
"caps ONE record at %llu (half its capacity). Flow control cannot help: "
"no amount of draining makes a record fit a ring that is too small for "
"it. SEG_EVENT's size is fixed (SessionSegmentSizes::EventRingBytes; the "
"MOBILEGL_IPC_EVENT_KB knob P5e proposed was never built), so slice the "
"event at its producer, as the writeback path already does",
eventName, static_cast<unsigned long long>(payloadBytes),
static_cast<unsigned long long>(cap));
}
const auto signals = session.DataLink()->Signals();
Transport::Doorbell& bell = session.DataLink()->ConsumerBell();
const auto drained = [signals] {
return signals.EventRingFull->load(std::memory_order_acquire) == 0;
};
const auto drained = [signals] { return signals.EventRingFull->load(std::memory_order_acquire) == 0; };
// THE WAIT ALSO ENDS ON A STOP (PH-6 fix round). ServerLoop::Stop() raises the session's
// request and rings this same bell; a predicate that asked only "drained?" swallowed
// that ring and parked again for the rest of the knob, so any knob over Stop()'s 5000 ms
// join turned an ordinary end of the control stream into Fatal{ApplyThreadJoinTimeout}.
const auto drainedOrStopping = [&drained, &session] {
return drained() || session.ApplyStopRequested();
};
const auto drainedOrStopping = [&drained, &session] { return drained() || session.ApplyStopRequested(); };
// ONE DEADLINE FOR THE WHOLE RESERVATION, NOT ONE PER PARK. The loop goes round as
// often as the client clears the latch - that is how a client that drains in pieces
// eventually makes room - but every round spends the same budget, so a peer that
@@ -299,13 +294,13 @@ namespace MobileGL::MG_Remote::Server {
const auto outOfPatience = [&]() {
return shortDrains == 0
? session.ForfeitReverseChannel("NotDraining", "the client did not drain SEG_EVENT",
eventName, payloadBytes, MillisecondsSince(start),
budgetMs, shortDrains)
eventName, payloadBytes, MillisecondsSince(start), budgetMs,
shortDrains)
: session.ForfeitReverseChannel("TooSlow",
"the client drained SEG_EVENT but never made room for "
"this record",
eventName, payloadBytes, MillisecondsSince(start),
budgetMs, shortDrains);
eventName, payloadBytes, MillisecondsSince(start), budgetMs,
shortDrains);
};
// Asked AFTER Dead() everywhere below: under spawn a stop usually FOLLOWS the peer's
// hangup (control EOF), and the hangup is the more specific answer. The same fact can
@@ -341,7 +336,8 @@ namespace MobileGL::MG_Remote::Server {
if (!drained()) {
if (session.ApplyStopRequested()) return stopped();
const auto left = std::chrono::duration_cast<std::chrono::milliseconds>(
deadline - std::chrono::steady_clock::now()).count();
deadline - std::chrono::steady_clock::now())
.count();
if (left <= 0) return outOfPatience();
if (!bell.Wait(*signals.ConsumerParked, drainedOrStopping, /*spinUs=*/0,
static_cast<Uint32>(left))) {
@@ -386,8 +382,10 @@ namespace MobileGL::MG_Remote::Server {
// @Ph-declined (ID-P7-1): returns ServerSession& - there is no session to hand
// back and no honest "declined" reference, and the input is the backend's own
// reverse call, not a peer's bytes. Stays Fatal.
SessionFail(MGFatalFamily::RoleViolation, "MGPipe: Fatal{RoleViolation, \"%s.session-missing\"} - "
"a reverse callback has no accepted session owner", callback);
SessionFail(MGFatalFamily::RoleViolation,
"MGPipe: Fatal{RoleViolation, \"%s.session-missing\"} - "
"a reverse callback has no accepted session owner",
callback);
}
return *session;
}
@@ -407,8 +405,7 @@ namespace MobileGL::MG_Remote::Server {
return session->Events().Ring().Capacity();
}
void ServerOnBufferWriteback(MG_Pipe::MGPipeHandle res, Uint64 offset,
MG_Pipe::MGPBlobRef bytes) {
void ServerOnBufferWriteback(MG_Pipe::MGPipeHandle res, Uint64 offset, MG_Pipe::MGPBlobRef bytes) {
ServerSession& session = ReverseCallbackOwner("OnBufferWriteback");
if (bytes.Seg != MG_Pipe::kMGHostSpanSegNone) {
// The backend handed over a segment-tagged blobref. The ONLY legal shape at
@@ -417,15 +414,16 @@ namespace MobileGL::MG_Remote::Server {
// @Ph-declined (ID-P7-1): the blobref is the BACKEND's (a reverse callback with
// a void signature and no caller that could act on a decline), and it rides the
// ServerSession& above; not a peer's bytes. Stays Fatal.
SessionFail(MGFatalFamily::ProtocolCorruption, "MGPipe: Fatal{ProtocolCorruption, \"OnBufferWriteback.Seg\"} - the "
"writeback producer was handed Seg %u; at the backend boundary the "
"blobref names the backend's own mapped bytes (Seg = "
"kMGHostSpanSegNone) and the copy into SEG_EVENT is the producer's",
bytes.Seg);
SessionFail(MGFatalFamily::ProtocolCorruption,
"MGPipe: Fatal{ProtocolCorruption, \"OnBufferWriteback.Seg\"} - the "
"writeback producer was handed Seg %u; at the backend boundary the "
"blobref names the backend's own mapped bytes (Seg = "
"kMGHostSpanSegNone) and the copy into SEG_EVENT is the producer's",
bytes.Seg);
}
const Uint64 payloadBytes = sizeof(Transport::EventBufferWritebackHead) + bytes.Size;
void* slot = ReserveEventOrBlock(session, Transport::kEventBufferWriteback,
"kEventBufferWriteback", payloadBytes);
void* slot =
ReserveEventOrBlock(session, Transport::kEventBufferWriteback, "kEventBufferWriteback", payloadBytes);
Transport::EventBufferWritebackHead head{};
head.Resource = Transport::EventHandle{res.Slot, res.Gen};
head.Offset = offset;
@@ -440,13 +438,11 @@ namespace MobileGL::MG_Remote::Server {
session.PublishEvents();
}
void ServerOnGpuWritten(MG_Pipe::MGPipeHandle res, Uint rangeCount,
const MG_Pipe::MGPRange* ranges) {
void ServerOnGpuWritten(MG_Pipe::MGPipeHandle res, Uint rangeCount, const MG_Pipe::MGPRange* ranges) {
ServerSession& session = ReverseCallbackOwner("OnGpuWritten");
const Uint64 tailBytes = static_cast<Uint64>(rangeCount) * sizeof(Transport::EventRange);
const Uint64 payloadBytes = sizeof(Transport::EventGpuWrittenHead) + tailBytes;
void* slot = ReserveEventOrBlock(session, Transport::kEventGpuWritten,
"kEventGpuWritten", payloadBytes);
void* slot = ReserveEventOrBlock(session, Transport::kEventGpuWritten, "kEventGpuWritten", payloadBytes);
Transport::EventGpuWrittenHead head{};
head.Resource = Transport::EventHandle{res.Slot, res.Gen};
head.RangeCount = static_cast<std::uint32_t>(rangeCount);
@@ -454,8 +450,7 @@ namespace MobileGL::MG_Remote::Server {
if (tailBytes != 0) {
// EventRange and MGPRange are the same two Uint64s (EventRing.h asserts it at
// EventRange's declaration), so the tail is a plain copy rather than a per-element conversion.
std::memcpy(static_cast<Uint8*>(slot) + sizeof(head), ranges,
static_cast<SizeT>(tailBytes));
std::memcpy(static_cast<Uint8*>(slot) + sizeof(head), ranges, static_cast<SizeT>(tailBytes));
}
session.PublishEvents();
}
@@ -463,8 +458,8 @@ namespace MobileGL::MG_Remote::Server {
void ServerOnSurfaceChanged(const MG_Pipe::MGPSurfaceInfo* info) {
ServerSession& session = ReverseCallbackOwner("OnSurfaceChanged");
constexpr Uint64 payloadBytes = sizeof(Transport::EventSurfaceChangedHead);
void* slot = ReserveEventOrBlock(session, Transport::kEventSurfaceChanged,
"kEventSurfaceChanged", payloadBytes);
void* slot =
ReserveEventOrBlock(session, Transport::kEventSurfaceChanged, "kEventSurfaceChanged", payloadBytes);
Transport::EventSurfaceChangedHead head{};
if (info != nullptr) {
head.Width = info->Width;
@@ -492,10 +487,11 @@ namespace MobileGL::MG_Remote::Server {
template <typename Fn>
void InstallReverseCallback(Fn& entry, Fn producer) {
if (entry != nullptr && entry != producer) {
SessionFail(MGFatalFamily::RoleViolation, "MGPipe: Fatal{RoleViolation, \"callback-double-install\"} - a reverse "
"MGPipeCallbacks entry is already claimed by a different function. With "
"an active transport the four reverse entries are the server "
"session's producers; the client installs them under monolith only");
SessionFail(MGFatalFamily::RoleViolation,
"MGPipe: Fatal{RoleViolation, \"callback-double-install\"} - a reverse "
"MGPipeCallbacks entry is already claimed by a different function. With "
"an active transport the four reverse entries are the server "
"session's producers; the client installs them under monolith only");
}
entry = producer;
}
@@ -518,7 +514,9 @@ namespace MobileGL::MG_Remote::Server {
} // namespace
Uint32 ServerSessionCount() { return g_liveSessions.load(std::memory_order_acquire); }
Uint32 ServerSessionCount() {
return g_liveSessions.load(std::memory_order_acquire);
}
ServerSession& ServerSessionInstance() {
if (ServerSession* const own = Detail::CurrentSession()) return *own;
@@ -536,10 +534,13 @@ namespace MobileGL::MG_Remote::Server {
ServerSession::ServerSession() {
m_link = Transport::CreateSharedLink(Transport::TransportRoleTag::ServerConsumer);
m_commands = &m_link->CommandsIn(); m_events = &m_link->EventsOut();
m_commands = &m_link->CommandsIn();
m_events = &m_link->EventsOut();
}
ServerSession::~ServerSession() { Close(); }
ServerSession::~ServerSession() {
Close();
}
void ServerSession::SetSegmentSizes(const Transport::SessionSegmentSizes& sizes) {
if (m_accepted) {
@@ -551,7 +552,9 @@ namespace MobileGL::MG_Remote::Server {
m_sizesSet = true;
}
void ServerSession::SetBackend(MG_Backend::BackendObject* backend) { m_backend = backend; }
void ServerSession::SetBackend(MG_Backend::BackendObject* backend) {
m_backend = backend;
}
void ServerSession::SetCapabilityBits(Uint64 capBits) {
m_capBits = capBits;
@@ -563,7 +566,9 @@ namespace MobileGL::MG_Remote::Server {
m_consumedSet = true;
}
Bool ServerSession::CallMaskIsSet() const { return m_capBitsSet && m_consumedSet; }
Bool ServerSession::CallMaskIsSet() const {
return m_capBitsSet && m_consumedSet;
}
Uint64 ServerSession::CallMask() const {
if (!CallMaskIsSet()) {
@@ -572,10 +577,11 @@ namespace MobileGL::MG_Remote::Server {
return m_capBits | MGCapsConsumerBits(m_consumedSubsystems);
}
Bool ServerSession::Accepted() const { return m_accepted; }
Bool ServerSession::Accepted() const {
return m_accepted;
}
MobileGLResult ServerSession::Accept(Transport::ITransport& transport,
const std::vector<Uint8>* firstFrame) {
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
@@ -586,19 +592,20 @@ namespace MobileGL::MG_Remote::Server {
// Fatal{callback-double-install} the single-session ruling asks for.
const Bool sharedTable = Detail::CurrentSession() == this;
ServerSession* expectedOwner = nullptr;
if (!sharedTable && !g_sessionOwner.compare_exchange_strong(expectedOwner, this,
std::memory_order_acq_rel, std::memory_order_acquire)) {
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 "
"ServerSession already owns or is accepting the process reverse channel");
SessionFail(MGFatalFamily::RoleViolation,
"MGPipe: Fatal{RoleViolation, \"callback-double-install\"} - another "
"ServerSession already owns or is accepting the process reverse channel");
}
struct ReleaseFailedClaim {
ServerSession* self;
~ReleaseFailedClaim() {
if (!self->Accepted()) {
ServerSession* expected = self;
g_sessionOwner.compare_exchange_strong(expected, nullptr,
std::memory_order_release, std::memory_order_relaxed);
g_sessionOwner.compare_exchange_strong(expected, nullptr, std::memory_order_release,
std::memory_order_relaxed);
}
}
} releaseOnFailure{this};
@@ -617,11 +624,10 @@ namespace MobileGL::MG_Remote::Server {
// shared memory exists. Its whole purpose is to refuse to interpret the peer's bytes.
std::vector<Uint8> frame;
if (firstFrame != nullptr) frame = *firstFrame;
const MobileGLResult received = firstFrame != nullptr ? MOBILEGL_OK
: ReceiveEnvelope(transport, frame, kHandshakeTimeoutMs);
const MobileGLResult received =
firstFrame != nullptr ? MOBILEGL_OK : ReceiveEnvelope(transport, frame, kHandshakeTimeoutMs);
if (received != MOBILEGL_OK) {
MGLOG_E("MG_Remote server: no Hello within %u ms (rc=%d)", kHandshakeTimeoutMs,
static_cast<int>(received));
MGLOG_E("MG_Remote server: no Hello within %u ms (rc=%d)", kHandshakeTimeoutMs, static_cast<int>(received));
return received;
}
const ::MobileGL::Wire::CtrlEnvelope* envelope = ParseEnvelope(frame);
@@ -637,8 +643,7 @@ namespace MobileGL::MG_Remote::Server {
"first control frame is not a verifiable Hello");
}
const ::MobileGL::Wire::Hello* hello = envelope->msg_as_Hello();
const char* theirStamp =
hello->buildFingerprint() == nullptr ? nullptr : hello->buildFingerprint()->c_str();
const char* theirStamp = hello->buildFingerprint() == nullptr ? nullptr : hello->buildFingerprint()->c_str();
// PH-7 (1). One policy, one constant-time comparison, shared with ServerMain's supervisor
// and its session child (Handshake.h AuthenticatePeerToken). This site used std::strcmp,
@@ -656,15 +661,14 @@ namespace MobileGL::MG_Remote::Server {
if (hello->dialMode() != ::MobileGL::Wire::DialMode::No &&
hello->dialMode() != ::MobileGL::Wire::DialMode::Fork &&
hello->dialMode() != ::MobileGL::Wire::DialMode::Connect)
return RefuseHandshake(transport, ::MobileGL::Wire::RefuseCode::MalformedHello,
"unknown dial mode");
return RefuseHandshake(transport, ::MobileGL::Wire::RefuseCode::MalformedHello, "unknown dial mode");
// P11 B1: remembered for the apply thread's `auto` policy (ApplyThreadPolicy.h).
m_peer = hello->dialMode() == ::MobileGL::Wire::DialMode::Connect ? ApplyPeer::Connected
: hello->dialMode() == ::MobileGL::Wire::DialMode::Fork ? ApplyPeer::Forked
: ApplyPeer::InProcess;
m_clientPid = hello->pid();
const MobileGLResult compatible = ValidatePeerHandshake(transport, hello->abiMajor(),
hello->abiMinor(), hello->wireFingerprint(), theirStamp, hello->dialMode());
const MobileGLResult compatible = ValidatePeerHandshake(
transport, hello->abiMajor(), hello->abiMinor(), hello->wireFingerprint(), theirStamp, hello->dialMode());
if (compatible != MOBILEGL_OK) return compatible;
const Uint64 ourFingerprint = WireFingerprint();
const auto* terms = hello->linkTerms();
@@ -680,9 +684,9 @@ namespace MobileGL::MG_Remote::Server {
"stream requires a data connection");
if (hello->backendType() >= static_cast<Uint32>(BackendType::BackendTypeCount) ||
(m_backend != nullptr && hello->backendType() != static_cast<Uint32>(m_backend->GetBackendType())))
return RefuseHandshake(transport, ::MobileGL::Wire::RefuseCode::Backend,
"backend request differs from server", m_backend == nullptr ? 0 :
static_cast<Uint32>(m_backend->GetBackendType()), hello->backendType());
return RefuseHandshake(
transport, ::MobileGL::Wire::RefuseCode::Backend, "backend request differs from server",
m_backend == nullptr ? 0 : static_cast<Uint32>(m_backend->GetBackendType()), hello->backendType());
// ---- P11 A1: this side's adopt tier, from its own knob and the plane the Hello asked
// for, before a byte of Welcome. A stream refuses T0/T1 by name and serves T2; over
@@ -767,7 +771,6 @@ namespace MobileGL::MG_Remote::Server {
m_replies = ReplyPool();
m_replies.SetLink(m_link.get());
m_consumer.SetLink(m_link->Capabilities().PublishIsDelivery ? nullptr : m_link.get());
m_replies.SetLink(m_link.get());
m_applier = PipeApplier(&m_segments, &m_replies);
@@ -777,8 +780,7 @@ namespace MobileGL::MG_Remote::Server {
::flatbuffers::FlatBufferBuilder builder(1024);
using Slot = Transport::SessionSegmentSlot;
const auto segmentRef = [&](Uint32 id, ::MobileGL::Wire::SegmentKind kind, Slot slot) {
return ::MobileGL::Wire::CreateSegmentRefDirect(builder, id, kind,
m_link->Memory().AnnouncedSize(slot),
return ::MobileGL::Wire::CreateSegmentRefDirect(builder, id, kind, m_link->Memory().AnnouncedSize(slot),
m_link->Memory().AnnouncedName(slot));
};
auto cmd = segmentRef(1, ::MobileGL::Wire::SegmentKind::Cmd, Slot::Cmd);
@@ -786,9 +788,8 @@ namespace MobileGL::MG_Remote::Server {
auto reply = segmentRef(3, ::MobileGL::Wire::SegmentKind::Reply, Slot::Reply);
auto event = segmentRef(4, ::MobileGL::Wire::SegmentKind::Event, Slot::Event);
auto stamp = builder.CreateString(BuildFingerprint());
const auto nonce = pendingStream != nullptr
? builder.CreateVector(dataNonce, sizeof(dataNonce))
: ::flatbuffers::Offset<::flatbuffers::Vector<Uint8>>();
const auto nonce = pendingStream != nullptr ? builder.CreateVector(dataNonce, sizeof(dataNonce))
: ::flatbuffers::Offset<::flatbuffers::Vector<Uint8>>();
const Uint64 maxReply = m_sizes.ReplyBytes / m_sizes.ReplySlotCount - sizeof(Transport::ReplySlotHeader);
const Uint64 cmdWindow = m_link->Memory().CmdRingCapacity();
const Uint64 stageWindow = m_link->Memory().StageBytes();
@@ -808,14 +809,12 @@ namespace MobileGL::MG_Remote::Server {
static_cast<unsigned long long>(terms->stageWindowBytes()),
static_cast<unsigned long long>(terms->eventWindowBytes()),
static_cast<unsigned long long>(terms->maxReplyBytes()),
static_cast<unsigned long long>(cmdWindow),
static_cast<unsigned long long>(stageWindow),
static_cast<unsigned long long>(eventWindow),
static_cast<unsigned long long>(maxReply));
static_cast<unsigned long long>(cmdWindow), static_cast<unsigned long long>(stageWindow),
static_cast<unsigned long long>(eventWindow), static_cast<unsigned long long>(maxReply));
}
auto negotiated = ::MobileGL::Wire::CreateLinkTerms(builder, terms->dataPlane(),
::MobileGL::Wire::WireForm::StructImage, maxReply, cmdWindow, stageWindow, eventWindow,
static_cast<Uint8>(m_adoptT0Asked ? m_adoptAsk : 2));
auto negotiated = ::MobileGL::Wire::CreateLinkTerms(
builder, terms->dataPlane(), ::MobileGL::Wire::WireForm::StructImage, maxReply, cmdWindow, stageWindow,
eventWindow, static_cast<Uint8>(m_adoptT0Asked ? m_adoptAsk : 2));
auto welcome = ::MobileGL::Wire::CreateWelcome(
builder, MOBILEGL_PROTOCOL_ABI_MAJOR, MOBILEGL_PROTOCOL_ABI_MINOR,
// CONTRACT-P6 4.3: THE SERVER'S OWN PID, not an echo of the client's.
@@ -825,12 +824,11 @@ namespace MobileGL::MG_Remote::Server {
// this is its natural carrier: under spawn it is the one value in the handshake
// that a same-process session cannot produce, because there the two pids are
// equal by construction.
static_cast<Uint32>(SelfProcessId()),
cmd, stage, reply, event, stamp, ourFingerprint, ourFingerprint, negotiated,
m_backend == nullptr ? hello->backendType() : static_cast<Uint32>(m_backend->GetBackendType()),
nonce);
auto root = ::MobileGL::Wire::CreateCtrlEnvelope(
builder, ::MobileGL::Wire::CtrlMsg::Welcome, welcome.Union());
static_cast<Uint32>(SelfProcessId()), cmd, stage, reply, event, stamp, ourFingerprint, ourFingerprint,
negotiated,
m_backend == nullptr ? hello->backendType() : static_cast<Uint32>(m_backend->GetBackendType()), nonce);
auto root =
::MobileGL::Wire::CreateCtrlEnvelope(builder, ::MobileGL::Wire::CtrlMsg::Welcome, welcome.Union());
::MobileGL::Wire::FinishCtrlEnvelopeBuffer(builder, root);
const MobileGLResult sent = SendEnvelope(transport, builder);
if (sent != MOBILEGL_OK) {
@@ -873,11 +871,9 @@ namespace MobileGL::MG_Remote::Server {
// by definition not monolith, so finding one of them claimed here is the double
// installation the check exists to name.
InstallReverseCallback(MG_Pipe::gMGPipeCallbacks.OnGlError, &ServerOnGlError);
InstallReverseCallback(MG_Pipe::gMGPipeCallbacks.OnBufferWriteback,
&ServerOnBufferWriteback);
InstallReverseCallback(MG_Pipe::gMGPipeCallbacks.OnBufferWriteback, &ServerOnBufferWriteback);
InstallReverseCallback(MG_Pipe::gMGPipeCallbacks.OnGpuWritten, &ServerOnGpuWritten);
InstallReverseCallback(MG_Pipe::gMGPipeCallbacks.OnSurfaceChanged,
&ServerOnSurfaceChanged);
InstallReverseCallback(MG_Pipe::gMGPipeCallbacks.OnSurfaceChanged, &ServerOnSurfaceChanged);
// ... and, beside them, the one NUMBER a writeback producer has to know: how much of
// SEG_EVENT one record may be. Same ownership rule as the four entries above - installed
// here, released at Close only if it is still ours - because a producer left holding a
@@ -948,8 +944,7 @@ namespace MobileGL::MG_Remote::Server {
callMask &= ~static_cast<Uint64>(MG_Pipe::kCapTimerQuery);
::flatbuffers::FlatBufferBuilder builder(4096);
auto dynamicVector =
builder.CreateVector(dynamicBytes, static_cast<::flatbuffers::uoffset_t>(sizeof(dynamic)));
auto dynamicVector = builder.CreateVector(dynamicBytes, static_cast<::flatbuffers::uoffset_t>(sizeof(dynamic)));
auto rendererVector = builder.CreateVector(renderer.data(), renderer.size());
auto formatsVector = builder.CreateVector(formats.data(), formats.size());
// The client reads this back through BackendObject_Remote::GetBackendAPIVersionString()
@@ -960,11 +955,11 @@ namespace MobileGL::MG_Remote::Server {
// answered "Espryt (MobileGL Core) (<real GLES renderer>, OpenGL ES <major>.<minor>)",
// i.e. it dropped the only place the real device was named.
auto apiVersion = builder.CreateString(m_backend->GetBackendAPIVersionString());
auto snapshot = ::MobileGL::Wire::CreateCapsSnapshot(
builder, dynamicVector, rendererVector, formatsVector, /*extensions=*/0, apiVersion,
callMask, static_cast<Uint32>(m_backend->GetBackendType()));
auto root = ::MobileGL::Wire::CreateCtrlEnvelope(
builder, ::MobileGL::Wire::CtrlMsg::CapsSnapshot, snapshot.Union());
auto snapshot = ::MobileGL::Wire::CreateCapsSnapshot(builder, dynamicVector, rendererVector, formatsVector,
/*extensions=*/0, apiVersion, callMask,
static_cast<Uint32>(m_backend->GetBackendType()));
auto root =
::MobileGL::Wire::CreateCtrlEnvelope(builder, ::MobileGL::Wire::CtrlMsg::CapsSnapshot, snapshot.Union());
::MobileGL::Wire::FinishCtrlEnvelopeBuffer(builder, root);
return SendEnvelope(*m_transport, builder);
}
@@ -978,16 +973,18 @@ namespace MobileGL::MG_Remote::Server {
// cannot end the session it failed to join. What ends the wait is the deadline or the
// control peer going away; the deadline is refused on the control connection, where the
// client is listening.
MobileGLResult ServerSession::BindDataConnection(Transport::ITransport& control,
Transport::ILink& link, const Uint8* nonce) {
MobileGLResult ServerSession::BindDataConnection(Transport::ITransport& control, Transport::ILink& link,
const Uint8* nonce) {
const auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(kHandshakeTimeoutMs);
Uint32 refused = 0;
for (;;) {
const auto left = std::chrono::duration_cast<std::chrono::milliseconds>(
deadline - std::chrono::steady_clock::now()).count();
const auto left =
std::chrono::duration_cast<std::chrono::milliseconds>(deadline - std::chrono::steady_clock::now())
.count();
if (left <= 0) {
MGLOG_E("MG_Remote server: no data connection presented this session's nonce within "
"%u ms (%u refused)", kHandshakeTimeoutMs, refused);
"%u ms (%u refused)",
kHandshakeTimeoutMs, refused);
return RefuseHandshake(control, ::MobileGL::Wire::RefuseCode::Authentication,
"no data connection presented the session nonce");
}
@@ -1017,7 +1014,8 @@ namespace MobileGL::MG_Remote::Server {
void ServerSession::AttachDataLink(std::unique_ptr<Transport::ILink> link) {
m_link = std::move(link);
m_commands = &m_link->CommandsIn(); m_events = &m_link->EventsOut();
m_commands = &m_link->CommandsIn();
m_events = &m_link->EventsOut();
m_consumer.SetLink(m_link->Capabilities().PublishIsDelivery ? nullptr : m_link.get());
m_replies.SetLink(m_link.get());
if (m_link) SetExternalDoorbells(&m_link->ConsumerBell(), &m_link->ProducerBell());
@@ -1033,8 +1031,7 @@ namespace MobileGL::MG_Remote::Server {
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);
g_active.compare_exchange_strong(expectedActive, nullptr, std::memory_order_acq_rel, std::memory_order_acquire);
if (m_accepted) {
// 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
@@ -1071,14 +1068,13 @@ namespace MobileGL::MG_Remote::Server {
// A default ask that ended on T2 says its totals at MGLOG_D, like its refusal.
const bool quiet = m_adoptT0Quiet && !m_adoptT0;
const char* ran = m_adoptT0 ? "ran T0" : m_adoptT0Settled ? "not granted (T2)" : "no native bind (T2)";
#define MGL_T0_SERVER_TOTALS(LOG) \
LOG("MG_Remote server: T0 session totals - %s%s; stores imported %llu, bytes %llu, declined %llu, " \
"refused %llu, stale offers %llu, malformed %llu, unclaimed %zu", \
ran, m_adoptT0Quiet ? " (default ask)" : "", static_cast<unsigned long long>(m_t0Stores), \
static_cast<unsigned long long>(m_t0Bytes), static_cast<unsigned long long>(m_t0Declined), \
static_cast<unsigned long long>(m_t0Refusals), \
static_cast<unsigned long long>(m_adoptInbox.StaleOffers()), \
static_cast<unsigned long long>(m_adoptInbox.MalformedOffers()), m_adoptInbox.Kept())
#define MGL_T0_SERVER_TOTALS(LOG) \
LOG("MG_Remote server: T0 session totals - %s%s; stores imported %llu, bytes %llu, declined %llu, " \
"refused %llu, stale offers %llu, malformed %llu, unclaimed %zu", \
ran, m_adoptT0Quiet ? " (default ask)" : "", static_cast<unsigned long long>(m_t0Stores), \
static_cast<unsigned long long>(m_t0Bytes), static_cast<unsigned long long>(m_t0Declined), \
static_cast<unsigned long long>(m_t0Refusals), static_cast<unsigned long long>(m_adoptInbox.StaleOffers()), \
static_cast<unsigned long long>(m_adoptInbox.MalformedOffers()), m_adoptInbox.Kept())
if (quiet) {
MGL_T0_SERVER_TOTALS(MGLOG_D);
} else {
@@ -1097,14 +1093,16 @@ namespace MobileGL::MG_Remote::Server {
*m_events = Transport::EventRingProducer();
m_replies = ReplyPool();
m_link = Transport::CreateSharedLink(Transport::TransportRoleTag::ServerConsumer);
m_commands = &m_link->CommandsIn(); m_events = &m_link->EventsOut();
m_externalConsumerBell = nullptr; m_externalProducerBell = nullptr;
m_commands = &m_link->CommandsIn();
m_events = &m_link->EventsOut();
m_externalConsumerBell = nullptr;
m_externalProducerBell = nullptr;
m_link->Memory().Close();
m_transport = nullptr;
m_accepted = false;
ServerSession* expectedOwner = this;
g_sessionOwner.compare_exchange_strong(expectedOwner, nullptr,
std::memory_order_release, std::memory_order_relaxed);
g_sessionOwner.compare_exchange_strong(expectedOwner, nullptr, std::memory_order_release,
std::memory_order_relaxed);
}
// ---- P11 B2: T0 (docs/archive/contracts/CONTRACT-P11.md B2) ------------------------------------------
@@ -1127,8 +1125,9 @@ namespace MobileGL::MG_Remote::Server {
void ServerSession::SettleAdoptT0AtBind() {
if (!m_accepted || !m_adoptT0Asked || m_adoptT0Settled) return;
m_adoptT0Settled = true;
const char* backendName = m_backend == nullptr ? "server"
: m_backend->GetBackendType() == BackendType::DirectVulkan ? "Magma" : "Espryt";
const char* backendName = m_backend == nullptr ? "server"
: m_backend->GetBackendType() == BackendType::DirectVulkan ? "Magma"
: "Espryt";
std::string why;
// A CLIENT IN THIS PROCESS SHARES THE SERVER'S MEMORY ALREADY: its persistent maps are the
// stores' own mappings, donated as monolith donates them, and no AHardwareBuffer, import
@@ -1177,15 +1176,15 @@ namespace MobileGL::MG_Remote::Server {
}
if (!why.empty()) {
++m_t0Refusals;
const char* word = MG_Config::Ipc.AllowAdoptT0 == 0 ? "disallowed"
const char* word = MG_Config::Ipc.AllowAdoptT0 == 0 ? "disallowed"
: inProcess ? "in process"
: !Transport::AdoptT0::PlatformHasAhb() ? "no AHardwareBuffer"
: "POST";
if (m_adoptT0Quiet) {
// THE DEFAULT ASK (MOBILEGL_IPC_ADOPT_TIER unset) FALLS BACK QUIETLY: every host
// session would otherwise carry this line. Counted (T0Refusals, the totals line).
MGLOG_D("MG_Remote server: T0 by default not granted (%s) - %s; the session runs T2",
word, why.c_str());
MGLOG_D("MG_Remote server: T0 by default not granted (%s) - %s; the session runs T2", word,
why.c_str());
return;
}
MGLOG_W("MG_Remote server: Refuse{AdoptT0Unavailable, \"%s\"} - the client asked T0 "
@@ -1226,8 +1225,7 @@ namespace MobileGL::MG_Remote::Server {
int hop = -1;
Transport::AdoptT0::Offer offer{};
std::string why;
const AdoptInbox::Outcome outcome =
m_adoptInbox.Take(seq, Transport::AdoptT0::kOfferWaitMs, &hop, &offer, why);
const AdoptInbox::Outcome outcome = m_adoptInbox.Take(seq, Transport::AdoptT0::kOfferWaitMs, &hop, &offer, why);
const auto closeHop = [&] {
#if !defined(_WIN32)
if (hop >= 0) ::close(hop);
@@ -1336,27 +1334,35 @@ namespace MobileGL::MG_Remote::Server {
return true;
}
Transport::RingConsumer& ServerSession::CommandRing() { return *m_commands; }
Transport::RingConsumer& ServerSession::CommandRing() {
return *m_commands;
}
Transport::RingControl& ServerSession::Control() {
Transport::RingControl* control = m_link->Memory().CmdControl();
if (control == nullptr) {
// @Ph-declined (ID-P7-1): returns RingControl& - no honest reference exists before
// Accept() mapped SEG_CMD, and this is a call-order invariant, not a peer's bytes.
SessionFail(MGFatalFamily::ProtocolCorruption, "MGPipe: Fatal{ProtocolCorruption, \"ServerSession::Control\"} - the control "
"page does not exist until Accept() has mapped SEG_CMD");
SessionFail(MGFatalFamily::ProtocolCorruption,
"MGPipe: Fatal{ProtocolCorruption, \"ServerSession::Control\"} - the control "
"page does not exist until Accept() has mapped SEG_CMD");
}
return *control;
}
Wire::SegmentTable& ServerSession::Segments() { return m_segments; }
PipeApplier& ServerSession::Applier() { return m_applier; }
ReplyPool& ServerSession::Replies() { return m_replies; }
Wire::SegmentTable& ServerSession::Segments() {
return m_segments;
}
PipeApplier& ServerSession::Applier() {
return m_applier;
}
ReplyPool& ServerSession::Replies() {
return m_replies;
}
// The bell the apply thread parks on. On the server endpoint of an InProcessTransport that
// is SelfDoorbell(); the client reaches the same bell through its own PeerDoorbell().
void ServerSession::SetExternalDoorbells(Transport::Doorbell* consumer,
Transport::Doorbell* producer) {
void ServerSession::SetExternalDoorbells(Transport::Doorbell* consumer, Transport::Doorbell* producer) {
m_externalConsumerBell = consumer;
m_externalProducerBell = producer;
}
@@ -1370,8 +1376,9 @@ namespace MobileGL::MG_Remote::Server {
if (m_transport == nullptr) {
// @Ph-declined (ID-P7-1): returns Doorbell& - no bell exists to hand back before
// Accept(); a call-order invariant, not a peer's bytes.
SessionFail(MGFatalFamily::ProtocolCorruption, "MGPipe: Fatal{ProtocolCorruption, \"ServerSession::ConsumerDoorbell\"} - no "
"transport; Accept() has not run");
SessionFail(MGFatalFamily::ProtocolCorruption,
"MGPipe: Fatal{ProtocolCorruption, \"ServerSession::ConsumerDoorbell\"} - no "
"transport; Accept() has not run");
}
if (m_transport->Role() == Transport::TransportRole::InProcess) {
return static_cast<Transport::InProcessTransport*>(m_transport)->SelfDoorbell();
@@ -1381,9 +1388,10 @@ namespace MobileGL::MG_Remote::Server {
// every transport has to invent a home for.
// @Ph-declined (ID-P7-1): returns Doorbell& for a transport role this build wires no
// pair for - a build-shape fact, not a peer's bytes, and no reference to decline with.
SessionFail(MGFatalFamily::UnmigratedVerb, "MGPipe: Fatal{UnmigratedVerb, \"ServerSession::ConsumerDoorbell\"} - transport "
"role %u has no doorbell pair yet; that is P6's SocketTransport",
static_cast<unsigned>(m_transport->Role()));
SessionFail(MGFatalFamily::UnmigratedVerb,
"MGPipe: Fatal{UnmigratedVerb, \"ServerSession::ConsumerDoorbell\"} - transport "
"role %u has no doorbell pair yet; that is P6's SocketTransport",
static_cast<unsigned>(m_transport->Role()));
}
Transport::Doorbell& ServerSession::ProducerDoorbell() {
@@ -1392,22 +1400,32 @@ namespace MobileGL::MG_Remote::Server {
}
if (m_transport == nullptr) {
// @Ph-declined (ID-P7-1): returns Doorbell& - as ConsumerDoorbell above.
SessionFail(MGFatalFamily::ProtocolCorruption, "MGPipe: Fatal{ProtocolCorruption, \"ServerSession::ProducerDoorbell\"} - no "
"transport; Accept() has not run");
SessionFail(MGFatalFamily::ProtocolCorruption,
"MGPipe: Fatal{ProtocolCorruption, \"ServerSession::ProducerDoorbell\"} - no "
"transport; Accept() has not run");
}
if (m_transport->Role() == Transport::TransportRole::InProcess) {
return static_cast<Transport::InProcessTransport*>(m_transport)->PeerDoorbell();
}
// @Ph-declined (ID-P7-1): returns Doorbell& - as ConsumerDoorbell above.
SessionFail(MGFatalFamily::UnmigratedVerb, "MGPipe: Fatal{UnmigratedVerb, \"ServerSession::ProducerDoorbell\"} - transport "
"role %u has no doorbell pair yet; that is P6's SocketTransport",
static_cast<unsigned>(m_transport->Role()));
SessionFail(MGFatalFamily::UnmigratedVerb,
"MGPipe: Fatal{UnmigratedVerb, \"ServerSession::ProducerDoorbell\"} - transport "
"role %u has no doorbell pair yet; that is P6's SocketTransport",
static_cast<unsigned>(m_transport->Role()));
}
Transport::SessionSegments& ServerSession::Shm() { return m_link->Memory(); }
Transport::SessionConsumer& ServerSession::Consumer() { return m_consumer; }
Transport::EventRingProducer& ServerSession::Events() { return *m_events; }
Transport::ITransport* ServerSession::Control_Plane() { return m_transport; }
Transport::SessionSegments& ServerSession::Shm() {
return m_link->Memory();
}
Transport::SessionConsumer& ServerSession::Consumer() {
return m_consumer;
}
Transport::EventRingProducer& ServerSession::Events() {
return *m_events;
}
Transport::ITransport* ServerSession::Control_Plane() {
return m_transport;
}
void ServerSession::PublishEvents() {
if (!m_accepted) {
@@ -1438,8 +1456,7 @@ namespace MobileGL::MG_Remote::Server {
}
const Uint32 messageBytes = static_cast<Uint32>(length) + 1;
const Uint64 payloadBytes = sizeof(Transport::EventGlErrorHead) + messageBytes;
void* slot = ReserveEventOrBlock(*this, Transport::kEventGlError, "kEventGlError",
payloadBytes);
void* slot = ReserveEventOrBlock(*this, Transport::kEventGlError, "kEventGlError", payloadBytes);
Transport::EventGlErrorHead head{};
head.Code = code;
head.MessageBytes = messageBytes;
+6 -12
View File
@@ -58,8 +58,7 @@ namespace MobileGL::MG_Remote::Server {
// CapsSnapshot. The ABI assertion (CapsCodec.h) happens HERE, before a single record is
// decoded: sizeof(DynamicBackendParameters), sizeof(MGPCaps), sizeof(GLFunctionsTable)
// and the build fingerprint must match, and a mismatch is Fatal{AbiMismatch}.
MobileGLResult Accept(Transport::ITransport& transport,
const std::vector<Uint8>* firstFrame = nullptr);
MobileGLResult Accept(Transport::ITransport& transport, const std::vector<Uint8>* firstFrame = nullptr);
// PH-7 (4), ID-P7-3. WHERE A TCP SESSION'S DATA CONNECTION COMES FROM.
//
@@ -203,18 +202,15 @@ namespace MobileGL::MG_Remote::Server {
// 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);
}
Bool ReverseChannelForfeited() const { return m_reverseChannelForfeit.load(std::memory_order_acquire); }
// Drops since the latch went up, counted HERE because the shared page's eventDropped is
// on a page the peer can write.
Uint64 ForfeitDrops() const { return m_forfeitDrops.load(std::memory_order_acquire); }
// `cause` is one word (the braces' content); `why` the sentence; `shortDrains` how many
// times the client cleared the latch without making room. Returns the scratch the caller
// writes the dropped event into.
void* ForfeitReverseChannel(const char* cause, const char* why, const char* eventName,
Uint64 payloadBytes, Uint32 waitedMs, Uint32 budgetMs,
Uint32 shortDrains);
void* ForfeitReverseChannel(const char* cause, const char* why, const char* eventName, Uint64 payloadBytes,
Uint32 waitedMs, Uint32 budgetMs, Uint32 shortDrains);
void* DropEventAfterForfeit(Uint64 payloadBytes);
// PH-6 fix round. SERVERLOOP::STOP'S REQUEST, SEEN BY THE ONE APPLY-THREAD WAIT THAT IS NOT
@@ -271,8 +267,7 @@ namespace MobileGL::MG_Remote::Server {
// DECLINED with a named line).
// A client in this process (inproc) takes no AHardwareBuffer: the backend donates the
// store's own mapping and `inProcessBase` carries its address in the OK answer.
Bool AdoptStoreT0(const MG_Pipe::MGPHandleOnly& handle, Uint64 seq, Int32& status,
Uint64& inProcessBase);
Bool AdoptStoreT0(const MG_Pipe::MGPHandleOnly& handle, Uint64 seq, Int32& status, Uint64& inProcessBase);
// T0 granted for a client in this process: map_persistent donates (kCapAdoptInProcess).
Bool AdoptT0InProcess() const { return m_adoptT0InProcess; }
// The arm's proof for this session (B2): stores imported and their bytes, declined.
@@ -335,8 +330,7 @@ namespace MobileGL::MG_Remote::Server {
Uint64 ContextBinds() const { return m_contextBinds; }
private:
MobileGLResult BindDataConnection(Transport::ITransport& control, Transport::ILink& link,
const Uint8* nonce);
MobileGLResult BindDataConnection(Transport::ITransport& control, Transport::ILink& link, const Uint8* nonce);
DataConnectionSource m_dataSource;
std::unique_ptr<Transport::ILink> m_link;
+33 -34
View File
@@ -18,17 +18,17 @@
#include <vector>
#if defined(__unix__) || defined(__APPLE__) || defined(__ANDROID__)
# define MOBILEGL_SERVER_SPAWN_POSIX 1
# include <dirent.h>
# include <fcntl.h>
# include <dlfcn.h>
# include <sys/socket.h>
# include <sys/stat.h>
# include <sys/types.h>
# include <sys/wait.h>
# include <unistd.h>
#define MOBILEGL_SERVER_SPAWN_POSIX 1
#include <dirent.h>
#include <fcntl.h>
#include <dlfcn.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#else
# define MOBILEGL_SERVER_SPAWN_POSIX 0
#define MOBILEGL_SERVER_SPAWN_POSIX 0
#endif
namespace MobileGL::MG_Remote::Server {
@@ -46,7 +46,7 @@ namespace MobileGL::MG_Remote::Server {
if (path.empty()) {
return false;
}
struct stat st {};
struct stat st{};
if (::stat(path.c_str(), &st) != 0) {
return false;
}
@@ -66,8 +66,7 @@ namespace MobileGL::MG_Remote::Server {
return configured;
}
Dl_info info{};
if (::dladdr(reinterpret_cast<void*>(&ResolveImage), &info) != 0 &&
info.dli_fname != nullptr) {
if (::dladdr(reinterpret_cast<void*>(&ResolveImage), &info) != 0 && info.dli_fname != nullptr) {
const std::string self(info.dli_fname);
const std::size_t slash = self.find_last_of('/');
if (slash != std::string::npos) {
@@ -86,8 +85,9 @@ namespace MobileGL::MG_Remote::Server {
// 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=",
"MOBILEGL_IPC_AUDIT=", "MOBILEGL_IPC_EVENT_WAIT_MS=", "MOBILEGL_IPC_ALLOW_ADOPT_T0=",
"MOBILEGL_IPC_WIRE_DEFERRED_MB=", "MOBILEGL_IPC_SPIN_US=",
"MOBILEGL_IPC_SERVER_AFFINITY=", "MOBILEGL_IPC_AUDIT=",
"MOBILEGL_IPC_EVENT_WAIT_MS=", "MOBILEGL_IPC_ALLOW_ADOPT_T0=",
};
for (const char* kept : kServerOwned) {
if (std::strncmp(entry, kept, std::strlen(kept)) == 0) {
@@ -184,14 +184,12 @@ namespace MobileGL::MG_Remote::Server {
return children;
}
MobileGLResult LaunchServer(const std::string& imagePath, const std::string& endpoint,
LaunchedServer* out) {
MobileGLResult LaunchServer(const std::string& imagePath, const std::string& endpoint, LaunchedServer* out) {
return LaunchServerWithArgs(imagePath, endpoint, {}, out);
}
MobileGLResult LaunchServerWithArgs(const std::string& imagePath, const std::string& endpoint,
const std::vector<std::string>& extraArgs,
LaunchedServer* out) {
const std::vector<std::string>& extraArgs, LaunchedServer* out) {
if (out == nullptr || endpoint.empty()) {
return MOBILEGL_ERR_INVALID_ARGUMENT;
}
@@ -202,27 +200,27 @@ namespace MobileGL::MG_Remote::Server {
// NAMED, never a fallback. ConfigLoader.cpp's own comment names the
// accident this prevents: a lane that asked for spawn, silently got
// monolith, and went green on the wrong arm.
Transport::WireLogError(
"MG_Remote spawn: the server image is not executable: \"%s\" - refusing. Set "
"MOBILEGL_IPC_SERVER_PATH, or place libMobileGLServer.so beside libMobileGL.so. "
"There is NO monolith fallback from here.",
image.empty() ? "<unresolved>" : image.c_str());
Transport::WireLogError("MG_Remote spawn: the server image is not executable: \"%s\" - refusing. Set "
"MOBILEGL_IPC_SERVER_PATH, or place libMobileGLServer.so beside libMobileGL.so. "
"There is NO monolith fallback from here.",
image.empty() ? "<unresolved>" : image.c_str());
return MOBILEGL_ERR_INVALID_ARGUMENT;
}
// The image's directory, which is where its libMobileGL.so is.
const std::string::size_type slash = image.find_last_of('/');
ScrubbedEnv env =
BuildChildEnv(slash == std::string::npos ? std::string() : image.substr(0, slash));
ScrubbedEnv env = BuildChildEnv(slash == std::string::npos ? std::string() : image.substr(0, slash));
// Built before the fork: the child may only make async-signal-safe calls until execve.
std::vector<std::string> args;
args.reserve(2 + extraArgs.size());
args.push_back(image);
args.push_back(endpoint);
for (const std::string& arg : extraArgs) args.push_back(arg);
for (const std::string& arg : extraArgs)
args.push_back(arg);
std::vector<char*> argvStorage;
argvStorage.reserve(args.size() + 1);
for (std::string& arg : args) argvStorage.push_back(arg.data());
for (std::string& arg : args)
argvStorage.push_back(arg.data());
argvStorage.push_back(nullptr);
char** argv = argvStorage.data();
@@ -266,8 +264,8 @@ namespace MobileGL::MG_Remote::Server {
const ssize_t got = ::read(report[0], &childErrno, sizeof(childErrno));
::close(report[0]);
if (got == static_cast<ssize_t>(sizeof(childErrno))) {
Transport::WireLogError("MG_Remote spawn: execve(\"%s\") failed in the child: %s",
image.c_str(), std::strerror(childErrno));
Transport::WireLogError("MG_Remote spawn: execve(\"%s\") failed in the child: %s", image.c_str(),
std::strerror(childErrno));
int status = 0;
::waitpid(pid, &status, 0);
return MOBILEGL_ERR_INVALID_ARGUMENT;
@@ -281,8 +279,7 @@ namespace MobileGL::MG_Remote::Server {
return MOBILEGL_OK;
}
MobileGLResult ReapServer(LaunchedServer& server, std::uint32_t timeoutMs,
int* outExitCode) {
MobileGLResult ReapServer(LaunchedServer& server, std::uint32_t timeoutMs, int* outExitCode) {
if (server.pid < 0) {
return MOBILEGL_ERR_INVALID_ARGUMENT;
}
@@ -318,7 +315,7 @@ namespace MobileGL::MG_Remote::Server {
MobileGLResult LaunchServer(const std::string&, const std::string&, LaunchedServer*) {
Transport::WireLogError("MG_Remote spawn: unsupported on this platform - P6 lands POSIX only "
"(CONTRACT-P6 §2.6); there is no fork() to build a second process from");
"(CONTRACT-P6 §2.6); there is no fork() to build a second process from");
return MOBILEGL_ERR_UNSUPPORTED;
}
MobileGLResult LaunchServerWithArgs(const std::string& imagePath, const std::string& endpoint,
@@ -328,7 +325,9 @@ namespace MobileGL::MG_Remote::Server {
MobileGLResult ReapServer(LaunchedServer&, std::uint32_t, int*) {
return MOBILEGL_ERR_UNSUPPORTED;
}
int CountOwnChildren() { return -1; }
int CountOwnChildren() {
return -1;
}
#endif
+2 -4
View File
@@ -51,16 +51,14 @@ namespace MobileGL::MG_Remote::Server {
// unresolvable path is a NAMED REFUSAL and never a monolith fallback -
// ConfigLoader.cpp names that accident and this is the code that must not
// repeat it.
MobileGLResult LaunchServer(const std::string& imagePath, const std::string& endpoint,
LaunchedServer* out);
MobileGLResult LaunchServer(const std::string& imagePath, const std::string& endpoint, LaunchedServer* out);
// The same launch with arguments after the endpoint - `--serve` for the fork-per-session
// supervisor a TCP deployment runs (ServerMain.cpp). PH-1 (4)'s control needs exactly that
// shape on a unit rig: a session that latches must leave a supervisor that serves the next
// connection, and a single-session server exits with its only session.
MobileGLResult LaunchServerWithArgs(const std::string& imagePath, const std::string& endpoint,
const std::vector<std::string>& extraArgs,
LaunchedServer* out);
const std::vector<std::string>& extraArgs, LaunchedServer* out);
// Waits for the child, up to `timeoutMs`. Returns MOBILEGL_ERR_TIMEOUT if it
// is still running, in which case the caller decides whether to escalate -
+12 -7
View File
@@ -77,8 +77,8 @@ namespace MobileGL::MG_Remote::Server {
SessionRuntime* runtime = t_runtime;
if (runtime == nullptr) return false;
outKey->SessionKey = reinterpret_cast<Uint64>(&runtime->Session());
outKey->ShareGroupKey = MG_Pipe::MGPipeApplierShareGroupKeyFor(
outKey->SessionKey, runtime->Session().CurrentContextToken());
outKey->ShareGroupKey =
MG_Pipe::MGPipeApplierShareGroupKeyFor(outKey->SessionKey, runtime->Session().CurrentContextToken());
return true;
}
@@ -106,7 +106,9 @@ namespace MobileGL::MG_Remote::Server {
MG_Record::SetStagedBucketResolver(&ResolveThreadStagedBucket);
}
SessionRuntime* Detail::CurrentRuntime() { return t_runtime; }
SessionRuntime* Detail::CurrentRuntime() {
return t_runtime;
}
ServerSession* Detail::CurrentSession() {
SessionRuntime* runtime = t_runtime;
@@ -118,7 +120,9 @@ namespace MobileGL::MG_Remote::Server {
return runtime != nullptr ? &runtime->Loop() : nullptr;
}
MG_Pipe::PipeInputs* Detail::CurrentInputs() { return ResolveThreadInputs(); }
MG_Pipe::PipeInputs* Detail::CurrentInputs() {
return ResolveThreadInputs();
}
Detail::ThreadSessionScope::ThreadSessionScope(SessionRuntime& runtime) {
InstallSessionRuntimeHooks();
@@ -141,8 +145,7 @@ namespace MobileGL::MG_Remote::Server {
t_runtime = m_previous;
}
SessionRuntime::SessionRuntime()
: m_latchDomain(FatalLatchDomainOpen()) {}
SessionRuntime::SessionRuntime() : m_latchDomain(FatalLatchDomainOpen()) {}
SessionRuntime::~SessionRuntime() {
// P14 S5: this runtime's session is the key every applier it registered was filed
@@ -156,6 +159,8 @@ namespace MobileGL::MG_Remote::Server {
m_latchDomain = 0;
}
Uint32 LiveServerSessionCount() { return ServerSessionCount(); }
Uint32 LiveServerSessionCount() {
return ServerSessionCount();
}
} // namespace MobileGL::MG_Remote::Server
@@ -64,7 +64,7 @@ namespace MobileGL::MG_Remote::Server::SharedImages {
#if !defined(_WIN32)
Bool IdentityOf(int fd, Uint64* dev, Uint64* ino) {
struct stat st {};
struct stat st{};
if (::fstat(fd, &st) != 0) return false;
*dev = static_cast<Uint64>(st.st_dev);
*ino = static_cast<Uint64>(st.st_ino);
@@ -105,7 +105,8 @@ namespace MobileGL::MG_Remote::Server::SharedImages {
if (c->cmsg_level != SOL_SOCKET || c->cmsg_type != SCM_RIGHTS) continue;
const SizeT n = (c->cmsg_len - CMSG_LEN(0)) / sizeof(int);
const int* in = reinterpret_cast<const int*>(CMSG_DATA(c));
for (SizeT i = 0; i < n; ++i) fds.push_back(in[i]);
for (SizeT i = 0; i < n; ++i)
fds.push_back(in[i]);
}
}
::close(pair[1]);
@@ -144,8 +145,8 @@ namespace MobileGL::MG_Remote::Server::SharedImages {
// CPU usage also keeps the layout one the platform can lock plane by plane, which is how
// every layout question about it is answered (AHardwareBuffer_lockPlanes) - never by
// assuming one.
constexpr uint64_t kYuvUsage = AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE |
AHARDWAREBUFFER_USAGE_CPU_WRITE_OFTEN | AHARDWAREBUFFER_USAGE_CPU_READ_RARELY;
constexpr uint64_t kYuvUsage = AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE | AHARDWAREBUFFER_USAGE_CPU_WRITE_OFTEN |
AHARDWAREBUFFER_USAGE_CPU_READ_RARELY;
uint32_t AhbFormatOf(Uint32 fourcc) {
if (fourcc == kFourccNv12) return AHARDWAREBUFFER_FORMAT_Y8Cb8Cr8_420;
@@ -218,7 +219,8 @@ namespace MobileGL::MG_Remote::Server::SharedImages {
}
image.Native = ahb;
image.Fd = fds[0];
for (SizeT i = 1; i < fds.size(); ++i) ::close(fds[i]);
for (SizeT i = 1; i < fds.size(); ++i)
::close(fds[i]);
image.Offset = 0;
if (!FourccIsYuv(image.Fourcc)) {
image.Stride = described.stride * 4;
@@ -255,7 +257,9 @@ namespace MobileGL::MG_Remote::Server::SharedImages {
// A host has no AHardwareBuffer. A memfd stands in for the dma-buf so the registry, the
// descriptor round trip and identification can be exercised by the unit tests; no backend
// binds one.
Bool YuvAllocatableNative(Uint32) { return true; }
Bool YuvAllocatableNative(Uint32) {
return true;
}
Bool AllocateNative(Image& image, std::string& why) {
Uint64 bytes = 0;
@@ -288,7 +292,9 @@ namespace MobileGL::MG_Remote::Server::SharedImages {
void ReleaseNative(void*) {}
#else
Bool YuvAllocatableNative(Uint32) { return false; }
Bool YuvAllocatableNative(Uint32) {
return false;
}
Bool AllocateNative(Image&, std::string& why) {
why = "shared images need POSIX descriptors";
@@ -353,8 +359,7 @@ namespace MobileGL::MG_Remote::Server::SharedImages {
void DmaBufSync(int fd, Bool start) {
dma_buf_sync sync{};
sync.flags = DMA_BUF_SYNC_READ | (start ? DMA_BUF_SYNC_START : DMA_BUF_SYNC_END);
while (::ioctl(fd, DMA_BUF_IOCTL_SYNC, &sync) != 0 && (errno == EINTR || errno == EAGAIN)) {
}
while (::ioctl(fd, DMA_BUF_IOCTL_SYNC, &sync) != 0 && (errno == EINTR || errno == EAGAIN)) {}
}
#endif
} // namespace
@@ -384,12 +389,15 @@ namespace MobileGL::MG_Remote::Server::SharedImages {
}
if (Fd >= 0) ::close(Fd);
if (WriteFence >= 0) ::close(WriteFence);
for (const int fence : ReadFences) ::close(fence);
for (const int fence : ReadFences)
::close(fence);
#endif
ReleaseNative(Native);
}
Bool FourccIsYuv(Uint32 fourcc) { return fourcc == kFourccNv12 || fourcc == kFourccP010; }
Bool FourccIsYuv(Uint32 fourcc) {
return fourcc == kFourccNv12 || fourcc == kFourccP010;
}
Uint32 FourccYuvSampleBytes(Uint32 fourcc) {
if (fourcc == kFourccNv12) return 1;
@@ -414,7 +422,9 @@ namespace MobileGL::MG_Remote::Server::SharedImages {
fourcc == kFourccXrgb8888 || YuvFourccAllocatable(fourcc);
}
Bool FourccIgnoresAlpha(Uint32 fourcc) { return fourcc == kFourccXbgr8888 || fourcc == kFourccXrgb8888; }
Bool FourccIgnoresAlpha(Uint32 fourcc) {
return fourcc == kFourccXbgr8888 || fourcc == kFourccXrgb8888;
}
namespace {
// Allocate's body. `foreign`, when given, is on the image before anything can find it.
@@ -457,8 +467,7 @@ namespace MobileGL::MG_Remote::Server::SharedImages {
}
reg.byIdentity[key] = image;
if (image->Foreign != nullptr) {
reg.foreignByIdentity[std::make_pair(image->Foreign->IdentityDev, image->Foreign->IdentityIno)] =
image;
reg.foreignByIdentity[std::make_pair(image->Foreign->IdentityDev, image->Foreign->IdentityIno)] = image;
}
return image;
}
@@ -517,8 +526,8 @@ namespace MobileGL::MG_Remote::Server::SharedImages {
const Uint64 lumaEnd = static_cast<Uint64>(layout.Offset[0]) +
static_cast<Uint64>(layout.Pitch[0]) * (height - 1) +
static_cast<Uint64>(width) * sampleBytes;
const Uint64 chromaEnd =
static_cast<Uint64>(layout.Offset[1]) + static_cast<Uint64>(layout.Pitch[1]) * (chromaHeight - 1) + chromaRow;
const Uint64 chromaEnd = static_cast<Uint64>(layout.Offset[1]) +
static_cast<Uint64>(layout.Pitch[1]) * (chromaHeight - 1) + chromaRow;
if (layout.Pitch[0] < width * sampleBytes || layout.Pitch[1] < chromaRow || lumaEnd > size ||
chromaEnd > size) {
why = Format("its planes do not fit the %lld-byte buffer", static_cast<long long>(size));
@@ -633,8 +642,8 @@ namespace MobileGL::MG_Remote::Server::SharedImages {
const auto it = reg.byIdentity.find(std::make_pair(dev, ino));
ImageRef image = it != reg.byIdentity.end() ? it->second.lock() : nullptr;
if (image == nullptr) {
why = Format("the descriptor (dev %llu ino %llu) was not exported by this server", static_cast<long long>(dev),
static_cast<long long>(ino));
why = Format("the descriptor (dev %llu ino %llu) was not exported by this server",
static_cast<long long>(dev), static_cast<long long>(ino));
}
return image;
#endif
@@ -651,14 +660,17 @@ namespace MobileGL::MG_Remote::Server::SharedImages {
Registry& reg = Reg();
const std::lock_guard<std::mutex> lock(reg.mutex);
SizeT live = 0;
for (const auto& [id, weak] : reg.byId) live += weak.expired() ? 0 : 1;
for (const auto& [id, weak] : reg.byId)
live += weak.expired() ? 0 : 1;
return live;
}
// ---- synchronisation ------------------------------------------------------------------------
namespace SyncFile {
Bool Signaled(int fd) { return Wait(fd, 0); }
Bool Signaled(int fd) {
return Wait(fd, 0);
}
Bool Wait(int fd, Uint32 timeoutMs) {
#if defined(_WIN32)
@@ -767,7 +779,8 @@ namespace MobileGL::MG_Remote::Server::SharedImages {
}
void ReadTracker::PublishFrame(int fence) {
for (const auto& [id, image] : m_images) PublishRead(*image, Dup(fence));
for (const auto& [id, image] : m_images)
PublishRead(*image, Dup(fence));
CloseFd(fence);
m_images.clear();
}
+4 -3
View File
@@ -91,7 +91,8 @@ namespace MobileGL::MG_Remote::Server::SharedImages::Yuv {
-cScale * 2.0 * kr * (1.0 - kr) / kg,
0.0,
};
for (SizeT i = 0; i < 9; ++i) c.Matrix[i] = static_cast<float>(m[i]);
for (SizeT i = 0; i < 9; ++i)
c.Matrix[i] = static_cast<float>(m[i]);
c.Offset[0] = static_cast<float>(yOffset);
c.Offset[1] = static_cast<float>(cOffset);
c.Offset[2] = static_cast<float>(cOffset);
@@ -130,8 +131,8 @@ namespace MobileGL::MG_Remote::Server::SharedImages::Yuv {
std::memcpy(to, from, static_cast<SizeT>(width) * sampleBytes);
} else {
for (Uint32 x = 0; x < width; ++x)
std::memcpy(to + static_cast<SizeT>(x) * dst.Y.PixelStride, from + static_cast<SizeT>(x) * sampleBytes,
sampleBytes);
std::memcpy(to + static_cast<SizeT>(x) * dst.Y.PixelStride,
from + static_cast<SizeT>(x) * sampleBytes, sampleBytes);
}
}
// Chroma.
@@ -12,23 +12,40 @@ namespace MobileGL::MG_Remote::Server {
const char* SurfaceControlOpName(SurfaceControlOp op) {
switch (op) {
case SurfaceControlOp::None: return "None";
case SurfaceControlOp::InitializeDisplay: return "InitializeDisplay";
case SurfaceControlOp::CreateWindowSurface: return "CreateWindowSurface";
case SurfaceControlOp::CreatePbufferSurface: return "CreatePbufferSurface";
case SurfaceControlOp::ResizeWindowSurface: return "ResizeWindowSurface";
case SurfaceControlOp::ReleaseSurface: return "ReleaseSurface";
case SurfaceControlOp::MakeCurrent: return "MakeCurrent";
case SurfaceControlOp::ReleaseCurrent: return "ReleaseCurrent";
case SurfaceControlOp::SetSwapInterval: return "SetSwapInterval";
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";
case SurfaceControlOp::None:
return "None";
case SurfaceControlOp::InitializeDisplay:
return "InitializeDisplay";
case SurfaceControlOp::CreateWindowSurface:
return "CreateWindowSurface";
case SurfaceControlOp::CreatePbufferSurface:
return "CreatePbufferSurface";
case SurfaceControlOp::ResizeWindowSurface:
return "ResizeWindowSurface";
case SurfaceControlOp::ReleaseSurface:
return "ReleaseSurface";
case SurfaceControlOp::MakeCurrent:
return "MakeCurrent";
case SurfaceControlOp::ReleaseCurrent:
return "ReleaseCurrent";
case SurfaceControlOp::SetSwapInterval:
return "SetSwapInterval";
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";
}
return "<unknown SurfaceControlOp>";
}
@@ -62,11 +79,16 @@ namespace MobileGL::MG_Remote::Server {
const char* SurfaceRefusalCodeName(SurfaceRefusalCode code) {
switch (code) {
case SurfaceRefusalCode::None: return "None";
case SurfaceRefusalCode::NoServerDisplay: return "NoServerDisplay";
case SurfaceRefusalCode::NoServerWindow: return "NoServerWindow";
case SurfaceRefusalCode::SurfaceModeMismatch: return "SurfaceModeMismatch";
case SurfaceRefusalCode::ServerOwnedOnSetWindowHandle: return "ServerOwnedOnSetWindowHandle";
case SurfaceRefusalCode::None:
return "None";
case SurfaceRefusalCode::NoServerDisplay:
return "NoServerDisplay";
case SurfaceRefusalCode::NoServerWindow:
return "NoServerWindow";
case SurfaceRefusalCode::SurfaceModeMismatch:
return "SurfaceModeMismatch";
case SurfaceRefusalCode::ServerOwnedOnSetWindowHandle:
return "ServerOwnedOnSetWindowHandle";
}
return "<unknown SurfaceRefusalCode>";
}
@@ -62,9 +62,9 @@ namespace MobileGL::MG_Remote::Server {
// 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
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.
@@ -151,16 +151,15 @@ namespace MobileGL::MG_Remote::Server {
SurfaceControlFrame frame{};
// 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, shareGroupToken, contextFlags, ok,
eglMajor, eglMinor, eventHead, refusal] = frame;
const auto& [kind, seq, display, surface, readSurface, context, windowBackend, 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(shareGroupToken)> &&
IsSurfaceControlValue<decltype(swapInterval)> && IsSurfaceControlValue<decltype(shareGroupToken)> &&
IsSurfaceControlValue<decltype(contextFlags)> && IsSurfaceControlValue<decltype(ok)> &&
IsSurfaceControlValue<decltype(eglMajor)> && IsSurfaceControlValue<decltype(eglMinor)> &&
IsSurfaceControlValue<decltype(eventHead)> && IsSurfaceControlValue<decltype(refusal)>;
@@ -169,8 +168,7 @@ namespace MobileGL::MG_Remote::Server {
static_assert(Detail::SurfaceControlFrameHasOnlyValues(),
"every surface control frame member must be an integer or enum, never a pointer");
static_assert(std::is_trivially_copyable_v<SurfaceControlFrame> &&
std::is_standard_layout_v<SurfaceControlFrame>,
static_assert(std::is_trivially_copyable_v<SurfaceControlFrame> && std::is_standard_layout_v<SurfaceControlFrame>,
"the surface control frame must remain a trivially copyable value aggregate");
const char* SurfaceControlOpName(SurfaceControlOp op);