diff --git a/CMakeLists.txt b/CMakeLists.txt index de68a52d..d40dfbe9 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -646,6 +646,7 @@ if (MOBILEGL_BUILD_DISAGGREGATED) MobileGL/MG_Remote/FatalFunnel.cpp MobileGL/MG_Remote/Wire/PipeWireCodec.cpp MobileGL/MG_Remote/Client/ClientSession.cpp +MobileGL/MG_Remote/Client/DmaBufImport.cpp MobileGL/MG_Remote/Client/EmitTables.cpp MobileGL/MG_Remote/Client/CapsMirror.cpp # P5 c1: the client role's BackendObject. pActiveBackendObject holds one of these @@ -824,6 +825,17 @@ target_link_libraries(${CMAKE_PROJECT_NAME} ${MOBILEGL_LINK_LIBRARIES} ) +# A LINUX BUILD COMPILES THE DirectVulkan BACKEND BUT HAS NO VULKAN LOADER TO LINK AGAINST, so the +# resulting shared library carries undefined vk* symbols - and that is not theoretical: glvnd dlopens +# this file as the EGL vendor with RTLD_NOW, so the load fails outright with "undefined symbol: +# vkGetQueryPoolResults" (measured on the phone's container). Android links the loader already; on +# Linux the caller passes the runtime's own libvulkan.so.1, and leaving the variable empty keeps the +# previous behaviour for every build that has no Vulkan runtime to point at. +set(MOBILEGL_VULKAN_LOADER "" CACHE FILEPATH "Vulkan loader (libvulkan.so.1) to link into the GL library") +if (UNIX AND NOT ANDROID AND MOBILEGL_VULKAN_LOADER) + target_link_libraries(${CMAKE_PROJECT_NAME} PRIVATE ${MOBILEGL_VULKAN_LOADER}) +endif() + target_compile_definitions(${CMAKE_PROJECT_NAME} PUBLIC ${MOBILEGL_COMPILE_DEF} diff --git a/MobileGL/Defines.h b/MobileGL/Defines.h index 3fabfc82..5a15ceb2 100644 --- a/MobileGL/Defines.h +++ b/MobileGL/Defines.h @@ -8,6 +8,8 @@ #pragma once +#include + // ============== Platform-specific definitions and macros ============== // // No __ANDROID_API__ pin here on purpose. The effective API level is owned by // the build system (gradle minSdk 26 -> -DANDROID_PLATFORM=android-26, enforced @@ -110,8 +112,8 @@ #define MOBILEGL_ASSERT(condition, ...) \ do { \ if (!(condition)) { \ - MGLOG_F("Assertion failed" __VA_OPT__(": ") __VA_ARGS__); \ - MGLOG_F(" at %s:%d (%s)", __FILE__, __LINE__, __func__); \ + fprintf(stderr, "Assertion failed" __VA_OPT__(": ") "%s", "" __VA_ARGS__); \ + fprintf(stderr, " at %s:%d (%s)\n", __FILE__, __LINE__, __func__); \ TRAP; \ } \ } while (0) diff --git a/MobileGL/MG_Backend/BackendObject.cpp b/MobileGL/MG_Backend/BackendObject.cpp index 04b3a30d..e1e31c80 100644 --- a/MobileGL/MG_Backend/BackendObject.cpp +++ b/MobileGL/MG_Backend/BackendObject.cpp @@ -346,6 +346,29 @@ namespace MobileGL::MG_Backend { MGLOG_E("MakeEGLCurrent failed: EGL display mismatch or not initialized"); return false; } + // EGL_KHR_surfaceless_context. A context whose draw and read surfaces are both absent has + // no framebuffer of its own to be bound to: the caller draws into framebuffers it binds + // itself, and this side only has to have its own GL context current on this thread for the + // records that follow. Everything below this point describes a surface, so none of it + // applies - and what is recorded is exactly what was asked for, so a later swap on a + // surface that does not exist is never made to look like one that does. + if (draw == EGL_NO_SURFACE && read == EGL_NO_SURFACE && ctx != EGL_NO_CONTEXT) { + if (!m_backendCapabilitiesInitialized) { + if (!InitCapabilities()) { + MGLOG_E("MakeEGLCurrent failed: InitCapabilities failed"); + return false; + } + m_backendCapabilitiesInitialized = true; + } + ReleaseEGLCurrentThread(threadKey); + m_eglCurrentThreads[threadKey] = EGLCurrentState{ + .Display = dpy, + .DrawSurface = EGL_NO_SURFACE, + .ReadSurface = EGL_NO_SURFACE, + .Context = ctx, + }; + return true; + } if (!m_eglSurfaceInitialized) { if (draw != read || !ActivateEGLSurface(draw)) { MGLOG_E("MakeEGLCurrent failed: EGL surface is not initialized"); diff --git a/MobileGL/MG_Backend/DirectGLES/BackendObject_DirectGLES.cpp b/MobileGL/MG_Backend/DirectGLES/BackendObject_DirectGLES.cpp index 34092770..22024191 100644 --- a/MobileGL/MG_Backend/DirectGLES/BackendObject_DirectGLES.cpp +++ b/MobileGL/MG_Backend/DirectGLES/BackendObject_DirectGLES.cpp @@ -6,6 +6,12 @@ // SPDX-License-Identifier: LGPL-3.0-only // End of Source File Header +#if MOBILEGL_BUILD_DISAGGREGATED && defined(__ANDROID__) +// The role's own backend is resolved the way Utils.cpp (C6 / ID-52) resolves it; that needs this +// header, and it has to be included at file scope - a header included inside this file's namespace +// would nest its own namespace under it. +#include +#endif #include "BackendObject_DirectGLES.h" #include "MG_Backend/BackendObject.h" #include "MG_Backend/BackendObjects.h" @@ -1036,6 +1042,20 @@ namespace MobileGL::MG_Backend::DirectGLES { constexpr Int kHostFrameWaitMs = 30000; } + Bool TakeHostFrameForExternalTexture(Uint width, Uint height) { + // THIS ROLE'S OWN BACKEND, resolved exactly the way ActiveBackendFormatCaps (Utils.cpp, + // C6 / ID-52) resolves it: under a live split session the SERVER's private backend owns the + // context on the apply thread, and pActiveBackendObject is the CLIENT's mirror there. + MG_Backend::BackendObject* backend = nullptr; + if (MG_Config::Transport != MG_Config::TransportMode::Monolith) { + backend = MG_Remote::Server::ServerLoopInstance().Backend(); + } else { + backend = MG_Backend::pActiveBackendObject.get(); + } + if (backend == nullptr) return false; + return backend->InitHostFrameSurface(static_cast(width), static_cast(height)); + } + Bool BackendObject_DirectGLES::InitHostFrameSurface(EGLint width, EGLint height) { // The EGL context comes from the same place a pbuffer session's does. What changes is not // how this side draws but what it draws INTO: a frame the display host allocated, bound as @@ -1078,6 +1098,12 @@ namespace MobileGL::MG_Backend::DirectGLES { // BEFORE the bind: every default-framebuffer bind the engine makes from here on has to // resolve to this frame, and that resolution is what this global is. g_hostFrameFramebufferId = m_hostFrameTarget.Framebuffer; + // Published together with the framebuffer, because they describe the same frame: the STORAGE + // an attachment is bound to when the client's texture has none of its own (the frame's own + // renderbuffer), and the SIZE that decides whether binding it is right at all. + g_hostFrameRenderbuffer = m_hostFrameTarget.Renderbuffer; + g_hostFrameWidth = m_hostFrameTarget.Width; + g_hostFrameHeight = m_hostFrameTarget.Height; FramebufferImpl::InvalidateFramebufferBindingCache(); HostFrameTargetBind(m_hostFrameTarget); // AND ON TO THE CONTAINER, as the dma-buf descriptor behind it. The Wayland compositor @@ -1102,21 +1128,24 @@ namespace MobileGL::MG_Backend::DirectGLES { void BackendObject_DirectGLES::DestroyHostFrame() { g_hostFrameFramebufferId = 0; + g_hostFrameRenderbuffer = 0; + g_hostFrameWidth = 0; + g_hostFrameHeight = 0; HostFrameTargetDestroy(m_hostFrameTarget); if (m_hostFrameBuffer != nullptr) { AHardwareBuffer_release(m_hostFrameBuffer); m_hostFrameBuffer = nullptr; } - // THE CONNECTION THAT DESCRIBED IT GOES WITH IT. Every frame this side drops is one the - // container was told to render into by descriptor, and a channel left open across that - // would go on describing frames as if the one it named were still the draw target - so - // the connection ends here, the container falls back to allocating frames of its own - // (the state it starts in), and the next frame taken opens the socket again and is - // offered to whoever dials. Close() is idempotent and safe from a destructor, which is - // also what the member's own does at backend teardown, so this call costs the paths that - // drop nothing - a take that replaces the frame, a teardown before the first one - a - // handful of integer tests. - m_gbmFrameChannel.Close(); + // AND NOTHING IS SAID TO THE CHANNEL HERE, which is the fix rather than an omission. This + // runs once per presented frame: it used to Close() the channel (unlinking the container's + // socket node and dropping its connection sixty times a second - measured: connect() + // answered EAGAIN(11) on every attempt) and it used to tell the channel to forget the frame, + // which left the ONE window a compositor's first allocations arrive in - between this frame + // being presented and the host handing the next one over, i.e. inside Complete() above - + // with nothing to answer a dialer with. A compositor allocates its swapchain ONCE and keeps + // those buffers for the life of the process, so a dialer that finds nothing here renders + // its whole life into buffers nobody displays. The frame the channel remembers is the last + // one the host handed over: the next offer replaces it and Close() releases it. } Bool BackendObject_DirectGLES::PresentHostFrame() { @@ -1147,6 +1176,11 @@ namespace MobileGL::MG_Backend::DirectGLES { #else // !(MOBILEGL_BUILD_DISAGGREGATED && __ANDROID__) + // The other arm's half: on a build with no host frames there is no frame to take, and the + // attach site's ordinary path (a storage-less external texture, exactly as before) is the honest + // behaviour there rather than a link error. + Bool TakeHostFrameForExternalTexture(Uint, Uint) { return false; } + Bool BackendObject_DirectGLES::InitHostFrameSurface(EGLint width, EGLint height) { (void)width; (void)height; @@ -1188,13 +1222,42 @@ namespace MobileGL::MG_Backend::DirectGLES { MGLOG_E("MakeEGLCurrent failed: EGL display mismatch or not initialized"); return false; } - if (!m_eglSurfaceInitialized) { - MGLOG_E("MakeEGLCurrent failed: EGL surface is not initialized"); - return false; + // EGL_KHR_surfaceless_context, WHICH IS THE SHAPE A COMPOSITOR ASKS FOR. Its context has no + // draw surface of its own - every frame goes into a framebuffer it binds itself, and under + // this project that framebuffer is one of the display host's frames - so the surface checks + // below describe a surface that legitimately does not exist. What the server still needs is + // its own GL context current on this thread for the records that follow, and that is what + // the native bind underneath them does. + const Bool surfaceless = draw == EGL_NO_SURFACE && read == EGL_NO_SURFACE && ctx != EGL_NO_CONTEXT; + if (surfaceless && !m_eglSurfaceInitialized) { + // A DRAWABLE OF THIS SIDE'S OWN, WHICH IS WHAT A SURFACELESS CLIENT LEAVES TO US. The + // backend's native context has to be current on a surface of some kind before a single + // record of the client's can run - that is what the Init*Surface calls establish - and a + // client that makes its context current with no surface at all supplies none of its own. + // A pbuffer is the one that costs nothing to keep: it is never scanned out and never + // read, because every frame the client draws goes into a framebuffer it binds itself. + // The client is NOT told it has a surface - m_eglSurface stays EGL_NO_SURFACE - so a + // swap on one is still the refusal it was. + if (!InitPbufferSurface(1, 1)) { + MGLOG_E("MakeEGLCurrent failed: the backend's own drawable for a surfaceless context could not " + "be created"); + return false; + } + m_eglSurface = EGL_NO_SURFACE; + m_eglSurfaceInitialized = true; + m_eglSurfaceKind = SurfaceKind::Pbuffer; + m_eglCurrentThreads.clear(); + m_backendCapabilitiesInitialized = false; } - if (draw == EGL_NO_SURFACE || read == EGL_NO_SURFACE || ctx == EGL_NO_CONTEXT) { - MGLOG_E("MakeEGLCurrent failed: draw/read/context is invalid"); - return false; + if (!surfaceless) { + if (!m_eglSurfaceInitialized) { + MGLOG_E("MakeEGLCurrent failed: EGL surface is not initialized"); + return false; + } + if (draw == EGL_NO_SURFACE || read == EGL_NO_SURFACE || ctx == EGL_NO_CONTEXT) { + MGLOG_E("MakeEGLCurrent failed: draw/read/context is invalid"); + return false; + } } #if MOBILEGL_BUILD_DISAGGREGATED @@ -1222,9 +1285,9 @@ namespace MobileGL::MG_Backend::DirectGLES { // function table instead of 1), or make NativeBindCanBeSkippedFor answer true for any tuple // (the ID-67 control's different tuple stays at 1 native bind where 2 are required). const Bool nativelyCurrentAlready = MG_Config::Transport != MG_Config::TransportMode::Monolith && - m_eglSurfaceInitialized && m_eglSurface == draw && DirectGLES::IsBackendContextCurrentOnThisThread() && - NativeBindCanBeSkippedFor(dpy, draw, read, ctx); + (surfaceless || (m_eglSurfaceInitialized && m_eglSurface == draw && + NativeBindCanBeSkippedFor(dpy, draw, read, ctx))); if (!nativelyCurrentAlready && !DirectGLES::MakeCurrent()) { NoteNativeContextGone(); return false; @@ -1408,7 +1471,40 @@ namespace MobileGL::MG_Backend::DirectGLES { // Advertised with GL_NUM_PROGRAM_BINARY_FORMATS = 0, which the // extension explicitly permits. It is also the only thing that // exposes glProgramParameteri before GL 4.1. - E_GL_ARB_get_program_binary}; + E_GL_ARB_get_program_binary, + // kwin_wayland 6.7.3 will not use a context it cannot drive, and it asks for these + // three names first: EglContext::checkSupported() (src/opengl/eglcontext.cpp) takes the + // DESKTOP-OpenGL branch for every context whose GL_VERSION is not an "OpenGL ES" + // string, and that branch requires GL_ARB_shader_objects, GL_ARB_fragment_shader and + // GL_ARB_vertex_shader. GL_VERSION here is "4.6.0 MobileGL ...", so with the names + // missing checkSupported() answered false, EglContext::create() returned nullptr, + // EglBackend::createContext() returned false, and kwin printed "Could not initialize + // rendering context" and quit before drawing a frame. + // + // The three are true statements about this backend now rather than a test unlock: every + // procedure they define is implemented in MG_Impl/GLImpl/Exporting/Definitions.cpp over + // the same shader and program objects the core entry points drive - the 39 of + // ARB_shader_objects, ARB_vertex_shader's three attrib-location entry points, and none + // at all for ARB_fragment_shader ("New Procedures and Functions: None" - it is the + // capability half, and the reason kwin's conjunction names it). + E_GL_ARB_shader_objects, E_GL_ARB_vertex_shader, E_GL_ARB_fragment_shader, + // NPOT textures: core since GL 2.0, and every host this backend can run on provides + // them. Full non-power-of-two support - mipmapping and every wrap mode, not ES 2.0's + // CLAMP_TO_EDGE-only exception - is required from ES 3.0 on, and the entries this list + // already advertises without any gate (compute shaders, shader storage buffers, + // indirect draws) need an ES 3.1 host. Nothing in the texture path rejects or pads a + // non-power-of-two size - storage and sampling are forwarded to that host - so the + // string describes what an application actually gets. + E_GL_ARB_texture_non_power_of_two, + // GL_OES_EGL_image: the entry points are real (MG_Impl/GLImpl/Exporting/Definitions.cpp) + // and this name is what makes them reachable - libepoxy in kwin resolves + // glEGLImageTargetTexture2DOES BY NAME and refuses the import path without it, printing + // "No provider of glEGLImageTargetTexture2DOES found. Requires one of: GL_OES_EGL_image". + // That import path is how the compositor's scene reaches the display daemon's dma-bufs. + // The render-server half of the import (fd over the GBM socket, then the server-side + // EGLImage) is the next change; until it lands an imported texture has no storage behind + // it, which is logged once at the entry point rather than left to look like a black frame. + E_GL_OES_EGL_image}; // Minecraft 26.3 checks this prerequisite before it even considers // GL_ARB_multi_draw_indirect. ES 3.1 supplies both single-draw entry points; the loader // folds the version and pointer checks into SupportsDrawIndirect. diff --git a/MobileGL/MG_Backend/DirectGLES/BackendObject_DirectGLES.h b/MobileGL/MG_Backend/DirectGLES/BackendObject_DirectGLES.h index 5c91315d..a48ef2b2 100644 --- a/MobileGL/MG_Backend/DirectGLES/BackendObject_DirectGLES.h +++ b/MobileGL/MG_Backend/DirectGLES/BackendObject_DirectGLES.h @@ -10,6 +10,7 @@ #include #include "HostFrameTarget.h" #include "MG_Backend/HostFrameBridge.h" +#include "MG_Backend/GbmFrameChannel.h" #include "../BackendObject.h" #include @@ -74,6 +75,10 @@ namespace MobileGL::MG_Backend::DirectGLES { // is what the host offers - it hands one over and waits for the answer before it // presents it and offers the next. MG_Backend::HostFrameBridge m_hostFrameBridge; + // The frames the bridge just took, on to the container: the Wayland compositor over there + // renders into this same memory, and the only route to it that end has is the dma-buf + // descriptor this channel offers per frame and reads a release back from. + MG_Backend::GbmFrameChannel m_gbmFrameChannel; HostFrameTarget m_hostFrameTarget; struct AHardwareBuffer* m_hostFrameBuffer = nullptr; MG_Backend::HostFrameOffer m_hostFrameOffer{}; diff --git a/MobileGL/MG_Backend/DirectGLES/DirectGLES.cpp b/MobileGL/MG_Backend/DirectGLES/DirectGLES.cpp index 51a8387e..3b0137a4 100644 --- a/MobileGL/MG_Backend/DirectGLES/DirectGLES.cpp +++ b/MobileGL/MG_Backend/DirectGLES/DirectGLES.cpp @@ -88,6 +88,9 @@ namespace MobileGL::MG_Backend::DirectGLES { MG_External::EGLFunctionsTable g_EGLFuncs; Uint g_hostFrameFramebufferId = 0; + Uint g_hostFrameRenderbuffer = 0; + Uint g_hostFrameWidth = 0; + Uint g_hostFrameHeight = 0; MG_External::GLESFunctionsTable g_GLESFuncs; MG_External::GLESCapabilities g_GLESCapabilities; diff --git a/MobileGL/MG_Backend/DirectGLES/DirectGLES.h b/MobileGL/MG_Backend/DirectGLES/DirectGLES.h index 43aea248..38b724a0 100644 --- a/MobileGL/MG_Backend/DirectGLES/DirectGLES.h +++ b/MobileGL/MG_Backend/DirectGLES/DirectGLES.h @@ -254,6 +254,21 @@ namespace MobileGL::MG_Backend::DirectGLES { // then - but on a host-framed surface the pixels belong to a frame the display host owns, // and drawing into the driver's 0 would draw into a pbuffer nobody ever sees. extern Uint g_hostFrameFramebufferId; + // WHAT THE HOST FRAME'S STORAGE IS, for the one caller that has to bind it in place of a + // storage-less attachment: an imported dma-buf is the display host's frame (same memory, same + // size), and the frame's storage is a RENDERBUFFER (HostFrameTarget.cpp binds it with + // glFramebufferRenderbuffer). A texture argument cannot name it, which is why these exist and + // why g_hostFrameFramebufferId alone was not enough. Zero whenever no frame is held. + extern Uint g_hostFrameRenderbuffer; + extern Uint g_hostFrameWidth; + extern Uint g_hostFrameHeight; + // TAKE THE FRAME WHEN NOTHING ELSE WILL. On the anland route the container's compositor never + // creates a window surface, so ActivateEGLSurface never runs and InitHostFrameSurface is never + // reached: the FIRST proof that the display host's frame is wanted is an ATTACHMENT of an + // imported external texture (Managers.cpp's 0x8D65 arm), and that is where the frame has to be + // taken. The host's own offer carries the width/height, so the numbers passed here are only + // what the bridge logs. Answers false (and changes nothing) whenever no backend is up. + Bool TakeHostFrameForExternalTexture(Uint width, Uint height); extern MG_External::EGLFunctionsTable g_EGLFuncs; extern MG_External::GLESFunctionsTable g_GLESFuncs; extern MG_External::GLESCapabilities g_GLESCapabilities; diff --git a/MobileGL/MG_Backend/DirectGLES/Managers.cpp b/MobileGL/MG_Backend/DirectGLES/Managers.cpp index 726a05ae..57db0774 100644 --- a/MobileGL/MG_Backend/DirectGLES/Managers.cpp +++ b/MobileGL/MG_Backend/DirectGLES/Managers.cpp @@ -10151,7 +10151,7 @@ namespace MobileGL::MG_Backend::DirectGLES { } MGLOG_D("Texture state changed significantly or not initialized, regenerating texture buffer with " "ID: %u, buffer ID: %u, buffer size: %zu, format: %s", - m_backendTextureId, backendId, buffer ? buffer->GetSize() : rangeSize, + m_backendTextureId, backendId, buffer ? buffer->GetSize() : (SizeT)0, MG_Util::ConvertGLEnumToString(glInternalFormat).c_str()); // A texture that names a window of the buffer needs the range form; the // whole-buffer forms report offset 0 and the buffer's current size, which @@ -11282,9 +11282,38 @@ namespace MobileGL::MG_Backend::DirectGLES { const Bool isCubeFace = glTextureTarget >= GL_TEXTURE_CUBE_MAP_POSITIVE_X && glTextureTarget <= GL_TEXTURE_CUBE_MAP_NEGATIVE_Z; backendTextureObject->Bind(isCubeFace ? GL_TEXTURE_CUBE_MAP : glTextureTarget); - g_GLESFuncs.glFramebufferTexture2D(glFBOTarget, glBackendAttachment, glTextureTarget, - backendTextureObject->GetBackendTextureId(), - static_cast(attachmentObject.GetTextureLevel())); + if (glTextureTarget == 0x8D65 && g_hostFrameRenderbuffer == 0) { + // NOBODY ELSE TAKES THE FRAME ON THIS ROUTE (DirectGLES.h): the compositor + // here never creates a window surface, so this attachment is the first place + // the display host's frame is known to be wanted. A failed take leaves the + // ordinary arm below exactly as it was. + // The numbers size only the fallback pbuffer that is the draw target for the + // moment before the first frame arrives; the frame's real extent comes from the + // display host's own offer. They are the panel's, because that is the surface + // this route exists to fill. + (void)TakeHostFrameForExternalTexture(1440, 3200); + } + if (glTextureTarget == 0x8D65 && g_hostFrameRenderbuffer != 0) { + // THE IMPORTED dma-buf IS THE DISPLAY HOST'S FRAME. Measured, and the whole reason + // this branch exists: kwin_wayland in the container imports the display daemon's + // dma-buf as an EGLImage ("taking target 0x8d65 over an EGLImage of 1440x2937 + // fourcc 0x34324241") and builds a framebuffer over that texture - and a texture + // that arrived this way has NO storage on this side, so the attachment was bound + // as an empty texture and kwin refused its own framebuffer ("framebuffer for + // dmabuf 0 is not complete"). The buffer it imports IS the frame the display + // host handed this process (same memory, same size), and that frame's storage is + // a RENDERBUFFER - a texture argument cannot name it - so the attachment is bound + // to the frame itself. The gate is the measured shape of that case: target + // GL_TEXTURE_EXTERNAL_OES (0x8d65), which nothing else in this stack binds, and a + // frame currently held. Every other attachment - a normal GL_TEXTURE_2D, or any + // moment with no frame - takes the ordinary path below, unchanged. + g_GLESFuncs.glFramebufferRenderbuffer(glFBOTarget, glBackendAttachment, GL_RENDERBUFFER, + g_hostFrameRenderbuffer); + } else { + g_GLESFuncs.glFramebufferTexture2D(glFBOTarget, glBackendAttachment, glTextureTarget, + backendTextureObject->GetBackendTextureId(), + static_cast(attachmentObject.GetTextureLevel())); + } } } else if (attachmentObject.IsRenderbuffer()) { const auto& renderbufferObject = attachmentObject.GetRenderbuffer(); @@ -11683,9 +11712,38 @@ namespace MobileGL::MG_Backend::DirectGLES { const Bool isCubeFace = glTextureTarget >= GL_TEXTURE_CUBE_MAP_POSITIVE_X && glTextureTarget <= GL_TEXTURE_CUBE_MAP_NEGATIVE_Z; backendTextureObject->Bind(isCubeFace ? GL_TEXTURE_CUBE_MAP : glTextureTarget); - g_GLESFuncs.glFramebufferTexture2D(glFBOTarget, glBackendAttachment, glTextureTarget, - backendTextureObject->GetBackendTextureId(), - static_cast(surface.Level)); + if (glTextureTarget == 0x8D65 && g_hostFrameRenderbuffer == 0) { + // NOBODY ELSE TAKES THE FRAME ON THIS ROUTE (DirectGLES.h): the compositor + // here never creates a window surface, so this attachment is the first place + // the display host's frame is known to be wanted. A failed take leaves the + // ordinary arm below exactly as it was. + // The numbers size only the fallback pbuffer that is the draw target for the + // moment before the first frame arrives; the frame's real extent comes from the + // display host's own offer. They are the panel's, because that is the surface + // this route exists to fill. + (void)TakeHostFrameForExternalTexture(1440, 3200); + } + if (glTextureTarget == 0x8D65 && g_hostFrameRenderbuffer != 0) { + // THE IMPORTED dma-buf IS THE DISPLAY HOST'S FRAME. Measured, and the whole reason + // this branch exists: kwin_wayland in the container imports the display daemon's + // dma-buf as an EGLImage ("taking target 0x8d65 over an EGLImage of 1440x2937 + // fourcc 0x34324241") and builds a framebuffer over that texture - and a texture + // that arrived this way has NO storage on this side, so the attachment was bound + // as an empty texture and kwin refused its own framebuffer ("framebuffer for + // dmabuf 0 is not complete"). The buffer it imports IS the frame the display + // host handed this process (same memory, same size), and that frame's storage is + // a RENDERBUFFER - a texture argument cannot name it - so the attachment is bound + // to the frame itself. The gate is the measured shape of that case: target + // GL_TEXTURE_EXTERNAL_OES (0x8d65), which nothing else in this stack binds, and a + // frame currently held. Every other attachment - a normal GL_TEXTURE_2D, or any + // moment with no frame - takes the ordinary path below, unchanged. + g_GLESFuncs.glFramebufferRenderbuffer(glFBOTarget, glBackendAttachment, GL_RENDERBUFFER, + g_hostFrameRenderbuffer); + } else { + g_GLESFuncs.glFramebufferTexture2D(glFBOTarget, glBackendAttachment, glTextureTarget, + backendTextureObject->GetBackendTextureId(), + static_cast(surface.Level)); + } } return true; } diff --git a/MobileGL/MG_Backend/DirectVulkan/BackendObject_DirectVulkan.cpp b/MobileGL/MG_Backend/DirectVulkan/BackendObject_DirectVulkan.cpp index f38eb944..4dfa0292 100644 --- a/MobileGL/MG_Backend/DirectVulkan/BackendObject_DirectVulkan.cpp +++ b/MobileGL/MG_Backend/DirectVulkan/BackendObject_DirectVulkan.cpp @@ -659,7 +659,38 @@ namespace MobileGL::MG_Backend::DirectVulkan { // Advertised with GL_NUM_PROGRAM_BINARY_FORMATS = 0, which the // extension explicitly permits. It is also the only thing that // exposes glProgramParameteri before GL 4.1. - E_GL_ARB_get_program_binary}; + E_GL_ARB_get_program_binary, + // kwin_wayland 6.7.3 will not use a context it cannot drive, and it asks for these + // three names first: EglContext::checkSupported() (src/opengl/eglcontext.cpp) takes the + // DESKTOP-OpenGL branch for every context whose GL_VERSION is not an "OpenGL ES" + // string, and that branch requires GL_ARB_shader_objects, GL_ARB_fragment_shader and + // GL_ARB_vertex_shader. GL_VERSION here is "4.6.0 MobileGL ...", so with the names + // missing checkSupported() answered false, EglContext::create() returned nullptr, + // EglBackend::createContext() returned false, and kwin printed "Could not initialize + // rendering context" and quit before drawing a frame. + // + // The three are true statements about this backend too, and the entry points behind + // them are the same ones the DirectGLES half of this list is advertised with: the + // frontend implements all 39 ARB_shader_objects procedures, ARB_vertex_shader's three + // attrib-location entry points, and nothing for ARB_fragment_shader, whose "New + // Procedures and Functions" section reads "None". The shader and program objects live in + // MG_Impl/MG_State, above the backend that draws with them, so a name that is true on + // one backend is true on the other. + E_GL_ARB_shader_objects, E_GL_ARB_vertex_shader, E_GL_ARB_fragment_shader, + // NPOT textures: Vulkan puts no power-of-two restriction on an image, its mip chain or + // its samplers, so this is the strongest form of the promise the string makes. Kept + // identical to the DirectGLES group so the two backends do not disagree about what + // MobileGL is. + E_GL_ARB_texture_non_power_of_two, + // GL_OES_EGL_image: the entry points are real (MG_Impl/GLImpl/Exporting/Definitions.cpp) + // and this name is what makes them reachable - libepoxy in kwin resolves + // glEGLImageTargetTexture2DOES BY NAME and refuses the import path without it, printing + // "No provider of glEGLImageTargetTexture2DOES found. Requires one of: GL_OES_EGL_image". + // That import path is how the compositor's scene reaches the display daemon's dma-bufs. + // The render-server half of the import (fd over the GBM socket, then the server-side + // EGLImage) is the next change; until it lands an imported texture has no storage behind + // it, which is logged once at the entry point rather than left to look like a black frame. + E_GL_OES_EGL_image}; // Vulkan's drawIndirectFirstInstance feature is optional. Direct base-instance calls work // without it, but ARB_base_instance also promises non-zero firstInstance in GPU indirect // commands; the renderer supplies true only when that word is legal and gl_InstanceID can diff --git a/MobileGL/MG_Backend/GbmFrameChannel.cpp b/MobileGL/MG_Backend/GbmFrameChannel.cpp index e1377b50..7211a5c3 100644 --- a/MobileGL/MG_Backend/GbmFrameChannel.cpp +++ b/MobileGL/MG_Backend/GbmFrameChannel.cpp @@ -55,6 +55,17 @@ namespace MobileGL::MG_Backend { // loop to exhaustion: the messages left behind stay in the socket, whose buffer the kernel // bounds, and the next frame drains them. constexpr Int kDrainMax = 64; + // HOW MANY DIALERS THE KERNEL MAY HOLD FOR THIS LISTENER. One container is the protocol, + // but the queue is not the connection: every compositor that was restarted dials once more, + // and a listener that only ever has one slot leaves its queue full for the next one. With + // listen(fd, 1) that is exactly what was measured - connect() from the container answered + // EAGAIN(11) on four attempts out of four after two restarts, and no dialer reached this + // side again for as long as the server lived. + constexpr Int kDialerBacklog = 16; + // The acceptor's poll timeout. It is a wake-up and not a schedule, so it only has to be + // short enough that a container dialling into a socket nothing else touches is taken + // promptly; a dialer that arrives while the thread is waiting wakes it at once. + constexpr Int kAcceptPollMs = 100; // How long the relay read waits for bytes the send one statement earlier has already put in // the socket. It exists only so that an invariant broken somewhere else cannot park the // apply thread; on a local socketpair the wait is zero. @@ -73,6 +84,7 @@ namespace MobileGL::MG_Backend { GbmFrameChannel::~GbmFrameChannel() { Close(); } Bool GbmFrameChannel::Open() { + const std::lock_guard lock(m_mutex); if (m_listen >= 0) return true; const char* configured = ::getenv(kGbmFrameSocketEnv); @@ -123,7 +135,7 @@ namespace MobileGL::MG_Backend { "this socket", path, std::strerror(errno)); } - if (::listen(fd, 1) != 0) { + if (::listen(fd, kDialerBacklog) != 0) { MGLOG_E_ONCE("gbm frame channel: listen(%s): %s; the frames are drawn and presented without a container", path, std::strerror(errno)); ::unlink(path); @@ -133,6 +145,22 @@ namespace MobileGL::MG_Backend { m_listen = fd; m_path = path; + // THE ACCEPTOR IS STARTED WITH THE SOCKET AND NOT WITH THE FIRST FRAME. A compositor dials + // at its device creation and keeps the connection, so the dial a frame would have answered + // has already happened by the time that frame is offered: an accept on the offer path is an + // accept that runs after the thing it exists for. The descriptor is copied into the thread + // as an argument - it is the one piece of this object the thread reads without the lock, + // which is what lets Close() join it before closing that descriptor. + m_accepting.store(true, std::memory_order_release); + try { + m_acceptor = std::thread(&GbmFrameChannel::AcceptLoop, this, fd); + } catch (...) { + // A thread that cannot be made is a phone that is out of them, not a reason to refuse + // the frames the container can still be given one at a time. + m_accepting.store(false, std::memory_order_release); + MGLOG_W_ONCE("gbm frame channel: the acceptor thread could not be started; a container is only taken in " + "when a frame is offered, and one that dials between frames waits for the next one"); + } MGLOG_I("gbm frame channel: listening on %s for one container (SOCK_SEQPACKET, one message per frame)", path); return true; } @@ -276,41 +304,106 @@ namespace MobileGL::MG_Backend { return false; } - payloadBytes = (SizeT)got; + // THE BYTES THAT COME BACK ARE THE HANDLE'S INTEGER ARRAY, NOT A handle AND ITS COUNTS. + // Measured on the phone: parsing the front of this payload as {version, numFds, numInts} + // produced a NumFds taken from the buffer's own integer data, and every frame was refused + // with "its handle carries more descriptors than either end takes" - which is what the + // container saw as a connection that was accepted and then closed without a frame. The two + // counts are known HERE and are not in those bytes: the descriptors came out of the control + // data (collected of them) and the payload is their integer array. So the header is BUILT + // rather than copied, and what leaves this process is a real native_handle_t layout - + // version, numFds, numInts, then the ints - which is exactly what the container's parser + // reads (GbmInternal.h's AHBNativeHandleHeader). + if (payloadBytes + sizeof(GbmNativeHandleHeader) > capacity) { + MGLOG_W_ONCE("gbm frame channel: a handle's integer array does not fit in a frame message with its " + "header; the frame is not offered to the container"); + for (Int i = 0; i < collected; ++i) CloseQuietly(fds[i]); + DropRelay(); + return false; + } + std::memmove(payload + sizeof(GbmNativeHandleHeader), payload, payloadBytes); + GbmNativeHandleHeader header = {}; + header.Version = (Int32)sizeof(GbmNativeHandleHeader); + header.NumFds = (Int32)collected; + header.NumInts = (Int32)(payloadBytes / sizeof(Int32)); + std::memcpy(payload, &header, sizeof(header)); + payloadBytes += sizeof(header); fdCount = collected; return true; } - void GbmFrameChannel::AcceptDialer() { - if (m_listen < 0) return; - // accept4, so the connection is close-on-exec and non-blocking from the moment it exists: a - // container that stops reading must not be able to park a send on the apply thread. - const Int fd = ::accept4(m_listen, nullptr, nullptr, SOCK_CLOEXEC | SOCK_NONBLOCK); - if (fd < 0) { - // EAGAIN is nobody dialling, which is the ordinary state of a phone whose container is - // not running. The rest are worth one line between them: the listener outlives them and - // the next frame tries again. - if (errno != EAGAIN && errno != EWOULDBLOCK && errno != EINTR && errno != ECONNABORTED) { - MGLOG_W_ONCE("gbm frame channel: accept on %s failed (%d: %s); a container cannot connect until the " - "next frame tries again", - m_path.c_str(), errno, std::strerror(errno)); + // The acceptor. It touches the listener - its own copy of the descriptor, which nothing else + // closes while this loop runs - and, once per dialer, the channel under its lock. + void GbmFrameChannel::AcceptLoop(Int listen) { + while (m_accepting.load(std::memory_order_acquire)) { + struct pollfd waiting = {}; + waiting.fd = listen; + waiting.events = POLLIN; + const Int ready = ::poll(&waiting, 1, kAcceptPollMs); + if (ready < 0) { + if (errno == EINTR) continue; + MGLOG_W_ONCE("gbm frame channel: poll on the listening socket failed (%d: %s); no container can be " + "taken in until the socket is opened again", + errno, std::strerror(errno)); + return; } + if (ready == 0) continue; + // accept4, so the connection is close-on-exec and non-blocking from the moment it + // exists: a container that stops reading must not be able to park a send on either + // thread. + const Int fd = ::accept4(listen, nullptr, nullptr, SOCK_CLOEXEC | SOCK_NONBLOCK); + if (fd < 0) { + if (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK || errno == ECONNABORTED) continue; + MGLOG_W_ONCE("gbm frame channel: accept failed (%d: %s); no container can be taken in until the " + "socket is opened again", + errno, std::strerror(errno)); + return; + } + const std::lock_guard lock(m_mutex); + AdoptLocked(fd); + } + } + + void GbmFrameChannel::AdoptLocked(Int fd) { + if (ClientAliveLocked()) { + // ONE CLIENT, which is what the protocol is written for, and a dialer that arrives while + // a live one is connected is closed rather than left connected - it learns it is not the + // one being served instead of holding a connection whose frames nobody reads. + CloseQuietly(fd); + MGLOG_W_ONCE("gbm frame channel: a second peer dialled %s while a container is connected; it is closed " + "and the frames stay with the connected one", + m_path.c_str()); return; } - if (m_client < 0) { - m_client = fd; - MGLOG_I("gbm frame channel: a container is connected on %s; every frame the host offers is sent to it as " - "the dma-buf descriptor behind it", - m_path.c_str()); - return; + m_client = fd; + MGLOG_I("gbm frame channel: a container is connected on %s; every frame the host offers is sent to it as " + "the dma-buf descriptor behind it", + m_path.c_str()); + // AND THE FRAME IT DIALED FOR GOES OUT FROM HERE. A compositor creates its GBM device before + // it asks for a surface, so the frame that is the draw target right now was offered before + // this connection existed; a container that is not told about it allocates every buffer of + // its new swapchain locally, and keeps them for the life of the process. + ReofferFrameLocked(); + } + + Bool GbmFrameChannel::ClientAliveLocked() { + if (m_client < 0) return false; + Uint8 peek = 0; + // MSG_PEEK, because a release waiting in the socket belongs to the render path: this test + // only asks whether the peer is still there, and a release it consumed would be a frame the + // channel believed was still outstanding. + const ssize_t got = ::recv(m_client, &peek, sizeof(peek), MSG_DONTWAIT | MSG_PEEK); + if (got > 0) return true; + if (got == 0) { + // Zero bytes on a connected socket is the end of it, whether the container exited or + // the kernel gave up on it. A compositor that crashed and is being restarted is + // exactly this, and its successor is the dialer standing right here. + MarkDown("the container closed the connection", 0); + return false; } - // ONE CLIENT, which is what the protocol is written for: a second dialer is closed rather - // than left connected, so that it learns it is not the one being served instead of holding a - // connection whose messages nobody reads. - CloseQuietly(fd); - MGLOG_W_ONCE("gbm frame channel: a second peer dialled %s while a container is connected; it is closed and " - "the frames stay with the connected one", - m_path.c_str()); + if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) return true; + MarkDown("recv", errno); + return false; } void GbmFrameChannel::MarkDown(const char* what, Int error) { @@ -332,13 +425,67 @@ namespace MobileGL::MG_Backend { if (buffer == nullptr) return false; // Open() does nothing once the socket exists, so this is an integer test in the common case. Open(); + const std::lock_guard lock(m_mutex); - // Releases first, and the accept after them: a container that has died is noticed and its - // replacement taken before this frame is handed to a socket the kernel has already given up - // on, which is what lets a compositor that restarted receive frames from the very next one - // rather than from the frame after it. - Poll(); - AcceptDialer(); + // The releases the container has sent since the last frame, which is also how a container + // that died is noticed. Whoever replaced it was taken by the acceptor's own thread the + // moment it dialled: that thread is what makes a container's connect() succeed at all. + PollLocked(); + // AND THE FRAME IS REMEMBERED BEFORE IT IS SENT. A container that dials while this call is + // running is one the acceptor hands the frame it finds here to, so the two threads must not + // be able to disagree about which frame is the one being drawn into. + const Uint32 seq = m_nextSeq; + RememberFrameLocked(buffer, offer, seq); + if (m_client < 0) return false; + return SendFrameLocked(buffer, offer, seq, /*counting=*/true); + } + + void GbmFrameChannel::RememberFrameLocked(struct AHardwareBuffer* buffer, const HostFrameOffer& offer, Uint32 seq) { + if (m_frame == buffer) { + // The host redrawing into the buffer it already handed over: the same frame under a new + // sequence number. Acquiring it again would be a reference this channel takes and never + // gives back. + m_frameOffer = offer; + m_frameSeq = seq; + return; + } + // The reference is this channel's own, and it is what makes the frame a container that dials + // late is owed safe to hold: the backend drops its handle the moment the frame is presented, + // and a frame owed to a dialer arriving in the same millisecond may not be memory that has + // already gone back to the host's pool. + AHardwareBuffer_acquire(buffer); + ReleaseFrameLocked(); + m_frame = buffer; + m_frameOffer = offer; + m_frameSeq = seq; + } + + void GbmFrameChannel::ReleaseFrameLocked() { + if (m_frame == nullptr) return; + AHardwareBuffer_release(m_frame); + m_frame = nullptr; + m_frameOffer = {}; + m_frameSeq = 0; + } + + void GbmFrameChannel::DropFrame() { + const std::lock_guard lock(m_mutex); + ReleaseFrameLocked(); + } + + void GbmFrameChannel::ReofferFrameLocked() { + if (m_frame == nullptr) return; + // The same frame, under the sequence number it was offered with: it IS the frame that is the + // draw target now, and a second number for it would be this channel claiming the host had + // handed over a frame it never handed over. + MGLOG_I("gbm frame channel: a container dialled after frame %u was offered; it is sent that frame, which is " + "still the draw target", + m_frameSeq); + SendFrameLocked(m_frame, m_frameOffer, m_frameSeq, /*counting=*/false); + } + + Bool GbmFrameChannel::SendFrameLocked(struct AHardwareBuffer* buffer, const HostFrameOffer& offer, Uint32 seq, + Bool counting) { if (m_client < 0) return false; Uint8 payload[kMessageMax]; @@ -399,7 +546,7 @@ namespace MobileGL::MG_Backend { GbmFrameOffer out = {}; out.Magic = kGbmFrameOfferMagic; out.Version = kGbmFrameVersion; - out.Seq = m_nextSeq; + out.Seq = seq; out.Index = offer.Index; out.Width = offer.Width; out.Height = offer.Height; @@ -437,9 +584,15 @@ namespace MobileGL::MG_Backend { if (sent != (ssize_t)messageBytes) { MarkDown("sendmsg", (sent < 0) ? errno : 0); } else { - m_nextSeq = out.Seq + 1; - ++m_offered; - ++m_outstanding; + // A frame offered for the first time is the next sequence number and one more frame + // outstanding. The same frame sent again to a container that has just dialled is + // neither: the host handed over nothing new, and a count of frames waiting to be + // released may not be moved by a message that describes one already in it. + if (counting) { + m_nextSeq = seq + 1; + ++m_offered; + ++m_outstanding; + } offered = true; // The first offer is the one worth a line, and it carries the host's own numbers: // the format in particular is the field the two ends could disagree about without @@ -461,6 +614,11 @@ namespace MobileGL::MG_Backend { } void GbmFrameChannel::Poll() { + const std::lock_guard lock(m_mutex); + PollLocked(); + } + + void GbmFrameChannel::PollLocked() { if (m_client < 0) return; for (Int drained = 0; drained < kDrainMax; ++drained) { GbmFrameRelease release = {}; @@ -524,6 +682,17 @@ namespace MobileGL::MG_Backend { } void GbmFrameChannel::Close() { + // THE ACCEPTOR IS STOPPED AND JOINED FIRST, and outside the lock. It may be inside that + // lock when this is called - a teardown that waited for it while holding it would wait for + // ever - and it polls the listening descriptor, which may not be closed under it: the next + // open() in this process hands out the descriptor number a moment later, and the thread + // would then be polling somebody else's socket. + m_accepting.store(false, std::memory_order_release); + if (m_acceptor.joinable()) m_acceptor.join(); + const std::lock_guard lock(m_mutex); + // The frame is this channel's reference and is released with it: the backend has already + // dropped its own by the time a teardown here is a teardown of the frame as well. + ReleaseFrameLocked(); // The connection is closed quietly rather than marked down: this is a teardown, not a // failure, and a warning about it would be noise in a log read for the failures. CloseQuietly(m_client); diff --git a/MobileGL/MG_Backend/GbmFrameChannel.h b/MobileGL/MG_Backend/GbmFrameChannel.h index 06b34ac1..c0983529 100644 --- a/MobileGL/MG_Backend/GbmFrameChannel.h +++ b/MobileGL/MG_Backend/GbmFrameChannel.h @@ -83,6 +83,48 @@ namespace MobileGL::MG_Backend { Uint32 Seq; } __attribute__((packed)); + // THE OTHER DIRECTION: A dma-buf THE CONTAINER WANTS THIS SIDE TO BACK A TEXTURE WITH. + // + // The compositor's scene reaches the display daemon's dma-bufs through glEGLImageTargetTexture2DOES + // (MG_Impl/GLImpl/Exporting/Definitions.cpp, MG_Backend/DirectGLES/BackendObject_DirectGLES.cpp both + // name this half as the next change). eglCreateImageKHR has already held a dup() of every plane's + // descriptor since the image was made; what was missing is the render server's half - telling THIS + // side which texture that dma-buf backs, over the one channel that can carry a descriptor across the + // container boundary. This message is that half: the client names the texture target and the + // texture's own name, describes the buffer exactly as drmModeAddFB2 would, and the plane descriptors + // ride in the SCM_RIGHTS control data of the same sendmsg. One message per import, as SEQPACKET + // requires, so a descriptor and its description are never read apart. + // + // The reply is what the client waits for before a framebuffer is allowed to be complete over the + // texture: Ok=0 means this side could not make the import real, and the client keeps treating the + // texture as having no storage rather than letting it render into nothing. + inline constexpr Uint32 kGbmImportRequestMagic = 0x4947474Du; // 'M','G','G','I' in memory order + inline constexpr Uint32 kGbmImportReplyMagic = 0x52474749u; // 'I','G','G','R' in memory order + inline constexpr Uint32 kGbmImportVersion = 1u; + inline constexpr Uint32 kGbmImportMaxPlanes = 4u; + + struct GbmImportRequest { + Uint32 Magic; + Uint32 Version; + Uint32 Target; // the GL texture target the image was bound to (0x8D65 = GL_TEXTURE_EXTERNAL_OES) + Uint32 TexName; // the CLIENT's texture name; this side resolves its twin + Uint32 Width; + Uint32 Height; + Uint32 FourCC; + Uint32 PlaneCount; // 1..kGbmImportMaxPlanes; the descriptors are the message's control data + Int32 Stride[kGbmImportMaxPlanes]; + Int32 Offset[kGbmImportMaxPlanes]; + Uint64 Modifier[kGbmImportMaxPlanes]; + Uint32 HasModifier[kGbmImportMaxPlanes]; + } __attribute__((packed)); + + struct GbmImportReply { + Uint32 Magic; + Uint32 Version; + Uint32 Ok; + Uint32 Reserved; + } __attribute__((packed)); + // An AHardwareBuffer native handle as it appears on the wire: the platform's native_handle_t // (version, then the two counts, then the descriptor array followed by the integer array), // written by AHardwareBuffer_sendHandleToUnixSocket and read by the container's @@ -94,11 +136,21 @@ namespace MobileGL::MG_Backend { Int32 NumInts; } __attribute__((packed)); - // ONE CONTAINER, ONE LISTENING SOCKET, ONE THREAD. + // ONE CONTAINER, ONE LISTENING SOCKET, TWO THREADS: the render path's, and an acceptor's. // - // There is no lock in here on purpose: the channel is opened, offered to and closed from the - // apply thread, which is the one thread that takes the host's frames and draws them, so there - // is no second thread to order against - the same reason HostFrameBridge has none. + // A compositor dials ONCE - when it creates its GBM device - and keeps that connection for the + // life of the process, while this side offers a frame per drawn frame. An accept that only ran + // inside OfferFrame therefore ran after the dial it was supposed to answer, and a dialer that + // nobody took kept the listener's queue full for every later one. That is measured on the + // phone rather than argued: with accept() only on the offer path, connect() from the container + // answered EAGAIN(11) on four attempts out of four while the node sat there listening. + // + // So the accept has a thread of its own, started by Open() and stopped by Close(), and it + // adopts what it takes on the spot - including sending it the frame the host last handed over, + // because a compositor's first allocation is the one its swapchain is built from. The + // connected socket, the frame that is remembered, the relay and the counters are shared between + // the two threads and guarded by the one mutex below; both entry points are non-blocking, so + // neither thread can park the other for longer than a syscall. class GbmFrameChannel { public: GbmFrameChannel() = default; @@ -106,12 +158,13 @@ namespace MobileGL::MG_Backend { GbmFrameChannel& operator=(const GbmFrameChannel&) = delete; ~GbmFrameChannel(); - // Creates the listening socket if it is not there yet, and does nothing otherwise. It - // never waits for a container: the socket is bound, listen(1) is called, and the accept - // happens later, when a frame is actually offered. A caller that wants the container to - // find the socket before the first frame - the container dials once at its own device - // creation and retries about once a second - can call this when the host-framed surface - // is initialized, beside HostFrameBridge::Open. + // Creates the listening socket if it is not there yet and starts the acceptor, and does + // nothing otherwise. It never waits for a container: the socket is bound, a backlog is + // given to listen(), and the acceptor takes whoever dials from then on - whether or not a + // frame is being drawn. A caller that wants the container to find the socket before the + // first frame - the container dials once at its own device creation and retries about once + // a second - can call this when the host-framed surface is initialized, beside + // HostFrameBridge::Open. Bool Open(); // Offers one frame the host just handed over, as the dma-buf descriptor behind it. @@ -126,14 +179,28 @@ namespace MobileGL::MG_Backend { // needs it if it wants releases drained on a path that has no new frame in it. void Poll(); + // The frame the host handed over is gone - it was presented, or it was replaced - and this + // channel may no longer hold it or offer it to anybody. THE CHANNEL ITSELF STAYS OPEN, and + // that is the point of the call: the listening socket, its node and the container's + // connection outlive every frame, and a channel that was closed and reopened per frame took + // the node away sixty times a second - a container dialling at the wrong moment got ENOENT + // for a socket that was there a millisecond earlier and would be there a millisecond later. + void DropFrame(); + // True while a container is connected and the frames are being offered to it. - Bool IsUp() const { return m_client >= 0; } + Bool IsUp() const { + const std::lock_guard lock(m_mutex); + return m_client >= 0; + } // How many frames have been offered and not released, as a count of messages and not a // record of them. It is here to be logged, and it is deliberately the only per-frame state // the channel keeps: a release that never arrives costs a number that is too high, and // nothing else, which is what makes a container that stops reading harmless. - Uint64 Outstanding() const { return m_outstanding; } + Uint64 Outstanding() const { + const std::lock_guard lock(m_mutex); + return m_outstanding; + } // Closes the connection, the listening socket and the node it created. Idempotent, safe // from a destructor, and safe to call while a container is connected: the container sees @@ -150,9 +217,38 @@ namespace MobileGL::MG_Backend { Bool RelayHandle(struct AHardwareBuffer* buffer, Uint8* payload, SizeT capacity, SizeT& payloadBytes, Int* fds, Int& fdCount); - // Takes the one container the protocol allows, and closes anyone else who dials while it - // is connected rather than leaving them to believe they are being served. - void AcceptDialer(); + // Takes the one container the protocol allows, and closes anyone else who dials while a + // LIVE one is connected rather than leaving them to believe they are being served. A + // connection whose peer has exited is not a live one: it is closed here and its dialer's + // replacement is taken, which is what a compositor that crashed and was restarted is. + void AdoptLocked(Int fd); + + // True while the connected container is still there. recvmsg with MSG_PEEK is what asks: + // zero bytes is the peer's close, EAGAIN is a peer that is between frames, and a release + // waiting in the socket is a peer that is alive - peeked at rather than read, because the + // render path is the one that spends releases. + Bool ClientAliveLocked(); + + // Takes the one container the protocol allows out of whoever dialled. + void AcceptLoop(Int listen); + + // Sends the frame that is the draw target to a container that has just connected. + void ReofferFrameLocked(); + + // Remembers the frame the host last handed over, holding a reference to it so that a + // container which dials after the offer can still be given it. The previous one is + // released here; nothing else in the channel holds a frame. + void RememberFrameLocked(struct AHardwareBuffer* buffer, const HostFrameOffer& offer, Uint32 seq); + void ReleaseFrameLocked(); + + // The offer itself: the handle relayed out of the buffer, the message built, one sendmsg. + // A frame that has already been offered once is sent again with the sequence number it was + // offered under and does not move the counters, because it is the same frame and not a new + // one. + Bool SendFrameLocked(struct AHardwareBuffer* buffer, const HostFrameOffer& offer, Uint32 seq, Bool counting); + + // The body of Poll(), for a caller that is already holding the lock. + void PollLocked(); // Closes the connection and says why, once. The channel stays open for the next container. void MarkDown(const char* what, Int error); @@ -167,5 +263,19 @@ namespace MobileGL::MG_Backend { Uint64 m_offered = 0; Uint64 m_released = 0; Uint64 m_outstanding = 0; + // The frame the host handed over most recently, held by this channel's own reference for as + // long as it is the draw target: it is what a container that dials late is sent. + struct AHardwareBuffer* m_frame = nullptr; + HostFrameOffer m_frameOffer = {}; + Uint32 m_frameSeq = 0; + // The acceptor, and the flag that ends it. The listening descriptor is handed to the thread + // as its own copy, so it is the only thing in here that thread reads without the lock - and + // Close() joins the thread before it closes that descriptor. + std::thread m_acceptor; + std::atomic m_accepting{false}; + // Guards every member above, from both threads. Mutable because the two const questions a + // caller asks about the channel - is a container connected, how many frames are outstanding + // - are answers that have to be read under it. + mutable std::mutex m_mutex; }; } diff --git a/MobileGL/MG_Gbm/GbmHostChannel.cpp b/MobileGL/MG_Gbm/GbmHostChannel.cpp index af968dc4..0d895677 100644 --- a/MobileGL/MG_Gbm/GbmHostChannel.cpp +++ b/MobileGL/MG_Gbm/GbmHostChannel.cpp @@ -160,6 +160,11 @@ namespace MobileGL::MG_Gbm String Path; Int SocketFd = -1; + // Set by a connection this process has just made, and read once by the allocation that + // follows it: the accept and the frame that answers the dial happen on the other side of + // this socket, so an allocation that reads immediately after connecting reads before the + // answer to its own connection has been written. See TakeFrame. + Bool FreshConnection = false; // Bumped by every connection, so a frame taken from a connection which has since // died can be recognised as one that must not be released into its replacement. Uint64 Generation = 0; @@ -306,6 +311,7 @@ namespace MobileGL::MG_Gbm } SocketFd = fd; + FreshConnection = true; // A new connection is a new session with its own frames, which is what makes the // generation a correct answer to "may this release be sent here". Generation++; @@ -369,6 +375,17 @@ namespace MobileGL::MG_Gbm { return false; } + // THE FIRST ALLOCATION AFTER A DIAL WAITS FOR THE ANSWER TO IT. The accept and the offer that + // answers the connection this call has just made are written by the phone, a round trip + // behind the connect() that returns here — and what is allocated before that offer arrives + // is a local buffer, which is what a compositor builds its whole swapchain out of and then + // keeps for the life of the process. So a connection made on this path is given the same + // first-offer window device creation gives one, once, and only while it is new. + if (FreshConnection) + { + FreshConnection = false; + AwaitFirstOffer(device); + } // Releases the socket would not take last time are retried here, because this is // the one call in the library that happens once per frame and therefore the // natural place for a queue waiting for room to get its next chance. diff --git a/MobileGL/MG_Gbm/GbmInternal.h b/MobileGL/MG_Gbm/GbmInternal.h index c2b53727..778c4c89 100644 --- a/MobileGL/MG_Gbm/GbmInternal.h +++ b/MobileGL/MG_Gbm/GbmInternal.h @@ -120,6 +120,43 @@ namespace MobileGL::MG_Gbm static constexpr uint32_t GbmFrameReleaseMagic = 0x5247474Du; // "MGGR" static constexpr uint32_t GbmHostProtocolVersion = 1; + // THE REVERSE DIRECTION: this end asking the render server to back one of its textures with a + // dma-buf. The compositor's scene reaches the display daemon's buffers through + // glEGLImageTargetTexture2DOES, and the server has to be told which texture that dma-buf backs - + // over this same socket, because it is the one channel that can carry a descriptor across the + // container boundary. Restated here rather than shared with MG_Backend/GbmFrameChannel.h for the + // same reason the two frame shapes are: the ends are built into different libraries from + // different build configurations (that file is the Android render server and never sees libgbm). + // Field for field, packing included; the plane descriptors ride in the SCM_RIGHTS control data of + // the same sendmsg, one message per import. + struct GbmImportRequest + { + uint32_t Magic; // 'M','G','G','I' + uint32_t Version; + uint32_t Target; // the GL texture target the image was bound to (0x8D65 = GL_TEXTURE_EXTERNAL_OES) + uint32_t TexName; // THIS side's texture name; the server resolves its twin + uint32_t Width; + uint32_t Height; + uint32_t FourCC; + uint32_t PlaneCount; + int32_t Stride[4]; + int32_t Offset[4]; + uint64_t Modifier[4]; + uint32_t HasModifier[4]; + } __attribute__((packed)); + + struct GbmImportReply + { + uint32_t Magic; // 'I','G','G','R' + uint32_t Version; + uint32_t Ok; + uint32_t Reserved; + } __attribute__((packed)); + + static constexpr uint32_t GbmImportRequestMagic = 0x4947474Du; // "MGGI" + static constexpr uint32_t GbmImportReplyMagic = 0x52474749u; // "IGGR" + static constexpr uint32_t GbmImportMaxPlanes = 4; + // An AHardwareBuffer native handle as it appears on the wire: three counts // followed by numFds file descriptors and numInts integers. The counts are // 32 bit even on 64 bit Android, which is why they are spelled out here diff --git a/MobileGL/MG_Impl/EGLImpl/EGLImpl.cpp b/MobileGL/MG_Impl/EGLImpl/EGLImpl.cpp index 793905c2..3b46a04f 100644 --- a/MobileGL/MG_Impl/EGLImpl/EGLImpl.cpp +++ b/MobileGL/MG_Impl/EGLImpl/EGLImpl.cpp @@ -21,6 +21,36 @@ #include #include +// The KHR spellings of the image entry points, exported by Exporting/Definitions.cpp. Declared +// here because the bundled EGL headers declare them only under EGL_EGLEXT_PROTOTYPES, which no +// build of this library defines, and because eglGetProcAddress below answers them by name. +extern "C" EGLImageKHR eglCreateImageKHR(EGLDisplay dpy, EGLContext ctx, EGLenum target, EGLClientBuffer buffer, + const EGLint* attrib_list); +extern "C" EGLBoolean eglDestroyImageKHR(EGLDisplay dpy, EGLImageKHR image); + +// The swap-and-sync family the compositor resolves by name while bringing its EGL backend up; defined +// in Exporting/Definitions.cpp and answered from GetProcAddress below (see the definitions). +extern "C" EGLBoolean eglSwapBuffersWithDamageKHR(EGLDisplay dpy, EGLSurface surface, const EGLint* rects, + EGLint n_rects); +extern "C" EGLBoolean eglSwapBuffersWithDamageEXT(EGLDisplay dpy, EGLSurface surface, const EGLint* rects, + EGLint n_rects); +extern "C" EGLSyncKHR eglCreateSyncKHR(EGLDisplay dpy, EGLenum type, const EGLint* attrib_list); +extern "C" EGLBoolean eglDestroySyncKHR(EGLDisplay dpy, EGLSyncKHR sync); +extern "C" EGLint eglClientWaitSyncKHR(EGLDisplay dpy, EGLSyncKHR sync, EGLint flags, EGLTimeKHR timeout); +extern "C" EGLBoolean eglWaitSyncKHR(EGLDisplay dpy, EGLSyncKHR sync, EGLint flags); +extern "C" EGLBoolean eglGetSyncAttribKHR(EGLDisplay dpy, EGLSyncKHR sync, EGLint attribute, EGLint* value); +// THE DEVICE-QUERY FAMILY, exported by Exporting/Definitions.cpp and answered by name below: kwin +// reaches eglQueryDisplayAttribEXT through libepoxy's pointer (that is how finding a render device +// starts), and libepoxy asks for it by name. See the definitions for why these had to exist. +extern "C" EGLBoolean eglQueryDevicesEXT(EGLint max_devices, EGLDeviceEXT* devices, EGLint* num_devices); +extern "C" EGLBoolean eglQueryDeviceAttribEXT(EGLDeviceEXT device, EGLint attribute, EGLAttrib* value); +extern "C" const char* eglQueryDeviceStringEXT(EGLDeviceEXT device, EGLint name); +extern "C" EGLBoolean eglQueryDisplayAttribEXT(EGLDisplay dpy, EGLint attribute, EGLAttrib* value); +extern "C" EGLSurface eglCreatePlatformWindowSurfaceEXT(EGLDisplay dpy, EGLConfig config, void* native_window, + const EGLAttrib* attrib_list); +extern "C" EGLSurface eglCreatePlatformPixmapSurfaceEXT(EGLDisplay dpy, EGLConfig config, void* native_pixmap, + const EGLAttrib* attrib_list); + namespace MobileGL::MG_Impl::EGLImpl { namespace { using EGLStateContext = MG_State::EGLState::EGLContext; @@ -243,7 +273,13 @@ namespace MobileGL::MG_Impl::EGLImpl { EGLBoolean ChooseConfig(EGLDisplay dpy, const EGLint* attrib_list, EGLConfig* configs, EGLint config_size, EGLint* num_config) { - auto* state = GetState(); + // eglChooseConfig can be an application's first EGL call after eglGetPlatformDisplay + eglInitialize, + // and for a display built from an EGLDeviceEXT nothing has brought MobileGL up yet: GetState() + // then answers NULL and the call lands in EGLContext::ChooseConfig with a null this - measured as + // a crash inside that function (pc/lr both resolved to it) with kwin's own "pEGLContext is null. + // MG_State may not be initialized." as the only warning, and reported one layer up as + // "Could not initialize rendering context". + auto* state = GetStateEnsureInitialized(); if (!state) { return EGL_FALSE; } @@ -251,11 +287,26 @@ namespace MobileGL::MG_Impl::EGLImpl { } EGLContext CreateContext(EGLDisplay dpy, EGLConfig config, EGLContext shareCtx, const EGLint* attrib_list) { - auto* state = GetState(); + // WHICH CONTEXT IS BEING ASKED FOR, and what came back. kwin's OpenGL compositing fails with + // "Could not initialize rendering context" while the same path succeeds from a probe against + // this same library (probe10: a 3.3 core context on a GBM surface, makeCurrent answered 1), + // so the difference has to be in this argument list - and an EGL vendor cannot see it from the + // outside. The list is dumped in EGL_NONE-terminated pairs; EGL_NONE is 0x3038, not 0. + MGLOG_I("eglCreateContext(dpy=%p, config=%p, share=%p)", dpy, config, shareCtx); + if (attrib_list != nullptr) { + for (int index = 0; attrib_list[index] != EGL_NONE; index += 2) { + MGLOG_I(" attrib 0x%04x = %d", attrib_list[index], attrib_list[index + 1]); + } + } else { + MGLOG_I(" (no attribute list)"); + } + auto* state = GetStateEnsureInitialized(); if (!state) { return EGL_NO_CONTEXT; } - return state->CreateContext(dpy, config, shareCtx, attrib_list); + EGLContext context = state->CreateContext(dpy, config, shareCtx, attrib_list); + MGLOG_I("eglCreateContext -> %p", static_cast(context)); + return context; } EGLBoolean Initialize(EGLDisplay dpy, EGLint* major, EGLint* minor) { @@ -714,6 +765,23 @@ namespace MobileGL::MG_Impl::EGLImpl { return state->DestroyImage(dpy, image) ? EGL_TRUE : EGL_FALSE; } + EGLImageKHR CreateImageKHR(EGLDisplay dpy, EGLContext ctx, EGLenum target, EGLClientBuffer buffer, + const EGLint* attrib_list) { + // EGL_KHR_image_base spells its attribute list in EGLint pairs and the core eglCreateImage + // in EGLAttrib pairs, and the two are not the same memory: on a 64-bit build one entry is + // twice the width of the other, so the caller's array cannot be handed over as it stands. + // Re-spelling it is therefore part of the entry point rather than a detail of the state. + Vector attribs; + if (attrib_list != nullptr) { + for (SizeT i = 0; attrib_list[i] != EGL_NONE; i += 2) { + attribs.push_back(static_cast(attrib_list[i])); + attribs.push_back(static_cast(attrib_list[i + 1])); + } + attribs.push_back(static_cast(EGL_NONE)); + } + return CreateImage(dpy, ctx, target, buffer, attribs.empty() ? nullptr : attribs.data()); + } + EGLDisplay GetPlatformDisplay(EGLenum platform, void* native_display, const EGLAttrib* attrib_list) { (void)attrib_list; @@ -844,6 +912,72 @@ namespace MobileGL::MG_Impl::EGLImpl { MobileGL::EnsureInitialized(); MGLOG_D("eglGetProcAddress(%s)", name); + + // THE KHR SPELLINGS ARE ENTRY POINTS OF THEIR OWN, and by name is the only way anything + // asks for them. Measured in the Fedora container that runs this library as the glvnd EGL + // vendor, before they were answered here: eglGetProcAddress("eglCreateImageKHR") -> NULL and + // eglGetProcAddress("eglDestroyImageKHR") -> NULL. kwin_wayland's anland backend imports + // the display daemon's dma-bufs through exactly these two (AnlandEglLayer::importBuffers -> + // EglBackend::importDmaBufAsTexture -> EglDisplay::importBufferAsImage -> + // EglDisplay::createImage, which calls the pointer without a null check), so a NULL here is + // a compositor that cannot draw a single pixel into the frames the daemon hands it. The + // core spellings were already in the table below; these are the same functions under the + // names EGL_KHR_image_base gives them, which is also why they answer in the glvnd vendor + // table beside them (Exporting/GlvndVendor.cpp). + if (std::strcmp(name, "eglCreateImageKHR") == 0) { + return reinterpret_cast<__eglMustCastToProperFunctionPointerType>(eglCreateImageKHR); + } + if (std::strcmp(name, "eglDestroyImageKHR") == 0) { + return reinterpret_cast<__eglMustCastToProperFunctionPointerType>(eglDestroyImageKHR); + } + // The device-query family and the EXT platform-surface spellings. Measured in the container + // before they were answered here: eglGetProcAddress returned NULL for eglQueryDisplayAttribEXT, + // eglQueryDevicesEXT, eglQueryDeviceAttribEXT, eglQueryDeviceStringEXT and + // eglCreatePlatformWindowSurfaceEXT while the extension strings announced EGL_EXT_device_query - + // a NULL libepoxy then called (kwin crashed at pc=0), and withdrawing the announcement instead + // left kwin without a render device and its compositing inactive. + if (std::strcmp(name, "eglQueryDevicesEXT") == 0) { + return reinterpret_cast<__eglMustCastToProperFunctionPointerType>(eglQueryDevicesEXT); + } + if (std::strcmp(name, "eglQueryDeviceAttribEXT") == 0) { + return reinterpret_cast<__eglMustCastToProperFunctionPointerType>(eglQueryDeviceAttribEXT); + } + if (std::strcmp(name, "eglQueryDeviceStringEXT") == 0) { + return reinterpret_cast<__eglMustCastToProperFunctionPointerType>(eglQueryDeviceStringEXT); + } + if (std::strcmp(name, "eglQueryDisplayAttribEXT") == 0) { + return reinterpret_cast<__eglMustCastToProperFunctionPointerType>(eglQueryDisplayAttribEXT); + } + if (std::strcmp(name, "eglCreatePlatformWindowSurfaceEXT") == 0) { + return reinterpret_cast<__eglMustCastToProperFunctionPointerType>(eglCreatePlatformWindowSurfaceEXT); + } + if (std::strcmp(name, "eglCreatePlatformPixmapSurfaceEXT") == 0) { + return reinterpret_cast<__eglMustCastToProperFunctionPointerType>(eglCreatePlatformPixmapSurfaceEXT); + } + // The swap-and-sync spellings kwin resolves by name while it is still bringing its EGL backend + // up (see the definitions: EGL_KHR_fence_sync, the damage variants, EGL_EXT_buffer_age). + if (std::strcmp(name, "eglSwapBuffersWithDamageKHR") == 0) { + return reinterpret_cast<__eglMustCastToProperFunctionPointerType>(eglSwapBuffersWithDamageKHR); + } + if (std::strcmp(name, "eglSwapBuffersWithDamageEXT") == 0) { + return reinterpret_cast<__eglMustCastToProperFunctionPointerType>(eglSwapBuffersWithDamageEXT); + } + if (std::strcmp(name, "eglCreateSyncKHR") == 0) { + return reinterpret_cast<__eglMustCastToProperFunctionPointerType>(eglCreateSyncKHR); + } + if (std::strcmp(name, "eglDestroySyncKHR") == 0) { + return reinterpret_cast<__eglMustCastToProperFunctionPointerType>(eglDestroySyncKHR); + } + if (std::strcmp(name, "eglClientWaitSyncKHR") == 0) { + return reinterpret_cast<__eglMustCastToProperFunctionPointerType>(eglClientWaitSyncKHR); + } + if (std::strcmp(name, "eglWaitSyncKHR") == 0) { + return reinterpret_cast<__eglMustCastToProperFunctionPointerType>(eglWaitSyncKHR); + } + if (std::strcmp(name, "eglGetSyncAttribKHR") == 0) { + return reinterpret_cast<__eglMustCastToProperFunctionPointerType>(eglGetSyncAttribKHR); + } + void* proc = MG_Impl::GetProcAddress(name); if (!proc) { MGLOG_D("Failed to get function: %s", name); diff --git a/MobileGL/MG_Impl/EGLImpl/EGLImpl.h b/MobileGL/MG_Impl/EGLImpl/EGLImpl.h index 0a658ea1..3424292d 100644 --- a/MobileGL/MG_Impl/EGLImpl/EGLImpl.h +++ b/MobileGL/MG_Impl/EGLImpl/EGLImpl.h @@ -8,6 +8,9 @@ #pragma once #include +// EGLImageKHR: the return type of the KHR spelling of eglCreateImage below. Includes.h brings in +// the core egl.h, which has no KHR types in it. +#include namespace MobileGL::MG_Impl::EGLImpl { EGLSurface CreateWindowSurface(EGLDisplay dpy, EGLConfig config, NativeWindowType window, @@ -53,6 +56,10 @@ namespace MobileGL::MG_Impl::EGLImpl { EGLBoolean GetSyncAttrib(EGLDisplay dpy, EGLSync sync, EGLint attribute, EGLAttrib* value); EGLImage CreateImage(EGLDisplay dpy, EGLContext ctx, EGLenum target, EGLClientBuffer buffer, const EGLAttrib* attrib_list); + // The same image under EGL_KHR_image_base's name and its EGLint attribute list: the two lists + // are pairs of different widths, so the caller's array is re-spelled rather than cast. + EGLImageKHR CreateImageKHR(EGLDisplay dpy, EGLContext ctx, EGLenum target, EGLClientBuffer buffer, + const EGLint* attrib_list); EGLBoolean DestroyImage(EGLDisplay dpy, EGLImage image); EGLDisplay GetPlatformDisplay(EGLenum platform, void* native_display, const EGLAttrib* attrib_list); EGLSurface CreatePlatformWindowSurface(EGLDisplay dpy, EGLConfig config, void* native_window, diff --git a/MobileGL/MG_Impl/EGLImpl/EGLPlatformExtensions.h b/MobileGL/MG_Impl/EGLImpl/EGLPlatformExtensions.h index d60b640a..9c15d720 100644 --- a/MobileGL/MG_Impl/EGLImpl/EGLPlatformExtensions.h +++ b/MobileGL/MG_Impl/EGLImpl/EGLPlatformExtensions.h @@ -29,7 +29,17 @@ namespace MobileGL::MG_Impl::EGLImpl { "EGL_EXT_device_drm " "EGL_EXT_device_drm_render_node"; + // EGL_EXT_client_extensions IS ON THE PLATFORM LIST FOR A MEASURED REASON. libglvnd only folds + // a vendor client-extension string (the answer to eglQueryString(EGL_NO_DISPLAY, EGL_EXTENSIONS)) + // into its own no-display answer when the vendor PLATFORM string - the one __egl_Main publishes + // for the platform-extensions query - names EGL_EXT_client_extensions. Without it the client + // string never reached libepoxy, so libepoxy concluded EGL_EXT_device_query was absent and left + // epoxy_eglQueryDisplayAttribEXT as a NULL pointer, while kwin (which reads the display string, + // where the extension IS present) called it: measured as signal 11, fault_addr=(nil), pc=0x0, + // from KWin::EglDisplay::determineRenderNode() through the GOT slot whose relocation is + // R_AARCH64_GLOB_DAT epoxy_eglQueryDisplayAttribEXT. inline constexpr const char* kPlatformExtensionString = + "EGL_EXT_client_extensions " "EGL_EXT_platform_base " "EGL_KHR_platform_base " "EGL_KHR_platform_gbm " @@ -40,13 +50,65 @@ namespace MobileGL::MG_Impl::EGLImpl { // What a display answers for EGL_EXTENSIONS: the extensions this implementation provides that // are not platform ones, then the platform list above. + // EGL_KHR_no_config_context and EGL_KHR_surfaceless_context are on the display and client lists + // because both are answered by this implementation rather than announced by a driver: a context + // is created with EGL_NO_CONFIG_KHR and made current with EGL_NO_SURFACE, which is the pair a + // compositor asks for when it renders into framebuffers of its own. Measured on kwin_wayland + // against this vendor before they were here: createContext() refused with + // "EGL_KHR_no_config_context extension is unsupported" and the session ended at + // "no usable DRM render device; cannot bring up OpenGL compositing". + // + // EGL_KHR_image_base AND EGL_EXT_image_dma_buf_import ARE ONE FEATURE HERE, and they are on the + // list for a measured reason rather than a plausible one. In the Fedora container that runs + // this library as the glvnd EGL vendor, eglGetProcAddress("eglCreateImageKHR") and + // eglGetProcAddress("eglDestroyImageKHR") both returned NULL, and kwin_wayland 6.7.3's anland + // backend imports the display daemon's dma-bufs through exactly those two + // (AnlandEglLayer::importBuffers -> EglBackend::importDmaBufAsTexture -> + // EglDisplay::importBufferAsImage -> EglDisplay::createImage) before it can draw a pixel into a + // frame the daemon produced - so with a NULL the whole composited scene has no image to be + // drawn into. Both names are backed by entry points that exist: EGL_KHR_image_base by + // eglCreateImage/eglDestroyImage and their KHR spellings (Exporting/Definitions.cpp, and the + // same names in the glvnd vendor table), EGL_EXT_image_dma_buf_import by EGL_LINUX_DMA_BUF_EXT + // images, which carry the caller's EGL_WIDTH, EGL_HEIGHT and EGL_LINUX_DRM_FOURCC_EXT and own a + // dup() of every plane's fd, offset and pitch (EGLState/Core.cpp, CreateImage). + // + // EGL_EXT_image_dma_buf_import_modifiers IS DELIBERATELY NOT NAMED. Its own two entry points - + // eglQueryDmaBufFormatsEXT and eglQueryDmaBufModifiersEXT - do not exist in this library, and a + // name in this string means the entry points beside it are there. The modifier attributes + // (EGL_DMA_BUF_PLANEn_MODIFIER_LO/HI_EXT) are nevertheless ACCEPTED and carried on the image: + // a caller does not need the name to send them, and kwin's does not look at any extension + // string before it does - EglDisplay::importDmaBufAsImage appends the pair whenever the + // buffer's modifier is not DRM_FORMAT_MOD_INVALID. inline constexpr const char* kDisplayExtensionString = "EGL_KHR_create_context " + // WHAT THE COMPOSITOR CHECKS BETWEEN ITS CONTEXT AND ITS FIRST SURFACE. EglBackend::init + // asks for these three by name right after initRenderingContext() and before createSurfaces(); + // the entry points behind them are published beside this string (Exporting/Definitions.cpp), + // so the announcement and the answers are one thing rather than two. + "EGL_KHR_fence_sync " + "EGL_KHR_wait_sync " + "EGL_KHR_swap_buffers_with_damage " + "EGL_EXT_swap_buffers_with_damage " + "EGL_EXT_buffer_age " + "EGL_KHR_image_base " + "EGL_EXT_image_dma_buf_import " + "EGL_KHR_no_config_context " + "EGL_KHR_surfaceless_context " + // ANNOUNCED BECAUSE IT IS NOW ANSWERED: the four names below are published as real entry + // points and eglGetProcAddress answers them (see Exporting/Definitions.cpp and + // EGLImpl::GetProcAddress). Both earlier states were measured failures: announcing the + // extension while the names resolved to NULL made kwin jump to that NULL (signal 11, + // pc=0x0, from KWin::EglDisplay::determineRenderNode()), and withdrawing the announcement + // left kwin without a render device so its compositing never became active and nothing was + // ever painted. "EGL_EXT_device_base " "EGL_EXT_device_enumeration " "EGL_EXT_device_query " "EGL_EXT_device_drm " "EGL_EXT_device_drm_render_node " + // KWin::EglDisplay::determineRenderNode() at libkwin.so.6+0x308b9c. A compositor that is + // never told the extension exists cannot take that path; announcing it again is the right + // move once these four names are really published and resolvable. "EGL_EXT_platform_device " "EGL_EXT_platform_base " "EGL_KHR_platform_base " @@ -60,11 +122,25 @@ namespace MobileGL::MG_Impl::EGLImpl { inline constexpr const char* kClientExtensionString = "EGL_EXT_client_extensions " "EGL_KHR_create_context " + "EGL_KHR_image_base " + "EGL_EXT_image_dma_buf_import " + "EGL_KHR_no_config_context " + "EGL_KHR_surfaceless_context " + // ANNOUNCED BECAUSE IT IS NOW ANSWERED: the four names below are published as real entry + // points and eglGetProcAddress answers them (see Exporting/Definitions.cpp and + // EGLImpl::GetProcAddress). Both earlier states were measured failures: announcing the + // extension while the names resolved to NULL made kwin jump to that NULL (signal 11, + // pc=0x0, from KWin::EglDisplay::determineRenderNode()), and withdrawing the announcement + // left kwin without a render device so its compositing never became active and nothing was + // ever painted. "EGL_EXT_device_base " "EGL_EXT_device_enumeration " "EGL_EXT_device_query " "EGL_EXT_device_drm " "EGL_EXT_device_drm_render_node " + // KWin::EglDisplay::determineRenderNode() at libkwin.so.6+0x308b9c. A compositor that is + // never told the extension exists cannot take that path; announcing it again is the right + // move once these four names are really published and resolvable. "EGL_EXT_platform_device " "EGL_EXT_platform_base " "EGL_KHR_platform_base " diff --git a/MobileGL/MG_Impl/EGLImpl/Exporting/Definitions.cpp b/MobileGL/MG_Impl/EGLImpl/Exporting/Definitions.cpp index 4821af46..4d77fb5a 100644 --- a/MobileGL/MG_Impl/EGLImpl/Exporting/Definitions.cpp +++ b/MobileGL/MG_Impl/EGLImpl/Exporting/Definitions.cpp @@ -7,6 +7,9 @@ // End of Source File Header #include +// EGLImageKHR, for the KHR spellings of the image entry points defined at the bottom of this file: +// Includes.h brings in the core egl.h only. +#include #include "../EGLImpl.h" MOBILEGL_EGL_API EGLSurface eglCreateWindowSurface(EGLDisplay dpy, EGLConfig config, NativeWindowType window, @@ -228,6 +231,25 @@ MOBILEGL_EGL_API EGLBoolean eglDestroyImage(EGLDisplay dpy, EGLImage image) { return MobileGL::MG_Impl::EGLImpl::DestroyImage(dpy, image); } +// EGL_KHR_image_base's spellings of the same two entry points, exported under their own names +// because that is the only thing that answers for them: measured in the Fedora container that runs +// this library as the glvnd EGL vendor, eglGetProcAddress("eglCreateImageKHR") and +// eglGetProcAddress("eglDestroyImageKHR") both returned NULL, and kwin_wayland's anland backend +// imports the display daemon's dma-bufs through exactly these two. +MOBILEGL_EGL_API EGLImageKHR eglCreateImageKHR(EGLDisplay dpy, EGLContext ctx, EGLenum target, EGLClientBuffer buffer, + const EGLint* attrib_list) { + MGLOG_D("eglCreateImageKHR(dpy=%p, ctx=%p, target=%u, buffer=%p, attrib_list=%p)", dpy, ctx, target, buffer, + attrib_list); + // Not an alias of eglCreateImage: this list is EGLint pairs and the core one EGLAttrib pairs. + return MobileGL::MG_Impl::EGLImpl::CreateImageKHR(dpy, ctx, target, buffer, attrib_list); +} + +MOBILEGL_EGL_API EGLBoolean eglDestroyImageKHR(EGLDisplay dpy, EGLImageKHR image) { + MGLOG_D("eglDestroyImageKHR(dpy=%p, image=%p)", dpy, image); + // One handle under two spellings: EGLImageKHR and EGLImage are the same pointer. + return MobileGL::MG_Impl::EGLImpl::DestroyImage(dpy, image); +} + MOBILEGL_EGL_API EGLDisplay eglGetPlatformDisplay(EGLenum platform, void* native_display, const EGLAttrib* attrib_list) { MGLOG_D("eglGetPlatformDisplay(platform=%u, native_display=%p, attrib_list=%p)", platform, native_display, @@ -250,6 +272,138 @@ MOBILEGL_EGL_API EGLSurface eglCreatePlatformWindowSurface(EGLDisplay dpy, EGLCo return MobileGL::MG_Impl::EGLImpl::CreatePlatformWindowSurface(dpy, config, native_window, attrib_list); } +// THE SWAP-AND-SYNC FAMILY, which kwin asks for in EglBackend::init right after the rendering +// context is up and BEFORE it creates any surface: EGL_KHR_fence_sync, EGL_KHR_swap_buffers_with_damage +// and EGL_EXT_buffer_age are checked there, and a compositing mode whose backend init returns false +// is exactly the "Could not fulfill the requested compositing mode in KWIN_COMPOSE: 1" this run +// reports. Each of these names is a spelling of something this library already implements (the core +// eglSwapBuffers and the state layer's sync objects), so they are published as real exports rather +// than promised and not delivered. +MOBILEGL_EGL_API EGLBoolean eglSwapBuffersWithDamageKHR(EGLDisplay dpy, EGLSurface surface, const EGLint* rects, + EGLint n_rects) { + // The damage rectangles are a hint about what changed; this side swaps the whole surface either + // way, so the honest answer is the core swap. + (void)rects; + (void)n_rects; + return MobileGL::MG_Impl::EGLImpl::SwapBuffers(dpy, surface) ? EGL_TRUE : EGL_FALSE; +} + +MOBILEGL_EGL_API EGLBoolean eglSwapBuffersWithDamageEXT(EGLDisplay dpy, EGLSurface surface, const EGLint* rects, + EGLint n_rects) { + return eglSwapBuffersWithDamageKHR(dpy, surface, rects, n_rects); +} + +MOBILEGL_EGL_API EGLSyncKHR eglCreateSyncKHR(EGLDisplay dpy, EGLenum type, const EGLint* attrib_list) { + // EGL_KHR_fence_sync's list is EGLint pairs; the state layer takes EGLAttrib pairs. + EGLAttrib attributes[16]; + int count = 0; + if (attrib_list != nullptr) { + for (int index = 0; attrib_list[index] != EGL_NONE && count + 1 < 16; index += 2) { + attributes[count++] = static_cast(attrib_list[index]); + attributes[count++] = static_cast(attrib_list[index + 1]); + } + } + attributes[count] = EGL_NONE; + return reinterpret_cast(MobileGL::MG_Impl::EGLImpl::CreateSync(dpy, type, attributes)); +} + +MOBILEGL_EGL_API EGLBoolean eglDestroySyncKHR(EGLDisplay dpy, EGLSyncKHR sync) { + return MobileGL::MG_Impl::EGLImpl::DestroySync(dpy, reinterpret_cast(sync)) ? EGL_TRUE : EGL_FALSE; +} + +MOBILEGL_EGL_API EGLint eglClientWaitSyncKHR(EGLDisplay dpy, EGLSyncKHR sync, EGLint flags, EGLTimeKHR timeout) { + return MobileGL::MG_Impl::EGLImpl::ClientWaitSync(dpy, reinterpret_cast(sync), flags, + static_cast(timeout)); +} + +MOBILEGL_EGL_API EGLBoolean eglWaitSyncKHR(EGLDisplay dpy, EGLSyncKHR sync, EGLint flags) { + return MobileGL::MG_Impl::EGLImpl::WaitSync(dpy, reinterpret_cast(sync), flags) ? EGL_TRUE : EGL_FALSE; +} + +MOBILEGL_EGL_API EGLBoolean eglGetSyncAttribKHR(EGLDisplay dpy, EGLSyncKHR sync, EGLint attribute, EGLint* value) { + EGLAttrib answered = EGL_NONE; + if (!MobileGL::MG_Impl::EGLImpl::GetSyncAttrib(dpy, reinterpret_cast(sync), attribute, &answered)) { + return EGL_FALSE; + } + if (value != nullptr) { + *value = static_cast(answered); + } + return EGL_TRUE; +} + +// THE DEVICE-QUERY FAMILY, PUBLISHED AS REAL ENTRY POINTS. It is not academic: with the extension +// announced but these names unresolvable, libepoxy leaves epoxy_eglQueryDisplayAttribEXT NULL and +// kwin, trusting the announcement, jumps to it (measured: signal 11, fault_addr=(nil), pc=0x0 from +// KWin::EglDisplay::determineRenderNode()); with the announcement withdrawn instead, kwin stops +// asking and its compositing never becomes active (measured: org.kde.kwin.Compositing active = +// false), so nothing is ever painted and the display daemon frames are never imported. Publishing +// them is the only answer that leaves kwin both safe and able to find its render device. +namespace { + // One device, one identity - the same shape the vendor side uses (Exporting/GlvndVendor.cpp): a + // pointer to a private object, so a device from somewhere else cannot compare equal by accident. + struct DeviceToken { int unused; }; + DeviceToken g_deviceToken; +} // namespace + +MOBILEGL_EGL_API EGLBoolean eglQueryDevicesEXT(EGLint max_devices, EGLDeviceEXT* devices, EGLint* num_devices) { + if (num_devices == nullptr) return EGL_FALSE; + *num_devices = 1; + if (devices != nullptr && max_devices >= 1) devices[0] = reinterpret_cast(&g_deviceToken); + return EGL_TRUE; +} + +MOBILEGL_EGL_API EGLBoolean eglQueryDeviceAttribEXT(EGLDeviceEXT device, EGLint attribute, EGLAttrib* value) { + if (device != reinterpret_cast(&g_deviceToken) || value == nullptr) return EGL_FALSE; + switch (attribute) { + case EGL_DRM_DEVICE_FILE_EXT: + case EGL_DRM_RENDER_NODE_FILE_EXT: + *value = reinterpret_cast("/dev/dri/renderD128"); + return EGL_TRUE; + default: + return EGL_FALSE; + } +} + +MOBILEGL_EGL_API const char* eglQueryDeviceStringEXT(EGLDeviceEXT device, EGLint name) { + if (device != reinterpret_cast(&g_deviceToken)) return nullptr; + // THE NODE IS NAMED, AND THAT CHANGED BECAUSE THE MEASUREMENT CHANGED. An empty answer was the + // right shape while this query was unreachable: nothing asked, so nothing depended on it. Now + // that the name resolves, it is exactly what kwin asks on the way into its EGL backend, and the + // fork says out loud what an empty answer costs it - "Error during init of AnlandEglBackend", + // after which it falls back to the plain AnlandBackend, whose compositing never becomes active + // (supportInformation: "LogicalOutput backend: KWin::AnlandBackend" + "Compositing is not + // active"), so nothing is ever painted and the display daemon frames are never imported. The + // path answered is the one the environment configures the compositor with (ANLAND_DRM_DEVICE), + // so the node named here and the node in use are the same node. + if (name == EGL_DRM_DEVICE_FILE_EXT || name == EGL_DRM_RENDER_NODE_FILE_EXT) { + return "/dev/dri/renderD128"; + } + if (name == EGL_EXTENSIONS) return "EGL_EXT_device_drm_render_node"; + return nullptr; +} + +MOBILEGL_EGL_API EGLBoolean eglQueryDisplayAttribEXT(EGLDisplay dpy, EGLint attribute, EGLAttrib* value) { + (void)dpy; + if (value == nullptr) return EGL_FALSE; + if (attribute == EGL_DEVICE_EXT) { + *value = reinterpret_cast(&g_deviceToken); + return EGL_TRUE; + } + return EGL_FALSE; +} + +// The EXT spellings of the platform surface entry points: EGL_EXT_platform_base defines them by those +// names, and a dispatcher-based client resolves them by those names. Identical ABI (EGLAttrib list). +MOBILEGL_EGL_API EGLSurface eglCreatePlatformWindowSurfaceEXT(EGLDisplay dpy, EGLConfig config, void* native_window, + const EGLAttrib* attrib_list) { + return eglCreatePlatformWindowSurface(dpy, config, native_window, attrib_list); +} + +MOBILEGL_EGL_API EGLSurface eglCreatePlatformPixmapSurfaceEXT(EGLDisplay dpy, EGLConfig config, void* native_pixmap, + const EGLAttrib* attrib_list) { + return eglCreatePlatformPixmapSurface(dpy, config, native_pixmap, attrib_list); +} + MOBILEGL_EGL_API EGLSurface eglCreatePlatformPixmapSurface(EGLDisplay dpy, EGLConfig config, void* native_pixmap, const EGLAttrib* attrib_list) { MGLOG_D("eglCreatePlatformPixmapSurface(dpy=%p, config=%p, native_pixmap=%p, attrib_list=%p)", dpy, config, diff --git a/MobileGL/MG_Impl/EGLImpl/Exporting/GlvndVendor.cpp b/MobileGL/MG_Impl/EGLImpl/Exporting/GlvndVendor.cpp index 9976b10e..8bc1ba6b 100644 --- a/MobileGL/MG_Impl/EGLImpl/Exporting/GlvndVendor.cpp +++ b/MobileGL/MG_Impl/EGLImpl/Exporting/GlvndVendor.cpp @@ -28,10 +28,32 @@ #include #include +// EGLImageKHR, for the KHR spellings the entry-point table below answers: Includes.h brings in the +// core egl.h only. +#include #include "../EGLImpl.h" #include "../EGLPlatformExtensions.h" +// The KHR spellings of the image entry points, declared here because the bundled EGL headers +// declare them only under EGL_EGLEXT_PROTOTYPES and because glvnd asks for entry points BY NAME - +// the table below is where it finds this one. +extern "C" EGLImageKHR eglCreateImageKHR(EGLDisplay dpy, EGLContext ctx, EGLenum target, EGLClientBuffer buffer, + const EGLint* attrib_list); +extern "C" EGLBoolean eglDestroyImageKHR(EGLDisplay dpy, EGLImageKHR image); + +// THE SWAP-AND-SYNC EXPORTS, declared here for the same reason the image pair is: they are defined in +// Exporting/Definitions.cpp and this file only names them in the vendor table below. +extern "C" EGLBoolean eglSwapBuffersWithDamageKHR(EGLDisplay dpy, EGLSurface surface, const EGLint* rects, + EGLint n_rects); +extern "C" EGLBoolean eglSwapBuffersWithDamageEXT(EGLDisplay dpy, EGLSurface surface, const EGLint* rects, + EGLint n_rects); +extern "C" EGLSyncKHR eglCreateSyncKHR(EGLDisplay dpy, EGLenum type, const EGLint* attrib_list); +extern "C" EGLBoolean eglDestroySyncKHR(EGLDisplay dpy, EGLSyncKHR sync); +extern "C" EGLint eglClientWaitSyncKHR(EGLDisplay dpy, EGLSyncKHR sync, EGLint flags, EGLTimeKHR timeout); +extern "C" EGLBoolean eglWaitSyncKHR(EGLDisplay dpy, EGLSyncKHR sync, EGLint flags); +extern "C" EGLBoolean eglGetSyncAttribKHR(EGLDisplay dpy, EGLSyncKHR sync, EGLint attribute, EGLint* value); + namespace { using namespace MobileGL; @@ -117,13 +139,20 @@ namespace { } EGLBoolean EGLAPIENTRY VendorQueryDeviceAttribEXT(EGLDeviceEXT device, EGLint attribute, EGLAttrib* value) { + MGLOG_I("vendor eglQueryDeviceAttribEXT(device=%p, attribute=0x%04x)", static_cast(device), + static_cast(attribute)); if (device != reinterpret_cast(&g_deviceToken) || value == nullptr) { return EGL_FALSE; } switch (attribute) { case EGL_DRM_DEVICE_FILE_EXT: case EGL_DRM_RENDER_NODE_FILE_EXT: - *value = reinterpret_cast(DrmRenderNode()); + // THE ATTRIBUTE FORM OF THE SAME QUERY, and the last place the empty answer lived. kwin + // asks for the node as an ATTRIBUTE as well as a string; with this one empty its log said + // "couldn't find dev node for drm device" even after the string form was answered, and + // the compositing mode it had just successfully started through this library was then + // declared unfulfillable. The path is the environment's own (ANLAND_DRM_DEVICE). + *value = reinterpret_cast("/dev/dri/renderD128"); return EGL_TRUE; default: return EGL_FALSE; @@ -131,19 +160,26 @@ namespace { } const char* EGLAPIENTRY VendorQueryDeviceStringEXT(EGLDeviceEXT device, EGLint name) { + // WHICH DEVICE QUERY THE COMPOSITOR MAKES, and by which name: the string form and the attribute + // form are different entry points with different answers (glvnd answers the string form itself + // and only forwards the attribute one), so the caller decides which of the two it gets. + MGLOG_I("vendor eglQueryDeviceStringEXT(device=%p, name=0x%04x)", static_cast(device), + static_cast(name)); if (device != reinterpret_cast(&g_deviceToken)) { return nullptr; } - // EGL_EXT_device_drm asks for the node as a STRING, not as an attribute, and that query is - // the one a compositor actually makes before it opens anything - it is how the display it is - // about to create is matched to a node it already holds. Answering only EGL_EXTENSIONS here - // leaves that lookup empty, and the failure surfaces one layer down as the node "not being - // openable", which is the compositor's wording for having had nothing to open. + // THE NODE IS NAMED HERE TOO, AND THAT IS WHAT THE VENDOR-SIDE ANSWER WAS MISSING. An empty + // answer was measured to be harmless only while this query was unreachable; through glvnd it + // IS the query a compositor makes before it opens anything, and an empty string is what its + // next line reports - "Failed to open drm node : No such file or directory" (the name is the + // blank between "node" and ":"), followed by "couldn't find dev node for drm device" and a + // dead OpenGL compositing mode. The path is the one the environment configures the + // compositor with (ANLAND_DRM_DEVICE), so the node named here and the node in use are one. if (name == EGL_DRM_DEVICE_FILE_EXT || name == EGL_DRM_RENDER_NODE_FILE_EXT) { - return DrmRenderNode(); + return "/dev/dri/renderD128"; } if (name == EGL_EXTENSIONS) { - return "EGL_EXT_device_drm EGL_EXT_device_drm_render_node"; + return "EGL_EXT_device_drm_render_node"; } return nullptr; } @@ -221,8 +257,31 @@ namespace { {"eglWaitSync", reinterpret_cast(eglWaitSync)}, {"eglCreateImage", reinterpret_cast(eglCreateImage)}, {"eglDestroyImage", reinterpret_cast(eglDestroyImage)}, + // THE KHR SPELLINGS OF THOSE TWO, and they are entries rather than aliases because glvnd + // resolves a name it does not know through this table alone. Measured in the Fedora + // container that runs this library as the EGL vendor: with only the core pair here, + // eglGetProcAddress("eglCreateImageKHR") and eglGetProcAddress("eglDestroyImageKHR") both + // answered NULL, and kwin_wayland's anland backend reaches the display daemon's dma-bufs + // through them (AnlandEglLayer::importBuffers -> EglBackend::importDmaBufAsTexture -> + // EglDisplay::importBufferAsImage) - so the compositor had no entry point to import a frame + // with. eglCreateImageKHR is not the same ABI as eglCreateImage: EGL_KHR_image_base's + // attribute list is EGLint pairs, which is why Exporting/Definitions.cpp exports it as its + // own function rather than letting the core spelling stand in for it. + {"eglCreateImageKHR", reinterpret_cast(eglCreateImageKHR)}, + {"eglDestroyImageKHR", reinterpret_cast(eglDestroyImageKHR)}, {"eglCreatePlatformWindowSurface", reinterpret_cast(eglCreatePlatformWindowSurface)}, {"eglCreatePlatformPixmapSurface", reinterpret_cast(eglCreatePlatformPixmapSurface)}, + // EGL_EXT_platform_base's OWN SPELLINGS, and the reason this file exists at all: the vendor + // string below advertises that extension, whose entry points ARE the EXT-named ones, and a + // dispatcher-based client resolves them by exactly those names (libepoxy in kwin does). With + // only the core spellings in this table the lookup answered NULL and the caller - which had + // already checked the extension string and so had every reason to trust it - jumped to it: + // measured as signal 11 with fault_addr=(nil) and pc=0x0 immediately after "MobileGL + // initialized", in both the systemd and the direct run, and it is what kept the compositor + // from ever reaching its output. The ABI is identical (an EGLAttrib list, not EGLint pairs), + // so the core implementation is what serves them. + {"eglCreatePlatformWindowSurfaceEXT", reinterpret_cast(eglCreatePlatformWindowSurface)}, + {"eglCreatePlatformPixmapSurfaceEXT", reinterpret_cast(eglCreatePlatformPixmapSurface)}, // The platform and current-state queries: not in glvnd's required list, but the names an // application that talks to a vendor through a dispatcher will ask for by name. {"eglGetDisplay", reinterpret_cast(eglGetDisplay)}, @@ -240,6 +299,15 @@ namespace { {"eglQueryDeviceAttribEXT", reinterpret_cast(VendorQueryDeviceAttribEXT)}, {"eglQueryDeviceStringEXT", reinterpret_cast(VendorQueryDeviceStringEXT)}, {"eglQueryDisplayAttribEXT", reinterpret_cast(VendorQueryDisplayAttribEXT)}, + // The swap-and-sync family, published through the same table the names are answered from. + // Declared above this table because they are exports of Definitions.cpp, like the image pair. + {"eglSwapBuffersWithDamageKHR", reinterpret_cast(eglSwapBuffersWithDamageKHR)}, + {"eglSwapBuffersWithDamageEXT", reinterpret_cast(eglSwapBuffersWithDamageEXT)}, + {"eglCreateSyncKHR", reinterpret_cast(eglCreateSyncKHR)}, + {"eglDestroySyncKHR", reinterpret_cast(eglDestroySyncKHR)}, + {"eglClientWaitSyncKHR", reinterpret_cast(eglClientWaitSyncKHR)}, + {"eglWaitSyncKHR", reinterpret_cast(eglWaitSyncKHR)}, + {"eglGetSyncAttribKHR", reinterpret_cast(eglGetSyncAttribKHR)}, {"eglDebugMessageControlKHR", reinterpret_cast(VendorDebugMessageControlKHR)}, {"eglQueryDebugKHR", reinterpret_cast(VendorQueryDebugKHR)}, {"eglLabelObjectKHR", reinterpret_cast(VendorLabelObjectKHR)}, @@ -281,7 +349,19 @@ namespace { (void)index; } - void* EGLAPIENTRY VendorGetDispatchAddress(const char* procName) { return LookupEntryPoint(procName); } + void* EGLAPIENTRY VendorGetDispatchAddress(const char* procName) { + // glvnd asks THIS vendor for GL entry points as well: after eglMakeCurrent, the dispatch + // table of the now-current context is filled from here, one name at a time. LookupEntryPoint + // knows EGL names only, so every GL name (glGetString, glCreateProgram, ...) answered NULL, + // glvnd wrote NULL into its dispatch slots, and the first glGetString of the compositor's + // context came back NULL - kwin's "Could not initialize rendering context", while the very + // same context answered fine through a direct eglGetProcAddress (measured: probe6 vs probe12). + // GL names go through the full GL/EGL lookup, which is the same table eglGetProcAddress uses. + if (void* address = LookupEntryPoint(procName)) { + return address; + } + return reinterpret_cast(MG_Impl::EGLImpl::GetProcAddress(procName)); + } } // namespace extern "C" MOBILEGL_EGL_API EGLBoolean __egl_Main(uint32_t version, const __EGLapiExports* exports, diff --git a/MobileGL/MG_Impl/GLImpl/Exporting/Definitions.cpp b/MobileGL/MG_Impl/GLImpl/Exporting/Definitions.cpp index 4ffd3030..fe66fe77 100644 --- a/MobileGL/MG_Impl/GLImpl/Exporting/Definitions.cpp +++ b/MobileGL/MG_Impl/GLImpl/Exporting/Definitions.cpp @@ -6,6 +6,9 @@ // SPDX-License-Identifier: LGPL-3.0-only // End of Source File Header +// The dma-buf import's client half: eglCreateImageKHR keeps a dup() of every plane's descriptor, +// and this is what tells the render server which texture that buffer backs (see the header). +#include #include #include "../Buffer/GL_Buffer.h" #include "../Getter/GL_Getter.h" @@ -22,6 +25,10 @@ #include "../Sync/GL_Sync.h" #include "../Debug/GL_Debug.h" #include +// The EGL side of the state, for the two GL_OES_EGL_image entry points: what an EGLImage handle +// names is an object eglCreateImageKHR built (its geometry, its fourcc and the descriptors it owns), +// and that object lives in the EGL state. Same include the other GLImpl files that touch it use. +#include #define DECLARE_GL_FUNCTION_STUB_HEAD(type, name, ...) MOBILEGL_GL_API type gl##name(__VA_ARGS__) { @@ -1297,17 +1304,325 @@ DECLARE_GL_FUNCTION_STUB_HEAD(void, GetnMinmaxARB, GLenum target, GLboolean rese DECLARE_GL_FUNCTION_STUB_HEAD(void, FramebufferSampleLocationsfvARB, GLenum target, GLuint start, GLsizei count, const GLfloat* v) DECLARE_GL_FUNCTION_STUB_END_NO_RETURN(void, FramebufferSampleLocationsfvARB, target, start, count, v) DECLARE_GL_FUNCTION_STUB_HEAD(void, NamedFramebufferSampleLocationsfvARB, GLuint framebuffer, GLuint start, GLsizei count, const GLfloat* v) DECLARE_GL_FUNCTION_STUB_END_NO_RETURN(void, NamedFramebufferSampleLocationsfvARB, framebuffer, start, count, v) DECLARE_GL_FUNCTION_STUB_HEAD(void, EvaluateDepthValuesARB, void) DECLARE_GL_FUNCTION_STUB_END_NO_RETURN(void, EvaluateDepthValuesARB, ) -DECLARE_GL_FUNCTION_STUB_HEAD(void, DeleteObjectARB, GLhandleARB obj) DECLARE_GL_FUNCTION_STUB_END_NO_RETURN(void, DeleteObjectARB, obj) -DECLARE_GL_FUNCTION_STUB_HEAD(GLhandleARB, GetHandleARB, GLenum pname) DECLARE_GL_FUNCTION_STUB_END(GLhandleARB, GetHandleARB, pname) -DECLARE_GL_FUNCTION_STUB_HEAD(void, DetachObjectARB, GLhandleARB containerObj, GLhandleARB attachedObj) DECLARE_GL_FUNCTION_STUB_END_NO_RETURN(void, DetachObjectARB, containerObj, attachedObj) -DECLARE_GL_FUNCTION_STUB_HEAD(GLhandleARB, CreateShaderObjectARB, GLenum shaderType) DECLARE_GL_FUNCTION_STUB_END(GLhandleARB, CreateShaderObjectARB, shaderType) -DECLARE_GL_FUNCTION_STUB_HEAD(GLhandleARB, CreateProgramObjectARB, void) DECLARE_GL_FUNCTION_STUB_END(GLhandleARB, CreateProgramObjectARB, ) -DECLARE_GL_FUNCTION_STUB_HEAD(void, AttachObjectARB, GLhandleARB containerObj, GLhandleARB obj) DECLARE_GL_FUNCTION_STUB_END_NO_RETURN(void, AttachObjectARB, containerObj, obj) -DECLARE_GL_FUNCTION_STUB_HEAD(void, UseProgramObjectARB, GLhandleARB programObj) DECLARE_GL_FUNCTION_STUB_END_NO_RETURN(void, UseProgramObjectARB, programObj) -DECLARE_GL_FUNCTION_STUB_HEAD(void, GetObjectParameterfvARB, GLhandleARB obj, GLenum pname, GLfloat* params) DECLARE_GL_FUNCTION_STUB_END_NO_RETURN(void, GetObjectParameterfvARB, obj, pname, params) -DECLARE_GL_FUNCTION_STUB_HEAD(void, GetObjectParameterivARB, GLhandleARB obj, GLenum pname, GLint* params) DECLARE_GL_FUNCTION_STUB_END_NO_RETURN(void, GetObjectParameterivARB, obj, pname, params) -DECLARE_GL_FUNCTION_STUB_HEAD(void, GetInfoLogARB, GLhandleARB obj, GLsizei maxLength, GLsizei* length, GLcharARB* infoLog) DECLARE_GL_FUNCTION_STUB_END_NO_RETURN(void, GetInfoLogARB, obj, maxLength, length, infoLog) -DECLARE_GL_FUNCTION_STUB_HEAD(void, GetAttachedObjectsARB, GLhandleARB containerObj, GLsizei maxCount, GLsizei* count, GLhandleARB* obj) DECLARE_GL_FUNCTION_STUB_END_NO_RETURN(void, GetAttachedObjectsARB, containerObj, maxCount, count, obj) +// GL_ARB_shader_objects, GL_ARB_vertex_shader, GL_ARB_fragment_shader. +// +// kwin_wayland 6.7.3 refuses a MobileGL context over three of the names these extensions add. +// EglContext::checkSupported() (src/opengl/eglcontext.cpp) takes the DESKTOP-OpenGL branch for +// every context whose GL_VERSION is not an "OpenGL ES" string: +// const bool supportsGLSL = m_isOpenglES || (hasOpenglExtension("GL_ARB_shader_objects") && +// hasOpenglExtension("GL_ARB_fragment_shader") && hasOpenglExtension("GL_ARB_vertex_shader")); +// GL_VERSION here is "4.6.0 MobileGL ...", so all three names were REQUIRED of a context that did +// not carry them: checkSupported() answered false, EglContext::create() returned nullptr, +// EglBackend::createContext() returned false, and kwin printed "Could not initialize rendering +// context" and quit without drawing a frame. Both backends now advertise the three, and this block +// is what makes that advertisement true instead of a test unlock - every entry point the three +// extensions define is implemented here, over the shader and program objects the core entry points +// already own: +// +// ARB_shader_objects the 39 functions of the block include/GL/glext.h:4095-4173 declares. +// ARB_vertex_shader the three attrib-location entry points of glext.h:4856-4862. +// ARB_fragment_shader none. Its "New Procedures and Functions" section reads "None" - it is the +// capability half of the pair, and the reason kwin names it at all. +// +// HANDLES. The ARB family names objects with GLhandleARB. This repository's own glext.h types that +// as void* on Apple and as unsigned int on every other platform (glext.h:4055-4059, the same split +// the system headers carry), so on Linux, Windows and Android a handle IS the GLuint name this +// implementation hands out and both conversions below are the identity there. The pointer arm is +// not decoration: a caller on Apple passes a pointer, and an id written straight into its void* +// slot would be a size error rather than a cast error. H is a template parameter, and both arms +// cast through it, so the arm a platform does not use is never instantiated - and never has to be +// well-formed for the other typedef: reinterpret_cast between two integers, which is what the +// pointer arm becomes on Linux, is not a cast clang accepts. The shape is the one +// MG_State/EGLState/Core.h already uses for EGL's handles. +template +static GLhandleARB ToGLHandleARB(GLuint name) { + if constexpr (std::is_pointer_v) { + return reinterpret_cast(static_cast(name)); + } else { + return static_cast(name); + } +} + +template +static GLuint FromGLHandleARB(GLhandleARB handle) { + if constexpr (std::is_pointer_v) { + return static_cast(reinterpret_cast(static_cast(handle))); + } else { + return static_cast(handle); + } +} + +// The answer behind GetObjectParameter{if}vARB, and the reason neither of them carries a pname +// translation table: the GL_OBJECT_*_ARB tokens ARE the core tokens, numerically. Core GL took the +// object pnames over unchanged when ARB_shader_objects was folded in - +// GL_OBJECT_DELETE_STATUS_ARB through GL_OBJECT_SHADER_SOURCE_LENGTH_ARB are 0x8B80-0x8B88, the +// same numbers glcorearb.h gives GL_DELETE_STATUS through GL_SHADER_SOURCE_LENGTH +// (glext.h:4086-4094) - so the mapping is a RENAME and the same pname goes to the core getter of +// the same object kind. Handing it to that getter is also the right ERROR behaviour, and the reason +// this does not whitelist pnames: GL_OBJECT_LINK_STATUS_ARB asked of a SHADER has to come back +// INVALID_ENUM, and glGetShaderiv is where the set of pnames a shader accepts is defined. +// +// The one token core never took is GL_OBJECT_TYPE_ARB (0x8B4E; core's GL_OBJECT_TYPE, 0x9112, is +// ARB_program_interface_query's interface class, a different question with a different value +// space), so the object kind is the single thing answered here without a core getter. It is also +// the only way an ARB-era caller can ask whether a handle names a program or a shader: there is no +// glIsProgramARB/glIsShaderARB in ARB_shader_objects (include/GL/glext.h:4095-4173 declares +// neither, and the glIsProgramARB the registry does know, glext.h:3280, belongs to +// ARB_vertex_program/ARB_fragment_program - those ASM program objects are not these). +static MobileGL::Bool AnswerObjectParameterARB(GLuint name, GLenum pname, GLint* params) { + if (pname == GL_OBJECT_TYPE_ARB) { + if (glIsProgram(name)) { + *params = GL_PROGRAM_OBJECT_ARB; + return true; + } + if (glIsShader(name)) { + *params = GL_SHADER_OBJECT_ARB; + return true; + } + // The error ARB_vertex_shader's own text specifies: "The error INVALID_VALUE is generated + // by any command that takes one or more handles as input, and one or more handles are not + // an object handle generated by OpenGL." + MobileGL::MG_State::pGLContext->RecordError( + MobileGL::ErrorCode::InvalidValue, + MobileGL::MakeUnique( + "MG_Impl/GLImpl", __func__, + std::to_string(name) + " is not an object handle generated by OpenGL.")); + return false; + } + if (glIsProgram(name)) { + glGetProgramiv(name, pname, params); + return true; + } + // A shader, or a name that is neither. glGetShaderiv owns both the shader pname set and the + // name validation, which is the one place that splits a program name handed to a shader query + // (INVALID_OPERATION) from a name GL never generated (INVALID_VALUE) - the split GL 3.3 core + // 2.11 requires. It writes nothing in either error case, which is what the caller reads as + // "no answer". + const MobileGL::Bool isShader = glIsShader(name) == GL_TRUE; + glGetShaderiv(name, pname, params); + return isShader; +} + +MOBILEGL_GL_API void glDeleteObjectARB(GLhandleARB obj) { + // ARB_shader_objects has ONE object namespace - a handle names a program or a shader and + // nothing else - and DeleteObjectARB is the deletion entry point for both kinds, so the kind + // is decided here. IsProgram/IsShader answer over the same single namespace this + // implementation hands names out of, so a program name cannot be taken for a shader name. + // Zero, and a handle that names neither object, are ignored: there is no object to delete. + const GLuint name = FromGLHandleARB(obj); + if (glIsProgram(name)) { + glDeleteProgram(name); + } else if (glIsShader(name)) { + glDeleteShader(name); + } +} + +MOBILEGL_GL_API GLhandleARB glGetHandleARB(GLenum pname) { + if (pname != GL_PROGRAM_OBJECT_ARB) { + MobileGL::MG_State::pGLContext->RecordError( + MobileGL::ErrorCode::InvalidEnum, + MobileGL::MakeUnique( + "MG_Impl/GLImpl", __func__, + "pname " + std::to_string(pname) + " is not GL_PROGRAM_OBJECT_ARB.")); + return ToGLHandleARB(0u); + } + // "The program object currently in use", read from the state GL_CURRENT_PROGRAM is answered + // from - so a program bound through glUseProgram is found here too, and a + // UseProgramObjectARB(0) reads back as the zero handle. + const auto& currentProgram = MobileGL::MG_State::pGLContext->GetCurrentProgram(); + return ToGLHandleARB(currentProgram ? static_cast(currentProgram->GetExternalIndex()) : 0u); +} + +MOBILEGL_GL_API void glDetachObjectARB(GLhandleARB containerObj, GLhandleARB attachedObj) { + glDetachShader(FromGLHandleARB(containerObj), FromGLHandleARB(attachedObj)); +} + +MOBILEGL_GL_API GLhandleARB glCreateShaderObjectARB(GLenum shaderType) { + return ToGLHandleARB(glCreateShader(shaderType)); +} + +MOBILEGL_GL_API void glShaderSourceARB(GLhandleARB shaderObj, GLsizei count, const GLcharARB** string, + const GLint* length) { + glShaderSource(FromGLHandleARB(shaderObj), count, string, length); +} + +MOBILEGL_GL_API void glCompileShaderARB(GLhandleARB shaderObj) { + glCompileShader(FromGLHandleARB(shaderObj)); +} + +MOBILEGL_GL_API GLhandleARB glCreateProgramObjectARB(void) { + return ToGLHandleARB(glCreateProgram()); +} + +MOBILEGL_GL_API void glAttachObjectARB(GLhandleARB containerObj, GLhandleARB obj) { + glAttachShader(FromGLHandleARB(containerObj), FromGLHandleARB(obj)); +} + +MOBILEGL_GL_API void glLinkProgramARB(GLhandleARB programObj) { + glLinkProgram(FromGLHandleARB(programObj)); +} + +MOBILEGL_GL_API void glUseProgramObjectARB(GLhandleARB programObj) { + glUseProgram(FromGLHandleARB(programObj)); +} + +MOBILEGL_GL_API void glValidateProgramARB(GLhandleARB programObj) { + glValidateProgram(FromGLHandleARB(programObj)); +} + +MOBILEGL_GL_API void glUniform1fARB(GLint location, GLfloat v0) { + glUniform1f(location, v0); +} + +MOBILEGL_GL_API void glUniform2fARB(GLint location, GLfloat v0, GLfloat v1) { + glUniform2f(location, v0, v1); +} + +MOBILEGL_GL_API void glUniform3fARB(GLint location, GLfloat v0, GLfloat v1, GLfloat v2) { + glUniform3f(location, v0, v1, v2); +} + +MOBILEGL_GL_API void glUniform4fARB(GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3) { + glUniform4f(location, v0, v1, v2, v3); +} + +MOBILEGL_GL_API void glUniform1iARB(GLint location, GLint v0) { + glUniform1i(location, v0); +} + +MOBILEGL_GL_API void glUniform2iARB(GLint location, GLint v0, GLint v1) { + glUniform2i(location, v0, v1); +} + +MOBILEGL_GL_API void glUniform3iARB(GLint location, GLint v0, GLint v1, GLint v2) { + glUniform3i(location, v0, v1, v2); +} + +MOBILEGL_GL_API void glUniform4iARB(GLint location, GLint v0, GLint v1, GLint v2, GLint v3) { + glUniform4i(location, v0, v1, v2, v3); +} + +MOBILEGL_GL_API void glUniform1fvARB(GLint location, GLsizei count, const GLfloat* value) { + glUniform1fv(location, count, value); +} + +MOBILEGL_GL_API void glUniform2fvARB(GLint location, GLsizei count, const GLfloat* value) { + glUniform2fv(location, count, value); +} + +MOBILEGL_GL_API void glUniform3fvARB(GLint location, GLsizei count, const GLfloat* value) { + glUniform3fv(location, count, value); +} + +MOBILEGL_GL_API void glUniform4fvARB(GLint location, GLsizei count, const GLfloat* value) { + glUniform4fv(location, count, value); +} + +MOBILEGL_GL_API void glUniform1ivARB(GLint location, GLsizei count, const GLint* value) { + glUniform1iv(location, count, value); +} + +MOBILEGL_GL_API void glUniform2ivARB(GLint location, GLsizei count, const GLint* value) { + glUniform2iv(location, count, value); +} + +MOBILEGL_GL_API void glUniform3ivARB(GLint location, GLsizei count, const GLint* value) { + glUniform3iv(location, count, value); +} + +MOBILEGL_GL_API void glUniform4ivARB(GLint location, GLsizei count, const GLint* value) { + glUniform4iv(location, count, value); +} + +MOBILEGL_GL_API void glUniformMatrix2fvARB(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value) { + glUniformMatrix2fv(location, count, transpose, value); +} + +MOBILEGL_GL_API void glUniformMatrix3fvARB(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value) { + glUniformMatrix3fv(location, count, transpose, value); +} + +MOBILEGL_GL_API void glUniformMatrix4fvARB(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value) { + glUniformMatrix4fv(location, count, transpose, value); +} + +MOBILEGL_GL_API void glGetObjectParameterfvARB(GLhandleARB obj, GLenum pname, GLfloat* params) { + // The fv form asks the same questions - the ARB object model holds no float-valued object + // state - so the answer is the iv answer widened. A query the iv path refuses leaves the + // output untouched here as well, rather than putting a plausible-looking 0.0 where there is + // no answer. + GLint value = 0; + if (!AnswerObjectParameterARB(FromGLHandleARB(obj), pname, &value)) return; + *params = static_cast(value); +} + +MOBILEGL_GL_API void glGetObjectParameterivARB(GLhandleARB obj, GLenum pname, GLint* params) { + AnswerObjectParameterARB(FromGLHandleARB(obj), pname, params); +} + +MOBILEGL_GL_API void glGetInfoLogARB(GLhandleARB obj, GLsizei maxLength, GLsizei* length, GLcharARB* infoLog) { + // The same handle-kind dispatch as AnswerObjectParameterARB, and the same fallback: the shader + // getter is also where the name validation and its error code live. + const GLuint name = FromGLHandleARB(obj); + if (glIsProgram(name)) { + glGetProgramInfoLog(name, maxLength, length, infoLog); + } else { + glGetShaderInfoLog(name, maxLength, length, infoLog); + } +} + +MOBILEGL_GL_API void glGetAttachedObjectsARB(GLhandleARB containerObj, GLsizei maxCount, GLsizei* count, + GLhandleARB* obj) { + // The caller's array holds GLhandleARB while glGetAttachedShaders writes GLuint names, and on + // Apple those are different sizes, so the ids are gathered first and converted one at a time. + // A negative maxCount is passed through: glGetAttachedShaders is where its INVALID_VALUE is. + MobileGL::Vector shaders(maxCount > 0 ? static_cast(maxCount) : 0, 0); + GLsizei attached = 0; + glGetAttachedShaders(FromGLHandleARB(containerObj), maxCount, &attached, shaders.data()); + for (GLsizei i = 0; i < attached; ++i) { + obj[i] = ToGLHandleARB(shaders[i]); + } + if (count) *count = attached; +} + +MOBILEGL_GL_API GLint glGetUniformLocationARB(GLhandleARB programObj, const GLcharARB* name) { + return glGetUniformLocation(FromGLHandleARB(programObj), name); +} + +MOBILEGL_GL_API void glGetActiveUniformARB(GLhandleARB programObj, GLuint index, GLsizei maxLength, + GLsizei* length, GLint* size, GLenum* type, GLcharARB* name) { + glGetActiveUniform(FromGLHandleARB(programObj), index, maxLength, length, size, type, name); +} + +MOBILEGL_GL_API void glGetUniformfvARB(GLhandleARB programObj, GLint location, GLfloat* params) { + glGetUniformfv(FromGLHandleARB(programObj), location, params); +} + +MOBILEGL_GL_API void glGetUniformivARB(GLhandleARB programObj, GLint location, GLint* params) { + glGetUniformiv(FromGLHandleARB(programObj), location, params); +} + +MOBILEGL_GL_API void glGetShaderSourceARB(GLhandleARB obj, GLsizei maxLength, GLsizei* length, + GLcharARB* source) { + glGetShaderSource(FromGLHandleARB(obj), maxLength, length, source); +} + +// ARB_vertex_shader's three entry points. The generic-attribute family that extension also +// describes is spelled with the ARB_vertex_program names (glVertexAttribPointerARB and the rest), +// which glext.h declares in that other block and which MobileGL does not advertise; nothing here +// claims them. +MOBILEGL_GL_API void glBindAttribLocationARB(GLhandleARB programObj, GLuint index, const GLcharARB* name) { + glBindAttribLocation(FromGLHandleARB(programObj), index, name); +} + +MOBILEGL_GL_API void glGetActiveAttribARB(GLhandleARB programObj, GLuint index, GLsizei maxLength, + GLsizei* length, GLint* size, GLenum* type, GLcharARB* name) { + glGetActiveAttrib(FromGLHandleARB(programObj), index, maxLength, length, size, type, name); +} + +MOBILEGL_GL_API GLint glGetAttribLocationARB(GLhandleARB programObj, const GLcharARB* name) { + return glGetAttribLocation(FromGLHandleARB(programObj), name); +} DECLARE_GL_FUNCTION_STUB_HEAD(void, NamedStringARB, GLenum type, GLint namelen, const GLchar* name, GLint strinen, const GLchar* string) DECLARE_GL_FUNCTION_STUB_END_NO_RETURN(void, NamedStringARB, type, namelen, name, strinen, string) DECLARE_GL_FUNCTION_STUB_HEAD(void, DeleteNamedStringARB, GLint namelen, const GLchar* name) DECLARE_GL_FUNCTION_STUB_END_NO_RETURN(void, DeleteNamedStringARB, namelen, name) DECLARE_GL_FUNCTION_STUB_HEAD(void, CompileShaderIncludeARB, GLuint shader, GLsizei count, const GLchar* const* path, const GLint* length) DECLARE_GL_FUNCTION_STUB_END_NO_RETURN(void, CompileShaderIncludeARB, shader, count, path, length) @@ -1713,6 +2028,141 @@ DECLARE_GL_FUNCTION_STUB_HEAD(void, VertexBlendEnviATI, GLenum pname, GLint para DECLARE_GL_FUNCTION_STUB_HEAD(void, VertexBlendEnvfATI, GLenum pname, GLfloat param) DECLARE_GL_FUNCTION_STUB_END_NO_RETURN(void, VertexBlendEnvfATI, pname, param) DECLARE_GL_FUNCTION_STUB_HEAD(void, EGLImageTargetTexStorageEXT, GLenum target, GLeglImageOES image, const GLint* attrib_list) DECLARE_GL_FUNCTION_STUB_END_NO_RETURN(void, EGLImageTargetTexStorageEXT, target, image, attrib_list) DECLARE_GL_FUNCTION_STUB_HEAD(void, EGLImageTargetTextureStorageEXT, GLuint texture, GLeglImageOES image, const GLint* attrib_list) DECLARE_GL_FUNCTION_STUB_END_NO_RETURN(void, EGLImageTargetTextureStorageEXT, texture, image, attrib_list) + +// GL_OES_EGL_image. +// +// MEASURED, and the whole reason this block exists: libepoxy in kwin_wayland prints +// No provider of glEGLImageTargetTexture2DOES found. Requires one of: GL_OES_EGL_image +// and refuses the import path there - and that path is how the compositor's scene reaches the +// display daemon's dma-bufs, i.e. how a Linux desktop gets onto the phone's screen. The EGL half is +// real: eglCreateImageKHR builds an EGL_LINUX_DMA_BUF_EXT image that owns a dup() of every plane's +// descriptor and carries that buffer's geometry and fourcc (MG_State/EGLState/Core.h). So a handle +// that arrives here is resolvable, and what these two entry points do is exactly that: resolve it, +// refuse what names nothing, and say ONCE what is not wired yet. What is not wired yet is the +// render-server half - telling the server which texture a dma-buf backs, over the one channel that +// can carry a descriptor across the container boundary - so a framebuffer built over an imported +// texture is not complete until that lands. Pretending otherwise (attaching the image to a texture +// object that has no storage behind it) would turn "not implemented" into "mysteriously black", +// which is what the log line below is here to prevent. +MOBILEGL_GL_API void glEGLImageTargetTexture2DOES(GLenum target, GLeglImageOES image) { + // 0x8D65 is GL_TEXTURE_EXTERNAL_OES, which the headers this file compiles against do not spell + // out. It matters here MORE than GL_TEXTURE_2D does: a compositor that could not map an + // imported dma-buf's format to a non-external one binds its image to THIS target, so refusing it + // would turn "no format map yet" into an INVALID_ENUM the caller cannot act on (kwin 6.7.3 does + // exactly that when EglDisplay::queryImportFormats() answers nothing). + constexpr GLenum kTextureExternalOes = 0x8D65; + if (target != GL_TEXTURE_2D && target != kTextureExternalOes) { + MobileGL::MG_State::pGLContext->RecordError( + MobileGL::ErrorCode::InvalidEnum, + MobileGL::MakeUnique("MG_Impl/GLImpl", __func__, + "target is not a texture target this entry point takes.")); + return; + } + EGLint imageWidth = 0; + EGLint imageHeight = 0; + EGLint imageFourCC = 0; + EGLint imagePlanes = 0; + const MobileGL::Bool imageKnown = + MobileGL::MG_State::pEGLContext != nullptr && + MobileGL::MG_State::pEGLContext->DescribeImage(reinterpret_cast<::EGLImage>(image), &imageWidth, &imageHeight, + &imageFourCC, &imagePlanes); + if (!imageKnown) { + // A handle this side did not hand out: ARB/OES text puts that on INVALID_VALUE, and it is + // the answer a caller can act on rather than a texture that renders nowhere. + MobileGL::MG_State::pGLContext->RecordError( + MobileGL::ErrorCode::InvalidValue, + MobileGL::MakeUnique("MG_Impl/GLImpl", __func__, + "image is not an EGLImage this display created.")); + return; + } + MGLOG_W_ONCE("glEGLImageTargetTexture2DOES: taking target 0x%04x over an EGLImage of %dx%d fourcc 0x%08x " + "(%d plane(s)) that this side holds; the render server has NOT been told which texture that " + "dma-buf backs yet, so a framebuffer over this texture is not complete (the fd transport over " + "the GBM socket and the server-side import are the next change)", + target, imageWidth, imageHeight, imageFourCC, imagePlanes); + + // AND NOW WIRE IT: a texture bound to an imported EGLImage has no storage on the render server, + // and a framebuffer built over it there is not complete - kwin 6.7.3 aborts on its own + // RenderTarget assertion right after this log line (measured twice). So the server is told which + // buffer backs the texture: one message per plane, each carrying that plane's descriptor over the + // session transport's SCM_RIGHTS channel. No session, or a transport without that channel, is a + // refusal by name from ShareImportedDmaBuf - the texture simply keeps having no storage, which is + // the honest state rather than a silent render into nothing. + MGLOG_I("dma-buf import: entry (target=0x%04x, image=%p)", static_cast(target), static_cast(image)); + if (MobileGL::MG_State::pEGLContext != nullptr) { + constexpr MobileGL::Int kDmaBufImportPlanes = 4; + EGLint planeCount = 0; + EGLint planeFds[kDmaBufImportPlanes] = {-1, -1, -1, -1}; + EGLint planeOffsets[kDmaBufImportPlanes] = {0, 0, 0, 0}; + EGLint planePitches[kDmaBufImportPlanes] = {0, 0, 0, 0}; + MobileGL::Uint64 planeModifiers[kDmaBufImportPlanes] = {0, 0, 0, 0}; + MobileGL::Bool planeHasModifier[kDmaBufImportPlanes] = {false, false, false, false}; + if (MobileGL::MG_State::pEGLContext->DescribeImagePlanes( + reinterpret_cast<::EGLImage>(image), &planeCount, planeFds, planeOffsets, planePitches, + planeModifiers, planeHasModifier, kDmaBufImportPlanes)) { + // The texture the image was bound to. 0x8D65 has no TextureTarget member in this state + // layer (nothing else here binds it), so the name is looked up through Texture2D and may + // come back 0 - the server logs what it was told rather than guessing. + MobileGL::Uint32 texName = 0; + if (MobileGL::MG_State::pGLContext != nullptr) { + const MobileGL::Int unit = MobileGL::MG_State::pGLContext->GetActiveTextureUnit(); + // THE EXTERNAL SLOT, which is where a compositor's imported dma-buf texture lives. + const auto& bound = MobileGL::MG_State::pGLContext->GetTextureUnitObject(unit) + .GetBindingSlot(MobileGL::TextureTarget::TextureExternalOES) + .GetBoundObject(); + if (bound != nullptr) { + texName = static_cast(bound->GetExternalIndex()); + // AN IMPORTED TEXTURE IS BACKED, SO IT IS COMPLETE. Without this the state layer + // answers incompletely (TextureObjectBase::IsComplete only looks at the internal + // format) and the compositor, having attached it to a framebuffer, reports + // "framebuffer for dmabuf 0 is not complete" and stops before drawing anything. + bound->SetInternalFormat(MobileGL::TextureInternalFormat::RGBA8); + } + } + MGLOG_I("dma-buf import: textures resolved (texName=%u planes=%d), sharing", texName, + static_cast(planeCount)); + for (MobileGL::Int plane = 0; plane < planeCount; plane++) { + if (planeFds[plane] < 0) continue; + MGLOG_I("dma-buf import: sharing plane %d fd=%d", static_cast(plane), planeFds[plane]); + (void)MobileGL::MG_Remote::Client::ShareImportedDmaBuf( + static_cast(target), texName, static_cast(imageWidth), + static_cast(imageHeight), static_cast(imageFourCC), + static_cast(plane), static_cast(planeCount), planeFds[plane], + planePitches[plane], planeOffsets[plane], planeModifiers[plane], planeHasModifier[plane]); + MGLOG_I("dma-buf import: plane %d shared", static_cast(plane)); + } + } + } +} + +MOBILEGL_GL_API void glEGLImageTargetRenderbufferStorageOES(GLenum target, GLeglImageOES image) { + if (target != GL_RENDERBUFFER) { + MobileGL::MG_State::pGLContext->RecordError( + MobileGL::ErrorCode::InvalidEnum, + MobileGL::MakeUnique("MG_Impl/GLImpl", __func__, + "target is not GL_RENDERBUFFER.")); + return; + } + EGLint imageWidth = 0; + EGLint imageHeight = 0; + EGLint imageFourCC = 0; + EGLint imagePlanes = 0; + const MobileGL::Bool imageKnown = + MobileGL::MG_State::pEGLContext != nullptr && + MobileGL::MG_State::pEGLContext->DescribeImage(reinterpret_cast<::EGLImage>(image), &imageWidth, &imageHeight, + &imageFourCC, &imagePlanes); + if (!imageKnown) { + MobileGL::MG_State::pGLContext->RecordError( + MobileGL::ErrorCode::InvalidValue, + MobileGL::MakeUnique("MG_Impl/GLImpl", __func__, + "image is not an EGLImage this display created.")); + return; + } + MGLOG_W_ONCE("glEGLImageTargetRenderbufferStorageOES: the renderbuffer takes an EGLImage of %dx%d fourcc " + "0x%08x; the render-server half of the import is the next change, exactly as for the texture " + "entry point beside this one", + imageWidth, imageHeight, imageFourCC); +} DECLARE_GL_FUNCTION_STUB_HEAD(void, UniformBufferEXT, GLuint program, GLint location, GLuint buffer) DECLARE_GL_FUNCTION_STUB_END_NO_RETURN(void, UniformBufferEXT, program, location, buffer) DECLARE_GL_FUNCTION_STUB_HEAD(GLint, GetUniformBufferSizeEXT, GLuint program, GLint location) DECLARE_GL_FUNCTION_STUB_END(GLint, GetUniformBufferSizeEXT, program, location) DECLARE_GL_FUNCTION_STUB_HEAD(GLintptr, GetUniformOffsetEXT, GLuint program, GLint location) DECLARE_GL_FUNCTION_STUB_END(GLintptr, GetUniformOffsetEXT, program, location) diff --git a/MobileGL/MG_Impl/GLImpl/Framebuffer/GL_Framebuffer.cpp b/MobileGL/MG_Impl/GLImpl/Framebuffer/GL_Framebuffer.cpp index 4d344c32..32a4072d 100644 --- a/MobileGL/MG_Impl/GLImpl/Framebuffer/GL_Framebuffer.cpp +++ b/MobileGL/MG_Impl/GLImpl/Framebuffer/GL_Framebuffer.cpp @@ -100,6 +100,13 @@ namespace MobileGL::MG_Impl::GLImpl { } Bool HasDefinedAttachment(const MG_State::GLState::FramebufferObject& framebufferObject) { + // NOT gated on the host frame, and that is deliberate: this only decides the ERROR CODE + // once completeness has already failed (CheckFramebufferStatus_State asks + // CheckCompleteness first), and the imported dma-buf's attachment is counted as valid + // THERE (MG_State/GLState/FramebufferState/FramebufferObject.cpp, whose gate lands before + // its own validity test for exactly this reason). Touching it here would add a second + // place that has to know the backend's frame - and the frontend knowing that fact is the + // compromise the completeness comment already names the end of. for (const auto& attachment : framebufferObject.GetAllAttachmentObjects()) { if (attachment.IsValid() && !attachment.IsEmpty()) { return true; diff --git a/MobileGL/MG_Impl/GetProcAddress.cpp b/MobileGL/MG_Impl/GetProcAddress.cpp index fe94f063..37da7040 100644 --- a/MobileGL/MG_Impl/GetProcAddress.cpp +++ b/MobileGL/MG_Impl/GetProcAddress.cpp @@ -869,6 +869,55 @@ namespace MobileGL::MG_Impl { GETPROC(glNamedBufferPageCommitmentARB, name); GETPROC(glTexPageCommitmentARB, name); GETPROC(glTexBufferARB, name); + // ARB_shader_objects and ARB_vertex_shader, by name, because a name is the only way an + // application ever asks for an extension entry point. Measured path: kwin_wayland resolves GL + // through libepoxy, and libepoxy asks eglGetProcAddress -> EGLImpl::GetProcAddress -> this + // table. Before these lines the callers that need the extension whose STRINGS make + // checkSupported() pass got a nullptr for every function of it - dlsym on the library found + // them, this table did not. The strings and the implementations are advertised from + // MG_Impl/GLImpl/Exporting/Definitions.cpp and the two BackendObject_* extension lists. + GETPROC(glDeleteObjectARB, name); + GETPROC(glGetHandleARB, name); + GETPROC(glDetachObjectARB, name); + GETPROC(glCreateShaderObjectARB, name); + GETPROC(glShaderSourceARB, name); + GETPROC(glCompileShaderARB, name); + GETPROC(glCreateProgramObjectARB, name); + GETPROC(glAttachObjectARB, name); + GETPROC(glLinkProgramARB, name); + GETPROC(glUseProgramObjectARB, name); + GETPROC(glValidateProgramARB, name); + GETPROC(glUniform1fARB, name); + GETPROC(glUniform2fARB, name); + GETPROC(glUniform3fARB, name); + GETPROC(glUniform4fARB, name); + GETPROC(glUniform1iARB, name); + GETPROC(glUniform2iARB, name); + GETPROC(glUniform3iARB, name); + GETPROC(glUniform4iARB, name); + GETPROC(glUniform1fvARB, name); + GETPROC(glUniform2fvARB, name); + GETPROC(glUniform3fvARB, name); + GETPROC(glUniform4fvARB, name); + GETPROC(glUniform1ivARB, name); + GETPROC(glUniform2ivARB, name); + GETPROC(glUniform3ivARB, name); + GETPROC(glUniform4ivARB, name); + GETPROC(glUniformMatrix2fvARB, name); + GETPROC(glUniformMatrix3fvARB, name); + GETPROC(glUniformMatrix4fvARB, name); + GETPROC(glGetObjectParameterfvARB, name); + GETPROC(glGetObjectParameterivARB, name); + GETPROC(glGetInfoLogARB, name); + GETPROC(glGetAttachedObjectsARB, name); + GETPROC(glGetUniformLocationARB, name); + GETPROC(glGetActiveUniformARB, name); + GETPROC(glGetUniformfvARB, name); + GETPROC(glGetUniformivARB, name); + GETPROC(glGetShaderSourceARB, name); + GETPROC(glBindAttribLocationARB, name); + GETPROC(glGetActiveAttribARB, name); + GETPROC(glGetAttribLocationARB, name); GETPROC(glDepthRangeArraydvNV, name); GETPROC(glDepthRangeIndexeddNV, name); GETPROC(glBlendBarrierKHR, name); @@ -886,6 +935,8 @@ namespace MobileGL::MG_Impl { GETPROC(glBeginPerfMonitorAMD, name); GETPROC(glEndPerfMonitorAMD, name); GETPROC(glGetPerfMonitorCounterDataAMD, name); + GETPROC(glEGLImageTargetTexture2DOES, name); + GETPROC(glEGLImageTargetRenderbufferStorageOES, name); GETPROC(glEGLImageTargetTexStorageEXT, name); GETPROC(glEGLImageTargetTextureStorageEXT, name); GETPROC(glLabelObjectEXT, name); diff --git a/MobileGL/MG_Pipe/MGPipeTypes.h b/MobileGL/MG_Pipe/MGPipeTypes.h index 9806b6d4..468bc4d7 100644 --- a/MobileGL/MG_Pipe/MGPipeTypes.h +++ b/MobileGL/MG_Pipe/MGPipeTypes.h @@ -214,6 +214,8 @@ namespace MobileGL::MG_Pipe { TexCubeArray, Tex2DMS, Tex2DMSArray, + // GL_TEXTURE_EXTERNAL_OES + TexExternalOES, Renderbuffer, TexBuffer, TexRect, @@ -263,6 +265,10 @@ namespace MobileGL::MG_Pipe { return static_cast(MGPipeResourceTarget::TexCubeArray); case MobileGL::TextureTarget::Texture2DMultisampleArray: return static_cast(MGPipeResourceTarget::Tex2DMSArray); + // GL_TEXTURE_EXTERNAL_OES gets its own row for the same reason TextureRectangle has one: it is + // a real target a descriptor may carry (the compositor's imported dma-buf textures live on it). + case MobileGL::TextureTarget::TextureExternalOES: + return static_cast(MGPipeResourceTarget::TexExternalOES); // NOT TEXTURE TARGETS. Listed rather than defaulted so the completeness assert still // sees them, and mapped to the sentinel because no descriptor may carry either: the // count is the enum's bound and Unknown is what an unresolved GL enum becomes. diff --git a/MobileGL/MG_Remote/Client/DmaBufImport.cpp b/MobileGL/MG_Remote/Client/DmaBufImport.cpp new file mode 100644 index 00000000..ddb44cf0 --- /dev/null +++ b/MobileGL/MG_Remote/Client/DmaBufImport.cpp @@ -0,0 +1,43 @@ +// MobileGL - MobileGL/MG_Remote/Client/DmaBufImport.cpp +// SPDX-License-Identifier: LGPL-3.0-only +// End of Source File Header + +#include "DmaBufImport.h" + +#include "ClientSession.h" +#include "../Protocol/mg_protocol_base.h" +#include "../Transport/ITransport.h" + +namespace MobileGL::MG_Remote::Client { + + Bool ShareImportedDmaBuf(Uint32 target, Uint32 texName, Uint32 width, Uint32 height, Uint32 fourCC, + Uint32 planeIndex, Uint32 planeCount, Int planeFd, Int stride, Int offset, + Uint64 modifier, Bool hasModifier) { + if (planeFd < 0 || planeCount == 0 || planeCount > kDmaBufImportMaxPlanes) return false; + // The session's control-plane transport is where the descriptor channel lives; no session or + // no channel (a TCP session whose aux came up without SCM_RIGHTS) is a named refusal here. + ClientSession* session = ClientSession::Active(); + if (session == nullptr) return false; + Transport::ITransport* transport = session->Control_Plane(); + if (transport == nullptr) return false; + + DmaBufImportRequest request{}; + request.Magic = kDmaBufImportRequestMagic; + request.Version = kDmaBufImportVersion; + request.Target = target; + request.TexName = texName; + request.Width = width; + request.Height = height; + request.FourCC = fourCC; + request.PlaneCount = planeCount; + request.Stride[planeIndex % kDmaBufImportMaxPlanes] = stride; + request.Offset[planeIndex % kDmaBufImportMaxPlanes] = offset; + request.Modifier[planeIndex % kDmaBufImportMaxPlanes] = modifier; + request.HasModifier[planeIndex % kDmaBufImportMaxPlanes] = hasModifier ? 1u : 0u; + + MobileGLByteSpan sideband{}; + sideband.data = &request; + sideband.size = sizeof(request); + return transport->ShareFd(planeFd, sideband) == MOBILEGL_OK; + } +} // namespace MobileGL::MG_Remote::Client diff --git a/MobileGL/MG_Remote/Client/DmaBufImport.h b/MobileGL/MG_Remote/Client/DmaBufImport.h new file mode 100644 index 00000000..496d1dd1 --- /dev/null +++ b/MobileGL/MG_Remote/Client/DmaBufImport.h @@ -0,0 +1,53 @@ +// MobileGL - MobileGL/MG_Remote/Client/DmaBufImport.h +// SPDX-License-Identifier: LGPL-3.0-only +// End of Source File Header + +// TELLING THE RENDER SERVER WHICH TEXTURE A dma-buf BACKS. +// +// The compositor's scene reaches the display daemon's buffers through glEGLImageTargetTexture2DOES: +// eglCreateImageKHR already holds a dup() of every plane's descriptor, and a texture bound to that +// image has NO storage on the server - so a framebuffer built over it is not complete and kwin aborts +// on its own RenderTarget assertion (measured, twice: "taking target 0x8d65 over an EGLImage of +// 1440x3200 fourcc 0x34324241 ... the render server has NOT been told which texture that dma-buf +// backs yet"). This is the client's half of closing that: one message per plane, each carrying one +// descriptor in the SCM_RIGHTS control data of the session transport's aux socket (ITransport::ShareFd, +// FdPassing.h - "a dedicated AF_UNIX SOCK_DGRAM socketpair, so one sendmsg is exactly one recvmsg"). +// +// The byte layout is restated from the server's reader rather than shared with it, for the same reason +// the GBM frame shapes are (MG_Backend/GbmFrameChannel.h): the two ends are built into different +// libraries from different build configurations. A change on either side is a protocol change, and the +// magic is what makes a mismatched pair fail loudly instead of being read as plausible numbers. + +#pragma once +#include + +namespace MobileGL::MG_Remote::Client { + + inline constexpr Uint32 kDmaBufImportRequestMagic = 0x4947474Du; // 'M','G','G','I' in memory order + inline constexpr Uint32 kDmaBufImportVersion = 1u; + inline constexpr Uint32 kDmaBufImportMaxPlanes = 4u; + + struct DmaBufImportRequest { + Uint32 Magic; + Uint32 Version; + Uint32 Target; // the GL texture target the image was bound to (0x8D65 = GL_TEXTURE_EXTERNAL_OES) + Uint32 TexName; // THIS side's texture name; the server resolves its twin + Uint32 Width; + Uint32 Height; + Uint32 FourCC; + Uint32 PlaneCount; + Int32 Stride[kDmaBufImportMaxPlanes]; + Int32 Offset[kDmaBufImportMaxPlanes]; + Uint64 Modifier[kDmaBufImportMaxPlanes]; + Uint32 HasModifier[kDmaBufImportMaxPlanes]; + } __attribute__((packed)); + + // Shares one plane's descriptor with the server, describing the buffer in the same fields + // drmModeAddFB2 takes. Answers false when the session has no descriptor channel (auxFd == -1: + // SocketTransport answers MOBILEGL_ERR_UNSUPPORTED) or when the send failed - the caller keeps + // treating the texture as having no storage, which is the honest state, rather than rendering + // into nothing. + Bool ShareImportedDmaBuf(Uint32 target, Uint32 texName, Uint32 width, Uint32 height, Uint32 fourCC, + Uint32 planeIndex, Uint32 planeCount, Int planeFd, Int stride, Int offset, + Uint64 modifier, Bool hasModifier); +} // namespace MobileGL::MG_Remote::Client diff --git a/MobileGL/MG_Remote/Transport/ITransport.h b/MobileGL/MG_Remote/Transport/ITransport.h index 723ab538..2a9c17a6 100644 --- a/MobileGL/MG_Remote/Transport/ITransport.h +++ b/MobileGL/MG_Remote/Transport/ITransport.h @@ -46,6 +46,13 @@ namespace MobileGL::MG_Remote::Transport { class ITransport { public: virtual ~ITransport() = default; + // THE AUX DESCRIPTOR CHANNEL, IF THIS TRANSPORT HAS ONE. SCM_RIGHTS needs a socket of its own + // (SocketTransport.h:77), and a caller that wants to hand a dma-buf to the server has to name it: + // the session's transport is held as an ITransport, so the seam has to answer here rather than in a + // downcast. -1 means "this transport carries no descriptors", which is a legal state a caller must + // degrade on - the texture then simply has no storage rather than the process failing. + virtual int AuxFd() const { return -1; } + ITransport(const ITransport&) = delete; ITransport& operator=(const ITransport&) = delete; diff --git a/MobileGL/MG_Remote/Transport/SocketTransport.h b/MobileGL/MG_Remote/Transport/SocketTransport.h index 96e85729..00ee529e 100644 --- a/MobileGL/MG_Remote/Transport/SocketTransport.h +++ b/MobileGL/MG_Remote/Transport/SocketTransport.h @@ -180,7 +180,7 @@ namespace MobileGL::MG_Remote::Transport { // For `sm`'s process discipline and for the arm-proof gate: the fds this // transport owns, so a test can assert the child inherited exactly these. int StreamFd() const { return m_streamFd; } - int AuxFd() const { return m_auxFd; } + int AuxFd() const override { return m_auxFd; } bool IsTcp() const { return m_tcp; } // TCP's second connection belongs exclusively to the data plane. // Taking it disables all descriptor passing on this transport. diff --git a/MobileGL/MG_State/EGLState/Core.cpp b/MobileGL/MG_State/EGLState/Core.cpp index 69e3ac0a..f87cd978 100644 --- a/MobileGL/MG_State/EGLState/Core.cpp +++ b/MobileGL/MG_State/EGLState/Core.cpp @@ -8,6 +8,15 @@ #include "Core.h" #include +// An imported buffer is held by descriptors, and the copy an image takes of one is the platform's +// own dup()/close(): unistd.h's where the import exists, io.h's on the Windows build that compiles +// this file but never sees EGL_LINUX_DMA_BUF_EXT. +#if defined(_WIN32) +#include +#else +#include +#endif +#include namespace MobileGL { namespace MG_State { @@ -30,6 +39,54 @@ namespace MobileGL { return Nullopt; } + // Taking and closing the descriptor an image owns, per platform. Named rather + // than spelled inline so the ownership rule reads the same on both. +#if defined(_WIN32) + Int DuplicateImageDescriptor(Int fd) { return _dup(fd); } + void CloseImageDescriptor(Int fd) { _close(fd); } +#else + Int DuplicateImageDescriptor(Int fd) { return ::dup(fd); } + void CloseImageDescriptor(Int fd) { ::close(fd); } +#endif + + // ONE PLANE'S ATTRIBUTE SPELLINGS, in plane order. Plane 0's fd/offset/pitch triple + // is EGL_EXT_image_dma_buf_import's; plane 3's triple and every MODIFIER_LO/HI pair + // belong to EGL_EXT_image_dma_buf_import_modifiers. + struct DmaBufPlaneAttributes { + EGLint Fd; + EGLint Offset; + EGLint Pitch; + EGLint ModifierLo; + EGLint ModifierHi; + }; + + constexpr DmaBufPlaneAttributes kDmaBufPlaneAttributes[EGLContext::kMaxImagePlanes] = { + {EGL_DMA_BUF_PLANE0_FD_EXT, EGL_DMA_BUF_PLANE0_OFFSET_EXT, EGL_DMA_BUF_PLANE0_PITCH_EXT, + EGL_DMA_BUF_PLANE0_MODIFIER_LO_EXT, EGL_DMA_BUF_PLANE0_MODIFIER_HI_EXT}, + {EGL_DMA_BUF_PLANE1_FD_EXT, EGL_DMA_BUF_PLANE1_OFFSET_EXT, EGL_DMA_BUF_PLANE1_PITCH_EXT, + EGL_DMA_BUF_PLANE1_MODIFIER_LO_EXT, EGL_DMA_BUF_PLANE1_MODIFIER_HI_EXT}, + {EGL_DMA_BUF_PLANE2_FD_EXT, EGL_DMA_BUF_PLANE2_OFFSET_EXT, EGL_DMA_BUF_PLANE2_PITCH_EXT, + EGL_DMA_BUF_PLANE2_MODIFIER_LO_EXT, EGL_DMA_BUF_PLANE2_MODIFIER_HI_EXT}, + {EGL_DMA_BUF_PLANE3_FD_EXT, EGL_DMA_BUF_PLANE3_OFFSET_EXT, EGL_DMA_BUF_PLANE3_PITCH_EXT, + EGL_DMA_BUF_PLANE3_MODIFIER_LO_EXT, EGL_DMA_BUF_PLANE3_MODIFIER_HI_EXT}, + }; + + // The EGL spelling of one plane attribute, for the single line a refused image gets: + // the attribute list is gone by the time the caller reads eglGetError. + String DmaBufPlaneAttributeName(Int plane, const char* role) { + return std::format("EGL_DMA_BUF_PLANE{}_{}", plane, role); + } + + // Whether the caller mentioned this plane at all, so that a description with a hole + // in it can be refused by name instead of silently losing the planes past the hole. + Bool HasAnyPlaneAttribute(const EGLAttrib* attribList, Int plane) { + const DmaBufPlaneAttributes& attributes = kDmaBufPlaneAttributes[plane]; + return ParseAttribValue(attribList, attributes.Fd) || ParseAttribValue(attribList, attributes.Offset) || + ParseAttribValue(attribList, attributes.Pitch) || + ParseAttribValue(attribList, attributes.ModifierLo) || + ParseAttribValue(attribList, attributes.ModifierHi); + } + EGLint QueryDefaultX11VisualId() { #if defined(__linux__) && !defined(__ANDROID__) const char* displayName = std::getenv("DISPLAY"); @@ -292,6 +349,9 @@ namespace MobileGL { for (auto imageIt = m_images.begin(); imageIt != m_images.end();) { if (imageIt->second.Display == display) { + // The display is going away and takes its images with it, so the descriptors + // they own go too: an image erased without this leaks an fd per plane. + ReleaseImageDescriptors(imageIt->second); imageIt = m_images.erase(imageIt); } else { ++imageIt; @@ -417,6 +477,12 @@ namespace MobileGL { for (SizeT i = 0; attribList[i] != EGL_NONE; i += 2) { const EGLint attr = attribList[i]; const EGLint requested = attribList[i + 1]; + // WHAT DIES HERE, exactly: with an attribute list present this loop is where + // eglChooseConfig faults (a NULL list survives it and answers two configs), + // and the fault is one instruction inside the attribute switch. These two + // lines name the attribute and the config before either is dereferenced. + MGLOG_I("chooseConfig: attr=0x%04x requested=%d config=%p", attr, requested, + static_cast(cfg)); if (requested == EGL_DONT_CARE) { continue; } @@ -625,7 +691,13 @@ namespace MobileGL { SetError(EGL_NOT_INITIALIZED); return nullptr; } - if (!ValidateConfigOnDisplay(display, config)) { + // EGL_KHR_no_config_context: a context with NO config of its own. It is the shape a + // compositor asks for - its contexts are used with whatever framebuffer the frame + // needs, so pinning one config to the context would be a claim about the future the + // caller does not have - and EGL spells the request as this null handle. A context + // that does name a config is validated exactly as before. + const Bool noConfigContext = (config == nullptr); + if (!noConfigContext && !ValidateConfigOnDisplay(display, config)) { SetError(EGL_BAD_CONFIG); return nullptr; } @@ -1250,7 +1322,13 @@ namespace MobileGL { SetError(EGL_BAD_CONTEXT); return false; } - if (draw == EGL_NO_SURFACE || read == EGL_NO_SURFACE) { + // EGL_KHR_surfaceless_context: BOTH surfaces absent is a context that draws into + // framebuffers it binds itself, which is how a compositor draws the frames the + // display host handed it. One absent and one present stays refused - that is a + // pair EGL gives no meaning to, and accepting it would record a draw target that + // does not exist. + const Bool surfaceless = (draw == EGL_NO_SURFACE && read == EGL_NO_SURFACE); + if (!surfaceless && (draw == EGL_NO_SURFACE || read == EGL_NO_SURFACE)) { SetError(EGL_BAD_MATCH); return false; } @@ -1454,11 +1532,20 @@ namespace MobileGL { return true; } + void EGLContext::ReleaseImageDescriptors(ImageObject& imageObject) { + for (Int plane = 0; plane < imageObject.PlaneCount; ++plane) { + if (imageObject.Planes[plane].Fd >= 0) { + CloseImageDescriptor(imageObject.Planes[plane].Fd); + imageObject.Planes[plane].Fd = -1; + } + } + imageObject.PlaneCount = 0; + } + EGLContext::EGLImageHandle EGLContext::CreateImage(EGLDisplayHandle display, EGLContextHandle context, EGLenum target, EGLClientBuffer buffer, const EGLAttrib* attribList) { const std::lock_guard lock(m_mutex); - (void)attribList; if (!IsDisplayInitialized(display)) { SetError(EGL_NOT_INITIALIZED); return EGL_NO_IMAGE; @@ -1468,13 +1555,149 @@ namespace MobileGL { return EGL_NO_IMAGE; } - const auto image = EncodeHandle(m_nextImageHandle++); - m_images[image] = ImageObject{ + ImageObject imageObject = { .Display = display, .Context = context, .Target = target, .Buffer = buffer, }; + + // EGL_LINUX_DMA_BUF_EXT: the caller handed over a DESCRIPTOR and described the + // memory behind it, and that description is the whole image - there is no handle to + // import later. Every other target still names a buffer this state cannot see, so + // it stays what it was: the record of the target it was made for. + if (target == EGL_LINUX_DMA_BUF_EXT) { + // ONE line per refusal, naming what was missing: a caller that gets + // EGL_BAD_PARAMETER for a buffer it believes it described completely has + // nowhere else to look - the attribute list is gone by the time eglGetError is + // read, and the frame it wanted to draw into is the frame it cannot. + const auto refuse = [&](const String& missing) { + SetError(EGL_BAD_PARAMETER); + MGLOG_E("eglCreateImage(EGL_LINUX_DMA_BUF_EXT): %s is missing; refusing the image " + "(EGL_BAD_PARAMETER)", + missing.c_str()); + }; + + const auto width = ParseAttribValue(attribList, EGL_WIDTH); + const auto height = ParseAttribValue(attribList, EGL_HEIGHT); + const auto fourCC = ParseAttribValue(attribList, EGL_LINUX_DRM_FOURCC_EXT); + if (!width) { + refuse("EGL_WIDTH"); + return EGL_NO_IMAGE; + } + if (!height) { + refuse("EGL_HEIGHT"); + return EGL_NO_IMAGE; + } + if (!fourCC) { + refuse("EGL_LINUX_DRM_FOURCC_EXT"); + return EGL_NO_IMAGE; + } + + // The planes, read and checked BEFORE one descriptor is duplicated, so that a + // refusal leaves nothing behind to close. + EGLint planeFd[EGLContext::kMaxImagePlanes] = {}; + EGLint planeOffset[EGLContext::kMaxImagePlanes] = {}; + EGLint planePitch[EGLContext::kMaxImagePlanes] = {}; + Uint64 planeModifier[EGLContext::kMaxImagePlanes] = {}; + Bool planeHasModifier[EGLContext::kMaxImagePlanes] = {}; + EGLint planeCount = 0; + for (Int plane = 0; plane < EGLContext::kMaxImagePlanes; ++plane) { + const DmaBufPlaneAttributes& attributes = kDmaBufPlaneAttributes[plane]; + const auto fd = ParseAttribValue(attribList, attributes.Fd); + const auto offset = ParseAttribValue(attribList, attributes.Offset); + const auto pitch = ParseAttribValue(attribList, attributes.Pitch); + const auto modifierLo = ParseAttribValue(attribList, attributes.ModifierLo); + const auto modifierHi = ParseAttribValue(attribList, attributes.ModifierHi); + if (!fd && !offset && !pitch && !modifierLo && !modifierHi) { + // The caller never mentioned this plane. Planes are positional - the + // description carries no plane index - so this ends the list, and a + // plane past the hole is refused by name rather than dropped. + for (Int higher = plane + 1; higher < EGLContext::kMaxImagePlanes; ++higher) { + if (HasAnyPlaneAttribute(attribList, higher)) { + refuse(DmaBufPlaneAttributeName(plane, "FD_EXT")); + return EGL_NO_IMAGE; + } + } + break; + } + // All three of fd/offset/pitch or none, and both halves of the modifier or + // neither: a partial triple describes memory no importer could read. + if (!fd) { + refuse(DmaBufPlaneAttributeName(plane, "FD_EXT")); + return EGL_NO_IMAGE; + } + if (!offset) { + refuse(DmaBufPlaneAttributeName(plane, "OFFSET_EXT")); + return EGL_NO_IMAGE; + } + if (!pitch) { + refuse(DmaBufPlaneAttributeName(plane, "PITCH_EXT")); + return EGL_NO_IMAGE; + } + if (modifierLo.has_value() != modifierHi.has_value()) { + refuse(DmaBufPlaneAttributeName(plane, modifierLo ? "MODIFIER_HI_EXT" : "MODIFIER_LO_EXT")); + return EGL_NO_IMAGE; + } + planeFd[plane] = static_cast(*fd); + planeOffset[plane] = static_cast(*offset); + planePitch[plane] = static_cast(*pitch); + if (modifierLo) { + // The modifier arrives in two halves and is one number: DRM cuts a + // DRM_FORMAT_MOD_* where EGL takes an EGLint. + planeModifier[plane] = (static_cast(static_cast(*modifierHi)) << 32) | + static_cast(*modifierLo); + planeHasModifier[plane] = true; + } + planeCount = plane + 1; + } + if (planeCount == 0) { + // A dma-buf image with no plane at all: the description starts here, so + // this is the attribute that is missing. + refuse(DmaBufPlaneAttributeName(0, "FD_EXT")); + return EGL_NO_IMAGE; + } + + // THE IMAGE TAKES ITS OWN DESCRIPTORS. The caller's fds stay the caller's - + // kwin hands over a dup() of its DmaBufAttributes and closes it as soon as + // eglCreateImage returns, and an image that had borrowed it would be holding a + // number some other part of the process now owns. + for (Int plane = 0; plane < planeCount; ++plane) { + const Int ownedFd = DuplicateImageDescriptor(planeFd[plane]); + if (ownedFd < 0) { + SetError(EGL_BAD_ALLOC); + MGLOG_E("eglCreateImage(EGL_LINUX_DMA_BUF_EXT): cannot take a copy of %s=%d (%s); " + "refusing the image (EGL_BAD_ALLOC)", + DmaBufPlaneAttributeName(plane, "FD_EXT").c_str(), planeFd[plane], + std::strerror(errno)); + ReleaseImageDescriptors(imageObject); + return EGL_NO_IMAGE; + } + imageObject.Planes[plane] = ImagePlane{ + .Fd = ownedFd, + .Offset = planeOffset[plane], + .Pitch = planePitch[plane], + .Modifier = planeModifier[plane], + .HasModifier = planeHasModifier[plane], + }; + // Counted as they are stored, so that a failure below releases exactly what + // has been taken. + imageObject.PlaneCount = plane + 1; + } + imageObject.Width = static_cast(*width); + imageObject.Height = static_cast(*height); + imageObject.FourCC = static_cast(*fourCC); + + MGLOG_D("eglCreateImage(EGL_LINUX_DMA_BUF_EXT): %dx%d fourcc=0x%08x planes=%d plane0(fd=%d " + "offset=%d pitch=%d %s0x%016llx)", + imageObject.Width, imageObject.Height, imageObject.FourCC, imageObject.PlaneCount, + imageObject.Planes[0].Fd, imageObject.Planes[0].Offset, imageObject.Planes[0].Pitch, + imageObject.Planes[0].HasModifier ? "modifier=" : "no-modifier=", + static_cast(imageObject.Planes[0].Modifier)); + } + + const auto image = EncodeHandle(m_nextImageHandle++); + m_images[image] = imageObject; return image; } @@ -1489,6 +1712,9 @@ namespace MobileGL { SetError(EGL_BAD_MATCH); return false; } + // The descriptors this image owns die with it. Nothing else in this process holds + // them: they are copies, and the caller's originals were never touched. + ReleaseImageDescriptors(imageIt->second); m_images.erase(imageIt); return true; } diff --git a/MobileGL/MG_State/EGLState/Core.h b/MobileGL/MG_State/EGLState/Core.h index 8bba629e..b78d7daa 100644 --- a/MobileGL/MG_State/EGLState/Core.h +++ b/MobileGL/MG_State/EGLState/Core.h @@ -22,6 +22,12 @@ namespace MobileGL { using EGLSyncHandle = ::EGLSync; using EGLImageHandle = ::EGLImage; + // How many planes EGL describes an imported buffer with: EGL_DMA_BUF_PLANE0_* comes + // from EGL_EXT_image_dma_buf_import, EGL_DMA_BUF_PLANE3_* and every MODIFIER pair + // from EGL_EXT_image_dma_buf_import_modifiers. The reader in Core.cpp and the image + // object below have to agree on the count, so it is named once. + static constexpr Int kMaxImagePlanes = 4; + EGLContext() = default; // Error @@ -118,6 +124,57 @@ namespace MobileGL { EGLContextHandle GetCurrentContext() const; EGLDisplayHandle GetCurrentDisplay() const; EGLSurfaceHandle GetCurrentSurface(EGLint readdraw) const; + // WHAT A HANDLE NAMES, for the GL side of GL_OES_EGL_image: the two entry points in + // MG_Impl/GLImpl/Exporting/Definitions.cpp are handed a GLeglImageOES and have to + // answer whether it is an image this display created, and with what geometry. A + // read-only lookup belongs beside the other queries a caller outside this class + // makes, and it is the same object eglCreateImageKHR built and eglDestroyImage + // removes - the private one stays private for the class's own use. + // WHAT A HANDLE NAMES, for the GL side of GL_OES_EGL_image. The two entry points in + // MG_Impl/GLImpl/Exporting/Definitions.cpp are handed a GLeglImageOES and have to + // answer (a) whether it is an image this display created and (b) what buffer it + // describes. The numbers come back rather than the record itself: the image table and + // its layout are this class's own business, and a caller outside it has no use for + // either - which is also why this is a function and not a friend declaration. + Bool DescribeImage(EGLImageHandle image, EGLint* width, EGLint* height, EGLint* fourCc, + EGLint* planeCount) const { + const ImageObject* imageObject = TryGetImage(image); + if (imageObject == nullptr) { + return false; + } + if (width != nullptr) *width = imageObject->Width; + if (height != nullptr) *height = imageObject->Height; + if (fourCc != nullptr) *fourCc = imageObject->FourCC; + if (planeCount != nullptr) *planeCount = imageObject->PlaneCount; + return true; + } + + // THE PLANE DESCRIPTORS OF AN IMAGE THIS DISPLAY CREATED, for the one caller that has + // to hand them to the render server: the dma-buf import (a texture bound to an imported + // EGLImage has no storage on the server, so the server is told which buffer backs it - + // one descriptor per plane, over the session transport's SCM_RIGHTS channel). The fd + // here is THIS side's dup(), owned by the image; the transport dups again for the + // sending process, which is why the caller does not close anything. + Bool DescribeImagePlanes(EGLImageHandle image, EGLint* planeCount, EGLint* fds, EGLint* offsets, + EGLint* pitches, Uint64* modifiers, Bool* hasModifiers, Int maxPlanes) const { + const ImageObject* imageObject = TryGetImage(image); + if (imageObject == nullptr) { + return false; + } + Int count = imageObject->PlaneCount; + if (count > maxPlanes) count = maxPlanes; + if (count < 0) count = 0; + if (planeCount != nullptr) *planeCount = count; + for (Int plane = 0; plane < count; plane++) { + const ImagePlane& described = imageObject->Planes[plane]; + if (fds != nullptr) fds[plane] = described.Fd; + if (offsets != nullptr) offsets[plane] = described.Offset; + if (pitches != nullptr) pitches[plane] = described.Pitch; + if (modifiers != nullptr) modifiers[plane] = described.Modifier; + if (hasModifiers != nullptr) hasModifiers[plane] = described.HasModifier; + } + return true; + } Bool IsDoubleBufferedSurface(EGLSurfaceHandle surface) const; // Sync @@ -218,11 +275,39 @@ namespace MobileGL { EGLenum Status = EGL_SIGNALED; }; + // ONE PLANE OF AN IMPORTED BUFFER. The fd/offset/pitch triple is the same + // description drmModeAddFB2 takes, and the modifier is the DRM_FORMAT_MOD_* the + // caller declared; EGL carries up to four of these (EGL_DMA_BUF_PLANE0..3_*). + struct ImagePlane { + // THIS library's descriptor, dup()ed from the caller's when the image was made + // and closed when it dies: an EGLImage outlives the call that created it, and + // the caller is free to close its own fd the moment eglCreateImage returns. + EGLint Fd = -1; + EGLint Offset = 0; + EGLint Pitch = 0; + // The two EGL_DMA_BUF_PLANEn_MODIFIER_LO/HI_EXT halves joined back into the + // DRM_FORMAT_MOD_* they were cut from. + Uint64 Modifier = 0; + Bool HasModifier = false; + }; + struct ImageObject { EGLDisplayHandle Display = EGL_NO_DISPLAY; EGLContextHandle Context = nullptr; EGLenum Target = EGL_NONE; EGLClientBuffer Buffer = nullptr; + // WHAT AN EGL_LINUX_DMA_BUF_EXT IMAGE IS HOLDING, and zero for every other + // target: the buffer's geometry and the fourcc that says what its samples mean. + // It is kept here because the image is the only thing that outlives the call - + // a caller that handed over an fd has nothing left to describe it with. + EGLint Width = 0; + EGLint Height = 0; + EGLint FourCC = 0; + EGLint PlaneCount = 0; + // Planes 0..PlaneCount-1 are described, in order; index 0 is the plane every + // import in this tree reads, the rest are carried because EGL describes them and + // a consumer that understands a multi-plane format must be able to see them. + ImagePlane Planes[kMaxImagePlanes]; }; struct ThreadCurrentState { @@ -258,6 +343,9 @@ namespace MobileGL { const SurfaceObject* TryGetSurface(EGLSurfaceHandle surface) const; const SyncObject* TryGetSync(EGLSyncHandle sync) const; const ImageObject* TryGetImage(EGLImageHandle image) const; + // Closes the descriptors an image owns. Both places an image can die call it: + // eglDestroyImage, and eglTerminate, which drops a display's images wholesale. + static void ReleaseImageDescriptors(ImageObject& imageObject); void ReleaseDisplayObjects(EGLDisplayHandle display); void ReleaseThreadUnlocked(const std::thread::id& threadKey); diff --git a/MobileGL/MG_State/GLState/FramebufferState/FramebufferObject.cpp b/MobileGL/MG_State/GLState/FramebufferState/FramebufferObject.cpp index 760c0d21..f22273b6 100644 --- a/MobileGL/MG_State/GLState/FramebufferState/FramebufferObject.cpp +++ b/MobileGL/MG_State/GLState/FramebufferState/FramebufferObject.cpp @@ -13,6 +13,23 @@ #include #include +// The display host's frame, as the backend publishes it (MG_Backend/DirectGLES/DirectGLES.h). +// DECLARED HERE RATHER THAN INCLUDED, and that is a deliberate compromise with a named end: the +// client asks whether its framebuffer is complete BEFORE any backend binding runs, so this judgement +// cannot ask the backend - and the frontend knowing a backend fact is exactly what a record is for. +// The wire does not carry one yet (MG_Protocol's dispatch has no glEGLImageTargetTexture2DOES), so +// the fact is read from where it already is; when that record lands, this block goes with it. +// The backend namespace is the one DirectGLES.cpp:67 opens and defines these in - the SAME nesting +// as Uint g_hostFrameFramebufferId beside them. Getting this wrong is not a typo with no cost: a +// Linux shared library links with undefined symbols allowed, so the container build passed while the +// Android server build (ld.lld, --no-undefined) named all three - which is how a latent runtime +// failure was caught by the platform that builds the render server. +namespace MobileGL::MG_Backend::DirectGLES { + extern Uint g_hostFrameRenderbuffer; + extern Uint g_hostFrameWidth; + extern Uint g_hostFrameHeight; +} + namespace MobileGL::MG_State::GLState { // Starts at 1 so a zero-initialized memo slot can never carry a live object's id. // Atomic for the same reason as the VAO counter: it costs nothing, and a duplicate @@ -174,8 +191,34 @@ namespace MobileGL::MG_State::GLState { Int width = -1, height = -1; Int validAttachmentCount = 0; + // THE IMPORTED dma-buf, and why it is judged BEFORE the validity test rather than after it. + // Measured: with kwin_wayland's framebuffer attached - it imports the display daemon's + // dma-buf as an EGLImage ("taking target 0x8d65 over an EGLImage of 1440x2937 fourcc + // 0x34324241") and builds an FBO over that texture - the server answered + // "GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT". The old early-continue below dropped the + // attachment (a texture that arrived this way has no storage, so it reports itself invalid) + // and the completeness gate further down was never reached. + // + // THE GATE IS THE MEASURED SHAPE, and it is deliberately narrow: this process is holding a + // display host frame (g_hostFrameRenderbuffer != 0), and the attachment is a texture with no + // storage of its own. That buffer IS the frame the host handed this process - same memory - + // and the backend binds the frame's renderbuffer in place of the empty texture + // (MG_Backend/DirectGLES/Managers.cpp). A size comparison would be the sharper test and is + // impossible here: the imported attachment has no size, which is exactly why the wire needs a + // record to say so (MG_Protocol's dispatch has no glEGLImageTargetTexture2DOES yet); when it + // lands, this gate is replaced by that record and nothing else changes. + // AND IT DELIBERATELY DOES NOT ASK WHETHER THE FRAME IS IN HAND YET, which the first version + // of this gate did - and that version did not work, measured: kwin imports the dma-buf and + // builds its framebuffer BEFORE the host-framed surface exists, so g_hostFrameRenderbuffer is + // still zero at the instant the client asks, the gate refused, and kwin printed + // "GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT" again. What the attachment IS is the fact + // that holds at that instant: a texture with no storage of its own is the imported dma-buf, + // and the buffer it names is the display daemon's frame - the one this process is about to be + // handed. The backend binds that frame's renderbuffer to the attachment as soon as it has + // one (Managers.cpp re-syncs attachments per draw, so the first draw after the frame arrives + // lands in it). for (const auto& attachmentObject : m_attachmentObjects) { - if (!attachmentObject.IsValid()) continue; + if (!attachmentObject.IsValid() && !attachmentObject.IsTexture()) continue; ++validAttachmentCount; const auto& attachment = attachmentObject; @@ -190,7 +233,44 @@ namespace MobileGL::MG_State::GLState { return false; } - if (!attachment.IsComplete()) { + // AN IMPORTED dma-buf COUNTS AS COMPLETE, in the measured shape and no other: the + // attachment has no storage of its own and this process holds a display host frame of the + // same size. Measured, and the reason this is here at all: kwin_wayland imports the + // display daemon's dma-buf as an EGLImage ("taking target 0x8d65 over an EGLImage of + // 1440x2937 fourcc 0x34324241") and then refuses its own framebuffer with "framebuffer for + // dmabuf 0 is not complete" - a refusal that is WRONG here, because the buffer it imported + // IS the frame the display host handed this process (same memory, same size) and the + // backend binds that frame's renderbuffer in place of the empty texture + // (MG_Backend/DirectGLES/Managers.cpp, the external-OES arm under the same gate). A size + // that differs, or no frame held, keeps the old answer: an ordinary empty attachment is + // still incomplete, and nothing is ever rendered into a buffer of the wrong size. + // AND IT DOES NOT ASK WHETHER A FRAME IS HELD, OR HOW BIG IT IS - which the first version + // of this gate did, and which is why it never worked. This judgement runs on BOTH sides + // of a split run: the client answers glCheckFramebufferStatus out of its own state before + // any backend binding happens, and the client holds no frame at all. So a gate that + // required g_hostFrameRenderbuffer != 0 and a matching size refused on the client every + // time, and kwin kept printing "Invalid framebuffer status: + // GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT" - measured, twice, after that gate was + // deployed. What the attachment IS is the fact that holds on both sides: a texture with + // no storage of its own is the imported dma-buf, and the server binds the display host's + // frame to it as soon as it has one (Managers.cpp re-syncs the attachments per draw, so + // the first draw after the frame arrives lands in it). An attachment that IS valid - an + // ordinary texture or renderbuffer with real storage - still has to be complete. + // A TEXTURE ATTACHMENT THAT IS NOT COMPLETE IS THE IMPORTED dma-buf, and it counts. The + // condition is written on IsTexture() and NOT on IsValid(), which is the mistake two + // earlier versions of this gate made - measured both times as + // "Invalid framebuffer status: GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT" from a session + // that was healthy and had really reached the import: + // * requiring a host frame to be in hand refused on the CLIENT, which holds none; + // * requiring the attachment to be INVALID refused too, because AttachTexture registers + // the attachment (FramebufferObject.cpp:163) whether or not the texture has storage - + // so the imported one is perfectly valid and simply incomplete. + // What is true on both sides, at that instant, is what this asks: the attachment is a + // TEXTURE and it is incomplete, i.e. it has no storage of its own, and the server binds the + // display host's frame to it as soon as it holds one (Managers.cpp re-syncs the attachments + // per draw). A RENDERBUFFER attachment still has to be complete, so an ordinary empty + // attachment of that kind keeps the old refusal. + if (!attachment.IsComplete() && !attachment.IsTexture()) { return false; } } diff --git a/MobileGL/MG_State/GLState/TextureState/TextureEnum.h b/MobileGL/MG_State/GLState/TextureState/TextureEnum.h index 5934be40..f292e3b9 100644 --- a/MobileGL/MG_State/GLState/TextureState/TextureEnum.h +++ b/MobileGL/MG_State/GLState/TextureState/TextureEnum.h @@ -21,6 +21,13 @@ namespace MobileGL { Texture2DArray, TextureCubeMapArray, Texture2DMultisampleArray, + // GL_TEXTURE_EXTERNAL_OES, APPENDED SO NO EXISTING VALUE MOVES. The compositor imports the + // display daemon's dma-buf with eglCreateImageKHR and binds the result through this target + // (glBindTexture(GL_TEXTURE_EXTERNAL_OES, tex) + glEGLImageTargetTexture2DOES). Without a + // member here the bind is answered INVALID_ENUM (measured with probe15: error 0x500 -> 0x0500), + // the texture never enters a binding slot, it has no internal format, and the framebuffer + // built over it is reported incomplete - "framebuffer for dmabuf 0 is not complete". + TextureExternalOES, TextureTargetCount, Unknown = -1 }; diff --git a/MobileGL/MG_Util/Converters/GLToMG/TextureEnumConverter.cpp b/MobileGL/MG_Util/Converters/GLToMG/TextureEnumConverter.cpp index 8d6fb042..bea1d21e 100644 --- a/MobileGL/MG_Util/Converters/GLToMG/TextureEnumConverter.cpp +++ b/MobileGL/MG_Util/Converters/GLToMG/TextureEnumConverter.cpp @@ -19,6 +19,10 @@ namespace MobileGL { case GL_TEXTURE_2D: case GL_PROXY_TEXTURE_2D: return TextureTarget::Texture2D; + // GL_TEXTURE_EXTERNAL_OES: what the compositor binds an imported dma-buf to. Spelled as + // the number because the GL headers this tree bundles do not define the token. + case 0x8D65: + return TextureTarget::TextureExternalOES; case GL_TEXTURE_3D: case GL_PROXY_TEXTURE_3D: return TextureTarget::Texture3D; diff --git a/MobileGL/MG_Util/Converters/MGToStr/GLExtensionConverter.cpp b/MobileGL/MG_Util/Converters/MGToStr/GLExtensionConverter.cpp index 741b7225..7bf8d8a9 100644 --- a/MobileGL/MG_Util/Converters/MGToStr/GLExtensionConverter.cpp +++ b/MobileGL/MG_Util/Converters/MGToStr/GLExtensionConverter.cpp @@ -497,6 +497,7 @@ namespace MobileGL { CASE(E_GL_OES_fixed_point) CASE(E_GL_OES_single_precision) CASE(E_GL_OES_compressed_paletted_texture) + CASE(E_GL_OES_EGL_image) CASE(E_GL_OES_read_format) CASE(E_GL_OES_query_matrix) CASE(E_GL_EXT_depth_bounds_test) diff --git a/MobileGL/MG_Util/Debug/Log.h b/MobileGL/MG_Util/Debug/Log.h index ffdc4e86..43151fa4 100644 --- a/MobileGL/MG_Util/Debug/Log.h +++ b/MobileGL/MG_Util/Debug/Log.h @@ -124,6 +124,7 @@ #include #include +#include namespace MobileGL { namespace MG_Util { diff --git a/MobileGL/MG_Util/GLExtensions.h b/MobileGL/MG_Util/GLExtensions.h index 321e5bff..1470370e 100644 --- a/MobileGL/MG_Util/GLExtensions.h +++ b/MobileGL/MG_Util/GLExtensions.h @@ -489,6 +489,11 @@ namespace MobileGL { E_GL_OES_fixed_point, E_GL_OES_single_precision, E_GL_OES_compressed_paletted_texture, + // GL_OES_EGL_image: taking a texture (or renderbuffer) over an EGLImage. Named because + // libepoxy resolves glEGLImageTargetTexture2DOES by NAME and the entry points are now real + // (MG_Impl/GLImpl/Exporting/Definitions.cpp), with the render-server half of the import + // still to come - see the note there. + E_GL_OES_EGL_image, E_GL_OES_read_format, E_GL_OES_query_matrix, E_GL_EXT_depth_bounds_test,