diff --git a/CMakeLists.txt b/CMakeLists.txt index c7d22bf2..f869b95c 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -657,6 +657,7 @@ list(APPEND SOURCE_FILES MobileGL/MG_Pipe/MGPipeRenderStateSpans.cpp MobileGL/MG_Pipe/PipeApply.cpp MobileGL/MG_Pipe/PipeDeviceLossKnobs.cpp + MobileGL/MG_Pipe/PipeResidentBuffer.cpp MobileGL/MG_Impl/Pipe/SlotAllocator.cpp # P4a's contract: the reflection-archive serializer over ProgramArtifacts.h's # VisitFields tables. Push-only for the same G1 reason as the three above - in diff --git a/MobileGL/MG_Backend/BackendObject.cpp b/MobileGL/MG_Backend/BackendObject.cpp index 5f0ee7bf..cd7cdd64 100644 --- a/MobileGL/MG_Backend/BackendObject.cpp +++ b/MobileGL/MG_Backend/BackendObject.cpp @@ -37,6 +37,31 @@ namespace MobileGL::MG_Backend { m_egl.ReleaseSurface(surface); } + Bool BackendObject::CreateEGLWindowSurfaceOnDisplay(EGLDisplay display, EGLSurface surface, + const WindowHandle& handle) { + const auto lock = m_egl.Lock(); + const auto previous = m_egl.SetRegistrationDisplay(display); + const Bool created = CreateEGLWindowSurface(surface, handle); + m_egl.SetRegistrationDisplay(previous); + return created; + } + + Bool BackendObject::CreateEGLPbufferSurfaceOnDisplay(EGLDisplay display, EGLSurface surface, EGLint width, + EGLint height) { + const auto lock = m_egl.Lock(); + const auto previous = m_egl.SetRegistrationDisplay(display); + const Bool created = CreateEGLPbufferSurface(surface, width, height); + m_egl.SetRegistrationDisplay(previous); + return created; + } + + void BackendObject::ReleaseEGLDisplay(EGLDisplay display) { + const auto lock = m_egl.Lock(); + for (const EGLSurface surface : m_egl.SurfacesOnDisplay(display)) + ReleaseEGLSurface(surface); + m_egl.ReleaseDisplay(display); + } + void BackendObject::ReleaseEGLResources() { m_egl.ReleaseAll(); } diff --git a/MobileGL/MG_Backend/BackendObject.h b/MobileGL/MG_Backend/BackendObject.h index e936822c..da810cb9 100644 --- a/MobileGL/MG_Backend/BackendObject.h +++ b/MobileGL/MG_Backend/BackendObject.h @@ -47,6 +47,13 @@ namespace MobileGL { virtual void SetEGLSwapInterval(Int interval); virtual void ReleaseEGLSurface(EGLSurface surface); virtual void ReleaseEGLResources(); + void ReleaseEGLDisplay(EGLDisplay display); + Bool CreateEGLWindowSurfaceOnDisplay(EGLDisplay display, EGLSurface surface, const WindowHandle& handle); + Bool CreateEGLPbufferSurfaceOnDisplay(EGLDisplay display, EGLSurface surface, EGLint width, EGLint height); + virtual void RegisterEGLContext(EGLContext, Uint64, Uint64) {} + virtual void ReleaseEGLContext(Uint64) {} + virtual Uint64 SetEGLObjectShareGroup(Uint64) { return 0; } + virtual void BeginEGLCommands() {} void SetWindowHandle(const WindowHandle& handle); diff --git a/MobileGL/MG_Backend/DirectGLES/BackendObject_DirectGLES.cpp b/MobileGL/MG_Backend/DirectGLES/BackendObject_DirectGLES.cpp index c251a5b6..26d54c8b 100644 --- a/MobileGL/MG_Backend/DirectGLES/BackendObject_DirectGLES.cpp +++ b/MobileGL/MG_Backend/DirectGLES/BackendObject_DirectGLES.cpp @@ -28,6 +28,14 @@ namespace MobileGL::MG_Backend::DirectGLES { namespace { + Bool UsesLocalEGLContexts() { +#if MOBILEGL_BUILD_DISAGGREGATED + return MG_Config::Transport == MG_Config::TransportMode::Monolith; +#else + return true; +#endif + } + Bool IsReleaseCurrentRequest(EGLDisplay dpy, EGLSurface draw, EGLSurface read, EGLContext ctx) { (void)dpy; return draw == EGL_NO_SURFACE && read == EGL_NO_SURFACE && ctx == EGL_NO_CONTEXT; @@ -995,6 +1003,14 @@ namespace MobileGL::MG_Backend::DirectGLES { Bool BackendObject_DirectGLES::InitWindowSurface() { const EGLSurface activating = EGLRegistry().ActivatingSurface(); + if (UsesLocalEGLContexts() && activating != EGL_NO_SURFACE) { + if (m_nativeSurfaces.find(activating) != m_nativeSurfaces.end()) return true; + EGLSurface native = EGL_NO_SURFACE; + auto window = reinterpret_cast(EGLRegistry().CurrentWindowHandle().Handle); + if (!DirectGLES::InitWindowSurface(window, &native)) return false; + m_nativeSurfaces[activating] = native; + return true; + } if (RebindNativeSurfaceFor(activating)) return true; // A suspended surface whose placeholder went: another placeholder - never the window, which // is gone. @@ -1103,13 +1119,10 @@ namespace MobileGL::MG_Backend::DirectGLES { // and its objects. ResetRuntimeState still runs because the registry's per-surface // bookkeeping (which surface is active, which threads made it current) does describe the // surface that is being replaced. + if (UsesLocalEGLContexts()) return BackendObject::CreateEGLWindowSurface(surface, handle); +#if MOBILEGL_BUILD_DISAGGREGATED const EGLSurface previous = egl.HasActiveSurface() ? egl.ActiveSurface() : EGL_NO_SURFACE; const EGLSurface previousNativeDraw = DirectGLES::CurrentContextDrawSurface(); - if (egl.HasActiveSurface()) { - egl.ResetRuntimeState(); - } - -#if MOBILEGL_BUILD_DISAGGREGATED // ID-54 / ID-67: the surface's creation bound natively (InitWindowSurface -> MakeCurrent); // the first virtual tuple adopts that bind. On failure nothing is known to be bound. The // pull arm below is the original statement, byte for byte (G1). @@ -1145,11 +1158,9 @@ namespace MobileGL::MG_Backend::DirectGLES { // P14 S4: as for the window surface above - the native context is the (session, context // token) tuple's and survives a surface switch. This used to be DestroyEGLContext(). + if (UsesLocalEGLContexts()) return BackendObject::CreateEGLPbufferSurface(surface, width, height); const EGLSurface previous = egl.HasActiveSurface() ? egl.ActiveSurface() : EGL_NO_SURFACE; const EGLSurface previousNativeDraw = DirectGLES::CurrentContextDrawSurface(); - if (egl.HasActiveSurface()) { - egl.ResetRuntimeState(); - } // ID-54 / ID-67: as for the window surface - InitPbufferSurface bound natively. The pull // arm below is the original statement, byte for byte (G1). @@ -1172,8 +1183,8 @@ namespace MobileGL::MG_Backend::DirectGLES { if (!record || record->Kind != EGLSurfaceRegistry::SurfaceKind::Pbuffer || native == m_nativeSurfaces.end()) { return BackendObject::ResizeEGLWindowSurface(surface, width, height); } - // A pbuffer has no resize: the client surface gets a new native pbuffer at the new size, - // and every context that drew to the old one draws to the new one. + // Replacing a current pbuffer requires a bind on its owning thread. + if (UsesLocalEGLContexts() && EGLRegistry().IsCurrentOnOtherThread(surface)) return false; const EGLint w = static_cast(std::max(width, 1)); const EGLint h = static_cast(std::max(height, 1)); const EGLSurface replacement = DirectGLES::CreateSessionPbuffer(w, h); @@ -1181,13 +1192,23 @@ namespace MobileGL::MG_Backend::DirectGLES { MGLOG_E("ResizeEGLWindowSurface: no %dx%d pbuffer could replace the old drawable", w, h); return false; } - DirectGLES::ReplaceSessionSurface(native->second, replacement); + if (!DirectGLES::ReplaceSessionSurface(native->second, replacement)) { + DirectGLES::DestroySessionSurface(replacement); + return false; + } native->second = replacement; return BackendObject::ResizeEGLWindowSurface(surface, width, height); } Bool BackendObject_DirectGLES::InitPbufferSurface(EGLint width, EGLint height) { const EGLSurface activating = EGLRegistry().ActivatingSurface(); + if (UsesLocalEGLContexts() && activating != EGL_NO_SURFACE) { + if (m_nativeSurfaces.find(activating) != m_nativeSurfaces.end()) return true; + EGLSurface native = EGL_NO_SURFACE; + if (!DirectGLES::InitPbufferSurface(width, height, &native)) return false; + m_nativeSurfaces[activating] = native; + return true; + } if (RebindNativeSurfaceFor(activating)) return true; if (!DirectGLES::InitPbufferSurface(width, height)) return false; if (activating != EGL_NO_SURFACE) { @@ -1196,6 +1217,33 @@ namespace MobileGL::MG_Backend::DirectGLES { return true; } + void BackendObject_DirectGLES::RegisterEGLContext(EGLContext context, Uint64 token, Uint64 shareGroup) { + const auto lock = EGLRegistry().Lock(); + m_contexts.insert_or_assign(context, ContextIdentity{token, shareGroup}); + } + + void BackendObject_DirectGLES::ReleaseEGLContext(Uint64 token) { + const auto lock = EGLRegistry().Lock(); + const auto it = std::find_if(m_contexts.begin(), m_contexts.end(), + [token](const auto& entry) { return entry.second.Token == token; }); + if (it == m_contexts.end()) return; + const Uint64 shareGroup = it->second.ShareGroup; + m_contexts.erase(it); + const Bool groupLives = std::any_of(m_contexts.begin(), m_contexts.end(), [shareGroup](const auto& entry) { + return entry.second.ShareGroup == shareGroup; + }); + if (!groupLives) BufferImpl::OnShareGroupDestroyed(0, shareGroup); + DirectGLES::DestroyNativeContextFor(token); + } + + Uint64 BackendObject_DirectGLES::SetEGLObjectShareGroup(Uint64 shareGroup) { + return DirectGLES::SetMonolithObjectShareGroup(shareGroup); + } + + void BackendObject_DirectGLES::BeginEGLCommands() { + DirectGLES::BeginMonolithCommands(); + } + Bool BackendObject_DirectGLES::MakeEGLCurrent(EGLDisplay dpy, EGLSurface draw, EGLSurface read, EGLContext ctx) { const auto lock = EGLRegistry().Lock(); if (IsReleaseCurrentRequest(dpy, draw, read, ctx)) { @@ -1211,19 +1259,41 @@ namespace MobileGL::MG_Backend::DirectGLES { return false; } const EGLSurfaceRegistry& egl = EGLRegistry(); - if (!egl.DisplayInitialized() || egl.Display() != dpy) { + if (!egl.DisplayInitialized(dpy)) { MGLOG_E("MakeEGLCurrent failed: EGL display mismatch or not initialized"); return false; } - if (!egl.HasActiveSurface()) { - MGLOG_E("MakeEGLCurrent failed: EGL surface is not initialized"); + if (!egl.IsRegistered(draw)) { + MGLOG_E("MakeEGLCurrent failed: EGL surface is not registered"); return false; } - if (draw == EGL_NO_SURFACE || read == EGL_NO_SURFACE || ctx == EGL_NO_CONTEXT) { + if (draw == EGL_NO_SURFACE || draw != read || ctx == EGL_NO_CONTEXT) { MGLOG_E("MakeEGLCurrent failed: draw/read/context is invalid"); return false; } + if (const auto identity = m_contexts.find(ctx); identity != m_contexts.end()) { + const auto record = egl.Find(draw); + const auto native = m_nativeSurfaces.find(draw); + if (!record || record->Display != dpy || record->DestroyPending || native == m_nativeSurfaces.end()) + return false; + const auto oldBinding = egl.CurrentOn(std::this_thread::get_id()); + if (!DirectGLES::BindMonolithNativeContext(identity->second.Token, identity->second.ShareGroup, + native->second)) + return false; + if (BackendObject::MakeEGLCurrent(dpy, draw, read, ctx)) return true; + if (oldBinding) { + const auto previous = m_contexts.find(oldBinding->Context); + const auto previousNative = m_nativeSurfaces.find(oldBinding->DrawSurface); + if (previous != m_contexts.end() && previousNative != m_nativeSurfaces.end() && + DirectGLES::BindMonolithNativeContext(previous->second.Token, previous->second.ShareGroup, + previousNative->second)) + return false; + } + (void)DirectGLES::ReleaseCurrent(); + return false; + } + #if MOBILEGL_BUILD_DISAGGREGATED // ID-54 / C7, the native half of "bind once per tuple" (v1, under ID-52/ID-59's grant for // this file; #if-guarded so the pull build is byte-identical). Under an active transport diff --git a/MobileGL/MG_Backend/DirectGLES/BackendObject_DirectGLES.h b/MobileGL/MG_Backend/DirectGLES/BackendObject_DirectGLES.h index 1590ded0..754fe209 100644 --- a/MobileGL/MG_Backend/DirectGLES/BackendObject_DirectGLES.h +++ b/MobileGL/MG_Backend/DirectGLES/BackendObject_DirectGLES.h @@ -60,6 +60,10 @@ namespace MobileGL::MG_Backend::DirectGLES { Bool ExportNativeFence(int* fence) override; void ReleaseEGLSurface(EGLSurface surface) override; void ReleaseEGLResources() override; + void RegisterEGLContext(EGLContext context, Uint64 token, Uint64 shareGroup) override; + void ReleaseEGLContext(Uint64 token) override; + Uint64 SetEGLObjectShareGroup(Uint64 shareGroup) override; + void BeginEGLCommands() override; // The server window going and coming back: each window surface on it swaps its native EGL // window surface for a placeholder pbuffer and back (DirectGLES::Suspend/ResumeSessionWindowSurface). Bool SuspendServerWindow(void* window) override; @@ -88,6 +92,11 @@ namespace MobileGL::MG_Backend::DirectGLES { // surface natively; put the previous one back for the context that held it. void RestoreSurfaceAfterCreation(EGLSurface previousNativeDraw); + struct ContextIdentity { + Uint64 Token; + Uint64 ShareGroup; + }; + UnorderedMap m_contexts; Bool m_initialized = false; // P14: ONE NATIVE SURFACE PER CLIENT SURFACE, created on its first activation and re-bound // on every later one. A multi-window client switches surfaces every frame; making a new diff --git a/MobileGL/MG_Backend/DirectGLES/DirectGLES.h b/MobileGL/MG_Backend/DirectGLES/DirectGLES.h index 7de760ea..3daed462 100644 --- a/MobileGL/MG_Backend/DirectGLES/DirectGLES.h +++ b/MobileGL/MG_Backend/DirectGLES/DirectGLES.h @@ -89,8 +89,9 @@ namespace MobileGL::MG_Backend::DirectGLES { GLenum format); void GetIntegeri_v(GLenum target, GLuint index, GLint* data); void ShaderStorageBlockBinding(GLuint program, const GLchar* storageBlockName, GLuint storageBlockBinding); - Bool InitWindowSurface(NativeWindowType window); - Bool InitPbufferSurface(EGLint width, EGLint height); + Bool InitWindowSurface(NativeWindowType window, EGLSurface* unbound = nullptr); + Bool InitPbufferSurface(EGLint width, EGLint height, EGLSurface* unbound = nullptr); + void BeginMonolithCommands(); // The calling thread's session's current native draw surface (the one the last Init*Surface // created, or the last BindSessionSurface named). EGLSurface CurrentSessionDrawSurface(); @@ -117,9 +118,9 @@ namespace MobileGL::MG_Backend::DirectGLES { // A new pbuffer of the calling thread's session, created with the active context's config and // bound to nothing (EGL: creating a surface changes no binding). EGLSurface CreateSessionPbuffer(EGLint width, EGLint height); - // Every context of the session that drew to `previous` draws to `replacement` instead, and - // `previous` is destroyed (a pbuffer-backed window's resize). - void ReplaceSessionSurface(EGLSurface previous, EGLSurface replacement); + // Replace an owned surface after rebinding it on the calling thread, if current there. + // On failure both surfaces remain registered and the current binding is unchanged. + Bool ReplaceSessionSurface(EGLSurface previous, EGLSurface replacement); // The server window going away (screen off): every context of the session that drew to the // window surface `windowSurface` draws to a new 1x1 placeholder pbuffer instead, and the window // surface is destroyed - no longer current anywhere once this returns. The contexts and their @@ -312,6 +313,8 @@ namespace MobileGL::MG_Backend::DirectGLES { // contexts are untouched; the display is terminated only when the last context in the process // has gone. void DestroyNativeContextFor(Uint64 contextToken); + Bool BindMonolithNativeContext(Uint64 token, Uint64 shareGroup, EGLSurface surface); + Uint64 SetMonolithObjectShareGroup(Uint64 shareGroup); // ---- objects that belong to ONE native context ---- // diff --git a/MobileGL/MG_Backend/DirectGLES/DirectGLESContext.cpp b/MobileGL/MG_Backend/DirectGLES/DirectGLESContext.cpp index 25231738..d30931a1 100644 --- a/MobileGL/MG_Backend/DirectGLES/DirectGLESContext.cpp +++ b/MobileGL/MG_Backend/DirectGLES/DirectGLESContext.cpp @@ -82,9 +82,8 @@ namespace MobileGL::MG_Backend::DirectGLES { // draw surface (NoteDrawSurfaceMoved at each `session.Draw =`). Surface creation and destruction // also move g_nativeRegistryEpoch, which the size memo keys on as well. std::atomic g_surfaceSizeEpoch{1}; - // Never erased while the process lives: a context teardown marks its tuple dead (Context = - // EGL_NO_CONTEXT) instead of freeing it, so a cached pointer is never dangling between the - // epoch bump and the next resolution. + // Context switches and teardown run under the backend command lock. The registry epoch + // invalidates each thread's cached pointer before its next context lookup. Vector& NativeContexts() { static Vector* contexts = new Vector(); return *contexts; @@ -116,8 +115,15 @@ namespace MobileGL::MG_Backend::DirectGLES { outKey->SessionKey = 0; outKey->ShareGroupKey = 0; const TwinKeyResolver resolver = g_twinKeyResolver.load(std::memory_order_acquire); - if (resolver == nullptr) return false; - return resolver(outKey); + if (t_native.monolithShareGroup != 0) { + outKey->ShareGroupKey = t_native.monolithShareGroup; + return true; + } + return resolver != nullptr && resolver(outKey); + } + + Uint64 SetMonolithObjectShareGroup(Uint64 shareGroup) { + return std::exchange(t_native.monolithShareGroup, shareGroup); } Uint64 CurrentNativeSessionKey() { @@ -198,13 +204,7 @@ namespace MobileGL::MG_Backend::DirectGLES { NativeThreadState& tls = t_native; Uint64 session = 0; Uint64 token = 0; - if (tls.forcedValid) { - session = tls.forcedSession; - token = tls.forcedToken; - } else { - const NativeContextKeyResolver resolver = g_nativeContextKeyResolver.load(std::memory_order_acquire); - if (resolver != nullptr) (void)resolver(&session, &token); - } + ResolveNativeKey(session, token); const Uint64 epoch = g_nativeRegistryEpoch.load(std::memory_order_acquire); if (tls.activeTuple != nullptr && tls.activeEpoch == epoch && tls.activeSession == session && tls.activeToken == token) { @@ -275,6 +275,7 @@ namespace MobileGL::MG_Backend::DirectGLES { // The display's one-time initialization. Returns false only when there is no EGL to talk to. static Bool EnsureDisplayInitialized() { + if (g_EGLFuncs.eglBindAPI) g_EGLFuncs.eglBindAPI(EGL_OPENGL_ES_API); if (g_Display != EGL_NO_DISPLAY) return true; if (!g_EGLFuncs.eglGetDisplay) return false; g_Display = g_EGLFuncs.eglGetDisplay(EGL_DEFAULT_DISPLAY); @@ -283,7 +284,6 @@ namespace MobileGL::MG_Backend::DirectGLES { g_Display = EGL_NO_DISPLAY; return false; } - if (g_EGLFuncs.eglBindAPI) g_EGLFuncs.eglBindAPI(EGL_OPENGL_ES_API); return true; } @@ -313,7 +313,7 @@ namespace MobileGL::MG_Backend::DirectGLES { } // P14 S4: the surface is the SESSION's, not the process's - the tuple that draws to it is // one of the session's contexts. - const EGLSurface surface = ActiveNativeSession().Draw; + const EGLSurface surface = CurrentContextDrawSurface(); if (!g_EGLFuncs.eglQuerySurface || g_Display == EGL_NO_DISPLAY || surface == EGL_NO_SURFACE) { return false; } @@ -715,8 +715,7 @@ namespace MobileGL::MG_Backend::DirectGLES { DiagnoseEsprytSlotArm(); } - // RESET NOTIFICATION, decided once per process by its first native context (EnsureNativeContext - // says why). MOBILEGL_ESPRYT_RESET_NOTIFICATION=0 keeps the driver's default. + // Split native contexts agree on one reset strategy. Monolith leaves the driver default. namespace { // EGL_EXT_create_context_robustness (eglext.h is not part of this file's include set). @@ -730,6 +729,7 @@ namespace MobileGL::MG_Backend::DirectGLES { std::atomic g_resetNotification{ResetNotification::Undecided}; Bool ResetNotificationWanted() { + if (MG_Config::Transport == MG_Config::TransportMode::Monolith) return false; const ResetNotification decided = g_resetNotification.load(std::memory_order_acquire); if (decided != ResetNotification::Undecided) return decided == ResetNotification::On; if (const char* value = std::getenv("MOBILEGL_ESPRYT_RESET_NOTIFICATION"); @@ -755,6 +755,7 @@ namespace MobileGL::MG_Backend::DirectGLES { } void NoteResetNotificationDecided(Bool used) { + if (MG_Config::Transport == MG_Config::TransportMode::Monolith) return; ResetNotification expected = ResetNotification::Undecided; const ResetNotification decided = used ? ResetNotification::On : ResetNotification::Off; if (g_resetNotification.compare_exchange_strong(expected, decided, std::memory_order_acq_rel)) @@ -766,7 +767,8 @@ namespace MobileGL::MG_Backend::DirectGLES { } // namespace Bool NativeContextsNotifyResets() { - return g_resetNotification.load(std::memory_order_acquire) == ResetNotification::On; + return MG_Config::Transport != MG_Config::TransportMode::Monolith && + g_resetNotification.load(std::memory_order_acquire) == ResetNotification::On; } static Bool EnsureNativeContext(NativeContextTuple& tuple, EGLint surfaceBit, NativeWindowType window) { @@ -862,6 +864,33 @@ namespace MobileGL::MG_Backend::DirectGLES { return true; } + Bool BindMonolithNativeContext(Uint64 token, Uint64 shareGroup, EGLSurface surface) { + auto& session = ActiveNativeSession(); + const auto* drawable = FindSessionSurfaceLocked(session, surface); + if (drawable == nullptr) return false; + + const Uint64 previousToken = std::exchange(t_native.monolithToken, token); + const Uint64 previousGroup = SetMonolithObjectShareGroup(shareGroup); + auto& tuple = ActiveNativeContext(); + if (tuple.Context == EGL_NO_CONTEXT) { + tuple.Config = drawable->Config; + tuple.ShareGroupToken = shareGroup; + } + const EGLSurface previousDraw = session.Draw; + const EGLSurface previousRead = session.Read; + if (EnsureNativeContext(tuple, EGL_PBUFFER_BIT, static_cast(0)) && + SelectSessionSurface(surface) && MakeCurrent()) { + PublishDefaultFramebufferDepthStencilFormat(); + return true; + } + + session.Draw = previousDraw; + session.Read = previousRead; + t_native.monolithToken = previousToken; + SetMonolithObjectShareGroup(previousGroup); + return false; + } + Bool CreateNativeContextFor(Uint64 contextToken, Uint64 shareGroupToken) { if (contextToken == 0) return false; const Uint64 sessionKey = CurrentNativeSessionKey(); @@ -893,7 +922,13 @@ namespace MobileGL::MG_Backend::DirectGLES { if (contextToken == 0) return; const std::lock_guard lock(g_nativeRegistryMutex); NativeContextTuple* tuple = FindNativeContext(sessionKey, contextToken); - if (tuple == nullptr || tuple->Context == EGL_NO_CONTEXT) return; + if (tuple == nullptr) return; + if (tuple->Context == EGL_NO_CONTEXT) { + std::erase(NativeContexts(), tuple); + delete tuple; + g_nativeRegistryEpoch.fetch_add(1, std::memory_order_acq_rel); + return; + } #if MOBILEGL_BUILD_DISAGGREGATED // Its last shared-image reads, fenced while it is still current. if (t_native.boundContext == tuple->Context) SharedImageImpl::PublishPendingReads(); @@ -915,11 +950,8 @@ namespace MobileGL::MG_Backend::DirectGLES { t_nativeContextThread.BoundSerial = 0; } ForgetNativeContextObjects(tuple->Serial); - tuple->Serial = 0; - tuple->Context = EGL_NO_CONTEXT; - tuple->Config = nullptr; - tuple->Draw = EGL_NO_SURFACE; - tuple->Read = EGL_NO_SURFACE; + std::erase(NativeContexts(), tuple); + delete tuple; g_nativeRegistryEpoch.fetch_add(1, std::memory_order_acq_rel); if (g_displayUsers > 0) --g_displayUsers; // NOT WHILE A SESSION STILL HOLDS SURFACES. eglTerminate destroys them with the display, and @@ -978,7 +1010,7 @@ namespace MobileGL::MG_Backend::DirectGLES { } EGLSurface CurrentContextDrawSurface() { - return ActiveNativeContext().Draw; + return t_native.boundDraw; } namespace { @@ -1064,7 +1096,7 @@ namespace MobileGL::MG_Backend::DirectGLES { if (t_windowBufferFlushIssued) return; t_windowBufferFlushIssued = true; NativeSessionState& session = ActiveNativeSession(); - const EGLSurface surface = session.Draw; + const EGLSurface surface = CurrentContextDrawSurface(); if (surface == EGL_NO_SURFACE) return; { const std::lock_guard lock(g_nativeRegistryMutex); @@ -1076,7 +1108,7 @@ namespace MobileGL::MG_Backend::DirectGLES { Int32 CurrentDrawBufferAge(Bool damageRegionFollows) { NativeSessionState& session = ActiveNativeSession(); - const EGLSurface surface = session.Draw; + const EGLSurface surface = CurrentContextDrawSurface(); if (surface == EGL_NO_SURFACE || g_Display == EGL_NO_DISPLAY) return 0; Bool window = false; Uint64 presents = 0; @@ -1102,7 +1134,7 @@ namespace MobileGL::MG_Backend::DirectGLES { Bool SetCurrentDrawDamageRegion(const MG_Util::Damage::Region& region) { NativeSessionState& session = ActiveNativeSession(); - const EGLSurface surface = session.Draw; + const EGLSurface surface = CurrentContextDrawSurface(); if (surface == EGL_NO_SURFACE || g_Display == EGL_NO_DISPLAY) return true; { const std::lock_guard lock(g_nativeRegistryMutex); @@ -1158,14 +1190,18 @@ namespace MobileGL::MG_Backend::DirectGLES { if (surface == EGL_NO_SURFACE) return EGL_NO_SURFACE; NativeSessionState& session = ActiveNativeSession(); const std::lock_guard lock(g_nativeRegistryMutex); - session.Surfaces.push_back({static_cast(0), surface}); + session.Surfaces.push_back({static_cast(0), surface, 0, tuple.Config}); g_nativeRegistryEpoch.fetch_add(1, std::memory_order_acq_rel); return surface; } - void ReplaceSessionSurface(EGLSurface previous, EGLSurface replacement) { - if (previous == EGL_NO_SURFACE || replacement == EGL_NO_SURFACE || previous == replacement) return; + static Bool MakeCurrentOnSurface(EGLSurface draw, EGLSurface read); + + Bool ReplaceSessionSurface(EGLSurface previous, EGLSurface replacement) { NativeSessionState& session = ActiveNativeSession(); + if (!SessionOwnsSurface(session, previous) || !SessionOwnsSurface(session, replacement)) return false; + if (previous == replacement) return true; + if (t_native.boundDraw == previous && !MakeCurrentOnSurface(replacement, replacement)) return false; { const std::lock_guard lock(g_nativeRegistryMutex); for (auto* tuple : NativeContexts()) { @@ -1185,11 +1221,9 @@ namespace MobileGL::MG_Backend::DirectGLES { NoteDrawSurfaceMoved(); } if (session.Read == previous) session.Read = replacement; - // The calling thread drew to the old one: draw to the new one from here (the old is then - // no longer current, and its destruction below is immediate). - if (t_native.boundDraw == previous && ActiveNativeContext().Context != EGL_NO_CONTEXT) (void)MakeCurrent(); if (g_EGLFuncs.eglDestroySurface && g_Display != EGL_NO_DISPLAY) g_EGLFuncs.eglDestroySurface(g_Display, previous); + return true; } void DestroySessionSurface(EGLSurface surface) { @@ -1236,7 +1270,7 @@ namespace MobileGL::MG_Backend::DirectGLES { void ApplyRequestedSwapInterval() { if (g_requestedSwapInterval < 0) return; - const EGLSurface surface = ActiveNativeSession().Draw; + const EGLSurface surface = CurrentContextDrawSurface(); if (!g_EGLFuncs.eglSwapInterval || g_Display == EGL_NO_DISPLAY || surface == EGL_NO_SURFACE) return; const EGLBoolean ok = g_EGLFuncs.eglSwapInterval(g_Display, g_requestedSwapInterval); MGLOG_D("DirectGLES: applied native swap interval %d (%s)", g_requestedSwapInterval, ok ? "ok" : "failed"); @@ -1318,10 +1352,13 @@ namespace MobileGL::MG_Backend::DirectGLES { reinterpret_cast(windowSurface), static_cast(error)); return EGL_NO_SURFACE; } - ReplaceSessionSurface(windowSurface, placeholder); - // The rebind onto the placeholder failed and the window surface is still current here - EGL - // destroys a current surface only once it is not, and the window goes when this returns. - if (t_native.boundDraw == windowSurface) (void)ReleaseCurrent(); + if (!ReplaceSessionSurface(windowSurface, placeholder)) { + // Unbind before retiring a window the platform is about to release. + if (!ReleaseCurrent() || !ReplaceSessionSurface(windowSurface, placeholder)) { + DestroySessionSurface(placeholder); + return EGL_NO_SURFACE; + } + } return placeholder; } @@ -1340,11 +1377,13 @@ namespace MobileGL::MG_Backend::DirectGLES { NativeSessionState& session = ActiveNativeSession(); { const std::lock_guard lock(g_nativeRegistryMutex); - session.Surfaces.push_back({window, surface}); + session.Surfaces.push_back({window, surface, 0, tuple.Config}); g_nativeRegistryEpoch.fetch_add(1, std::memory_order_acq_rel); } - if (placeholder != EGL_NO_SURFACE && SessionOwnsSurface(session, placeholder)) { - ReplaceSessionSurface(placeholder, surface); + if (placeholder != EGL_NO_SURFACE && SessionOwnsSurface(session, placeholder) && + !ReplaceSessionSurface(placeholder, surface)) { + DestroySessionSurface(surface); + return EGL_NO_SURFACE; } // Bound, because the publish below reads the default framebuffer. if (!BindSessionSurface(surface) || t_native.boundDraw != surface) { @@ -1358,7 +1397,7 @@ namespace MobileGL::MG_Backend::DirectGLES { return surface; } - Bool InitWindowSurface(NativeWindowType window) { + Bool InitWindowSurface(NativeWindowType window, EGLSurface* unbound) { if (!window) return false; DiagnoseEsprytSlotArmAtBringUp(); @@ -1366,7 +1405,7 @@ namespace MobileGL::MG_Backend::DirectGLES { NativeContextTuple& tuple = ActiveNativeContext(); if (!EnsureNativeContext(tuple, EGL_WINDOW_BIT, window)) return false; - DestroyStaleSurfacesOnWindow(window); + if (unbound == nullptr) DestroyStaleSurfacesOnWindow(window); const EGLSurface surface = g_EGLFuncs.eglCreateWindowSurface(g_Display, tuple.Config, window, nullptr); if (surface == EGL_NO_SURFACE) { @@ -1376,7 +1415,11 @@ namespace MobileGL::MG_Backend::DirectGLES { return false; } NativeSessionState& session = ActiveNativeSession(); - session.Surfaces.push_back({window, surface}); + session.Surfaces.push_back({window, surface, 0, tuple.Config}); + if (unbound != nullptr) { + *unbound = surface; + return true; + } session.Draw = surface; NoteDrawSurfaceMoved(); session.Read = surface; @@ -1393,7 +1436,7 @@ namespace MobileGL::MG_Backend::DirectGLES { return true; } - Bool InitPbufferSurface(EGLint width, EGLint height) { + Bool InitPbufferSurface(EGLint width, EGLint height, EGLSurface* unbound) { if (width <= 0 || height <= 0) return false; DiagnoseEsprytSlotArmAtBringUp(); @@ -1405,7 +1448,11 @@ namespace MobileGL::MG_Backend::DirectGLES { const EGLSurface surface = g_EGLFuncs.eglCreatePbufferSurface(g_Display, tuple.Config, surfaceAttribs); if (surface == EGL_NO_SURFACE) return false; NativeSessionState& session = ActiveNativeSession(); - session.Surfaces.push_back({static_cast(0), surface}); + session.Surfaces.push_back({static_cast(0), surface, 0, tuple.Config}); + if (unbound != nullptr) { + *unbound = surface; + return true; + } session.Draw = surface; NoteDrawSurfaceMoved(); session.Read = surface; @@ -1420,7 +1467,7 @@ namespace MobileGL::MG_Backend::DirectGLES { surface, tuple.Context, width, height); return true; } - // The single backend ES context migrates between app threads (FCL/pojav-style + // The backend turn follows the thread whose binding shadows are active (FCL/pojav-style // LWJGL hands the EGL context from JVM thread to JVM thread). Ownership must // live in ONE global slot: a per-thread flag can never be cleared on the // LOSING thread when another thread takes (or destroys/releases) the context, @@ -1483,13 +1530,13 @@ namespace MobileGL::MG_Backend::DirectGLES { } Bool MakeCurrent() { - // P14 S4: the context comes from the calling thread's tuple (the session's bound token), - // the surface from the session. Both halves used to be file-level singletons. - NativeContextTuple& tuple = ActiveNativeContext(); NativeSessionState& session = ActiveNativeSession(); - tuple.Draw = session.Draw; - tuple.Read = session.Read; - if (!g_EGLFuncs.eglMakeCurrent || g_Display == EGL_NO_DISPLAY || session.Draw == EGL_NO_SURFACE || + return MakeCurrentOnSurface(session.Draw, session.Read); + } + + static Bool MakeCurrentOnSurface(EGLSurface draw, EGLSurface read) { + NativeContextTuple& tuple = ActiveNativeContext(); + if (!g_EGLFuncs.eglMakeCurrent || g_Display == EGL_NO_DISPLAY || draw == EGL_NO_SURFACE || tuple.Context == EGL_NO_CONTEXT) { MGLOG_E_ONCE("DirectGLES::MakeCurrent failed: EGL display/surface/context is not initialized"); return false; @@ -1500,15 +1547,17 @@ namespace MobileGL::MG_Backend::DirectGLES { SharedImageImpl::PublishPendingReads(); } #endif - if (!g_EGLFuncs.eglMakeCurrent(g_Display, session.Draw, session.Draw, tuple.Context)) { + if (!g_EGLFuncs.eglMakeCurrent(g_Display, draw, draw, tuple.Context)) { const EGLint error = g_EGLFuncs.eglGetError ? g_EGLFuncs.eglGetError() : EGL_SUCCESS; MGLOG_E_ONCE("DirectGLES::MakeCurrent failed: native eglMakeCurrent returned error 0x%04x", error); return false; } + tuple.Draw = draw; + tuple.Read = read; g_EGLFuncs.eglSwapBuffersWithDamageEXT = MG_Util::BackendLoader::ResolveSwapBuffersWithDamage(g_EGLFuncs); InvalidateEglVerifiedStamp(); t_native.boundContext = tuple.Context; - t_native.boundDraw = session.Draw; + t_native.boundDraw = draw; t_nativeContextThread.BoundSerial = tuple.Serial; g_backendContextOwnerThread.store(std::this_thread::get_id(), std::memory_order_release); // The ops table may have been unregistered when a previous ES context was @@ -1535,6 +1584,12 @@ namespace MobileGL::MG_Backend::DirectGLES { InvalidateNativeBindingShadows(); } + void BeginMonolithCommands() { + if (g_backendContextOwnerThread.load(std::memory_order_acquire) != std::this_thread::get_id()) { + OnBackendTurnHandoff(); + } + } + Bool ReleaseCurrent() { if (!g_EGLFuncs.eglMakeCurrent || g_Display == EGL_NO_DISPLAY) { InvalidateEglVerifiedStamp(); @@ -1556,6 +1611,8 @@ namespace MobileGL::MG_Backend::DirectGLES { t_native.boundContext = EGL_NO_CONTEXT; t_native.boundDraw = EGL_NO_SURFACE; t_nativeContextThread.BoundSerial = 0; + t_native.monolithToken = 0; + SetMonolithObjectShareGroup(0); g_backendContextOwnerThread.store(std::thread::id{}, std::memory_order_release); return true; } diff --git a/MobileGL/MG_Backend/DirectGLES/DirectGLESDraw.cpp b/MobileGL/MG_Backend/DirectGLES/DirectGLESDraw.cpp index 4cca0bc3..b2bdd330 100644 --- a/MobileGL/MG_Backend/DirectGLES/DirectGLESDraw.cpp +++ b/MobileGL/MG_Backend/DirectGLES/DirectGLESDraw.cpp @@ -1137,7 +1137,8 @@ namespace MobileGL::MG_Backend::DirectGLES { const SizeT commandBytes = commandOffset + static_cast(stride) * static_cast(maxdrawcount - 1) + sizeof(DrawElementsIndirectCommand); auto* drawResource = BufferImpl::FindBufferResourceForHandle(applierState.VerbIndirectBuffer); - auto* paramResource = BufferImpl::FindBufferResourceForHandle(applierState.VerbIndirectParameterBuffer); + auto* paramResource = + BufferImpl::EnsureBufferResourceForHandle(nullptr, applierState.VerbIndirectParameterBuffer); // P8-C: the count is CONSUMED here, so the parameter buffer is made current first // (a store a shader wrote on this side is read back); the command buffer only gets a // first copy when it has none - its fields are made current by the executor, and @@ -1249,7 +1250,8 @@ namespace MobileGL::MG_Backend::DirectGLES { const SizeT commandBytes = commandOffset + static_cast(stride) * static_cast(maxdrawcount - 1) + sizeof(DrawArraysIndirectCommand); auto* drawResource = BufferImpl::FindBufferResourceForHandle(applierState.VerbIndirectBuffer); - auto* paramResource = BufferImpl::FindBufferResourceForHandle(applierState.VerbIndirectParameterBuffer); + auto* paramResource = + BufferImpl::EnsureBufferResourceForHandle(nullptr, applierState.VerbIndirectParameterBuffer); // P8-C: the count is CONSUMED here, so the parameter buffer is made current first // (a store a shader wrote on this side is read back); the command buffer only gets a // first copy when it has none - its fields are made current by the executor, and diff --git a/MobileGL/MG_Backend/DirectGLES/DirectGLESInternal.h b/MobileGL/MG_Backend/DirectGLES/DirectGLESInternal.h index 22a9fe60..7e456834 100644 --- a/MobileGL/MG_Backend/DirectGLES/DirectGLESInternal.h +++ b/MobileGL/MG_Backend/DirectGLES/DirectGLESInternal.h @@ -945,6 +945,7 @@ namespace MobileGL::MG_Backend::DirectGLES { // Presents made on this native surface since it was created: a pbuffer's content is // the last presented frame once there has been one (its buffer age is then 1). Uint64 Presents = 0; + EGLConfig Config = nullptr; }; Vector Surfaces; // The surface the session currently draws to / reads from - what a bind to another context @@ -980,6 +981,8 @@ namespace MobileGL::MG_Backend::DirectGLES { Bool forcedValid = false; Uint64 forcedSession = 0; Uint64 forcedToken = 0; + Uint64 monolithToken = 0; + Uint64 monolithShareGroup = 0; NativeContextTuple* activeTuple = nullptr; Uint64 activeEpoch = 0; Uint64 activeSession = 0; @@ -1002,7 +1005,7 @@ namespace MobileGL::MG_Backend::DirectGLES { return; } outSession = 0; - outToken = 0; + outToken = t_native.monolithToken; const NativeContextKeyResolver resolver = g_nativeContextKeyResolver.load(std::memory_order_acquire); if (resolver != nullptr) (void)resolver(&outSession, &outToken); } diff --git a/MobileGL/MG_Backend/DirectGLES/DirectGLESSync.cpp b/MobileGL/MG_Backend/DirectGLES/DirectGLESSync.cpp index 1300d8d3..17126f84 100644 --- a/MobileGL/MG_Backend/DirectGLES/DirectGLESSync.cpp +++ b/MobileGL/MG_Backend/DirectGLES/DirectGLESSync.cpp @@ -17,14 +17,10 @@ namespace MobileGL::MG_Backend::DirectGLES { Uint contextGeneration = 0; }; - // Backend timer-query handle: a native GL query object name plus the - // ES context generation it was created under. Stale-generation - // handles read as available with a zero result, and deleting them - // only frees the wrapper (the dead ES context already reclaimed the - // query object). + // Query names belong to the native context that allocated them. struct GLESQueryObject { GLuint queryId = 0; - Uint contextGeneration = 0; + Uint64 nativeContextSerial = 0; // Non-zero for the core (non-timer) query targets - occlusion and transform // feedback primitives - and then holds the glBeginQuery target, which glEndQuery // needs back. Their results are counts reachable only through the core @@ -251,12 +247,12 @@ namespace MobileGL::MG_Backend::DirectGLES { return nullptr; } g_GLESFuncs.glBeginQuery(GL_TIME_ELAPSED, queryId); - return new GLESQueryObject{queryId, g_syncContextGeneration}; + return new GLESQueryObject{queryId, CurrentNativeContextSerial()}; } void EndTimeElapsedQuery(BackendQueryHandle handle) { const auto* query = static_cast(handle); - if (query == nullptr || query->contextGeneration != g_syncContextGeneration || + if (query == nullptr || query->nativeContextSerial != CurrentNativeContextSerial() || !IsBackendContextCurrentOnThisThread() || !g_GLESFuncs.glEndQuery) { return; } @@ -275,7 +271,7 @@ namespace MobileGL::MG_Backend::DirectGLES { return nullptr; } g_GLESFuncs.glQueryCounterEXT(queryId, GL_TIMESTAMP); - return new GLESQueryObject{queryId, g_syncContextGeneration}; + return new GLESQueryObject{queryId, CurrentNativeContextSerial()}; } // The core (non-timer) query targets - occlusion and transform feedback primitives. @@ -296,12 +292,12 @@ namespace MobileGL::MG_Backend::DirectGLES { return nullptr; } g_GLESFuncs.glBeginQuery(target, queryId); - return new GLESQueryObject{queryId, g_syncContextGeneration, target}; + return new GLESQueryObject{queryId, CurrentNativeContextSerial(), target}; } static void EndCoreQuery(BackendQueryHandle handle) { const auto* query = static_cast(handle); - if (query == nullptr || query->coreTarget == 0 || query->contextGeneration != g_syncContextGeneration || + if (query == nullptr || query->coreTarget == 0 || query->nativeContextSerial != CurrentNativeContextSerial() || !IsBackendContextCurrentOnThisThread() || !g_GLESFuncs.glEndQuery) { return; } @@ -344,7 +340,7 @@ namespace MobileGL::MG_Backend::DirectGLES { // not own the ES context also reports available: GetQueryResult64 // then returns false and the frontend keeps the handle for a later // read from the owning thread. - if (query == nullptr || query->contextGeneration != g_syncContextGeneration || + if (query == nullptr || query->nativeContextSerial != CurrentNativeContextSerial() || !IsBackendContextCurrentOnThisThread() || !g_GLESFuncs.glGetQueryObjectuiv) { return true; } @@ -362,7 +358,7 @@ namespace MobileGL::MG_Backend::DirectGLES { // require them): zero is the FINAL result in all three cases, so // report it as produced and let the frontend cache it and release // the handle. - if (query == nullptr || query->contextGeneration != g_syncContextGeneration || + if (query == nullptr || query->nativeContextSerial != CurrentNativeContextSerial() || !g_GLESFuncs.glGetQueryObjectuiv || (query->coreTarget == 0 && !g_GLESFuncs.glGetQueryObjectui64vEXT)) { return true; } @@ -418,7 +414,7 @@ namespace MobileGL::MG_Backend::DirectGLES { if (query == nullptr) { return; } - if (query->contextGeneration == g_syncContextGeneration && IsBackendContextCurrentOnThisThread() && + if (query->nativeContextSerial == CurrentNativeContextSerial() && IsBackendContextCurrentOnThisThread() && g_GLESFuncs.glDeleteQueries) { g_GLESFuncs.glDeleteQueries(1, &query->queryId); } @@ -531,6 +527,7 @@ namespace MobileGL::MG_Backend::DirectGLES { return false; } t_deviceLossLatched = true; + BufferImpl::RevokeResidentBuffersForCurrentSession(); (void)MG_Pipe::MGPipeSessionLatch(MG_Pipe::MGPipeFatalFamily::DeviceLost, "MGPipe: Fatal{BackendDeviceLost, \"Espryt:%s\"} - this session's EGL " "context was reset (glGetGraphicsResetStatus 0x%x); the session ends " @@ -613,7 +610,7 @@ namespace MobileGL::MG_Backend::DirectGLES { // ONLY A WINDOW SURFACE TAKES RECTANGLES: the platform's swap-with-damage hands them to the // surface's native window, and a pbuffer has none (Android's dereferences it regardless). NativeSessionState& session = ActiveNativeSession(); // before the lock: it takes it too - const EGLSurface drawSurface = session.Draw; + const EGLSurface drawSurface = CurrentContextDrawSurface(); Bool windowSurface = false; if (drawSurface != EGL_NO_SURFACE) { const std::lock_guard lock(g_nativeRegistryMutex); diff --git a/MobileGL/MG_Backend/DirectGLES/Managers.cpp b/MobileGL/MG_Backend/DirectGLES/Managers.cpp index a099a6c6..ced2131f 100644 --- a/MobileGL/MG_Backend/DirectGLES/Managers.cpp +++ b/MobileGL/MG_Backend/DirectGLES/Managers.cpp @@ -79,7 +79,7 @@ namespace MobileGL::MG_Backend::DirectGLES { #if MOBILEGL_BUILD_DISAGGREGATED // P12: raised only while DropEveryTwinForEndedServerSession empties the twin tables, on the // apply thread that is the only reader of the twins (Managers.h). - Bool g_serverSessionTwinTeardown = false; + thread_local Bool g_serverSessionTwinTeardown = false; #endif } // namespace @@ -231,10 +231,8 @@ namespace MobileGL::MG_Backend::DirectGLES { buckets += SamplerImpl::g_backendSamplerObjects.DropBucketsOfSession(key.SessionKey); buckets += TextureImpl::g_backendTextureObjects.DropBucketsOfSession(key.SessionKey); buckets += RenderbufferImpl::g_backendRenderbufferObjects.DropBucketsOfSession(key.SessionKey); - buckets += BufferImpl::g_backendBufferResources.DropBucketsOfSession(key.SessionKey); - MGLOG_I("DirectGLES: the ended server session dropped %u twin group(s) across eight kinds " - "(no driver call); the other sessions in this process keep theirs", - buckets); + buckets += BufferImpl::DropBuffersForEndedServerSession(&key); + MGLOG_I("DirectGLES: retired %u twin groups of the ended server session", buckets); } else { SamplerViewImpl::g_backendSamplerViews.ResetBuckets(); FramebufferImpl::g_backendFramebufferObjects.ResetBuckets(); @@ -243,7 +241,7 @@ namespace MobileGL::MG_Backend::DirectGLES { SamplerImpl::g_backendSamplerObjects.ResetBuckets(); TextureImpl::g_backendTextureObjects.ResetBuckets(); RenderbufferImpl::g_backendRenderbufferObjects.ResetBuckets(); - BufferImpl::g_backendBufferResources.ResetBuckets(); + BufferImpl::DropBuffersForEndedServerSession(nullptr); } // P12 review fix (major): AND THE UNIT SHADOWS THAT POINT AT THEM. A texture or sampler twin // scrubs itself out of g_boundTexturesCache / g_boundSamplersCache in its destructor - but diff --git a/MobileGL/MG_Backend/DirectGLES/Managers.h b/MobileGL/MG_Backend/DirectGLES/Managers.h index 043462d7..7c602942 100644 --- a/MobileGL/MG_Backend/DirectGLES/Managers.h +++ b/MobileGL/MG_Backend/DirectGLES/Managers.h @@ -792,7 +792,7 @@ namespace MobileGL::MG_Backend::DirectGLES { Vector bytes; }; Vector pendingResidentWrites; - std::mutex pendingMutex; + mutable std::mutex pendingMutex; // Buffer-mutation epoch (see CurrentBufferMutationEpoch) at which this // resource last probed IsBufferDrawClean == true, 0 = never (epochs start // at 1). Written only on the draw thread; per-draw resource consumers @@ -902,12 +902,15 @@ namespace MobileGL::MG_Backend::DirectGLES { // substitution, the multi-draw index rebase): the R-11 staged copy, or - for a T0 store, // which has none - this server's own coherent map of the client's AHardwareBuffer, read // exactly as the monolith arm reads the adopted map through MappedData(). + Uint CurrentBufferContextGeneration(); + inline const Uint8* SplitHostBytes(const GLESBufferResource& resource) { if (resource.hostBytes != nullptr) return resource.hostBytes; // P13 W4a: any coherent persistent store, not only T0's - monolith's record arm donates // its maps in-process (Ops_H_MapPersistent), and such a store keeps no shadow at all. // Under split the wire's map_persistent declines, so there this is still T0 alone. - return resource.persistentMapped && resource.persistentPtr != nullptr + return resource.persistentMapped && resource.persistentPtr != nullptr && + resource.contextGeneration == CurrentBufferContextGeneration() ? static_cast(resource.persistentPtr) : nullptr; } @@ -1050,12 +1053,6 @@ namespace MobileGL::MG_Backend::DirectGLES { // record. It is what the narrowed-fp64 memo keys its freshness on now that the // frontend change serial is gone from the backend's view. Uint64 ResourceSerialForHandle(MG_Pipe::MGPipeHandle res); - // The ES context generation a twin's driver id must carry to be current. Its one - // consumer is the draw-clean probe's unit test, which has to build a twin that answers - // CLEAN to every question except the one under test - a case that cannot go red for - // that question otherwise. Push-only, like the rest of this block. - Uint CurrentBufferContextGeneration(); - // Registered as the frontend's BufferBackendOps at backend init and on // every MakeCurrent (the ES context can be destroyed and recreated, e.g. // by the trace replayer's probe context). @@ -1067,6 +1064,9 @@ namespace MobileGL::MG_Backend::DirectGLES { // process-wide share group): drops only the ending session's own staged bytes. void OnServerSessionEndedWithOthersLive(); void OnBackendContextDestroyed(); + void OnShareGroupDestroyed(Uint64 sessionKey, Uint64 shareGroupToken); + Uint32 DropBuffersForEndedServerSession(const TwinKey* key); + void RevokeResidentBuffersForCurrentSession(); // Deletes GL buffers whose owning frontend objects died (possibly on a // thread without a current ES context). Called from draw-time sync. @@ -1427,6 +1427,7 @@ namespace MobileGL::MG_Backend::DirectGLES { ResolvedDrawBuffers m_resolvedDrawBuffers; PendingAttribValueMask m_pendingAttribValueMask; Uint m_backendVAOId = 0; + Uint64 m_nativeContextSerial = 0; Array m_clientAttributeBufferIds; // Scratch stores for the buffer-backed GL_DOUBLE narrowing and BGRA swizzle. Deliberately separate // from m_clientAttributeBufferIds: that one holds the per-draw upload of a @@ -2176,7 +2177,7 @@ namespace MobileGL::MG_Backend::DirectGLES { private: Uint m_backendFBOId = 0; - Uint m_contextGeneration = 0; + Uint64 m_nativeContextSerial = 0; /* this will save buffers in its original form, reversion, absence or not consecutive are all allowed, as long as GL spec allows it diff --git a/MobileGL/MG_Backend/DirectGLES/ManagersBuffers.cpp b/MobileGL/MG_Backend/DirectGLES/ManagersBuffers.cpp index 2bb2f9c1..d1b087ec 100644 --- a/MobileGL/MG_Backend/DirectGLES/ManagersBuffers.cpp +++ b/MobileGL/MG_Backend/DirectGLES/ManagersBuffers.cpp @@ -8,6 +8,8 @@ #include "ManagersInternal.h" +#include + namespace MobileGL::MG_Backend::DirectGLES { constexpr Bool PREFER_MAP_BUFFER_RANGE_FOR_BUFFER_SYNC = false; @@ -251,11 +253,14 @@ namespace MobileGL::MG_Backend::DirectGLES { // why the test is on initialData rather than on size. MG_Util::PipeStats::AddBytes(MG_Util::PipeStats::ByteClass::StageBuffer, static_cast(size)); } - resource.storageSize = size; - resource.storageInitialized = true; - resource.pendingRespecify = false; - resource.pendingRanges.clear(); - resource.pendingResidentWrites.clear(); + { + const std::lock_guard lock(resource.pendingMutex); + resource.storageSize = size; + resource.storageInitialized = true; + resource.pendingRespecify = false; + resource.pendingRanges.clear(); + resource.pendingResidentWrites.clear(); + } resource.syncedChangeSerial = syncedSerial; // A GROWN store keeps its indexed bindings, and BindBufferBaseCached skips a // rebind whenever the shadow already records this id at that index - so on a @@ -335,6 +340,7 @@ namespace MobileGL::MG_Backend::DirectGLES { void* ahb = nullptr; Uint generation = 0; }; + std::mutex g_t0RetiredMutex; Vector g_t0Retired; // T0 twins whose destroy found no current context: Ops_OnDestroy queued them on the // deferred-release list and keeps a second reference here, so the reference is @@ -342,9 +348,10 @@ namespace MobileGL::MG_Backend::DirectGLES { // g_deferredBufferReleasesMutex, like the list it shadows. Vector> g_t0DeferredDestroys; std::atomic g_hasT0DeferredDestroys{false}; - Uint64 g_t0ImportsLive = 0; + std::atomic g_t0ImportsLive{0}; void SweepT0Retired(Bool contextGone) { + const std::lock_guard lock(g_t0RetiredMutex); for (SizeT i = 0; i < g_t0Retired.size();) { T0RetiredImport& retired = g_t0Retired[i]; const Bool sameContext = @@ -380,8 +387,11 @@ namespace MobileGL::MG_Backend::DirectGLES { retired.fence = g_GLESFuncs.glFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0); } resource.externalAhb = nullptr; - if (g_t0ImportsLive > 0) --g_t0ImportsLive; - g_t0Retired.push_back(retired); + g_t0ImportsLive.fetch_sub(1, std::memory_order_relaxed); + { + const std::lock_guard lock(g_t0RetiredMutex); + g_t0Retired.push_back(retired); + } SweepT0Retired(false); } #else @@ -740,6 +750,7 @@ namespace MobileGL::MG_Backend::DirectGLES { } if (!resource) return; // lazy: the ensure path full-uploads on creation if (resource->immutableStorage) { + const std::lock_guard lock(resource->pendingMutex); resource->persistentMapped = false; resource->persistentPtr = nullptr; if (resource->id != 0 && CanTouchGLNow() && @@ -768,12 +779,14 @@ namespace MobileGL::MG_Backend::DirectGLES { return; } if (!CanTouchGLNow() || resource->id == 0 || resource->contextGeneration != g_bufferContextGeneration) { + const std::lock_guard lock(resource->pendingMutex); resource->pendingRespecify = true; resource->pendingRanges.clear(); resource->pendingResidentWrites.clear(); return; } if (desc.Width == 0) { + const std::lock_guard lock(resource->pendingMutex); resource->storageInitialized = false; resource->storageSize = 0; resource->pendingRespecify = false; @@ -917,10 +930,14 @@ namespace MobileGL::MG_Backend::DirectGLES { const SizeT size = static_cast(MG_Pipe::MGPipeSubDataBufferSize(record)); auto* resource = FindBufferResourceForHandle(res); if (!resource || size == 0 || bytes == nullptr) return; - // DELIBERATELY not stored as hostBytes: these are the application's staging - // store and are valid for the duration of the call only (BufferObject.h:84-85), - // which is exactly why they are COPIED here rather than referenced later. const std::lock_guard lock(resource->pendingMutex); + if (resource->contextGeneration != g_bufferContextGeneration || resource->id == 0 || + !resource->persistentMapped || resource->persistentPtr == nullptr || + !resource->storageInitialized || resource->pendingRespecify || offset > resource->storageSize || + size > resource->storageSize - offset) { + return; + } + // The caller owns the temporary input span; the queued write owns a copy. auto& write = resource->pendingResidentWrites.emplace_back(); write.offset = offset; const auto* source = static_cast(bytes); @@ -997,86 +1014,52 @@ namespace MobileGL::MG_Backend::DirectGLES { resource->syncedChangeSerial = ResourceSerialOf(res); } - void Ops_H_Readback(MG_Pipe::MGPipeHandle res, const MG_Pipe::MGPReadback& record) { - // An empty capture may conservatively request a writeback before - // any draw materialized this buffer. Resolve its staged resource - // exactly as a GPU consumer would, then return the real bytes. + Bool Ops_H_Readback(MG_Pipe::MGPipeHandle res, const MG_Pipe::MGPReadback& record) { + // Check the context before ensure, which may allocate driver storage. + if (!CanTouchGLNow()) return false; auto* resource = EnsureBufferResourceForHandle(nullptr, res); - if (!resource || resource->id == 0 || !resource->storageInitialized) return; - if (!CanTouchGLNow() || resource->contextGeneration != g_bufferContextGeneration) return; - if (resource->persistentMapped) { - // Queued resident SubData bytes land first (GPU-ordered), then the finish - // makes them - and any shader writes already queued on this context - - // visible through the coherent mapping the reads use. There is no backend - // copy to read back in this case. - DrainResidentWritesNow(*resource); - if (g_GLESFuncs.glFinish) g_GLESFuncs.glFinish(); - return; + if (!resource || resource->id == 0 || !resource->storageInitialized || resource->pendingRespecify || + resource->contextGeneration != g_bufferContextGeneration) { + return false; } - if (!g_GLESFuncs.glMapBufferRange || !g_GLESFuncs.glUnmapBuffer) return; - // The map below starts at record.Offset where the legacy arm mapped at literal - // zero, so the clamp has to be against what is left of the BACKEND store past - // that offset: the applier's BufferRangeFault checked the range against - // Desc.Width, and a store that is smaller than the descriptor (a respecify the - // backend has not applied yet) would otherwise be mapped past its end. - const SizeT readOffset = static_cast(record.Offset); - if (readOffset >= resource->storageSize) return; - const SizeT size = std::min(static_cast(record.Size), resource->storageSize - readOffset); - if (size == 0) return; + if (record.Size == 0 || record.Offset > resource->storageSize || + record.Size > resource->storageSize - record.Offset) { + return false; + } + if (resource->persistentMapped) { + if (resource->persistentPtr == nullptr || !g_GLESFuncs.glFinish) return false; + // The client already owns the coherent bytes. Wait for all queued GPU writes. + DrainResidentWritesNow(*resource); + g_GLESFuncs.glFinish(); + return true; + } + const auto writeback = MG_Pipe::gMGPipeCallbacks.OnBufferWriteback; + if (!g_GLESFuncs.glMapBufferRange || !g_GLESFuncs.glUnmapBuffer || writeback == nullptr) return false; - // Queued app writes must land in the backend store before it is read back, or - // the writeback below would revert them in the shadow. Under split every queued - // range must lie inside the server shadow's staged coverage first (R-11 / the - // M-6 ruling): the drain's tier-1 map would otherwise declare live GPU bytes - // dead over a range nothing staged. MGL_SERVER_STAGED_REQUIRE_PENDING(*resource, resource->hostBytes, ResourceWidthOf(res), "readback_flush_pending"); FlushPendingRangesFrom(*resource, resource->hostBytes, ResourceWidthOf(res)); BindBufferId(TempBufferTarget, resource->id); - void* mapped = g_GLESFuncs.glMapBufferRange(TempBufferTarget, (GLintptr)record.Offset, - static_cast(size), GL_MAP_READ_BIT); + const SizeT size = static_cast(record.Size); + const auto* mapped = static_cast( + g_GLESFuncs.glMapBufferRange(TempBufferTarget, static_cast(record.Offset), + static_cast(size), GL_MAP_READ_BIT)); if (mapped == nullptr) { - MGLOG_E_ONCE("Ops_H_Readback: glMapBufferRange(read) failed for buffer %u", resource->id); - return; + MGLOG_E_ONCE("Buffer readback: glMapBufferRange failed for buffer %u", resource->id); + return false; } - // The reverse channel replaces BufferObject::WritebackFromBackend: the backend - // no longer reaches into the frontend's address space, it ANSWERS. In monolith - // the client's implementation is one call away, so SyncGpuWrites' caller still - // sees the reconciled shadow on return, exactly as before. - // - // THE ORDER FROM HERE IS A CORRECTNESS RULE, NOT A PREFERENCE - // (ARCHITECTURE.md 8.2: "the writeback's epoch bump must be applied by the server before any - // later command that reads that handle; the reverse channel needs the same ordering guarantees as the - // forward channel"): - // 1. writeback - the client's shadow takes the bytes, - // 2. unmap - the read mapping goes away, - // 3. serial stamp- syncedChangeSerial catches up with the record, so the next - // draw does not re-upload the readback over itself, - // 4. epoch bump - in Ops_H_ReadbackTracked, i.e. strictly AFTER 1-3, so a - // draw-clean memo re-probed by the bump can never observe a - // half-reconciled resource. The bump must NEVER move earlier. - if (MG_Pipe::gMGPipeCallbacks.OnBufferWriteback != nullptr) { - MG_Pipe::gMGPipeCallbacks.OnBufferWriteback(res, record.Offset, - MG_Pipe::MGPBlobRef{reinterpret_cast(mapped), - static_cast(size), - MG_Pipe::kMGHostSpanSegNone, 0}); - } else { - MGLOG_E_ONCE("Ops_H_Readback: no reverse channel is installed, so the GPU-written bytes of " - "buffer %u cannot reach the client shadow", - resource->id); - } - g_GLESFuncs.glUnmapBuffer(TempBufferTarget); - // The shadow now matches the backend byte for byte; without this the next draw - // would see a newer serial and re-upload the readback over it. + // If unmap reports corruption, discard the copy before publishing any bytes. + const Vector bytes(mapped, mapped + size); + if (g_GLESFuncs.glUnmapBuffer(TempBufferTarget) == GL_FALSE) return false; + writeback(res, record.Offset, + MG_Pipe::MGPBlobRef{reinterpret_cast(bytes.data()), record.Size, + MG_Pipe::kMGHostSpanSegNone, 0}); resource->syncedChangeSerial = ResourceSerialOf(res); - // P13 W4a: on monolith's record arm the base this twin reads IS the shadow the - // writeback just filled, so a whole-store readback is also the refresh - // SplitHostBytesForCpuRead would owe. (A copying store's copy is not the - // client's shadow, and keeps its mark.) - if (MG_Config::RecordArmAliasesFrontend() && readOffset == 0 && size >= ResourceWidthOf(res)) { + if (MG_Config::RecordArmAliasesFrontend() && record.Offset == 0 && size == ResourceWidthOf(res)) { resource->serverGpuWritten = false; } + return true; } void Ops_H_Destroy(MG_Pipe::MGPipeHandle res) { @@ -1218,9 +1201,10 @@ namespace MobileGL::MG_Backend::DirectGLES { Ops_H_FlushRange(res, record, bytes); BumpBufferMutationEpoch(); } - void Ops_H_ReadbackTracked(MG_Pipe::MGPipeHandle res, const MG_Pipe::MGPReadback& record) { - Ops_H_Readback(res, record); + Bool Ops_H_ReadbackTracked(MG_Pipe::MGPipeHandle res, const MG_Pipe::MGPReadback& record) { + if (!Ops_H_Readback(res, record)) return false; BumpBufferMutationEpoch(); + return true; } void Ops_H_DestroyTracked(MG_Pipe::MGPipeHandle res) { Ops_H_Destroy(res); @@ -2037,6 +2021,58 @@ namespace MobileGL::MG_Backend::DirectGLES { g_hasDeferredBufferReleases.store(false, std::memory_order_release); } + namespace { + void InvalidateResidentBacking(MG_Pipe::MGPipeHandle handle, GLESBufferResource& resource) { + const std::lock_guard lock(resource.pendingMutex); + if (resource.persistentPtr != nullptr && resource.externalAhb == nullptr) { + MG_Pipe::MGPipeRevokeResidentBuffer(handle, resource.persistentPtr); + } + resource.persistentMapped = false; + resource.persistentPtr = nullptr; + resource.pendingResidentWrites.clear(); + } + + void RetireBufferTwin(MG_Pipe::MGPipeHandle handle, const SharedPtr& twin) { + InvalidateResidentBacking(handle, *twin); + MGL_SERVER_STAGED_DROP(*twin); + twin->hostBytes = nullptr; + twin->storageInitialized = false; + // Session teardown can still have a live native share group. Follow the + // normal driver-deletion and import-retirement paths in that case. + if (twin->id != 0 || twin->externalAhb != nullptr) + Ops_OnDestroy(SharedPtr(twin)); + } + } // namespace + + void OnShareGroupDestroyed(Uint64 sessionKey, Uint64 shareGroupToken) { + const TwinKey dying{sessionKey, shareGroupToken}; + g_backendBufferResources.ForEachBucket( + [&](const TwinKey& key, MG_Pipe::MGPipeHandle handle, const SharedPtr& twin) { + if (key == dying) RetireBufferTwin(handle, twin); + }); + g_backendBufferResources.Drop(dying); + } + + Uint32 DropBuffersForEndedServerSession(const TwinKey* key) { + g_backendBufferResources.ForEachBucket( + [&](const TwinKey& bucket, MG_Pipe::MGPipeHandle handle, const SharedPtr& twin) { + if (key == nullptr || bucket.SessionKey == key->SessionKey) RetireBufferTwin(handle, twin); + }); + if (key != nullptr) return g_backendBufferResources.DropSession(key->SessionKey); + const auto buckets = static_cast(g_backendBufferResources.BucketCount()); + g_backendBufferResources.Reset(); + return buckets; + } + + void RevokeResidentBuffersForCurrentSession() { + const Uint64 sessionKey = CurrentNativeSessionKey(); + g_backendBufferResources.ForEachBucket( + [&](const TwinKey& key, MG_Pipe::MGPipeHandle handle, const SharedPtr& twin) { + if (key.SessionKey == sessionKey) InvalidateResidentBacking(handle, *twin); + }); + BumpBufferMutationEpoch(); + } + void OnServerSessionEndedWithOthersLive() { // Only what belongs to the ending session: its staged bytes (both stores are // session-scoped). The rings, the ops table and the buffer generation are the @@ -2050,6 +2086,14 @@ namespace MobileGL::MG_Backend::DirectGLES { void OnBackendContextDestroyed() { UnregisterBufferBackendOps(); // also bumps the buffer-mutation epoch ++g_bufferContextGeneration; + g_backendBufferResources.ForEachBucket( + [](const TwinKey&, MG_Pipe::MGPipeHandle handle, const SharedPtr& twin) { + InvalidateResidentBacking(handle, *twin); + // A private or server-owned shadow is about to be freed. Plain aliases + // into a frontend shadow remain valid until the next content record. + if (ServerStaged().HasShadow(twin.get())) twin->hostBytes = nullptr; + twin->serverGpuWritten = false; + }); // The generation moved AFTER the unregister bump above; re-open the // memos again so no stamp can predate the generation change. BumpBufferMutationEpoch(); @@ -2116,7 +2160,7 @@ namespace MobileGL::MG_Backend::DirectGLES { // fence signaled let go of their AHardwareBuffer; a deferred T0 destroy is retired once // the drain deleted its id (the fence then follows the delete) or its context is gone. void ProcessDeferredT0Retires() { - if (!g_t0Retired.empty()) SweepT0Retired(false); + SweepT0Retired(false); if (!g_hasT0DeferredDestroys.load(std::memory_order_acquire)) return; Vector> ready; { @@ -2167,6 +2211,7 @@ namespace MobileGL::MG_Backend::DirectGLES { if (twin == nullptr || twin->get() != resource) return false; if (resource->contextGeneration != g_bufferContextGeneration) return false; if (resource->id == 0) return false; + const std::lock_guard lock(resource->pendingMutex); if (resource->persistentMapped) { return resource->persistentPtr != nullptr && resource->pendingResidentWrites.empty(); } @@ -2197,43 +2242,29 @@ namespace MobileGL::MG_Backend::DirectGLES { return resource->syncedChangeSerial.load(std::memory_order_acquire) == record->Serial; } - // The handle arm of the ensure path. Same shape, same order, same branches; the four - // frontend reads become the applier's stored descriptor, its Serial and the shadow base - // the last content-carrying call handed over. - // - // It still takes the frontend object for ONE reason, recorded rather than hidden: - // BufferObject::SyncPersistentMappedRange() is one of the eleven Espryt sites - // ROADMAP/D-N explicitly keeps where it is for P3a (the per-site attribution table is - // P8's to execute). Every other line here is handle-shaped. When P8 moves that call to - // the client this signature loses its last frontend argument. + // A split server reads its own staged bytes. A local backend can resolve a live shadow + // by handle to refresh an alias after the frontend reallocates it. GLESBufferResource* EnsureBufferResourceForHandle( const SharedPtr& bufferObject, MG_Pipe::MGPipeHandle res) { auto* resource = GetOrCreateBufferResourceForHandle(res); if (!resource) return nullptr; - // The client's shadow base, RE-READ at every use, exactly as the legacy arm re-read - // MappedData() at every use. It is deliberately NOT resource->hostBytes here: two - // ordinary events move or free what a base recorded by an earlier call points at - - // a shadow resize (PipeResource::ResizeShadow is reserve + resize, so a grow past - // the reserve reallocates) and persistent-map adoption (the shadow is cleared and - // shrunk to fit) - and this path still holds the frontend object anyway, because - // D-N keeps SyncPersistentMappedRange here for all of P3a. hostBytes stays the - // fallback for the drains that have NO object (the readback flush), and it is - // nulled at both of those events. - const auto liveHostBase = [&resource, &bufferObject]() -> const Uint8* { - // M-2 / codex 3 / ID-52 item 3: under an ACTIVE TRANSPORT the server's staged - // copy (resource->hostBytes, filled by MGL_SERVER_STAGED_ADOPT in Ops_H_SubData / - // Ops_H_FlushRange) is the ONLY authoritative base. Preferring the frontend - // object's MappedData() here - which under inproc is always non-null, same process - // - meant every reduced-path drain read the CLIENT's shadow and NEVER the server's, - // so a corrupt staged upload rendered the frontend's correct bytes and the R-2.5 - // 0xDD audit could not reach a draw. R-2 / table 3: honest inproc is inproc that - // does not read the client object's memory. Under monolith nothing changes. - return resource->hostBytes; + const MG_State::GLState::BufferObject* frontend = nullptr; + const auto liveHostBase = [&](SizeT width) -> const Uint8* { + if (!MG_Config::RecordArmAliasesFrontend()) return resource->hostBytes; + if (!frontend) { + frontend = + bufferObject ? bufferObject.get() : MG_Pipe::MGPipeResourceTrackerInstance().Resolve(res); + } + if (!frontend) return resource->hostBytes; + if (frontend->GetSize() != width || frontend->IsBackendPersistentMapped()) return nullptr; + return frontend->MappedData(); }; if (resource->contextGeneration != g_bufferContextGeneration) { - // The id (if any) belonged to a destroyed ES context. + // A stale driver name cannot be reused in the new context. Keep any + // shadow staged by records that preceded the first use of this twin. + const std::lock_guard lock(resource->pendingMutex); resource->id = 0; resource->storageInitialized = false; resource->storageSize = 0; @@ -2244,25 +2275,9 @@ namespace MobileGL::MG_Backend::DirectGLES { resource->persistentMapped = false; resource->persistentPtr = nullptr; resource->immutableStorage = false; - // m-5 / codex 5: OnBackendContextDestroyed ran MGL_SERVER_STAGED_DROP_ALL(), which - // frees every server shadow but does NOT null the hostBytes that name them - so a - // twin that SURVIVES a context loss still carries a base into the freed allocation. - // Null it here, where a surviving twin is re-armed - but ONLY when the shadow is - // really gone. This block also runs on a twin's FIRST ensure (contextGeneration - // starts mismatched), and there the shadow a preceding resource_subdata just staged - // is still live; nulling it then would drop the reduced path's own bytes (it did, - // and TriangleScenario read the wrong VBO). HasShadow is the discriminator: false - // after DropAll, true after an ordinary Adopt. - // - // TRANSPORT-GUARDED like the other two split hunks in this file (review v2 N-7): - // under MONOLITH transport in a disaggregated build the store never copies, Adopt - // never sets m_any, HasShadow answers false for everything, and this null would - // run on every twin's first ensure - harmless there only because liveHostBase() - // prefers MappedData() under monolith, and "under monolith nothing changes" should - // be true by construction rather than by luck. - if (ServerStaged().CopiesIntoServerStorage() && !ServerStaged().HasShadow(resource)) { - resource->hostBytes = nullptr; - } + } + + if (resource->id == 0) { #if defined(__ANDROID__) && MOBILEGL_BUILD_DISAGGREGATED // P11 B2: A T0 STORE OUTLIVES ITS CONTEXT. Its pages are the client's // AHardwareBuffer, which this twin still holds, so the store is imported again on @@ -2283,6 +2298,9 @@ namespace MobileGL::MG_Backend::DirectGLES { "%s; the store has no GPU backing", res.Slot, res.Gen, why.c_str()); RetireT0Import(*resource); + (void)MG_Pipe::MGPipeSessionLatch(MG_Pipe::MGPipeFatalFamily::DeviceLost, + "T0 buffer import lost its GPU backing: %s", why.c_str()); + return nullptr; } } #endif @@ -2308,12 +2326,10 @@ namespace MobileGL::MG_Backend::DirectGLES { if (resource->id == 0) { const SizeT poolSize = ResourceWidthOf(res); - // The pool DECISION is the legacy one, unchanged: extent and residence only. - // An earlier cut added "and a shadow base was recorded", which silently stopped - // a buffer recycling pool ids - a change to D-F's pool behavior, not to "the - // source of bytes" the conversion is allowed to move, and one that moves - // AcquireFromPool call counts StreamedArenaScenario observes. - const Uint reused = (poolSize > 0 && !resource->persistentMapped) ? AcquireFromPool(poolSize) : 0; + const Uint8* const poolBytes = liveHostBase(poolSize); + const Bool canReuse = + poolSize > 0 && !resource->persistentMapped && !resource->immutableStorage && poolBytes != nullptr; + const Uint reused = canReuse ? AcquireFromPool(poolSize) : 0; if (reused != 0) { resource->id = reused; resource->storageSize = poolSize; @@ -2329,9 +2345,9 @@ namespace MobileGL::MG_Backend::DirectGLES { // legal (ResourceContentIsDeclared, above). RequireCoverage is a no-op for the // legacy arm's MappedData() and for a non-copying store. if (ResourceContentIsDeclared(res)) { - MGL_SERVER_STAGED_REQUIRE(*resource, liveHostBase(), 0, poolSize, "pool_reuse_whole_store"); + MGL_SERVER_STAGED_REQUIRE(*resource, poolBytes, 0, poolSize, "pool_reuse_whole_store"); } - g_GLESFuncs.glBufferSubData(TempBufferTarget, 0, (GLsizeiptr)poolSize, liveHostBase()); + g_GLESFuncs.glBufferSubData(TempBufferTarget, 0, (GLsizeiptr)poolSize, poolBytes); if (MG_Util::PipeStats::Enabled()) { MG_Util::PipeStats::AddBytes(MG_Util::PipeStats::ByteClass::StageBuffer, static_cast(poolSize)); @@ -2355,13 +2371,6 @@ namespace MobileGL::MG_Backend::DirectGLES { } } - // D-N keeps this call here for P3a. It can queue ranges and move the record, so - // everything below is read AFTER it. - // P5c (hd, CONTRACT-P5C §3.8): under an active transport the frontend accessor is a - // layer-1 surface ("buffer-legacy-arm") and the client's own pre-verb - // persistent-map push is the only producer; the call is skipped outright. Under - // monolith D-N's placement stands. - const auto* record = ResourceRecordOf(res); const SizeT size = record != nullptr ? static_cast(record->Desc.Width) : 0; if (size == 0) { @@ -2369,55 +2378,16 @@ namespace MobileGL::MG_Backend::DirectGLES { } const Uint64 serial = record->Serial; const GLenum usage = MG_Util::ConvertBufferUsageToGLEnum(static_cast(record->Desc.Usage)); - // Read AFTER SyncPersistentMappedRange above, and through liveHostBase for the - // reason written where it is declared. - const Uint8* const hostBase = liveHostBase(); - // AND PUBLISH IT, because the readers that have NO frontend object read - // resource->hostBytes and nothing else: the readback flush (Ops_H_Readback), the - // kill-switch map arm of Ops_H_FlushRange, and the fp64 narrowing - // (SyncConvertedAttributeByHandle, whose legacy counterpart reads - // bufferObject->MappedData()). A twin is created LAZILY - D-A2's row makes - // Ops_H_Create a no-op - so the very first resource_respecify of a buffer finds - // FindBufferResourceForHandle == nullptr and its base is dropped on the floor; with - // glBufferData(..., data) followed by no further content call (the ordinary static - // vertex array) hostBytes then stayed null for the object's whole life and the fp64 - // narrowing refused every draw, disabling the array. This is the one place that both - // holds the object and runs before every draw that uses the store, so it is where the - // base is refreshed. Only reached for a NON-adopted resource (the adopted arm - // returned above), so C-2's rule is intact: an adopted store's hostBytes stays null - // and its bytes are read through persistentPtr. - if (hostBase != nullptr) resource->hostBytes = hostBase; - // "DOES THE SHADOW THIS PATH IS ABOUT TO UPLOAD HOLD MEANINGFUL BYTES?" - and it has - // to be asked of the SAME thing the bytes come from. The legacy arm pairs - // bufferObject.MappedData() with bufferObject.HasDefinedContent() (RespecifyStorageNow) - // and this arm pairs the same two, so the source of the bytes and the statement about - // them can never disagree. - // - // P5c (hd, CONTRACT-P5C §3.6 / B1): with an active transport the answer is the - // DESCRIPTOR's bit - which the client publishes on ResourceCreate/Respecify - OR the - // staged coverage the content records behind it delivered. The coverage half is what - // keeps the answer equal to the frontend flag's in the one case the descriptor alone - // cannot see: an ORPHANING respecify (descriptor clear) followed by glBufferSubData, - // which defines content without a new descriptor - the bytes crossed as - // resource_subdata and the staged store's coverage is exactly "content defined since - // the last orphan". With no coverage and a clear bit the store is undefined by the - // application's own declaration and the upload stays a pure NULL reallocation. + const Uint8* const hostBase = liveHostBase(size); + if (frontend) resource->hostBytes = hostBase; + + // Upload only surviving host content. Adoption drops the shadow. const Bool shadowHasContent = - (record->Desc.HasDefinedContent != 0 || - (ServerStaged().CopiesIntoServerStorage() ? ServerStaged().CoveredRunCount(resource) != 0 - : resource->contentSinceRespecify)); + frontend ? frontend->HasDefinedContent() + : (record->Desc.HasDefinedContent != 0 || + (ServerStaged().CopiesIntoServerStorage() ? ServerStaged().CoveredRunCount(resource) != 0 + : resource->contentSinceRespecify)); const void* initialData = shadowHasContent ? hostBase : nullptr; - // M-3 / codex 4: a RespecifyStorageWith(..., initialData != nullptr) is a WHOLE-STORE - // [0, size) upload from the base, so it owes the same coverage the pending-range drain - // below owes - the two respecify arms were the readers M-6's "never widened" rule did - // not reach. No-op for the legacy arm's MappedData() and for a non-copying store; a - // Fatal{StageSnapshotTooNarrow, "respecify_whole_store"} under split when the - // DESCRIPTOR says the application supplied the content and the shadow's coverage does - // not span the store (a missing record), instead of uploading its zero-fill as content. - // NOT for a store the application orphaned: there `shadowHasContent` is the frontend - // object's flag, which the streaming idiom's partial glBufferSubData flips to true, and - // the bytes it did not write are undefined by its own glBufferData(NULL) - the rule at - // ResourceContentIsDeclared. Round 2 refused that idiom and aborted six joint entries. const auto requireWholeStoreCoverage = [&]() { if (initialData != nullptr && record->Desc.HasDefinedContent != 0) { MGL_SERVER_STAGED_REQUIRE(*resource, static_cast(initialData), 0, size, diff --git a/MobileGL/MG_Backend/DirectGLES/ManagersFramebuffers.cpp b/MobileGL/MG_Backend/DirectGLES/ManagersFramebuffers.cpp index ab087175..67db815c 100644 --- a/MobileGL/MG_Backend/DirectGLES/ManagersFramebuffers.cpp +++ b/MobileGL/MG_Backend/DirectGLES/ManagersFramebuffers.cpp @@ -25,7 +25,7 @@ namespace MobileGL::MG_Backend::DirectGLES { m_backendColorSlots[i] = GL_COLOR_ATTACHMENT0 + i; } g_GLESFuncs.glGenFramebuffers(1, &m_backendFBOId); - m_contextGeneration = g_backendContextGeneration; + m_nativeContextSerial = CurrentNativeContextSerial(); if (m_backendFBOId == 0) { MGLOG_E_ONCE("Failed to generate framebuffer object."); MGLOG_E_ONCE("ES glGetError(): %s", MG_Util::ConvertGLEnumToString(g_GLESFuncs.glGetError()).c_str()); @@ -38,13 +38,14 @@ namespace MobileGL::MG_Backend::DirectGLES { if (InProcessTeardown()) { return; // see InProcessTeardown(): the driver may be unloaded already } - if (m_backendFBOId == 0) { + // A different native context can have a framebuffer with the same numeric name. + if (m_backendFBOId == 0 || m_nativeContextSerial != CurrentNativeContextSerial()) { return; } // Scrub the binding shadow whether or not the id can still be deleted: a // recycled name must never satisfy the shadow's dedup. NoteFramebufferIdDeleted(m_backendFBOId); - if (m_contextGeneration == g_backendContextGeneration && g_GLESFuncs.glDeleteFramebuffers) { + if (g_GLESFuncs.glDeleteFramebuffers) { g_GLESFuncs.glDeleteFramebuffers(1, &m_backendFBOId); TextureImpl::DeleteDrawTextureFramebuffer(m_backendFBOId); } diff --git a/MobileGL/MG_Backend/DirectGLES/ManagersVertexArrays.cpp b/MobileGL/MG_Backend/DirectGLES/ManagersVertexArrays.cpp index 0f17c344..f13ff205 100644 --- a/MobileGL/MG_Backend/DirectGLES/ManagersVertexArrays.cpp +++ b/MobileGL/MG_Backend/DirectGLES/ManagersVertexArrays.cpp @@ -80,7 +80,8 @@ namespace MobileGL::MG_Backend::DirectGLES { const char* site) { // A coherent store - T0's import, or (P13 W4a) a map monolith's record arm donated - // has no copy: its bytes are read through the map once queued writes have landed. - const Bool coherent = resource.persistentMapped && resource.persistentPtr != nullptr; + const Bool coherent = resource.persistentMapped && resource.persistentPtr != nullptr && + resource.contextGeneration == CurrentBufferContextGeneration(); Bool residentWritesQueued = false; if (coherent) { const std::lock_guard lock(resource.pendingMutex); @@ -241,6 +242,7 @@ namespace MobileGL::MG_Backend::DirectGLES { m_clientAttributeBufferIds.fill(0); m_convertedAttributeBufferIds.fill(0); g_GLESFuncs.glGenVertexArrays(1, &m_backendVAOId); + m_nativeContextSerial = CurrentNativeContextSerial(); if (m_backendVAOId == 0) { MGLOG_E_ONCE("Failed to generate vertex array object."); MGLOG_E_ONCE("ES glGetError(): %s", MG_Util::ConvertGLEnumToString(g_GLESFuncs.glGetError()).c_str()); @@ -253,7 +255,7 @@ namespace MobileGL::MG_Backend::DirectGLES { if (InProcessTeardown()) { return; // see InProcessTeardown(): the driver may be unloaded already } - if (m_backendVAOId != 0) { + if (m_backendVAOId != 0 && m_nativeContextSerial == CurrentNativeContextSerial()) { NoteVAOIdDeleted(m_backendVAOId); g_GLESFuncs.glDeleteVertexArrays(1, &m_backendVAOId); m_backendVAOId = 0; diff --git a/MobileGL/MG_Backend/DirectVulkan/Renderer/VkBufferManager.cpp b/MobileGL/MG_Backend/DirectVulkan/Renderer/VkBufferManager.cpp index 7520646d..88d281d0 100644 --- a/MobileGL/MG_Backend/DirectVulkan/Renderer/VkBufferManager.cpp +++ b/MobileGL/MG_Backend/DirectVulkan/Renderer/VkBufferManager.cpp @@ -134,7 +134,8 @@ namespace MobileGL::MG_Backend::DirectVulkan { }, .Readback = [](auto res, const auto& record) { - if (auto* m = WireManager("readback")) m->ReadbackWireBuffer(res, record.Offset, record.Size); + auto* m = WireManager("readback"); + return m != nullptr && m->ReadbackWireBuffer(res, record.Offset, record.Size); }, .Destroy = [](auto res) { @@ -712,33 +713,28 @@ namespace MobileGL::MG_Backend::DirectVulkan { return true; } - void VkBufferManager::ReadbackWireBuffer(MG_Pipe::MGPipeHandle res, Uint64 offset, Uint64 size) { - // P11 B2: A T0 STORE'S READBACK IS "DONE, NO BYTES". Its pages are the client's - // AHardwareBuffer, so what the client needs before it reads them is this server's GPU - // having finished every write to them - the resident copies WriteWireBuffer recorded and - // any shader write - and nothing crossing SEG_EVENT. The wait is the store's own host-access - // wait (a barrier to host, then the sync point's submission); the reply then says "done". - // One death for both shapes: the store could not be made readable. + Bool VkBufferManager::ReadbackWireBuffer(MG_Pipe::MGPipeHandle res, Uint64 offset, Uint64 size) { auto* resource = FindWireBuffer(res); - const Bool t0 = resource != nullptr && resource->imported; - Vector bytes(t0 ? 0 : static_cast(size)); - if (t0 ? !WaitForWireBufferHostAccess(*resource) : !ReadWireBuffer(res, offset, size, bytes.data())) { - // A lost device: the session is latched and closing; its client reads a lost context. - if (LatchedOnDeviceLoss("buffer-readback")) return; - MGLOG_F("Magma: Fatal{ResourceUnavailable, \"buffer-readback\"} {slot=%u, gen=%u}", res.Slot, res.Gen); - std::abort(); + if (resource == nullptr || size == 0 || offset > resource->size || size > resource->size - offset || + resource->buffer.GetMappedData() == nullptr) { + return false; } - if (t0) { - return; + if (resource->imported) { + // The frontend reads the shared mapping directly once GPU writes are visible. + if (WaitForWireBufferHostAccess(*resource)) return true; + LatchedOnDeviceLoss("buffer-readback"); + return false; } - if (MG_Pipe::gMGPipeCallbacks.OnBufferWriteback == nullptr) { - MGLOG_F("Magma: Fatal{ResourceUnavailable, \"buffer-writeback-callback\"}"); - std::abort(); + if (MG_Pipe::gMGPipeCallbacks.OnBufferWriteback == nullptr) return false; + Vector bytes(static_cast(size)); + if (!ReadWireBuffer(res, offset, size, bytes.data())) { + LatchedOnDeviceLoss("buffer-readback"); + return false; } - // The reverse producer synchronously copies into SEG_EVENT before - // this owned vector is released; no mapped Vulkan pointer crosses roles. + // The reverse callback copies these bytes before the vector is released. MG_Pipe::gMGPipeCallbacks.OnBufferWriteback( res, offset, {reinterpret_cast(bytes.data()), size, MG_Pipe::kMGHostSpanSegNone, 0}); + return true; } void VkBufferManager::MarkWireBufferGpuWritten(MG_Pipe::MGPipeHandle res, Uint64 offset, Uint64 size) { diff --git a/MobileGL/MG_Backend/DirectVulkan/Renderer/VkBufferManager.h b/MobileGL/MG_Backend/DirectVulkan/Renderer/VkBufferManager.h index 1c7c0d85..2c44090a 100644 --- a/MobileGL/MG_Backend/DirectVulkan/Renderer/VkBufferManager.h +++ b/MobileGL/MG_Backend/DirectVulkan/Renderer/VkBufferManager.h @@ -92,7 +92,7 @@ namespace MobileGL::MG_Backend::DirectVulkan { const void* initialBytes); void WriteWireBuffer(MG_Pipe::MGPipeHandle res, Uint64 offset, Uint64 size, const void* bytes); void FlushWireBuffer(MG_Pipe::MGPipeHandle res, Uint64 offset, Uint64 size, const void* bytes); - void ReadbackWireBuffer(MG_Pipe::MGPipeHandle res, Uint64 offset, Uint64 size); + Bool ReadbackWireBuffer(MG_Pipe::MGPipeHandle res, Uint64 offset, Uint64 size); void DestroyWireBuffer(MG_Pipe::MGPipeHandle res); // P11 B2 (T0): make the client's AHardwareBuffer `ahb` (a BLOB of `size` bytes) buffer // `res`'s store - a VkBuffer on memory imported through diff --git a/MobileGL/MG_Backend/EGLSurfaceRegistry.cpp b/MobileGL/MG_Backend/EGLSurfaceRegistry.cpp index 452059b8..e20a6e49 100644 --- a/MobileGL/MG_Backend/EGLSurfaceRegistry.cpp +++ b/MobileGL/MG_Backend/EGLSurfaceRegistry.cpp @@ -28,17 +28,8 @@ namespace MobileGL::MG_Backend { return false; } - // A DISPLAY IS A CONNECTION, NOT A RESOURCE THIS BACKEND OWNS, and refusing the second one - // refused a caller for a reason that is not there: the surface and context tables are keyed - // by the display each was created on, every operation carries its own display handle, and - // this field has no reader anywhere - it was the whole of the rule. - // - // What the rule cost was a compositor. One asks for the display it will draw into AFTER - // probing another, so the second eglInitialize is the one that matters, and a refusal there - // is reported one layer up as "no usable DRM render device" - the probe having succeeded - // and the real display having failed, with nothing in between that says which was refused. m_display = dpy; - m_displayInitialized = true; + m_initializedDisplays.insert(dpy); if (major) { *major = 1; } @@ -79,7 +70,7 @@ namespace MobileGL::MG_Backend { Bool EGLSurfaceRegistry::RegisterWindowSurface(EGLSurface surface, const WindowHandle& handle) { const std::lock_guard lock(m_mutex); - if (!m_displayInitialized) { + if (!DisplayInitialized(RegistrationDisplay())) { MGLOG_E("RegisterEGLWindowSurface failed: EGL display is not initialized"); return false; } @@ -95,6 +86,7 @@ namespace MobileGL::MG_Backend { auto& state = m_surfaces[surface]; state = SurfaceState{ .Kind = SurfaceKind::Window, + .Display = RegistrationDisplay(), .Window = handle, .Width = static_cast(std::max(handle.Width, 1)), .Height = static_cast(std::max(handle.Height, 1)), @@ -104,7 +96,7 @@ namespace MobileGL::MG_Backend { Bool EGLSurfaceRegistry::RegisterPbufferSurface(EGLSurface surface, EGLint width, EGLint height) { const std::lock_guard lock(m_mutex); - if (!m_displayInitialized) { + if (!DisplayInitialized(RegistrationDisplay())) { MGLOG_E("RegisterEGLPbufferSurface failed: EGL display is not initialized"); return false; } @@ -119,6 +111,7 @@ namespace MobileGL::MG_Backend { m_surfaces[surface] = SurfaceState{ .Kind = SurfaceKind::Pbuffer, + .Display = RegistrationDisplay(), .Width = width, .Height = height, }; @@ -181,10 +174,15 @@ namespace MobileGL::MG_Backend { return true; } - if (!m_displayInitialized || m_display != dpy) { + if (!DisplayInitialized(dpy)) { MGLOG_E("MakeEGLCurrent failed: EGL display mismatch or not initialized"); return false; } + const auto* drawState = Registered(draw); + const auto* readState = Registered(read); + if ((drawState && (drawState->Display != dpy || drawState->DestroyPending)) || + (readState && (readState->Display != dpy || readState->DestroyPending))) + return false; if (!m_hasActiveSurface) { if (draw != read || !Activate(draw)) { MGLOG_E("MakeEGLCurrent failed: EGL surface is not initialized"); @@ -246,7 +244,7 @@ namespace MobileGL::MG_Backend { Bool EGLSurfaceRegistry::Swap(EGLDisplay dpy, EGLSurface draw) { const std::lock_guard lock(m_mutex); - if (!m_displayInitialized || m_display != dpy) { + if (!DisplayInitialized(dpy)) { MGLOG_E("SwapEGLBuffers failed: EGL display mismatch or not initialized"); return false; } @@ -281,6 +279,15 @@ namespace MobileGL::MG_Backend { return true; } + Bool EGLSurfaceRegistry::IsCurrentOnOtherThread(EGLSurface surface) const { + const auto lock = Lock(); + const auto thread = CurrentThreadKey(); + for (const auto& [owner, current] : m_currentThreads) { + if (owner != thread && (current.DrawSurface == surface || current.ReadSurface == surface)) return true; + } + return false; + } + Bool EGLSurfaceRegistry::IsCurrentOnAnyThread(EGLSurface surface) const { if (surface == EGL_NO_SURFACE) { return false; @@ -345,7 +352,8 @@ namespace MobileGL::MG_Backend { ResetRuntimeState(); m_surfaces.clear(); m_display = EGL_NO_DISPLAY; - m_displayInitialized = false; + m_initializedDisplays.clear(); + m_registrationDisplay = EGL_NO_DISPLAY; } void EGLSurfaceRegistry::SetWindowHandle(const WindowHandle& handle) { @@ -393,7 +401,44 @@ namespace MobileGL::MG_Backend { Bool EGLSurfaceRegistry::DisplayInitialized() const { const std::lock_guard lock(m_mutex); - return m_displayInitialized; + return !m_initializedDisplays.empty(); + } + + Bool EGLSurfaceRegistry::DisplayInitialized(EGLDisplay display) const { + const std::lock_guard lock(m_mutex); + return m_initializedDisplays.contains(display); + } + + EGLDisplay EGLSurfaceRegistry::SetRegistrationDisplay(EGLDisplay display) { + const std::lock_guard lock(m_mutex); + return std::exchange(m_registrationDisplay, display); + } + + EGLDisplay EGLSurfaceRegistry::RegistrationDisplay() const { + const std::lock_guard lock(m_mutex); + return m_registrationDisplay == EGL_NO_DISPLAY ? m_display : m_registrationDisplay; + } + + Vector EGLSurfaceRegistry::InitializedDisplays() const { + const std::lock_guard lock(m_mutex); + return {m_initializedDisplays.begin(), m_initializedDisplays.end()}; + } + + Vector EGLSurfaceRegistry::SurfacesOnDisplay(EGLDisplay display) const { + const std::lock_guard lock(m_mutex); + Vector result; + for (const auto& [surface, state] : m_surfaces) { + if (state.Display == display) result.push_back(surface); + } + return result; + } + + void EGLSurfaceRegistry::ReleaseDisplay(EGLDisplay display) { + const std::lock_guard lock(m_mutex); + m_initializedDisplays.erase(display); + if (m_display == display) { + m_display = m_initializedDisplays.empty() ? EGL_NO_DISPLAY : *m_initializedDisplays.begin(); + } } EGLDisplay EGLSurfaceRegistry::Display() const { diff --git a/MobileGL/MG_Backend/EGLSurfaceRegistry.h b/MobileGL/MG_Backend/EGLSurfaceRegistry.h index 2c3ad5cf..40f37146 100644 --- a/MobileGL/MG_Backend/EGLSurfaceRegistry.h +++ b/MobileGL/MG_Backend/EGLSurfaceRegistry.h @@ -48,6 +48,7 @@ namespace MobileGL::MG_Backend { struct SurfaceState { SurfaceKind Kind = SurfaceKind::None; + EGLDisplay Display = EGL_NO_DISPLAY; Bool DestroyPending = false; // Activated at least once: a re-activation (a multi-window client switching back) // is a re-bind and does not re-run the backend's capability probe. @@ -92,6 +93,11 @@ namespace MobileGL::MG_Backend { Bool MakeCurrent(EGLDisplay dpy, EGLSurface draw, EGLSurface read, EGLContext ctx); Bool Swap(EGLDisplay dpy, EGLSurface draw); void ReleaseSurface(EGLSurface surface); + void ReleaseDisplay(EGLDisplay display); + EGLDisplay SetRegistrationDisplay(EGLDisplay display); + EGLDisplay RegistrationDisplay() const; + Vector InitializedDisplays() const; + Vector SurfacesOnDisplay(EGLDisplay display) const; // Every surface, the display and every thread's current state; no hook runs. void ReleaseAll(); void SetWindowHandle(const WindowHandle& handle); @@ -117,6 +123,7 @@ namespace MobileGL::MG_Backend { // ---- queries -------------------------------------------------------------------------- Bool DisplayInitialized() const; + Bool DisplayInitialized(EGLDisplay display) const; EGLDisplay Display() const; Bool HasActiveSurface() const; EGLSurface ActiveSurface() const; @@ -130,6 +137,7 @@ namespace MobileGL::MG_Backend { Bool IsRegistered(EGLSurface surface) const; Optional Find(EGLSurface surface) const; Optional CurrentOn(std::thread::id thread) const; + Bool IsCurrentOnOtherThread(EGLSurface surface) const; SizeT CurrentThreadCount() const; private: @@ -144,7 +152,8 @@ namespace MobileGL::MG_Backend { EGLDisplay m_display = EGL_NO_DISPLAY; EGLSurface m_activeSurface = EGL_NO_SURFACE; EGLSurface m_activatingSurface = EGL_NO_SURFACE; - Bool m_displayInitialized = false; + std::unordered_set m_initializedDisplays; + EGLDisplay m_registrationDisplay = EGL_NO_DISPLAY; Bool m_hasActiveSurface = false; Bool m_capabilitiesInitialized = false; SurfaceKind m_activeSurfaceKind = SurfaceKind::None; diff --git a/MobileGL/MG_Impl/EGLImpl/EGLImpl.cpp b/MobileGL/MG_Impl/EGLImpl/EGLImpl.cpp index cf45d2c2..f7e56bfe 100644 --- a/MobileGL/MG_Impl/EGLImpl/EGLImpl.cpp +++ b/MobileGL/MG_Impl/EGLImpl/EGLImpl.cpp @@ -187,13 +187,68 @@ namespace MobileGL::MG_Impl::EGLImpl { #endif std::recursive_mutex& EGLOperationMutex() { - static std::recursive_mutex mutex; - return mutex; + static auto* mutex = new std::recursive_mutex(); + return *mutex; } -#if MOBILEGL_BUILD_DISAGGREGATED + struct EGLThreadBinding { + Bool Bound = false; + ~EGLThreadBinding() { + if (Bound) (void)ReleaseThread(); + } + }; + + EGLThreadBinding& ThreadBinding() { + thread_local EGLThreadBinding binding; + return binding; + } + + class ScopedEGLObjectShareGroup { + public: + ScopedEGLObjectShareGroup(MG_Backend::BackendObject* backend, Uint64 group) + : m_backend(backend), m_previous(backend ? backend->SetEGLObjectShareGroup(group) : 0) {} + ~ScopedEGLObjectShareGroup() { + if (m_backend) (void)m_backend->SetEGLObjectShareGroup(m_previous); + } + + private: + MG_Backend::BackendObject* m_backend; + Uint64 m_previous; + }; + + void ReleaseContextStandIn(EGLContext context); + + void FinishLocalContextDestroy(EGLContext context, Uint64 token, Uint64 group, + SharedPtr glState) { + auto* backend = MG_Backend::pActiveBackendObject.get(); + { + const ScopedEGLObjectShareGroup scope(backend, group); + glState.reset(); + } + if (backend) backend->ReleaseEGLContext(token); + ReleaseContextStandIn(context); + } } // namespace + std::recursive_mutex* LockGLCommands(Bool bindStream) { +#if MOBILEGL_BUILD_DISAGGREGATED + if (MG_Remote::Client::RunsAsTheServerRole()) return nullptr; +#endif + auto& mutex = EGLOperationMutex(); + mutex.lock(); +#if MOBILEGL_BUILD_DISAGGREGATED + if (StreamGateActive()) { + if (bindStream) StreamBindCallingThreadLocked(); + return &mutex; + } +#else + (void)bindStream; +#endif + if (auto* backend = MG_Backend::pActiveBackendObject.get()) backend->BeginEGLCommands(); + return &mutex; + } + +#if MOBILEGL_BUILD_DISAGGREGATED Bool StreamGateActive() { return MG_Config::Transport != MG_Config::TransportMode::Monolith && !MG_Remote::Client::RunsAsTheServerRole(); } @@ -279,7 +334,10 @@ namespace MobileGL::MG_Impl::EGLImpl { void FinishReapedContexts(MG_State::EGLState::EGLContext* state) { if (state == nullptr) return; if (!StreamGateActive()) { - (void)state->TakeReapedContexts(); // dropping them ends their GL state + for (auto& reaped : state->TakeReapedContexts()) { + FinishLocalContextDestroy(reaped.Handle, reaped.ClientContextToken, reaped.ShareGroupToken, + Move(reaped.GLStateObject)); + } return; } for (auto& reaped : state->TakeReapedContexts()) { @@ -291,11 +349,18 @@ namespace MobileGL::MG_Impl::EGLImpl { namespace { #else + namespace { // A monolith has no stream to bind: a context whose deferred destroy completed simply ends. void FinishReapedContexts(MG_State::EGLState::EGLContext* state) { - if (state != nullptr) (void)state->TakeReapedContexts(); + if (state == nullptr) return; + for (auto& reaped : state->TakeReapedContexts()) { + FinishLocalContextDestroy(reaped.Handle, reaped.ClientContextToken, reaped.ShareGroupToken, + Move(reaped.GLStateObject)); + } } #endif + void TearDownIdleEGL(EGLStateContext* state); + String CurrentThreadIdString() { std::ostringstream stream; stream << std::this_thread::get_id(); @@ -366,27 +431,38 @@ namespace MobileGL::MG_Impl::EGLImpl { return *surfaces; } - // EGL_KHR_surfaceless_context. The EGL state records a surfaceless binding as exactly that - // (eglGetCurrentSurface answers EGL_NO_SURFACE), but every backend renders into the surface - // it was bound to, and a session's capabilities are published on its first bind to one. So - // the backend is bound to a 1x1 pbuffer of the display's own instead: one per display, made - // on the first surfaceless bind, never handed to the application, and gone with the display - // (eglTerminate). Guarded by EGLOperationMutex. - std::unordered_map& SurfacelessStandIns() { - static auto* standIns = new std::unordered_map(); - return *standIns; - } - + // A private pbuffer backs a surfaceless context. Native contexts that can be + // current concurrently need distinct pbuffers; split clients serialize on one. // eglCreatePbufferSurface for the stand-in, except that a split client creates it on the // server as a stand-in, which takes no surface mode there (a server-owned window may follow). EGLSurface CreateSurfacelessStandInPbuffer(EGLStateContext* state, EGLDisplay dpy, EGLConfig config, const EGLint* attribs); - // The display's stand-in, made now if it has none (or the one it had did not survive). - // EGL_NO_SURFACE when the backend could not make a pbuffer; the EGL error is then set. - EGLSurface SurfacelessStandIn(EGLStateContext* state, EGLDisplay dpy) { - auto& standIns = SurfacelessStandIns(); - if (const auto it = standIns.find(dpy); it != standIns.end()) { + using StandInKey = std::pair; + std::map& ContextStandIns() { + static auto* standIns = new std::map(); + return *standIns; + } + + void ReleaseContextStandIn(EGLContext context) { + auto& standIns = ContextStandIns(); + const auto it = std::find_if(standIns.begin(), standIns.end(), + [context](const auto& entry) { return entry.first.second == context; }); + if (it == standIns.end()) return; + const auto [display, surface] = std::pair(it->first.first, it->second); + standIns.erase(it); + if (auto* state = GetState(); state && state->ValidateSurfaceOnDisplay(display, surface)) { + (void)DestroySurface(display, surface); + } + } + + EGLSurface SurfacelessStandIn(EGLStateContext* state, EGLDisplay dpy, EGLContext ctx) { + auto& standIns = ContextStandIns(); +#if MOBILEGL_BUILD_DISAGGREGATED + if (StreamGateActive()) ctx = EGL_NO_CONTEXT; +#endif + const StandInKey key{dpy, ctx}; + if (const auto it = standIns.find(key); it != standIns.end()) { if (state->ValidateSurfaceOnDisplay(dpy, it->second)) return it->second; standIns.erase(it); } @@ -399,7 +475,7 @@ namespace MobileGL::MG_Impl::EGLImpl { } const EGLint attribs[] = {EGL_WIDTH, 1, EGL_HEIGHT, 1, EGL_NONE}; const EGLSurface standIn = CreateSurfacelessStandInPbuffer(state, dpy, config, attribs); - if (standIn != EGL_NO_SURFACE) standIns[dpy] = standIn; + if (standIn != EGL_NO_SURFACE) standIns[key] = standIn; return standIn; } @@ -469,7 +545,7 @@ namespace MobileGL::MG_Impl::EGLImpl { if (surface == EGL_NO_SURFACE) return true; (void)state->ResizeSurface(dpy, surface, width, height); auto* backendObject = GetBackendObject(state); - if (!backendObject || !backendObject->CreateEGLPbufferSurface(surface, width, height)) { + if (!backendObject || !backendObject->CreateEGLPbufferSurfaceOnDisplay(dpy, surface, width, height)) { MGLOG_E("eglCreateWindowSurface: the backend refused the %dx%d drawable behind a Wayland window", width, height); state->DestroySurface(dpy, surface); @@ -491,13 +567,15 @@ namespace MobileGL::MG_Impl::EGLImpl { if (it == WaylandSurfaces().end()) return; EGLint width = 0; EGLint height = 0; - if (!it->second->TakeResize(&width, &height)) return; - (void)state->ResizeSurface(dpy, surface, width, height); + if (!it->second->GetPendingResize(&width, &height)) return; auto* backendObject = MG_Backend::pActiveBackendObject.get(); if (backendObject == nullptr || !backendObject->ResizeEGLWindowSurface(surface, static_cast(width), static_cast(height))) { MGLOG_E("Wayland: the drawable behind a %dx%d window could not be resized", width, height); + return; } + (void)state->ResizeSurface(dpy, surface, width, height); + it->second->CommitResize(width, height); } #endif @@ -615,7 +693,7 @@ namespace MobileGL::MG_Impl::EGLImpl { if (!RecoverBeforeCreatingSurface(state)) return EGL_NO_SURFACE; const EGLSurface surface = state->CreatePbufferSurface(dpy, config, attribs); if (surface == EGL_NO_SURFACE) return EGL_NO_SURFACE; - if (!remote->CreateEGLSurfacelessStandIn(surface, GetAttribValue(attribs, EGL_WIDTH, 1), + if (!remote->CreateEGLSurfacelessStandIn(dpy, surface, GetAttribValue(attribs, EGL_WIDTH, 1), GetAttribValue(attribs, EGL_HEIGHT, 1))) { state->DestroySurface(dpy, surface); state->SetError(EGL_BAD_ALLOC); @@ -720,7 +798,7 @@ namespace MobileGL::MG_Impl::EGLImpl { state->DestroySurface(dpy, surface); return EGL_NO_SURFACE; } - if (!backendObject->CreateEGLWindowSurface(surface, windowHandle)) { + if (!backendObject->CreateEGLWindowSurfaceOnDisplay(dpy, surface, windowHandle)) { state->DestroySurface(dpy, surface); state->SetError(EGL_BAD_NATIVE_WINDOW); return EGL_NO_SURFACE; @@ -845,6 +923,7 @@ namespace MobileGL::MG_Impl::EGLImpl { if (!state) { return EGL_NO_CONTEXT; } + const std::lock_guard operationLock(EGLOperationMutex()); // The API the context is for, as the dispatcher reports it (SetDispatcherCurrentApiHook): // an ES context made without an eglBindAPI - or with one of the default - is an ES context. if (const auto currentApi = g_dispatcherCurrentApi.load()) { @@ -856,7 +935,6 @@ namespace MobileGL::MG_Impl::EGLImpl { // session comes up (RecoverLostSession) - before the context's GL state is built, because // building it already emits the creates of its default objects. Sharing with a lost // context would share objects no reachable server holds. - const std::lock_guard operationLock(EGLOperationMutex()); // The lost share group this context replaces (ReplacementShareContexts), 0 for none. Uint64 replacedGroup = 0; if (StreamGateActive()) { @@ -888,10 +966,18 @@ namespace MobileGL::MG_Impl::EGLImpl { #else constexpr Bool splitClient = false; #endif - EGLContext context = state->CreateContext(dpy, config, shareCtx, attrib_list, splitClient); + EGLContext context = + state->CreateContext(dpy, config, shareCtx, attrib_list, true, ResetNotificationAvailable()); if (context == EGL_NO_CONTEXT) { return EGL_NO_CONTEXT; } + if (!splitClient) { + auto* backend = MG_Backend::pActiveBackendObject.get(); + const Uint64 group = state->GetContextShareGroupToken(context); + if (backend) backend->RegisterEGLContext(context, state->GetContextClientToken(context), group); + const ScopedEGLObjectShareGroup scope(backend, group); + (void)state->BuildContextGLState(context); + } #if MOBILEGL_BUILD_DISAGGREGATED if (replacedGroup != 0) ReplacementShareContexts()[replacedGroup].push_back(context); #endif @@ -927,7 +1013,8 @@ namespace MobileGL::MG_Impl::EGLImpl { replacedGroup = state->GetContextShareGroupToken(shareCtx); shareCtx = ReplacementShareContext(state, dpy, replacedGroup); } - context = state->CreateContext(dpy, config, shareCtx, attrib_list, splitClient); + context = + state->CreateContext(dpy, config, shareCtx, attrib_list, true, ResetNotificationAvailable()); } if (context == EGL_NO_CONTEXT) { state->SetError(EGL_BAD_ALLOC); @@ -1012,13 +1099,6 @@ namespace MobileGL::MG_Impl::EGLImpl { if (!state) { return EGL_FALSE; } - // A release (explicit, or the implicit one of binding another context) may complete the - // deferred destroy of the context it releases; that destroy is finished on the way out, - // under the lock, whichever way this call returns. - struct FinishReapedOnExit { - EGLStateContext* State; - ~FinishReapedOnExit() { FinishReapedContexts(State); } - } finishReaped{state}; const auto oldDisplay = state->GetCurrentDisplay(); const auto oldDraw = state->GetCurrentSurface(EGL_DRAW); @@ -1053,26 +1133,27 @@ namespace MobileGL::MG_Impl::EGLImpl { } #endif -#if MOBILEGL_WAYLAND_WINDOWS - if (draw != EGL_NO_SURFACE) ApplyWaylandResize(state, dpy, draw); -#endif - if (!state->MakeCurrent(dpy, draw, read, ctx)) { + if (!state->MakeCurrent(dpy, draw, read, ctx, true)) { const EGLint error = state->ConsumeError(); MGLOG_D("eglMakeCurrent rejected by EGLState thread=%s error=0x%04x", threadId.c_str(), error); state->SetError(error); return EGL_FALSE; } +#if MOBILEGL_WAYLAND_WINDOWS + if (draw != EGL_NO_SURFACE) ApplyWaylandResize(state, dpy, draw); +#endif const Bool releaseCurrentRequest = draw == EGL_NO_SURFACE && read == EGL_NO_SURFACE && ctx == EGL_NO_CONTEXT; if (releaseCurrentRequest) { if (auto* backendObject = MG_Backend::pActiveBackendObject.get()) { if (!backendObject->MakeEGLCurrent(dpy, draw, read, ctx)) { MGLOG_E_ONCE("eglMakeCurrent release failed in backend thread=%s", threadId.c_str()); - state->MakeCurrent(oldDisplay, oldDraw, oldRead, oldContext); state->SetError(EGL_BAD_ACCESS); return EGL_FALSE; } } + (void)state->MakeCurrent(dpy, draw, read, ctx); + ThreadBinding().Bound = false; MGLOG_D("eglMakeCurrent release succeeded thread=%s", threadId.c_str()); #if MOBILEGL_BUILD_DISAGGREGATED { @@ -1081,26 +1162,25 @@ namespace MobileGL::MG_Impl::EGLImpl { EmitContextBinding(state, EGL_NO_CONTEXT, oldContextToken); } #endif + FinishReapedContexts(state); + if (oldDisplay != EGL_NO_DISPLAY && !state->IsDisplayInitialized(oldDisplay)) TearDownIdleEGL(state); return EGL_TRUE; } auto* backendObject = GetBackendObject(state); if (!backendObject) { MGLOG_E_ONCE("activeBackendObject not initialized!"); - state->MakeCurrent(oldDisplay, oldDraw, oldRead, oldContext); return EGL_FALSE; } - // A surfaceless binding (EGL_KHR_surfaceless_context; EGLState took it above and records - // EGL_NO_SURFACE): the backend gets the display's stand-in pbuffer to render into. + // The frontend records a surfaceless binding. The backend renders into a private pbuffer. EGLSurface backendDraw = draw; EGLSurface backendRead = read; if (draw == EGL_NO_SURFACE && read == EGL_NO_SURFACE) { - backendDraw = backendRead = SurfacelessStandIn(state, dpy); + backendDraw = backendRead = SurfacelessStandIn(state, dpy, ctx); if (backendDraw == EGL_NO_SURFACE) { const EGLint error = state->ConsumeError(); MGLOG_E_ONCE("eglMakeCurrent: no stand-in pbuffer for a surfaceless binding thread=%s (error=0x%04x)", threadId.c_str(), error); - state->MakeCurrent(oldDisplay, oldDraw, oldRead, oldContext); state->SetError(error != EGL_SUCCESS ? error : EGL_BAD_ALLOC); return EGL_FALSE; } @@ -1109,14 +1189,17 @@ namespace MobileGL::MG_Impl::EGLImpl { MGLOG_E_ONCE("eglMakeCurrent backend attach failed thread=%s dpy=%p draw=%p read=%p ctx=%p", threadId.c_str(), dpy, draw, read, ctx); state->SetError(EGL_BAD_ACCESS); - state->MakeCurrent(oldDisplay, oldDraw, oldRead, oldContext); return EGL_FALSE; } + (void)state->MakeCurrent(dpy, draw, read, ctx); + // Construct the guard after GL-state TLS so it releases the EGL binding first at exit. + ThreadBinding().Bound = true; MGLOG_D("eglMakeCurrent attach succeeded thread=%s dpy=%p draw=%p read=%p ctx=%p", threadId.c_str(), dpy, draw, read, ctx); #if MOBILEGL_BUILD_DISAGGREGATED EmitContextBinding(state, ctx, oldContextToken); #endif + FinishReapedContexts(state); return EGL_TRUE; } @@ -1125,7 +1208,6 @@ namespace MobileGL::MG_Impl::EGLImpl { if (!state) { return EGL_FALSE; } -#if MOBILEGL_BUILD_DISAGGREGATED // Under the operation lock, like every GL call: what ends here writes records. const std::lock_guard destroyLock(EGLOperationMutex()); // P14 S1. Read BEFORE the client's own book drops the context: after DestroyContext @@ -1138,7 +1220,6 @@ namespace MobileGL::MG_Impl::EGLImpl { // A LOST CONTEXT IS DESTROYED IN SILENCE. Its objects die here, and a death that reached // the wire would land on whichever session is current now - a fresh one after a recovery, // which never created them. - const Bool lost = ContextIsLost(state, ctx); // The context's GL state, held across the book's drop so that its objects end in // FinishContextDestroy, under the context's own binding, rather than inside EGLState. SharedPtr glState = state->GetContextGLState(ctx); @@ -1146,16 +1227,19 @@ namespace MobileGL::MG_Impl::EGLImpl { if (!state->DestroyContext(dpy, ctx, &deferred)) { return EGL_FALSE; } + // A current context keeps drawing until its owner releases it. +#if MOBILEGL_BUILD_DISAGGREGATED ForgetReplacementShareContext(ctx); - // CURRENT TO A THREAD (this one or another): EGL destroys it once it is released, and that - // release finishes it (FinishReapedContexts). Until then its thread keeps drawing in it. +#endif if (deferred) return EGL_TRUE; - FinishContextDestroy(contextToken, shareGroupToken, Move(glState), lost); -#else - if (!state->DestroyContext(dpy, ctx)) { - return EGL_FALSE; +#if MOBILEGL_BUILD_DISAGGREGATED + if (StreamGateActive()) { + const Bool lost = glState && (glState->IsFromEndedWireSession() || ClientSession::SessionLatchedLost()); + FinishContextDestroy(contextToken, shareGroupToken, Move(glState), lost); + return EGL_TRUE; } #endif + FinishLocalContextDestroy(ctx, contextToken, shareGroupToken, Move(glState)); return EGL_TRUE; } @@ -1178,7 +1262,17 @@ namespace MobileGL::MG_Impl::EGLImpl { return EGL_TRUE; } + namespace { + void TearDownIdleEGL(EGLStateContext* state) { + if (state->HasAnyInitializedDisplay() || state->HasAnyCurrentContext()) return; + if (auto* backend = MG_Backend::pActiveBackendObject.get()) backend->ReleaseEGLResources(); + MG_State::ReleaseProcessDefaultGLContext(); + MobileGL::Destroy(); + } + } // namespace + EGLBoolean Terminate(EGLDisplay dpy) { + const std::lock_guard operationLock(EGLOperationMutex()); auto* state = GetState(); if (!state) { return EGL_FALSE; @@ -1186,51 +1280,38 @@ namespace MobileGL::MG_Impl::EGLImpl { if (!state->TerminateDisplay(dpy)) { return EGL_FALSE; } - { - // The display's surfaces went with it, its surfaceless stand-in among them; the backend - // side goes with ReleaseEGLResources below. - const std::lock_guard operationLock(EGLOperationMutex()); - SurfacelessStandIns().erase(dpy); - } + std::erase_if(ContextStandIns(), [dpy](const auto& entry) { return entry.first.first == dpy; }); + FinishReapedContexts(state); if (auto* backendObject = MG_Backend::pActiveBackendObject.get()) { // The display's dma-buf EGLImages went with it; so do their shared-image references. MG_Backend::ClientHooks* client = backendObject->AsClient(); for (const Uint64 sharedImageId : state->TakeOrphanedSharedImages()) { if (client != nullptr) (void)client->ReleaseSharedImage(sharedImageId); } - backendObject->ReleaseEGLResources(); - } - // The last initialized display is gone and nothing is current on any - // thread: tear the whole library down deterministically inside the - // EGL lifecycle (backend, GL/EGL state, glslang). A later EGL call - // re-initializes lazily via GetStateEnsureInitialized(); process exit - // then has nothing left to destroy. - if (!state->HasAnyInitializedDisplay() && !state->HasAnyCurrentContext()) { - // P14 S3: the process default context (and with it the GL objects the frontend - // built while no EGL context was current) goes before Destroy() does, so nothing - // it owns outlives glslang::FinalizeProcess() through a thread's fallback binding. - MG_State::ReleaseProcessDefaultGLContext(); - MobileGL::Destroy(); + backendObject->ReleaseEGLDisplay(dpy); } + TearDownIdleEGL(state); return EGL_TRUE; } EGLBoolean ReleaseThread() { - // Always succeeds (EGL 1.4 §3.11): after the last eglTerminate tore MobileGL down there is - // simply nothing of this thread's left to release. - if (!MG_State::pEGLContext) return EGL_TRUE; + // EGL thread release also runs when an application thread exits. const std::lock_guard operationLock(EGLOperationMutex()); + if (!MG_State::pEGLContext) return EGL_TRUE; auto* state = GetState(); + const EGLDisplay oldDisplay = state->GetCurrentDisplay(); if (auto* backendObject = MG_Backend::pActiveBackendObject.get()) { (void)backendObject->MakeEGLCurrent(EGL_NO_DISPLAY, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); } state->ReleaseThread(); + ThreadBinding().Bound = false; #if MOBILEGL_BUILD_DISAGGREGATED // The release edge, as eglMakeCurrent's release sends it: this thread has no context now, // and the binding must not keep naming the one it had. EmitContextBinding(state, EGL_NO_CONTEXT, 0); #endif FinishReapedContexts(state); + if (oldDisplay != EGL_NO_DISPLAY && !state->IsDisplayInitialized(oldDisplay)) TearDownIdleEGL(state); return EGL_TRUE; } @@ -1405,7 +1486,9 @@ namespace MobileGL::MG_Impl::EGLImpl { // this query an application reads have to agree: an application that does not see the // platform extension here never asks for a platform display at all. if (display == EGL_NO_DISPLAY) return kClientExtensionString; - return SharedImagesAvailable() ? kDisplayExtensionStringWithSharedImages : kDisplayExtensionString; + if (SharedImagesAvailable()) return kDisplayExtensionStringWithSharedImages; + return ResetNotificationAvailable() ? kDisplayExtensionStringWithResetNotification + : kDisplayExtensionString; default: state->SetError(EGL_BAD_PARAMETER); return nullptr; @@ -1449,7 +1532,7 @@ namespace MobileGL::MG_Impl::EGLImpl { if (!backendObject) { return EGL_NO_SURFACE; } - if (!backendObject->CreateEGLPbufferSurface(surface, width, height)) { + if (!backendObject->CreateEGLPbufferSurfaceOnDisplay(dpy, surface, width, height)) { state->DestroySurface(dpy, surface); state->SetError(EGL_BAD_ALLOC); return EGL_NO_SURFACE; @@ -1670,6 +1753,14 @@ namespace MobileGL::MG_Impl::EGLImpl { g_dispatcherCurrentApi.store(hook); } + Bool ResetNotificationAvailable() { +#if MOBILEGL_BUILD_DISAGGREGATED + return StreamGateActive(); +#else + return false; +#endif + } + Bool SharedImagesAvailable() { #if MOBILEGL_BUILD_DISAGGREGATED // A split client's backend is the remote one, which forwards the shared-image verbs to @@ -2000,7 +2091,7 @@ namespace MobileGL::MG_Impl::EGLImpl { state->DestroySurface(dpy, surface); return EGL_NO_SURFACE; } - if (!backendObject->CreateEGLWindowSurface(surface, windowHandle)) { + if (!backendObject->CreateEGLWindowSurfaceOnDisplay(dpy, surface, windowHandle)) { state->DestroySurface(dpy, surface); state->SetError(EGL_BAD_NATIVE_WINDOW); return EGL_NO_SURFACE; diff --git a/MobileGL/MG_Impl/EGLImpl/EGLImpl.h b/MobileGL/MG_Impl/EGLImpl/EGLImpl.h index cca48d61..03df1c9b 100644 --- a/MobileGL/MG_Impl/EGLImpl/EGLImpl.h +++ b/MobileGL/MG_Impl/EGLImpl/EGLImpl.h @@ -68,6 +68,8 @@ namespace MobileGL::MG_Impl::EGLImpl { // a split client's does, a monolith's does not. Decides the dma-buf EGL extensions, the // Wayland linux-dmabuf presentation and GL_OES_EGL_image. Bool SharedImagesAvailable(); + // Reset reporting is provided by the split client through its session. + Bool ResetNotificationAvailable(); // Whether the server also holds YUV (NV12/P010) images: decides the YUV dma-buf formats and // GL_OES_EGL_image_external. One round trip the first time it is asked, cached after. Bool SharedImageYuvAvailable(); @@ -114,15 +116,14 @@ namespace MobileGL::MG_Impl::EGLImpl { // (a monolith, the server's own apply thread), where no binding crosses. Read under // StreamMutex(), like the binding itself. Bool StreamBoundShareGroupToken(Uint64* outToken); +#endif + + // Serialize commands that use the same backend binding shadows. + std::recursive_mutex* LockGLCommands(Bool bindStream = true); class GLStreamScope { public: - GLStreamScope() { - if (!StreamGateActive()) return; - m_mutex = &StreamMutex(); - m_mutex->lock(); - StreamBindCallingThreadLocked(); - } + GLStreamScope() : m_mutex(LockGLCommands()) {} ~GLStreamScope() { if (m_mutex != nullptr) m_mutex->unlock(); } @@ -130,18 +131,13 @@ namespace MobileGL::MG_Impl::EGLImpl { GLStreamScope& operator=(const GLStreamScope&) = delete; private: - std::recursive_mutex* m_mutex = nullptr; + std::recursive_mutex* m_mutex; }; - // The lock alone, for every EGL entry point: an EGL call may publish into the ring too (a - // surface forwarder's catch-up wait, a present, a context frame), and a second thread's GL - // record written into the middle of it is a torn record the server latches the session on. + + // EGL commands serialize without changing the remote stream's current context. class StreamLockScope { public: - StreamLockScope() { - if (!StreamGateActive()) return; - m_mutex = &StreamMutex(); - m_mutex->lock(); - } + StreamLockScope() : m_mutex(LockGLCommands(false)) {} ~StreamLockScope() { if (m_mutex != nullptr) m_mutex->unlock(); } @@ -149,10 +145,6 @@ namespace MobileGL::MG_Impl::EGLImpl { StreamLockScope& operator=(const StreamLockScope&) = delete; private: - std::recursive_mutex* m_mutex = nullptr; + std::recursive_mutex* m_mutex; }; -#else - class GLStreamScope {}; - class StreamLockScope {}; -#endif } // namespace MobileGL::MG_Impl::EGLImpl diff --git a/MobileGL/MG_Impl/EGLImpl/EGLPlatformExtensions.h b/MobileGL/MG_Impl/EGLImpl/EGLPlatformExtensions.h index 18c4f49d..1e53f0b4 100644 --- a/MobileGL/MG_Impl/EGLImpl/EGLPlatformExtensions.h +++ b/MobileGL/MG_Impl/EGLImpl/EGLPlatformExtensions.h @@ -25,23 +25,19 @@ namespace MobileGL::MG_Impl::EGLImpl { inline constexpr const char* kPlatformExtensionString = "EGL_EXT_client_extensions EGL_EXT_platform_base EGL_KHR_platform_base " "EGL_MESA_platform_surfaceless" MOBILEGL_PLATFORM_WAYLAND_EXTENSIONS; - // EGL_EXT_create_context_robustness: a context may ask for EGL_LOSE_CONTEXT_ON_RESET, and a - // split client's contexts are lost exactly when their server session is (a device loss on the - // server ends that session). An application learns of it through glGetGraphicsResetStatus only - // if it could ask for it here: ANGLE's GL-on-EGL backend mirrors this extension onto its own - // display, and Chrome checks that display for it before it ever queries the reset status. - inline constexpr const char* kDisplayExtensionString = - "EGL_KHR_create_context EGL_KHR_surfaceless_context EGL_KHR_no_config_context EGL_EXT_platform_base " - "EGL_EXT_create_context_robustness EGL_KHR_platform_base " - "EGL_MESA_platform_surfaceless" MOBILEGL_PLATFORM_WAYLAND_EXTENSIONS; +#define MOBILEGL_DISPLAY_EXTENSIONS \ + "EGL_KHR_create_context EGL_KHR_surfaceless_context EGL_KHR_no_config_context EGL_EXT_platform_base " \ + "EGL_KHR_platform_base EGL_MESA_platform_surfaceless" MOBILEGL_PLATFORM_WAYLAND_EXTENSIONS + inline constexpr const char* kDisplayExtensionString = MOBILEGL_DISPLAY_EXTENSIONS; + // The split client reports a lost server session through glGetGraphicsResetStatus. + inline constexpr const char* kDisplayExtensionStringWithResetNotification = + MOBILEGL_DISPLAY_EXTENSIONS " EGL_EXT_create_context_robustness"; // The display list again, with the dma-buf import a backend with shared images has (a split // client: the server allocates the images and names the descriptors that come back). A // monolith has no allocator to recognize a dma-buf with, so it never advertises these. The // same server answers the buffer age of its surfaces and takes swap damage to its presents. - inline constexpr const char* kDisplayExtensionStringWithSharedImages = - "EGL_KHR_create_context EGL_KHR_surfaceless_context EGL_KHR_no_config_context EGL_EXT_platform_base " - "EGL_EXT_create_context_robustness EGL_KHR_platform_base " - "EGL_MESA_platform_surfaceless" MOBILEGL_PLATFORM_WAYLAND_EXTENSIONS + inline constexpr const char* kDisplayExtensionStringWithSharedImages = MOBILEGL_DISPLAY_EXTENSIONS + " EGL_EXT_create_context_robustness" " EGL_KHR_image_base EGL_EXT_image_dma_buf_import EGL_EXT_image_dma_buf_import_modifiers" " EGL_EXT_buffer_age EGL_KHR_partial_update EGL_KHR_swap_buffers_with_damage" " EGL_EXT_swap_buffers_with_damage" @@ -49,6 +45,7 @@ namespace MobileGL::MG_Impl::EGLImpl { // which is also what publishes a context's writes into dma-bufs to the compositor without a // swap: Chrome's GPU process ends each frame with one rather than a flush. " EGL_KHR_fence_sync EGL_KHR_wait_sync EGL_ANDROID_native_fence_sync"; +#undef MOBILEGL_DISPLAY_EXTENSIONS inline constexpr const char* kClientExtensionString = "EGL_EXT_client_extensions EGL_KHR_create_context EGL_EXT_platform_base " "EGL_KHR_platform_base EGL_MESA_platform_surfaceless" MOBILEGL_PLATFORM_WAYLAND_EXTENSIONS; diff --git a/MobileGL/MG_Impl/EGLImpl/WaylandWindow.cpp b/MobileGL/MG_Impl/EGLImpl/WaylandWindow.cpp index 00471842..ace12597 100644 --- a/MobileGL/MG_Impl/EGLImpl/WaylandWindow.cpp +++ b/MobileGL/MG_Impl/EGLImpl/WaylandWindow.cpp @@ -813,17 +813,20 @@ namespace MobileGL::MG_Impl::EGLImpl::Wayland { return UniquePtr(new WindowSurface(std::move(impl))); } - Bool WindowSurface::TakeResize(EGLint* width, EGLint* height) { - Impl& impl = *m_impl; + Bool WindowSurface::GetPendingResize(EGLint* width, EGLint* height) const { + const Impl& impl = *m_impl; if (impl.window == nullptr || impl.window->width <= 0 || impl.window->height <= 0) return false; if (impl.window->width == impl.width && impl.window->height == impl.height) return false; - impl.width = impl.window->width; - impl.height = impl.window->height; - *width = impl.width; - *height = impl.height; + *width = impl.window->width; + *height = impl.window->height; return true; } + void WindowSurface::CommitResize(EGLint width, EGLint height) { + m_impl->width = width; + m_impl->height = height; + } + void WindowSurface::OnSessionReplaced() { Impl& impl = *m_impl; const Api& api = WaylandApi(); diff --git a/MobileGL/MG_Impl/EGLImpl/WaylandWindow.h b/MobileGL/MG_Impl/EGLImpl/WaylandWindow.h index ace06f47..3c0a1333 100644 --- a/MobileGL/MG_Impl/EGLImpl/WaylandWindow.h +++ b/MobileGL/MG_Impl/EGLImpl/WaylandWindow.h @@ -97,10 +97,9 @@ namespace MobileGL::MG_Impl::EGLImpl::Wayland { }; PresentResult Present(const MG_Util::Damage::Region& damage, Int swapInterval, Bool (*sessionLost)()); - // wl_egl_window_resize's effect, taken: true (with the new size) when the application gave - // its wl_egl_window a size this presentation is not at yet. The presentation adopts it - - // its next buffer is that size - and the caller resizes the drawable behind it. - Bool TakeResize(EGLint* width, EGLint* height); + // Keep a resize pending until the backing drawable has been resized. + Bool GetPendingResize(EGLint* width, EGLint* height) const; + void CommitResize(EGLint width, EGLint height); // A swap that presents nothing (its context was lost) still commits the application's // wl_surface, with no new buffer: the frame callback a toolkit asked for just before the diff --git a/MobileGL/MG_Impl/GLImpl/Buffer/GL_Buffer.cpp b/MobileGL/MG_Impl/GLImpl/Buffer/GL_Buffer.cpp index ffeeb998..2780beb2 100644 --- a/MobileGL/MG_Impl/GLImpl/Buffer/GL_Buffer.cpp +++ b/MobileGL/MG_Impl/GLImpl/Buffer/GL_Buffer.cpp @@ -177,11 +177,16 @@ namespace MobileGL::MG_Impl::GLImpl { return false; } - if (bufferObject->IsMapped() && !(bufferObject->GetMappingAccess() & BufferMappingAccessBit::Persistent)) { + const SizeT clearStart = static_cast(offset); + const SizeT clearSize = static_cast(size); + const Range1D mappedRange = bufferObject->GetMappedRange(); + if (clearSize != 0 && bufferObject->IsMapped() && + !(bufferObject->GetMappingAccess() & BufferMappingAccessBit::Persistent) && + clearStart < mappedRange.end && clearStart + clearSize > mappedRange.start) { MG_State::pGLContext->RecordError( ErrorCode::InvalidOperation, MakeUnique("MG_Impl/GLImpl", GetBufferOpName(op), - "Cannot clear a non-persistently mapped buffer object.")); + "Clear range overlaps a non-persistently mapped range.")); return false; } @@ -267,11 +272,7 @@ namespace MobileGL::MG_Impl::GLImpl { } SharedPtr GetNamedBufferObject(GLuint buffer, BufferOp op) { - if (!BufferImpl::ValidateBufferName(buffer, false)) return nullptr; - if (!MG_State::pGLContext->ValidateBufferObject(buffer)) { - MG_State::pGLContext->CreateBufferObject(buffer); - } - auto& bufferObject = MG_State::pGLContext->GetBufferObject(buffer); + const auto& bufferObject = MG_State::pGLContext->GetBufferObject(buffer); if (!bufferObject) { MG_State::pGLContext->RecordError( ErrorCode::InvalidOperation, @@ -615,8 +616,7 @@ namespace MobileGL::MG_Impl::GLImpl { return GL_FALSE; } - bufferObject->ReleaseMemory(); - return GL_TRUE; + return bufferObject->ReleaseMemory() ? GL_TRUE : GL_FALSE; } void* MapBufferRange_State(GLenum target, GLintptr offset, GLsizeiptr length, GLbitfield access) { @@ -709,16 +709,11 @@ namespace MobileGL::MG_Impl::GLImpl { if (!ValidateImmutableMapAccess(bufferObject, accessBits, BufferOp::MapBufferRange)) return nullptr; if (bufferObject->IsMapped()) { - const auto invalidateFlags = - BufferMappingAccessBit::InvalidateRange | BufferMappingAccessBit::InvalidateBuffer; - - if (!(accessBits & invalidateFlags)) { - MG_State::pGLContext->RecordError( - ErrorCode::InvalidOperation, - MakeUnique("MG_Impl/GLImpl", "MapBufferRange_State", - "Cannot map a buffer object that is already mapped.")); - return nullptr; - } + MG_State::pGLContext->RecordError( + ErrorCode::InvalidOperation, + MakeUnique("MG_Impl/GLImpl", "MapBufferRange_State", + "Cannot map a buffer object that is already mapped.")); + return nullptr; } void* result = bufferObject->AcquireMemoryRange( @@ -1341,15 +1336,11 @@ namespace MobileGL::MG_Impl::GLImpl { if (!ValidateImmutableMapAccess(bufferObject, accessBits, BufferOp::MapNamedBufferRange)) return nullptr; if (bufferObject->IsMapped()) { - const auto invalidateFlags = - BufferMappingAccessBit::InvalidateRange | BufferMappingAccessBit::InvalidateBuffer; - if (!(accessBits & invalidateFlags)) { - MG_State::pGLContext->RecordError( - ErrorCode::InvalidOperation, - MakeUnique("MG_Impl/GLImpl", "MapNamedBufferRange_State", - "Cannot map a buffer object that is already mapped.")); - return nullptr; - } + MG_State::pGLContext->RecordError( + ErrorCode::InvalidOperation, + MakeUnique("MG_Impl/GLImpl", "MapNamedBufferRange_State", + "Cannot map a buffer object that is already mapped.")); + return nullptr; } return bufferObject->AcquireMemoryRange({static_cast(offset), static_cast(offset + length)}, @@ -1366,8 +1357,7 @@ namespace MobileGL::MG_Impl::GLImpl { "Cannot unmap a buffer object that is not mapped.")); return GL_FALSE; } - bufferObject->ReleaseMemory(); - return GL_TRUE; + return bufferObject->ReleaseMemory() ? GL_TRUE : GL_FALSE; } void FlushMappedNamedBufferRange_State(GLuint buffer, GLintptr offset, GLsizeiptr length) { diff --git a/MobileGL/MG_Impl/GLImpl/Getter/GL_Getter.cpp b/MobileGL/MG_Impl/GLImpl/Getter/GL_Getter.cpp index d0fbdb60..5d47e41c 100644 --- a/MobileGL/MG_Impl/GLImpl/Getter/GL_Getter.cpp +++ b/MobileGL/MG_Impl/GLImpl/Getter/GL_Getter.cpp @@ -611,7 +611,8 @@ namespace MobileGL::MG_Impl::GLImpl { MG_State::pEGLContext && MG_State::pEGLContext->GetCurrentContextClientAPI() == EGL_OPENGL_ES_API; const Bool external = images && ClientSideExternalImageExtensionsAllowed() && MG_Impl::EGLImpl::SharedImageYuvAvailable(); - return ClientSideExtensionList(images, external, EsIdentityActive(), esApi); + return ClientSideExtensionList(images, external, EsIdentityActive(), esApi, + MG_Impl::EGLImpl::ResetNotificationAvailable()); } // Robust buffer access as GL 4.5 / KHR_robust_buffer_access_behavior define it: the backend @@ -671,27 +672,24 @@ namespace MobileGL::MG_Impl::GLImpl { // server's, under split), which cannot know about them: // * GL_OES_EGL_image binds the EGL side's dma-buf images, which only a backend with // shared images has (EGLImpl::SharedImagesAvailable); - // * the robustness family - reset notification (glGetGraphicsResetStatus, the contexts' - // EGL reset strategy, GL_CONTEXT_LOST) and the bounded queries (glReadnPixels, - // glGetnUniform*) are this frontend's, whatever the backend. KHR for GL and ES, ARB for - // desktop GL applications that ask for that name, EXT for ES applications that ask for - // that one. Robust buffer ACCESS is a separate promise (GL_CONTEXT_ROBUST_ACCESS) and is - // not implied by any of them. - const Vector& ClientSideExtensionList(Bool images, Bool external, Bool es, Bool esApi) { + // * the robustness family includes reset reporting, which the split client provides. + const Vector& ClientSideExtensionList(Bool images, Bool external, Bool es, Bool esApi, + Bool robustness) { // GL_OES_EGL_image_external(_essl3) only where the server samples YUV images: an // external texture is a 2D texture holding the image converted to RGBA, which needs // the server to hold the YUV image in the first place (EGLImpl::SharedImageYuvAvailable). - static const auto build = [](Bool images, Bool external, Bool es, Bool esApi) { + static const auto build = [](Bool images, Bool external, Bool es, Bool esApi, Bool robustness) { Vector list; if (images) list.push_back("GL_OES_EGL_image"); if (images && external) { list.push_back("GL_OES_EGL_image_external"); list.push_back("GL_OES_EGL_image_external_essl3"); } - // An ES context lists no ARB names (KHR-GLES*.exposed_extensions). - list.push_back("GL_KHR_robustness"); - if (!esApi) list.push_back("GL_ARB_robustness"); - list.push_back("GL_EXT_robustness"); + if (robustness) { + list.push_back("GL_KHR_robustness"); + if (!esApi) list.push_back("GL_ARB_robustness"); + list.push_back("GL_EXT_robustness"); + } // Under the ES identity (EsIdentityActive) the ES names of what desktop GL has in core: // BGRA textures, render targets and read-backs. GL_BGRA_EXT / GL_BGRA8_EXT as internal // formats are taken as RGBA storage (TextureEnumConverter), the byte order being the @@ -710,14 +708,13 @@ namespace MobileGL::MG_Impl::GLImpl { } return list; }; - static const Vector lists[16] = { - build(false, false, false, false), build(false, false, false, true), build(false, false, true, false), - build(false, false, true, true), build(false, true, false, false), build(false, true, false, true), - build(false, true, true, false), build(false, true, true, true), build(true, false, false, false), - build(true, false, false, true), build(true, false, true, false), build(true, false, true, true), - build(true, true, false, false), build(true, true, false, true), build(true, true, true, false), - build(true, true, true, true)}; - return lists[(images ? 8 : 0) + (external ? 4 : 0) + (es ? 2 : 0) + (esApi ? 1 : 0)]; + static const auto lists = [] { + std::array, 32> result; + for (SizeT i = 0; i < result.size(); ++i) + result[i] = build(i & 8, i & 4, i & 2, i & 1, i & 16); + return result; + }(); + return lists[(robustness ? 16 : 0) + (images ? 8 : 0) + (external ? 4 : 0) + (es ? 2 : 0) + (esApi ? 1 : 0)]; } // The external-image names are ES extensions (GL_OES_EGL_image_external_essl3 extends ESSL diff --git a/MobileGL/MG_Impl/GLImpl/Getter/GL_Getter.h b/MobileGL/MG_Impl/GLImpl/Getter/GL_Getter.h index eff54054..1034b89e 100644 --- a/MobileGL/MG_Impl/GLImpl/Getter/GL_Getter.h +++ b/MobileGL/MG_Impl/GLImpl/Getter/GL_Getter.h @@ -50,8 +50,9 @@ namespace MobileGL::MG_Impl::GLImpl { // The extensions the frontend appends to the backend's list - one list behind // glGetString(GL_EXTENSIONS), glGetStringi and GL_NUM_EXTENSIONS - for the given conditions: // shared images, YUV images that may be advertised (ClientSideExternalImageExtensionsAllowed), - // the ES identity, and a context created for the OpenGL ES API. - const Vector& ClientSideExtensionList(Bool images, Bool external, Bool es, Bool esApi); + // the ES identity, a context created for the OpenGL ES API, and supported reset reporting. + const Vector& ClientSideExtensionList(Bool images, Bool external, Bool es, Bool esApi, + Bool robustness); // Whether the current context may list GL_OES_EGL_image_external(_essl3): a context created // for the OpenGL ES API, or any context outside the strict core-profile rules // (MG_State::IsRelaxedSemanticsActive). diff --git a/MobileGL/MG_Impl/Pipe/PipeFill.cpp b/MobileGL/MG_Impl/Pipe/PipeFill.cpp index 032c50e1..466aace5 100644 --- a/MobileGL/MG_Impl/Pipe/PipeFill.cpp +++ b/MobileGL/MG_Impl/Pipe/PipeFill.cpp @@ -1080,17 +1080,13 @@ namespace MobileGL::MG_Pipe { MGPipeRouteResourceFlushRange(record, buffer.MappedData() + offset); } - void MGPipeEmitResourceReadback(BufferObject& buffer) { - // Whole-buffer by contract (BufferObject.h: the op pulls the backend's current - // contents for the WHOLE buffer into the shadow). The split arm's slicing lives in - // the CALLER (BufferObject::SyncGpuWrites): what "whole" costs is decided by the - // event ring's capacity, which this layer does not read. - MGPipeEmitResourceReadbackRange(buffer, 0, buffer.GetSize()); + Bool MGPipeEmitResourceReadback(BufferObject& buffer) { + return MGPipeEmitResourceReadbackRange(buffer, 0, buffer.GetSize()); } - void MGPipeEmitResourceReadbackRange(BufferObject& buffer, SizeT offset, SizeT size) { + Bool MGPipeEmitResourceReadbackRange(BufferObject& buffer, SizeT offset, SizeT size) { const MGPipeHandle handle = ContentHandleFor(buffer, "resource_readback"); - if (MGPipeHandleIsNull(handle)) return; + if (MGPipeHandleIsNull(handle)) return false; MGPReadback record{}; record.Res = handle; record.Offset = offset; @@ -1098,20 +1094,11 @@ namespace MobileGL::MG_Pipe { if (MG_Util::PipeStats::Enabled()) { MG_Util::PipeStats::AddCalls(MG_Util::PipeStats::CallClass::ResourceReadbacks, 1); } - // The answer travels back through MGPipeClientOnBufferWriteback, and the server's - // epoch bump happens AFTER that writeback, never before. - MGPipeRouteResourceReadback(record); + return MGPipeRouteResourceReadback(record); } - // NO UnmapPersistent PRODUCER IN P3a, AND THAT IS DELIBERATE. The catalog has the call - // and wire implemented it, but D-J forbids new behavior and there is nothing to convert: - // BufferBackendOps has seven hooks and none of them is an unmap, and - // PipeResource::ReleasePersistentMap() (BufferObject.cpp, from RedefineStorage) tells the - // backend nothing today - it learns from the Respecify that follows. Emitting - // unmap_persistent here would therefore be a new call to a backend that has never been - // told about a release, so the client emits none and the applier's refusal counter stays - // at 0 for it. The producer lands with the phase that gives the backend an unmap hook. - void* MGPipeEmitMapPersistent(BufferObject& buffer) { + // A storage redefinition ends the donation through the respecify record. + void* MGPipeEmitMapPersistent(BufferObject& buffer, SharedPtr>& lifetime) { const MGPipeHandle handle = ContentHandleFor(buffer, "map_persistent"); if (MGPipeHandleIsNull(handle)) return nullptr; MGPipeResourceTrackerInstance().NoteMapPersistent(); @@ -1123,13 +1110,20 @@ namespace MobileGL::MG_Pipe { if (MG_Util::PipeStats::Enabled()) { MG_Util::PipeStats::AddCalls(MG_Util::PipeStats::CallClass::MapPersistentRoundtrips, 1); } - return MGPipeRouteMapPersistent(BufferHandleOnly(handle), buffer.GetSize(), buffer.MappedData()); + lifetime = MGPipeWatchResidentBuffer(handle); + void* base = MGPipeRouteMapPersistent(BufferHandleOnly(handle), buffer.GetSize(), + buffer.HasDefinedContent() ? buffer.MappedData() : nullptr); + if (base != nullptr && lifetime->load(std::memory_order_acquire)) return base; + MGPipeRevokeResidentBuffer(handle); + lifetime.reset(); + return nullptr; } Bool MGPipeEmitResourceDestroyAndFree(BufferObject& buffer) { MGPipeResourceTracker& tracker = MGPipeResourceTrackerInstance(); const MGPipeHandle handle = tracker.Find(buffer); if (MGPipeHandleIsNull(handle)) return false; + MGPipeRevokeResidentBuffer(handle); // THE LATCHED ANSWER, not the live one (m12): create and destroy are gated at two // different moments, and a buffer constructed while a backend's table was registered // and destroyed after UnregisterBufferBackendOps() would otherwise free its slot with diff --git a/MobileGL/MG_Pipe/PipeApply.cpp b/MobileGL/MG_Pipe/PipeApply.cpp index 5646e068..ae4f1b40 100644 --- a/MobileGL/MG_Pipe/PipeApply.cpp +++ b/MobileGL/MG_Pipe/PipeApply.cpp @@ -1631,6 +1631,7 @@ namespace MobileGL::MG_Pipe { } void MGPipeSetResourceOps(const MGPipeResourceOps* ops) { + if (g_resourceOps != ops) MGPipeRevokeAllResidentBuffers(); g_resourceOps = ops; } const MGPipeResourceOps* MGPipeGetResourceOps() { @@ -2413,9 +2414,9 @@ namespace MobileGL::MG_Pipe { } } - void MGPipeApplyResourceReadback(const MGPReadback& record) { + Bool MGPipeApplyResourceReadback(const MGPReadback& record) { MGPipeResourceRecord* stored = ResolveResource("resource_readback", record.Res); - if (stored == nullptr) return; + if (stored == nullptr) return false; const char* fault = BufferRangeFault(record.Offset, record.Size, stored->Desc.Width); if (fault != nullptr) { @@ -2425,29 +2426,14 @@ namespace MobileGL::MG_Pipe { record.Res.Slot, record.Res.Gen, stored->Desc.GlNameForDiag, fault, static_cast(record.Offset), static_cast(record.Size), stored->Desc.Width); - return; + return false; } - // The readback READS the store this flag describes, so it is one of the calls whose - // answer would change silently the day a producer sets it (D-A4). PinNoLiveHostWrites(*stored, record.Res, "resource_readback"); - // NO SERIAL MOVES. A readback does not mutate the resource; it produces host bytes out - // of it. Bumping here would tell the backend twin its store had changed and buy a - // re-upload of what it had just been read out of. - // - // THE ANSWER TRAVELS BACK THROUGH THE REVERSE CHANNEL, NOT THROUGH THIS FUNCTION, and - // the applier's contribution to that is the ORDER: the hook is called synchronously - // and this returns only once it has finished, so the writeback into the client's - // shadow and the mutation-epoch bump that must follow it have both happened before the - // caller reads. The epoch bump stays server-side and happens AFTER the writeback, - // never before - a rule the reverse channel needs as much as the forward one, because - // a bump that overtook its writeback would leave the draw-clean memo stale behind it. - // - // With no table registered nothing answers, and nothing asks either: the frontend is - // still on the path this call replaces. - if (g_resourceOps != nullptr && g_resourceOps->Readback != nullptr) { - g_resourceOps->Readback(record.Res, record); - } + // Readback changes no resource serial. The synchronous hook delivers the bytes or + // synchronizes shared memory before reporting success. + return g_resourceOps != nullptr && g_resourceOps->Readback != nullptr && + g_resourceOps->Readback(record.Res, record); } void MGPipeApplyResourceDestroy(const MGPHandleOnly& handle) { @@ -2523,19 +2509,7 @@ namespace MobileGL::MG_Pipe { PinNoLiveHostWrites(*record, handle.Handle, "map_persistent"); #if MOBILEGL_BUILD_DISAGGREGATED - // R-6: A SPLIT BUILD RUNS AT TIER T2 AND DECLINES EVERY ACQUISITION, ALWAYS. - // - // The mint returns a raw void* that the client stores as the store's base - // (BufferObject.cpp:238 / :603 / :658). Across a process boundary that address is - // meaningless, and under `inproc` it is WORSE than meaningless: it happens to work, - // so a lane that kept adoption alive would be green for a reason spawn cannot - // reproduce, and persistent-map-push - an exit-gate counter - would be structurally - // zero (PipeStats.cpp says so in as many words). Forcing T2 here rather than at the - // three client call sites is what keeps `mpr` identical between the arms: the - // roundtrip is COUNTED above, unconditionally, because a decline costs the same round - // trip as a mint. - // - // The frontend already tolerates a decline in all three places, and has since P3a. + // The emulated tier has its own shadow and never borrows a backend pointer. if (MG_Config::Transport != MG_Config::TransportMode::Monolith && MG_Remote::Client::AdoptTierIsEmulate()) { return nullptr; } @@ -2554,7 +2528,10 @@ namespace MobileGL::MG_Pipe { // An adopted store has no live host writer to announce: the client writes the store's // own memory and tells the applier nothing (BufferObject::NotePersistentMapStateChanged // sends no falling edge for it), so the rising edge the map published ends here. - if (base != nullptr) record->HasLiveHostWrites = false; + if (base != nullptr) { + record->HasLiveHostWrites = false; + MGPipeNoteResidentMapBase(handle.Handle, base); + } return base; } @@ -2628,7 +2605,10 @@ namespace MobileGL::MG_Pipe { PinNoLiveHostWrites(*record, handle.Handle, "donate_in_process"); if (g_resourceOps == nullptr || g_resourceOps->DonateInProcess == nullptr) return nullptr; void* base = g_resourceOps->DonateInProcess(handle.Handle, record->Desc.Width); - if (base != nullptr) record->HasLiveHostWrites = false; // as map_persistent's mint + if (base != nullptr) { + record->HasLiveHostWrites = false; + MGPipeNoteResidentMapBase(handle.Handle, base); + } return base; } #endif diff --git a/MobileGL/MG_Pipe/PipeApply.h b/MobileGL/MG_Pipe/PipeApply.h index 415ab490..4baf1500 100644 --- a/MobileGL/MG_Pipe/PipeApply.h +++ b/MobileGL/MG_Pipe/PipeApply.h @@ -8,6 +8,7 @@ #pragma once #include +#include #include "MGPipeRenderStateSpans.h" #include "MGPipeTypes.h" @@ -69,7 +70,8 @@ namespace MobileGL::MG_Pipe { // the duration of the call only. void (*SubDataResident)(MGPipeHandle res, const MGPSubData& record, const void* bytes); void (*FlushRange)(MGPipeHandle res, const MGPFlushRange& record, const void* bytes); - void (*Readback)(MGPipeHandle res, const MGPReadback& record); + // True once the requested bytes are visible to the host. + Bool (*Readback)(MGPipeHandle res, const MGPReadback& record); void (*Destroy)(MGPipeHandle res); void* (*MapPersistent)(MGPipeHandle res, Uint64 size, const void* seedBytes); void (*UnmapPersistent)(MGPipeHandle res); @@ -117,6 +119,13 @@ namespace MobileGL::MG_Pipe { void MGPipeSetResourceOps(const MGPipeResourceOps* ops); const MGPipeResourceOps* MGPipeGetResourceOps(); + // Local frontend map lifetimes. Revoke before the owner releases the mapped storage. + SharedPtr> MGPipeWatchResidentBuffer(MGPipeHandle handle); + void MGPipeNoteResidentMapBase(MGPipeHandle handle, const void* base); + Bool MGPipeSeedResidentBuffer(const std::atomic& lifetime, void* base, const void* seed, SizeT size); + void MGPipeRevokeResidentBuffer(MGPipeHandle handle, const void* mappedBase = nullptr); + void MGPipeRevokeAllResidentBuffers(); + // --------------------------------------------------------------------------------- // P3a: the applier's own records (D-G4) // --------------------------------------------------------------------------------- @@ -1168,10 +1177,9 @@ namespace MobileGL::MG_Pipe { // resource_flush_range: record.AccessFlags are the application's REAL mapping flags, not // a normalized subset - the backend reads them per call to choose its upload shape. void MGPipeApplyResourceFlushRange(const MGPFlushRange& record, const void* bytes); - // resource_readback: whole-buffer by contract. The answer travels back through the - // reverse channel, and the writeback happens BEFORE the mutation epoch bumps, never - // after - the ordering is a correctness rule, not a preference. - void MGPipeApplyResourceReadback(const MGPReadback& record); + // Resource readback returns the backend verdict. Any reverse writeback precedes the + // mutation epoch bump and the successful reply. + Bool MGPipeApplyResourceReadback(const MGPReadback& record); // resource_destroy: clears Live and drops the record, then the backend frees its twin. // The CLIENT frees the slot afterwards, in that order, because the allocator forgets the // lifetime id on free and a notice resolved twice finds nothing the second time. diff --git a/MobileGL/MG_Pipe/PipeMutation.h b/MobileGL/MG_Pipe/PipeMutation.h index 65eeb13b..784f0f39 100644 --- a/MobileGL/MG_Pipe/PipeMutation.h +++ b/MobileGL/MG_Pipe/PipeMutation.h @@ -17,6 +17,7 @@ // that one field when it belongs to the verb in flight. It never touches the poison stamp, so a // stamp the fill withheld (negative control B) stays withheld. #include +#include namespace MobileGL::MG_Pipe { // MG_Impl/Pipe/PipeFill.cpp (the client side, the only place that may spell pGLContext). // A no-op unless a context is live, a verb has been filled, and `field` is in that verb @@ -228,15 +229,17 @@ namespace MobileGL::MG_Pipe { SizeT size); void MGPipeEmitResourceFlushRange(MG_State::GLState::BufferObject& buffer, SizeT offset, SizeT size, Uint32 accessFlags); - void MGPipeEmitResourceReadback(MG_State::GLState::BufferObject& buffer); + Bool MGPipeEmitResourceReadback(MG_State::GLState::BufferObject& buffer); // The ranged form, for the split arm's sliced whole-buffer readback: the writeback's // bytes travel INLINE in a SEG_EVENT record, so a buffer larger than the ring can hold // is read back as [offset, offset+size) slices, each its own record. Monolith never // calls it - the direct callback carries a pointer, not a copy. - void MGPipeEmitResourceReadbackRange(MG_State::GLState::BufferObject& buffer, SizeT offset, SizeT size); + Bool MGPipeEmitResourceReadbackRange(MG_State::GLState::BufferObject& buffer, SizeT offset, SizeT size); + [[noreturn]] void MGPipeFailResourceReadback(Uint buffer, SizeT offset, SizeT size, Bool accepted); // Returns the coherent host pointer the resource owner donated, or null for a DECLINE - // which is a real answer. Every call, mint or decline, is one map-persistent roundtrip. - void* MGPipeEmitMapPersistent(MG_State::GLState::BufferObject& buffer); + void* MGPipeEmitMapPersistent(MG_State::GLState::BufferObject& buffer, + SharedPtr>& lifetime); // ================================================================================ // Birth hooks, one per client path MG_State owns diff --git a/MobileGL/MG_Pipe/PipeResidentBuffer.cpp b/MobileGL/MG_Pipe/PipeResidentBuffer.cpp new file mode 100644 index 00000000..75876fa7 --- /dev/null +++ b/MobileGL/MG_Pipe/PipeResidentBuffer.cpp @@ -0,0 +1,79 @@ +// MobileGL - MobileGL/MG_Pipe/PipeResidentBuffer.cpp +// Copyright (c) 2025-2026 MobileGL-Dev +// Licensed under the GNU Lesser General Public License v3.0: +// https://www.gnu.org/licenses/gpl-3.0.txt +// https://www.gnu.org/licenses/lgpl-3.0.txt +// SPDX-License-Identifier: LGPL-3.0-only +// End of Source File Header + +#include "PipeApply.h" + +#include +#include + +namespace MobileGL::MG_Pipe { + namespace { + struct ResidentBufferMap { + WeakPtr> Lifetime; + const void* Base = nullptr; + }; + + struct ResidentBufferMaps { + std::mutex Mutex; + UnorderedMap ByHandle; + }; + + ResidentBufferMaps& ResidentMaps() { + static auto* maps = new ResidentBufferMaps(); + return *maps; + } + + Uint64 ResidentMapKey(MGPipeHandle handle) { + return (static_cast(handle.Gen) << 32) | handle.Slot; + } + } // namespace + + void MGPipeNoteResidentMapBase(MGPipeHandle handle, const void* base) { + auto& maps = ResidentMaps(); + const std::lock_guard lock(maps.Mutex); + const auto it = maps.ByHandle.find(ResidentMapKey(handle)); + if (it != maps.ByHandle.end()) it->second.Base = base; + } + + SharedPtr> MGPipeWatchResidentBuffer(MGPipeHandle handle) { + auto& maps = ResidentMaps(); + const std::lock_guard lock(maps.Mutex); + auto& map = maps.ByHandle[ResidentMapKey(handle)]; + if (auto lifetime = map.Lifetime.lock()) return lifetime; + auto lifetime = MakeShared>(true); + map = {lifetime, nullptr}; + return lifetime; + } + + Bool MGPipeSeedResidentBuffer(const std::atomic& lifetime, void* base, const void* seed, SizeT size) { + // A same-process donation can be revoked by the apply thread as the reply arrives. + const std::lock_guard lock(ResidentMaps().Mutex); + if (!lifetime.load(std::memory_order_acquire)) return false; + if (seed != nullptr) std::memcpy(base, seed, size); + return true; + } + + void MGPipeRevokeResidentBuffer(MGPipeHandle handle, const void* mappedBase) { + auto& maps = ResidentMaps(); + const std::lock_guard lock(maps.Mutex); + const auto it = maps.ByHandle.find(ResidentMapKey(handle)); + if (it == maps.ByHandle.end() || (mappedBase != nullptr && mappedBase != it->second.Base)) return; + if (auto lifetime = it->second.Lifetime.lock()) lifetime->store(false, std::memory_order_release); + maps.ByHandle.erase(it); + } + + void MGPipeRevokeAllResidentBuffers() { + auto& maps = ResidentMaps(); + const std::lock_guard lock(maps.Mutex); + for (const auto& entry : maps.ByHandle) { + if (auto lifetime = entry.second.Lifetime.lock()) lifetime->store(false, std::memory_order_release); + } + maps.ByHandle.clear(); + } + +} // namespace MobileGL::MG_Pipe diff --git a/MobileGL/MG_Pipe/PipeRoute.cpp b/MobileGL/MG_Pipe/PipeRoute.cpp index 88d672de..2d61c2ae 100644 --- a/MobileGL/MG_Pipe/PipeRoute.cpp +++ b/MobileGL/MG_Pipe/PipeRoute.cpp @@ -16,6 +16,8 @@ // static-archive link can drop this object), so no MGP_* thunk needs a null check. #include "PipeRoute.h" +#include "PipeMutation.h" +#include "PipeSessionFail.h" #include #include @@ -67,6 +69,19 @@ namespace MobileGL::MG_Pipe { return g_monolithEscapes; } + void MGPipeFailResourceReadback(Uint buffer, SizeT offset, SizeT size, Bool accepted) { + if (!accepted) { + MGPipeRecordFail(MGFatalFamily::ReadbackDeclined, + "MGPipe: Fatal{ReadbackDeclined, \"buffer-writeback\"} - buffer %u " + "could not read back %zu bytes at offset %zu", + buffer, size, offset); + } + MGPipeRecordFail(MGFatalFamily::UnimplementedWritebackWait, + "MGPipe: Fatal{UnimplementedWritebackWait} - readback for buffer %u " + "succeeded without making its GPU writes visible to the host", + buffer); + } + MGPReplySlot MGPipeMintReplySlot() { // 1-based, for ReplySlot.h's reason: "Seq is 1-based; 0 means 'no record'". A zero id // must stay unmintable so an un-posted mailbox is distinguishable from a posted one. @@ -260,14 +275,9 @@ namespace MobileGL::MG_Pipe { std::abort(); } - // resource_readback carries kReplySlot but its answer is COMPLETION, not a value: the - // bytes go server -> client through SEG_EVENT's OnBufferWriteback (CONTRACT-P5 table 1 - // row 22), and the split decoder posts exactly kStatusOk with a zero-length payload. - // The monolith arm says the same thing, so the two arms hand their caller the same - // answer rather than one of them handing it nothing. void Mono_ResourceReadback(const MGPReadback* payload, MGPReplySlot* reply) { - MGPipeApplyResourceReadback(*payload); - MGPipePostReply(*reply, 0, 0); + const Bool accepted = MGPipeApplyResourceReadback(*payload); + MGPipePostReply(*reply, accepted ? 0 : 1, accepted ? 1u : 0u); } // The three acceptance rows that DO fit a generated signature. Each posts the diff --git a/MobileGL/MG_Pipe/PipeRoute.h b/MobileGL/MG_Pipe/PipeRoute.h index 0fbb15db..265cf4c9 100644 --- a/MobileGL/MG_Pipe/PipeRoute.h +++ b/MobileGL/MG_Pipe/PipeRoute.h @@ -211,13 +211,10 @@ namespace MobileGL::MG_Pipe { inline void MGPipeRouteResourceFlushRange(const MGPFlushRange& record, const void* bytes) { gMGPipeRouteEscapes.ResourceFlushRange(&record, bytes); } - inline void MGPipeRouteResourceReadback(const MGPReadback& record) { + inline Bool MGPipeRouteResourceReadback(const MGPReadback& record) { MGPReplySlot reply = MGPipeMintReplySlot(); MGP_ResourceReadback(&record, &reply); - // The answer is COMPLETION, not a value: the bytes come back through SEG_EVENT's - // OnBufferWriteback (table 1 row 22). It is still TAKEN, because an untaken mailbox - // entry is what the next row's ReplyOverrun Fatal is looking for. - (void)MGPipeTakeReplyBool(reply, "resource_readback"); + return MGPipeTakeReplyBool(reply, "resource_readback"); } // ---- render state ------------------------------------------------------------------ diff --git a/MobileGL/MG_Remote/Client/BackendObject_Remote.cpp b/MobileGL/MG_Remote/Client/BackendObject_Remote.cpp index bd8900ff..042dc26d 100644 --- a/MobileGL/MG_Remote/Client/BackendObject_Remote.cpp +++ b/MobileGL/MG_Remote/Client/BackendObject_Remote.cpp @@ -201,7 +201,7 @@ namespace MobileGL::MG_Remote::Client { // P12 (D1): unless the window is the SERVER's - then there is no handle of ours to tell. if (MG_Config::ServerOwnedWindowSurfaces()) return CreateServerOwnedWindowSurface(surface, handle); Server::ServerSetWindowHandle(handle); - if (!Server::ServerCreateEGLWindowSurface(surface, handle)) return false; + if (!Server::ServerCreateEGLWindowSurface(surface, handle, EGLRegistry().RegistrationDisplay())) return false; // The server's surface init published the default framebuffer's shape as a // surface-changed EVENT (P5c ev): DirectGLES' depth/stencil format, Magma's // swapchain extent. Apply it NOW - the RPC's return is a moment the apply thread @@ -281,9 +281,13 @@ namespace MobileGL::MG_Remote::Client { return CreatePbufferOnServer(surface, width, height, /*standIn=*/false); } - Bool BackendObject_Remote::CreateEGLSurfacelessStandIn(EGLSurface surface, EGLint width, EGLint height) { - if (!CreatePbufferOnServer(surface, width, height, /*standIn=*/true)) return false; + Bool BackendObject_Remote::CreateEGLSurfacelessStandIn(EGLDisplay display, EGLSurface surface, EGLint width, + EGLint height) { const auto lock = EGLRegistry().Lock(); + const auto previousDisplay = EGLRegistry().SetRegistrationDisplay(display); + const Bool created = CreatePbufferOnServer(surface, width, height, /*standIn=*/true); + EGLRegistry().SetRegistrationDisplay(previousDisplay); + if (!created) return false; m_standInSurfaces.insert(surface); return true; } @@ -292,7 +296,8 @@ namespace MobileGL::MG_Remote::Client { WaitForApplyBeforeEglForwarder("CreateEGLPbufferSurface"); Server::SurfaceRefusalCode refusal = Server::SurfaceRefusalCode::None; if (!Server::ServerCreateEGLPbufferSurface(surface, width, height, &refusal, - standIn ? Server::kPbufferFlagSurfacelessStandIn : 0u)) { + standIn ? Server::kPbufferFlagSurfacelessStandIn : 0u, + EGLRegistry().RegistrationDisplay())) { if (refusal == Server::SurfaceRefusalCode::SurfaceModeMismatch) { // P12 (D4), named on THIS side too: the server logged its half. MGLOG_E("MG_Remote client: SurfaceModeMismatch - eglCreatePbufferSurface (%dx%d) in a session " @@ -322,8 +327,8 @@ namespace MobileGL::MG_Remote::Client { Bool BackendObject_Remote::CreateServerOwnedWindowSurface(EGLSurface surface, const MG_Backend::WindowHandle& handle) { - const Server::ServerOwnedWindowReply reply = - Server::ServerCreateServerOwnedWindowSurface(surface, handle.Width, handle.Height); + const Server::ServerOwnedWindowReply reply = Server::ServerCreateServerOwnedWindowSurface( + surface, handle.Width, handle.Height, EGLRegistry().RegistrationDisplay()); if (!reply.ok) { // P12: FAILS BY NAME ON THIS SIDE TOO. The server logged its reason; the reply's refusal // code is what lets this line say the same thing instead of "ok=false". @@ -498,10 +503,8 @@ namespace MobileGL::MG_Remote::Client { m_sessionSharedImages.clear(); // The display the application initialized is initialized on the new server too: its // surfaces and contexts are created against it from here on. - if (EGLRegistry().DisplayInitialized()) { - EGLint major = 0; - EGLint minor = 0; - if (!Server::ServerInitializeEGLDisplay(EGLRegistry().Display(), &major, &minor)) { + for (const EGLDisplay display : EGLRegistry().InitializedDisplays()) { + if (!Server::ServerInitializeEGLDisplay(display, nullptr, nullptr)) { MGLOG_E("MG_Remote client: the fresh session's server did not initialize the display; " "surfaces and contexts on it will fail"); } @@ -522,7 +525,8 @@ namespace MobileGL::MG_Remote::Client { const char* kind = "pbuffer"; if (state.Kind == MG_Backend::EGLSurfaceRegistry::SurfaceKind::Pbuffer) { const Uint32 flags = m_standInSurfaces.count(surface) != 0 ? Server::kPbufferFlagSurfacelessStandIn : 0u; - recreated = Server::ServerCreateEGLPbufferSurface(surface, state.Width, state.Height, nullptr, flags); + recreated = Server::ServerCreateEGLPbufferSurface(surface, state.Width, state.Height, nullptr, flags, + state.Display); } else if (ClientSession::IsServerOwnedWindowSurface(surface)) { kind = "server-owned window"; // The window is asked for what the application asked for (its own size for a surface @@ -531,7 +535,7 @@ namespace MobileGL::MG_Remote::Client { const Uint32 wantWidth = requested != m_serverOwnedRequests.end() ? requested->second.first : 0u; const Uint32 wantHeight = requested != m_serverOwnedRequests.end() ? requested->second.second : 0u; const Server::ServerOwnedWindowReply reply = - Server::ServerCreateServerOwnedWindowSurface(surface, wantWidth, wantHeight); + Server::ServerCreateServerOwnedWindowSurface(surface, wantWidth, wantHeight, state.Display); recreated = reply.ok; if (recreated && reply.width != 0 && reply.height != 0) { if (MG_State::pEGLContext) { @@ -544,7 +548,7 @@ namespace MobileGL::MG_Remote::Client { } else { kind = "window"; Server::ServerSetWindowHandle(state.Window); - recreated = Server::ServerCreateEGLWindowSurface(surface, state.Window); + recreated = Server::ServerCreateEGLWindowSurface(surface, state.Window, state.Display); } if (!recreated) { MGLOG_E("MG_Remote client: the %s surface %p (%dx%d) of a lost session could not be re-created on " diff --git a/MobileGL/MG_Remote/Client/BackendObject_Remote.h b/MobileGL/MG_Remote/Client/BackendObject_Remote.h index c5b4d545..677994e0 100644 --- a/MobileGL/MG_Remote/Client/BackendObject_Remote.h +++ b/MobileGL/MG_Remote/Client/BackendObject_Remote.h @@ -87,7 +87,7 @@ namespace MobileGL::MG_Remote::Client { // EGL_KHR_surfaceless_context's hidden pbuffer (EGLImpl's SurfacelessStandIn): an ordinary // pbuffer on this side, created on the server with kPbufferFlagSurfacelessStandIn so it // takes no surface mode there, and re-created the same way on a fresh session. - Bool CreateEGLSurfacelessStandIn(EGLSurface surface, EGLint width, EGLint height); + Bool CreateEGLSurfacelessStandIn(EGLDisplay display, EGLSurface surface, EGLint width, EGLint height); protected: Bool InitPbufferSurface(EGLint width, EGLint height) override; diff --git a/MobileGL/MG_Remote/Client/ClientSession.cpp b/MobileGL/MG_Remote/Client/ClientSession.cpp index c07b79b2..90cbe337 100644 --- a/MobileGL/MG_Remote/Client/ClientSession.cpp +++ b/MobileGL/MG_Remote/Client/ClientSession.cpp @@ -34,6 +34,7 @@ #include #include #include +#include #include #include #include @@ -1938,6 +1939,7 @@ namespace MobileGL::MG_Remote::Client { // process with no session at all - and by then the rings are gone, so the applier a // monolith adapter runs is a defined no-op rather than a use-after-free. UninstallClientWireTables(); + if (m_started) MG_Pipe::MGPipeRevokeAllResidentBuffers(); if (!m_started) { m_controlInbox.reset(); if (m_socketTransport) m_socketTransport->Shutdown(); @@ -2027,8 +2029,7 @@ namespace MobileGL::MG_Remote::Client { // 4. and ONLY NOW may anything an emitter owns be released: a var-tail still // referenced by an unapplied record is a use-after-free the join is what prevents. LogMemory("teardown"); - // P11 B2: the T0 arm's proof for this session, and the client's references to its stores - // (the server's imports held their own and are gone with the server's backend). + // The server is done with its imports. Release the client's stores. ResetT0(true); LogWireLedger(); Transport::LinkMetricsEnd(); @@ -2366,11 +2367,8 @@ namespace MobileGL::MG_Remote::Client { Transport::LinkMetricsReplyApplied(replyMetricStart); - // THE REVERSE CHANNEL IS DRAINED HERE, and here is the only place it can be: under the - // barrier this is the one instant at which the apply thread is known not to be inside - // the applier, and MGPipeClientOnGpuWritten / OnBufferWriteback write frontend objects. - // It is what gives AwaitBufferWriteback something to have waited FOR: b1's third state - // clears when the writeback lands, and the writeback lands on this ring. + // The barrier makes it safe to apply events that update frontend objects. Drain their + // writebacks before returning the readback verdict to the caller. DrainEventRing(*m_events); if (!ownsReplySlot) { @@ -3076,12 +3074,9 @@ namespace MobileGL::MG_Remote::Client { return nullptr; } - // T0 IN ONE PROCESS (kCapAdoptInProcess): the OK answer carries the address of the server's own - // mapping of the store, which becomes this buffer's persistent map - the memory both sides - // already share, as monolith's donation is. The server has drained the GPU's use of the store - // before answering and applies nothing of this client's until this call returns, so the - // shadow is copied in here, by the side that owns it. + // The apply thread drains GPU use before donating its mapping. The client seeds that mapping. void* ClientSession::AdoptPersistentInProcess(const MG_Pipe::MGPHandleOnly& handle, Uint64 size, const void* seed) { + const auto lifetime = MG_Pipe::MGPipeWatchResidentBuffer(handle.Handle); Uint64 base = 0; Uint64 returned = 0; Int32 status = Wire::ReplySink::kStatusError; @@ -3102,7 +3097,10 @@ namespace MobileGL::MG_Remote::Client { "in-process T0 store without the store's address"); } void* ptr = reinterpret_cast(static_cast(base)); - if (seed != nullptr) std::memcpy(ptr, seed, static_cast(size)); + if (!MG_Pipe::MGPipeSeedResidentBuffer(*lifetime, ptr, seed, static_cast(size))) { + ++m_t0Declined; + return nullptr; + } ++m_t0Imported; m_t0Bytes += size; // No AHardwareBuffer to hold: the entry only marks the handle T0 (its release is a no-op). diff --git a/MobileGL/MG_Remote/Client/GpuWritePending.cpp b/MobileGL/MG_Remote/Client/GpuWritePending.cpp index cd71b148..6083e4c9 100644 --- a/MobileGL/MG_Remote/Client/GpuWritePending.cpp +++ b/MobileGL/MG_Remote/Client/GpuWritePending.cpp @@ -7,26 +7,14 @@ // End of Source File Header #include "GpuWritePending.h" -#include #include "ClientSession.h" // RunsAsTheServerRole: declared beside the wire emitters that need the same predicate, so this // TU does not pull a server header in for it. #include "WireTables.h" -#include -#include -#include -#include -#include -#include - -#include - namespace MobileGL::MG_Remote::Client { - using MG_State::GLState::BufferObject; - SizeT BufferWritebackSliceBytes() { ClientSession* session = ClientSession::Active(); if (session == nullptr) return 0; @@ -77,46 +65,4 @@ namespace MobileGL::MG_Remote::Client { return session == nullptr ? 0 : session->LastPublishedSeq(); } - void AwaitBufferWriteback(BufferObject& buffer) { - // THE WAIT IS THE BARRIER'S WAIT (R-3). The reply-slot id IS the record's seq, so - // "appliedSeq reached my readback" and "my answer is back" are one condition, and - // ClientSession::EmitAndWait is what pays for it. With no session - a build-split lane - // running monolith, and every unit case - the emission WAS the application, - // synchronously, so the writeback has already landed and there is nothing to wait for. - // Spelling that as "return" rather than as a loop is deliberate: a loop here would be - // a hang in exactly that configuration, which is the configuration every gate lane - // runs. - if (ClientSession::Active() == nullptr) return; - - // AND THE OTHER ARM IS A NAMED FATAL, NOT AN EMPTY BODY. A session exists, so the - // apply side is no longer synchronous, and if the flag is still set the shadow this - // caller is about to read is STALE - which is the whole failure the third state was - // introduced to stop. An empty body here would make that failure silent and would let - // s1/c1 land a session without noticing that nobody ever wrote the wait; a stub that - // aborts by name is the house shape for exactly this (EmitTables.cpp's - // UnmigratedVerbFatal), and it is what gives the hole a red spelling before the - // transport arrives. - if (!buffer.HasOutstandingGpuWrite()) return; - // P9 F1 (CONTRACT-P9.md §4): THE DEVICE WENT AWAY WITH THE WRITE STILL OWED. A lost device - // DECLINES every record, so the readback that was to bring the GPU's bytes back was never - // sent - and the shadow the caller is about to read holds whatever the buffer held BEFORE - // the write (for a pack-buffer read, the bytes before the pixels). Returning it would be the - // one outcome the reverse channel exists to prevent: stale bytes that look like a - // successful read. It is the reply form's ReadbackDeclined, arriving one call later. - if (ClientSession::DeviceLost()) { - SessionFail(MGFatalFamily::ReadbackDeclined, - "MGPipe: Fatal{ReadbackDeclined, \"buffer-writeback\"} - buffer %u " - "still owes a GPU write (a pack-buffer read or a shader store) and the device is " - "lost, so its readback was declined; its shadow holds the bytes from before the " - "write and is not returned as the GPU's", - buffer.GetExternalIndex()); - } - SessionFail(MGFatalFamily::UnimplementedWritebackWait, - "MGPipe: Fatal{UnimplementedWritebackWait} - a ClientSession is active and buffer %u " - "still has an outstanding GPU write after its readback was emitted. The wait is " - "ClientSession::EmitAndWait's (R-3: the reply slot id IS the record seq); P5 package " - "b1 landed the third state and s1/c1 own the wait itself.", - buffer.GetExternalIndex()); - } - } // namespace MobileGL::MG_Remote::Client diff --git a/MobileGL/MG_Remote/Client/GpuWritePending.h b/MobileGL/MG_Remote/Client/GpuWritePending.h index db457b5b..cc5f8669 100644 --- a/MobileGL/MG_Remote/Client/GpuWritePending.h +++ b/MobileGL/MG_Remote/Client/GpuWritePending.h @@ -6,10 +6,7 @@ // SPDX-License-Identifier: LGPL-3.0-only // End of Source File Header -// P13 W5: the session's half of the client GPU-write set - the writeback wait and the two -// clamps that depend on a live session's rings. The set itself (the producers, the walks, -// the row predicates) is MG_Record's (MG_Impl/Pipe/Verb/GpuWriteSet.h): the record arm -// keeps it in a library without a transport too. +// Client-side ordering and size limits that depend on a live transport session. #pragma once #include @@ -17,21 +14,8 @@ #include #include -namespace MobileGL::MG_State::GLState { - class BufferObject; - struct ImageTextureBinding; -} // namespace MobileGL::MG_State::GLState - namespace MobileGL::MG_Remote::Client { - // ---- SyncGpuWrites' third state (CONTRACT-P5.md section 3) ----------------------- - - // Blocks until this buffer's OnBufferWriteback has landed. With no session - a build-split - // lane running monolith, and every unit case - the emission was synchronous and the answer - // is already in, so this returns at once; that is why it is a call rather than a loop the - // caller writes, because the loop would be a hang in exactly that configuration. - void AwaitBufferWriteback(MG_State::GLState::BufferObject& buffer); - // The order a GPU-write mark is stamped with: the last command seq this session // published, so the work the mark stands for is in a LATER record and only a writeback // the server produced after that record can retire it (BufferObject::WritebackFromBackend). diff --git a/MobileGL/MG_Remote/Client/WireTables.cpp b/MobileGL/MG_Remote/Client/WireTables.cpp index a451d021..431bd4e8 100644 --- a/MobileGL/MG_Remote/Client/WireTables.cpp +++ b/MobileGL/MG_Remote/Client/WireTables.cpp @@ -266,23 +266,20 @@ namespace MobileGL::MG_Remote::Client { "comparator owns the capability cross-check)"); } - // resource_readback. kReplySlot, and the answer is COMPLETION only: the bytes travel - // server -> client in SEG_EVENT through OnBufferWriteback, because the destination is - // the client's shadow and its size is the resource's, not a slot's (CONTRACT-P5 table 1 - // row 22). So the reply buffer is deliberately {nullptr, 0} and the wait is what makes - // the writeback already drained by the time this returns. + // The slot carries the readback verdict. EmitAndWait drains any separately delivered + // writeback before it returns. void Wire_ResourceReadback(const MG_Pipe::MGPReadback* payload, MG_Pipe::MGPReplySlot* reply) { if (RunsAsTheServerRole()) { MG_Pipe::MGPipeMonolithContext().ResourceReadback(payload, reply); return; } ClientSession& session = RequireSession("ResourceReadback"); - Int32 status = 0; + Int32 status = Wire::ReplySink::kStatusError; const Uint64 seq = session.EmitAndWait(MGPWireOp::ResourceReadback, payload, sizeof(*payload), nullptr, 0, nullptr, 0, &status); // Cancellation has no wire ordinal; retain the caller's nonzero local ticket. if (seq != Wire::kInvalidSeq) reply->Id = seq; - MG_Pipe::MGPipePostReply(*reply, status, 0); + MG_Pipe::MGPipePostReply(*reply, status, status == Wire::ReplySink::kStatusOk ? 1u : 0u); ++g_emitted; } diff --git a/MobileGL/MG_Remote/Server/ServerLoop.cpp b/MobileGL/MG_Remote/Server/ServerLoop.cpp index fd930fe5..960fd85c 100644 --- a/MobileGL/MG_Remote/Server/ServerLoop.cpp +++ b/MobileGL/MG_Remote/Server/ServerLoop.cpp @@ -1675,7 +1675,8 @@ namespace MobileGL::MG_Remote::Server { frame.ok = false; return MOBILEGL_ERR_PROTOCOL_MISMATCH; // PH-1 (3): latched } - frame.ok = backend->CreateEGLWindowSurface(HandleFromToken(frame.surface), window); + frame.ok = backend->CreateEGLWindowSurfaceOnDisplay(HandleFromToken(frame.display), + HandleFromToken(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(); @@ -1708,8 +1709,9 @@ namespace MobileGL::MG_Remote::Server { SessionSurfaceModeName(m_surfaceMode)); return MOBILEGL_ERR_INVALID_ARGUMENT; } - frame.ok = - backend->CreateEGLPbufferSurface(HandleFromToken(frame.surface), frame.width, frame.height); + frame.ok = backend->CreateEGLPbufferSurfaceOnDisplay(HandleFromToken(frame.display), + HandleFromToken(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). @@ -2075,7 +2077,8 @@ namespace MobileGL::MG_Remote::Server { const ServerOwnedSurfaceHook surfaceHook = g_serverOwnedSurfaceHook.load(std::memory_order_acquire); const EGLSurface ownedSurface = HandleFromToken(frame.surface); frame.ok = surfaceHook != nullptr ? surfaceHook(backend, ownedSurface, window) - : backend->CreateEGLWindowSurface(ownedSurface, window); + : backend->CreateEGLWindowSurfaceOnDisplay( + HandleFromToken(frame.display), ownedSurface, window); if (!frame.ok) { MGLOG_E("MG_Remote server: the backend could not create a window surface on the server window %p " "(%ux%u) for ServerOwned seq %llu", @@ -2317,9 +2320,10 @@ namespace MobileGL::MG_Remote::Server { return rc == MOBILEGL_OK && frame.ok; } - Bool ServerCreateEGLWindowSurface(EGLSurface surface, const MG_Backend::WindowHandle& handle) { + Bool ServerCreateEGLWindowSurface(EGLSurface surface, const MG_Backend::WindowHandle& handle, EGLDisplay display) { SurfaceControlFrame frame; frame.kind = SurfaceControlOp::CreateWindowSurface; + frame.display = TokenFromHandle(display); frame.surface = TokenFromHandle(surface); PackWindowHandle(frame, handle); const MobileGLResult rc = ServerLoopInstance().RunSurfaceControlFrame(frame); @@ -2337,9 +2341,10 @@ namespace MobileGL::MG_Remote::Server { } Bool ServerCreateEGLPbufferSurface(EGLSurface surface, EGLint width, EGLint height, SurfaceRefusalCode* refusal, - Uint32 flags) { + Uint32 flags, EGLDisplay display) { SurfaceControlFrame frame; frame.kind = SurfaceControlOp::CreatePbufferSurface; + frame.display = TokenFromHandle(display); frame.surface = TokenFromHandle(surface); frame.width = width; frame.height = height; @@ -2349,12 +2354,14 @@ namespace MobileGL::MG_Remote::Server { return rc == MOBILEGL_OK && frame.ok; } - ServerOwnedWindowReply ServerCreateServerOwnedWindowSurface(EGLSurface surface, Uint32 width, Uint32 height) { + ServerOwnedWindowReply ServerCreateServerOwnedWindowSurface(EGLSurface surface, Uint32 width, Uint32 height, + EGLDisplay display) { // P12 (D1/D2): ONE frame, and no SetWindowHandle in front of it - the window is the // server's, so there is nothing of the client's to name. The frame-local tag is what the // codec turns into WindowKind::ServerOwned with token 0. SurfaceControlFrame frame; frame.kind = SurfaceControlOp::CreateWindowSurface; + frame.display = TokenFromHandle(display); frame.surface = TokenFromHandle(surface); frame.windowBackend = kServerOwnedWindowBackend; frame.nativeToken = 0; diff --git a/MobileGL/MG_Remote/Server/ServerLoop.h b/MobileGL/MG_Remote/Server/ServerLoop.h index cf63fe3d..7afcbb60 100644 --- a/MobileGL/MG_Remote/Server/ServerLoop.h +++ b/MobileGL/MG_Remote/Server/ServerLoop.h @@ -546,13 +546,15 @@ namespace MobileGL::MG_Remote::Server { // because the client needs only these calls. SwapBuffers and InitWindowSurface are // inproc-only frame kinds with no wire op: present travels as a record. Bool ServerInitializeEGLDisplay(EGLDisplay dpy, EGLint* major, EGLint* minor); - Bool ServerCreateEGLWindowSurface(EGLSurface surface, const MG_Backend::WindowHandle& handle); + Bool ServerCreateEGLWindowSurface(EGLSurface surface, const MG_Backend::WindowHandle& handle, + EGLDisplay display = EGL_NO_DISPLAY); Bool ServerResizeEGLWindowSurface(EGLSurface surface, Uint32 width, Uint32 height); // P12: `refusal`, when given, receives the server's named refusal (SurfaceModeMismatch for a // pbuffer in an on-screen session), None otherwise. `flags`: kPbufferFlagSurfacelessStandIn // for the hidden pbuffer of a surfaceless make-current, which takes no surface mode. Bool ServerCreateEGLPbufferSurface(EGLSurface surface, EGLint width, EGLint height, - SurfaceRefusalCode* refusal = nullptr, Uint32 flags = 0); + SurfaceRefusalCode* refusal = nullptr, Uint32 flags = 0, + EGLDisplay display = EGL_NO_DISPLAY); // P12 (on-screen server window), D1/D2. CreateWindowSurface on the SERVER's window: one frame, // WindowKind::ServerOwned with nativeToken 0 on the wire, no SetWindowHandle. `width`/`height` // is the size the client asked for (0/0 = the server window's own size); the reply carries the @@ -564,7 +566,8 @@ namespace MobileGL::MG_Remote::Server { Uint32 width = 0; Uint32 height = 0; }; - ServerOwnedWindowReply ServerCreateServerOwnedWindowSurface(EGLSurface surface, Uint32 width, Uint32 height); + ServerOwnedWindowReply ServerCreateServerOwnedWindowSurface(EGLSurface surface, Uint32 width, Uint32 height, + EGLDisplay display = EGL_NO_DISPLAY); // P12 review fix: ResizeWindowSurface for a surface created on the server's window. The server // resizes its WINDOW (a geometry request) and replies with the window's real extent. ServerOwnedWindowReply ServerResizeServerOwnedWindowSurface(EGLSurface surface, Uint32 width, Uint32 height); diff --git a/MobileGL/MG_Remote/Wire/PipeWireCodec.cpp b/MobileGL/MG_Remote/Wire/PipeWireCodec.cpp index 0b05d5a7..e35403bd 100644 --- a/MobileGL/MG_Remote/Wire/PipeWireCodec.cpp +++ b/MobileGL/MG_Remote/Wire/PipeWireCodec.cpp @@ -2281,13 +2281,12 @@ namespace MobileGL::MG_Remote::Wire { MGPipeApplyResourceFlushRange(*static_cast(payload), nullptr); return true; - case MGPWireOp::ResourceReadback: - // The BYTES go back in SEG_EVENT through OnBufferWriteback (contract table 1 row - // 22) - the destination is the client's shadow and the size is the resource's, not - // a fixed slot's - so the reply slot carries COMPLETION only. - MGPipeApplyResourceReadback(*static_cast(payload)); - PostReply(op, seq, ReplySink::kStatusOk, nullptr, 0); + case MGPWireOp::ResourceReadback: { + // The reply carries the outcome. Any bytes travel through OnBufferWriteback. + const Bool accepted = MGPipeApplyResourceReadback(*static_cast(payload)); + PostReply(op, seq, accepted ? ReplySink::kStatusOk : ReplySink::kStatusDeclined, nullptr, 0); return true; + } // P5b (CONTRACT-P5B.md): the two transfer verbs with no applier reach the sink like the // class-B five. resource_copy_region = glCopyImageSubData (i1), generate_mipmap = diff --git a/MobileGL/MG_State/EGLState/Core.cpp b/MobileGL/MG_State/EGLState/Core.cpp index b975feb5..12768382 100644 --- a/MobileGL/MG_State/EGLState/Core.cpp +++ b/MobileGL/MG_State/EGLState/Core.cpp @@ -367,25 +367,28 @@ namespace MobileGL { } void EGLContext::ReleaseDisplayObjects(EGLDisplayHandle display) { - Vector removedContexts; - for (auto contextIt = m_contexts.begin(); contextIt != m_contexts.end();) { - if (contextIt->second.Display == display) { - removedContexts.push_back(contextIt->first); - contextIt = m_contexts.erase(contextIt); + for (auto it = m_contexts.begin(); it != m_contexts.end();) { + if (it->second.Display != display) { + ++it; + } else if (m_contextOwners.find(it->first) != m_contextOwners.end()) { + it->second.DestroyPending = true; + ++it; } else { - ++contextIt; + m_reapedContexts.push_back(ReapedContext{it->first, it->second.ClientContextToken, + it->second.ShareGroupToken, + Move(it->second.GLStateObject)}); + it = m_contexts.erase(it); } } - for (const auto context : removedContexts) { - m_contextOwners.erase(context); - } - - for (auto surfaceIt = m_surfaces.begin(); surfaceIt != m_surfaces.end();) { - if (surfaceIt->second.Display == display) { - surfaceIt = m_surfaces.erase(surfaceIt); + for (auto it = m_surfaces.begin(); it != m_surfaces.end();) { + if (it->second.Display != display) { + ++it; + } else if (IsSurfaceCurrentUnlocked(it->first)) { + it->second.DestroyPending = true; + ++it; } else { - ++surfaceIt; + it = m_surfaces.erase(it); } } @@ -413,28 +416,7 @@ namespace MobileGL { ++imageIt; } } - - for (auto threadIt = m_threadCurrents.begin(); threadIt != m_threadCurrents.end();) { - if (threadIt->second.Display == display) { - if (threadIt->second.Context != nullptr) { - auto ownerIt = m_contextOwners.find(threadIt->second.Context); - if (ownerIt != m_contextOwners.end() && ownerIt->second == threadIt->first) { - m_contextOwners.erase(ownerIt); - } - } - // Only the CALLING thread's TLS is reachable from here - another - // thread's current is dropped from the table, and its own next EGL - // call re-establishes the binding. - if (threadIt->first == CurrentThreadKey() && threadIt->second.RestoreThreadGLState) { - pGLContext = Move(threadIt->second.RestoreThreadGLState); - } - threadIt = m_threadCurrents.erase(threadIt); - } else { - ++threadIt; - } - } } - EGLContext::EGLDisplayHandle EGLContext::GetDisplay(NativeDisplayType nativeDisplay) { const std::lock_guard lock(m_mutex); return GetOrCreateDisplay(ToNativeKey(nativeDisplay), EGL_NONE); @@ -746,7 +728,7 @@ namespace MobileGL { EGLContext::EGLContextHandle EGLContext::CreateContext(EGLDisplayHandle display, EGLConfigHandle config, EGLContextHandle shareCtx, const EGLint* attribList, - Bool deferGLState) { + Bool deferGLState, Bool allowResetNotification) { const std::lock_guard lock(m_mutex); const auto* displayObject = TryGetDisplay(display); if (!displayObject) { @@ -786,6 +768,10 @@ namespace MobileGL { resetStrategy = *value; } } + if (resetStrategy == EGL_LOSE_CONTEXT_ON_RESET && !allowResetNotification) { + SetError(EGL_BAD_MATCH); + return nullptr; + } if (shareCtx != nullptr) { const auto* shared = TryGetContext(shareCtx); if (shared != nullptr && shared->ResetNotificationStrategy != resetStrategy) { @@ -1493,7 +1479,7 @@ namespace MobileGL { } Bool EGLContext::MakeCurrent(EGLDisplayHandle display, EGLSurfaceHandle draw, EGLSurfaceHandle read, - EGLContextHandle context) { + EGLContextHandle context, Bool validateOnly) { const std::lock_guard lock(m_mutex); const Bool releaseCurrentRequest = draw == EGL_NO_SURFACE && read == EGL_NO_SURFACE && context == nullptr; @@ -1505,12 +1491,8 @@ namespace MobileGL { SetError(EGL_BAD_DISPLAY); return false; } - if (!displayObject->Initialized) { - SetError(EGL_NOT_INITIALIZED); - return false; - } } - ReleaseThreadUnlocked(threadKey); + if (!validateOnly) ReleaseThreadUnlocked(threadKey); return true; } @@ -1559,6 +1541,8 @@ namespace MobileGL { } } + if (validateOnly) return true; + // P14 S3: whatever this thread's GL state was before the first EGL context was // bound to it is what a later release goes back to. SharedPtr restoreThreadGLState; @@ -1593,7 +1577,10 @@ namespace MobileGL { void EGLContext::ReleaseThread() { const std::lock_guard lock(m_mutex); - ReleaseThreadUnlocked(CurrentThreadKey()); + const auto thread = CurrentThreadKey(); + ReleaseThreadUnlocked(thread); + m_threadErrors.erase(thread); + m_threadBoundAPI.erase(thread); } EGLContext::EGLContextHandle EGLContext::GetCurrentContext() const { diff --git a/MobileGL/MG_State/EGLState/Core.h b/MobileGL/MG_State/EGLState/Core.h index 3fcac5d6..0de6549e 100644 --- a/MobileGL/MG_State/EGLState/Core.h +++ b/MobileGL/MG_State/EGLState/Core.h @@ -65,7 +65,7 @@ namespace MobileGL { // first (the server must know the context before anything is filed under it). EGLContextHandle CreateContext(EGLDisplayHandle display, EGLConfigHandle config, EGLContextHandle shareCtx, const EGLint* attribList, - Bool deferGLState = false); + Bool deferGLState = false, Bool allowResetNotification = true); Bool BuildContextGLState(EGLContextHandle context); // EGL 1.5 3.7.2: a context current to some thread is not destroyed until it is no // longer current. Such a destroy answers true with `*deferred` set: the handle is @@ -154,7 +154,7 @@ namespace MobileGL { // Current Bool MakeCurrent(EGLDisplayHandle display, EGLSurfaceHandle draw, EGLSurfaceHandle read, - EGLContextHandle context); + EGLContextHandle context, Bool validateOnly = false); void ReleaseThread(); EGLContextHandle GetCurrentContext() const; EGLDisplayHandle GetCurrentDisplay() const; diff --git a/MobileGL/MG_State/GLState/BufferState/BufferObject.cpp b/MobileGL/MG_State/GLState/BufferState/BufferObject.cpp index 88f1630e..20ce46d7 100644 --- a/MobileGL/MG_State/GLState/BufferState/BufferObject.cpp +++ b/MobileGL/MG_State/GLState/BufferState/BufferObject.cpp @@ -10,6 +10,7 @@ #include +#include #include #include #include @@ -183,6 +184,29 @@ namespace MobileGL::MG_State::GLState { NotifySubData(offset, size); } + void BufferObject::CheckResidentStorage() const { + if (!m_resource.IsResidentMapRevoked()) return; + + // Adoption dropped the shadow. Lost GPU bytes cannot seed the new store. + // A staging map owns separate storage and can still land its writes on unmap. + m_resource.ResizeShadow(m_size); + m_resource.ReleasePersistentMap(); + m_mappingLost = m_isMapped && !m_ownsStagingData; + m_gpuWritePending = false; + m_hasDefinedContent = false; + } + + Bool BufferObject::TryAdoptResidentStorage(Bool trackedMap) { + if (m_size == 0 || !MG_Pipe::MGPipeResourceSubsystemEnabled()) return false; + SharedPtr> lifetime; + void* base = MG_Pipe::MGPipeEmitMapPersistent(*this, lifetime); + if (base == nullptr) return false; + // Unprotect the shadow before adoption frees its pages. + if (trackedMap) MG_Record::PersistentMapTracker::Instance().Forget(*this); + m_resource.AdoptPersistentMap(base, std::move(lifetime)); + return true; + } + // A (re)definition of the store is about to write `size` bytes through Bytes(). // Sizing the shadow is all that takes for a shadow-backed buffer. A buffer whose // bytes were adopted into backend GPU memory has to give the adoption back first, @@ -204,7 +228,7 @@ namespace MobileGL::MG_State::GLState { // then does the busy-tracking and the conditional orphan it has always done, and the // next binding that wants GPU residency takes a fresh mapping of the new store. void BufferObject::RedefineStorage(SizeT size) { - if (m_resource.IsGpuResident()) { + if (m_resource.IsGpuResident() || m_resource.IsResidentMapRevoked()) { m_resource.ReleasePersistentMap(); // Whatever a shader or a capture wrote is in the store being replaced, so // there is nothing left to reconcile - and leaving the flag set would make @@ -285,12 +309,11 @@ namespace MobileGL::MG_State::GLState { if (m_size < kLargeBufferAdoptBytes) return; if (m_resource.IsGpuResident()) return; if (m_isMapped) return; - if (MG_Pipe::MGPipeResourceSubsystemEnabled()) { - if (void* base = MG_Pipe::MGPipeEmitMapPersistent(*this)) m_resource.AdoptPersistentMap(base); - } + TryAdoptResidentStorage(); } void BufferObject::UploadData(DataPtr data, SizeT atOffset) { + CheckResidentStorage(); MOBILEGL_ASSERT(atOffset + data.size <= m_size, "UploadData out of bounds: atOffset (%zu) + data.size (%zu) > m_size (%zu)", atOffset, data.size, m_size); @@ -304,11 +327,13 @@ namespace MobileGL::MG_State::GLState { m_usage = usage; } - void BufferObject::ReleaseMemory(Bool landStagedWrites) { - if (!m_isMapped) return; + Bool BufferObject::ReleaseMemory(Bool landStagedWrites) { + if (!m_isMapped) return true; + if (landStagedWrites) CheckResidentStorage(); + const Bool valid = !m_mappingLost; - if (landStagedWrites && (m_mappingAccess & BufferMappingAccessBit::Write)) { // if we wrote to the buffer - if (!(m_mappingAccess & BufferMappingAccessBit::FlushExplicit)) { // if we didn't flush explicitly + if (valid && landStagedWrites && (m_mappingAccess & BufferMappingAccessBit::Write)) { + if (!(m_mappingAccess & BufferMappingAccessBit::FlushExplicit)) { const SizeT mappedLength = m_mappedRange.end - m_mappedRange.start; if (m_resource.IsGpuResident()) { // A persistent map of an adopted store wrote straight into coherent @@ -347,13 +372,16 @@ namespace MobileGL::MG_State::GLState { m_mappedRange = {0, 0}; m_stagingBias = 0; m_ownsStagingData = false; + m_mappingLost = false; // AFTER the reset, so the predicate reads the post-unmap state, and after the landing // above, so the last bytes of a write map are already on the wire when the record // that says "no live writer" goes out behind them. NotePersistentMapStateChanged(); + return valid; } void BufferObject::FlushMemoryRange(SizeT offset, SizeT length) { + if (HasLostMapping()) return; MOBILEGL_ASSERT(m_isMapped, "Buffer must be mapped to flush memory range."); MOBILEGL_ASSERT((m_mappingAccess & BufferMappingAccessBit::FlushExplicit), "Buffer must be mapped with FlushExplicit access to flush memory range."); @@ -411,7 +439,7 @@ namespace MobileGL::MG_State::GLState { MG_Record::PersistentMapTracker::Instance().PushBlocksFor(*this); return; } - if (!m_isMapped) return; + if (!m_isMapped || HasLostMapping()) return; // GPU-resident: the app already wrote directly into coherent GPU memory. This is // the whole point of the persistent-map path - the per-draw whole-buffer re-upload // that used to run here is gone. @@ -482,8 +510,8 @@ namespace MobileGL::MG_State::GLState { // regression one layer down, and the rising-edge record is what breaks the cycle: the // server learns a host writer is live BEFORE the first probe, answers dirty while the // map lives, and the ensure - and with it the push - runs every draw. - const Bool live = - m_isMapped && (m_mappingAccess & BufferMappingAccessBit::Write) && !m_resource.IsGpuResident(); + const Bool live = m_isMapped && (m_mappingAccess & BufferMappingAccessBit::Write) && + !m_resource.IsGpuResident() && !HasLostMapping(); if (live == m_publishedLiveHostWrites) return; m_publishedLiveHostWrites = live; // AN ADOPTION ENDS THE STATE WITHOUT A RECORD. The one falling edge a resident store @@ -511,31 +539,17 @@ namespace MobileGL::MG_State::GLState { } void BufferObject::WritebackFromBackend(DataPtr data, SizeT atOffset, Uint64 producedAtSeq) { + CheckResidentStorage(); MOBILEGL_ASSERT(atOffset + data.size <= m_size, "WritebackFromBackend out of bounds: atOffset (%zu) + data.size (%zu) > m_size (%zu)", atOffset, data.size, m_size); Memcpy(m_resource.Bytes() + atOffset, data.data, data.size); ++m_changeSerial; MGP_NOTE_AGGREGATE(BufferChange); - // THE THIRD STATE'S ONLY EXIT. In a split build SyncGpuWrites does NOT clear the - // flag before emitting, because between the emission and the answer the shadow is - // stale and the object has no way to say so; the answer landing here is what makes it - // current, so the answer is what clears. Gated: in monolith SyncGpuWrites has already - // cleared by the time the applier calls back, and a second clear here would also - // retire a GPU write announced by something other than a readback - a ReadPixels into - // a pack PBO writes back through this same function. - // - // P13 W4a: monolith's record arm refreshes an aliased store through this function too - // (Managers.cpp RefreshAliasedStoreFromGpu), and a whole-store landing there is exactly as - // current as one under split. - // - // ORDERED, NOT MERELY WHOLE. A writeback the client never asked for - the end of a - // transform feedback capture - is drained whenever the client next waits, which under - // run-ahead can be after a later dispatch has marked this same buffer written again. - // Those bytes are the capture's, not the dispatch's, so they may not retire the newer - // mark: only a writeback produced by a record after the one the mark was taken for can - // (the readback SyncGpuWrites emits always is). 0 is the synchronous answer - monolith - // and every no-session case - which has nothing to be ordered against. + // A whole-store writeback clears the pending mark when it covers the latest GPU write. + // A delayed capture may have produced bytes before a later dispatch marked this buffer + // again, so only a newer producedAtSeq can retire the mark. Zero denotes a synchronous + // writeback with no sequence to compare. if (atOffset == 0 && data.size >= m_size && (producedAtSeq == 0 || producedAtSeq > m_gpuWriteMarkSeq)) { m_gpuWritePending = false; } @@ -550,11 +564,13 @@ namespace MobileGL::MG_State::GLState { } void BufferObject::MarkGpuWrittenInChannelOrder() { + CheckResidentStorage(); m_hasDefinedContent = true; m_gpuWritePending = true; } void BufferObject::MarkGpuWrittenAfter(Uint64 orderSeq) { + CheckResidentStorage(); m_hasDefinedContent = true; m_gpuWritePending = true; // Assigned, not maxed: within a session the seq only grows, and a new session (or @@ -564,90 +580,45 @@ namespace MobileGL::MG_State::GLState { } void BufferObject::SyncGpuWrites() { + CheckResidentStorage(); if (!m_gpuWritePending) return; + if (m_size == 0 || !MG_Pipe::MGPipeResourceSubsystemEnabled()) { + m_gpuWritePending = false; + return; + } + + // A resident store shares the GPU mapping, so a successful reply alone makes it + // current. An ordinary whole-buffer readback clears the mark when its bytes land. + const Bool resident = m_resource.IsGpuResident(); #if MOBILEGL_BUILD_DISAGGREGATED - // THE THIRD STATE (CONTRACT-P5.md section 3, ARCHITECTURE.md §13.1). This function has - // only ever been able to say "pending" or "not pending", and clearing first is safe - // in monolith because the readback is synchronous INSIDE the applier: the caller sees - // the reconciled shadow on return. Under a transport there is a third state - the - // readback was emitted and the answer has not arrived - which the flag cannot express, - // and clearing optimistically leaves the shadow silently stale for the object's life. - // - // So: emit, then BLOCK until OnBufferWriteback lands, and let the writeback do the - // clearing. ARCHITECTURE.md §13.1 lists "the first CPU read of a GPU-write-pending - // buffer" among the UNAVOIDABLE blocking points, because monolith already glFinish()es - // here; under R-1's verb barrier the block is nearly free, since the client is already - // waiting for appliedSeq to reach the record it just emitted. - // - // NO NARROWING (MGPipeClientOnGpuWritten's rangeCount == 1 assertion stays): this - // phase only gives the client a conservative set, and a zero-range announcement stays - // illegal until P8/P9 make it mean "fully narrowed - nothing is dirty". - if (MG_Config::Transport != MG_Config::TransportMode::Monolith) { - if (m_size != 0 && MG_Pipe::MGPipeResourceSubsystemEnabled() && m_resource.IsGpuResident()) { - // P11 B2: A T0 STORE IS READ WHERE IT IS. Under split a store is resident only - // when T0 adopted it - its pages ARE the client's AHardwareBuffer - so no bytes - // need to come back: the readback's round trip is "done, no bytes". The server - // lands every resident write it queued (GPU-ordered), waits for its GPU, answers, - // and only then does this read the held mapping (monolith's adopted-store readback, - // Managers.cpp's persistentMapped arm, by the same rule). The flag clears here - // because no writeback will arrive to clear it (WritebackFromBackend). - MG_Pipe::MGPipeEmitResourceReadback(*this); + if (MG_Config::Transport != MG_Config::TransportMode::Monolith && !resident) { + const SizeT sliceBytes = MG_Remote::Client::BufferWritebackSliceBytes(); + if (sliceBytes != 0 && m_size > sliceBytes) { + // Each slice is written back and drained before the next, keeping each payload + // within the event ring budget. The mark covers the whole store. + for (SizeT offset = 0; offset < m_size;) { + const SizeT size = std::min(sliceBytes, m_size - offset); + if (!MG_Pipe::MGPipeEmitResourceReadbackRange(*this, offset, size)) { + MG_Pipe::MGPipeFailResourceReadback(GetExternalIndex(), offset, size, false); + } + offset += size; + } m_gpuWritePending = false; return; } - if (m_size != 0 && MG_Pipe::MGPipeResourceSubsystemEnabled()) { - const SizeT sliceBytes = MG_Remote::Client::BufferWritebackSliceBytes(); - if (sliceBytes != 0 && m_size > sliceBytes) { - // The writeback's bytes travel INLINE in a SEG_EVENT record (P5c ev), - // and one record must fit the ring (MaxRecordBytes == capacity/2) - a - // whole-buffer request for a buffer larger than that aborts the server - // on Fatal{EventRingOverflow}. Slice the request instead: every slice - // round-trips its own barrier + drain before the next is emitted, so - // the ring holds at most one slice's bytes at a time, and the in-order - // channel makes the last slice's landing imply every earlier one. - for (SizeT off = 0; off < m_size; off += sliceBytes) { - const SizeT left = m_size - off; - MG_Pipe::MGPipeEmitResourceReadbackRange(*this, off, left < sliceBytes ? left : sliceBytes); - } - // No single writeback covered the whole buffer, so - // WritebackFromBackend's clear (above) never fired - but every slice - // has landed by here, which is exactly what the flag-clearing there - // says. Clearing by hand is what keeps AwaitBufferWriteback's - // third-state Fatal from misfiring on a sliced readback. - m_gpuWritePending = false; - } else { - MG_Pipe::MGPipeEmitResourceReadback(*this); - } - // The wait is the barrier's wait: the reply slot id IS the record's seq, so - // "my answer is back" and "appliedSeq reached me" are one condition. With no - // session (a build-split lane running monolith, and every unit case) the - // emission was synchronous and the writeback has already cleared the flag. - MG_Remote::Client::AwaitBufferWriteback(*this); - } - // A buffer with no readback route - no size, or a backend that registered no - // resource ops - can never catch up, and retrying on every subsequent read would - // only repeat the same no-op. That is the ONE case the monolith clear covers that - // the writeback cannot, so it is spelled out here rather than inherited. - if (m_gpuWritePending && !MG_Record::BufferWritebackIsReachable(*this)) { - m_gpuWritePending = false; - } - return; } #endif - // Cleared unconditionally: without a readback op the shadow can never catch up, - // and retrying on every subsequent read would only repeat the same no-op. - m_gpuWritePending = false; - if (m_size != 0 && MG_Pipe::MGPipeResourceSubsystemEnabled()) { - // The answer comes back through the reverse channel's OnBufferWriteback, which - // resolves this handle to this object and writes the shadow before the server - // bumps its mutation epoch. In monolith the whole sequence is synchronous inside - // the applier, so the caller sees the reconciled shadow on return exactly as it - // does today. - MG_Pipe::MGPipeEmitResourceReadback(*this); + if (!MG_Pipe::MGPipeEmitResourceReadback(*this)) { + MG_Pipe::MGPipeFailResourceReadback(GetExternalIndex(), 0, m_size, false); + } + if (resident) m_gpuWritePending = false; + if (m_gpuWritePending) { + MG_Pipe::MGPipeFailResourceReadback(GetExternalIndex(), 0, m_size, true); } } void BufferObject::UploadSubData(DataPtr data, SizeT atOffset) { + CheckResidentStorage(); // GL 4.6 core 6.5 forbids only the OVERLAPPING write: a glBufferSubData that stays // clear of a non-persistent mapping is legal, and the frontend lets it through. MOBILEGL_ASSERT(!m_isMapped || (m_mappingAccess & BufferMappingAccessBit::Persistent) || @@ -722,9 +693,10 @@ namespace MobileGL::MG_State::GLState { MOBILEGL_ASSERT(atOffset <= m_size && size <= m_size - atOffset, "FillSubData out of bounds: atOffset (%zu) + size (%zu) > m_size (%zu)", atOffset, size, m_size); - MOBILEGL_ASSERT(!m_isMapped || (m_mappingAccess & BufferMappingAccessBit::Persistent), - "Cannot fill data while buffer is non-persistently mapped."); if (size == 0) return; + MOBILEGL_ASSERT(!m_isMapped || (m_mappingAccess & BufferMappingAccessBit::Persistent) || + atOffset >= m_mappedRange.end || atOffset + size <= m_mappedRange.start, + "Fill range overlaps a non-persistently mapped range."); // An adopted store takes the same landing as UploadSubData: the in-place write // below would tear in-flight readers of the mapping. The pattern is expanded @@ -765,6 +737,8 @@ namespace MobileGL::MG_State::GLState { } void BufferObject::DownloadSubData(void* dst, SizeT atOffset, SizeT size) const { + CheckResidentStorage(); + if (size == 0) return; MOBILEGL_ASSERT(atOffset + size <= m_size, "DownloadSubData out of bounds: atOffset (%zu) + size (%zu) > m_size (%zu)", atOffset, size, m_size); @@ -783,7 +757,9 @@ namespace MobileGL::MG_State::GLState { "Destination buffer copy out of bounds: dstOffset (%zu) + size (%zu) > m_size (%zu)", dstOffset, size, m_size); + if (size == 0) return; src->SyncGpuWrites(); + CheckResidentStorage(); // An adopted DESTINATION takes the same landing as UploadSubData: the in-place // write below would tear in-flight readers of the mapping, and pending recorded // GPU writes to it must retire before the copy lands or they would execute on @@ -828,6 +804,7 @@ namespace MobileGL::MG_State::GLState { } Bool BufferObject::EnsureGpuResidentStorage() { + CheckResidentStorage(); if (m_resource.IsGpuResident()) { return true; } @@ -841,16 +818,11 @@ namespace MobileGL::MG_State::GLState { if (m_isMapped) { return false; } - if (m_size != 0 && MG_Pipe::MGPipeResourceSubsystemEnabled()) { - void* pushedBase = MG_Pipe::MGPipeEmitMapPersistent(*this); - if (pushedBase == nullptr) return false; - m_resource.AdoptPersistentMap(pushedBase); - return true; - } - return false; + return TryAdoptResidentStorage(); } void* BufferObject::AcquireMemoryRange(Range1D range, Flags access) { + CheckResidentStorage(); MOBILEGL_ASSERT(range.end <= m_size && range.start <= range.end, "AcquireMemoryRange out of bounds: range (%zu, %zu) exceeds m_size (%zu)", range.start, range.end, m_size); @@ -891,22 +863,8 @@ namespace MobileGL::MG_State::GLState { // shadow when the backend declines (returns null). Only attempted once - the // storage is immutable and outlives unmap/remap. if (!m_resource.IsGpuResident() && (access & BufferMappingAccessBit::Write) && - !(access & BufferMappingAccessBit::FlushExplicit) && MG_Pipe::MGPipeResourceSubsystemEnabled()) { - if (void* pushedBase = MG_Pipe::MGPipeEmitMapPersistent(*this)) { - // P11 B2 made this reachable (a T0 adoption), so the tracker lets go of the - // shadow range WHILE THE SHADOW IS STILL OURS: AdoptPersistentMap frees it, and - // an untrack after that would mprotect pages the buffer no longer owns. - MG_Record::PersistentMapTracker::Instance().Forget(*this); - m_resource.AdoptPersistentMap(pushedBase); - // An adoption takes the buffer OUT of the push set and out of the - // live-host-writes state: the application now writes coherent GPU memory - // and there is nothing to ship. Under R-6 this is unreachable; it is here - // because the comment below used to claim the adoption path withdrew the - // entry and nothing did, which would have left the published bit true - // across an adoption until unmap (latent for P11). - NotePersistentMapStateChanged(); - } - return m_resource.Bytes() + range.start; + !(access & BufferMappingAccessBit::FlushExplicit) && TryAdoptResidentStorage(true)) { + NotePersistentMapStateChanged(); } return m_resource.Bytes() + range.start; } @@ -937,6 +895,7 @@ namespace MobileGL::MG_State::GLState { #if MOBILEGL_BUILD_DISAGGREGATED RefuseLegacyBufferArmFromApplyThread("MappedData"); #endif + CheckResidentStorage(); return m_resource.Bytes(); } @@ -952,6 +911,10 @@ namespace MobileGL::MG_State::GLState { return m_resource.IsGpuResident(); } + Bool BufferObject::HasLostMapping() const { + return m_mappingLost || (m_isMapped && !m_ownsStagingData && m_resource.IsResidentMapRevoked()); + } + SizeT BufferObject::GetSize() const { return m_size; } @@ -977,7 +940,7 @@ namespace MobileGL::MG_State::GLState { // answer on this side; the frontend flag is client memory. RefuseLegacyBufferArmFromApplyThread("HasDefinedContent"); #endif - return m_hasDefinedContent; + return m_hasDefinedContent && !m_resource.IsResidentMapRevoked(); } Bool BufferObject::IsMapped() const { @@ -992,7 +955,7 @@ namespace MobileGL::MG_State::GLState { } void* BufferObject::GetMappedPointer() const { - if (!m_isMapped) return nullptr; + if (!m_isMapped || HasLostMapping()) return nullptr; if (m_mappingAccess & BufferMappingAccessBit::Persistent) { // GPU-resident maps return the coherent GPU pointer; shadow-backed persistent // maps return the shadow. m_resource.Bytes() resolves both. diff --git a/MobileGL/MG_State/GLState/BufferState/BufferObject.h b/MobileGL/MG_State/GLState/BufferState/BufferObject.h index e5284cb8..b13edb06 100644 --- a/MobileGL/MG_State/GLState/BufferState/BufferObject.h +++ b/MobileGL/MG_State/GLState/BufferState/BufferObject.h @@ -104,7 +104,7 @@ namespace MobileGL { // the caller is about to replace that store (a respecification) and passes // false - landing them there would copy a whole mapped range into storage // being handed back on the next line. - void ReleaseMemory(Bool landStagedWrites = true); + Bool ReleaseMemory(Bool landStagedWrites = true); void FlushMemoryRange(SizeT offset, SizeT length); // Pushes the persistently-mapped write range to the backend; called by @@ -213,6 +213,7 @@ namespace MobileGL { // coherent persistent map): reads/writes hit GPU memory and no per-write // backend transfer op is dispatched. Bool IsBackendPersistentMapped() const; + Bool HasLostMapping() const; Flags GetMappingAccess() const; GLbitfield GetStorageFlags() const; Uint GetExternalIndex() const; @@ -236,6 +237,10 @@ namespace MobileGL { Bool HasDefinedContent() const; private: + // Switch a revoked borrowed mapping to newly allocated, undefined shadow storage. + void CheckResidentStorage() const; + Bool TryAdoptResidentStorage(Bool trackedMap = false); + // Sizes the store for a (re)definition, renewing an adopted GPU-resident // mapping across it. See the definition for why the renewal is not optional. void RedefineStorage(SizeT size); @@ -267,18 +272,19 @@ namespace MobileGL { BufferUsage m_usage = BufferUsage::StaticDraw; // Owns the buffer's bytes (CPU shadow or backend persistent GPU map) and // the backend GPU resource. All data access goes through it. - PipeResource m_resource; + mutable PipeResource m_resource; + mutable Bool m_mappingLost = false; Bool m_isMapped; Flags m_mappingAccess; Bool m_isImmutableStorage = false; GLbitfield m_storageFlags = 0; Uint64 m_changeSerial = 0; // See HasDefinedContent(). - Bool m_hasDefinedContent = true; + mutable Bool m_hasDefinedContent = true; // Set by MarkGpuWritten, cleared by SyncGpuWrites once the shadow is refreshed - // and, in a split build, cleared by WritebackFromBackend instead, because there // the answer arrives later than the request. See SyncGpuWrites' definition. - Bool m_gpuWritePending = false; + mutable Bool m_gpuWritePending = false; // The command seq the latest GPU-write mark was taken after. A monotonic record // seq, never a count of writebacks: only a writeback produced by a LATER record // can retire the mark (WritebackFromBackend). diff --git a/MobileGL/MG_State/GLState/BufferState/PersistentMapTracker.cpp b/MobileGL/MG_State/GLState/BufferState/PersistentMapTracker.cpp index 63b08189..f7442593 100644 --- a/MobileGL/MG_State/GLState/BufferState/PersistentMapTracker.cpp +++ b/MobileGL/MG_State/GLState/BufferState/PersistentMapTracker.cpp @@ -752,7 +752,7 @@ namespace MobileGL::MG_Record { // predicate exists to have. Item 1 made that guard two loads instead, which is cheaper than // the reorder would have been and costs nothing in meaning. Bool PersistentMapTracker::IsLivePersistentMap(const BufferObject& buffer) { - if (!buffer.IsMapped()) return false; + if (!buffer.IsMapped() || buffer.HasLostMapping()) return false; // GPU-resident: the application already wrote into coherent GPU memory and there is // nothing to ship. At tier T2 this arm is unreachable - MapPersistent declines - but // the predicate must still read the chain, not the tier: a build that reaches T0/T1 diff --git a/MobileGL/MG_State/GLState/BufferState/PipeResource.h b/MobileGL/MG_State/GLState/BufferState/PipeResource.h index bd72a7da..fce1ce61 100644 --- a/MobileGL/MG_State/GLState/BufferState/PipeResource.h +++ b/MobileGL/MG_State/GLState/BufferState/PipeResource.h @@ -9,8 +9,10 @@ #pragma once #include #include +#include #include #include +#include #include namespace MobileGL::MG_State::GLState { @@ -120,21 +122,24 @@ namespace MobileGL::MG_State::GLState { // alias Data = Vector used for the shadow.) class PipeResource { public: - Uint8* Bytes() { return m_gpuMapped != nullptr ? static_cast(m_gpuMapped) : m_shadow->data(); } + Uint8* Bytes() { return const_cast(std::as_const(*this).Bytes()); } const Uint8* Bytes() const { - return m_gpuMapped != nullptr ? static_cast(m_gpuMapped) : m_shadow->data(); + if (IsGpuResident()) return static_cast(m_gpuMapped); + if (m_shadow->size() != m_shadowSize) ResizeShadow(m_shadowSize); + return m_shadow->data(); } - // True once the buffer's bytes have been adopted into backend GPU memory. - Bool IsGpuResident() const { return m_gpuMapped != nullptr; } + Bool IsGpuResident() const { return m_gpuMapped != nullptr && !IsResidentMapRevoked(); } + Bool IsResidentMapRevoked() const { return m_mapLifetime && !m_mapLifetime->load(std::memory_order_acquire); } // Shadow (re)allocation for non-persistent storage (glBufferData / // glBufferStorage before any persistent map). Mirrors the previous // power-of-two reserve + exact resize of the old m_dataPtr. - void ResizeShadow(SizeT size) { + void ResizeShadow(SizeT size) const { const SizeT reserved = std::bit_ceil(size == 0 ? SizeT{1} : size); m_shadow->reserve(reserved); m_shadow->resize(size); + m_shadowSize = size; // RECORDED HERE, NOT INFERRED FROM capacity(). `reserved` is the count this // call asked the allocator for, so ShadowAllocationBytesFor(reserved) is the // block the allocator handed back whenever this reserve reallocated - and when @@ -168,8 +173,9 @@ namespace MobileGL::MG_State::GLState { // mapped base as the source of truth and drop the CPU shadow. The caller // must have already seeded the GPU memory from the shadow (via the backend // AcquirePersistentMap op) before calling this. - void AdoptPersistentMap(void* mappedBase) { + void AdoptPersistentMap(void* mappedBase, SharedPtr> lifetime) { m_gpuMapped = mappedBase; + m_mapLifetime = std::move(lifetime); m_shadow->clear(); m_shadow->shrink_to_fit(); // The block is gone with the shrink; the next ResizeShadow records the next one. @@ -183,7 +189,10 @@ namespace MobileGL::MG_State::GLState { // "unmap": a persistent map the application holds outlives every unmap by // definition, and the calls that could redefine such a buffer's store are // errors the frontend refuses before reaching here. - void ReleasePersistentMap() { m_gpuMapped = nullptr; } + void ReleasePersistentMap() { + m_gpuMapped = nullptr; + m_mapLifetime.reset(); + } private: // MapAlignedData, not Data: a read-only glMapBuffer hands the application this very @@ -191,7 +200,9 @@ namespace MobileGL::MG_State::GLState { // GL_MIN_MAP_BUFFER_ALIGNMENT grid for either to satisfy ARB_map_buffer_alignment. SharedPtr m_shadow = MakeShared(); void* m_gpuMapped = nullptr; - // See ShadowAllocationBytes. Split-only so the pull build's layout does not move (G1). - SizeT m_shadowExtent = 0; + SharedPtr> m_mapLifetime; + // Kept separately from the shadow vector, which is empty while the store is borrowed. + mutable SizeT m_shadowExtent = 0; + mutable SizeT m_shadowSize = 0; }; } // namespace MobileGL::MG_State::GLState diff --git a/MobileGL/MG_Test/Backend/BackendObjectEglStateTest.cpp b/MobileGL/MG_Test/Backend/BackendObjectEglStateTest.cpp index eb594105..66959b19 100644 --- a/MobileGL/MG_Test/Backend/BackendObjectEglStateTest.cpp +++ b/MobileGL/MG_Test/Backend/BackendObjectEglStateTest.cpp @@ -19,7 +19,12 @@ #include +#include #include +#include +#include +#include +#include #include #include @@ -257,6 +262,9 @@ namespace { s_live.compare_exchange_strong(self, nullptr); } + void ReleaseEGLContext(Uint64 token) override { ReleasedContextToken = token; } + + Uint64 ReleasedContextToken = 0; Uint64 HookCount() const { return m_hookCalls.load(); } Uint64 PresentCount() const { return m_presents.load(); } Uint64 SwapIntervalCount() const { return m_swapIntervals.load(); } @@ -803,26 +811,27 @@ TEST_F(BackendObjectEglDisplay, NullVersionPointersAreTolerated) { EXPECT_EQ(major, 1); } -// A second display replaces the first and nothing else; the first is then refused. -TEST_F(BackendObjectEglDisplay, ASecondDisplayReplacesTheFirst) { +TEST_F(BackendObjectEglDisplay, InitializedDisplaysKeepTheirSurfacesAndBindings) { ASSERT_TRUE(Init()); ASSERT_TRUE(BoundWindow(kS1, kWin1)); - b->ClearCalls(); - EXPECT_TRUE(b->InitializeEGLDisplay(kDpy2, nullptr, nullptr)); - EXPECT_TRUE(b->DisplayInitialized()); - EXPECT_EQ(b->DisplayNow(), kDpy2); - EXPECT_EQ(b->ActiveSurface(), kS1); - EXPECT_TRUE(b->CapsProbed()); - EXPECT_TRUE(RecordIs(b->Record(kS1), WindowRecord(kWin1, 640, 480, true))); + ASSERT_TRUE(b->InitializeEGLDisplay(kDpy2, nullptr, nullptr)); + ASSERT_TRUE(b->CreateEGLWindowSurfaceOnDisplay(kDpy2, kS2, kWin2)); + EXPECT_TRUE(Bind(kS1)); + EXPECT_TRUE(Swap(kS1)); + EXPECT_FALSE(b->MakeEGLCurrent(kDpy2, kS1, kS1, kCtx)); + EXPECT_FALSE(Bind(kS2)); EXPECT_TRUE(BoundTo(b->CurrentHere(), kDpy, kS1, kCtx)); - EXPECT_FALSE(b->MakeEGLCurrent(kDpy, kS1, kS1, kCtx)); - EXPECT_FALSE(b->SwapEGLBuffers(kDpy, kS1)); - EXPECT_TRUE(Trace().empty()); - // The new display works with the surfaces registered under the old one. - EXPECT_TRUE(b->MakeEGLCurrent(kDpy2, kS1, kS1, kCtx)); - EXPECT_TRUE(BoundTo(b->CurrentHere(), kDpy2, kS1, kCtx)); - EXPECT_TRUE(b->SwapEGLBuffers(kDpy2, kS1)); - EXPECT_EQ(Trace(), (Vector{"Present"})); + + Worker second; + ASSERT_TRUE(second.Run([&] { return b->MakeEGLCurrent(kDpy2, kS2, kS2, kCtx2); })); + b->ReleaseEGLDisplay(kDpy2); + EXPECT_TRUE(Swap(kS1)); + EXPECT_TRUE(BoundTo(b->CurrentHere(), kDpy, kS1, kCtx)); + ASSERT_TRUE(b->Record(kS2)); + EXPECT_TRUE(b->Record(kS2)->DestroyPending); + EXPECT_TRUE(ReleaseOn(second)); + EXPECT_FALSE(b->Record(kS2)); + EXPECT_FALSE(b->MakeEGLCurrent(kDpy2, kS2, kS2, kCtx2)); } TEST_F(BackendObjectEglDisplay, ReinitializingTheSameDisplayChangesNothing) { @@ -1657,36 +1666,31 @@ TEST_F(BackendObjectEglMakeCurrent, ARefusedBindKeepsThePreviousBinding) { EXPECT_TRUE(BoundTo(b->CurrentHere(), kDpy, kS1, kCtx)); } -// A quirk, pinned as it is: rebinding a pending surface current only on this thread -// succeeds, but the bind's own release destroys it: no active surface, an entry naming a dropped -// surface, and the next swap of it fails. -TEST_F(BackendObjectEglMakeCurrent, RebindingAPendingSurfaceDestroysItButSucceeds) { +TEST_F(BackendObjectEglMakeCurrent, RefusesRebindingAPendingSurfaceUntilRelease) { ASSERT_TRUE(Init()); ASSERT_TRUE(BoundWindow(kS1, kWin1)); b->ReleaseEGLSurface(kS1); b->ClearCalls(); - EXPECT_TRUE(Bind(kS1)); - EXPECT_EQ(Trace(), (Vector{"Released(s1)", "Forgotten(s1)"})); - EXPECT_FALSE(b->HasActiveSurface()); - EXPECT_FALSE(b->Record(kS1).has_value()); + EXPECT_FALSE(Bind(kS1)); + EXPECT_TRUE(Trace().empty()); + EXPECT_TRUE(b->HasActiveSurface()); EXPECT_TRUE(BoundTo(b->CurrentHere(), kDpy, kS1, kCtx)); - b->ClearCalls(); - EXPECT_FALSE(Swap(kS1)); - EXPECT_TRUE(TraceWithTableReads().empty()); - EXPECT_EQ(b->PresentCount(), 0u); + ASSERT_TRUE(b->Record(kS1)); + EXPECT_TRUE(b->Record(kS1)->DestroyPending); + EXPECT_TRUE(Release()); + EXPECT_EQ(Trace(), (Vector{"Released(s1)", "Forgotten(s1)"})); + EXPECT_FALSE(b->Record(kS1)); } -// A quirk: the same when the pending surface is not active - it is activated first. -TEST_F(BackendObjectEglMakeCurrent, RebindingAPendingInactiveSurfaceActivatesThenDestroysIt) { +TEST_F(BackendObjectEglMakeCurrent, RejectsAPendingInactiveSurfaceBeforeActivation) { ASSERT_TRUE(Init()); ASSERT_TRUE(BoundWindow(kS1, kWin1)); ASSERT_TRUE(b->CreateEGLWindowSurface(kS2, kWin2)); b->ReleaseEGLSurface(kS1); b->ClearCalls(); - EXPECT_TRUE(Bind(kS1)); - EXPECT_EQ(Trace(), (Vector{"InitWindow(s1)", "InitCaps", "Released(s1)", "Forgotten(s1)"})); - EXPECT_FALSE(b->HasActiveSurface()); - EXPECT_TRUE(ActiveInvariantHolds(*b)); + EXPECT_FALSE(Bind(kS1)); + EXPECT_TRUE(Trace().empty()); + EXPECT_EQ(b->ActiveSurface(), kS2); EXPECT_TRUE(BoundTo(b->CurrentHere(), kDpy, kS1, kCtx)); } @@ -1788,21 +1792,21 @@ TEST_F(BackendObjectEglSwap, ASwapNeedsTheInitializedDisplay) { b->ClearCalls(); EXPECT_FALSE(b->SwapEGLBuffers(kDpy2, kS1)); ASSERT_TRUE(b->InitializeEGLDisplay(kDpy2, nullptr, nullptr)); - EXPECT_FALSE(b->SwapEGLBuffers(kDpy, kS1)); // not the display any more - EXPECT_FALSE(b->SwapEGLBuffers(kDpy2, kS1)); // the binding names kDpy + EXPECT_FALSE(b->SwapEGLBuffers(kDpy2, kS1)); EXPECT_TRUE(TraceWithTableReads().empty()); - EXPECT_EQ(b->PresentCount(), 0u); + EXPECT_TRUE(b->SwapEGLBuffers(kDpy, kS1)); + EXPECT_EQ(b->PresentCount(), 1u); } // The display is checked before the re-activation: a swap of this thread's surface on -// a display that was replaced runs no hook, although that surface is not the active one. +// the wrong display runs no hook, even when the requested surface is inactive. TEST_F(BackendObjectEglSwap, ADisplayMismatchIsRefusedBeforeTheReactivation) { ASSERT_TRUE(Init()); ASSERT_TRUE(BoundWindow(kS1, kWin1)); ASSERT_TRUE(b->CreateEGLPbufferSurface(kS2, 4, 4)); ASSERT_TRUE(b->InitializeEGLDisplay(kDpy2, nullptr, nullptr)); b->ClearCalls(); - EXPECT_FALSE(Swap(kS1)); + EXPECT_FALSE(b->SwapEGLBuffers(kDpy2, kS1)); EXPECT_TRUE(TraceWithTableReads().empty()); EXPECT_EQ(b->ActiveSurface(), kS2); EXPECT_EQ(b->ActivatingSurface(), kS2); @@ -1970,15 +1974,12 @@ TEST_F(BackendObjectEglRelease, ReleasingACurrentSurfaceOnlyMarksIt) { EXPECT_TRUE(b->ResizeEGLWindowSurface(kS1, 5, 6)); EXPECT_TRUE(b->ActivateEGLSurface(kS2)); EXPECT_TRUE(b->ActivateEGLSurface(kS1)); - EXPECT_TRUE(BindOn(other, kS1, kCtx2)); - EXPECT_EQ(Trace(), (Vector{"Present", "InitPbuffer(s2,4,4)", "InitWindow(s1)", "InitCaps"})); + EXPECT_FALSE(BindOn(other, kS1, kCtx2)); + EXPECT_EQ(Trace(), (Vector{"Present", "InitPbuffer(s2,4,4)", "InitWindow(s1)"})); b->ClearCalls(); EXPECT_TRUE(Release()); - EXPECT_TRUE(Trace().empty()); - EXPECT_TRUE(b->IsRegistered(kS1)); - EXPECT_TRUE(ReleaseOn(other)); EXPECT_EQ(Trace(), (Vector{"Released(s1)", "Forgotten(s1)"})); - EXPECT_TRUE(AllCallsOn(other.Id())); + EXPECT_TRUE(AllCallsOn(std::this_thread::get_id())); EXPECT_FALSE(b->IsRegistered(kS1)); } @@ -2566,3 +2567,265 @@ TEST_F(BackendObjectEglLocking, SwapIntervalAndSwapWithDamageTakeNoLock) { kReachWindow), ProbeOutcome::GotThrough); } +namespace { + class FrontendEGLThreadLifetime : public ::testing::Test { + protected: + void SetUp() override { + m_oldState = Move(MG_State::pEGLContext); + m_oldBackend = Move(MG_Backend::pActiveBackendObject); + MG_State::pEGLContext = MakeUnique(); + MG_Backend::pActiveBackendObject = MakeUnique(); + Backend = static_cast(MG_Backend::pActiveBackendObject.get()); + Display = MG_State::pEGLContext->GetDisplay(EGL_DEFAULT_DISPLAY); + ASSERT_TRUE(MG_State::pEGLContext->InitializeDisplay(Display, nullptr, nullptr)); + ASSERT_TRUE(Backend->InitializeEGLDisplay(Display, nullptr, nullptr)); + EGLint configs = 0; + ASSERT_TRUE(MG_Impl::EGLImpl::ChooseConfig(Display, nullptr, &Config, 1, &configs)); + ASSERT_GT(configs, 0); + const EGLint dimensions[] = {EGL_WIDTH, 4, EGL_HEIGHT, 4, EGL_NONE}; + Surface = MG_Impl::EGLImpl::CreatePbufferSurface(Display, Config, dimensions); + ASSERT_NE(Surface, EGL_NO_SURFACE); + } + + void TearDown() override { + MG_Impl::EGLImpl::ReleaseThread(); + MG_State::pEGLContext = Move(m_oldState); + MG_Backend::pActiveBackendObject = Move(m_oldBackend); + } + + EglDouble* Backend = nullptr; + EGLDisplay Display = EGL_NO_DISPLAY; + EGLConfig Config = nullptr; + EGLSurface Surface = EGL_NO_SURFACE; + + private: + UniquePtr m_oldState; + UniquePtr m_oldBackend; + }; +} // namespace + +TEST_F(FrontendEGLThreadLifetime, ThreadExitReleasesCurrentContextForAnotherThread) { + using namespace MG_Impl::EGLImpl; + const EGLContext context = CreateContext(Display, Config, EGL_NO_CONTEXT, nullptr); + ASSERT_NE(context, EGL_NO_CONTEXT); + std::thread worker([&] { EXPECT_TRUE(MakeCurrent(Display, Surface, Surface, context)); }); + worker.join(); + + EXPECT_TRUE(MakeCurrent(Display, Surface, Surface, context)); +} + +TEST_F(FrontendEGLThreadLifetime, ThreadExitReapsPendingContextAndSurface) { + using namespace MG_Impl::EGLImpl; + const EGLContext context = CreateContext(Display, Config, EGL_NO_CONTEXT, nullptr); + ASSERT_NE(context, EGL_NO_CONTEXT); + const Uint64 token = MG_State::pEGLContext->GetContextClientToken(context); + { + Worker worker; + ASSERT_TRUE(worker.Run([&] { return MakeCurrent(Display, Surface, Surface, context); })); + ASSERT_TRUE(DestroyContext(Display, context)); + ASSERT_TRUE(DestroySurface(Display, Surface)); + EXPECT_EQ(Backend->ReleasedContextToken, 0u); + EXPECT_TRUE(Backend->Record(Surface)); + } + EXPECT_EQ(Backend->ReleasedContextToken, token); + EXPECT_FALSE(Backend->Record(Surface)); +} + +namespace { + namespace DGLES = MG_Backend::DirectGLES; + + class ResizeBackend : public DGLES::BackendObject_DirectGLES { + public: + // Use the production surface hooks with the fixture's EGL table and skip driver loading. + Bool InitializeFakeDisplay() { return BackendObject::InitializeEGLDisplay(kDpy, nullptr, nullptr); } + Bool CreateFakePbuffer(EGLSurface surface) { return BackendObject::CreateEGLPbufferSurface(surface, 4, 4); } + Optional Record(EGLSurface surface) const { return EGLRegistry().Find(surface); } + }; + + class NativeEGLContexts : public ::testing::Test { + protected: + enum class SurfaceOp { + Bind, + Destroy + }; + + struct SurfaceCall { + SurfaceOp Op; + EGLSurface Surface; + EGLContext Context = EGL_NO_CONTEXT; + Bool operator==(const SurfaceCall&) const = default; + }; + + void SetUp() override { +#if MOBILEGL_BUILD_DISAGGREGATED + m_previousTransport = std::exchange(MG_Config::Transport, MG_Config::TransportMode::Monolith); +#endif + MG_External::EGLFunctionsTable egl{}; + egl.eglGetDisplay = [](EGLNativeDisplayType) { return kDpy; }; + egl.eglInitialize = [](EGLDisplay, EGLint*, EGLint*) -> EGLBoolean { return EGL_TRUE; }; + egl.eglTerminate = [](EGLDisplay) -> EGLBoolean { return EGL_TRUE; }; + egl.eglChooseConfig = [](EGLDisplay, const EGLint*, EGLConfig* configs, EGLint size, + EGLint* count) -> EGLBoolean { + if (size > 0) configs[0] = reinterpret_cast(1); + *count = 1; + return EGL_TRUE; + }; + egl.eglCreateContext = [](EGLDisplay, EGLConfig, EGLContext share, const EGLint*) { + Shares.push_back(share); + return reinterpret_cast(Shares.size() + 1); + }; + egl.eglDestroyContext = [](EGLDisplay, EGLContext context) -> EGLBoolean { + Destroyed.push_back(context); + return EGL_TRUE; + }; + egl.eglCreatePbufferSurface = [](EGLDisplay, EGLConfig, const EGLint*) { + return reinterpret_cast(++NextSurface); + }; + egl.eglMakeCurrent = [](EGLDisplay, EGLSurface draw, EGLSurface read, EGLContext context) -> EGLBoolean { + EXPECT_EQ(draw, read); + SurfaceCalls.push_back({SurfaceOp::Bind, draw, context}); + if (std::exchange(FailNextBind, false)) return EGL_FALSE; + Current = context; + CurrentDraw = draw; + return EGL_TRUE; + }; + egl.eglDestroySurface = [](EGLDisplay, EGLSurface surface) -> EGLBoolean { + SurfaceCalls.push_back({SurfaceOp::Destroy, surface}); + return EGL_TRUE; + }; + egl.eglGetCurrentContext = [] { return Current; }; + DGLES::SetEGLFuncsTable(egl); + DGLES::SetGLESFuncsTable({}); + Shares.clear(); + Destroyed.clear(); + SurfaceCalls.clear(); + FailNextBind = false; + } + + void TearDown() override { + DGLES::DestroyEGLContext(); + DGLES::SetEGLFuncsTable({}); +#if MOBILEGL_BUILD_DISAGGREGATED + MG_Config::Transport = m_previousTransport; +#endif + } + + static EGLSurface LastCreatedSurface() { return Fake(NextSurface); } + + inline static std::uintptr_t NextSurface = 0; + inline static Vector Shares; + inline static Vector Destroyed; + inline static Vector SurfaceCalls; + inline static Bool FailNextBind = false; + inline static thread_local EGLContext Current = EGL_NO_CONTEXT; + inline static thread_local EGLSurface CurrentDraw = EGL_NO_SURFACE; + + private: +#if MOBILEGL_BUILD_DISAGGREGATED + MG_Config::TransportMode m_previousTransport = MG_Config::TransportMode::Monolith; +#endif + }; +} // namespace + +TEST_F(NativeEGLContexts, TwoThreadsBindDifferentNativeContextsInOneShareGroup) { + EGLSurface a = EGL_NO_SURFACE; + EGLSurface b = EGL_NO_SURFACE; + ASSERT_TRUE(DGLES::InitPbufferSurface(4, 4, &a)); + ASSERT_TRUE(DGLES::InitPbufferSurface(4, 4, &b)); + EXPECT_EQ(Current, EGL_NO_CONTEXT); + + ASSERT_TRUE(DGLES::BindMonolithNativeContext(101, 17, a)); + const EGLContext first = Current; + const Uint64 firstSerial = DGLES::CurrentNativeContextSerial(); + Worker worker; + const EGLContext second = worker.Run([&] { + EXPECT_TRUE(DGLES::BindMonolithNativeContext(102, 17, b)); + EXPECT_NE(DGLES::CurrentNativeContextSerial(), firstSerial); + EXPECT_EQ(DGLES::CurrentContextDrawSurface(), b); + return Current; + }); + ASSERT_NE(first, EGL_NO_CONTEXT); + ASSERT_NE(second, EGL_NO_CONTEXT); + EXPECT_NE(first, second); + EXPECT_EQ(Current, first); + EXPECT_EQ(DGLES::CurrentContextDrawSurface(), a); + EXPECT_EQ(Shares.back(), first); + + EXPECT_TRUE(DGLES::ReleaseCurrent()); + DGLES::DestroyNativeContextFor(101); + EXPECT_EQ(Destroyed, (Vector{first})); + EXPECT_EQ(DGLES::NativeContextHandleFor(0, 101), EGL_NO_CONTEXT); + EXPECT_EQ(DGLES::NativeContextHandleFor(0, 102), second); + EXPECT_TRUE(worker.Run([] { return DGLES::ReleaseCurrent(); })); +} + +TEST_F(NativeEGLContexts, ResizeRebindsThePbufferOnItsOwningThread) { + ResizeBackend backend; + ASSERT_TRUE(backend.InitializeFakeDisplay()); + ASSERT_TRUE(backend.CreateFakePbuffer(kS1)); + const EGLSurface original = LastCreatedSurface(); + ASSERT_TRUE(backend.CreateFakePbuffer(kS2)); + const EGLSurface other = LastCreatedSurface(); + + ASSERT_TRUE(DGLES::BindMonolithNativeContext(101, 17, original)); + const EGLContext first = Current; + Worker worker; + const EGLContext second = worker.Run([&] { + EXPECT_TRUE(DGLES::BindMonolithNativeContext(102, 17, other)); + return Current; + }); + ASSERT_NE(second, EGL_NO_CONTEXT); + ASSERT_EQ(DGLES::CurrentSessionDrawSurface(), other); + SurfaceCalls.clear(); + + ASSERT_TRUE(backend.ResizeEGLWindowSurface(kS1, 8, 6)); + const EGLSurface replacement = LastCreatedSurface(); + ASSERT_NE(replacement, original); + EXPECT_EQ(SurfaceCalls, + (Vector{{SurfaceOp::Bind, replacement, first}, {SurfaceOp::Destroy, original}})); + EXPECT_EQ(Current, first); + EXPECT_EQ(CurrentDraw, replacement); + EXPECT_EQ(DGLES::CurrentContextDrawSurface(), replacement); + EXPECT_EQ(DGLES::CurrentSessionDrawSurface(), other); + EXPECT_TRUE(RecordIs(backend.Record(kS1), PbufferRecord(8, 6, true, false, Win(0, 8, 6, WindowBackend::Unknown)))); + EXPECT_TRUE(RecordIs(backend.Record(kS2), PbufferRecord(4, 4, true))); + EXPECT_TRUE(worker.Run([&] { + EXPECT_EQ(Current, second); + EXPECT_EQ(CurrentDraw, other); + EXPECT_EQ(DGLES::CurrentContextDrawSurface(), other); + return DGLES::ReleaseCurrent(); + })); + EXPECT_TRUE(DGLES::ReleaseCurrent()); +} + +TEST_F(NativeEGLContexts, FailedResizePreservesThePbufferAndAllowsRetry) { + ResizeBackend backend; + ASSERT_TRUE(backend.InitializeFakeDisplay()); + ASSERT_TRUE(backend.CreateFakePbuffer(kS1)); + const EGLSurface original = LastCreatedSurface(); + ASSERT_TRUE(DGLES::BindMonolithNativeContext(101, 17, original)); + const EGLContext context = Current; + SurfaceCalls.clear(); + FailNextBind = true; + + EXPECT_FALSE(backend.ResizeEGLWindowSurface(kS1, 8, 6)); + const EGLSurface rejected = LastCreatedSurface(); + ASSERT_NE(rejected, original); + EXPECT_EQ(SurfaceCalls, + (Vector{{SurfaceOp::Bind, rejected, context}, {SurfaceOp::Destroy, rejected}})); + EXPECT_EQ(Current, context); + EXPECT_EQ(CurrentDraw, original); + EXPECT_EQ(DGLES::CurrentContextDrawSurface(), original); + EXPECT_EQ(DGLES::CurrentSessionDrawSurface(), original); + EXPECT_TRUE(RecordIs(backend.Record(kS1), PbufferRecord(4, 4, true))); + ASSERT_FALSE(DGLES::SelectSessionSurface(rejected)); + + SurfaceCalls.clear(); + ASSERT_TRUE(backend.ResizeEGLWindowSurface(kS1, 8, 6)); + const EGLSurface replacement = LastCreatedSurface(); + ASSERT_NE(replacement, rejected); + EXPECT_EQ(SurfaceCalls, + (Vector{{SurfaceOp::Bind, replacement, context}, {SurfaceOp::Destroy, original}})); + EXPECT_EQ(CurrentDraw, replacement); + EXPECT_TRUE(DGLES::ReleaseCurrent()); +} diff --git a/MobileGL/MG_Test/Buffer/BufferTest.cpp b/MobileGL/MG_Test/Buffer/BufferTest.cpp index 8550a6c6..4fd234e9 100644 --- a/MobileGL/MG_Test/Buffer/BufferTest.cpp +++ b/MobileGL/MG_Test/Buffer/BufferTest.cpp @@ -665,6 +665,78 @@ TEST_F(BufferTest, CreateBuffersCreatesObjectsImmediately) { EXPECT_EQ(MobileGL::MG_Impl::GLImpl::GetError(), GL_NO_ERROR); } +TEST_F(BufferTest, NamedBufferOperationsRequireAnExistingObject) { + using namespace MG_Impl::GLImpl; + GLuint buffer = 0; + GenBuffers(1, &buffer); + ASSERT_NE(buffer, 0u); + ASSERT_FALSE(IsBuffer(buffer)); + + for (const GLuint missing : {0u, buffer}) { + SCOPED_TRACE(missing); + NamedBufferData(missing, 16, nullptr, GL_STATIC_DRAW); + ExpectSingleGlError(GL_INVALID_OPERATION); + GLint size = -1; + GetNamedBufferParameteriv(missing, GL_BUFFER_SIZE, &size); + ExpectSingleGlError(GL_INVALID_OPERATION); + EXPECT_EQ(size, -1); + EXPECT_FALSE(IsBuffer(missing)); + } + + BindBuffer(GL_ARRAY_BUFFER, buffer); + EXPECT_TRUE(IsBuffer(buffer)); + NamedBufferData(buffer, 16, nullptr, GL_STATIC_DRAW); + GLint size = -1; + GetNamedBufferParameteriv(buffer, GL_BUFFER_SIZE, &size); + EXPECT_EQ(size, 16); + DeleteBuffers(1, &buffer); + EXPECT_EQ(GetError(), GL_NO_ERROR); +} + +TEST_F(BufferTest, MapRangeInvalidationCannotReplaceAnActiveMapping) { + using namespace MG_Impl::GLImpl; + for (const bool persistent : {false, true}) { + SCOPED_TRACE(persistent); + GLuint buffer = 0; + CreateBuffers(1, &buffer); + BindBuffer(GL_ARRAY_BUFFER, buffer); + const Vector initial(16, 0); + const GLbitfield access = GL_MAP_WRITE_BIT | (persistent ? GL_MAP_PERSISTENT_BIT : 0); + if (persistent) { + BufferStorage(GL_ARRAY_BUFFER, initial.size(), initial.data(), access); + } else { + BufferData(GL_ARRAY_BUFFER, initial.size(), initial.data(), GL_DYNAMIC_DRAW); + } + auto* mapped = static_cast(MapBufferRange(GL_ARRAY_BUFFER, 4, 4, access)); + ASSERT_NE(mapped, nullptr); + ASSERT_EQ(GetError(), GL_NO_ERROR); + mapped[0] = 0x5A; + + for (const GLbitfield invalidate : {GL_MAP_INVALIDATE_RANGE_BIT, GL_MAP_INVALIDATE_BUFFER_BIT}) { + SCOPED_TRACE(invalidate); + EXPECT_EQ(MapBufferRange(GL_ARRAY_BUFFER, 8, 8, GL_MAP_WRITE_BIT | invalidate), nullptr); + ExpectSingleGlError(GL_INVALID_OPERATION); + EXPECT_EQ(MapNamedBufferRange(buffer, 8, 8, GL_MAP_WRITE_BIT | invalidate), nullptr); + ExpectSingleGlError(GL_INVALID_OPERATION); + } + + void* actualPointer = nullptr; + GetNamedBufferPointerv(buffer, GL_BUFFER_MAP_POINTER, &actualPointer); + EXPECT_EQ(actualPointer, mapped); + GLint actualAccess = 0; + GetNamedBufferParameteriv(buffer, GL_BUFFER_ACCESS_FLAGS, &actualAccess); + EXPECT_EQ(static_cast(actualAccess), access); + EXPECT_TRUE(UnmapBuffer(GL_ARRAY_BUFFER)); + Vector actual(initial.size()); + GetBufferSubData(GL_ARRAY_BUFFER, 0, actual.size(), actual.data()); + Vector expected = initial; + expected[4] = 0x5A; + EXPECT_EQ(actual, expected); + DeleteBuffers(1, &buffer); + EXPECT_EQ(GetError(), GL_NO_ERROR); + } +} + TEST_F(BufferTest, CopyNamedBufferSubDataCopiesBetweenDSABuffers) { GLuint buffers[2] = {}; MobileGL::MG_Impl::GLImpl::CreateBuffers(2, buffers); @@ -843,6 +915,39 @@ TEST_F(BufferTest, ClearBufferDataConvertsOneClientPixelBeforeRepeatingIt) { DrainPendingGlErrors(); } +TEST_F(BufferTest, ClearBufferSubDataRejectsOnlyRangesOverlappingTheMapping) { + using namespace MG_Impl::GLImpl; + GLuint buffer = 0; + CreateBuffers(1, &buffer); + BindBuffer(GL_ARRAY_BUFFER, buffer); + const Vector initial(12, 0x19); + BufferData(GL_ARRAY_BUFFER, initial.size(), initial.data(), GL_DYNAMIC_DRAW); + ASSERT_NE(MapBufferRange(GL_ARRAY_BUFFER, 4, 4, GL_MAP_WRITE_BIT), nullptr); + ASSERT_EQ(GetError(), GL_NO_ERROR); + + const Uint8 value = 0xA5; + ClearBufferSubData(GL_ARRAY_BUFFER, GL_R8UI, 0, 4, GL_RED_INTEGER, GL_UNSIGNED_BYTE, &value); + EXPECT_EQ(GetError(), GL_NO_ERROR); + ClearNamedBufferSubData(buffer, GL_R8UI, 8, 4, GL_RED_INTEGER, GL_UNSIGNED_BYTE, &value); + EXPECT_EQ(GetError(), GL_NO_ERROR); + ClearNamedBufferSubData(buffer, GL_R8UI, 6, 0, GL_RED_INTEGER, GL_UNSIGNED_BYTE, &value); + EXPECT_EQ(GetError(), GL_NO_ERROR); + + ClearBufferSubData(GL_ARRAY_BUFFER, GL_R8UI, 3, 2, GL_RED_INTEGER, GL_UNSIGNED_BYTE, &value); + ExpectSingleGlError(GL_INVALID_OPERATION); + ClearNamedBufferSubData(buffer, GL_R8UI, 7, 2, GL_RED_INTEGER, GL_UNSIGNED_BYTE, &value); + ExpectSingleGlError(GL_INVALID_OPERATION); + ClearBufferData(GL_ARRAY_BUFFER, GL_R8UI, GL_RED_INTEGER, GL_UNSIGNED_BYTE, nullptr); + ExpectSingleGlError(GL_INVALID_OPERATION); + EXPECT_TRUE(UnmapBuffer(GL_ARRAY_BUFFER)); + + Vector actual(initial.size()); + GetBufferSubData(GL_ARRAY_BUFFER, 0, actual.size(), actual.data()); + EXPECT_EQ(actual, (Vector{value, value, value, value, 0x19, 0x19, 0x19, 0x19, value, value, value, value})); + DeleteBuffers(1, &buffer); + EXPECT_EQ(GetError(), GL_NO_ERROR); +} + TEST_F(BufferTest, ClearBufferSubDataRejectsUnboundTarget) { MobileGL::MG_Impl::GLImpl::BindBuffer(GL_SHADER_STORAGE_BUFFER, 0); const GLbyte zero = 0; @@ -1429,7 +1534,7 @@ TEST_F(GeneralBufferTest, General_PersistentExplicitFlushOnlyDirtiesFlushedRange TEST_F(GeneralBufferTest, General_NamedBufferStorageMappingWrappers) { GLuint buffer = 0; - GenBuffers(1, &buffer); + CreateBuffers(1, &buffer); GLint initial[] = {1, 2, 3, 4}; NamedBufferStorage(buffer, sizeof(initial), initial, @@ -1553,6 +1658,8 @@ namespace { struct ZeroCopyMockBackend { Vector gpu; // stand-in for host-visible coherent GPU storage int acquireMapCalls = 0; + Bool receivedMapSeed = false; + MG_Pipe::MGPipeHandle mappedHandle{}; int subDataCalls = 0; int respecifyCalls = 0; int flushCalls = 0; @@ -1574,8 +1681,10 @@ namespace { // registers - and no longer the deleted BufferBackendOps table. The frontend reaches it the // way it reaches a real backend in monolith: the emitters build the records and the applier // dispatches them synchronously. - void* ZeroCopyMock_MapPersistent(MG_Pipe::MGPipeHandle, Uint64 size, const void* seedBytes) { + void* ZeroCopyMock_MapPersistent(MG_Pipe::MGPipeHandle handle, Uint64 size, const void* seedBytes) { if (!g_zeroCopyMock || !g_zeroCopyMock->provideMap) return nullptr; + g_zeroCopyMock->mappedHandle = handle; + g_zeroCopyMock->receivedMapSeed = seedBytes != nullptr; if (g_zeroCopyMock->gpu.size() != size) { g_zeroCopyMock->gpu.assign(static_cast(size), 0); // Seed from the shadow the frontend hands over (it adopts only after we return). @@ -1587,7 +1696,14 @@ namespace { return g_zeroCopyMock->gpu.data(); } - void ZeroCopyMock_Respecify(MG_Pipe::MGPipeHandle, const MG_Pipe::MGPResourceDesc&, const void*) { + void ResetMockStore(MG_Pipe::MGPipeHandle handle) { + if (!g_zeroCopyMock || g_zeroCopyMock->mappedHandle != handle) return; + g_zeroCopyMock->gpu = {}; + g_zeroCopyMock->residentWrites.clear(); + g_zeroCopyMock->mappedHandle = {}; + } + void ZeroCopyMock_Respecify(MG_Pipe::MGPipeHandle handle, const MG_Pipe::MGPResourceDesc&, const void*) { + ResetMockStore(handle); if (g_zeroCopyMock) ++g_zeroCopyMock->respecifyCalls; } void ZeroCopyMock_SubData(MG_Pipe::MGPipeHandle, const MG_Pipe::MGPSubData&, const void*) { @@ -1596,7 +1712,9 @@ namespace { void ZeroCopyMock_Flush(MG_Pipe::MGPipeHandle, const MG_Pipe::MGPFlushRange&, const void*) { if (g_zeroCopyMock) ++g_zeroCopyMock->flushCalls; } - void ZeroCopyMock_Destroy(MG_Pipe::MGPipeHandle) {} + void ZeroCopyMock_Destroy(MG_Pipe::MGPipeHandle handle) { + ResetMockStore(handle); + } const MG_Pipe::MGPipeResourceOps kZeroCopyMockOps = { .Respecify = ZeroCopyMock_Respecify, @@ -1616,17 +1734,20 @@ namespace { const auto* first = static_cast(bytes); write.bytes.assign(first, first + static_cast(MG_Pipe::MGPipeSubDataBufferSize(record))); } - void ZeroCopyMock_Readback(MG_Pipe::MGPipeHandle, const MG_Pipe::MGPReadback&) { - if (!g_zeroCopyMock) return; + Bool ZeroCopyMock_Readback(MG_Pipe::MGPipeHandle, const MG_Pipe::MGPReadback&) { + if (!g_zeroCopyMock) return false; ++g_zeroCopyMock->readbackCalls; + Bool success = true; for (const auto& write : g_zeroCopyMock->residentWrites) { - // Reported, not asserted: an ASSERT here would return out of the readback and - // leave the remaining landings unapplied, which reads as a different failure. EXPECT_LE(write.offset + write.bytes.size(), g_zeroCopyMock->gpu.size()); - if (write.offset + write.bytes.size() > g_zeroCopyMock->gpu.size()) continue; + if (write.offset + write.bytes.size() > g_zeroCopyMock->gpu.size()) { + success = false; + continue; + } Memcpy(g_zeroCopyMock->gpu.data() + write.offset, write.bytes.data(), write.bytes.size()); } g_zeroCopyMock->residentWrites.clear(); + return success; } const MG_Pipe::MGPipeResourceOps kResidentSubDataMockOps = { @@ -1752,7 +1873,7 @@ TEST_F(GeneralBufferTest, General_CoherentAsFlush_DsaPersistentMapRewritesAndTol ScopedCoherentAsFlush scopedFeature; GLuint buffer = 0; - GenBuffers(1, &buffer); + CreateBuffers(1, &buffer); GLint initial[] = {1, 2, 3, 4}; NamedBufferStorage(buffer, sizeof(initial), initial, GL_MAP_WRITE_BIT | GL_MAP_PERSISTENT_BIT); @@ -1903,10 +2024,7 @@ TEST_F(BufferTest, RedefiningAnAdoptedBufferAtANewSizeStaysInBounds) { EXPECT_EQ(bufferObject->GetSize(), sizeof(large)); EXPECT_FALSE(bufferObject->IsBackendPersistentMapped()); EXPECT_EQ(std::memcmp(bufferObject->MappedData(), large, sizeof(large)), 0); - // The old, smaller GPU block was not written through: still the old size, still the - // old bytes. - EXPECT_EQ(mock.gpu.size(), sizeof(small)); - EXPECT_EQ(std::memcmp(mock.gpu.data(), small, sizeof(small)), 0); + EXPECT_TRUE(mock.gpu.empty()); // And residency can be taken again, now over the new store. ASSERT_TRUE(bufferObject->EnsureGpuResidentStorage()); @@ -2042,8 +2160,10 @@ namespace { auto bufferObject = MG_State::pGLContext->GetBufferObject(buffer); EXPECT_NE(bufferObject, nullptr); if (bufferObject == nullptr) return nullptr; - EXPECT_TRUE(bufferObject->EnsureGpuResidentStorage()); - EXPECT_TRUE(bufferObject->IsBackendPersistentMapped()); + if (!bufferObject->EnsureGpuResidentStorage() || !bufferObject->IsBackendPersistentMapped()) { + ADD_FAILURE() << "The mock did not provide resident storage"; + return nullptr; + } EXPECT_EQ(static_cast(bufferObject->MappedData()), static_cast(mock.gpu.data())); mock.subDataCalls = 0; mock.flushCalls = 0; @@ -2056,6 +2176,76 @@ namespace { } } // namespace +TEST_F(BufferTest, ReacquiresAnAdoptedStoreAfterResourceOpsAreUnregistered) { + ZeroCopyMockBackend first, replacement; + g_zeroCopyMock = &first; + ScopedBackendOps scopedOps(&kZeroCopyMockOps); + + GLuint buffer = 0; + auto object = MakeAdoptedBuffer(first, GL_ARRAY_BUFFER, buffer); + ASSERT_TRUE(object); + ASSERT_TRUE(object->IsBackendPersistentMapped()); + ASSERT_TRUE(first.receivedMapSeed); + const auto* oldBase = object->MappedData(); + ASSERT_NE(oldBase, nullptr); + + MG_Pipe::MGPipeSetResourceOps(&kZeroCopyMockOps); + EXPECT_TRUE(object->EnsureGpuResidentStorage()); + EXPECT_EQ(object->MappedData(), oldBase); + EXPECT_EQ(first.acquireMapCalls, 1); + + MG_Pipe::MGPipeSetResourceOps(nullptr); + g_zeroCopyMock = &replacement; + MG_Pipe::MGPipeSetResourceOps(&kZeroCopyMockOps); + EXPECT_FALSE(object->IsBackendPersistentMapped()); + EXPECT_FALSE(object->HasDefinedContent()); + const auto* shadow = object->MappedData(); + ASSERT_NE(shadow, nullptr); + EXPECT_NE(shadow, oldBase); + EXPECT_EQ(object->AcquireMemory(false, true, false), shadow); + GLint value = -1; + object->DownloadSubData(&value, sizeof(value), sizeof(value)); + EXPECT_NE(value, 1); + + ASSERT_TRUE(object->EnsureGpuResidentStorage()); + EXPECT_NE(object->MappedData(), oldBase); + EXPECT_EQ(replacement.acquireMapCalls, 1); + EXPECT_FALSE(replacement.receivedMapSeed); + DeleteBuffers(1, &buffer); + g_zeroCopyMock = nullptr; +} + +TEST_F(BufferTest, RevocationInvalidatesAnApplicationMapping) { + ZeroCopyMockBackend mock; + g_zeroCopyMock = &mock; + ScopedBackendOps scopedOps(&kZeroCopyMockOps); + + GLuint buffer = 0; + GenBuffers(1, &buffer); + BindBuffer(GL_ARRAY_BUFFER, buffer); + constexpr GLint seed = 42; + constexpr GLbitfield access = GL_MAP_WRITE_BIT | GL_MAP_PERSISTENT_BIT | GL_MAP_COHERENT_BIT; + BufferStorage(GL_ARRAY_BUFFER, sizeof(seed), &seed, access); + auto object = MG_State::pGLContext->GetBufferObject(buffer); + ASSERT_TRUE(object); + auto* mapping = MapBufferRange(GL_ARRAY_BUFFER, 0, sizeof(seed), access); + ASSERT_NE(mapping, nullptr); + ASSERT_TRUE(object->IsBackendPersistentMapped()); + EXPECT_EQ(object->GetMappedPointer(), mapping); + + MG_Pipe::MGPipeRevokeResidentBuffer(mock.mappedHandle, &seed); + EXPECT_EQ(object->GetMappedPointer(), mapping); + MG_Pipe::MGPipeRevokeResidentBuffer(mock.mappedHandle, mapping); + EXPECT_EQ(object->GetMappedPointer(), nullptr); + EXPECT_FALSE(object->EnsureGpuResidentStorage()); + EXPECT_EQ(UnmapBuffer(GL_ARRAY_BUFFER), GL_FALSE); + EXPECT_EQ(GetError(), GL_NO_ERROR); + EXPECT_FALSE(object->IsMapped()); + + DeleteBuffers(1, &buffer); + g_zeroCopyMock = nullptr; +} + TEST_F(BufferTest, ANonPersistentReadWriteRangeMapOfAnAdoptedStoreLandsAtUnmap) { ZeroCopyMockBackend mock; g_zeroCopyMock = &mock; diff --git a/MobileGL/MG_Test/EGLState/EGLStateTest.cpp b/MobileGL/MG_Test/EGLState/EGLStateTest.cpp index f0a7f731..3aed20cc 100644 --- a/MobileGL/MG_Test/EGLState/EGLStateTest.cpp +++ b/MobileGL/MG_Test/EGLState/EGLStateTest.cpp @@ -7,6 +7,7 @@ // End of Source File Header #include +#include #include #include #include @@ -626,6 +627,28 @@ TEST(EGLStateRobustness, ResetNotificationStrategyIsRecordedValidatedAndMatchedA EXPECT_NE(sharedPlain, EGL_NO_CONTEXT); } +TEST(EGLStateRobustness, HidesGlResetExtensionsWhenUnavailable) { + using MobileGL::MG_Impl::GLImpl::ClientSideExtensionList; + const auto& extensions = ClientSideExtensionList(true, false, false, false, false); + ASSERT_EQ(extensions.size(), 1u); + EXPECT_STREQ(extensions.front(), "GL_OES_EGL_image"); +} + +TEST(EGLStateRobustness, RejectsResetNotificationWhenUnavailable) { + auto fixture = CreateFixture(); + auto& state = fixture->State; + for (const EGLint attribute : + {EGL_CONTEXT_OPENGL_RESET_NOTIFICATION_STRATEGY, EGL_CONTEXT_OPENGL_RESET_NOTIFICATION_STRATEGY_EXT}) { + const EGLint lose[] = {attribute, EGL_LOSE_CONTEXT_ON_RESET, EGL_NONE}; + EXPECT_EQ(state.CreateContext(fixture->Display, fixture->Config, EGL_NO_CONTEXT, lose, false, false), + EGL_NO_CONTEXT); + EXPECT_EQ(state.ConsumeError(), EGL_BAD_MATCH); + } + const EGLint plain[] = {EGL_CONTEXT_OPENGL_RESET_NOTIFICATION_STRATEGY, EGL_NO_RESET_NOTIFICATION, EGL_NONE}; + EXPECT_NE(state.CreateContext(fixture->Display, fixture->Config, EGL_NO_CONTEXT, plain, false, false), + EGL_NO_CONTEXT); +} + TEST(EGLStateRobustness, RobustAccessIsARequestAndNeverAGLContextFlagByItself) { auto fixture = CreateFixture(); auto& state = fixture->State; diff --git a/MobileGL/MG_Test/Pipe/ResourceEmitTest.cpp b/MobileGL/MG_Test/Pipe/ResourceEmitTest.cpp index c1864062..6816a70f 100644 --- a/MobileGL/MG_Test/Pipe/ResourceEmitTest.cpp +++ b/MobileGL/MG_Test/Pipe/ResourceEmitTest.cpp @@ -252,9 +252,10 @@ namespace { ++g_spy.Flushes; g_spy.LastHandle = res; } - void SpyReadback(MGPipeHandle res, const MGPReadback&) { + Bool SpyReadback(MGPipeHandle res, const MGPReadback&) { ++g_spy.Readbacks; g_spy.LastHandle = res; + return true; } void SpyDestroy(MGPipeHandle res) { ++g_spy.Destroys; @@ -519,7 +520,7 @@ namespace { MGPipeApplyResourceSubData(BufferWrite(res, 0, 64), bytes); MGPipeApplyBufferSubDataResident(BufferWrite(res, 64, 64), bytes); MGPipeApplyResourceFlushRange(MGPFlushRange{res, 0, 64, 0, 0}, bytes); - MGPipeApplyResourceReadback(MGPReadback{res, 0, 256}); + EXPECT_FALSE(MGPipeApplyResourceReadback(MGPReadback{res, 0, 256})); EXPECT_EQ(MGPipeApplyMapPersistent(BufferHandle(res), 256, bytes), nullptr) << "an unregistered table declines every acquisition, which is a real answer"; MGPipeApplyUnmapPersistent(BufferHandle(res)); @@ -542,7 +543,7 @@ namespace { EXPECT_EQ(g_spy.Residents, 1u); MGPipeApplyResourceFlushRange(MGPFlushRange{other, 0, 64, 0, 0}, bytes); EXPECT_EQ(g_spy.Flushes, 1u); - MGPipeApplyResourceReadback(MGPReadback{other, 0, 256}); + EXPECT_TRUE(MGPipeApplyResourceReadback(MGPReadback{other, 0, 256})); EXPECT_EQ(g_spy.Readbacks, 1u); EXPECT_EQ(MGPipeApplyMapPersistent(BufferHandle(other), 256, bytes), &g_spyMapTarget) << "the donated pointer is the owner's answer and travels back unchanged"; diff --git a/MobileGL/MG_Test/SanityTest.cpp b/MobileGL/MG_Test/SanityTest.cpp index 803669ab..16da64f8 100644 --- a/MobileGL/MG_Test/SanityTest.cpp +++ b/MobileGL/MG_Test/SanityTest.cpp @@ -4216,21 +4216,22 @@ TEST(DirectGLESSlotTable, ASavedCopyOfARealRegistryDropsTheTwinOnTheSameNotice) << "the saved copy kept the dead texture's twin - the dispatcher told one holder only"; } -// P5 b1's half of the case above: THE PIN IS LIFTED, AND THIS IS WHAT REPLACED IT. -// -// The case above exists because answering the live-map question from HasLiveHostWrites alone -// read draw-CLEAN forever. P5 gives that field a producer and retires the last frontend read -// in IsBufferDrawCleanByHandle under split, because under a spawn there is no frontend object -// on that side to ask. -// -// EVERYTHING THE CASE OBSERVES IS WRITTEN BY THE PRODUCER, NOT BY THE CASE. A first cut of -// this test set `record.HasLiveHostWrites = true` by hand and therefore passed with the -// producer deleted - a test that constructs the state it is supposed to be observing cannot -// fail for the reason it exists. So the resource subsystem is armed with an empty ops table -// (MG_Test/Pipe's PushArm shape), the map and the unmap are made through the ordinary -// frontend entry points, and the record is only ever READ. Delete -// BufferObject::NotePersistentMapStateChanged's emission, or PipeFill.cpp's -// `record.HasLiveHostWrites = ...`, and this goes red. +TEST(DirectGLESBufferDrawProbe, CpuReadsRejectStaleMappedBacking) { + using namespace MobileGL; + using namespace MobileGL::MG_Backend::DirectGLES::BufferImpl; + Uint8 mapByte = 1, shadowByte = 2; + GLESBufferResource resource; + resource.persistentMapped = true; + resource.persistentPtr = &mapByte; + resource.contextGeneration = CurrentBufferContextGeneration(); + EXPECT_EQ(SplitHostBytesForCpuRead(resource, {}, "test"), &mapByte); + --resource.contextGeneration; + EXPECT_EQ(SplitHostBytes(resource), nullptr); + EXPECT_EQ(SplitHostBytesForCpuRead(resource, {}, "test"), nullptr); + resource.hostBytes = &shadowByte; + EXPECT_EQ(SplitHostBytesForCpuRead(resource, {}, "test"), &shadowByte); +} + TEST(DirectGLESBufferDrawProbe, UnderSplitTheRecordAloneAnswersTheLiveHostMapQuestion) { using namespace MobileGL; using namespace MobileGL::MG_Backend::DirectGLES; diff --git a/MobileGL/MG_Test/Texture/TextureTest.cpp b/MobileGL/MG_Test/Texture/TextureTest.cpp index a78c8b13..ec5910a8 100644 --- a/MobileGL/MG_Test/Texture/TextureTest.cpp +++ b/MobileGL/MG_Test/Texture/TextureTest.cpp @@ -1365,17 +1365,17 @@ TEST_F(TextureTest, ExternalImageExtensionNamesStayOffStrictDesktopContexts) { return std::any_of(list.begin(), list.end(), [&](const char* n) { return std::strcmp(n, name) == 0; }); }; // Strict desktop: the caller passes external=false (see ClientSideExtensions). - const auto& desktop = ClientSideExtensionList(true, false, false, false); + const auto& desktop = ClientSideExtensionList(true, false, false, false, true); for (const char* name : desktop) { if (std::strstr(name, "OES") != nullptr) EXPECT_STREQ(name, "GL_OES_EGL_image"); } EXPECT_TRUE(contains(desktop, "GL_ARB_robustness")); - const auto& relaxedDesktop = ClientSideExtensionList(true, true, false, false); + const auto& relaxedDesktop = ClientSideExtensionList(true, true, false, false, true); EXPECT_TRUE(contains(relaxedDesktop, "GL_OES_EGL_image_external")); EXPECT_TRUE(contains(relaxedDesktop, "GL_OES_EGL_image_external_essl3")); - const auto& es = ClientSideExtensionList(true, true, false, true); + const auto& es = ClientSideExtensionList(true, true, false, true, true); EXPECT_TRUE(contains(es, "GL_OES_EGL_image_external")); EXPECT_TRUE(contains(es, "GL_OES_EGL_image_external_essl3")); EXPECT_TRUE(contains(es, "GL_KHR_robustness")); diff --git a/MobileGL/MG_Test/Wire/PipeWireCodecTest.cpp b/MobileGL/MG_Test/Wire/PipeWireCodecTest.cpp index 06960124..bb4f9013 100644 --- a/MobileGL/MG_Test/Wire/PipeWireCodecTest.cpp +++ b/MobileGL/MG_Test/Wire/PipeWireCodecTest.cpp @@ -14,12 +14,8 @@ // reason: the R-2 arms report through MGLOG_F + std::abort, so a case that drives one FORKS // and reads the Fatal line back out of a log file this process names before anything logs. // NEVER EXPECT_DEATH - it re-runs the whole binary and would re-enter the applier's globals. -// -// WHAT A "ROUND TRIP" MEANS HERE. The decoder implements no semantics, so a case cannot -// assert on rendering; what it asserts is that the record crossed intact and that the arm -// reached the right consumer with the right arguments. For the five class-B verbs that is a -// recording WireVerbSink; for everything else it is the real applier, whose acceptance return -// comes back through the recording ReplySink on the record's own seq (R-3/R-5). +// The fixture checks the arguments received by the applier and verb sink and records +// the replies sent for each sequence. #include #include @@ -51,6 +47,7 @@ #include #include #include +#include #include #include #include @@ -2183,6 +2180,7 @@ TEST_F(PipeWireCodecTest, TheFourAcceptanceRowsAnswerThroughTheSlotAndNotOnlyThr ExpectRepliesAgreeWithTheAcceptanceTally(wire); } +#include "PipeWireReadback.inc" TEST_F(PipeWireCodecTest, TheAuditFillOverwritesExactlyTheRunsTheRecordResolved) { // R-2.5, the only mechanical control on rule C ("no applier entry point retains a pointer // past its return"). An instrumentation that cannot be observed to have run is decoration, diff --git a/MobileGL/MG_Test/Wire/PipeWireReadback.inc b/MobileGL/MG_Test/Wire/PipeWireReadback.inc new file mode 100644 index 00000000..eefe5c75 --- /dev/null +++ b/MobileGL/MG_Test/Wire/PipeWireReadback.inc @@ -0,0 +1,43 @@ +// MobileGL - MobileGL/MG_Test/Wire/PipeWireReadback.inc +// Copyright (c) 2025-2026 MobileGL-Dev +// Licensed under the GNU Lesser General Public License v3.0: +// https://www.gnu.org/licenses/gpl-3.0.txt +// https://www.gnu.org/licenses/lgpl-3.0.txt +// SPDX-License-Identifier: LGPL-3.0-only +// End of Source File Header + +TEST_F(PipeWireCodecTest, BufferReadbackReportsTheBackendVerdictInBothRoutes) { + static const MGPipeResourceOps ops = [] { + MGPipeResourceOps table{}; + table.Readback = [](MGPipeHandle, const MGPReadback& request) -> Bool { return request.Offset == 0; }; + return table; + }(); + struct RestoreResourceOps { + const MGPipeResourceOps* previous = MGPipeGetResourceOps(); + ~RestoreResourceOps() { MGPipeSetResourceOps(previous); } + } restore; + MGPipeSetResourceOps(&ops); + MGPipeInstallMonolithTables(); + + Wire2 wire; + MGPResourceDesc desc{}; + desc.Resource = MakeHandle(34); + desc.Target = kMGPipeResourceTargetBuffer; + desc.Width = 8; + ASSERT_TRUE(MGPipeApplyResourceCreate(desc)); + for (const Uint64 offset : {Uint64{0}, Uint64{4}}) { + const Bool expected = offset == 0; + const MGPReadback request{desc.Resource, offset, 4}; + const Uint64 seq = wire.Encoder().EncodeRecord(MGPWireOp::ResourceReadback, &request, sizeof(request)); + ASSERT_NE(seq, kInvalidSeq); + bool applied = false; + ASSERT_TRUE(wire.PumpOne(&applied)); + EXPECT_TRUE(applied); + ASSERT_EQ(wire.Answers().All.size(), seq); + const auto& reply = wire.Answers().All.back(); + EXPECT_EQ(reply.Seq, seq); + EXPECT_EQ(reply.Status, expected ? ReplySink::kStatusOk : ReplySink::kStatusDeclined); + EXPECT_TRUE(reply.Bytes.empty()); + EXPECT_EQ(MGPipeRouteResourceReadback(request), expected); + } +} diff --git a/MobileGL/MG_Test/Wire/RemoteClientControls.inc b/MobileGL/MG_Test/Wire/RemoteClientControls.inc index cbdcf5f4..e7aaf2b1 100644 --- a/MobileGL/MG_Test/Wire/RemoteClientControls.inc +++ b/MobileGL/MG_Test/Wire/RemoteClientControls.inc @@ -950,11 +950,6 @@ TEST(RemoteClientControls, DeviceLostRespecifyDoesNotDieOfTheUncarriedBytesCheck // before the read. The peer below plays a server that took the read and died before landing // it: it counts the record and writes nothing. The map that follows must end BY NAME, never // hand the old bytes back as pixels. -// -// THE REDS, RUN ONCE: with MOBILEGL_IPC_PBO_READBACK_SYNC=1 the read takes the reply form, the -// peer sees no pack-buffer record and the child exits 151; without AwaitBufferWriteback's -// device-lost arm the child still aborts, but as Fatal{UnimplementedWritebackWait}, which names -// a missing wait rather than a lost device. struct PackReadPeer : Codec::WireVerbSink { std::atomic packReads{0}; Bool OnReadPixelsToBuffer(const MGPReadbackToBuffer&) override { @@ -971,6 +966,63 @@ struct PackReadPeer : Codec::WireVerbSink { } }; +void ReadBackWithScriptedPeer(Bool sliced, Bool decline) { + StartControlSession(); + static Bool declineReadback = false; + declineReadback = decline; + MGPipeResourceOps ops{}; + ops.Readback = [](MGPipeHandle handle, const MGPReadback& readback) -> Bool { + // For a sliced request, deliver the first slice and decline the second. + if (declineReadback && (readback.Offset != 0 || readback.Size <= 64)) return false; + const Vector bytes(static_cast(readback.Size), 0x37); + gMGPipeCallbacks.OnBufferWriteback( + handle, readback.Offset, + MGPBlobRef{reinterpret_cast(bytes.data()), readback.Size, kMGHostSpanSegNone, 0}); + return true; + }; + const auto rc = Srv::ServerLoopInstance().RunProbeOnApplyThreadForTesting( + [](void* table) { + MGPipeSetResourceOps(static_cast(table)); + return MOBILEGL_OK; + }, + &ops); + if (rc != MOBILEGL_OK) ::_exit(153); + + MG_Config::Features.PipePush |= kMGPipeSubsystemResources; + MG_State::pGLContext = MakeUnique(); + constexpr GLenum kTarget = GL_ARRAY_BUFFER; + const SizeT size = sliced ? BufferWritebackSliceBytes() + 1 : 64; + GLuint name = 0; + MG_Impl::GLImpl::GenBuffers(1, &name); + MG_Impl::GLImpl::BindBuffer(kTarget, name); + MG_Impl::GLImpl::BufferData(kTarget, size, nullptr, GL_STREAM_READ); + const auto& buffer = MG_State::pGLContext->GetBufferObject(name); + if (!buffer) ::_exit(154); + buffer->MarkGpuWritten(); + Vector bytes(size, 0); + MG_Impl::GLImpl::GetBufferSubData(kTarget, 0, size, bytes.data()); + if (decline || buffer->HasOutstandingGpuWrite()) ::_exit(155); + if (!std::all_of(bytes.begin(), bytes.end(), [](Uint8 byte) { return byte == 0x37; })) ::_exit(156); + ClientSessionInstance().Stop(); + MGPipeSetResourceOps(nullptr); +} + +TEST(RemoteClientControls, SuccessfulWholeAndSlicedReadbacksReturnGpuBytes) { + for (const Bool sliced : {false, true}) { + SCOPED_TRACE(sliced); + ExpectChildSuccess(RunInChild([=] { ReadBackWithScriptedPeer(sliced, false); })); + } +} + +TEST(RemoteClientControls, BackendReadbackDeclinePreventsCpuRead) { + for (const Bool sliced : {false, true}) { + SCOPED_TRACE(sliced); + const auto child = RunInChild([=] { ReadBackWithScriptedPeer(sliced, true); }); + ExpectNamedAbort(child, "Fatal{ReadbackDeclined, \"buffer-writeback\"}"); + if (sliced) EXPECT_NE(child.Log.find("could not read back 1 bytes"), std::string::npos) << child.Log; + } +} + TEST(RemoteClientControls, APackReadOwedWhenTheDeviceIsLostNeverReadsBackAsTheOldBytes) { const auto child = RunInChild([] { StartControlSession(); diff --git a/MobileGL/MG_Test/Wire/RemoteClientTest.cpp b/MobileGL/MG_Test/Wire/RemoteClientTest.cpp index 4804e515..be13647b 100644 --- a/MobileGL/MG_Test/Wire/RemoteClientTest.cpp +++ b/MobileGL/MG_Test/Wire/RemoteClientTest.cpp @@ -6,16 +6,9 @@ // SPDX-License-Identifier: LGPL-3.0-only // End of Source File Header -// P5 package c1's suite: the 73-slot emit table, the caps mirror and R-8's liveness gates. -// The helper cases below are supplemented by RemoteClientControls.inc: installed producers -// over a live session, with adversarial peer replies and a repeated-make-current control. -// -// IT LINKS gtest RATHER THAN gtest_main AND CARRIES ITS OWN main(), for PipeWireCodecTest's and -// PipeInputsTest's reason: the Fatal arms report through MGLOG_F + std::abort, and MGLOG_F -// writes to STDOUT and to a named file, NEVER to stderr - so EXPECT_DEATH's stderr regex could -// only ever match the empty string. A case that drives one FORKS and reads the Fatal line back -// out of a log file this process names before anything logs. That is what makes each control -// assert ITS OWN failure string (R-16) instead of asserting that something, somewhere, died. +// Unit coverage for the emit table and capability gates. RemoteClientControls.inc exercises +// installed producers over a live session. +// Forked controls read the diagnostic from a named log because the logger can omit stderr. #include #include @@ -45,6 +38,8 @@ #include #include #include +#include +#include #include #include #include @@ -65,6 +60,7 @@ #include #include #include +#include #include #include #include