Compare commits

..
Author SHA1 Message Date
BZLZHH 7fd7f71d6c [Feature] (EGL): Wayland window surfaces, presented through wl_shm
A Wayland client's window is its own wl_surface, and what the compositor shows is the wl_buffer
attached to it - but the pixels of a MobileGL frame are drawn where the backend is, on a split
build in another process on another OS.  So far a wl_egl_window was taken for an X11 window and
its client-side address sent to the Android server (EGL_BAD_NATIVE_WINDOW at best), and under
glvnd a Wayland display never reached this vendor at all.

A window on a Wayland display - asked for as EGL_PLATFORM_WAYLAND, or a wl_display recognised by
its first word being wl_display_interface - is now a window surface in the EGL state at the
wl_egl_window's size with a pbuffer of that size behind it in the backend, whatever
MOBILEGL_IPC_SURFACE says.  At every swap the frame is read back out of the default framebuffer
through this library's own glReadPixels (the application's read framebuffer, pack buffer and pack
state put back as they were), its rows flipped and swizzled into a wl_shm buffer, and attached,
damaged and committed on the application's wl_surface.  Three buffers rotate on their release
events, dispatched on an event queue of the surface's own.  libwayland-client is loaded at run
time, so neither the build nor the library depends on it.  EGL_KHR_platform_wayland and
EGL_EXT_platform_wayland are announced on Linux.

Measured: glmark2-wayland runs its build scene at 13 FPS (400x300) and the window shows the frame
under kwin.  A window resize is not followed yet; the surface keeps its creation size.
2026-10-01 10:59:07 -04:00
BZLZHH 353daa265e [Fix] (Pipe): the records two families keep of their own are forgotten with the session too
MGPipeForgetAllPublications cleared the publication latch, but two death helpers do not ask the
latch: vertex elements ask the vertex-input emitter's RecordIsPublished and buffers ask the
resource tracker's WasPublished.  A VAO and its buffers destroyed with the GL context after the
split roles were down still found themselves published there, and glmark2's eglTerminate stopped
on the same assertion eglinfo's did (ResolveVertexElements, then ResolveResourceIn for a buffer).

Both records are now dropped beside the latch: the emitter's latches whole, the tracker's
Published flags.
2026-10-01 10:59:06 -04:00
BZLZHH 69728a4f9b [Fix] (Remote): the create window starts empty with each session
The window of creates whose answers are read later is process-global, and every entry names a
sequence number of the session that wrote it.  A process can run several sessions one after
another - eglinfo terminates one platform display and initializes the next - and an entry left by
the previous session made the new session's first create wait, in DrainCreateWindow, for a
sequence number the new server would not reach: the second session hung on its first texture
create.

InstallClientWireTables, which runs at the start of every session, now empties the window and the
create suspects; their answers and their objects died with the session that wrote them.
2026-10-01 10:31:20 -04:00
BZLZHH c6f828532a [Fix] (Pipe): nothing is published once the split session is gone
MobileGL::Destroy shuts the split roles down first and resets the GL context after, by design.  The
frontend objects that die in that reset still found their handles published, so their deletes were
routed to whichever applier was installed by then - the monolith one, which never had those
resources and asserted ("ResourceDestroy named {slot, gen}") from eglTerminate.  The abort also
threw away the program's buffered output, so eglinfo printed nothing but the assertion.

Every twin the server held died with the session, so ShutdownSplitRoles now clears the publication
latch (MGPipeForgetAllPublications): the deletes that follow are local bookkeeping only.
2026-10-01 10:31:20 -04:00
BZLZHH 5bb28140cb [Feature] (Remote): the TCP supervisor serves sessions side by side
A desktop is a compositor AND the GL programs run inside it, each a client with a session of its
own.  The TCP supervisor answered every authenticated Hello after the first with Refuse{Busy}, so
with kwin connected any other program - eglinfo, glxinfo, glmark2 from konsole - waited out its
Welcome and died on Fatal{CapsBeforeFirstSnapshot}.

The fork shape now keeps a list of live children and forks for a Hello while fewer than eight are
live.  What made it a single slot was the data connection: a DataBind names its session only by
the data nonce, which the child minted, so the supervisor could hand it to nothing but "the" child.
The nonce is now minted by the supervisor just before fork(); the child adopts it
(PresetDataNonceForThisProcess) instead of minting its own, and a DataBind goes to the child whose
nonce it presents.  Nothing on the wire changes.  The thread shape (the in-process display server)
still serves one session, Busy for a second as before.
2026-10-01 10:31:20 -04:00
BZLZHH bf7fc6bf6b [Fix] (DirectGLES): an imported external texture is attached as the host frame canvas
The arms that bind the display host's frame in place of an imported texture were gated on the
attach target being 0x8D65, but an external texture is attached through the GL_TEXTURE_2D upload
target, so they never ran.  The texture's twin on the server has no storage - the dma-buf behind it
never crosses - and kwin's framebuffers over it were incomplete (status 0x8cd7, every draw
GL_INVALID_FRAMEBUFFER_OPERATION), so nothing it drew landed anywhere.

The record arm (SyncAttachmentSurface) now recognises a texture point whose target is
TextureExternalOES and attaches the host frame canvas before any twin adoption or storage sync,
which have nothing to offer a texture with no storage; it takes the host frame first if none is held
yet.  The legacy object arm keys on the texture object's own target the same way.  Measured: all
four of kwin's daemon-buffer framebuffers complete, and the desktop it draws reaches the glass.
2026-10-01 09:47:32 -04:00
BZLZHH b72d4c5dff [Feature] (DirectGLES): a stable canvas in front of the host frames
Every present hands the frame back to the display host and takes a different one, and the frame's
renderbuffer is deleted with it.  A compositor attaches its framebuffers once (kwin: one per daemon
buffer, for the life of the process), so attachments bound to a frame's own renderbuffer named a
deleted object from the second frame on.

The backend now keeps a canvas - a renderbuffer and framebuffer of its own, made at the first
frame's size and kept for the session.  The host-frame globals (the default-framebuffer redirect,
the storage external attachments are bound to) name the canvas instead of the frame, and keep
naming it between a frame being handed back and the next one arriving.  PresentHostFrame copies the
canvas into the frame before its fence; the copy puts back the compositor's framebuffer bindings,
scissor test and rasterizer discard exactly as they were.  Without a canvas the frame itself stays
the draw target, as before.
2026-10-01 09:47:24 -04:00
BZLZHH c88c6ff196 [Fix] (Remote): the present record presents a host-framed surface
A split client's swap reaches the server as a present record, and ServerVerbSink::OnPresent only
ran the backend's Present - an eglSwapBuffers of the pbuffer the context was made with.
BackendObject::SwapEGLBuffers is the only route to PresentHostFrame and a split client never takes
it, so over TCP the display host was never told a frame was drawn: the app offered thousands of
frames and presented none.

BackendObject::PresentHostFrameIfCurrent presents the host frame when the current surface is
host-framed and is a no-op otherwise; OnPresent calls it after Present and before the credit goes
back, so a client released by the credit is released by a frame that is on its way to the glass.
2026-10-01 09:47:18 -04:00
BZLZHH 16488d5801 [Feature] (GL): glFlush presents the display host's frame for a compositor that never swaps
kwin draws the desktop into the display host's frame and then calls glFlush - and glFlush alone;
it never calls eglSwapBuffers.  The stream reached the server and the server drew, but the display
host was never told a frame was done, so nothing reached the glass.  When the surfaceless-bind hook
has taken the host frame, glFlush now swaps that surface after flushing the stream: that swap is the
host's "frame is done".

A swap of a surface the EGL state does not know used to return EGL_BAD_SURFACE without a word - the
whole reason the host frame's presents were invisible - so that refusal is now reported once.
2026-10-01 09:47:12 -04:00
BZLZHH c16a51da62 [Feature] (EGL): a surfaceless compositor takes the display host's frame surface
A compositor on the anland route never creates a window surface: it imports the display host's
dma-bufs, draws into them through framebuffers and binds its contexts with EGL_NO_SURFACE.  The
host frame bridge is only opened by a host-framed surface being created and activated, so with no
surface the bridge stayed shut and the display host offered its frames into a name nobody served.

So the first surfaceless bind of a real context, in a session that asked for host-framed surfaces,
makes the surface eglCreateWindowSurface would have made - registered in the EGL state AND created
through the backend's window-surface entry, which the remote backend routes to the host frame - and
every later surfaceless bind binds it, because the compositor rebinds with EGL_NO_SURFACE all the
time and a bind without it leaves nothing current to present.  Registering it in the EGL state is
not optional: a backend-only token was refused by the state (EGL_BAD_SURFACE) on every bind and
every swap.

Only the compositor takes the host frame.  Desktops are full of processes that bind with no surface
(konsole, plasmashell, kactivitymanagerd), and a second process taking it made the activation fail;
the compositor's launcher marks it with MOBILEGL_HOST_FRAME_CLIENT=1.
2026-10-01 09:47:06 -04:00
BZLZHH 08e45dc9c6 [Fix] (GLState): an external texture is a 2D texture that remembers it is external
GL_TEXTURE_EXTERNAL_OES had a target of its own but nothing behind it: the texture factory had no
row for it (the compositor died on "Unimplemented texture type" the moment it bound one), the
attach path had no upload target for 0x8D65 (validation failed, the attachment was never recorded
and the compositor read GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT), and nothing downstream
could tell an imported texture from an ordinary one.

An external texture is now a TextureObject2D created with the TextureExternalOES target, attached
through the 2D upload target - which the three framebuffer-texture validations accept for an
external object - and the target crosses the pipe (TexExternalOES maps back on the server) so the
render server can recognise it.  To the driver it stays a 2D texture: MapToBackendTextureTarget
folds it to Texture2D like the other targets ES does not have.
2026-10-01 09:46:57 -04:00
BZLZHH b2ce268c86 [Fix] (GLState): a global buffer target asked through the indexed lookup is a warning, not an abort
Only four buffer targets have per-index binding points (Uniform, TransformFeedback, AtomicCounter,
ShaderStorage).  A caller that asks GetBindingPoint for any other target is reading the wrong
accessor, not passing a bad enum - and kwin reached exactly that right after its vertex-attrib
setup, where the assertion killed the whole compositor with Trace/breakpoint trap.

The answer is now a one-time warning and index 0 of the indexed array: the caller gets a valid
slot, the global binding is untouched, and the mismatch stays visible in the log.
2026-10-01 09:46:46 -04:00
BZLZHH df58f21d83 [Feature] (EGL): the vendor answers what a compositor resolves, and the imported texture is complete
A compositor's bring-up is a fixed sequence of questions that all have to be answered by the same
library: which devices exist, which display a device serves, what its DRM node is, which platform
the display comes from, which configs exist, a context, a surfaceless make-current, the GL entry
points for that context, and finally the dma-buf import it draws with.  Every missing answer in that
list cost a run to find, and each is measured rather than assumed - an unanswered device query was a
call through a null pointer, an unanswered GL name left glvnd's dispatch table empty so glGetString
answered NULL through libGL while the same context answered through eglGetProcAddress, an unanswered
node string produced "couldn't find dev node for drm device", and a rejected
GL_TEXTURE_EXTERNAL_OES binding is why the framebuffer over an imported dma-buf was reported
incomplete.

The EGL side is whole now: the device-query family is published as real entry points with the DRM
node named, the dispatch hook answers GL names as well as EGL ones, and the swap-and-sync family the
compositor checks between its context and its first surface - EGL_KHR_fence_sync, EGL_KHR_wait_sync,
the damage variants, EGL_EXT_buffer_age - is implemented and announced.  A surfaceless context is
recorded as what it is rather than as a surface that does not exist.  These entry points log what
they are asked at DEBUG level, because the next bring-up should not need a disassembler.

GL_TEXTURE_EXTERNAL_OES is a target of its own (its TextureTarget, its pipe row, the GLenum mapping,
and the OES_EGL_image extension named), which is what lets the compositor's bind succeed at all; the
texture an imported image backs is marked backed, so a framebuffer built over it is complete.  The
client half of the import is new beside it: each plane's descriptor is described and shared with the
render server over the session transport, which is the change the server side has been waiting for.
2026-10-01 18:15:55 +08:00
gold 29a89cc10a [Fix] (gbm): the two defects only the Android build could find
Neither showed up in the Linux build that verified this library, and both are the kind that would
have been found by the first person to build the phone half - so they are fixed here rather than
left for that person.

bionic only declares memfd_create from API 30 and this library builds against 26. The kernel call is
far older than the declaration, so it is asked for by number: the same call with the name the
headers of this API level do not carry yet.

The library carries the tree's logger, which reaches Android's own log through liblog. The main
target gets that library in its own Android block; a second target built from the same sources needs
it for the same reason, and without it the link is what fails rather than anything in the code.
2026-10-01 08:23:04 +08:00
gold 8e3db2cb87 [Feature] (gbm): the server offers each taken frame to the container
The channel existed and had no callers.  Now the frame the server takes from the host is offered to
the container with the geometry the host decided, the apply loop consumes the releases the
compositor sends back, and the teardown that drops the host frame closes the channel.

Every call is on the optional path: with no container the render path is what it was.
2026-10-01 03:42:18 +08:00
gold 1ba7b1a96f [Feature] (gbm): the server sends each frame's dma-buf fd to the container
The container's GBM hands out buffers that are the display host's frames, and this is the phone end
of that: the server takes a frame from the host, offers its descriptor to the container over a unix
socket at a path both sides can reach, and takes the release back when the compositor is done with
it.

The channel is optional and silent by design. A compositor must render whether or not a container is
listening, and the render path must never wait on a socket - so it is opened lazily, every send is
bounded, and any error simply marks it down.
2026-10-01 03:37:50 +08:00
gold 1a7b4b6a2b [Feature] (gbm): the host-frame backend - the compositor's buffers are the phone's frames
The self-allocated backend makes the library stand on its own; this one makes it the thing the
project needs.  The display host on the phone owns a pool of frames, the render server draws into
them with Espryt and acks, and the host presents.  A gbm_bo created here is one of those frames: the
phone sends its dma-buf fd over a unix socket, the offer carries the geometry the host decided (not
the geometry the caller asked for), and destroying the bo sends the frame back.

Verified against a fake display host on this machine, with no phone involved: the buffer the fake
host fills is the buffer the bo maps - every pixel of the pattern is there - the fd the caller is
handed is a view of that same memory rather than a copy, a device with no frame waiting falls back
to allocating locally, and teardown closes exactly the descriptor it opened.  The self-allocated
path still passes its own test unchanged.

The channel is lazy and never blocking: a compositor must work whether or not the phone is there.
2026-10-01 03:27:22 +08:00
gold 55e5165e2f [Feature] (gbm): MobileGL's own GBM, so the compositor's buffers are the display host's frames
kwin never creates an EGL window surface.  Its undefined libgbm symbols are seventeen entry points
whose whole purpose is to hand out gbm_bo fds, and those fds are what Anland's display producer
sends to the daemon on the phone - so the question "whose pixels are on the screen" is answered by
"who allocated the bo", and today that is Mesa.  The client can be loaded, initialized and rendering
through glvnd with no window surface ever created, which is exactly what was measured.

This is a complete GBM: every public entry point of the vendored Mesa header, with the semantics a
compositor relies on - fds the caller owns, real mmap with refcounting, a swapchain that refuses to
hand out a busy buffer, import by fd, and teardown that leaves no descriptor or mapping behind.  The
buffers come from the display host's frames; where there is no host, the device allocates from the
dma-buf heap, falling back to an uncached heap and then to memfd, so the library stands on its own.

The vendored gbm.h is Mesa's, verbatim: the entry points are the ABI, not our idea of it.
2026-10-01 03:16:55 +08:00
gold 2860d09051 [Fix] (EGL): a second display is served, and glvnd gets its answers from one table
Two defects, both found by asking the client directly rather than by reading its log.

The backend refused to initialize any EGLDisplay but the first - "already bound to a different
EGLDisplay" - and the field it compared against has no reader anywhere else in the tree: the domain
rule was the whole of the rule.  What it cost was a compositor, which asks for the display it will
draw into AFTER probing another one.  The probe succeeded, the real display was refused, and the
caller reported the refusal one layer up as "no usable DRM render device" - a message that names
where it stopped, not why.

The second: glvnd asks a vendor for entry points from two places.  getProcAddress is how it builds
its own static EGL table, and getDispatchAddress is how it answers eglGetProcAddress for every name
it does not know itself - which is every extension entry point, the device queries among them.  This
side answered the second from a GL-only table, so an application asking for eglQueryDeviceStringEXT
got a null for a function the vendor implements.
2026-10-01 02:58:06 +08:00
gold c9206dd955 [Feature] (EGL): MobileGL serves EGL through libglvnd
On a system with libglvnd the libEGL.so.1 an application links is a dispatcher, not an
implementation, and the supported way to be the implementation it talks to is to be a vendor
library it loads and routes to.  On this machine it is also the ONLY way that reaches a caller which
does not link EGL directly: kwin goes through libepoxy, which dlopen()s libEGL.so.1 and dlsyms its
entry points at startup, so a library injected with LD_PRELOAD is invisible to it however loudly it
is named - measured, with the client in kwin's maps and not one call into it.

So this is the vendor half of that ABI: __egl_Main answers glvnd with the entry points by name, the
platforms this implementation serves, and the device it is associated with - the render node of the
machine, because that is what lets a compositor match its own node to the display it is about to
draw into, and because glvnd drops a vendor that does not answer at all.

Two details are the difference between a vendor that is loaded and a vendor that is used.  glvnd
requires setDispatchIndex to exist even when a vendor has nothing to record, which this one has -
its entry points are the implementation, they never re-enter glvnd.  And a vendor must hand over ITS
OWN entry points: with default visibility a reference inside this library resolves against the whole
process, where another libEGL that loaded first wins.  That is what -Bsymbolic-functions is for;
declaring the entry points protected says the same thing but does not compile against the platform
headers, which declare them default.
2026-10-01 02:58:06 +08:00
gold dfbda7ccb4 [Feature] (EGL): the platform and device extensions are one list, spelled once
A vendor string and an eglQueryString answer have to agree, and they are read by two different
parties: the system's libglvnd reads the first to decide which vendor a platform request should be
routed to, and an application reads the second before it decides to make that request at all.  Kept
apart they drift, and the drift has a signature - a library that is loaded, initialized, and never
called, while the caller reports that it found no provider for a function it never reached.

The list gains the device family for the same reason: a compositor asks which devices exist and
reads the DRM node off one before it asks for a display on it, so an implementation that answers
"no devices" is one it cannot use no matter how well the implementation draws.
2026-10-01 02:58:06 +08:00
gold 6a702afa72 [Chore] (glvnd): vendor the EGL vendor ABI headers
Two MIT headers from libglvnd, verbatim, because MobileGL is about to implement the vendor half of
glvnd's EGL ABI and the distribution ships the runtime without them.
2026-10-01 02:58:06 +08:00
gold ab685fb0e9 [Feature] (plugin): the server survives a dozing phone - a notification the user allows and a battery exemption the user grants
Two permissions decide whether a server on Android lives or dies, and both are invisible until
something goes wrong: without POST_NOTIFICATIONS (13+) a foreground service cannot show the
notification that is its reason to exist, and without the battery exemption a dozing phone freezes
the process - the listener stays in /proc/net and stops accepting, which from the other side of the
socket looks exactly like a network fault.

The control screen now shows the state of both and asks for whichever is missing, in the order that
makes sense: the notification prompt is a dialog of ours, the battery one leaves the app entirely,
and coming back from it re-runs the other branch through onResume. A denial is said out loud rather
than left to be discovered.

The manifest carries the two permissions; the service's own notification was already there.
2026-10-01 01:50:14 +08:00
gold 1ae7a8eaa4 [Feature] (disaggregated): WindowKind::HostFrame - the host-framed surface crosses the wire
The last thing between the host-framed surface and a run: the sub-byte on the wire that names it.
ServerOwned had one (7) and the host frame had none, so the encoder refused the op with
UnknownWindowKind - a correct refusal, and the reason the first run of MOBILEGL_IPC_SURFACE=host
failed in the codec rather than anywhere near the pixels.

 - protocol.fbs: WindowKind::HostFrame = 8, appended, legal on CreateWindowSurface only and always
   with nativeToken 0 - the same rules ServerOwned carries, for the same reason: no pointer of any
   process's window system crosses (Rule G/H).
 - SurfaceRefusal: HostFrameOnSetWindowHandle = 5, its own code rather than reusing the
   server-owned one: a refusal that names the wrong owner sends the next reader to the wrong place.
 - SurfaceOpCodec: the encode and decode arms, the two wire errors that go with them
   (HostFrameTokenNotZero latches as corruption, HostFrameOnSetWindowHandle is a named refusal), and
   the range bound that had ServerOwned as its upper limit now ends at HostFrame.
 - protocol_generated.h regenerated with the pinned submodule's flatc (scripts/gen_protocol.py),
   diff being exactly the two appended enumerators.

Both ends must be rebuilt together, as any protocol revision here: the container's client and the
device's server went out with this on either side.
2026-10-01 01:26:02 +08:00
gold ead7a10b68 [Feature] (disaggregated): the default framebuffer on a host-framed surface is the host's frame
Three things this path needs that the server-owned one never did, each because the pixels are not
in an EGL surface this time:

 - The client's DEFAULT framebuffer has to resolve to the frame.  Four places bind the driver's 0
   for the default framebuffer; they now ask g_hostFrameFramebufferId, which is 0 everywhere except
   while a host-framed surface is current, where it is the frame's framebuffer.  Without this every
   draw would land in the pbuffer the context was made with - a surface nobody ever sees.

 - eglMakeCurrent binds the surface's own default framebuffer behind the engine's binding shadow, so
   the frame has to be put back after every make-current, with the shadow invalidated first: a bind
   the shadow thinks already happened never reaches the driver.

 - The bind itself goes through FramebufferImpl::BindFramebufferId, not a raw glBindFramebuffer, for
   the same reason - a raw bind leaves the shadow claiming the previous framebuffer.

Frame lifecycle is otherwise unchanged: the frame becomes the draw target when it arrives, and is
dropped after the host has been answered and has presented it.

Compiles and links (libMobileGL.so, libMobileGLServer.so, exit 0), deployed to the device, and the
container's client is rebuilding against it.  The run that shows Plasma through it is next.
2026-10-01 01:14:51 +08:00
gold 035f1b07ae [Feature] (disaggregated): MOBILEGL_IPC_SURFACE=host - the display host owns the screen and the frames
The third on-screen shape, and the one this whole line was built toward: Anland keeps Wayland,
input and the display, and the render server draws into the frames the display host allocates.

    client (container)      asks for a window surface with no window of its own
    server (Android)        takes a frame from the host over the host frame bridge and binds it as
                            the draw target of that surface
    host (the app that
    owns the screen)        offers each frame, presents it when the server says it is drawn

The pieces, in the order a frame travels:

 - Config: MOBILEGL_IPC_SURFACE=host beside =server, and HostFrameWindowSurfaces() as the one
   predicate every client-side consumer asks (EGLImpl accepts a NULL window for either on-screen
   shape, and BackendObject_Remote routes the creation to the server instead of sending a handle).
 - Wire: the frame-local tag kHostFrameWindowBackend, the mirror of kServerOwnedWindowBackend - it
   names no WindowBackend of the pull build's enum, and the server consumes it before the unpack
   that would refuse it.
 - Server: ApplyHostFrameWindowSurface replaces nothing, unlike the server-owned arm: there is no
   window of either side's to substitute, because the backend takes the frames from the bridge.
 - Backend: SurfaceKind::HostFrame, InitHostFrameSurface (the EGL context comes from the pbuffer
   path; what changes is what it draws INTO) and PresentHostFrame (glFinish, answer the host, take
   the next frame) - and SwapEGLBuffers routes to it, because a host-framed surface has no
   swapchain to swap: the host is what puts the frame on the glass.

HostFrameTarget and HostFrameBridge, committed just before this, are what the backend uses.

Compiles and links in this tree (libMobileGL.so and libMobileGLServer.so, exit 0).  What is NOT
here yet, and is the next thing: the run that puts Plasma on the phone's screen through it.
2026-10-01 01:11:21 +08:00
gold c7ab618ab0 [Feature] (disaggregated): the host's frames as a draw target, and the socket they arrive on
Two modules, and nothing else changes yet: they are the half of the host-framed surface that is
about the frame itself, kept apart from the surface lifecycle so they can be reviewed and built
on their own.

HostFrameTarget (DirectGLES): an AHardwareBuffer becomes a renderbuffer through an EGLImage and a
framebuffer that is the drawing target while its frame is current.  The extension strings decide
first and the four entry points are taken from eglGetProcAddress only after they have, which is
the shape the T0 AHB import in Managers.cpp already uses; a driver that lacks one of them is
answered with its name, never an abort.  Every failure path drops what it made, so no GL name and
no EGLImage outlives a refusal.

HostFrameBridge (MG_Backend): the display host's own protocol, restated field for field - a
handle ahead of a fixed-size description on one AF_UNIX connection, then the answer, then the
host's readback of the pixels it can see.  The host dials; this side listens on the well-known
name.  A handle that arrives without its description is released before the failure is reported,
because a reference held past the connection starves the pool the host draws its frames from.

Why the host allocates the frames at all is measured, not chosen: AHardwareBuffer_createFromHandle
accepts an AHardwareBuffer this process allocated and refuses one the display queue handed over
(gralloc BAD_VALUE) - same process, same descriptor, same handle shape.  That result is what these
two modules are built around, and it is written down where the next reader will look for it.

Both compile against this tree's own flags.  Wiring them into the surface lifecycle, the swap path
and the client's opt-in is the next step, not this one.
2026-10-01 00:57:14 +08:00
BZLZHH 2e43df6125 [Docs] (disaggregated): the container as a client of the phone's on-screen server, and the two things that cost a run
Measured on the Redmi today: the Droidspaces container shares the phone's network namespace, so a
client in the container reaches the server's loopback listener with no adb forward and no LAN
address; the server owns the window (MOBILEGL_IPC_SURFACE=server), the Adreno does the drawing,
and a screenshot of the phone shows the colour that headless client asked for.

The two traps are written down because both cost a run: MOBILEGL_IPC_REQUIRE_SAME_BUILD=1 on the
server turns a Connect handshake's build-stamp warning into Refuse{BuildFingerprint} against a
release APK whose stamp is 0, and the client then dies on a caps gate that names something else.
2026-10-01 00:39:49 +08:00
BZLZHH 015b91f08d [Test] (extmem_probe): T4-host-image closes the round trip, and its first verdict was wrong for one constant
The leg now reports OK on the device: offered=3 imported=3 drawn=3 hostReadback=3 agreed=3 --
three self-allocated AHardwareBuffers from the display host imported as EGLImages by this side,
drawn into, and read back by the host at both the first pixel and the far corner.

Getting there took one measurement and one correction.  The handle message is 256 bytes on this
path and recvHandleFromUnixSocket drains it exactly (pending 256 -> 100, then 0 -> 100, then
0 -> 0), so the description that follows it was never the problem; the comparison was.  This leg
was checking the display host's messages against kT4Magic -- the dma-buf protocol's magic, which
belongs to the container peer -- while the host stamps AHB_BRIDGE_MAGIC on all three of its
messages.  A perfect round trip was reported as 'the offer's sideband did not follow its handle',
which named the wrong cause and cost the time.  kT4HostMagic is that value, and the leg now also
prints the handle's footprint and the bytes it actually read, so the next failure of this shape
cannot be mistaken for the other one.
2026-10-01 00:34:40 +08:00
BZLZHH 987b7ad13c [Test] (extmem_probe): T4-host-image is the other end - the buffer the display host is about to scan out, imported and drawn into, with the round trip closed by that host reading its own pixels back. 2026-09-30 23:53:49 +08:00
BZLZHH d26cf1e31b [Test] (extmem_probe): T4 asks the wrap question too - a driver without EGL_EXT_image_dma_buf_import is tried through AHardwareBuffer_createFromHandle before the offer is called untakeable, and both handle types are recorded so the answer names which one the platform reads. 2026-09-30 23:26:26 +08:00
BZLZHH 8196818e9f [Test] (extmem_probe): the T4 leg asks whether the render server can draw into an image allocated outside Android - and the device answers twice: this driver has no dma-buf import, Android-side allocation works end to end, and the offer must carry the plane layout rather than one linear plane. 2026-09-30 23:00:55 +08:00
289 changed files with 13217 additions and 23268 deletions
@@ -1,3 +0,0 @@
# Everything here is executed by bash/sh on Linux, Android or WSL: keep LF even on a Windows checkout
# (core.autocrlf=true would otherwise hand sh a script full of $'\r').
* text=auto eol=lf
@@ -1,176 +0,0 @@
---
name: anland-mobilegl-plasma
description: Bring up, rebuild, deploy, switch backends on, test and debug the "MobileGL + anland + KDE Plasma" stack - a rooted Android tablet whose anland APK embeds the MobileGL server, plus a Droidspaces Arch Linux ARM container running KWin/plasmashell/Chrome through the MobileGL client library and GBM backend - driven from this Windows machine (Git Bash, WSL archlinux, adb). Use it after a phone reboot, when changing server (NDK) or client (container glibc) MobileGL code or anland's KWin backend/patch, when switching Espryt/Magma, when validating zero-copy dma-buf presentation, and when chasing crashes, black windows, noise or software-rendering fallbacks in the Plasma session.
---
# MobileGL on anland KDE Plasma
**Setting this up on a new machine or phone from source: `reproduce.md` next to this file.**
Human-readable runbook (Chinese, same content): `docs/Disaggregated/notes/anland/runbook-plasma.md`.
Background: `docs/Disaggregated/notes/anland/handoff-legacy-mobilegl-unified.md` (state, commits, known
issues) and `plan-ahb-dmabuf.md` (zero-copy design). All scripts are in `scripts/` next to this file;
parameters are documented at the top of each script and in `scripts/env.sh`.
**The phone may be shared with another session.** Before anything that restarts the app, the daemon,
the container session or replaces a library, run the read-only `scripts/device/status.sh` and make sure
nobody else is mid-test. Use your own `ct.sh` channel names (others use c, c2, c3, xd, xr, gbm).
## Architecture (10 lines)
1. Phone: Lenovo TB321FU (Y700, Adreno 750, Android 15, kernel 6.1), rooted with **KernelSU** (`/data/adb/ksu`, `ksud`; `su -c` works). USB serial `HA27Q3LQ`, or wireless adb `ip:port`.
2. anland APK `com.anland.consumer.mobilegl` (debuggable build of anland branch `legacy-mobilegl-unified`): UI process + private service process `:mobilegl` (`MobileGLWorker`), which loads the **server** `libMobileGL.so` (NDK, from MobileGL `feat/disaggregated`) and listens on abstract socket `@anland-mobilegl`. One process serves every client (KWin, plasmashell, ksplash, Chrome...), one backend per process.
3. Backend = `setprop debug.mobilegl.backend DirectGLES|DirectVulkan` (Espryt = DirectGLES, Magma = DirectVulkan; prop lost on reboot) and must equal the container's `/etc/mobilegl/backend` (what every client reports; mismatch = "Hello.backendType disagrees with pinned backend").
4. Experiment display daemon `/data/adb/modules/anland-daemon/display_daemon /data/local/tmp/anland-mobilegl/display.sock` (display/input broker; NOT started at boot - the module only starts the original one on `/data/local/tmp/display_daemon.sock`, leave that alone).
5. Container `arch-kde-mgl` (Droidspaces 6.4.5, Arch Linux ARM aarch64 glibc, host net, `rootfs.img` mounted at `/mnt/Droidspaces/arch-kde-mgl` on the Android side). Bind mounts: `/data/local/tmp/anland-mobilegl` -> `/run/anland-mobilegl`, `/data/local/tmp/display_daemon.sock` -> `/run/display.sock`.
6. `desktop-session.service` (User=swung0x48) has drop-in `ExecStart=/opt/mobilegl/bin/mobilegl-startup.sh plasma`, which writes a user drop-in for `plasma-kwin_wayland.service` (kwin_wayland_wrapper -> `/opt/mobilegl/kwin/bin/kwin_wayland` + `/opt/mobilegl/kwin/lib/libkwin.so.6.7.4`, `ANLAND_MOBILEGL=1`, `MOBILEGL_IPC_SURFACE=server`) and runs `startplasma-wayland`.
7. KWin 6.7.4 with anland's `anland` backend renders straight into the anland Android Surface through the server. Every other GL process is `MOBILEGL_IPC_SURFACE=offscreen` and presents through KWin.
8. Client = `/opt/mobilegl/lib/libMobileGL.so` (glibc aarch64), the container's **system-wide** GL vendor (section below): glvnd EGL vendor `/usr/share/glvnd/egl_vendor.d/10_mobilegl.json` (sorts before the distribution's `50_*.json`, which serves whenever MobileGL declines), GLX vendor `/usr/lib/libGLX_mobilegl.so.0`, settings from `/etc/mobilegl/client.conf` (`MOBILEGL_TRANSPORT=spawn MOBILEGL_IPC_DATA=shm MOBILEGL_IPC_CONTROL=unix:@anland-mobilegl`) + `/etc/mobilegl/backend`. No per-process environment is needed.
9. Zero-copy windows: client `wl_egl_window` frames are server-allocated AHardwareBuffer "shared images" exported as dma-buf fds over `zwp_linux_dmabuf_v1`; KWin imports them with EGL and the server recognises its own buffer by inode. KWin gets a DRM device via `GBM_BACKEND=mobilegl` -> `/usr/lib/gbm/mobilegl_gbm.so` (node is only an identity, never ioctl'd). Without linux-dmabuf the client falls back to wl_shm readback.
10. X11 apps (Xwayland) use the MobileGL GLX vendor with per-frame readback + `xcb_put_image`. Chrome runs ANGLE-GLES over MobileGL EGL with the GPU in-process (`mobilegl-startup.sh chrome`).
## First-time prerequisites (Windows host)
- Git Bash, `adb` (SDK platform-tools), CMake >= 3.22 and Ninja on PATH (seen: CMake 3.27.6, Ninja 1.13.2), Python 3 + Pillow (only `rec.sh`).
- Android NDK **27.2.12479018** at `%LOCALAPPDATA%/Android/Sdk/ndk/27.2.12479018` (override `ANDROID_NDK`).
- WSL distro **archlinux** with clang, lld, llvm, cmake, ninja. **lld's major version must equal clang/llvm-libs'** (lld 23 on llvm 22 broke `ld.lld`; working set: all 22.1.6). Then export the sysroot once: `bash scripts/xsysroot/refresh-sysroot.sh` (-> `~/sysroots/arch-kde-mgl` + `~/sysroots/aarch64-arch.cmake`; re-run after container package upgrades, then `xbuild.sh --reconfigure`).
- MobileGL worktree (never build in the shared main checkout): `GIT_LFS_SKIP_SMUDGE=1 git worktree add ...`, `git submodule update --init --recursive`, and copy `3rdparty/glslang/External/spirv-tools` from the main checkout (the submodule leaves it empty).
- anland worktree on `legacy-mobilegl-unified` (KWin patch/backend, startup script, `mobilegl-tools/`).
- Phone side that already exists and is NOT recreated by this skill: the APK (build: anland `consumers/anland_v5/android_consumer/MOBILEGL.md`, gradle `:app:assemblePlainDebug` with `MOBILEGL_DIST`, `-PmobileglApplicationId=com.anland.consumer.mobilegl`; reinstalling with another key changes the UID and needs the KernelSU grant again - `mobilegl-tools/ksu_grant.c`), the anland KernelSU modules (`anland-daemon`, `anland-awl`), the container with KWin's configured build tree `/root/mobilegl-build/kwin-6.7.4/build` and pristine `/root/gbm-dev/kwin-a/src`.
- Install the helpers once (container must be running): `bash scripts/push-tools.sh` (device/*.sh -> `/data/local/tmp/anl`, `mgrun` -> container `/usr/local/bin`, `kwprep.sh` -> container `/root`).
Run host scripts from Git Bash as `bash scripts/<x>.sh`. Raw adb with device paths needs `MSYS_NO_PATHCONV=1` and the whole root command in one quoted string: `adb shell 'su -c "..."'`. A device script can also be run without pushing: `MSYS_NO_PATHCONV=1 adb shell 'su -c sh' < scripts/device/status.sh`.
## Bring-up after a phone reboot
Nothing of the session survives a reboot. Either `adb shell 'su -c "sh /data/local/tmp/anl/bringup.sh [DirectGLES|DirectVulkan]"'`, or by hand, in this order:
```sh
adb connect <ip>:<port> # only for wireless debugging (e.g. USB cannot power it)
export MSYS_NO_PATHCONV=1
adb shell 'su -c "svc power stayon true"'
adb shell 'su -c "setprop debug.mobilegl.backend DirectVulkan"' # or DirectGLES; match /etc/mobilegl/backend
adb shell 'su -c "am start -n com.anland.consumer.mobilegl/com.anland.consumer.MainActivity --es socket_path /data/local/tmp/anland-mobilegl/display.sock"'
adb shell 'su -c "/data/local/Droidspaces/bin/droidspaces -C /data/local/Droidspaces/Containers/arch-kde-mgl/container.config start"'
adb shell 'su -c "sh /data/local/tmp/anl/restart-daemon.sh"' # experiment display daemon, chmod 777 dir / 666 socket
adb shell 'su -c "sh /data/local/tmp/anl/run-plasma.sh"' # restarts app + desktop-session, ~90 s
```
`droidspaces` has no `status` command; `droidspaces show` lists running containers. Do not use the old
`/data/local/tmp/restart-daemon.sh` (it kills a hard-coded PID). Check with `device/status.sh`.
## Build and deploy loops
**Server (Android, NDK) -> APK lib**
```sh
bash scripts/build-android.sh # -> <worktree>/build-android/libMobileGL.so (RelWithDebInfo, unstripped)
bash scripts/cyc.sh s1 # clear sticky SW-renderer key, push, swap into APK, restart session, screenshot $ANL_DIR/s1.png, print fatals
```
`device/swap.sh` overwrites `/data/app/.../lib/arm64/libMobileGL.so` keeping owner/mode/SELinux context (original saved as `/data/local/tmp/anland-mobilegl/libMobileGL.so.orig`); no re-signing. To swap without the session restart: push to `/data/local/tmp/anland-mobilegl/libMobileGL.new.so`, `su -c "sh /data/local/tmp/anl/swap.sh"`, then `run-plasma.sh` anyway (KWin does not reconnect to a new server process).
**Client + GBM backend (container glibc) via WSL cross-build**
```sh
bash scripts/xbuild.sh [--reconfigure] # WSL ~/mgl-xbuild-a64; ~150 s full, seconds incremental
bash scripts/xdeploy.sh # rename-into-place install of libMobileGL.so + mobilegl_gbm.so, aliases, vendor JSONs, client.conf, GLX/GBM env drop-ins
```
Running clients keep the old inode; restart the client, or `run-plasma.sh` for KWin/plasmashell. Build server and client from the **same commit** (both stamp `git rev-parse HEAD`), else the logs WARN "compatible wire with different build". Fallback in-container build (slow): `scripts/sync-src.sh` + anland `mobilegl-tools/anland-build-client.sh`.
**KWin (anland backend / kwin.patch) - built inside the container**
```sh
bash scripts/kwin-stage.sh build # stage CR-stripped patch+backend+startup script, kwprep.sh, background sync-build-kwin.sh
printf 'tail -5 /root/kwin-build.log\n' | bash scripts/ct.sh kw # wait for "== ALL DONE =="
adb shell 'su -c "sh /data/local/tmp/anl/run-plasma.sh"'
```
`sync-build-kwin.sh` (anland `producers/kde/Arch_v5/`) copies only the backend sources, then `ninja -j4`, installs `kwin_wayland`, `libkwin.so.6.7.4`, the patched screencast plugin and `/opt/mobilegl/bin/mobilegl-startup.sh` by atomic rename. `kwprep.sh` is what applies changed `kwin.patch` hunks to core KWin files. Repo-root `libdisplay_producer/` is not synced by either. `kwin-stage.sh` is assembled from those two scripts and was not run as one unit yet.
**Unit tests (no device)** - in WSL (the MSVC build of this branch is broken):
```sh
MSYS2_ARG_CONV_EXCL='*' wsl -d archlinux -- bash /mnt/c/<worktree>/.claude/skills/anland-mobilegl-plasma/scripts/wsl-test.sh MultiSessionTest TwinOwnershipTest
MSYS2_ARG_CONV_EXCL='*' wsl -d archlinux -- bash -lc 'cd ~/mgl-anl-bld && ctest -R "MultiSession|TwinOwnership" -E DirectVulkan --output-on-failure'
```
`wsl-all.sh` builds and runs every unit test. Never run DirectVulkan integration tests; never two ctest runs at once.
## Switching backends
`adb shell 'su -c "sh /data/local/tmp/anl/switch.sh DirectGLES"'` (sets the prop, writes `/etc/mobilegl/backend`, restarts the app), then `run-plasma.sh` - the running session's clients are pinned to the old backend. `cyc.sh` keeps whatever is set.
## System-wide vendor and fallback
Installed by `xdeploy.sh` (and anland's `anland-build-client.sh`), so any process in the container gets MobileGL through the stock libglvnd/libgbm:
| File | Does |
|---|---|
| `/usr/share/glvnd/egl_vendor.d/10_mobilegl.json` | EGL vendor, asked before the system's `50_*.json` |
| `/opt/mobilegl/share/glvnd/egl_vendor.d/50_mobilegl.json` | same JSON, for per-process forcing with `__EGL_VENDOR_LIBRARY_FILENAMES` |
| `/etc/mobilegl/client.conf` | `KEY=value` defaults for every client (transport, data, endpoint); rewritten on deploy |
| `/etc/mobilegl/backend` | the backend (`switch.sh` writes it); wins over a `MOBILEGL_BACKEND_TYPE` line in client.conf |
| `/etc/environment.d/10-mobilegl.conf` | `__GLX_VENDOR_LIBRARY_NAME=mobilegl`, `GBM_BACKEND=mobilegl` for the systemd user manager (all Plasma services and what they start, terminals included) |
| `/etc/profile.d/mobilegl.sh` | the same two for login shells (`bash -l`, `su -l`, ssh, `droidspaces run bash -l`) |
Precedence is environment > `/etc/mobilegl/backend` (backend only) > client.conf > built-in; `MOBILEGL_CONFIG_FILE` / `MOBILEGL_BACKEND_FILE` name other files (empty = off); a server process never reads them.
**Fallback.** Before bringing anything up the client probes the configured endpoint (one non-blocking connect, `MOBILEGL_IPC_PROBE_TIMEOUT_MS`, default 250, 0 = off; a refused abstract socket answers in ~0.2 ms). With no server: the EGL vendor returns `EGL_NO_DISPLAY` and no devices (glvnd moves on to the other vendor), the GLX vendor fails `__glx_Main` (libGLX falls back to the vendor Xwayland names), and `mobilegl_gbm` fails `create_device` (libgbm falls back to the device's own backend). Client queries (`eglQueryString(EGL_NO_DISPLAY)`, `eglGetProcAddress`) never bring a session up. MobileGL also steps aside for a GBM device another backend created and for `LIBGL_ALWAYS_SOFTWARE=1` - that is how Xwayland (KWin's patch sets it) keeps the software stack. Show it without stopping the real server:
```sh
sed 's|^MOBILEGL_IPC_CONTROL=.*|MOBILEGL_IPC_CONTROL=unix:@nobody|' /etc/mobilegl/client.conf > /tmp/down.conf
sudo -u swung0x48 env -i HOME=/home/swung0x48 PATH=/usr/bin XDG_RUNTIME_DIR=/run/user/1000 WAYLAND_DISPLAY=wayland-0 \
MOBILEGL_CONFIG_FILE=/tmp/down.conf eglinfo -B -p wayland # vendor = the other one, ~0.1 s
```
## Test clients and how to verify
Inside the container as root (`printf '...' | bash scripts/ct.sh <chan>`), `mgrun offscreen <cmd>` runs a client as swung0x48 in the live session through a login shell, with nothing but the surface mode and the log path set (log `/tmp/mgl-run.client.log`, override base with `MGLOG=/tmp/x.log`); a plain `env -i ... bash -l -c '<cmd>'` as swung0x48 gets MobileGL the same way:
```sh
mgrun offscreen eglinfo -B ; mgrun offscreen glxinfo -B
timeout 25 mgrun offscreen glmark2-es2-wayland -s 1280x720 --run-forever > /tmp/gm.out 2>&1 &
sleep 8; grep -a "presented through" /tmp/mgl-run.client.log
```
Chrome: `bash scripts/chrome-launch.sh <tag> [flags]` (log `/tmp/mgl-chrome-<tag>.client.log`, screenshot `ch-<tag>.png`).
Probes: `scripts/probes/texfmt.c` (texture formats keep alpha?), `dmahash.c` (hash a process's dma-bufs); build in the container, e.g. `gcc -O1 /root/texfmt.c -o /usr/local/bin/mgl-texfmt -lEGL`, run with `mgrun offscreen`.
A result counts only if ALL hold:
- client log says `presented through linux-dmabuf shared images` (not `wl_shm`; `could not be presented through a linux-dmabuf shared image` = fell back);
- `bash scripts/shot.sh g 2 1` gives two different hashes while the client animates (a "fast" score can mean frames are not shown);
- `adb logcat -b crash -d` and `adb logcat -d | grep -E "Fatal signal|Abort message|E MobileGL"` are clean (a frozen window is usually a dead server);
- for plasmashell verdicts, the sticky software renderer is off (below) and `/tmp/mgl-plasmashell.client.log` is freshly written.
Reference (glmark2-es2-wayland 1280x720, zero-copy vs wl_shm): Espryt 187 vs 49, Magma 158 vs 34. Rerun any surprising pass.
## Logs
| What | Where |
|---|---|
| KWin client side | container `/tmp/mobilegl-compositor.client.log` |
| plasmashell / ksplash | `/tmp/mgl-plasmashell.client.log`, `/tmp/mgl-ksplash.client.log` (user drop-ins `~/.config/systemd/user/plasma-{plasmashell,ksplash}.service.d/mobilegl-log.conf`) |
| mgrun / Chrome | `/tmp/mgl-run.client.log`, `/tmp/mgl-chrome-<tag>.client.log` (+ `/tmp/chrome-<tag>-out.log`) |
| Server | `adb logcat -s MobileGL`; file `/data/data/com.anland.consumer.mobilegl/files/mobilegl-server.server.log` |
| Native crashes | `adb logcat -b crash -d`; container `coredumpctl list` |
| Session / KWin stderr | container `journalctl -u desktop-session --no-pager`, `journalctl --no-pager --since -2min \| grep kwin_wayland` |
| Display daemon | `/data/local/tmp/anland-mobilegl/display-daemon.log` |
`MOBILEGL_LOG_FILE_PATH=/tmp/x.log` produces `/tmp/x.client.log` (and `.server.log` for forwarded lines); files are truncated on open, so one base per process. Client builds log at INFO. Symbolize server frames with `$ANDROID_NDK/toolchains/llvm/prebuilt/windows-x86_64/bin/llvm-addr2line.exe -Cfe build-android/libMobileGL.so <offset>`.
## Pitfalls
- **pkill -f self-match**: a `ct.sh`/`droidspaces run bash -lc "<script>"` process carries the script in its argv; `pkill -f chrome` kills the runner. Use `pkill -x`.
- **Root-owned /tmp files**: a log created by a root-run client cannot be reopened by swung0x48 later (no log appears). `rm -f` it as root first.
- **Sticky Plasma software renderer**: after any server crash Plasma writes `[QtQuickRendererSettings] SceneGraphBackend=software` into `~swung0x48/.config/kdeglobals`; plasmashell then renders on the CPU and screenshots still look fine (tray icon "正在使用的软件渲染器"). Delete before any verdict: `sudo -u swung0x48 kwriteconfig6 --file kdeglobals --group QtQuickRendererSettings --key SceneGraphBackend --delete` (cyc.sh does it), restart the session.
- **Lock screen**: autolock is off (`kscreenlockerrc [Daemon] Autolock=false`); a real lock can only be left by typing the password (logind lock/unlock is not supported for this session type - `device/unlock.sh` is unverified). Test the greeter with `/usr/lib/kscreenlocker_greet --testing` and kill it.
- **CRLF**: `core.autocrlf=true` here; anland's backend sources and `sync-build-kwin.sh` are CRLF in the Windows checkout. Strip CR before anything runs on Linux/Android (`tr -d '\r'`; `ct.sh`, `push-tools.sh`, `kwin-stage.sh` do). This skill has a `.gitattributes` forcing LF.
- **Display daemon not auto-started** after reboot: KWin logs "failed to connect to display daemon at /run/anland-mobilegl/display.sock" and the session exits in ~3 s.
- **Device power/connection**: low battery or the screen turning off (30 s default) can kill the SurfaceView - `svc power stayon true`; wireless adb `ip:port` changes per pairing - never pin `-s HA27Q3LQ`, use `ANDROID_SERIAL` if several devices are attached.
- **Container vs phone paths**: container `/tmp` is a different place from the phone's `/data/local/tmp`; move files via `/mnt/Droidspaces/arch-kde-mgl/root` (container `/root`) or `/data/local/tmp/anland-mobilegl` (= container `/run/anland-mobilegl`).
- **Never overwrite a mapped .so in place** (container or APK while running): copy to a new inode and `mv -f`; the APK swap force-stops the app first.
- **Input**: plain `adb shell input` is blocked - use `su -c input`; anland grabs the touchscreen, so if `input tap` does nothing use `input mouse tap x y`. Never `debuggerd -b` a container process (signal 35 kills glibc processes).
- **linux-dmabuf**: the client must use `create` + roundtrip, never `create_immed` (KWin answers a failed immediate import with a protocol error that kills the client).
- **Cross-session bugs**: noise / another window's pixels after some client starts or exits = process-global state in the multi-session server (handles are per client, FBO/VAO per context). Repro with `kscreenlocker_greet --testing`.
- `/etc/environment` leaks the baseline session's driver variables through pam_env (and, via `/usr/lib/environment.d/99-environment.conf`, into the user manager); `mobilegl-startup.sh` unsets them - keep that when editing it.
- **Shared log path**: Xwayland inherits KWin's `MOBILEGL_LOG_FILE_PATH`; any line a process logs opens (truncates) that file. MobileGL stays silent in processes it does not serve, but give any extra client its own `MOBILEGL_LOG_FILE_PATH`.
- **Stale per-process overrides**: an `__EGL_VENDOR_LIBRARY_FILENAMES` / `MOBILEGL_*` left in a unit drop-in or the user manager's environment (`systemctl --user show-environment`) still wins over the system files; `run-plasma.sh` (terminate-user) clears the manager's.
- `handoff` mentions a `kwin_wayland` logging shim and `/tmp/mgl-kwin-<pid>.log`: stale - `/opt/mobilegl/kwin/bin/kwin_wayland` is now the real binary and logs to `/tmp/mobilegl-compositor.client.log`.
## House rules
- Work in a git worktree, never in the shared main checkout or its build dirs; worktrees need `GIT_LFS_SKIP_SMUDGE=1`.
- Commit with `git commit --no-verify`, one short sentence, **no** `Co-Authored-By` trailer.
- Never run the DirectVulkan integration tests (`ctest -E DirectVulkan`).
- No external project names ("Mesa", "Zink", ...) in source code or comments; describe the technique.
- Vendor-agnostic only on the zero-copy path: AHB, EGL_ANDROID_*, VK_ANDROID AHB import, sync_file, dma-buf, libgbm ABI - no kgsl/gralloc layouts/QCOM modifiers.
- Identity caches key on monotonic lifetime ids, never GL names or pointers.
@@ -1,170 +0,0 @@
# Reproducing the MobileGL + anland + KDE Plasma setup from source
This is the from-scratch path for a NEW development machine and/or a NEW phone. `SKILL.md` covers the
day-to-day loop once everything below exists. Paths and names that are specific to the original
machine are listed in step 9: set them in `scripts/env.sh` (or the environment) before running anything.
## 0. What you need
**Phone.**
- arm64 Android 11+ with **root**. KernelSU is what this was built on; the scripts only need `su -c`.
- A Vulkan 1.1 driver with `VK_ANDROID_external_memory_android_hardware_buffer` for Magma, and/or GLES 3.2 + EGL_ANDROID_native_fence_sync for Espryt. Nothing vendor-specific is used: no kgsl and no vendor ioctls, only AHardwareBuffer, sync_file and the vendor's public GLES/Vulkan.
- About 20 GB free for the container image.
**Development host.**
- The scripts are written for **Windows + Git Bash** with WSL (`archlinux` distro) for the unit tests and the cross build.
- A Linux host works too: drop the `cygpath`/`MSYS_NO_PATHCONV` handling in `env.sh`, and run the WSL parts natively.
- Tools:
- `adb`, CMake >= 3.22, Ninja, Python 3 (+ Pillow for screenshots/recording).
- Android NDK **27.2.12479018**.
- JDK 17 and Android SDK platform 36 (for the APK).
- In the Linux environment: clang/lld/llvm of ONE major version (a mismatched lld breaks `ld.lld`), cmake, ninja.
## 1. Sources
```sh
# MobileGL: branch feat/disaggregated (everything here is on it)
git clone https://github.com/MobileGL-Dev/MobileGL.git && cd MobileGL
git checkout feat/disaggregated
GIT_LFS_SKIP_SMUDGE=1 git submodule update --init --recursive
# 3rdparty/glslang is the MobileGL-Dev fork (main); its External/spirv-tools must be populated
# (glslang's own update_glslang_sources.py, or copy it from another checkout).
# Keep builds out of a shared checkout: work in a worktree (GIT_LFS_SKIP_SMUDGE=1 git worktree add ...).
# anland: branch legacy-mobilegl-unified (KWin backend + patch, startup script, APK, daemon module)
git clone https://github.com/MobileGL-Dev/anland.git && cd anland # the fork that carries this branch
git checkout legacy-mobilegl-unified
```
Build the server (APK) and the client (container) from the **same MobileGL commit**: both stamp
`git rev-parse HEAD`, and a mismatch logs "compatible wire with different build".
## 2. Phone base: root, Droidspaces, display daemon
1. **Root** with KernelSU (or another `su` provider).
2. **Droidspaces:** install the module and its app. Containers live under `/data/local/Droidspaces/Containers/<name>/`, and the CLI is `/data/local/Droidspaces/bin/droidspaces`.
3. **anland display daemon** (KernelSU/Magisk module `anland-daemon`):
- Build it from the anland repo with `build_daemon_android.sh`, then package it with `build_magisk_module.sh`, which uses `magisk_module/`. Flash it and reboot.
- The module's `service.sh` starts the original daemon on `/data/local/tmp/display_daemon.sock`.
- The MobileGL session uses a SECOND instance of the same binary on `/data/local/tmp/anland-mobilegl/display.sock`: see `scripts/device/restart-daemon.sh`, which also chmods the directory and socket.
## 3. The container
Use an **Arch Linux ARM (aarch64, glibc) KDE Plasma Wayland rootfs** that has a systemd `desktop-session.service` running the desktop as a normal user with `PAMName=login`. A ready-made one is the Arch KDE "Wayland" image from Droidspaces RootFS Desktop Builder (see anland `doc/UserManual/anland_guide.md`, "Use prebuilt packages or a RootFS"). Or install `plasma-desktop`, `plasma-workspace`, `libglvnd`, `xorg-xwayland`, `base-devel`, `cmake` and `ninja` on plain Arch Linux ARM and write the service yourself.
Import it into Droidspaces as `arch-kde-mgl`. The default name is in `env.sh`. Reference `container.config` keys:
```
enable_gpu_mode=1
net_mode=host
bind_mounts=/data/local/tmp/display_daemon.sock:/run/display.sock,/data/local/tmp/anland-mobilegl:/run/anland-mobilegl
run_at_boot=0
```
- **Host networking:** it is required. The MobileGL server listens on the ABSTRACT socket `@anland-mobilegl`, which crosses into the container only when the network namespace is shared.
- **The anland-mobilegl directory:** create `/data/local/tmp/anland-mobilegl` on the phone before the first start, mode 777.
- **Desktop user:** the default is `swung0x48` (`MGL_DESKTOP_USER`). Create your own and point `desktop-session.service` at it.
- **Starting it:** `droidspaces -C .../container.config start`. Android root sees the rootfs at `/mnt/Droidspaces/<name>`, which `CT_ROOT` in `env.sh` relies on.
- **Container tools:** install them with `bash scripts/push-tools.sh` once the container runs.
## 4. MobileGL server and the anland APK
```sh
bash scripts/build-android.sh # -> <worktree>/build-android/libMobileGL.so
```
The script runs, with the NDK toolchain:
```
-DANDROID_ABI=arm64-v8a -DANDROID_PLATFORM=android-26 -DCMAKE_BUILD_TYPE=RelWithDebInfo
-DMOBILEGL_PIPE_PUSH=ON -DMOBILEGL_BUILD_DISAGGREGATED=ON -DMOBILEGL_BUILD_DISAGGREGATED_INPROC=ON
-DMOBILEGL_BUILD_TEST=OFF -DMOBILEGL_BUILD_BENCHMARK=OFF
```
APK, from anland `consumers/anland_v5/android_consumer` (details in its `MOBILEGL.md`):
```sh
mkdir -p dist/arm64-v8a && cp <worktree>/build-android/libMobileGL.so dist/arm64-v8a/
MOBILEGL_DIST=$PWD/dist ./gradlew :app:assemblePlainDebug \
-PanlandNdkVersion=27.2.12479018 -PmobileglApplicationId=com.anland.consumer.mobilegl
adb install -r app/build/outputs/apk/plain/debug/app-plain-debug.apk
```
- **Grant root:** the app needs root for its helper; approve it in KernelSU.
- **Reinstall with another signing key:** that changes the UID, so grant root again (anland `mobilegl-tools/ksu_grant.c` does it from a shell). Don't uninstall to fix a signature clash: that wipes the app data.
- **Later server-only changes:** swap just the library into the installed APK (`scripts/cyc.sh` / `device/swap.sh`) instead of rebuilding the APK.
## 5. MobileGL client in the container
Pick one of these two:
- **Cross build** (fast, from WSL or Linux):
1. `bash scripts/xsysroot/refresh-sysroot.sh` exports the container's headers and libraries to `~/sysroots/arch-kde-mgl` and installs `~/sysroots/aarch64-arch.cmake`. Re-run it after container package upgrades.
2. `bash scripts/xbuild.sh`, then `bash scripts/xdeploy.sh`.
- **Native build in the container** (slow, no WSL): `scripts/sync-src.sh` copies the worktree to `/root/mobilegl-unified-src`, then run anland `producers/kde/Arch_v5/mobilegl-tools/anland-build-client.sh` inside (g++, `-DMOBILEGL_BUILD_DISAGGREGATED=ON`, Release).
Either route installs the same files, renamed into place so running clients keep their old mapping:
| File | What it is |
|---|---|
| `/opt/mobilegl/lib/libMobileGL.so` (+ `libEGL`/`libGL` aliases) | the client library |
| `/usr/share/glvnd/egl_vendor.d/10_mobilegl.json` | system-wide EGL vendor; sorts before the distribution's `50_*.json`, which serves whenever MobileGL declines (no server reachable) |
| `/opt/mobilegl/share/glvnd/egl_vendor.d/50_mobilegl.json` | per-process forcing |
| `/usr/lib/libGLX_mobilegl.so.0` | GLX vendor |
| `/usr/lib/gbm/mobilegl_gbm.so` | GBM backend (zero-copy window buffers) |
| `/etc/mobilegl/client.conf` | `MOBILEGL_TRANSPORT=spawn`, `MOBILEGL_IPC_DATA=shm`, `MOBILEGL_IPC_CONTROL=unix:@anland-mobilegl` |
| `/etc/mobilegl/backend` | `DirectVulkan` (Magma) or `DirectGLES` (Espryt) |
| `/etc/environment.d/10-mobilegl.conf`, `/etc/profile.d/mobilegl.sh` | `__GLX_VENDOR_LIBRARY_NAME=mobilegl`, `GBM_BACKEND=mobilegl` |
## 6. KWin 6.7.4 with the anland backend, and Xwayland
The MobileGL session runs a rebuilt KWin from `/opt/mobilegl/kwin`, so the packaged one stays untouched.
1. **Source tree:** in the container, unpack KWin 6.7.4 to `/root/mobilegl-build/kwin-6.7.4`, apply anland `producers/kde/Arch_v5/kwin.patch`, and overlay `producers/kde/anland_backend_Arch_v5/src/backends/anland` into `src/backends/anland`. Also take the current `common/` and `libdisplay_producer/`, as `mobilegl.md` there says.
2. **Configure:**
```sh
cmake -S kwin-6.7.4 -B kwin-6.7.4/build -G Ninja -DCMAKE_BUILD_TYPE=Release \
-DCMAKE_INSTALL_PREFIX=/usr -DCMAKE_INSTALL_LIBDIR=lib -DBUILD_TESTING=OFF
```
3. **Build and install:** run `producers/kde/Arch_v5/sync-build-kwin.sh` (`ninja -j4`). It installs `kwin_wayland` + `libkwin.so.6.7.4` into `/opt/mobilegl/kwin/{bin,lib}`, the patched screencast plugin in place (the original is kept beside it), and `/opt/mobilegl/bin/mobilegl-startup.sh`.
- From the dev host, `bash scripts/kwin-stage.sh build` does steps 1–3 incrementally: `kwprep.sh` applies changed patch hunks.
4. **Xwayland:** the anland-patched Xwayland 24.1.13 comes from `producers/kde/Arch_v5/build.sh` (makepkg, as a normal user; it builds the anland KWin and Xwayland packages). A prebuilt anland rootfs already has it.
5. **Session hook:** add `/etc/systemd/system/desktop-session.service.d/mobilegl.conf`:
```ini
[Service]
ExecStart=
ExecStart=/opt/mobilegl/bin/mobilegl-startup.sh plasma
Environment=ANLAND_SOCKET=/run/anland-mobilegl/display.sock
Environment=QT_LOGGING_RULES=kwin_*.info=true
```
`mobilegl-startup.sh plasma` writes the user drop-in for `plasma-kwin_wayland.service` (the `/opt/mobilegl/kwin` binary, `ANLAND_MOBILEGL=1`, `MOBILEGL_IPC_SURFACE=server`, `GBM_BACKEND=mobilegl`) and runs `startplasma-wayland`.
## 7. Bring it up
Until the app-driven auto-start lands, the order matters:
1. **Backend:** `setprop debug.mobilegl.backend DirectVulkan`; it must match `/etc/mobilegl/backend`.
2. **App:** start it with `--es socket_path /data/local/tmp/anland-mobilegl/display.sock`.
3. **Container:** start it.
4. **Display daemon:** start the MobileGL daemon instance.
5. **Plasma:** `run-plasma.sh`.
`scripts/device/bringup.sh [DirectVulkan|DirectGLES]` does all five. See SKILL.md "Bring-up after a phone reboot".
## 8. Verify
- **Plasma:** it appears in the app. The tray must NOT show the "software renderer" icon; if it does, delete `SceneGraphBackend=software` from the user's `kdeglobals` and restart.
- **Plain shell:** in a plain container shell as the desktop user, `eglinfo -B` names MobileGL, and `glxinfo -B` from a login shell does too.
- **Wayland client:** `timeout 25 mgrun offscreen glmark2-es2-wayland -s 1280x720`. The log must say `presented through linux-dmabuf shared images`.
- **Chrome:** `bash scripts/chrome-launch.sh t1` gives windows with correct icons.
- **Resize and lock:** BACK toggles the extra-keys bar (resize); lock/unlock resumes the desktop. `rtest.sh` in the scratch dir checks both.
- **Unit tests:** `bash scripts/wsl-all.sh` in WSL. NEVER run the DirectVulkan integration tests.
## 9. Machine-specific values to change
| Value | Original | Where |
|---|---|---|
| MobileGL worktree | this skill's worktree | `MGL_WORKTREE` (auto) |
| scratch dir | `%LOCALAPPDATA%/Temp/anl` | `ANL_DIR` |
| NDK | `<SDK>/ndk/27.2.12479018` | `ANDROID_NDK` |
| anland worktree | `%USERPROFILE%/AndroidStudioProjects/anland/.claude/worktrees/mgl-unified` | `ANLAND_WORKTREE` (`kwin-stage.sh`) |
| APK id | `com.anland.consumer.mobilegl` | `MGL_PKG` |
| container | `arch-kde-mgl` | `MGL_CONTAINER` |
| desktop user | `swung0x48` | `MGL_DESKTOP_USER` + `desktop-session.service` |
| WSL distro | `archlinux` | `WSL_DISTRO` (`xbuild.sh`, `wsl-*.sh`) |
| cross build dir | WSL `~/mgl-xbuild-a64` | `MGL_XBUILD_DIR` |
| phone | Lenovo TB321FU, Adreno 750 | nothing: no serial is pinned; with several devices set `ANDROID_SERIAL` |
**Thermals:** a phone vendor's thermal daemon may throttle charging while the screen is on during long sessions. That is not part of this setup.
@@ -1,24 +0,0 @@
#!/usr/bin/env bash
# build-android.sh - build the Android SERVER libMobileGL.so (NDK, arm64-v8a) that the anland APK embeds.
# Output: $MGL_WORKTREE/build-android/libMobileGL.so (RelWithDebInfo, unstripped, ~320 MB; keep it for
# llvm-addr2line, it is what cyc.sh pushes). Stamp = worktree HEAD, so the container client
# (xbuild.sh, same stamp) and the server agree on the build ("compatible wire with different build"
# WARN otherwise). Env: MGL_WORKTREE, ANDROID_NDK, BUILD_DIR (default build-android), JOBS (12).
# Log level is compiled to INFO.
set -euo pipefail
. "$(dirname "$0")/env.sh"
W=$MGL_WORKTREE
B=$W/${BUILD_DIR:-build-android}
STAMP=$(git -C "$W" rev-parse HEAD)
if [ ! -f "$B/build.ninja" ]; then
cmake -S "$W" -B "$B" -G Ninja -DCMAKE_TOOLCHAIN_FILE="$ANDROID_NDK/build/cmake/android.toolchain.cmake" \
-DANDROID_ABI=arm64-v8a -DANDROID_PLATFORM=android-26 -DCMAKE_BUILD_TYPE=RelWithDebInfo \
-DMOBILEGL_PIPE_PUSH=ON -DMOBILEGL_BUILD_DISAGGREGATED=ON -DMOBILEGL_BUILD_DISAGGREGATED_INPROC=ON \
-DMOBILEGL_BUILD_TEST=OFF -DMOBILEGL_BUILD_BENCHMARK=OFF \
-DCMAKE_CXX_FLAGS=-DMOBILEGL_LOG_ACTIVE_LEVEL=MOBILEGL_LOG_LEVEL_INFO \
-DMOBILEGL_BUILD_STAMP="$STAMP"
else
cmake "$B" -DMOBILEGL_BUILD_STAMP="$STAMP" >/dev/null
fi
cmake --build "$B" --target MobileGL -j"${JOBS:-12}"
ls -la "$B/libMobileGL.so"
@@ -1,20 +0,0 @@
#!/usr/bin/env bash
# chrome-launch.sh <tag> [extra chrome flags...] - (re)start Chrome inside the running Plasma session
# through mobilegl-startup.sh's `chrome` mode (ANGLE GLES over MobileGL EGL, in-process GPU), client
# log /tmp/mgl-chrome-<tag>.client.log, then print its "presented through" line and save a screenshot
# to $ANL_DIR/ch-<tag>.png. Kills the running chrome first (pkill -x, never -f). MobileGL is the
# container's system-wide vendor (10_mobilegl.json + /etc/mobilegl/client.conf), so only the log is set here.
# Env: WAIT (s before checking, default 20), CHANNEL (ct.sh channel, default chrome).
set -euo pipefail
here=$(cd "$(dirname "$0")" && pwd)
. "$here/env.sh"
TAG=${1:?usage: chrome-launch.sh <tag> [chrome flags...]}; shift
bash "$here/ct.sh" "${CHANNEL:-chrome}" <<IN
pkill -x chrome; sleep 2
U=\$(id -u $MGL_DESKTOP_USER)
sudo -u $MGL_DESKTOP_USER env XDG_RUNTIME_DIR=/run/user/\$U WAYLAND_DISPLAY=wayland-0 DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/\$U/bus MOBILEGL_LOG_FILE_PATH=/tmp/mgl-chrome-$TAG.log bash -c 'nohup /opt/mobilegl/bin/mobilegl-startup.sh chrome --restore-last-session $* > /tmp/chrome-$TAG-out.log 2>&1 &'
sleep ${WAIT:-20}
grep -ah 'presented through' /tmp/mgl-chrome-$TAG.client.log | head -3
IN
adb_ shell "su -c 'screencap -p $DEV_SHARE/ch-$TAG.png'"
adb_ pull "$DEV_SHARE/ch-$TAG.png" "$ANL_DIR/ch-$TAG.png" >/dev/null && echo "screenshot: $ANL_DIR/ch-$TAG.png"
@@ -1,29 +0,0 @@
#!/bin/bash
# kwprep.sh - (container, as root) bring the live KWin tree /root/mobilegl-build/kwin-6.7.4 in line with
# anland's kwin.patch + anland backend sources, touching ONLY files whose content changed (keeps the
# ninja build incremental). It re-applies the whole patch to a pristine copy of KWin's src/
# (/root/gbm-dev/kwin-a/src) in /root/kp and copies every patched file that differs into the live tree,
# then copies changed backend files. Build + install afterwards with anland's sync-build-kwin.sh.
#
# Input: /root/kwsync.tgz, a tar made in the anland worktree's producers/kde directory:
# tar czf kwsync.tgz Arch_v5/kwin.patch Arch_v5/mobilegl-startup.sh anland_backend_Arch_v5/src/backends/anland/
# and pushed to the container's /root (e.g. via /mnt/Droidspaces/arch-kde-mgl/root/ on the Android side).
# The pristine tree /root/gbm-dev/kwin-a/src was set up by hand earlier (unverified that it is exactly
# upstream 6.7.4); patch hunks that fail are reported by `patch`.
set -e
rm -rf /root/kwsync && mkdir -p /root/kwsync && tar xzf /root/kwsync.tgz -C /root/kwsync
P=/root/kwsync/Arch_v5/kwin.patch
rm -rf /root/kp && mkdir -p /root/kp && cp -a /root/gbm-dev/kwin-a/src /root/kp/
cd /root/kp && patch -p1 -s < $P
LIVE=/root/mobilegl-build/kwin-6.7.4
FILES=$(grep -E '^\+\+\+ b/' $P | sed 's|^+++ b/||' | awk '{print $1}' | sort -u)
for f in $FILES; do
if [ -f "/root/kp/$f" ] && ! cmp -s "/root/kp/$f" "$LIVE/$f"; then cp "/root/kp/$f" "$LIVE/$f"; echo "updated $f"; fi
done
for f in /root/kwsync/anland_backend_Arch_v5/src/backends/anland/*; do
# libdisplay_producer is a symlink in git; a Windows checkout turns it into a small text file. The live
# tree has the real directory (repo-root libdisplay_producer/), which neither script syncs.
[ -f "$f" ] && [ "$(basename $f)" != libdisplay_producer ] || continue
b=$(basename $f); if ! cmp -s "$f" "$LIVE/src/backends/anland/$b"; then cp "$f" "$LIVE/src/backends/anland/$b"; echo "updated anland/$b"; fi
done
echo PREP_DONE
@@ -1,21 +0,0 @@
#!/bin/bash
# mgrun <surface: offscreen|server> <command...> - (container, as root) run one MobileGL client as the
# desktop user inside the running Plasma session. Installed as /usr/local/bin/mgrun (push-tools.sh).
# mgrun offscreen glmark2-es2-wayland -s 1280x720 # Wayland client, presents through KWin
# mgrun offscreen eglinfo -B ; mgrun offscreen glxinfo -B # glxinfo goes through Xwayland + GLX vendor
# "server" is only for a client that owns the Android Surface itself (KWin does); everything else is
# offscreen. MobileGL is the container's system-wide vendor, so nothing selects it here: EGL comes from
# /usr/share/glvnd/egl_vendor.d/10_mobilegl.json, transport/endpoint from /etc/mobilegl/client.conf,
# the backend from /etc/mobilegl/backend (must match the server), and the GLX vendor name / GBM backend
# from /etc/profile.d/mobilegl.sh (sourced by the login shell below). Client log:
# ${MGLOG:-/tmp/mgl-run.log} -> the library writes /tmp/mgl-run.client.log (truncated per run; give
# concurrent clients different MGLOG values). Env: MGLOG, DESKTOP_USER (swung0x48).
S=$1; shift
DU=${DESKTOP_USER:-swung0x48}
U=$(id -u "$DU")
cd /tmp
exec sudo -u "$DU" env XDG_RUNTIME_DIR=/run/user/$U WAYLAND_DISPLAY=wayland-0 DISPLAY=:0 \
XAUTHORITY=$(ls /run/user/$U/xauth_* 2>/dev/null | head -1) \
DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/$U/bus QT_QPA_PLATFORM=wayland \
MOBILEGL_IPC_SURFACE=$S MOBILEGL_LOG_FILE_PATH=${MGLOG:-/tmp/mgl-run.log} \
bash -lc 'exec "$@"' mgrun "$@"
@@ -1,26 +0,0 @@
#!/usr/bin/env bash
# ct.sh <channel> [script-file] - run a bash script as ROOT inside the container (login shell),
# reading the script from the file or from stdin. Generic form of the old c.sh/c2.sh/c3.sh.
#
# printf '%s\n' 'ls -la /tmp/*.log' | bash ct.sh mychan
# bash ct.sh mychan ./something.cmd
#
# How: the script is written to $ANL_DIR/<channel>.cmd, pushed to $DEV_TOOLS/<channel>.cmd together with
# a one-line <channel>.sh that does `droidspaces --name=<container> run bash -lc "$(cat <channel>.cmd)"`,
# and that runs under `su`. Quoting through adb + su + droidspaces is thereby avoided entirely.
#
# Pick a channel name of your own: other sessions on the same phone use c, c2, c3, xd, xr, gbm...;
# writing to their channel files races with them. CR characters are stripped (Windows checkouts).
# Inside, run user-side commands with `sudo -u <desktop user> env XDG_RUNTIME_DIR=/run/user/<uid> ...`.
# Never `pkill -f <word>` in a channel script: the `bash -lc "<script>"` process carries the whole
# script on its command line and kills itself. Use `pkill -x <name>`.
set -euo pipefail
. "$(dirname "$0")/env.sh"
ch=${1:?usage: ct.sh <channel> [script-file]}
src=${2:--}
if [ "$src" = - ]; then tr -d '\r' > "$ANL_DIR/$ch.cmd"; else tr -d '\r' < "$src" > "$ANL_DIR/$ch.cmd"; fi
printf '%s\n' "$DS_BIN --name=$MGL_CONTAINER run bash -lc \"\$(cat $DEV_TOOLS/$ch.cmd)\"" > "$ANL_DIR/$ch.sh"
adb_ shell "mkdir -p $DEV_TOOLS"
adb_ push "$ANL_DIR/$ch.cmd" "$DEV_TOOLS/$ch.cmd" >/dev/null
adb_ push "$ANL_DIR/$ch.sh" "$DEV_TOOLS/$ch.sh" >/dev/null
adb_ shell "su -c 'sh $DEV_TOOLS/$ch.sh'"
@@ -1,19 +0,0 @@
#!/usr/bin/env bash
# cyc.sh <shot-name> - one server iteration: clear Plasma's sticky software-renderer key, push the
# NDK-built server lib, swap it into the installed APK (device/swap.sh), restart app + Plasma session
# (device/run-plasma.sh, ~90 s), screenshot to $ANL_DIR/<shot-name>.png, print fatal logcat lines.
# Env: SERVER_LIB (default $MGL_WORKTREE/build-android/libMobileGL.so), WAIT (s after the session
# restart, default 15), N (logcat lines, default 20), CHANNEL (ct.sh channel, default cyc).
# Needs device/swap.sh + device/run-plasma.sh in $DEV_TOOLS (push-tools.sh). RESTARTS THE SESSION.
set -euo pipefail
here=$(cd "$(dirname "$0")" && pwd)
. "$here/env.sh"
shot=${1:?usage: cyc.sh <shot-name>}
LIB=${SERVER_LIB:-$MGL_WORKTREE/build-android/libMobileGL.so}
printf '%s\n' "sudo -u $MGL_DESKTOP_USER kwriteconfig6 --file kdeglobals --group QtQuickRendererSettings --key SceneGraphBackend --delete; rm -f /tmp/mgl-plasmashell.client.log" \
| bash "$here/ct.sh" "${CHANNEL:-cyc}"
adb_ push "$LIB" "$DEV_SHARE/libMobileGL.new.so" >/dev/null
adb_ logcat -c
adb_ shell "su -c 'sh $DEV_TOOLS/swap.sh >/dev/null && sh $DEV_TOOLS/run-plasma.sh >/dev/null 2>&1; sleep ${WAIT:-15}; screencap -p $DEV_SHARE/$shot.png'"
adb_ pull "$DEV_SHARE/$shot.png" "$ANL_DIR/$shot.png" >/dev/null && echo "screenshot: $ANL_DIR/$shot.png"
adb_ logcat -d | grep -E "Fatal signal|FATAL|Abort message|Magma wire buffer|E MobileGL" | cut -c1-260 | head -"${N:-20}" || true
@@ -1,29 +0,0 @@
# bringup.sh [DirectGLES|DirectVulkan] - (Android root shell) bring the stack up after a phone reboot:
# stay-awake, container, backend property, experiment display daemon, anland app, then the Plasma
# session (run-plasma.sh, ~90 s; skip with NO_PLASMA=1). The backend defaults to the container's
# /etc/mobilegl/backend (persists across reboots; the property does not).
# Assembled from the documented manual steps; not exercised as one unit yet. Re-running restarts the
# daemon, the app and the session. Run: su -c "sh /data/local/tmp/anl/bringup.sh"
# Env: PKG, CONTAINER, DS, SOCK, TOOLS (dir holding run-plasma.sh / restart-daemon.sh; default: this dir).
D=${DS:-/data/local/Droidspaces/bin/droidspaces}
P=${PKG:-com.anland.consumer.mobilegl}
C=${CONTAINER:-arch-kde-mgl}
SOCK=${SOCK:-/data/local/tmp/anland-mobilegl/display.sock}
T=${TOOLS:-$(dirname $0)}
svc power stayon true
if $D show 2>/dev/null | grep -q " $C "; then
echo "container $C already running"
else
$D -C /data/local/Droidspaces/Containers/$C/container.config start
sleep 5
fi
B=${1:-$(cat /mnt/Droidspaces/$C/etc/mobilegl/backend 2>/dev/null)}
B=${B:-DirectGLES}
setprop debug.mobilegl.backend $B
echo "$B" > /mnt/Droidspaces/$C/etc/mobilegl/backend
echo "backend: $(getprop debug.mobilegl.backend)"
sh $T/restart-daemon.sh
am start -n $P/com.anland.consumer.MainActivity --es socket_path $SOCK >/dev/null
sleep 3
if pidof $P:mobilegl >/dev/null; then echo "server process $P:mobilegl up"; else echo "WARNING: $P:mobilegl not running"; fi
[ "${NO_PLASMA:-0}" = 1 ] || sh $T/run-plasma.sh
@@ -1,20 +0,0 @@
# restart-daemon.sh - (Android root shell) (re)start the EXPERIMENT's anland display daemon on $SOCK.
# It is not started at boot (the anland-daemon module's service.sh only starts the original daemon on
# /data/local/tmp/display_daemon.sock, which must be left alone). Without it KWin logs
# "failed to connect to display daemon at /run/anland-mobilegl/display.sock" and the session dies in ~3 s.
# The container sees $SOCK as /run/anland-mobilegl/display.sock (bind mount in container.config);
# uid 1000 in the container must connect, hence 777 dir / 666 socket.
# Env: SOCK, DAEMON (/data/adb/modules/anland-daemon/display_daemon).
SOCK=${SOCK:-/data/local/tmp/anland-mobilegl/display.sock}
DAEMON=${DAEMON:-/data/adb/modules/anland-daemon/display_daemon}
DIR=$(dirname $SOCK)
for p in $(ps -A -o PID,ARGS | grep "display_daemon $SOCK" | grep -v grep | awk '{print $1}'); do kill $p; done
sleep 1
rm -f $SOCK
mkdir -p $DIR
nohup $DAEMON $SOCK > $DIR/display-daemon.log 2>&1 &
sleep 1
chmod 777 $DIR
chmod 666 $SOCK
echo "daemon restarted:"
ps -A -o PID,ARGS | grep "display_daemon $SOCK" | grep -v grep
@@ -1,26 +0,0 @@
# run-plasma.sh - (Android root shell) restart the anland app and the container's Plasma session
# (desktop-session.service -> mobilegl-startup.sh plasma). Takes ~90 s (two 40 s waits: logind must
# finish tearing the old user session down before the new one starts). Prints the unit status, the
# plasma user units and recent coredumps. Run: su -c "sh /data/local/tmp/anl/run-plasma.sh"
# Env: PKG, CONTAINER, DESKTOP_USER (swung0x48), SOCK, DS (droidspaces binary).
D=${DS:-/data/local/Droidspaces/bin/droidspaces}
P=${PKG:-com.anland.consumer.mobilegl}
C=${CONTAINER:-arch-kde-mgl}
U=${DESKTOP_USER:-swung0x48}
SOCK=${SOCK:-/data/local/tmp/anland-mobilegl/display.sock}
am force-stop $P
am start -n $P/com.anland.consumer.MainActivity --es socket_path $SOCK >/dev/null
sleep 3
$D --name=$C run bash -lc "
systemctl stop desktop-session.service 2>/dev/null
loginctl terminate-user $U 2>/dev/null; sleep 40
systemctl reset-failed desktop-session.service
rm -f /tmp/mobilegl-compositor.log
date +%s > /tmp/plasma-start
systemctl start desktop-session.service
sleep 40
systemctl --no-pager status desktop-session.service | head -8
UID_=\$(id -u $U)
sudo -u $U XDG_RUNTIME_DIR=/run/user/\$UID_ systemctl --user --no-pager list-units --all 'plasma*' 2>&1 | head -30
coredumpctl --no-pager list --since '-2min' 2>&1 | tail -5
"
@@ -1,12 +0,0 @@
# status.sh - (Android root shell) READ-ONLY health check of the whole stack.
# Run: su -c "sh /data/local/tmp/anl/status.sh" Env: PKG, CONTAINER, DS, SOCK.
D=${DS:-/data/local/Droidspaces/bin/droidspaces}
P=${PKG:-com.anland.consumer.mobilegl}
C=${CONTAINER:-arch-kde-mgl}
SOCK=${SOCK:-/data/local/tmp/anland-mobilegl/display.sock}
echo "battery: $(dumpsys battery | grep ' level:' | tr -d ' ') $(dumpsys power | grep -o 'mStayOn=[a-z]*')"
echo "prop debug.mobilegl.backend=$(getprop debug.mobilegl.backend) container /etc/mobilegl/backend=$(cat /mnt/Droidspaces/$C/etc/mobilegl/backend 2>/dev/null)"
echo "app pid: $(pidof $P) server (:mobilegl) pid: $(pidof $P:mobilegl)"
ps -A -o PID,ARGS | grep "display_daemon $SOCK" | grep -v grep || echo "experiment display daemon NOT running"
$D show
$D --name=$C run bash -lc 'echo "desktop-session: $(systemctl is-active desktop-session.service)"; pgrep -a -x kwin_wayland; pgrep -a -x plasmashell; grep -A1 QtQuickRendererSettings /home/*/.config/kdeglobals 2>/dev/null || echo "kdeglobals: no sticky software renderer"'
@@ -1,17 +0,0 @@
# swap.sh - (Android root shell) replace the server libMobileGL.so inside the INSTALLED anland APK with
# $SHARE/libMobileGL.new.so, keeping owner, mode and SELinux context; force-stops the app. The first
# run backs the APK's original lib up to $SHARE/libMobileGL.so.orig. No re-signing/reinstall (that
# would change the app UID and lose its root grant). Run: su -c "sh /data/local/tmp/anl/swap.sh"
# Env: PKG (com.anland.consumer.mobilegl), SHARE (/data/local/tmp/anland-mobilegl).
set -e
P=${PKG:-com.anland.consumer.mobilegl}
SHARE=${SHARE:-/data/local/tmp/anland-mobilegl}
D=$(dirname $(pm path $P | sed 's/package://'))/lib/arm64
ls -laZ $D
[ -f $SHARE/libMobileGL.so.orig ] || cp $D/libMobileGL.so $SHARE/libMobileGL.so.orig
am force-stop $P
CTX=$(ls -Z $D/libMobileGL.so | awk '{print $1}')
OWN=$(stat -c %u:%g $D/libMobileGL.so)
cp $SHARE/libMobileGL.new.so $D/libMobileGL.so
chown $OWN $D/libMobileGL.so; chmod 755 $D/libMobileGL.so; chcon $CTX $D/libMobileGL.so
ls -laZ $D/libMobileGL.so
@@ -1,15 +0,0 @@
# switch.sh <DirectGLES|DirectVulkan> - (Android root shell) select the server backend: Espryt =
# DirectGLES, Magma = DirectVulkan. Sets the system property the server reads (lost on reboot), writes
# the container's /etc/mobilegl/backend (what every client and the KWin drop-in report; it must match or
# the server refuses the client: "Hello.backendType disagrees with pinned backend"), restarts the app.
# The running Plasma session still speaks the old backend: run run-plasma.sh afterwards.
# Env: PKG, CONTAINER (arch-kde-mgl), SOCK (display daemon socket).
B=${1:?usage: switch.sh DirectGLES|DirectVulkan}
P=${PKG:-com.anland.consumer.mobilegl}
C=${CONTAINER:-arch-kde-mgl}
SOCK=${SOCK:-/data/local/tmp/anland-mobilegl/display.sock}
setprop debug.mobilegl.backend $B
echo $B > /mnt/Droidspaces/$C/etc/mobilegl/backend
am force-stop $P
am start -n $P/com.anland.consumer.MainActivity --es socket_path $SOCK >/dev/null
sleep 4
@@ -1,8 +0,0 @@
# unlock.sh - (Android root shell) ask logind to unlock the desktop user's session. UNVERIFIED that this
# helps here: the handoff notes this logind session type does not support lock-session (a real lock
# screen then needs the password). Prevention: [Daemon] Autolock=false in ~/.config/kscreenlockerrc.
# Env: DS, CONTAINER, DESKTOP_USER.
D=${DS:-/data/local/Droidspaces/bin/droidspaces}
C=${CONTAINER:-arch-kde-mgl}
U=${DESKTOP_USER:-swung0x48}
$D --name=$C run bash -lc "S=\$(loginctl list-sessions --no-legend | awk '\$3==\"$U\"{print \$1}' | head -1); loginctl unlock-session \$S; echo unlocked \$S"
@@ -1,41 +0,0 @@
# env.sh - shared parameters for the host-side (Git Bash) scripts of the anland-mobilegl-plasma skill.
# Sourced, never run. Every value can be overridden from the environment before calling a script.
#
# MGL_WORKTREE MobileGL worktree (Windows form C:/...). Default: the worktree this skill lives in.
# ANL_DIR Local scratch dir: channel files, screenshots, xdist/. Default: %LOCALAPPDATA%/Temp/anl
# ANDROID_NDK NDK used for the Android server lib. Default: <SDK>/ndk/27.2.12479018
# MGL_PKG Anland APK that embeds the server. Default: com.anland.consumer.mobilegl
# MGL_CONTAINER Droidspaces container. Default: arch-kde-mgl
# MGL_DESKTOP_USER Desktop user inside the container. Default: swung0x48
# DS_BIN droidspaces binary on the phone. Default: /data/local/Droidspaces/bin/droidspaces
# DEV_TOOLS Phone dir for device/*.sh and channel files. Default: /data/local/tmp/anl
# DEV_SHARE Phone dir bind-mounted into the container as /run/anland-mobilegl (screenshots,
# server lib staging, display daemon socket). Default: /data/local/tmp/anland-mobilegl
# ANDROID_SERIAL Honoured by adb itself; leave unset when only one device is attached
# (USB serial or a wireless "ip:port").
_skill_scripts=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
if [ -z "${MGL_WORKTREE:-}" ]; then
MGL_WORKTREE=$(cd "$_skill_scripts/../../../.." && pwd -W 2>/dev/null || pwd)
fi
: "${ANL_DIR:=$(cygpath -m "${LOCALAPPDATA:-C:/Users/$USERNAME/AppData/Local}" 2>/dev/null || echo /tmp)/Temp/anl}"
: "${ANDROID_NDK:=$(cygpath -m "${LOCALAPPDATA:-C:/Users/$USERNAME/AppData/Local}" 2>/dev/null)/Android/Sdk/ndk/27.2.12479018}"
: "${MGL_PKG:=com.anland.consumer.mobilegl}"
: "${MGL_CONTAINER:=arch-kde-mgl}"
: "${MGL_DESKTOP_USER:=swung0x48}"
: "${DS_BIN:=/data/local/Droidspaces/bin/droidspaces}"
: "${DEV_TOOLS:=/data/local/tmp/anl}"
: "${DEV_SHARE:=/data/local/tmp/anland-mobilegl}"
# The container rootfs as Android root sees it (the container's /tmp is NOT visible here).
CT_ROOT=/mnt/Droidspaces/$MGL_CONTAINER
export MGL_WORKTREE ANL_DIR ANDROID_NDK MGL_PKG MGL_CONTAINER MGL_DESKTOP_USER DS_BIN DEV_TOOLS DEV_SHARE CT_ROOT
# Git Bash would rewrite /data/... arguments into C:/Program Files/Git/data/...; keep them literal.
# Consequence: pass LOCAL paths to Windows tools (adb, cmake, git) in C:/ form, never /c/.
export MSYS_NO_PATHCONV=1
adb_() { MSYS2_ARG_CONV_EXCL='*' adb "$@"; }
# C:/x/y -> /mnt/c/x/y (for WSL).
win2wsl() { local p=$1 d; d=$(printf '%s' "${p:0:1}" | tr 'A-Z' 'a-z'); printf '/mnt/%s%s' "$d" "${p:2}"; }
mkdir -p "$ANL_DIR"
@@ -1,46 +0,0 @@
#!/usr/bin/env bash
# kwin-stage.sh [build] - stage anland's KWin changes (kwin.patch, anland backend sources,
# mobilegl-startup.sh, sync-build-kwin.sh) for the in-container KWin rebuild; with "build", also run
# kwprep.sh (apply changed patch hunks / backend files to the live tree) and start sync-build-kwin.sh
# (ninja -j4 + atomic install into /opt/mobilegl/kwin, screencast plugin, startup script) in the
# background, log /root/kwin-build.log. KWin is NOT restarted: run device/run-plasma.sh afterwards.
# Poll: printf 'tail -5 /root/kwin-build.log\n' | bash ct.sh kw
#
# Two staging places, because the two container scripts read different ones:
# /root/kwsync.tgz <- kwprep.sh (installed by push-tools.sh)
# $DEV_SHARE/kwin-sync = /run/anland-mobilegl/kwin-sync <- sync-build-kwin.sh (as kwin-sync/sync-build.sh)
# All files are CR-stripped: the Windows checkout of anland has CRLF backend sources and a CRLF
# sync-build-kwin.sh (bash then fails on $'\r').
# Assembled from kwprep.sh + sync-build-kwin.sh; not exercised as one unit yet.
# Env: ANLAND_WORKTREE (anland checkout on branch legacy-mobilegl-unified, Windows form),
# CHANNEL (ct.sh channel, default kw).
set -euo pipefail
here=$(cd "$(dirname "$0")" && pwd)
. "$here/env.sh"
: "${ANLAND_WORKTREE:=$(cygpath -m "$USERPROFILE" 2>/dev/null)/AndroidStudioProjects/anland/.claude/worktrees/mgl-unified}"
K=$ANLAND_WORKTREE/producers/kde
st=$ANL_DIR/kwstage
rm -rf "$st"; mkdir -p "$st/kwsync/Arch_v5" "$st/kwsync/anland_backend_Arch_v5/src/backends/anland" "$st/kwin-sync/anland" "$st/kwin-sync/misc"
lf() { tr -d '\r' < "$1" > "$2"; }
for f in "$K"/anland_backend_Arch_v5/src/backends/anland/*; do
b=$(basename "$f"); [ "$b" = libdisplay_producer ] && continue
lf "$f" "$st/kwsync/anland_backend_Arch_v5/src/backends/anland/$b"
lf "$f" "$st/kwin-sync/anland/$b"
done
for f in kwin.patch mobilegl-startup.sh; do
lf "$K/Arch_v5/$f" "$st/kwsync/Arch_v5/$f"
lf "$K/Arch_v5/$f" "$st/kwin-sync/misc/$f"
done
lf "$K/Arch_v5/sync-build-kwin.sh" "$st/kwin-sync/sync-build.sh"
(cd "$st/kwsync" && tar --force-local -czf ../kwsync.tgz Arch_v5 anland_backend_Arch_v5)
tar --force-local -C "$st" -czf "$st/kwin-sync.tgz" kwin-sync
adb_ push "$st/kwsync.tgz" "$DEV_TOOLS/kwsync.tgz" >/dev/null
adb_ push "$st/kwin-sync.tgz" "$DEV_TOOLS/kwin-sync.tgz" >/dev/null
adb_ shell "su -c 'cp $DEV_TOOLS/kwsync.tgz $CT_ROOT/root/kwsync.tgz && tar xzf $DEV_TOOLS/kwin-sync.tgz -C $DEV_SHARE && chmod -R a+rX $DEV_SHARE/kwin-sync && rm -f $DEV_TOOLS/kwsync.tgz $DEV_TOOLS/kwin-sync.tgz && echo staged'"
if [ "${1:-}" = build ]; then
bash "$here/ct.sh" "${CHANNEL:-kw}" <<'IN'
bash /root/kwprep.sh || exit 1
nohup bash /run/anland-mobilegl/kwin-sync/sync-build.sh > /root/kwin-build.log 2>&1 < /dev/null &
echo "kwin build started (pid $!), log /root/kwin-build.log; it ends with '== ALL DONE =='"
IN
fi
@@ -1,34 +0,0 @@
// dmahash <pid> : for each dma-buf fd of <pid> at least 1 MB, print inode, size and a sampled checksum.
#include <dirent.h>
#include <fcntl.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>
int main(int argc, char** argv) {
char dir[64];
snprintf(dir, sizeof dir, "/proc/%s/fd", argv[1]);
DIR* d = opendir(dir);
if (!d) { perror("opendir"); return 1; }
struct dirent* e;
while ((e = readdir(d))) {
char p[128], l[128] = {0};
snprintf(p, sizeof p, "%s/%s", dir, e->d_name);
if (readlink(p, l, sizeof l - 1) <= 0 || strncmp(l, "/dmabuf", 7) != 0) continue;
int fd = open(p, O_RDONLY);
if (fd < 0) continue;
struct stat st; fstat(fd, &st);
if (st.st_size < (1 << 20)) { close(fd); continue; }
const uint8_t* m = mmap(NULL, st.st_size, PROT_READ, MAP_SHARED, fd, 0);
if (m == MAP_FAILED) { printf("fd %s ino %lu mmap failed\n", e->d_name, (unsigned long)st.st_ino); close(fd); continue; }
uint64_t h = 1469598103934665603ull; unsigned nz = 0;
for (off_t i = 0; i < st.st_size; i += 64) { h = (h ^ m[i]) * 1099511628211ull; nz += m[i] != 0; }
printf("fd %s ino %lu size %ld hash %016llx nz %u\n", e->d_name, (unsigned long)st.st_ino, (long)st.st_size,
(unsigned long long)h, nz);
munmap((void*)m, st.st_size); close(fd);
}
return 0;
}
@@ -1,95 +0,0 @@
/* texfmt: does a texture keep its alpha? One opaque red texel and one transparent texel per
* format, sampled across a 64x64 ES3 pbuffer cleared white with SRC_ALPHA blending. Expect the
* left half red and the right half WHITE; a black right half means the alpha was lost. */
#include <EGL/egl.h>
#include <GLES3/gl3.h>
#include <GLES2/gl2ext.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define P(T, n) T n = (T)eglGetProcAddress(#n)
static const char* vs = "#version 300 es\nlayout(location=0) in vec2 p; out vec2 uv; void main(){uv=p*0.5+0.5; gl_Position=vec4(p,0,1);}";
static const char* fs = "#version 300 es\nprecision mediump float; uniform sampler2D t; uniform int mode; in vec2 uv; out vec4 o;"
"void main(){vec4 c=texture(t,uv); o = mode==1 ? vec4(1.0,0.0,0.0,c.a) : (mode==2 ? vec4(c.r,0.0,0.0,c.r) : c);}";
int main(void) {
EGLDisplay d = eglGetDisplay(EGL_DEFAULT_DISPLAY); eglInitialize(d, 0, 0); eglBindAPI(EGL_OPENGL_ES_API);
EGLint ca[] = {EGL_SURFACE_TYPE, EGL_PBUFFER_BIT, EGL_RENDERABLE_TYPE, EGL_OPENGL_ES3_BIT, EGL_RED_SIZE, 8, EGL_GREEN_SIZE, 8, EGL_BLUE_SIZE, 8, EGL_ALPHA_SIZE, 8, EGL_NONE};
EGLConfig c; EGLint n; eglChooseConfig(d, ca, &c, 1, &n);
EGLint xa[] = {EGL_CONTEXT_CLIENT_VERSION, 3, EGL_NONE};
EGLContext x = eglCreateContext(d, c, EGL_NO_CONTEXT, xa);
EGLint pa[] = {EGL_WIDTH, 64, EGL_HEIGHT, 64, EGL_NONE};
EGLSurface s = eglCreatePbufferSurface(d, c, pa); eglMakeCurrent(d, s, s, x);
P(PFNGLCREATESHADERPROC, glCreateShader); P(PFNGLSHADERSOURCEPROC, glShaderSource); P(PFNGLCOMPILESHADERPROC, glCompileShader);
P(PFNGLCREATEPROGRAMPROC, glCreateProgram); P(PFNGLATTACHSHADERPROC, glAttachShader); P(PFNGLLINKPROGRAMPROC, glLinkProgram);
P(PFNGLUSEPROGRAMPROC, glUseProgram); P(PFNGLGETUNIFORMLOCATIONPROC, glGetUniformLocation); P(PFNGLUNIFORM1IPROC, glUniform1i);
P(PFNGLGENBUFFERSPROC, glGenBuffers); P(PFNGLBINDBUFFERPROC, glBindBuffer); P(PFNGLBUFFERDATAPROC, glBufferData);
P(PFNGLVERTEXATTRIBPOINTERPROC, glVertexAttribPointer); P(PFNGLENABLEVERTEXATTRIBARRAYPROC, glEnableVertexAttribArray);
P(PFNGLDRAWARRAYSPROC, glDrawArrays); P(PFNGLCLEARCOLORPROC, glClearColor); P(PFNGLCLEARPROC, glClear);
P(PFNGLREADPIXELSPROC, glReadPixels); P(PFNGLVIEWPORTPROC, glViewport); P(PFNGLGENTEXTURESPROC, glGenTextures);
P(PFNGLBINDTEXTUREPROC, glBindTexture); P(PFNGLTEXIMAGE2DPROC, glTexImage2D); P(PFNGLTEXPARAMETERIPROC, glTexParameteri);
P(PFNGLENABLEPROC, glEnable); P(PFNGLBLENDFUNCPROC, glBlendFunc); P(PFNGLGETERRORPROC, glGetError);
P(PFNGLTEXSTORAGE2DPROC, glTexStorage2D); P(PFNGLTEXSUBIMAGE2DPROC, glTexSubImage2D); P(PFNGLGETSTRINGPROC, glGetString);
printf("GL_VERSION %s\n", glGetString(GL_VERSION));
printf("BGRA ext: %s\n", strstr((const char*)glGetString(GL_EXTENSIONS), "GL_EXT_texture_format_BGRA8888") ? "yes" : "no");
GLuint v = glCreateShader(GL_VERTEX_SHADER), f = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(v, 1, &vs, 0); glCompileShader(v); glShaderSource(f, 1, &fs, 0); glCompileShader(f);
GLuint pr = glCreateProgram(); glAttachShader(pr, v); glAttachShader(pr, f); glLinkProgram(pr); glUseProgram(pr);
float q[] = {-1,-1, 1,-1, -1,1, 1,1};
GLuint vbo; glGenBuffers(1, &vbo); glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof q, q, GL_STATIC_DRAW); glVertexAttribPointer(0, 2, GL_FLOAT, 0, 0, 0); glEnableVertexAttribArray(0);
GLint lm = glGetUniformLocation(pr, "mode");
glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
struct { const char* name; GLint ifmt; GLenum fmt; int bpp; int mode; int storage; GLenum sized; unsigned char px[8]; } cases[] = {
{"RGBA/TexImage", GL_RGBA, GL_RGBA, 4, 0, 0, 0, {255,0,0,255, 0,0,0,0}},
{"BGRA_EXT/TexImage", GL_BGRA_EXT, GL_BGRA_EXT, 4, 0, 0, 0, {0,0,255,255, 0,0,0,0}},
{"BGRA8_EXT/TexStorage+Sub", 0, GL_BGRA_EXT, 4, 0, 1, GL_BGRA8_EXT, {0,0,255,255, 0,0,0,0}},
{"RGBA8/TexStorage+Sub", 0, GL_RGBA, 4, 0, 1, GL_RGBA8, {255,0,0,255, 0,0,0,0}},
{"ALPHA", GL_ALPHA, GL_ALPHA, 1, 1, 0, 0, {255, 0}},
{"LUMINANCE_ALPHA", GL_LUMINANCE_ALPHA, GL_LUMINANCE_ALPHA, 2, 1, 0, 0, {255,255, 0,0}},
{"R8/TexStorage+Sub", 0, GL_RED, 1, 2, 1, GL_R8, {255, 0}},
};
for (unsigned i = 0; i < sizeof cases / sizeof cases[0]; ++i) {
GLuint t; glGenTextures(1, &t); glBindTexture(GL_TEXTURE_2D, t);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
while (glGetError()) {}
if (cases[i].storage) {
glTexStorage2D(GL_TEXTURE_2D, 1, cases[i].sized, 2, 1);
glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 2, 1, cases[i].fmt, GL_UNSIGNED_BYTE, cases[i].px);
} else {
glTexImage2D(GL_TEXTURE_2D, 0, cases[i].ifmt, 2, 1, 0, cases[i].fmt, GL_UNSIGNED_BYTE, cases[i].px);
}
GLenum err = glGetError();
glUniform1i(lm, cases[i].mode);
glViewport(0, 0, 64, 64); glClearColor(1, 1, 1, 1); glClear(GL_COLOR_BUFFER_BIT);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
unsigned char l[4], r[4];
glReadPixels(16, 32, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, l); glReadPixels(48, 32, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, r);
const int ok = l[0] > 200 && l[1] < 60 && l[2] < 60 && r[0] > 200 && r[1] > 200 && r[2] > 200;
printf("%-26s err=0x%04x left=%3d,%3d,%3d right=%3d,%3d,%3d %s\n", cases[i].name, err, l[0], l[1], l[2], r[0], r[1], r[2], ok ? "ok" : "BAD");
}
/* ANGLE's emulation of ALPHA8 / LUMINANCE_ALPHA8 on a desktop-GL driver: R8 / RG8 + swizzle. */
P(PFNGLTEXPARAMETERIPROC, glTexParameteri2);
struct { const char* name; GLenum sized, fmt; int bpp; GLint sw[4]; unsigned char px[4]; unsigned char wantL[3], wantR[3]; } sz[] = {
{"R8 swizzled as ALPHA8", GL_R8, GL_RED, 1, {GL_ZERO, GL_ZERO, GL_ZERO, GL_RED}, {255, 0}, {0,0,0}, {255,255,255}},
{"RG8 swizzled as LUM_ALPHA", GL_RG8, GL_RG, 2, {GL_RED, GL_RED, GL_RED, GL_GREEN}, {255,255, 0,0}, {255,255,255}, {255,255,255}},
{"RG8 as LUM_ALPHA (lum 0)", GL_RG8, GL_RG, 2, {GL_RED, GL_RED, GL_RED, GL_GREEN}, {0,255, 0,0}, {0,0,0}, {255,255,255}},
};
glUniform1i(lm, 0);
for (unsigned i = 0; i < sizeof sz / sizeof sz[0]; ++i) {
GLuint t; glGenTextures(1, &t); glBindTexture(GL_TEXTURE_2D, t);
glTexParameteri2(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri2(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexStorage2D(GL_TEXTURE_2D, 1, sz[i].sized, 2, 1);
glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 2, 1, sz[i].fmt, GL_UNSIGNED_BYTE, sz[i].px);
glTexParameteri2(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_R, sz[i].sw[0]); glTexParameteri2(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_G, sz[i].sw[1]);
glTexParameteri2(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_B, sz[i].sw[2]); glTexParameteri2(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_A, sz[i].sw[3]);
GLenum err = glGetError();
glClearColor(1, 1, 1, 1); glClear(GL_COLOR_BUFFER_BIT); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
unsigned char l[4], r[4];
glReadPixels(16, 32, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, l); glReadPixels(48, 32, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, r);
int ok = 1;
for (int k = 0; k < 3; ++k) ok = ok && abs(l[k] - sz[i].wantL[k]) < 40 && abs(r[k] - sz[i].wantR[k]) < 40;
printf("%-26s err=0x%04x left=%3d,%3d,%3d right=%3d,%3d,%3d %s\n", sz[i].name, err, l[0], l[1], l[2], r[0], r[1], r[2], ok ? "ok" : "BAD");
}
return 0;
}
@@ -1,22 +0,0 @@
#!/usr/bin/env bash
# push-tools.sh - install this skill's device- and container-side helpers on the phone.
# device/*.sh -> $DEV_TOOLS (run as root: adb shell 'su -c "sh $DEV_TOOLS/<x>.sh"')
# container/mgrun -> <container>/usr/local/bin/mgrun
# container/kwprep.sh -> <container>/root/kwprep.sh
# Needs the container running (its rootfs is mounted at $CT_ROOT only then).
# Overwrites same-named files other sessions may be using in $DEV_TOOLS; check first on a shared phone.
set -euo pipefail
here=$(cd "$(dirname "$0")" && pwd)
. "$here/env.sh"
adb_ shell "mkdir -p $DEV_TOOLS"
for f in "$here"/device/*.sh; do
tr -d '\r' < "$f" > "$ANL_DIR/push.tmp"
adb_ push "$ANL_DIR/push.tmp" "$DEV_TOOLS/$(basename "$f")" >/dev/null
echo "pushed $DEV_TOOLS/$(basename "$f")"
done
for f in mgrun kwprep.sh; do
tr -d '\r' < "$here/container/$f" > "$ANL_DIR/push.tmp"
adb_ push "$ANL_DIR/push.tmp" "$DEV_TOOLS/$f" >/dev/null
done
rm -f "$ANL_DIR/push.tmp"
adb_ shell "su -c 'cp $DEV_TOOLS/mgrun $CT_ROOT/usr/local/bin/mgrun && chmod 755 $CT_ROOT/usr/local/bin/mgrun && cp $DEV_TOOLS/kwprep.sh $CT_ROOT/root/kwprep.sh && echo installed mgrun kwprep.sh'"
@@ -1,29 +0,0 @@
#!/usr/bin/env bash
# rec.sh <name> - record 3 s of the screen while opening Kickoff, extract frames inside the container
# with ffmpeg, pull them to $ANL_DIR/af_<name>/ and build a 3x4 contact sheet $ANL_DIR/grid_<name>.png
# (needs Python + Pillow on Windows). Use it to catch flicker/black frames a single screenshot misses.
# Env: TAP="x y" Kickoff button position (default "69 1349" = bottom-left on the 2560x1600 tablet;
# device specific). Note: anland grabs the touchscreen (EVIOCGRAB); if `input tap` does nothing, use
# `input mouse tap x y`. Env CHANNEL (default rec).
set -euo pipefail
here=$(cd "$(dirname "$0")" && pwd)
. "$here/env.sh"
N=${1:?usage: rec.sh <name>}; TAP=${TAP:-69 1349}
adb_ shell "su -c 'input keyevent 111; sleep 1.5; (screenrecord --time-limit 3 --bit-rate 20000000 $DEV_SHARE/$N.mp4 &); sleep 0.7; input tap $TAP; sleep 3; cp $DEV_SHARE/$N.mp4 $CT_ROOT/root/$N.mp4'"
bash "$here/ct.sh" "${CHANNEL:-rec}" <<IN
rm -rf /root/af_$N; mkdir -p /root/af_$N; ffmpeg -loglevel quiet -i /root/$N.mp4 -vf scale=1000:-1 -fps_mode passthrough /root/af_$N/f%03d.png; ls /root/af_$N | wc -l
IN
adb_ shell "su -c 'rm -rf $DEV_SHARE/af_$N; cp -r $CT_ROOT/root/af_$N $DEV_SHARE/ && chmod -R 777 $DEV_SHARE/af_$N'"
rm -rf "$ANL_DIR/af_$N"; adb_ pull "$DEV_SHARE/af_$N" "$ANL_DIR/" >/dev/null
python - "$ANL_DIR/af_$N" "$ANL_DIR/grid_$N.png" <<'P'
import sys, os
from PIL import Image
d, out = sys.argv[1], sys.argv[2]
fs = sorted(os.listdir(d)); n = len(fs)
pick = [fs[min(n-1, int(i * n / 12))] for i in range(12)]
ims = [Image.open(os.path.join(d, f)) for f in pick]
w, h = ims[0].size; tw, th = w // 2, h // 2
g = Image.new('RGB', (tw * 3, th * 4))
for i, im in enumerate(ims): g.paste(im.resize((tw, th)), ((i % 3) * tw, (i // 3) * th))
g.save(out); print(n, pick)
P
@@ -1,15 +0,0 @@
#!/usr/bin/env bash
# shot.sh <name> [count] [interval-s] - take <count> (default 2) phone screenshots <interval> s apart
# (default 1), pull them to $ANL_DIR/<name>-<i>.png and print their md5. Identical hashes while an
# animated client (glmark2, a video) runs mean the frames are NOT reaching the screen.
set -euo pipefail
. "$(dirname "$0")/env.sh"
name=${1:?usage: shot.sh <name> [count] [interval]}; n=${2:-2}; dt=${3:-1}
cmd=""; i=1
while [ "$i" -le "$n" ]; do cmd="$cmd screencap -p $DEV_SHARE/$name-$i.png; sleep $dt;"; i=$((i+1)); done
adb_ shell "su -c '$cmd'"
i=1
while [ "$i" -le "$n" ]; do
adb_ pull "$DEV_SHARE/$name-$i.png" "$ANL_DIR/$name-$i.png" >/dev/null
md5sum "$ANL_DIR/$name-$i.png"; i=$((i+1))
done
@@ -1,19 +0,0 @@
#!/usr/bin/env bash
# sync-src.sh - FALLBACK path only (the WSL cross build, xbuild.sh, replaced it). Pushes the files the
# worktree changed since the container's source stamp into the container's MobileGL source tree
# (/root/mobilegl-unified-src), keeping mtimes so the in-container ninja build stays incremental;
# then build/install inside the container with anland's anland-build-client.sh
# (producers/kde/Arch_v5/mobilegl-tools/, gcc, -j4, slow on the phone).
# A full re-sync of the tree is anland's anland-sync-source.sh (MOBILEGL_REPO=<worktree>).
set -euo pipefail
. "$(dirname "$0")/env.sh"
SRC=$CT_ROOT/root/mobilegl-unified-src
STAMP=$(adb_ shell "su -c 'cat $SRC/.anland-build-stamp'" | tr -d '\r\n')
cd "$MGL_WORKTREE"
FILES=$( (git diff --name-only --diff-filter=d "$STAMP"; git ls-files --others --exclude-standard) \
| grep -v -E '^(3rdparty/|build-android|\.anland-build-stamp|\.claude/)' | sort -u)
echo "$(echo "$FILES" | wc -l) files since $STAMP"
tar --force-local -czf "$ANL_DIR/src-delta.tgz" $FILES
adb_ push "$ANL_DIR/src-delta.tgz" /data/local/tmp/src-delta.tgz >/dev/null
HEAD=$(git rev-parse HEAD)
adb_ shell "su -c 'tar xzf /data/local/tmp/src-delta.tgz -C $SRC && echo $HEAD > $SRC/.anland-build-stamp && echo synced'"
@@ -1,9 +0,0 @@
#!/bin/bash
# wsl-all.sh - run INSIDE WSL archlinux after wsl-test.sh configured $B: build every *Test target except
# DirectVulkan*/Benchmark* and run the unit label. NEVER run the DirectVulkan integration tests
# (they need a live device + manual intervention); never run two ctest suites at once.
B=${B:-$HOME/mgl-anl-bld}
cd $B
T=$(ninja -t targets all 2>/dev/null | grep -oE "^[A-Za-z]+Test:" | tr -d : | sort -u | grep -v -E "^(DirectVulkan|Benchmark)" | tr "\n" " ")
ninja -j14 MobileGLServer $T 2>&1 | grep -E "error:|FAILED" | head -10
ctest -L unit -j10 --timeout 300 -E "DirectVulkan" 2>&1 | tail -25
@@ -1,13 +0,0 @@
#!/bin/bash
# wsl-test.sh <targets...> - run INSIDE WSL archlinux: configure (once) and build MobileGL unit-test
# targets for the host (clang, disaggregated + in-process server ON). From Git Bash:
# MSYS2_ARG_CONV_EXCL='*' wsl -d archlinux -- bash /mnt/c/<worktree>/.claude/skills/anland-mobilegl-plasma/scripts/wsl-test.sh MultiSessionTest
# then ctest in $B (see wsl-all.sh). Env: W (worktree, WSL path; default: derived from this file),
# B (build dir, default ~/mgl-anl-bld). The Windows MSVC build of feat/disaggregated is broken; use this.
set -e
W=${W:-$(cd "$(dirname "$0")/../../../.." && pwd)}
B=${B:-$HOME/mgl-anl-bld}
if [ ! -f $B/build.ninja ]; then
cmake -S $W -B $B -G Ninja -DCMAKE_BUILD_TYPE=Release -DCMAKE_C_COMPILER=clang -DCMAKE_CXX_COMPILER=clang++ -DMOBILEGL_BUILD_TEST=ON -DMOBILEGL_BUILD_DISAGGREGATED=ON -DMOBILEGL_BUILD_DISAGGREGATED_INPROC=ON -DMOBILEGL_BUILD_STAMP=wsl
fi
cmake --build $B --target "$@" -j16
@@ -1,42 +0,0 @@
#!/usr/bin/env bash
# xbuild.sh [--reconfigure] [extra ninja targets...] - cross-build the container CLIENT: libMobileGL.so
# (glibc aarch64, glvnd EGL/GLX vendor) + mobilegl_gbm.so (GBM backend), in WSL archlinux with
# clang + lld against a sysroot exported from the container (xsysroot/refresh-sysroot.sh).
# Full build ~150 s, incremental seconds. Deploy with xdeploy.sh.
# Env: MGL_WORKTREE (source, Windows form), MGL_XBUILD_DIR (WSL build dir, default ~/mgl-xbuild-a64),
# MGL_JOBS (16), WSL_DISTRO (archlinux).
# Prereq in WSL: clang, lld, llvm (lld major MUST equal clang/llvm-libs major - lld 23 on llvm 22
# broke ld.lld), cmake, ninja; ~/sysroots/aarch64-arch.cmake + ~/sysroots/arch-kde-mgl.
set -euo pipefail
. "$(dirname "$0")/env.sh"
STAMP=$(git -C "$MGL_WORKTREE" rev-parse HEAD)
RECONF=0
if [ "${1:-}" = "--reconfigure" ]; then RECONF=1; shift; fi
EXTRA="$*"
SRC_WSL=$(win2wsl "$MGL_WORKTREE")
wsl -d "${WSL_DISTRO:-archlinux}" -- env SRC="$SRC_WSL" STAMP="$STAMP" RECONF="$RECONF" EXTRA="$EXTRA" \
OUT="${MGL_XBUILD_DIR:-}" JOBS="${MGL_JOBS:-16}" bash -s <<'IN' 2>&1 | tr -d '\0' | grep -av '^wsl:'
set -euo pipefail
OUT=${OUT:-$HOME/mgl-xbuild-a64}
TC=$HOME/sysroots/aarch64-arch.cmake
[ -f "$TC" ] || { echo "missing toolchain $TC (run xsysroot/refresh-sysroot.sh)"; exit 1; }
ld.lld --version >/dev/null || { echo "ld.lld is not runnable in WSL (lld/llvm version mismatch?)"; exit 1; }
t0=$(date +%s)
if [ "$RECONF" = 1 ] || [ ! -f "$OUT/build.ninja" ]; then
rm -rf "$OUT/CMakeCache.txt" "$OUT/CMakeFiles"
cmake -S "$SRC" -B "$OUT" -G Ninja --toolchain "$TC" -DMOBILEGL_BUILD_STAMP="$STAMP" \
-DCMAKE_BUILD_TYPE=Release -DMOBILEGL_BUILD_TEST=OFF -DMOBILEGL_BUILD_BENCHMARK=OFF \
-DMOBILEGL_BUILD_DISAGGREGATED=ON -DMOBILEGL_ENABLE_LTO=OFF
elif ! grep -qx "MOBILEGL_BUILD_STAMP:STRING=$STAMP" "$OUT/CMakeCache.txt"; then
cmake -S "$SRC" -B "$OUT" -DMOBILEGL_BUILD_STAMP="$STAMP" >/dev/null
fi
t1=$(date +%s)
cmake --build "$OUT" --target MobileGL mobilegl_gbm $EXTRA -j"$JOBS"
t2=$(date +%s)
echo "stamp: $STAMP"
echo "configure: $((t1-t0))s build: $((t2-t1))s"
for f in "$OUT/libMobileGL.so" "$OUT/MobileGL/MG_Gbm/mobilegl_gbm.so"; do
ls -la "$f"; echo " windows: $(wslpath -w "$f")"
done
IN
exit "${PIPESTATUS[0]}"
@@ -1,65 +0,0 @@
#!/usr/bin/env bash
# xdeploy.sh - install the WSL cross-built libMobileGL.so + mobilegl_gbm.so into the container, exactly
# like anland's anland-build-client.sh: copy to a NEW inode and rename into place (overwriting a mapped
# .so in place crashes every running client, KWin included), refresh the libEGL/libGL aliases, the
# glvnd GLX vendor link, the EGL vendor JSON (system-wide 10_mobilegl.json + the /opt copy), the client
# config /etc/mobilegl/client.conf and the GLX/GBM selection drop-ins. Does not restart anything: already-running clients
# keep the old inode; restart the client (or the session) to pick up the new library.
# Env: MGL_XBUILD_DIR (WSL build dir), CHANNEL (ct.sh channel, default xd), WSL_DISTRO.
set -euo pipefail
here=$(cd "$(dirname "$0")" && pwd)
. "$here/env.sh"
mkdir -p "$ANL_DIR/xdist"
# 1. Copy the build outputs out of WSL.
wsl -d "${WSL_DISTRO:-archlinux}" -- env OUT="${MGL_XBUILD_DIR:-}" D="$(win2wsl "$ANL_DIR")/xdist" bash -s <<'IN' 2>&1 | tr -d '\0' | grep -av '^wsl:'
set -e; OUT=${OUT:-$HOME/mgl-xbuild-a64}
cp -f "$OUT/libMobileGL.so" "$D/libMobileGL.so"; cp -f "$OUT/MobileGL/MG_Gbm/mobilegl_gbm.so" "$D/mobilegl_gbm.so"
sha256sum "$D/libMobileGL.so" "$D/mobilegl_gbm.so"
IN
# 2. Push to the phone and stage them in the container's /root/xdeploy (the container's /tmp and the
# phone's /data/local/tmp are different places; the rootfs is reachable at $CT_ROOT).
adb_ shell "mkdir -p $DEV_TOOLS/xdist"
adb_ push "$ANL_DIR/xdist/libMobileGL.so" "$DEV_TOOLS/xdist/libMobileGL.so"
adb_ push "$ANL_DIR/xdist/mobilegl_gbm.so" "$DEV_TOOLS/xdist/mobilegl_gbm.so"
adb_ shell "su -c 'mkdir -p $CT_ROOT/root/xdeploy && cp $DEV_TOOLS/xdist/libMobileGL.so $DEV_TOOLS/xdist/mobilegl_gbm.so $CT_ROOT/root/xdeploy/ && rm -f $DEV_TOOLS/xdist/*.so'"
# 3. Install inside the container.
bash "$here/ct.sh" "${CHANNEL:-xd}" <<'IN'
set -euo pipefail
in=/root/xdeploy
mkdir -p /opt/mobilegl/lib /opt/mobilegl/share/glvnd/egl_vendor.d
cp "$in/libMobileGL.so" /opt/mobilegl/lib/libMobileGL.so.new
mv -f /opt/mobilegl/lib/libMobileGL.so.new /opt/mobilegl/lib/libMobileGL.so
for lib in libEGL.so libEGL.so.1 libGL.so libGL.so.1; do ln -sf libMobileGL.so "/opt/mobilegl/lib/$lib"; done
ln -sf /opt/mobilegl/lib/libMobileGL.so /usr/lib/libGLX_mobilegl.so.0
vendor='{"file_format_version":"1.0.0","ICD":{"library_path":"/opt/mobilegl/lib/libMobileGL.so"}}'
# Per-process forcing (__EGL_VENDOR_LIBRARY_FILENAMES=<this file>) keeps working off the /opt copy.
printf '%s\n' "$vendor" >/opt/mobilegl/share/glvnd/egl_vendor.d/50_mobilegl.json
# System-wide vendor: 10_ sorts ahead of the system's 50_mesa.json, so stock libglvnd asks MobileGL
# first and moves on to the other vendor whenever MobileGL declines (no server reachable).
mkdir -p /usr/share/glvnd/egl_vendor.d
printf '%s\n' "$vendor" >/usr/share/glvnd/egl_vendor.d/10_mobilegl.json.new
mv -f /usr/share/glvnd/egl_vendor.d/10_mobilegl.json.new /usr/share/glvnd/egl_vendor.d/10_mobilegl.json
# Client settings every process reads when its environment does not say otherwise (the backend
# comes from /etc/mobilegl/backend, which switch.sh rewrites).
mkdir -p /etc/mobilegl
cat >/etc/mobilegl/client.conf <<'CONF'
# MobileGL client configuration, read by every process that loads libMobileGL.so.
# KEY=value lines; a MOBILEGL_* variable in a process's environment overrides the line here.
# The backend is /etc/mobilegl/backend. Written by xdeploy.sh / anland-build-client.sh.
MOBILEGL_TRANSPORT=spawn
MOBILEGL_IPC_DATA=shm
MOBILEGL_IPC_CONTROL=unix:@anland-mobilegl
CONF
# What glvnd's libGLX and libgbm cannot infer: environment.d reaches the systemd user manager (every
# Plasma service and what it launches, terminals included), profile.d reaches login shells.
mkdir -p /etc/environment.d /etc/profile.d
printf '%s\n' '__GLX_VENDOR_LIBRARY_NAME=mobilegl' 'GBM_BACKEND=mobilegl' >/etc/environment.d/10-mobilegl.conf
printf '%s\n' 'export __GLX_VENDOR_LIBRARY_NAME=mobilegl' 'export GBM_BACKEND=mobilegl' >/etc/profile.d/mobilegl.sh
mkdir -p /usr/lib/gbm
cp "$in/mobilegl_gbm.so" /usr/lib/gbm/mobilegl_gbm.so.new
mv -f /usr/lib/gbm/mobilegl_gbm.so.new /usr/lib/gbm/mobilegl_gbm.so
rm -f "$in/libMobileGL.so" "$in/mobilegl_gbm.so"
sha256sum /opt/mobilegl/lib/libMobileGL.so /usr/lib/gbm/mobilegl_gbm.so
ls /usr/share/glvnd/egl_vendor.d/ /etc/mobilegl/ /etc/environment.d/
echo DEPLOYED
IN
@@ -1,47 +0,0 @@
# Cross toolchain: WSL clang -> aarch64 Arch Linux ARM (glibc) container "arch-kde-mgl".
# Sysroot exported from the container by refresh-sysroot.sh (default $HOME/sysroots/arch-kde-mgl).
set(CMAKE_SYSTEM_NAME Linux)
set(CMAKE_SYSTEM_PROCESSOR aarch64)
set(_triple aarch64-unknown-linux-gnu)
if (DEFINED ENV{MGL_SYSROOT})
set(_sysroot "$ENV{MGL_SYSROOT}")
else()
set(_sysroot "$ENV{HOME}/sysroots/arch-kde-mgl")
endif()
# The container's GCC install dir (crtbegin/crtend, libgcc, libstdc++ via /usr/include/c++/<ver>).
file(GLOB _gcc_dirs LIST_DIRECTORIES true "${_sysroot}/usr/lib/gcc/${_triple}/*")
list(SORT _gcc_dirs COMPARE NATURAL ORDER DESCENDING)
list(GET _gcc_dirs 0 _gcc_install_dir)
set(CMAKE_SYSROOT "${_sysroot}")
set(CMAKE_C_COMPILER clang)
set(CMAKE_CXX_COMPILER clang++)
set(CMAKE_ASM_COMPILER clang)
set(CMAKE_C_COMPILER_TARGET ${_triple})
set(CMAKE_CXX_COMPILER_TARGET ${_triple})
set(CMAKE_ASM_COMPILER_TARGET ${_triple})
set(CMAKE_AR llvm-ar)
set(CMAKE_RANLIB llvm-ranlib)
set(CMAKE_NM llvm-nm)
set(CMAKE_OBJCOPY llvm-objcopy)
set(CMAKE_STRIP llvm-strip)
set(_xflags "--gcc-install-dir=${_gcc_install_dir}")
set(CMAKE_C_FLAGS_INIT "${_xflags}")
set(CMAKE_CXX_FLAGS_INIT "${_xflags}")
set(CMAKE_ASM_FLAGS_INIT "${_xflags}")
set(CMAKE_EXE_LINKER_FLAGS_INIT "-fuse-ld=lld")
set(CMAKE_SHARED_LINKER_FLAGS_INIT "-fuse-ld=lld")
set(CMAKE_MODULE_LINKER_FLAGS_INIT "-fuse-ld=lld")
set(CMAKE_LINKER_TYPE LLD)
set(CMAKE_FIND_ROOT_PATH "${_sysroot}")
set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)
set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)
set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)
set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY)
set(ENV{PKG_CONFIG_SYSROOT_DIR} "${_sysroot}")
set(ENV{PKG_CONFIG_LIBDIR} "${_sysroot}/usr/lib/pkgconfig:${_sysroot}/usr/share/pkgconfig")
set(ENV{PKG_CONFIG_PATH} "")
@@ -1,26 +0,0 @@
#!/usr/bin/env bash
# xsysroot/refresh-sysroot.sh - (re)export the cross sysroot from the container into WSL
# ~/sysroots/arch-kde-mgl and install the toolchain file as ~/sysroots/aarch64-arch.cmake.
# Read-only on the container side (it only tars headers/libs into /root and moves the tarball out).
# Run once on a new machine, and again after the container upgrades glibc/gcc/vulkan/libdrm/gbm;
# then `bash xbuild.sh --reconfigure`. Env: CHANNEL (default xr), WSL_DISTRO.
set -euo pipefail
here=$(cd "$(dirname "$0")" && pwd)
. "$here/../env.sh"
cp -f "$here/aarch64-arch.cmake" "$ANL_DIR/aarch64-arch.cmake"
bash "$here/../ct.sh" "${CHANNEL:-xr}" <<'IN'
set -e; cd /
L=$(ls -d usr/lib/*crt*.o usr/lib/lib{c,m,mvec,pthread,dl,rt,util,resolv,anl,stdc++,stdc++fs,stdc++exp,supc++,gcc_s,atomic,vulkan,drm,drm_*,gbm,z}.* usr/lib/lib{c,m}_nonshared* usr/lib/ld-linux* usr/lib/pkgconfig usr/share/pkgconfig usr/share/cmake/VulkanHeaders usr/lib/cmake/Vulkan* 2>/dev/null)
tar czf /root/xsysroot.tar.gz --exclude='usr/lib/gcc/*/*/cc1' --exclude='usr/lib/gcc/*/*/cc1plus' --exclude='usr/lib/gcc/*/*/lto1' --exclude='usr/lib/gcc/*/*/lto-wrapper' --exclude='usr/lib/gcc/*/*/collect2' --exclude='usr/lib/gcc/*/*/plugin' --exclude='usr/lib/gcc/*/*/install-tools' --exclude='usr/lib/gcc/*/*/liblto_plugin.so' lib usr/include usr/lib/gcc $L
echo SYSROOT_TAR_DONE
IN
adb_ shell "su -c 'mv $CT_ROOT/root/xsysroot.tar.gz $DEV_TOOLS/xsysroot.tar.gz && chmod 644 $DEV_TOOLS/xsysroot.tar.gz'"
adb_ pull "$DEV_TOOLS/xsysroot.tar.gz" "$ANL_DIR/xsysroot.tar.gz"
adb_ shell "su -c 'rm -f $DEV_TOOLS/xsysroot.tar.gz'"
wsl -d "${WSL_DISTRO:-archlinux}" -- env A="$(win2wsl "$ANL_DIR")" bash -s <<'IN' 2>&1 | tr -d '\0' | grep -av '^wsl:'
set -e; S=$HOME/sysroots/arch-kde-mgl; rm -rf "$S.new"; mkdir -p "$S.new"
tar xzf "$A/xsysroot.tar.gz" -C "$S.new"
rm -rf "$S"; mv "$S.new" "$S"; cp -f "$A/aarch64-arch.cmake" "$HOME/sysroots/aarch64-arch.cmake"
du -sh "$S"; ls "$S/usr/lib/gcc/aarch64-unknown-linux-gnu/"
IN
rm -f "$ANL_DIR/xsysroot.tar.gz"
+538
View File
@@ -0,0 +1,538 @@
/*
* Copyright © 2011 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
* Authors:
* Benjamin Franzke <benjaminfranzke@googlemail.com>
*/
#ifndef _GBM_H_
#define _GBM_H_
#define __GBM__ 1
#include <stddef.h>
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* \file gbm.h
* \brief Generic Buffer Manager
*/
struct gbm_device;
struct gbm_bo;
struct gbm_surface;
/**
* \mainpage The Generic Buffer Manager
*
* This module provides an abstraction that the caller can use to request a
* buffer from the underlying memory management system for the platform.
*
* This allows the creation of portable code whilst still allowing access to
* the underlying memory manager.
*/
/**
* Abstraction representing the handle to a buffer allocated by the
* manager
*/
union gbm_bo_handle {
void *ptr;
int32_t s32;
uint32_t u32;
int64_t s64;
uint64_t u64;
};
/** Format of the allocated buffer */
enum gbm_bo_format {
/** RGB with 8 bits per channel in a 32 bit value */
GBM_BO_FORMAT_XRGB8888,
/** ARGB with 8 bits per channel in a 32 bit value */
GBM_BO_FORMAT_ARGB8888
};
/**
* The FourCC format codes are taken from the drm_fourcc.h definition, and
* re-namespaced. New GBM formats must not be added, unless they are
* identical ports from drm_fourcc.
*/
#define __gbm_fourcc_code(a,b,c,d) ((uint32_t)(a) | ((uint32_t)(b) << 8) | \
((uint32_t)(c) << 16) | ((uint32_t)(d) << 24))
#define GBM_FORMAT_BIG_ENDIAN (1<<31) /* format is big endian instead of little endian */
/* color index */
#define GBM_FORMAT_C8 __gbm_fourcc_code('C', '8', ' ', ' ') /* [7:0] C */
/* 8 bpp Red */
#define GBM_FORMAT_R8 __gbm_fourcc_code('R', '8', ' ', ' ') /* [7:0] R */
/* 16 bpp Red */
#define GBM_FORMAT_R16 __gbm_fourcc_code('R', '1', '6', ' ') /* [15:0] R little endian */
/* 16 bpp RG */
#define GBM_FORMAT_GR88 __gbm_fourcc_code('G', 'R', '8', '8') /* [15:0] G:R 8:8 little endian */
/* 32 bpp RG */
#define GBM_FORMAT_RG1616 __gbm_fourcc_code('R', 'G', '3', '2') /* [31:0] R:G 16:16 little endian */
#define GBM_FORMAT_GR1616 __gbm_fourcc_code('G', 'R', '3', '2') /* [31:0] G:R 16:16 little endian */
/* 8 bpp RGB */
#define GBM_FORMAT_RGB332 __gbm_fourcc_code('R', 'G', 'B', '8') /* [7:0] R:G:B 3:3:2 */
#define GBM_FORMAT_BGR233 __gbm_fourcc_code('B', 'G', 'R', '8') /* [7:0] B:G:R 2:3:3 */
/* 16 bpp RGB */
#define GBM_FORMAT_XRGB4444 __gbm_fourcc_code('X', 'R', '1', '2') /* [15:0] x:R:G:B 4:4:4:4 little endian */
#define GBM_FORMAT_XBGR4444 __gbm_fourcc_code('X', 'B', '1', '2') /* [15:0] x:B:G:R 4:4:4:4 little endian */
#define GBM_FORMAT_RGBX4444 __gbm_fourcc_code('R', 'X', '1', '2') /* [15:0] R:G:B:x 4:4:4:4 little endian */
#define GBM_FORMAT_BGRX4444 __gbm_fourcc_code('B', 'X', '1', '2') /* [15:0] B:G:R:x 4:4:4:4 little endian */
#define GBM_FORMAT_ARGB4444 __gbm_fourcc_code('A', 'R', '1', '2') /* [15:0] A:R:G:B 4:4:4:4 little endian */
#define GBM_FORMAT_ABGR4444 __gbm_fourcc_code('A', 'B', '1', '2') /* [15:0] A:B:G:R 4:4:4:4 little endian */
#define GBM_FORMAT_RGBA4444 __gbm_fourcc_code('R', 'A', '1', '2') /* [15:0] R:G:B:A 4:4:4:4 little endian */
#define GBM_FORMAT_BGRA4444 __gbm_fourcc_code('B', 'A', '1', '2') /* [15:0] B:G:R:A 4:4:4:4 little endian */
#define GBM_FORMAT_XRGB1555 __gbm_fourcc_code('X', 'R', '1', '5') /* [15:0] x:R:G:B 1:5:5:5 little endian */
#define GBM_FORMAT_XBGR1555 __gbm_fourcc_code('X', 'B', '1', '5') /* [15:0] x:B:G:R 1:5:5:5 little endian */
#define GBM_FORMAT_RGBX5551 __gbm_fourcc_code('R', 'X', '1', '5') /* [15:0] R:G:B:x 5:5:5:1 little endian */
#define GBM_FORMAT_BGRX5551 __gbm_fourcc_code('B', 'X', '1', '5') /* [15:0] B:G:R:x 5:5:5:1 little endian */
#define GBM_FORMAT_ARGB1555 __gbm_fourcc_code('A', 'R', '1', '5') /* [15:0] A:R:G:B 1:5:5:5 little endian */
#define GBM_FORMAT_ABGR1555 __gbm_fourcc_code('A', 'B', '1', '5') /* [15:0] A:B:G:R 1:5:5:5 little endian */
#define GBM_FORMAT_RGBA5551 __gbm_fourcc_code('R', 'A', '1', '5') /* [15:0] R:G:B:A 5:5:5:1 little endian */
#define GBM_FORMAT_BGRA5551 __gbm_fourcc_code('B', 'A', '1', '5') /* [15:0] B:G:R:A 5:5:5:1 little endian */
#define GBM_FORMAT_RGB565 __gbm_fourcc_code('R', 'G', '1', '6') /* [15:0] R:G:B 5:6:5 little endian */
#define GBM_FORMAT_BGR565 __gbm_fourcc_code('B', 'G', '1', '6') /* [15:0] B:G:R 5:6:5 little endian */
/* 24 bpp RGB */
#define GBM_FORMAT_RGB888 __gbm_fourcc_code('R', 'G', '2', '4') /* [23:0] R:G:B little endian */
#define GBM_FORMAT_BGR888 __gbm_fourcc_code('B', 'G', '2', '4') /* [23:0] B:G:R little endian */
/* 32 bpp RGB */
#define GBM_FORMAT_XRGB8888 __gbm_fourcc_code('X', 'R', '2', '4') /* [31:0] x:R:G:B 8:8:8:8 little endian */
#define GBM_FORMAT_XBGR8888 __gbm_fourcc_code('X', 'B', '2', '4') /* [31:0] x:B:G:R 8:8:8:8 little endian */
#define GBM_FORMAT_RGBX8888 __gbm_fourcc_code('R', 'X', '2', '4') /* [31:0] R:G:B:x 8:8:8:8 little endian */
#define GBM_FORMAT_BGRX8888 __gbm_fourcc_code('B', 'X', '2', '4') /* [31:0] B:G:R:x 8:8:8:8 little endian */
#define GBM_FORMAT_ARGB8888 __gbm_fourcc_code('A', 'R', '2', '4') /* [31:0] A:R:G:B 8:8:8:8 little endian */
#define GBM_FORMAT_ABGR8888 __gbm_fourcc_code('A', 'B', '2', '4') /* [31:0] A:B:G:R 8:8:8:8 little endian */
#define GBM_FORMAT_RGBA8888 __gbm_fourcc_code('R', 'A', '2', '4') /* [31:0] R:G:B:A 8:8:8:8 little endian */
#define GBM_FORMAT_BGRA8888 __gbm_fourcc_code('B', 'A', '2', '4') /* [31:0] B:G:R:A 8:8:8:8 little endian */
#define GBM_FORMAT_XRGB2101010 __gbm_fourcc_code('X', 'R', '3', '0') /* [31:0] x:R:G:B 2:10:10:10 little endian */
#define GBM_FORMAT_XBGR2101010 __gbm_fourcc_code('X', 'B', '3', '0') /* [31:0] x:B:G:R 2:10:10:10 little endian */
#define GBM_FORMAT_RGBX1010102 __gbm_fourcc_code('R', 'X', '3', '0') /* [31:0] R:G:B:x 10:10:10:2 little endian */
#define GBM_FORMAT_BGRX1010102 __gbm_fourcc_code('B', 'X', '3', '0') /* [31:0] B:G:R:x 10:10:10:2 little endian */
#define GBM_FORMAT_ARGB2101010 __gbm_fourcc_code('A', 'R', '3', '0') /* [31:0] A:R:G:B 2:10:10:10 little endian */
#define GBM_FORMAT_ABGR2101010 __gbm_fourcc_code('A', 'B', '3', '0') /* [31:0] A:B:G:R 2:10:10:10 little endian */
#define GBM_FORMAT_RGBA1010102 __gbm_fourcc_code('R', 'A', '3', '0') /* [31:0] R:G:B:A 10:10:10:2 little endian */
#define GBM_FORMAT_BGRA1010102 __gbm_fourcc_code('B', 'A', '3', '0') /* [31:0] B:G:R:A 10:10:10:2 little endian */
/* 64 bpp RGB */
#define GBM_FORMAT_XBGR16161616 __gbm_fourcc_code('X', 'B', '4', '8') /* [63:0] x:B:G:R 16:16:16:16 little endian */
#define GBM_FORMAT_ABGR16161616 __gbm_fourcc_code('A', 'B', '4', '8') /* [63:0] A:B:G:R 16:16:16:16 little endian */
/*
* Floating point 64bpp RGB
* IEEE 754-2008 binary16 half-precision float
* [15:0] sign:exponent:mantissa 1:5:10
*/
#define GBM_FORMAT_XBGR16161616F __gbm_fourcc_code('X', 'B', '4', 'H') /* [63:0] x:B:G:R 16:16:16:16 little endian */
#define GBM_FORMAT_ABGR16161616F __gbm_fourcc_code('A', 'B', '4', 'H') /* [63:0] A:B:G:R 16:16:16:16 little endian */
/* packed YCbCr */
#define GBM_FORMAT_YUYV __gbm_fourcc_code('Y', 'U', 'Y', 'V') /* [31:0] Cr0:Y1:Cb0:Y0 8:8:8:8 little endian */
#define GBM_FORMAT_YVYU __gbm_fourcc_code('Y', 'V', 'Y', 'U') /* [31:0] Cb0:Y1:Cr0:Y0 8:8:8:8 little endian */
#define GBM_FORMAT_UYVY __gbm_fourcc_code('U', 'Y', 'V', 'Y') /* [31:0] Y1:Cr0:Y0:Cb0 8:8:8:8 little endian */
#define GBM_FORMAT_VYUY __gbm_fourcc_code('V', 'Y', 'U', 'Y') /* [31:0] Y1:Cb0:Y0:Cr0 8:8:8:8 little endian */
#define GBM_FORMAT_AYUV __gbm_fourcc_code('A', 'Y', 'U', 'V') /* [31:0] A:Y:Cb:Cr 8:8:8:8 little endian */
/*
* 2 plane YCbCr
* index 0 = Y plane, [7:0] Y
* index 1 = Cr:Cb plane, [15:0] Cr:Cb little endian
* or
* index 1 = Cb:Cr plane, [15:0] Cb:Cr little endian
*/
#define GBM_FORMAT_NV12 __gbm_fourcc_code('N', 'V', '1', '2') /* 2x2 subsampled Cr:Cb plane */
#define GBM_FORMAT_NV21 __gbm_fourcc_code('N', 'V', '2', '1') /* 2x2 subsampled Cb:Cr plane */
#define GBM_FORMAT_NV16 __gbm_fourcc_code('N', 'V', '1', '6') /* 2x1 subsampled Cr:Cb plane */
#define GBM_FORMAT_NV61 __gbm_fourcc_code('N', 'V', '6', '1') /* 2x1 subsampled Cb:Cr plane */
/*
* 3 plane YCbCr
* index 0: Y plane, [7:0] Y
* index 1: Cb plane, [7:0] Cb
* index 2: Cr plane, [7:0] Cr
* or
* index 1: Cr plane, [7:0] Cr
* index 2: Cb plane, [7:0] Cb
*/
#define GBM_FORMAT_YUV410 __gbm_fourcc_code('Y', 'U', 'V', '9') /* 4x4 subsampled Cb (1) and Cr (2) planes */
#define GBM_FORMAT_YVU410 __gbm_fourcc_code('Y', 'V', 'U', '9') /* 4x4 subsampled Cr (1) and Cb (2) planes */
#define GBM_FORMAT_YUV411 __gbm_fourcc_code('Y', 'U', '1', '1') /* 4x1 subsampled Cb (1) and Cr (2) planes */
#define GBM_FORMAT_YVU411 __gbm_fourcc_code('Y', 'V', '1', '1') /* 4x1 subsampled Cr (1) and Cb (2) planes */
#define GBM_FORMAT_YUV420 __gbm_fourcc_code('Y', 'U', '1', '2') /* 2x2 subsampled Cb (1) and Cr (2) planes */
#define GBM_FORMAT_YVU420 __gbm_fourcc_code('Y', 'V', '1', '2') /* 2x2 subsampled Cr (1) and Cb (2) planes */
#define GBM_FORMAT_YUV422 __gbm_fourcc_code('Y', 'U', '1', '6') /* 2x1 subsampled Cb (1) and Cr (2) planes */
#define GBM_FORMAT_YVU422 __gbm_fourcc_code('Y', 'V', '1', '6') /* 2x1 subsampled Cr (1) and Cb (2) planes */
#define GBM_FORMAT_YUV444 __gbm_fourcc_code('Y', 'U', '2', '4') /* non-subsampled Cb (1) and Cr (2) planes */
#define GBM_FORMAT_YVU444 __gbm_fourcc_code('Y', 'V', '2', '4') /* non-subsampled Cr (1) and Cb (2) planes */
struct gbm_format_name_desc {
char name[5];
};
/**
* Flags to indicate the intended use for the buffer - these are passed into
* gbm_bo_create(). The caller must set the union of all the flags that are
* appropriate
*
* \sa Use gbm_device_is_format_supported() to check if the combination of format
* and use flags are supported
*/
enum gbm_bo_flags {
/**
* Buffer is going to be presented to the screen using an API such as KMS
*/
GBM_BO_USE_SCANOUT = (1 << 0),
/**
* Buffer is going to be used as cursor
*/
GBM_BO_USE_CURSOR = (1 << 1),
/**
* Deprecated
*/
GBM_BO_USE_CURSOR_64X64 = GBM_BO_USE_CURSOR,
/**
* Buffer is to be used for rendering - for example it is going to be used
* as the storage for a color buffer
*/
GBM_BO_USE_RENDERING = (1 << 2),
/**
* Buffer can be used for gbm_bo_write. This is guaranteed to work
* with GBM_BO_USE_CURSOR, but may not work for other combinations.
*/
GBM_BO_USE_WRITE = (1 << 3),
/**
* Buffer is linear, i.e. not tiled.
*/
GBM_BO_USE_LINEAR = (1 << 4),
/**
* Buffer is protected, i.e. encrypted and not readable by CPU or any
* other non-secure / non-trusted components nor by non-trusted OpenGL,
* OpenCL, and Vulkan applications.
*/
GBM_BO_USE_PROTECTED = (1 << 5),
/**
* The buffer will be used for front buffer rendering. On some
* platforms this may (for example) disable framebuffer compression
* to avoid problems with compression flags data being out of sync
* with pixel data.
*/
GBM_BO_USE_FRONT_RENDERING = (1 << 6),
/**
* Allow the driver to select fixed-rate compression parameters.
*/
GBM_BO_FIXED_COMPRESSION_DEFAULT = (1 << 7),
/**
* Fixed-rate compression: at least 1bpc, less than 2bpc
*/
GBM_BO_FIXED_COMPRESSION_1BPC = (2 << 7),
/**
* Fixed-rate compression: at least 2bpc, less than 3bpc
*/
GBM_BO_FIXED_COMPRESSION_2BPC = (3 << 7),
/**
* Fixed-rate compression: at least 3bpc, less than 4bpc
*/
GBM_BO_FIXED_COMPRESSION_3BPC = (4 << 7),
/**
* Fixed-rate compression: at least 4bpc, less than 5bpc
*/
GBM_BO_FIXED_COMPRESSION_4BPC = (5 << 7),
/**
* Fixed-rate compression: at least 5bpc, less than 6bpc
*/
GBM_BO_FIXED_COMPRESSION_5BPC = (6 << 7),
/**
* Fixed-rate compression: at least 6bpc, less than 7bpc
*/
GBM_BO_FIXED_COMPRESSION_6BPC = (7 << 7),
/**
* Fixed-rate compression: at least 7bpc, less than 8bpc
*/
GBM_BO_FIXED_COMPRESSION_7BPC = (8 << 7),
/**
* Fixed-rate compression: at least 8bpc, less than 9bpc
*/
GBM_BO_FIXED_COMPRESSION_8BPC = (9 << 7),
/**
* Fixed-rate compression: at least 9bpc, less than 10bpc
*/
GBM_BO_FIXED_COMPRESSION_9BPC = (10 << 7),
/**
* Fixed-rate compression: at least 10bpc, less than 11bpc
*/
GBM_BO_FIXED_COMPRESSION_10BPC = (11 << 7),
/**
* Fixed-rate compression: at least 11bpc, less than 12bpc
*/
GBM_BO_FIXED_COMPRESSION_11BPC = (12 << 7),
/**
* Fixed-rate compression: at least 12bpc, no maximum rate
*/
GBM_BO_FIXED_COMPRESSION_12BPC = (13 << 7),
/* next available value is (1 << 11) */
};
#define GBM_BO_FIXED_COMPRESSION_MASK (((1 << 11) - 1) & ~((1 << 7) - 1))
int
gbm_device_get_fd(struct gbm_device *gbm);
const char *
gbm_device_get_backend_name(struct gbm_device *gbm);
int
gbm_device_is_format_supported(struct gbm_device *gbm,
uint32_t format, uint32_t flags);
int
gbm_device_get_format_modifier_plane_count(struct gbm_device *gbm,
uint32_t format,
uint64_t modifier);
void
gbm_device_destroy(struct gbm_device *gbm);
struct gbm_device *
gbm_create_device(int fd);
struct gbm_bo *
gbm_bo_create(struct gbm_device *gbm,
uint32_t width, uint32_t height,
uint32_t format, uint32_t flags);
struct gbm_bo *
gbm_bo_create_with_modifiers(struct gbm_device *gbm,
uint32_t width, uint32_t height,
uint32_t format,
const uint64_t *modifiers,
const unsigned int count);
struct gbm_bo *
gbm_bo_create_with_modifiers2(struct gbm_device *gbm,
uint32_t width, uint32_t height,
uint32_t format,
const uint64_t *modifiers,
const unsigned int count,
uint32_t flags);
#define GBM_BO_IMPORT_WL_BUFFER 0x5501
#define GBM_BO_IMPORT_EGL_IMAGE 0x5502
#define GBM_BO_IMPORT_FD 0x5503
#define GBM_BO_IMPORT_FD_MODIFIER 0x5504
struct gbm_import_fd_data {
int fd;
uint32_t width;
uint32_t height;
uint32_t stride;
uint32_t format;
};
#define GBM_MAX_PLANES 4
struct gbm_import_fd_modifier_data {
uint32_t width;
uint32_t height;
uint32_t format;
uint32_t num_fds;
int fds[GBM_MAX_PLANES];
int strides[GBM_MAX_PLANES];
int offsets[GBM_MAX_PLANES];
uint64_t modifier;
};
struct gbm_bo *
gbm_bo_import(struct gbm_device *gbm, uint32_t type,
void *buffer, uint32_t flags);
/**
* Flags to indicate the type of mapping for the buffer - these are
* passed into gbm_bo_map(). The caller must set the union of all the
* flags that are appropriate.
*
* These flags are independent of the GBM_BO_USE_* creation flags. However,
* mapping the buffer may require copying to/from a staging buffer.
*
* See also: pipe_map_flags
*/
enum gbm_bo_transfer_flags {
/**
* Buffer contents read back (or accessed directly) at transfer
* create time.
*/
GBM_BO_TRANSFER_READ = (1 << 0),
/**
* Buffer contents will be written back at unmap time
* (or modified as a result of being accessed directly).
*/
GBM_BO_TRANSFER_WRITE = (1 << 1),
/**
* Read/modify/write
*/
GBM_BO_TRANSFER_READ_WRITE = (GBM_BO_TRANSFER_READ | GBM_BO_TRANSFER_WRITE),
};
void *
gbm_bo_map(struct gbm_bo *bo,
uint32_t x, uint32_t y, uint32_t width, uint32_t height,
uint32_t flags, uint32_t *stride, void **map_data);
void
gbm_bo_unmap(struct gbm_bo *bo, void *map_data);
uint32_t
gbm_bo_get_width(struct gbm_bo *bo);
uint32_t
gbm_bo_get_height(struct gbm_bo *bo);
uint32_t
gbm_bo_get_stride(struct gbm_bo *bo);
uint32_t
gbm_bo_get_stride_for_plane(struct gbm_bo *bo, int plane);
uint32_t
gbm_bo_get_format(struct gbm_bo *bo);
uint32_t
gbm_bo_get_bpp(struct gbm_bo *bo);
uint32_t
gbm_bo_get_offset(struct gbm_bo *bo, int plane);
struct gbm_device *
gbm_bo_get_device(struct gbm_bo *bo);
union gbm_bo_handle
gbm_bo_get_handle(struct gbm_bo *bo);
int
gbm_bo_get_fd(struct gbm_bo *bo);
uint64_t
gbm_bo_get_modifier(struct gbm_bo *bo);
int
gbm_bo_get_plane_count(struct gbm_bo *bo);
union gbm_bo_handle
gbm_bo_get_handle_for_plane(struct gbm_bo *bo, int plane);
int
gbm_bo_get_fd_for_plane(struct gbm_bo *bo, int plane);
int
gbm_bo_write(struct gbm_bo *bo, const void *buf, size_t count);
void
gbm_bo_set_user_data(struct gbm_bo *bo, void *data,
void (*destroy_user_data)(struct gbm_bo *, void *));
void *
gbm_bo_get_user_data(struct gbm_bo *bo);
void
gbm_bo_destroy(struct gbm_bo *bo);
struct gbm_surface *
gbm_surface_create(struct gbm_device *gbm,
uint32_t width, uint32_t height,
uint32_t format, uint32_t flags);
struct gbm_surface *
gbm_surface_create_with_modifiers(struct gbm_device *gbm,
uint32_t width, uint32_t height,
uint32_t format,
const uint64_t *modifiers,
const unsigned int count);
struct gbm_surface *
gbm_surface_create_with_modifiers2(struct gbm_device *gbm,
uint32_t width, uint32_t height,
uint32_t format,
const uint64_t *modifiers,
const unsigned int count,
uint32_t flags);
struct gbm_bo *
gbm_surface_lock_front_buffer(struct gbm_surface *surface);
void
gbm_surface_release_buffer(struct gbm_surface *surface, struct gbm_bo *bo);
int
gbm_surface_has_free_buffers(struct gbm_surface *surface);
void
gbm_surface_destroy(struct gbm_surface *surface);
char *
gbm_format_get_name(uint32_t gbm_format, struct gbm_format_name_desc *desc);
#ifdef __cplusplus
}
#endif
#endif
+86 -25
View File
@@ -399,7 +399,6 @@ set(SOURCE_FILES
MobileGL/MG_Util/Texture/TextureFormatProcessor.cpp
MobileGL/MG_Impl/GLXImpl/Exporting/Definitions.cpp
MobileGL/MG_Impl/GLXImpl/Exporting/GlvndVendor.cpp
MobileGL/MG_Impl/GLXImpl/GLXImpl.cpp
MobileGL/MG_Impl/GLXImpl/LookUp/LookUp.cpp
@@ -438,15 +437,18 @@ set(SOURCE_FILES
MobileGL/MG_Backend/Init.cpp
MobileGL/MG_Backend/BackendObject.cpp
MobileGL/MG_Backend/HostFrameBridge.cpp
MobileGL/MG_Backend/GbmFrameChannel.cpp
MobileGL/MG_Backend/DirectGLES/DirectGLES.cpp
MobileGL/MG_Backend/DirectGLES/BackendObject_DirectGLES.cpp
MobileGL/MG_Backend/DirectGLES/Utils.cpp
MobileGL/MG_Backend/DirectGLES/Managers.cpp
MobileGL/MG_Backend/DirectGLES/HostFrameTarget.cpp
MobileGL/MG_Backend/DirectGLES/MultiDraw.cpp
MobileGL/MG_Backend/DirectVulkan/DirectVulkan.cpp
MobileGL/MG_Backend/DirectVulkan/BackendObject_DirectVulkan.cpp
MobileGL/MG_Backend/DirectVulkan/MagmaSession.cpp
MobileGL/MG_Backend/DirectVulkan/VmaImpl.cpp
MobileGL/MG_Backend/DirectVulkan/Renderer/VulkanRenderer.cpp
MobileGL/MG_Backend/DirectVulkan/Renderer/SwapchainObject.cpp
@@ -466,7 +468,6 @@ set(SOURCE_FILES
MobileGL/MG_Backend/DirectVulkan/Renderer/VkRenderPassManager.cpp
MobileGL/MG_State/GLState/Core.cpp
MobileGL/MG_State/GLState/ShareGroupState.cpp
MobileGL/MG_State/EGLState/Core.cpp
MobileGL/MG_State/GLState/ErrorState/Error.cpp
MobileGL/MG_State/GLState/BufferState/BufferState.cpp
@@ -646,9 +647,7 @@ if (MOBILEGL_BUILD_DISAGGREGATED)
MobileGL/MG_Remote/FatalFunnel.cpp
MobileGL/MG_Remote/Wire/PipeWireCodec.cpp
MobileGL/MG_Remote/Client/ClientSession.cpp
# Whether the configured server is there at all, asked before a display is offered so the
# system's EGL/GLX/GBM loaders can move on to another implementation when it is not.
MobileGL/MG_Remote/Client/ServerProbe.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
@@ -668,19 +667,12 @@ if (MOBILEGL_BUILD_DISAGGREGATED)
MobileGL/MG_Remote/Server/ServerSession.cpp
MobileGL/MG_Remote/Server/PipeApplier.cpp
MobileGL/MG_Remote/Server/ServerLoop.cpp
# P14 S2: the per-session runtime and the thread routing that lets one process serve
# several sessions (the real session a singleton accessor answers with on that
# session's own threads).
MobileGL/MG_Remote/Server/SessionRuntime.cpp
MobileGL/MG_Remote/Server/ServerMain.cpp
# P11 PAIR: a socket client's control and aux connections paired by the nonce each
# presents first (PairBind), not by arrival order - both unix supervisors take pairs here.
MobileGL/MG_Remote/Server/PairAcceptor.cpp
# P11 B2: T0's Offers on the aux socket, matched to their map_persistent records by seq.
MobileGL/MG_Remote/Server/AdoptInbox.cpp
# Shared images: server-allocated AHardwareBuffers exported to clients as dma-buf descriptors
# (docs/Disaggregated/notes/anland/plan-ahb-dmabuf.md).
MobileGL/MG_Remote/Server/SharedImageRegistry.cpp
MobileGL/MG_Remote/Server/ServerSpawn.cpp
# P5f fc: the value frame that replaced the control mailbox's function-pointer payload,
# and its codec against protocol.fbs's SurfaceOp/SurfaceReply (the spawn arm's seam).
@@ -690,8 +682,6 @@ if (MOBILEGL_BUILD_DISAGGREGATED)
# (the display Activity's SurfaceView on Android; nobody installs one on the host, so a
# ServerOwned request is refused by name there).
MobileGL/MG_Remote/Server/ServerDisplay.cpp
# Package-neutral C ABI for an APK that owns the server and its ANativeWindow.
MobileGL/MG_Remote/Server/EmbeddedServer.cpp
# P7 gate 5 (g5-msprobe): the Magma wire arm's two multisample depth/stencil resolve
# arms and the probe that measures the first against the second, shared by the
# renderer's bring-up and the Vulkan POST. Wire-only - the monolith records neither arm -
@@ -836,6 +826,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}
@@ -845,7 +846,7 @@ target_compile_definitions(${CMAKE_PROJECT_NAME}
if(UNIX AND NOT APPLE AND NOT ANDROID)
foreach(MOBILEGL_LOADER_ALIAS
libEGL.so libEGL.so.1 libGL.so libGL.so.1 libGLX_mobilegl.so.0)
libEGL.so libEGL.so.1)
add_custom_command(TARGET ${CMAKE_PROJECT_NAME} POST_BUILD
COMMAND ${CMAKE_COMMAND} -E create_symlink
"$<TARGET_FILE_NAME:${CMAKE_PROJECT_NAME}>"
@@ -902,6 +903,68 @@ if(NOT ANDROID)
)
endif()
# ---------------------------------------------------------------------------
# MobileGLGbm: the GBM drop-in the container's compositor loads.
#
# kwin - the Wayland compositor in the container half of the split - allocates the
# buffers it renders into and scans out through libgbm, and the dma-buf fds it gets
# back are what the Anland display producer ships to the phone. Mesa's libgbm cannot
# serve that: its buffers belong to the host GPU, and the phone would receive a copy
# through a path that was never designed to carry one. This target is the library
# that is loaded in its place, under the name a loader looks for.
#
# It is deliberately NOT part of libMobileGL.so. The compositor needs one file named
# libgbm.so that it loads instead of Mesa's, and folding this code into the GL
# library would put a second GL frontend, a second Vulkan instance and a second
# glslang in the compositor's address space to serve an API that shares none of them.
#
# The include paths below are borrowed rather than linked. Includes.h - which this
# library includes for the MobileGL types and the MGLOG macros - pulls in the GL,
# EGL, Vulkan, glslang, SPIRV-Cross and xxHash HEADERS transitively, and headers are
# all this library wants from them: linking any of those static libraries into a
# libgbm would embed a copy of each in a process that already has one.
#
# -Bsymbolic-functions, for the same reason the main target carries it: the point of
# this library is to REPLACE a libgbm that may already be loaded in the process, so
# every internal reference has to bind to this file's own definitions rather than to
# whatever else the process has under the same names.
# ---------------------------------------------------------------------------
add_library(MobileGLGbm SHARED
MobileGL/MG_Gbm/GbmDevice.cpp
# The display host's socket protocol, kept in its own translation unit so that the
# allocation paths never have to know how a frame arrives - only that one did.
MobileGL/MG_Gbm/GbmHostChannel.cpp
MobileGL/MG_Gbm/GbmApi.cpp
# MGLOG_I/W/E expand to a call to MobileGL::MG_Util::Debug::Log, and this is the
# one translation unit that defines it. It is compiled in rather than linked from
# libMobileGL.so because this library has to load into a compositor that has no
# libMobileGL in it at all - and because a libgbm with an undefined symbol is a
# library that fails on the first diagnostic rather than at a link step somebody
# could have read.
MobileGL/MG_Util/Debug/Log.cpp
)
# The vendored gbm.h first: this library implements THAT declaration set, and a
# system <gbm.h> from another Mesa version on the include path ahead of it would
# change the ABI under the implementations in GbmApi.cpp.
target_include_directories(MobileGLGbm PRIVATE
${CMAKE_SOURCE_DIR}/3rdparty/gbm/include
${MOBILEGL_INCLUDE_DIR}
${CMAKE_SOURCE_DIR}/3rdparty/glslang
${CMAKE_SOURCE_DIR}/3rdparty/SPIRV-Cross
${CMAKE_SOURCE_DIR}/3rdparty/xxHash
${CMAKE_SOURCE_DIR}/3rdparty/Vulkan-Headers/include
)
set_target_properties(MobileGLGbm PROPERTIES
OUTPUT_NAME gbm
POSITION_INDEPENDENT_CODE ON
)
if (UNIX AND NOT APPLE)
target_link_options(MobileGLGbm PRIVATE "LINKER:-Bsymbolic-functions")
endif()
if (TRACY_ENABLE)
target_link_libraries(${CMAKE_PROJECT_NAME} PUBLIC Tracy::TracyClient)
target_link_libraries(${CMAKE_PROJECT_NAME}_s PUBLIC Tracy::TracyClient)
@@ -922,15 +985,6 @@ if (UNIX AND NOT APPLE)
target_link_options(${CMAKE_PROJECT_NAME} PRIVATE "LINKER:-Bsymbolic-functions")
endif()
# ---- Shared images outside GL: the C ABI and the GBM backend (Linux client, split builds) ----
# docs/Disaggregated/notes/anland/plan-ahb-dmabuf.md. libMobileGL.so exports the shared-image C ABI
# (MG_Impl/SharedImageApi.h); mobilegl_gbm.so (MG_Gbm/) is a separate GBM loader module that reaches
# it through dlsym. Self-contained: nothing outside this block refers to either.
if (MOBILEGL_BUILD_DISAGGREGATED AND UNIX AND NOT APPLE AND NOT ANDROID)
target_sources(${CMAKE_PROJECT_NAME} PRIVATE MobileGL/MG_Impl/SharedImageApi.cpp)
add_subdirectory(MobileGL/MG_Gbm)
endif()
if (ANDROID)
target_link_libraries(${CMAKE_PROJECT_NAME} PUBLIC
android
@@ -1199,3 +1253,10 @@ if (ANDROID AND MOBILEGL_BUILD_EXTMEM_PROBE)
endif()
endif()
endif()
# The GBM library carries the tree's logger, which reaches Android's own log. The main target gets
# these libraries in its own Android block; a library built from the same sources needs them for the
# same reason, and without them it is the LINK that fails rather than anything in the code.
if (ANDROID)
target_link_libraries(MobileGLGbm PRIVATE log android)
endif()
+13 -4
View File
@@ -14,7 +14,7 @@ namespace MobileGL::MG_Config {
inline const String ProjectName = "MobileGL";
inline const String CoreName = "MobileGL Core";
inline const String CoreVendor = "MobileGL-Dev (BZLZHH, Swung0x48, Tungsten)";
inline const Version CoreVersion = {26, 10, 0, "-dev", VersionType::Development};
inline const Version CoreVersion = {26, 9, 0, "-dev", VersionType::Development};
inline const VersionStringFormatAttrib DefaultVersionStringFormatAttrib = {2, 2, 0, true, true};
inline const Uint64 CacheVersion = 0;
@@ -423,9 +423,8 @@ namespace MobileGL::MG_Config {
Uint32 PipeIndexMirrorMb = 64;
// MOBILEGL_PIPE_STATS_PERIOD: frames per boundary-counter summary line. 120 is the
// steady-state cadence; the device retrace harness never reaches the teardown dump
// and a trimmed fixture (minecraft-1.21.1-neoforge-create-indirect-in-world-align1024)
// is shorter than 120 frames, so a run that needs its numbers at all sets this low
// enough to land at least one window.
// and a trimmed fixture (create-indirect) is shorter than 120 frames, so a run that
// needs its numbers at all sets this low enough to land at least one window.
Uint32 PipeStatsPeriod = 120;
// MOBILEGL_PIPE_STATS_FILE: where the boundary counters' teardown JSON dump goes.
// Empty (the default) means no dump; the per-120-frame summary line still goes to
@@ -500,6 +499,7 @@ namespace MobileGL::MG_Config {
enum class IpcSurface : Uint8 {
Offscreen = 0, // a window surface is the client's own window, as before (the default)
Server = 1, // a window surface is the SERVER's window: WindowKind::ServerOwned
Host = 2, // a window surface draws into frames the DISPLAY HOST owns; the host presents
};
// IpcTable::AdoptTier when MOBILEGL_IPC_ADOPT_TIER is unset (or unparseable): T0 by default,
// with QUIET fallbacks. Not a tier a user can type - the knob admits 0..2.
@@ -730,6 +730,15 @@ namespace MobileGL::MG_Config {
inline Bool ServerOwnedWindowSurfaces() {
return Transport == TransportMode::Spawn && Ipc.Surface == IpcSurface::Server;
}
// P12: the other on-screen shape, and the mirror image of the one above. The display host
// (the Android side that owns the screen) allocates the frames, offers each one over the
// host frame bridge, and puts it on the glass when this side says it is drawn - so a
// client that asks for this has no window of its own either, and the server takes the
// frames rather than making a window.
inline Bool HostFrameWindowSurfaces() {
return Transport == TransportMode::Spawn && Ipc.Surface == IpcSurface::Host;
}
#else
// The whole point: in a build without MG_Remote this folds at compile time, so
// `if (MG_Config::Transport != MG_Config::TransportMode::Monolith)` in Init.cpp is a
+15 -141
View File
@@ -6,9 +6,6 @@
// SPDX-License-Identifier: LGPL-3.0-only
// End of Source File Header
#if defined(__ANDROID__)
#include <sys/system_properties.h>
#endif
#include "Config.h"
#if MOBILEGL_PIPE_PUSH
// For kMGPipeSubsystemsMigratedAtP5e, the push build's PipePush default (the P2, P3a and P4a
@@ -18,10 +15,12 @@
#endif
#include <cerrno>
#include <cstdio>
#include <cstdlib>
// std::strcmp: InitIpc's server-role check (P12) and the system configuration's.
#if MOBILEGL_BUILD_DISAGGREGATED
// std::strcmp, for InitIpc's server-role check (P12). Split-only, so the pull build's TU is
// unchanged (G1).
#include <cstring>
#endif
#ifndef _WIN32
extern char** environ;
@@ -50,115 +49,6 @@ namespace MobileGL::MG_ConfigLoader {
return (key.compare(0, 6, "LIBGL_") == 0 || key.compare(0, 9, "MOBILEGL_") == 0);
}
// ---- the system configuration -----------------------------------------------------------
//
// A library that is every process's GL implementation (installed as the system's EGL/GLX
// vendor) cannot rely on each process having been started with MOBILEGL_* in its environment:
// most are started by something that has never heard of it. So the settings a whole machine
// shares live in files, and the environment only overrides them:
//
// environment > /etc/mobilegl/backend (MOBILEGL_BACKEND_TYPE only) > client.conf > built-in
//
// client.conf is `KEY=value` lines; blank lines and lines starting with '#' are skipped, the
// key and the value are trimmed, and one pair of matching quotes around the value is removed.
// Only MOBILEGL_* / LIBGL_* keys are taken, exactly as from the environment. The backend file
// holds just the backend's name (the file the backend switch rewrites), and names it over a
// MOBILEGL_BACKEND_TYPE line in client.conf so that switch cannot be silently shadowed.
//
// MOBILEGL_CONFIG_FILE / MOBILEGL_BACKEND_FILE name other files; set to empty they turn the
// file off. The defaults exist only on desktop Linux: an Android app configures its process
// itself, and a server process (MOBILEGL_IPC_ROLE=server) never reads the clients' file.
namespace {
#if defined(__linux__) && !defined(__ANDROID__)
constexpr const char* kDefaultConfigFile = "/etc/mobilegl/client.conf";
constexpr const char* kDefaultBackendFile = "/etc/mobilegl/backend";
#else
constexpr const char* kDefaultConfigFile = "";
constexpr const char* kDefaultBackendFile = "";
#endif
String FilePathSetting(const char* variable, const char* fallback) {
const char* value = std::getenv(variable);
return value != nullptr ? String(value) : String(fallback);
}
String Trimmed(const String& text) {
const auto first = text.find_first_not_of(" \t\r\n");
if (first == String::npos) return String();
const auto last = text.find_last_not_of(" \t\r\n");
return text.substr(first, last - first + 1);
}
Bool IsServerProcess() {
const char* role = std::getenv("MOBILEGL_IPC_ROLE");
return role != nullptr && std::strcmp(role, "server") == 0;
}
// Reads `path` into `out` without replacing what `out` already holds. A missing file is
// not an error: the defaults are the absence of one.
void ReadConfigFile(const String& path, UnorderedMap<String, String>& out, Bool log) {
if (path.empty()) return;
std::FILE* file = std::fopen(path.c_str(), "r");
if (file == nullptr) return;
char buffer[4096];
Uint32 lineNumber = 0;
while (std::fgets(buffer, sizeof(buffer), file) != nullptr) {
++lineNumber;
const String line = Trimmed(buffer);
if (line.empty() || line[0] == '#') continue;
const auto equals = line.find('=');
const String key = equals == String::npos ? String() : Trimmed(line.substr(0, equals));
if (key.empty() || !IsAcceptedPrefix(key)) {
if (log) {
MGLOG_W("Config: %s:%u is not a MOBILEGL_*/LIBGL_* KEY=value line; ignored", path.c_str(),
lineNumber);
}
continue;
}
String value = Trimmed(line.substr(equals + 1));
if (value.size() >= 2 && (value.front() == '"' || value.front() == '\'') && value.back() == value.front()) {
value = value.substr(1, value.size() - 2);
}
out.emplace(key, value);
}
std::fclose(file);
}
void ReadBackendFile(const String& path, UnorderedMap<String, String>& out) {
if (path.empty()) return;
std::FILE* file = std::fopen(path.c_str(), "r");
if (file == nullptr) return;
char buffer[256];
const Bool read = std::fgets(buffer, sizeof(buffer), file) != nullptr;
std::fclose(file);
if (!read) return;
const String name = Trimmed(buffer);
if (!name.empty()) out.emplace("MOBILEGL_BACKEND_TYPE", name);
}
// Everything the system files say, the backend file ahead of client.conf (first emplace
// wins). Re-read on every call: callers are few (Init, and a handful of lookups before it),
// and a file that changed between two processes' starts must not be served stale.
void ReadSystemConfig(UnorderedMap<String, String>& out, Bool log) {
if (IsServerProcess()) return;
ReadBackendFile(FilePathSetting("MOBILEGL_BACKEND_FILE", kDefaultBackendFile), out);
ReadConfigFile(FilePathSetting("MOBILEGL_CONFIG_FILE", kDefaultConfigFile), out, log);
}
} // namespace
Bool LookupSetting(const char* key, String& outValue) {
if (const char* value = std::getenv(key)) {
outValue = value;
return true;
}
UnorderedMap<String, String> system;
ReadSystemConfig(system, false);
const auto it = system.find(key);
if (it == system.end()) return false;
outValue = it->second;
return true;
}
inline void InitializeAcceptedEnvVariables() {
if (!acceptedEnvVariablesMap) {
acceptedEnvVariablesMap = MakeUnique<UnorderedMap<String, String>>();
@@ -189,15 +79,6 @@ namespace MobileGL::MG_ConfigLoader {
}
}
}
// Below the environment: a key the environment set is never replaced.
UnorderedMap<String, String> system;
ReadSystemConfig(system, true);
for (const auto& [key, value] : system) {
if (acceptedEnvVariablesMap->emplace(key, value).second) {
MGLOG_D("Config: Accepted system setting: %s=%s", key.c_str(), value.c_str());
}
}
}
inline void QueryEnvVariable(const String& key, String& outValue, const String& defaultValue) {
@@ -421,17 +302,6 @@ namespace MobileGL::MG_ConfigLoader {
inline void InitBackendType() {
String backendTypeStr;
QueryEnvVariable("MOBILEGL_BACKEND_TYPE", backendTypeStr, "DirectGLES");
#if defined(__ANDROID__)
// An Android app that hosts the library sets the environment itself, before the library
// loads; the debug property is how a developer picks the backend for such a process
// without rebuilding it (`adb shell setprop debug.mobilegl.backend DirectVulkan`).
char property[PROP_VALUE_MAX] = {};
if (__system_property_get("debug.mobilegl.backend", property) > 0) {
MGLOG_I("Config: debug.mobilegl.backend=%s overrides MOBILEGL_BACKEND_TYPE=%s", property,
backendTypeStr.c_str());
backendTypeStr = property;
}
#endif
#define ENTRY(backendType) \
if (backendTypeStr == #backendType) { \
MG_Config::ActiveBackendType = BackendType::backendType; \
@@ -624,8 +494,8 @@ namespace MobileGL::MG_ConfigLoader {
}
}
// P12 (on-screen server window): MOBILEGL_IPC_SURFACE = offscreen | server (Config.h has
// the semantics). An unknown value is named and read as the default, like every knob here.
// P12 (on-screen): MOBILEGL_IPC_SURFACE = offscreen | server | host (Config.h has the
// semantics). An unknown value is named and read as the default, like every knob here.
{
String surface;
QueryEnvVariable("MOBILEGL_IPC_SURFACE", surface, "offscreen");
@@ -635,9 +505,11 @@ namespace MobileGL::MG_ConfigLoader {
ipc.Surface = MG_Config::IpcSurface::Offscreen;
} else if (surface == "server") {
ipc.Surface = MG_Config::IpcSurface::Server;
} else if (surface == "host") {
ipc.Surface = MG_Config::IpcSurface::Host;
} else {
MGLOG_W("Config: Ignoring invalid env variable MOBILEGL_IPC_SURFACE='%s'; expected "
"offscreen|server, using offscreen",
"offscreen|server|host, using offscreen",
surface.c_str());
ipc.Surface = MG_Config::IpcSurface::Offscreen;
}
@@ -645,12 +517,14 @@ namespace MobileGL::MG_ConfigLoader {
// parses this before RunSession sets its own transport, and has no client half anyway.)
const char* role = std::getenv("MOBILEGL_IPC_ROLE");
const Bool serverProcess = role != nullptr && std::strcmp(role, "server") == 0;
if (ipc.Surface == MG_Config::IpcSurface::Server && !serverProcess &&
if (ipc.Surface != MG_Config::IpcSurface::Offscreen && !serverProcess &&
MG_Config::Transport != MG_Config::TransportMode::Spawn) {
// Said, not silently honoured: there is no remote server here to own a window.
MGLOG_W("Config: MOBILEGL_IPC_SURFACE=server is IGNORED - it asks a remote server "
"(MOBILEGL_TRANSPORT=spawn, a fork or tcp:// control) to own the window surface, "
"and this run has none. Window surfaces stay the client's own");
MGLOG_W("Config: MOBILEGL_IPC_SURFACE=%s is IGNORED - it asks for an on-screen "
"surface (the server's own window, or the frames the display host owns) and "
"this run has no remote server to provide one: MOBILEGL_TRANSPORT is not "
"spawn. Window surfaces stay the client's own",
ipc.Surface == MG_Config::IpcSurface::Server ? "server" : "host");
}
}
+4 -2
View File
@@ -8,6 +8,8 @@
#pragma once
#include <cstdio>
// ============== 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)
-38
View File
@@ -24,9 +24,6 @@
#if MOBILEGL_PIPE_VERIFY
#include <MG_Backend/MGPipe/PipeInputs.h> // MGPipeVerifyFlushSummary, before Debug::Close in DestroyImpl
#endif
#if MOBILEGL_BUILD_DISAGGREGATED
#include <MG_Remote/Client/ServerProbe.h>
#endif
#include <atomic>
#include <mutex>
@@ -105,10 +102,6 @@ namespace MobileGL {
MG_State::GLState::ClearProgramTranslationCache();
MG_Backend::gBackendFunctionsTable = {};
g_isInitialized = false;
#if MOBILEGL_BUILD_DISAGGREGATED
// A later re-initialization asks whether the server is there again.
MG_Remote::Client::ResetServerProbeCache();
#endif
#if MOBILEGL_PIPE_VERIFY
// BEFORE Close, and from here rather than from a static destructor (V1 fix round 2):
// Close() nulls the role's sink and Log.cpp's next write reopens it with "w", so the
@@ -227,37 +220,6 @@ namespace MobileGL {
DestroyImpl(true);
}
Bool ImplementationAvailable() {
if (g_isInitialized.load(std::memory_order_acquire)) {
#if MOBILEGL_BUILD_DISAGGREGATED
// Initialized: under a split transport the session either came up (a backend object
// exists) or it did not, and a display on a session that never came up cannot draw.
if (MG_Config::Transport != MG_Config::TransportMode::Monolith) {
return MG_Backend::pActiveBackendObject != nullptr;
}
#endif
return true;
}
#if defined(__linux__) && !defined(__ANDROID__)
// LIBGL_ALWAYS_SOFTWARE is how a process (or whoever launched it) asks the system's GL for a
// software renderer. MobileGL is a GPU forwarder, so it steps aside and lets the system's
// other implementation give the process what it asked for.
{
String software;
if (MG_ConfigLoader::LookupSetting("LIBGL_ALWAYS_SOFTWARE", software) && !software.empty() &&
software != "0" && software != "false") {
return false;
}
}
#endif
#if MOBILEGL_BUILD_DISAGGREGATED
// Not yet: the bring-up would dial the configured server and wait for it. Ask first.
return MG_Remote::Client::ConfiguredServerAvailable();
#else
return true;
#endif
}
// MobileGL's lifecycle is owned entirely by the host-API layers
// (EGL/WGL/CGL): initialization happens lazily on the first entry point
// via EnsureInitialized(), and full teardown happens deterministically
-12
View File
@@ -26,20 +26,8 @@ namespace MobileGL {
namespace MG_ConfigLoader {
void Init();
// One setting resolved the way Init() resolves it - the environment, then the system
// configuration files (ConfigLoader.cpp) - for the few readers that must decide something
// before MobileGL initializes. False when neither names it.
Bool LookupSetting(const char* key, String& outValue);
} // namespace MG_ConfigLoader
// Whether this process can be served right now. False when MobileGL is configured to reach a
// server that is not there (or a split session already failed to come up), or when the process
// asked for software rendering (LIBGL_ALWAYS_SOFTWARE, desktop Linux), so a
// caller that can choose another implementation - the system's EGL/GLX/GBM loaders - should
// decline rather than hand out something that cannot draw. Cheap: once true it stays true
// until the library is torn down, and a probe is one non-blocking connect with a short bound.
Bool ImplementationAvailable();
namespace MG_Backend {
void Init();
} // namespace MG_Backend
+82 -45
View File
@@ -200,15 +200,12 @@ namespace MobileGL::MG_Backend {
Bool BackendObject::ResizeEGLWindowSurface(EGLSurface surface, Uint32 width, Uint32 height) {
const std::lock_guard<std::recursive_mutex> lock(m_eglStateMutex);
auto surfaceIt = m_eglSurfaces.find(surface);
if (surfaceIt == m_eglSurfaces.end() || surfaceIt->second.Kind == SurfaceKind::None) {
if (surfaceIt == m_eglSurfaces.end() || surfaceIt->second.Kind != SurfaceKind::Window) {
MGLOG_E("ResizeEGLWindowSurface failed: no window surface is initialized");
return false;
}
// A pbuffer-backed window (a Wayland window presented through wl_shm) resizes too.
surfaceIt->second.Window.Width = width;
surfaceIt->second.Window.Height = height;
surfaceIt->second.Width = static_cast<EGLint>(std::max<Uint32>(width, 1));
surfaceIt->second.Height = static_cast<EGLint>(std::max<Uint32>(height, 1));
if (m_eglSurface == surface) {
m_windowHandle.Width = width;
m_windowHandle.Height = height;
@@ -216,6 +213,28 @@ namespace MobileGL::MG_Backend {
return true;
}
// The frame itself is the backend's business (InitHostFrameSurface); what happens here is
// the registration every surface kind shares, so the swap path and the state mirrors see
// a host-framed surface exactly like any other.
Bool BackendObject::CreateEGLHostFrameSurface(EGLSurface surface, Uint32 width, Uint32 height) {
const std::lock_guard<std::recursive_mutex> lock(m_eglStateMutex);
if (!m_eglDisplayInitialized) {
MGLOG_E("CreateEGLHostFrameSurface failed: EGL display is not initialized");
return false;
}
if (surface == EGL_NO_SURFACE) {
MGLOG_E("CreateEGLHostFrameSurface failed: invalid EGLSurface");
return false;
}
auto& state = m_eglSurfaces[surface];
state = EGLSurfaceState{
.Kind = SurfaceKind::HostFrame,
.Width = static_cast<EGLint>(std::max<Uint32>(width, 1)),
.Height = static_cast<EGLint>(std::max<Uint32>(height, 1)),
};
return ActivateEGLSurface(surface);
}
Bool BackendObject::CreateEGLPbufferSurface(EGLSurface surface, EGLint width, EGLint height) {
const std::lock_guard<std::recursive_mutex> lock(m_eglStateMutex);
return RegisterEGLPbufferSurface(surface, width, height) && ActivateEGLSurface(surface);
@@ -286,7 +305,6 @@ namespace MobileGL::MG_Backend {
return true;
}
m_activatingSurface = surface;
if (surfaceState->Kind == SurfaceKind::Window) {
SetWindowHandle(surfaceState->Window);
if (!InitWindowSurface()) {
@@ -298,6 +316,11 @@ namespace MobileGL::MG_Backend {
MGLOG_E("ActivateEGLSurface failed: backend InitPbufferSurface failed");
return false;
}
} else if (surfaceState->Kind == SurfaceKind::HostFrame) {
if (!InitHostFrameSurface(surfaceState->Width, surfaceState->Height)) {
MGLOG_E("ActivateEGLSurface failed: backend InitHostFrameSurface failed");
return false;
}
} else {
MGLOG_E("ActivateEGLSurface failed: unsupported surface kind");
return false;
@@ -306,14 +329,8 @@ namespace MobileGL::MG_Backend {
m_eglSurface = surface;
m_eglSurfaceInitialized = true;
m_eglSurfaceKind = surfaceState->Kind;
// NOT m_eglCurrentThreads.clear(): another thread's current context and surface are its
// own (a multi-window client renders each window on its own thread), and wiping them made
// that thread's next eglSwapBuffers fail with "no current context attached".
auto activatedIt = m_eglSurfaces.find(surface);
if (activatedIt != m_eglSurfaces.end() && !activatedIt->second.Activated) {
activatedIt->second.Activated = true;
m_backendCapabilitiesInitialized = false;
}
m_eglCurrentThreads.clear();
m_backendCapabilitiesInitialized = false;
return true;
}
@@ -329,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");
@@ -380,24 +420,6 @@ namespace MobileGL::MG_Backend {
m_eglCurrentThreads.clear();
}
void BackendObject::ForgetActiveEGLSurface() {
const std::lock_guard<std::recursive_mutex> lock(m_eglStateMutex);
m_eglSurfaceInitialized = false;
m_eglSurfaceKind = SurfaceKind::None;
m_eglSurface = EGL_NO_SURFACE;
m_windowHandle = {};
}
namespace {
MG_Util::Damage::Region& PresentDamageSlot() {
thread_local MG_Util::Damage::Region damage = MG_Util::Damage::Region::Full();
return damage;
}
} // namespace
const MG_Util::Damage::Region& CurrentPresentDamage() { return PresentDamageSlot(); }
void SetCurrentPresentDamage(const MG_Util::Damage::Region& damage) { PresentDamageSlot() = damage; }
Bool BackendObject::SwapEGLBuffers(EGLDisplay dpy, EGLSurface draw) {
const std::lock_guard<std::recursive_mutex> lock(m_eglStateMutex);
if (!m_eglDisplayInitialized || m_eglDisplay != dpy) {
@@ -414,15 +436,15 @@ namespace MobileGL::MG_Backend {
MGLOG_E("SwapEGLBuffers failed: draw surface is not current on this thread");
return false;
}
if (draw == EGL_NO_SURFACE || !GetRegisteredEGLSurface(draw)) {
if (!m_eglSurfaceInitialized || draw == EGL_NO_SURFACE || draw != m_eglSurface) {
MGLOG_E("SwapEGLBuffers failed: invalid draw surface");
return false;
}
// The calling thread's surface, which another thread's make-current may have moved the
// backend off: bring it back before presenting it.
if ((!m_eglSurfaceInitialized || draw != m_eglSurface) && !ActivateEGLSurface(draw)) {
MGLOG_E("SwapEGLBuffers failed: the draw surface could not be re-activated");
return false;
// A host-framed surface has no swapchain: presenting it means telling the host the frame
// is drawn, because the host is what puts it on the glass.
if (m_eglSurfaceKind == SurfaceKind::HostFrame) {
return PresentHostFrame();
}
const auto& backendFunctions = GetBackendFunctions();
@@ -442,6 +464,27 @@ namespace MobileGL::MG_Backend {
}
}
// A backend that has no host-framed surfaces says so by name: the server may ask for one
// (MOBILEGL_IPC_SURFACE=host) against a build that cannot serve it, and that has to be a
// refusal with a reason rather than a surface that draws nowhere.
Bool BackendObject::InitHostFrameSurface(EGLint width, EGLint height) {
(void)width;
(void)height;
MGLOG_E("InitHostFrameSurface: this backend has no host-framed surfaces");
return false;
}
Bool BackendObject::PresentHostFrame() {
MGLOG_E("PresentHostFrame: this backend has no host-framed surfaces");
return false;
}
Bool BackendObject::PresentHostFrameIfCurrent() {
const std::lock_guard<std::recursive_mutex> lock(m_eglStateMutex);
if (!m_eglSurfaceInitialized || m_eglSurfaceKind != SurfaceKind::HostFrame) return true;
return PresentHostFrame();
}
Bool BackendObject::IsEGLSurfaceCurrent(EGLSurface surface) const {
if (surface == EGL_NO_SURFACE) {
return false;
@@ -464,9 +507,8 @@ namespace MobileGL::MG_Backend {
m_eglSurfaces.erase(surfaceIt);
if (m_eglSurface == surface) {
OnEGLSurfaceReleased(surface);
ForgetActiveEGLSurface();
ResetEGLRuntimeState();
}
OnEGLSurfaceForgotten(surface);
}
void BackendObject::ReleaseEGLCurrentThread(const std::thread::id& threadKey) {
@@ -497,9 +539,8 @@ namespace MobileGL::MG_Backend {
m_eglSurfaces.erase(surfaceIt);
if (m_eglSurface == surface) {
OnEGLSurfaceReleased(surface);
ForgetActiveEGLSurface();
ResetEGLRuntimeState();
}
OnEGLSurfaceForgotten(surface);
}
void BackendObject::ReleaseEGLResources() {
@@ -532,8 +573,4 @@ namespace MobileGL::MG_Backend {
void BackendObject::OnEGLSurfaceReleased(EGLSurface surface) {
(void)surface;
}
void BackendObject::OnEGLSurfaceForgotten(EGLSurface surface) {
(void)surface;
}
} // namespace MobileGL::MG_Backend
+17 -187
View File
@@ -11,7 +11,6 @@
#include "MG_State/GLState/TextureState/TextureEnum.h"
#if MOBILEGL_BUILD_DISAGGREGATED
#include <MG_Pipe/MGPipeHandles.h>
#include <MG_Util/Damage/Damage.h>
#endif
namespace MobileGL {
@@ -584,197 +583,38 @@ namespace MobileGL {
Uint32 Height = 0;
};
// SHARED IMAGES (docs/Disaggregated/notes/anland/plan-ahb-dmabuf.md): server-allocated colour
// buffers exported to clients as dma-buf descriptors.
//
// The server-side view of one image, as a backend sees it: `NativeBuffer` is the image's
// AHardwareBuffer (null where there is none), `Fourcc` a DRM fourcc - ABGR8888 (R, G, B, A in
// memory, GL RGBA8) or XBGR8888 (alpha ignored); ARGB8888 / XRGB8888 images are stored the
// same way (SharedImageRegistry.h says why), so a backend binds every one as RGBA8.
struct SharedImageView {
Uint64 Id = 0;
Uint32 Width = 0;
Uint32 Height = 0;
Uint32 Fourcc = 0;
void* NativeBuffer = nullptr;
};
// The client-side answer of an allocation: the image's id and its exported descriptor
// (`Fd`, owned by the caller), with the plane layout a linux-dmabuf wl_buffer is created with.
struct SharedImageExport {
Uint64 Id = 0;
int Fd = -1;
Uint32 Width = 0;
Uint32 Height = 0;
Uint32 Fourcc = 0;
Uint32 Stride = 0;
Uint32 Offset = 0;
Uint64 Modifier = 0;
};
// THE DAMAGE OF THE PRESENT BEING APPLIED on this thread: the server's apply thread sets it
// around the backend's Present (from the present record), and a backend that can hand damage
// to its native present reads it there. Full whenever nothing set it.
const MG_Util::Damage::Region& CurrentPresentDamage();
void SetCurrentPresentDamage(const MG_Util::Damage::Region& damage);
class BackendObject {
public:
virtual ~BackendObject() = default;
// ---- shared images, SERVER side (a backend implements these) ---------------------
//
// Copies the default framebuffer of the surface current on this (the apply) thread into
// `image`, rows TOP FIRST - GL's top row (y = height-1) lands in the image's first memory
// row, which is what a wl_buffer's first row is - scaled to the image's extent if the two
// differ. The image is ORDERED THROUGH ITS SYNC STATE (SharedImageRegistry.h): the copy
// waits for the image's pending read fences before it writes, and its own completion
// is published with SharedImages::PublishWrite as a sync_file - the call returns once
// the copy is submitted, never waiting for it on the CPU (a backend with no fence export
// waits and publishes -1). A reader binding the image waits for that fence on its GPU
// when the write generation moved, and at its frame boundary publishes its frame's fence
// with PublishRead / ReadTracker. The application's GL state is untouched. False = not
// supported / failed (logged).
//
// `region` (GL window coordinates, origin bottom-left) is the part of the frame to copy;
// Full copies all of it. The rest of the image is left as it is - the client sends a
// region only for an image that already holds the frame outside it - and a backend that
// cannot be sure the image's contents survived (a target it has never written) copies
// all of it regardless.
virtual Bool BlitDefaultFramebufferToSharedImage(const SharedImageView& image,
const MG_Util::Damage::Region& region) {
(void)image, (void)region;
return false;
}
// EGL_BUFFER_AGE_EXT of the draw surface of the context current on this (the apply)
// thread: how many presents ago the buffer the next frame draws into held the frame then
// presented; 0 = unknown (the application repaints everything). Asking says the client
// relies on the answer, so from then on the backend keeps what it presents.
//
// `damageRegionFollows`: the client declares the region it draws (SetCurrentDamageRegion)
// before drawing. A driver whose only buffer age is EGL_KHR_partial_update's keeps a
// buffer's content only outside that region, so without one coming it is not asked.
virtual Int32 QueryCurrentBufferAge(Bool damageRegionFollows) {
(void)damageRegionFollows;
return 0;
}
// eglSetDamageRegionKHR for that draw surface: the frame draws `region` (GL window
// coordinates; Full = all of it) and nothing outside it. A backend without the notion
// ignores it.
virtual Bool SetCurrentDamageRegion(const MG_Util::Damage::Region& region) {
(void)region;
return true;
}
// ---- shared images, CLIENT side (BackendObject_Remote implements these) ----------
//
// A new image, allocated by the server; `out->Fd` is the caller's to close.
virtual Bool AllocateSharedImage(Uint32 width, Uint32 height, Uint32 fourcc, SharedImageExport* out) {
(void)width, (void)height, (void)fourcc, (void)out;
return false;
}
// Names the image `fd` was exported from (the caller keeps `fd`). False: not one of this
// server's images, or the size/format disagree.
virtual Bool ImportSharedImage(int fd, Uint32 width, Uint32 height, Uint32 fourcc, Uint64* outId) {
(void)fd, (void)width, (void)height, (void)fourcc, (void)outId;
return false;
}
// Drops this client's reference (an allocation's or an import's).
virtual Bool ReleaseSharedImage(Uint64 id) {
(void)id;
return false;
}
// In the GL stream: the current context's default framebuffer, copied top row first into
// the image (BlitDefaultFramebufferToSharedImage on the server) - `region` of it, Full for
// all. Returns when it completed.
virtual Bool PresentToSharedImage(Uint64 id, const MG_Util::Damage::Region& region) {
(void)id, (void)region;
return false;
}
// In the GL stream: EGL_BUFFER_AGE_EXT of the current draw surface (QueryCurrentBufferAge
// on the server). False: the backend has no answer (the caller reports 0).
virtual Bool QueryBufferAge(Bool damageRegionFollows, EGLint* age) {
(void)damageRegionFollows, (void)age;
return false;
}
// In the GL stream: eglSetDamageRegionKHR for the current draw surface
// (SetCurrentDamageRegion on the server).
virtual Bool SetDamageRegion(const MG_Util::Damage::Region& region) {
(void)region;
return false;
}
// In the GL stream: the texture whose lifetime id is `textureLifetimeId` takes the image as
// its level-0 storage (glEGLImageTargetTexture2DOES), until its next storage definition.
// The caller has already defined level 0 as Width x Height RGBA8 with no data.
virtual Bool AttachSharedImageToTexture(Uint64 textureLifetimeId, Uint64 id) {
(void)textureLifetimeId, (void)id;
return false;
}
virtual void Initialize() = 0;
virtual Bool InitCapabilities() = 0;
virtual Bool InitWindowSurface() = 0;
// A served session's apply thread - the one thread that runs this backend from here on -
// calls this first, in a process that may serve several sessions at once. A backend whose
// native state is process-global by construction gives this object its own copy and binds
// it to the calling thread. The default has nothing per process to separate.
virtual void BindSessionStateToThisThread() {}
// A served session's ring moved to another of its client's contexts (bind_context). A
// backend whose surface follows the native context it binds needs nothing; one that keeps
// a single native surface binding re-binds the surface that context was last made current
// with. `token` is the client's context token (the EGLContext MakeEGLCurrent was given).
virtual void OnClientContextBound(Uint64 token) { (void)token; }
virtual Bool InitializeEGLDisplay(EGLDisplay dpy, EGLint* major, EGLint* minor);
virtual Bool CreateEGLWindowSurface(EGLSurface surface, const WindowHandle& handle);
virtual Bool ResizeEGLWindowSurface(EGLSurface surface, Uint32 width, Uint32 height);
virtual Bool CreateEGLPbufferSurface(EGLSurface surface, EGLint width, EGLint height);
// The host owns the screen: this side never gets a window of the client's to draw
// into, so the surface it draws into is a frame the host allocated and offered over
// the host frame bridge. Each swap tells the host the frame is done and takes the
// next; presentation is the host's, not a swapchain's.
virtual Bool CreateEGLHostFrameSurface(EGLSurface surface, Uint32 width, Uint32 height);
virtual Bool InitHostFrameSurface(EGLint width, EGLint height);
virtual Bool PresentHostFrame();
// The present RECORD's half of a host-framed swap. A split client's swap reaches the
// server as a present record (ServerVerbSink::OnPresent), never as SwapEGLBuffers, so
// without this the host was never told a frame was drawn. True when the current
// surface is not host-framed: there is nothing to present then.
Bool PresentHostFrameIfCurrent();
virtual Bool MakeEGLCurrent(EGLDisplay dpy, EGLSurface draw, EGLSurface read, EGLContext ctx);
virtual Bool SwapEGLBuffers(EGLDisplay dpy, EGLSurface draw);
// eglSwapBuffersWithDamage: `damage` (GL window coordinates) is a hint for the native
// present. A backend with nothing to hand it to swaps as SwapEGLBuffers does.
virtual Bool SwapEGLBuffersWithDamage(EGLDisplay dpy, EGLSurface draw, const MG_Util::Damage::Region& damage) {
(void)damage;
return SwapEGLBuffers(dpy, draw);
}
// Forwards the app-requested eglSwapInterval to the backend's native
// presentation path (no-op for backends without a SetSwapInterval hook).
virtual void SetEGLSwapInterval(Int interval);
virtual void ReleaseEGLSurface(EGLSurface surface);
virtual void ReleaseEGLResources();
// ---- the server's own display window going away and coming back -------------------
//
// `window` (a window surface's native window) is about to be destroyed - the display's
// screen went off. Release ONLY what is bound to it: every window surface on it keeps its
// client handle and draws into a placeholder from here on, and every context, object and
// device stays. Called on the thread that runs this backend; nothing may reference the
// window once it returns true. False: not supported (the caller ends the session instead).
virtual Bool SuspendServerWindow(void* window) {
(void)window;
return false;
}
// The surfaces SuspendServerWindow parked are rebuilt on `window` (a new native window,
// `width`x`height`), and their new extent is published as a creation publishes it. False:
// they could not be (the caller ends the session).
virtual Bool ResumeServerWindow(void* window, Uint32 width, Uint32 height) {
(void)window, (void)width, (void)height;
return false;
}
// `window` changed size to `width`x`height` (the display's report - the one size to publish).
// Its surfaces publish that extent to the client now, without waiting for a present; a
// swapchain that has to follow is rebuilt when no frame is half-recorded, else at the
// present. False: nothing was published (no surface on it, or not supported).
virtual Bool ServerWindowResized(void* window, Uint32 width, Uint32 height) {
(void)window, (void)width, (void)height;
return false;
}
// CLIENT side, from eglQuerySurface(EGL_WIDTH/EGL_HEIGHT): a backend whose surface extents
// change under the application (a remote server's window) applies what it has received.
virtual void RefreshSurfaceExtent(EGLSurface surface) { (void)surface; }
void SetWindowHandle(const WindowHandle& handle);
virtual const RendererInfo& GetRendererInfo() const = 0;
@@ -788,7 +628,11 @@ namespace MobileGL {
enum class SurfaceKind {
None,
Window,
Pbuffer
Pbuffer,
// A surface whose drawing target is a frame the display host owns. There is no
// swapchain behind it: the host puts the frame on the glass when this side says
// it is drawn, which is why presenting one is its own call and not a Present.
HostFrame
};
struct EGLCurrentState {
@@ -801,28 +645,18 @@ namespace MobileGL {
struct EGLSurfaceState {
SurfaceKind Kind = SurfaceKind::None;
Bool DestroyPending = false;
// Activated at least once: a re-activation (a multi-window client switching back)
// is a re-bind and does not re-run the backend's capability probe.
Bool Activated = false;
WindowHandle Window;
EGLint Width = 1;
EGLint Height = 1;
};
void ResetEGLRuntimeState();
// ResetEGLRuntimeState for a released ACTIVE surface: the backend has no active surface
// any more, but every OTHER thread's current context and surface stay as they were (a
// multi-window client closing one popup must not unbind its other windows' threads).
void ForgetActiveEGLSurface();
Bool RegisterEGLWindowSurface(EGLSurface surface, const WindowHandle& handle);
Bool RegisterEGLPbufferSurface(EGLSurface surface, EGLint width, EGLint height);
const EGLSurfaceState* GetRegisteredEGLSurface(EGLSurface surface) const;
Bool ActivateEGLSurface(EGLSurface surface);
virtual Bool InitPbufferSurface(EGLint width, EGLint height);
virtual void OnEGLSurfaceReleased(EGLSurface surface);
// Every registered surface the base class drops, current or not, after it is gone from
// m_eglSurfaces. A backend that keeps a native surface per client surface frees it here.
virtual void OnEGLSurfaceForgotten(EGLSurface surface);
FormatCapabilityCache& MutableFormatCapabilities();
mutable std::recursive_mutex m_eglStateMutex;
@@ -830,10 +664,6 @@ namespace MobileGL {
WindowHandle m_windowHandle;
EGLDisplay m_eglDisplay = EGL_NO_DISPLAY;
EGLSurface m_eglSurface = EGL_NO_SURFACE;
// The client surface ActivateEGLSurface is bringing up while it calls InitWindowSurface /
// InitPbufferSurface, which take no surface argument: a backend that maps client surfaces
// to native ones reads it to re-bind an existing native surface instead of making another.
EGLSurface m_activatingSurface = EGL_NO_SURFACE;
Bool m_eglDisplayInitialized = false;
Bool m_eglSurfaceInitialized = false;
Bool m_backendCapabilitiesInitialized = false;
@@ -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 <MG_Remote/Server/ServerLoop.h>
#endif
#include "BackendObject_DirectGLES.h"
#include "MG_Backend/BackendObject.h"
#include "MG_Backend/BackendObjects.h"
@@ -906,58 +912,13 @@ namespace MobileGL::MG_Backend::DirectGLES {
#endif
}
Bool BackendObject_DirectGLES::RebindNativeSurfaceFor(EGLSurface surface) {
const auto it = m_nativeSurfaces.find(surface);
if (it == m_nativeSurfaces.end()) return false;
if (DirectGLES::BindSessionSurface(it->second)) return true;
// The session no longer owns it (destroyed with a window loss): forget and recreate.
m_nativeSurfaces.erase(it);
return false;
}
void BackendObject_DirectGLES::RestoreSurfaceAfterCreation(EGLSurface previousNativeDraw) {
// The ACTIVE CONTEXT's own surface, exactly: the creation's bind attached the new surface to
// whichever context the session had bound (often another window's thread), and putting back
// "the surface activated last" instead re-attached THAT context to a third window's surface -
// a desktop drawing into and reading back from the panel's pbuffer.
if (previousNativeDraw == EGL_NO_SURFACE) return;
if (!DirectGLES::BindSessionSurface(previousNativeDraw)) return;
for (const auto& [client, native] : m_nativeSurfaces) {
if (native != previousNativeDraw) continue;
const auto state = m_eglSurfaces.find(client);
if (state == m_eglSurfaces.end()) break;
m_eglSurface = client;
m_eglSurfaceInitialized = true;
m_eglSurfaceKind = state->second.Kind;
if (state->second.Kind == SurfaceKind::Window) m_windowHandle = state->second.Window;
break;
}
}
Bool BackendObject_DirectGLES::InitWindowSurface() {
if (RebindNativeSurfaceFor(m_activatingSurface)) return true;
// A suspended surface whose placeholder went: another placeholder - never the window, which
// is gone.
if (std::find(m_suspendedWindowSurfaces.begin(), m_suspendedWindowSurfaces.end(), m_activatingSurface) !=
m_suspendedWindowSurfaces.end()) {
const EGLSurface placeholder = DirectGLES::CreateSessionPbuffer(1, 1);
if (placeholder == EGL_NO_SURFACE || !DirectGLES::BindSessionSurface(placeholder)) {
MGLOG_E("DirectGLES: no placeholder for the suspended window surface %p",
reinterpret_cast<void*>(m_activatingSurface));
return false;
}
m_nativeSurfaces[m_activatingSurface] = placeholder;
return true;
}
// Only use EGL for now
auto nativeWindow = reinterpret_cast<NativeWindowType>(m_windowHandle.Handle);
if (!DirectGLES::InitWindowSurface(nativeWindow)) {
MGLOG_E("Failed to initialize window surface for DirectGLES backend");
return false;
}
if (m_activatingSurface != EGL_NO_SURFACE) {
m_nativeSurfaces[m_activatingSurface] = DirectGLES::CurrentSessionDrawSurface();
}
return true;
}
@@ -1021,19 +982,8 @@ namespace MobileGL::MG_Backend::DirectGLES {
return true;
}
// ---- P14 S4: A SECOND SURFACE NO LONGER TEARS THE CONTEXT DOWN. ----
//
// This used to be `DestroyEGLContext(); ResetEGLRuntimeState();` whenever a surface was
// created while another was active, i.e. every pbuffer -> window -> pbuffer switch destroyed
// the native context - and with it every buffer, texture and program the application had
// built. The native context now belongs to the (session, context token) tuple the backend
// resolves, and creating a surface for it only adds a surface: the tuple keeps its context
// and its objects. ResetEGLRuntimeState still runs because the base class's per-surface
// bookkeeping (which surface is active, which threads made it current) does describe the
// surface that is being replaced.
const EGLSurface previous = m_eglSurfaceInitialized ? m_eglSurface : EGL_NO_SURFACE;
const EGLSurface previousNativeDraw = DirectGLES::CurrentContextDrawSurface();
if (m_eglSurfaceInitialized) {
DestroyEGLContext();
ResetEGLRuntimeState();
}
@@ -1042,12 +992,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
// the first virtual tuple adopts that bind. On failure nothing is known to be bound. The
// pull arm below is the original statement, byte for byte (G1).
const Bool created = BackendObject::CreateEGLWindowSurface(surface, handle);
if (created && previous != EGL_NO_SURFACE && previous != surface) {
// Another surface was current: the creation must not leave the context that held it
// drawing to the new one (P14 multi-window clients).
RestoreSurfaceAfterCreation(previousNativeDraw);
NoteNativeContextGone();
} else if (created) {
if (created) {
NoteNativeContextFreshFromSurfaceCreation();
} else {
NoteNativeContextGone();
@@ -1069,11 +1014,8 @@ namespace MobileGL::MG_Backend::DirectGLES {
return true;
}
// P14 S4: as for the window surface above - the native context is the (session, context
// token) tuple's and survives a surface switch. This used to be DestroyEGLContext().
const EGLSurface previous = m_eglSurfaceInitialized ? m_eglSurface : EGL_NO_SURFACE;
const EGLSurface previousNativeDraw = DirectGLES::CurrentContextDrawSurface();
if (m_eglSurfaceInitialized) {
DestroyEGLContext();
ResetEGLRuntimeState();
}
@@ -1081,10 +1023,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
// ID-54 / ID-67: as for the window surface - InitPbufferSurface bound natively. The pull
// arm below is the original statement, byte for byte (G1).
const Bool created = BackendObject::CreateEGLPbufferSurface(surface, width, height);
if (created && previous != EGL_NO_SURFACE && previous != surface) {
RestoreSurfaceAfterCreation(previousNativeDraw);
NoteNativeContextGone();
} else if (created) {
if (created) {
NoteNativeContextFreshFromSurfaceCreation();
} else {
NoteNativeContextGone();
@@ -1095,36 +1034,245 @@ namespace MobileGL::MG_Backend::DirectGLES {
#endif
}
Bool BackendObject_DirectGLES::ResizeEGLWindowSurface(EGLSurface surface, Uint32 width, Uint32 height) {
const std::lock_guard<std::recursive_mutex> lock(m_eglStateMutex);
const auto state = m_eglSurfaces.find(surface);
const auto native = m_nativeSurfaces.find(surface);
if (state == m_eglSurfaces.end() || state->second.Kind != SurfaceKind::Pbuffer || native == m_nativeSurfaces.end()) {
return BackendObject::ResizeEGLWindowSurface(surface, width, height);
}
// A pbuffer has no resize: the client surface gets a new native pbuffer at the new size,
// and every context that drew to the old one draws to the new one.
const EGLint w = static_cast<EGLint>(std::max<Uint32>(width, 1));
const EGLint h = static_cast<EGLint>(std::max<Uint32>(height, 1));
const EGLSurface replacement = DirectGLES::CreateSessionPbuffer(w, h);
if (replacement == EGL_NO_SURFACE) {
MGLOG_E("ResizeEGLWindowSurface: no %dx%d pbuffer could replace the old drawable", w, h);
return false;
}
DirectGLES::ReplaceSessionSurface(native->second, replacement);
native->second = replacement;
return BackendObject::ResizeEGLWindowSurface(surface, width, height);
#if MOBILEGL_BUILD_DISAGGREGATED && defined(__ANDROID__)
namespace {
// The host may still be starting when the client asks for its surface: it is a separate
// app that has to come up and allocate its pool. Waiting is better than refusing a
// surface a client is entitled to, and the wait is answered by name if it expires.
constexpr Int kHostFrameWaitMs = 30000;
}
Bool BackendObject_DirectGLES::InitPbufferSurface(EGLint width, EGLint height) {
if (RebindNativeSurfaceFor(m_activatingSurface)) return true;
if (!DirectGLES::InitPbufferSurface(width, height)) return false;
if (m_activatingSurface != EGL_NO_SURFACE) {
m_nativeSurfaces[m_activatingSurface] = DirectGLES::CurrentSessionDrawSurface();
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<EGLint>(width), static_cast<EGLint>(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
// this context's framebuffer. The pbuffer stays as the draw target for the moment before
// the first frame arrives, which is the only moment it is used.
if (!DirectGLES::InitPbufferSurface(width, height)) {
MGLOG_E("InitHostFrameSurface: the context the host frames are drawn in did not come up");
return false;
}
if (!m_hostFrameBridgeOpen) {
String why;
if (!m_hostFrameBridge.Open(MG_Backend::kHostFrameSocket, kHostFrameWaitMs, why)) {
MGLOG_E("InitHostFrameSurface: no display host: %s", why.c_str());
return false;
}
m_hostFrameBridgeOpen = true;
}
return TakeHostFrame();
}
Bool BackendObject_DirectGLES::TakeHostFrame() {
String why;
struct AHardwareBuffer* frame = nullptr;
MG_Backend::HostFrameOffer offer{};
if (!m_hostFrameBridge.Acquire(&frame, offer, why)) {
MGLOG_E("TakeHostFrame: %s", why.c_str());
return false;
}
HostFrameTarget target;
if (!HostFrameTargetCreate(frame, target, why)) {
MGLOG_E("TakeHostFrame: the host frame %ux%u did not become a draw target: %s", offer.Width,
offer.Height, why.c_str());
AHardwareBuffer_release(frame);
return false;
}
DestroyHostFrame();
m_hostFrameTarget = target;
m_hostFrameBuffer = frame;
m_hostFrameOffer = offer;
// The canvas is made at the first frame's size and kept; a failure leaves the frame itself
// as the draw target, which is how this path behaved before the canvas existed.
if (!EnsureHostFrameCanvas(target.Width, target.Height))
MGLOG_E_ONCE("TakeHostFrame: no canvas in front of the host frames; drawing into the frame itself");
const HostFrameTarget& drawTarget = HostFrameDrawTarget();
// BEFORE the bind: every default-framebuffer bind the engine makes from here on has to
// resolve to this target, and that resolution is what this global is.
g_hostFrameFramebufferId = drawTarget.Framebuffer;
// Published together with the framebuffer, because they describe the same target: the STORAGE
// an attachment is bound to when the client's texture has none of its own, and the SIZE that
// decides whether binding it is right at all.
g_hostFrameRenderbuffer = drawTarget.Renderbuffer;
g_hostFrameWidth = drawTarget.Width;
g_hostFrameHeight = drawTarget.Height;
FramebufferImpl::InvalidateFramebufferBindingCache();
HostFrameTargetBind(drawTarget);
// AND ON TO THE CONTAINER, as the dma-buf descriptor behind it. The Wayland compositor
// over there renders into THESE frames - it runs this project's own GBM, whose
// gbm_bo_create answers with the phone's frame instead of an allocation of its own - so
// every frame taken here is useless to it until its descriptor has crossed. Open() binds
// the listening socket a container dials, and the IsUp() test keeps the ordinary frame
// down to an integer compare: the socket outlives every container and every connection,
// while OfferFrame accepts whoever dialled since the last frame and opens the socket
// itself when the first frame arrives before any container has.
//
// NEITHER ANSWER IS EXAMINED, and that is the channel's contract rather than an
// oversight: no container running, a container that has died, or one that has taken the
// descriptor and stopped reading must all leave this frame drawn and presented exactly as
// it would have been without a channel - the descriptor is a copy of the pixels' route,
// not a step in producing them.
if (!m_gbmFrameChannel.IsUp()) m_gbmFrameChannel.Open();
(void)m_gbmFrameChannel.OfferFrame(frame, offer);
MGLOG_I("host frame %u is the draw target: %ux%u", offer.Index, target.Width, target.Height);
return true;
}
void BackendObject_DirectGLES::DestroyHostFrame() {
// The canvas outlives the frame, so with one the globals keep naming it: the attachments
// made over it stay valid between this frame being handed back and the next one arriving.
g_hostFrameFramebufferId = m_hostFrameCanvas.Framebuffer;
g_hostFrameRenderbuffer = m_hostFrameCanvas.Renderbuffer;
g_hostFrameWidth = m_hostFrameCanvas.Width;
g_hostFrameHeight = m_hostFrameCanvas.Height;
HostFrameTargetDestroy(m_hostFrameTarget);
if (m_hostFrameBuffer != nullptr) {
AHardwareBuffer_release(m_hostFrameBuffer);
m_hostFrameBuffer = nullptr;
}
// 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() {
// When this returns, the pixels are complete: glFinish is the fence the host is told
// about, and the host's own readback - which Complete reads - is what proves the drawing
// landed where the screen will look.
BlitHostFrameCanvas();
if (g_GLESFuncs.glFinish != nullptr) g_GLESFuncs.glFinish();
// WHAT THE CONTAINER SAID WHILE THIS FRAME WAS BEING DRAWN. This is the one place the
// server's apply loop passes through the host channel - the swap it runs lands here for a
// host-framed surface - and a release is the container's compositor saying it is done
// reading a frame this side handed over. Poll() is a bare recvmsg on a non-blocking
// socket: with no container connected it returns on its first test, and a container that
// is between frames answers EAGAIN, so a pass costs nothing when there is nothing to
// read. Nothing here is waited for and nothing is required to arrive; the count of
// frames offered and not released is a number the channel keeps for the log, never a
// frame the render path waits on.
m_gbmFrameChannel.Poll();
String why;
if (!m_hostFrameBridge.Complete(m_hostFrameOffer, /*imported=*/true, /*drawn=*/true, /*fenceOk=*/true, why)) {
MGLOG_E("PresentHostFrame: %s", why.c_str());
return false;
}
// The answer has been read, so the host has already put this frame on the glass: it is
// this side's to drop, and the next one becomes the drawing target.
DestroyHostFrame();
return TakeHostFrame();
}
Bool BackendObject_DirectGLES::EnsureHostFrameCanvas(Uint width, Uint height) {
if (m_hostFrameCanvas.Framebuffer != 0) return true;
if (width == 0 || height == 0 || !g_GLESFuncs.glRenderbufferStorage || !g_GLESFuncs.glBlitFramebuffer ||
!g_GLESFuncs.glGenRenderbuffers || !g_GLESFuncs.glGenFramebuffers || !g_GLESFuncs.glCheckFramebufferStatus)
return false;
// RAW binds, as HostFrameTargetCreate makes them: the caller invalidates the engine's
// framebuffer shadow and binds through it right after.
GLuint renderbuffer = 0;
g_GLESFuncs.glGenRenderbuffers(1, &renderbuffer);
g_GLESFuncs.glBindRenderbuffer(GL_RENDERBUFFER, renderbuffer);
// The frames are R8G8B8A8_UNORM (the display host allocates them so), and so is this.
g_GLESFuncs.glRenderbufferStorage(GL_RENDERBUFFER, GL_RGBA8, static_cast<GLsizei>(width),
static_cast<GLsizei>(height));
GLuint framebuffer = 0;
g_GLESFuncs.glGenFramebuffers(1, &framebuffer);
g_GLESFuncs.glBindFramebuffer(GL_FRAMEBUFFER, framebuffer);
g_GLESFuncs.glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, renderbuffer);
const GLenum status = g_GLESFuncs.glCheckFramebufferStatus(GL_FRAMEBUFFER);
if (status != GL_FRAMEBUFFER_COMPLETE) {
MGLOG_E("host frame canvas %ux%u: framebuffer status 0x%04x", width, height, status);
g_GLESFuncs.glDeleteFramebuffers(1, &framebuffer);
g_GLESFuncs.glDeleteRenderbuffers(1, &renderbuffer);
return false;
}
m_hostFrameCanvas.Renderbuffer = renderbuffer;
m_hostFrameCanvas.Framebuffer = framebuffer;
m_hostFrameCanvas.Width = width;
m_hostFrameCanvas.Height = height;
MGLOG_I("host frame canvas: %ux%u as framebuffer %u (renderbuffer %u), copied into each frame at present",
width, height, framebuffer, renderbuffer);
return true;
}
void BackendObject_DirectGLES::BlitHostFrameCanvas() {
if (m_hostFrameCanvas.Framebuffer == 0 || m_hostFrameTarget.Framebuffer == 0) return;
// Whatever the compositor had bound is put back as it was, raw for raw, so the engine's
// shadow (which never saw this) is still right afterwards. The scissor test and
// rasterizer discard both apply to a blit, so they are lifted for it.
GLint readBinding = 0;
GLint drawBinding = 0;
g_GLESFuncs.glGetIntegerv(GL_READ_FRAMEBUFFER_BINDING, &readBinding);
g_GLESFuncs.glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &drawBinding);
const GLboolean scissor = g_GLESFuncs.glIsEnabled(GL_SCISSOR_TEST);
const GLboolean discard = g_GLESFuncs.glIsEnabled(GL_RASTERIZER_DISCARD);
if (scissor) g_GLESFuncs.glDisable(GL_SCISSOR_TEST);
if (discard) g_GLESFuncs.glDisable(GL_RASTERIZER_DISCARD);
g_GLESFuncs.glBindFramebuffer(GL_READ_FRAMEBUFFER, m_hostFrameCanvas.Framebuffer);
g_GLESFuncs.glBindFramebuffer(GL_DRAW_FRAMEBUFFER, m_hostFrameTarget.Framebuffer);
const Bool sameSize = m_hostFrameCanvas.Width == m_hostFrameTarget.Width &&
m_hostFrameCanvas.Height == m_hostFrameTarget.Height;
g_GLESFuncs.glBlitFramebuffer(0, 0, static_cast<GLint>(m_hostFrameCanvas.Width),
static_cast<GLint>(m_hostFrameCanvas.Height), 0, 0,
static_cast<GLint>(m_hostFrameTarget.Width),
static_cast<GLint>(m_hostFrameTarget.Height), GL_COLOR_BUFFER_BIT,
sameSize ? GL_NEAREST : GL_LINEAR);
g_GLESFuncs.glBindFramebuffer(GL_READ_FRAMEBUFFER, static_cast<GLuint>(readBinding));
g_GLESFuncs.glBindFramebuffer(GL_DRAW_FRAMEBUFFER, static_cast<GLuint>(drawBinding));
if (scissor) g_GLESFuncs.glEnable(GL_SCISSOR_TEST);
if (discard) g_GLESFuncs.glEnable(GL_RASTERIZER_DISCARD);
}
#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;
MGLOG_E("InitHostFrameSurface: host frames are a disaggregated Android path");
return false;
}
Bool BackendObject_DirectGLES::TakeHostFrame() { return false; }
void BackendObject_DirectGLES::DestroyHostFrame() {}
Bool BackendObject_DirectGLES::EnsureHostFrameCanvas(Uint, Uint) { return false; }
void BackendObject_DirectGLES::BlitHostFrameCanvas() {}
Bool BackendObject_DirectGLES::PresentHostFrame() {
MGLOG_E("PresentHostFrame: host frames are a disaggregated Android path");
return false;
}
#endif
Bool BackendObject_DirectGLES::InitPbufferSurface(EGLint width, EGLint height) {
return DirectGLES::InitPbufferSurface(width, height);
}
Bool BackendObject_DirectGLES::MakeEGLCurrent(EGLDisplay dpy, EGLSurface draw, EGLSurface read, EGLContext ctx) {
const std::lock_guard<std::recursive_mutex> lock(m_eglStateMutex);
if (IsReleaseCurrentRequest(dpy, draw, read, ctx)) {
@@ -1145,13 +1293,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
@@ -1179,19 +1356,10 @@ 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);
// The draw surface's own native surface (P14 multi-window): a known one is re-bound, so the
// bind goes to it and not to whichever surface the session drew to last.
// The real bind still runs whenever the skip above says so (ID-67: a different tuple onto
// the same surface needs MakeCurrent's invalidations even though the driver triple is equal).
const auto nativeDraw = m_nativeSurfaces.find(draw);
if (!nativelyCurrentAlready && nativeDraw != m_nativeSurfaces.end()) {
(void)DirectGLES::SelectSessionSurface(nativeDraw->second);
}
const Bool bound = nativelyCurrentAlready || DirectGLES::MakeCurrent();
if (!bound) {
(surfaceless || (m_eglSurfaceInitialized && m_eglSurface == draw &&
NativeBindCanBeSkippedFor(dpy, draw, read, ctx)));
if (!nativelyCurrentAlready && !DirectGLES::MakeCurrent()) {
NoteNativeContextGone();
return false;
}
@@ -1209,27 +1377,18 @@ namespace MobileGL::MG_Backend::DirectGLES {
#endif
return false;
}
// A HOST-FRAMED SURFACE HAS TO BE PUT BACK AFTER EVERY MAKE-CURRENT. The native call
// binds the surface's own default framebuffer - the pbuffer this path makes its context
// with - and that is not where these pixels go. Both the driver and the engine's binding
// shadow have to be told again, or the next default-framebuffer bind is deduped away and
// every draw lands in a pbuffer nobody sees.
if (m_eglSurfaceKind == SurfaceKind::HostFrame && m_hostFrameTarget.Framebuffer != 0) {
FramebufferImpl::InvalidateFramebufferBindingCache();
HostFrameTargetBind(HostFrameDrawTarget());
}
return true;
}
Bool BackendObject_DirectGLES::BlitDefaultFramebufferToSharedImage(const SharedImageView& image,
const MG_Util::Damage::Region& region) {
#if MOBILEGL_BUILD_DISAGGREGATED
return DirectGLES::SharedImageImpl::BlitDefaultFramebufferTo(image, region);
#else
(void)image, (void)region;
return false;
#endif
}
Int32 BackendObject_DirectGLES::QueryCurrentBufferAge(Bool damageRegionFollows) {
return DirectGLES::CurrentDrawBufferAge(damageRegionFollows);
}
Bool BackendObject_DirectGLES::SetCurrentDamageRegion(const MG_Util::Damage::Region& region) {
return DirectGLES::SetCurrentDrawDamageRegion(region);
}
Bool BackendObject_DirectGLES::SwapEGLBuffers(EGLDisplay dpy, EGLSurface draw) {
return BackendObject::SwapEGLBuffers(dpy, draw);
}
@@ -1245,118 +1404,17 @@ namespace MobileGL::MG_Backend::DirectGLES {
#if MOBILEGL_BUILD_DISAGGREGATED
NoteNativeContextGone();
#endif
m_suspendedWindowSurfaces.clear();
BackendObject::ReleaseEGLResources();
}
Bool BackendObject_DirectGLES::SuspendServerWindow(void* window) {
const std::lock_guard<std::recursive_mutex> lock(m_eglStateMutex);
if (window == nullptr) return false;
Vector<EGLSurface> onWindow;
for (const auto& [client, state] : m_eglSurfaces) {
if (state.Kind != SurfaceKind::Window || state.Window.Handle != window) continue;
if (std::find(m_suspendedWindowSurfaces.begin(), m_suspendedWindowSurfaces.end(), client) !=
m_suspendedWindowSurfaces.end())
continue;
onWindow.push_back(client);
}
for (const EGLSurface client : onWindow) {
// A surface never activated has no native surface: only its record names the window.
const auto native = m_nativeSurfaces.find(client);
if (native != m_nativeSurfaces.end()) {
const EGLSurface placeholder = DirectGLES::SuspendSessionWindowSurface(native->second);
if (placeholder == EGL_NO_SURFACE) return false;
native->second = placeholder;
}
m_suspendedWindowSurfaces.push_back(client);
}
#if MOBILEGL_BUILD_DISAGGREGATED
// The native binding moved onto the placeholder: the next make-current binds for real.
NoteNativeContextGone();
#endif
MGLOG_I("DirectGLES: %zu window surface(s) on server window %p now draw into placeholder pbuffers; the "
"contexts and their objects stay",
onWindow.size(), window);
return true;
}
Bool BackendObject_DirectGLES::ResumeServerWindow(void* window, Uint32 width, Uint32 height) {
const std::lock_guard<std::recursive_mutex> lock(m_eglStateMutex);
if (window == nullptr) return false;
Vector<EGLSurface> suspended;
suspended.swap(m_suspendedWindowSurfaces);
for (const EGLSurface client : suspended) {
const auto state = m_eglSurfaces.find(client);
if (state == m_eglSurfaces.end()) continue; // released while suspended
state->second.Window.Handle = window;
state->second.Window.Width = width;
state->second.Window.Height = height;
state->second.Width = static_cast<EGLint>(std::max<Uint32>(width, 1));
state->second.Height = static_cast<EGLint>(std::max<Uint32>(height, 1));
if (m_eglSurface == client) m_windowHandle = state->second.Window;
// Never activated: its first activation creates it on the new window.
const auto native = m_nativeSurfaces.find(client);
if (native == m_nativeSurfaces.end()) continue;
const EGLSurface surface =
DirectGLES::ResumeSessionWindowSurface(native->second, reinterpret_cast<NativeWindowType>(window));
if (surface == EGL_NO_SURFACE) return false;
native->second = surface;
}
#if MOBILEGL_BUILD_DISAGGREGATED
NoteNativeContextGone();
#endif
MGLOG_I("DirectGLES: %zu suspended window surface(s) rebuilt on server window %p (%ux%u)", suspended.size(),
window, width, height);
return true;
}
Bool BackendObject_DirectGLES::ServerWindowResized(void* window, Uint32 width, Uint32 height) {
const std::lock_guard<std::recursive_mutex> lock(m_eglStateMutex);
if (window == nullptr) return false;
Bool published = false;
for (auto& [client, state] : m_eglSurfaces) {
if (state.Kind != SurfaceKind::Window || state.Window.Handle != window) continue;
if (std::find(m_suspendedWindowSurfaces.begin(), m_suspendedWindowSurfaces.end(), client) !=
m_suspendedWindowSurfaces.end())
continue;
state.Window.Width = width;
state.Window.Height = height;
state.Width = static_cast<EGLint>(std::max<Uint32>(width, 1));
state.Height = static_cast<EGLint>(std::max<Uint32>(height, 1));
if (m_eglSurface == client) m_windowHandle = state.Window;
// The window surface's buffers follow the window by themselves (from the next one the
// driver dequeues); only the client has to be told.
const auto native = m_nativeSurfaces.find(client);
if (native == m_nativeSurfaces.end()) continue;
published = DirectGLES::RepublishWindowSurfaceShape(native->second,
reinterpret_cast<NativeWindowType>(window)) ||
published;
}
return published;
}
void BackendObject_DirectGLES::OnEGLSurfaceReleased(EGLSurface surface) {
// P14: releasing a surface releases THAT SURFACE (OnEGLSurfaceForgotten), never the
// contexts. This used to be DestroyEGLContext() - every native context of the session, with
// every object the client had built - which a multi-window client hit on its first closed
// popup.
(void)surface;
DestroyEGLContext();
#if MOBILEGL_BUILD_DISAGGREGATED
NoteNativeContextGone();
#endif
}
void BackendObject_DirectGLES::OnEGLSurfaceForgotten(EGLSurface surface) {
m_suspendedWindowSurfaces.erase(
std::remove(m_suspendedWindowSurfaces.begin(), m_suspendedWindowSurfaces.end(), surface),
m_suspendedWindowSurfaces.end());
const auto it = m_nativeSurfaces.find(surface);
if (it == m_nativeSurfaces.end()) return;
const EGLSurface native = it->second;
m_nativeSurfaces.erase(it);
DirectGLES::DestroySessionSurface(native);
}
const RendererInfo& BackendObject_DirectGLES::GetRendererInfo() const {
return MutableRendererInfo();
}
@@ -1386,13 +1444,6 @@ namespace MobileGL::MG_Backend::DirectGLES {
V_OpenGL30, V_OpenGL31, V_OpenGL32, V_OpenGL33, V_OpenGL40, V_OpenGL41, V_OpenGL42, V_OpenGL43,
V_OpenGL44, V_OpenGL45, V_OpenGL46,
E_GL_ARB_draw_buffers_blend,
// The GLSL 1.00/1.10-era ARB trio plus NPOT textures: all core since GL 2.0 and
// trivially true for every context this backend claims (4.6). KWin 6's
// EglContext::checkSupported() gates desktop-GL compositing on exactly these four
// strings, so withholding them fails its renderer bring-up on an otherwise capable
// implementation.
E_GL_ARB_shader_objects, E_GL_ARB_vertex_shader, E_GL_ARB_fragment_shader,
E_GL_ARB_texture_non_power_of_two,
E_GL_ARB_compute_shader, E_GL_ARB_shader_storage_buffer_object, E_GL_ARB_shader_image_load_store,
E_GL_ARB_clear_buffer_object, E_GL_ARB_program_interface_query, E_GL_ARB_framebuffer_object, E_GL_EXT_framebuffer_object,
E_GL_ARB_depth_texture, E_GL_ARB_buffer_storage, E_GL_ARB_texture_storage,
@@ -1491,7 +1542,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.
@@ -8,6 +8,9 @@
#pragma once
#include <Includes.h>
#include "HostFrameTarget.h"
#include "MG_Backend/HostFrameBridge.h"
#include "MG_Backend/GbmFrameChannel.h"
#include "../BackendObject.h"
#include <MG_Util/BackendLoaders/OpenGL/Loader.h>
@@ -38,26 +41,10 @@ namespace MobileGL::MG_Backend::DirectGLES {
Bool InitializeEGLDisplay(EGLDisplay dpy, EGLint* major, EGLint* minor) override;
Bool CreateEGLWindowSurface(EGLSurface surface, const WindowHandle& handle) override;
Bool CreateEGLPbufferSurface(EGLSurface surface, EGLint width, EGLint height) override;
Bool ResizeEGLWindowSurface(EGLSurface surface, Uint32 width, Uint32 height) override;
Bool MakeEGLCurrent(EGLDisplay dpy, EGLSurface draw, EGLSurface read, EGLContext ctx) override;
Bool SwapEGLBuffers(EGLDisplay dpy, EGLSurface draw) override;
// Shared images: a GL blit of default framebuffer 0 into a renderbuffer whose storage is
// the image's EGLImage, ordered after the image's pending reads and published as a native
// fence without a CPU wait (DirectGLES.h, SharedImageImpl).
Bool BlitDefaultFramebufferToSharedImage(const SharedImageView& image,
const MG_Util::Damage::Region& region) override;
// A window surface's age is the driver's (EGL_EXT_buffer_age); a pbuffer keeps its content,
// so it is 1 once it has been presented (DirectGLES::CurrentDrawBufferAge).
Int32 QueryCurrentBufferAge(Bool damageRegionFollows) override;
// eglSetDamageRegionKHR on a window surface whose driver has EGL_KHR_partial_update.
Bool SetCurrentDamageRegion(const MG_Util::Damage::Region& region) override;
void ReleaseEGLSurface(EGLSurface surface) override;
void ReleaseEGLResources() override;
// The server window going and coming back: each window surface on it swaps its native EGL
// window surface for a placeholder pbuffer and back (DirectGLES::Suspend/ResumeSessionWindowSurface).
Bool SuspendServerWindow(void* window) override;
Bool ResumeServerWindow(void* window, Uint32 width, Uint32 height) override;
Bool ServerWindowResized(void* window, Uint32 width, Uint32 height) override;
const RendererInfo& GetRendererInfo() const override;
String GetBackendAPIVersionString() const override;
@@ -72,23 +59,47 @@ namespace MobileGL::MG_Backend::DirectGLES {
private:
void UpdateDynamicBackendParameters();
Bool InitPbufferSurface(EGLint width, EGLint height) override;
// A host-framed surface draws into a frame the display host owns; presenting one
// tells the host the frame is drawn, because the host is what puts it on the glass.
// NOT CreateEGLHostFrameSurface: the base class registers the surface and activates it,
// and activation is what reaches InitHostFrameSurface below. There is nothing about the
// EGL side of a host-framed surface this backend needs to do its own way.
Bool InitHostFrameSurface(EGLint width, EGLint height) override;
Bool PresentHostFrame() override;
// Takes the next frame from the host and makes it this context's framebuffer.
Bool TakeHostFrame();
void DestroyHostFrame();
// The canvas the compositor draws into, made once at the first frame's size.
Bool EnsureHostFrameCanvas(Uint width, Uint height);
// Copies the canvas into the frame about to be presented.
void BlitHostFrameCanvas();
// What draws resolve to: the canvas when there is one, the frame itself otherwise.
const HostFrameTarget& HostFrameDrawTarget() const {
return m_hostFrameCanvas.Framebuffer != 0 ? m_hostFrameCanvas : m_hostFrameTarget;
}
void OnEGLSurfaceReleased(EGLSurface surface) override;
void OnEGLSurfaceForgotten(EGLSurface surface) override;
// An existing native surface for the client surface being activated, re-bound; false when
// there is none yet (the caller creates it).
Bool RebindNativeSurfaceFor(EGLSurface surface);
// EGL: creating a surface does not change what is current. The creation bound the new
// surface natively; put the previous one back for the context that held it.
void RestoreSurfaceAfterCreation(EGLSurface previousNativeDraw);
// MOBILEGL_IPC_SURFACE=host: the frames the display host owns, one at a time, which
// 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;
// A STABLE TARGET IN FRONT OF THE FRAMES. Every present hands the frame back and takes
// a different one, and its renderbuffer is deleted with it - but a compositor attaches
// its framebuffers ONCE (kwin: one per daemon buffer, for the life of the process), so
// attachments bound to a frame's own renderbuffer named a deleted object from the second
// frame on. The attachments name this instead, and each present copies it into the
// frame. No EGLImage behind it (Image stays null).
HostFrameTarget m_hostFrameCanvas;
struct AHardwareBuffer* m_hostFrameBuffer = nullptr;
MG_Backend::HostFrameOffer m_hostFrameOffer{};
Bool m_hostFrameBridgeOpen = false;
Bool m_initialized = false;
// P14: ONE NATIVE SURFACE PER CLIENT SURFACE, created on its first activation and re-bound
// on every later one. A multi-window client switches surfaces every frame; making a new
// native surface each time leaked them and lost what the window had drawn.
UnorderedMap<EGLSurface, EGLSurface> m_nativeSurfaces;
// Window surfaces whose window is gone (SuspendServerWindow): their native surface is a
// placeholder pbuffer until ResumeServerWindow.
Vector<EGLSurface> m_suspendedWindowSurfaces;
MG_External::EGLFunctionsTable m_EGLFunctions;
MG_External::GLESFunctionsTable m_GLESFunctions;
MG_External::GLESCapabilities m_GLESCapabilities;
File diff suppressed because it is too large Load Diff
+20 -300
View File
@@ -111,65 +111,11 @@ namespace MobileGL::MG_Backend::DirectGLES {
void ShaderStorageBlockBinding(GLuint program, const GLchar* storageBlockName, GLuint storageBlockBinding);
Bool InitWindowSurface(NativeWindowType window);
Bool InitPbufferSurface(EGLint width, EGLint height);
// The calling thread's session's current native draw surface (the one the last Init*Surface
// created, or the last BindSessionSurface named).
EGLSurface CurrentSessionDrawSurface();
// The surface the calling thread's ACTIVE context last drew to (EGL_NO_SURFACE for none).
EGLSurface CurrentContextDrawSurface();
// EGL_BUFFER_AGE_EXT of the session's current draw surface for the next frame: the driver's
// answer for a window surface, 1 for a pbuffer that has been presented (a pbuffer's content stays
// across swaps), 0 otherwise. A driver whose buffer age is only EGL_KHR_partial_update's keeps
// nothing inside the frame's damage region - the whole surface unless one is set - so it is asked
// only when `damageRegionFollows` (SetCurrentDrawDamageRegion before the first draw).
Int32 CurrentDrawBufferAge(Bool damageRegionFollows);
// eglSetDamageRegionKHR(region) on the session's current window surface (a pbuffer, or a driver
// without EGL_KHR_partial_update, ignores it). The driver wants the age asked first in the frame;
// when the client was answered without asking it, it is asked here.
Bool SetCurrentDrawDamageRegion(const MG_Util::Damage::Region& region);
// Makes an EXISTING native surface of the calling thread's session the one it draws to, and
// binds it to the active context. False for a surface the session does not own.
Bool BindSessionSurface(EGLSurface surface);
// The same selection without the bind (the caller binds - MakeCurrent - unconditionally).
Bool SelectSessionSurface(EGLSurface surface);
// Destroys one native surface of the calling thread's session - and only it; the session's
// contexts and other surfaces are untouched.
void DestroySessionSurface(EGLSurface surface);
// A new pbuffer of the calling thread's session, created with the active context's config and
// bound to nothing (EGL: creating a surface changes no binding).
EGLSurface CreateSessionPbuffer(EGLint width, EGLint height);
// Every context of the session that drew to `previous` draws to `replacement` instead, and
// `previous` is destroyed (a pbuffer-backed window's resize).
void ReplaceSessionSurface(EGLSurface previous, EGLSurface replacement);
// The server window going away (screen off): every context of the session that drew to the
// window surface `windowSurface` draws to a new 1x1 placeholder pbuffer instead, and the window
// surface is destroyed - no longer current anywhere once this returns. The contexts and their
// objects stay. Returns the placeholder, or EGL_NO_SURFACE (nothing changed) when none could be
// made.
EGLSurface SuspendSessionWindowSurface(EGLSurface windowSurface);
// The way back: a window surface on `window` replaces `placeholder` (EGL_NO_SURFACE: none to
// replace) for every context that drew to it, is bound, and its extent is published as a
// creation publishes it. Returns the new surface, or EGL_NO_SURFACE.
EGLSurface ResumeSessionWindowSurface(EGLSurface placeholder, NativeWindowType window);
// The window under `surface` changed size: its extent (the display's) is published again, at once.
Bool RepublishWindowSurfaceShape(EGLSurface surface, NativeWindowType window);
Bool MakeCurrent();
Bool ReleaseCurrent();
// True when the backend ES context is current on the calling thread, i.e.
// immediate buffer ops may issue GL calls right now.
Bool IsBackendContextCurrentOnThisThread();
#if MOBILEGL_BUILD_DISAGGREGATED
// DEVICE LOSS, Espryt's half (Magma's is VulkanRenderer::LatchWireDeviceLoss). Asks the
// driver whether the calling thread's context was reset (glGetGraphicsResetStatus); a reset -
// or the debug knob MGPipeDebugDeviceLossDue - latches THIS session through
// MGPipeSessionLatch and answers true, and the caller returns from its verb without issuing
// more GL. Asked at the frame boundaries (Present, a shared-image present) and before a
// readback, never per draw. The contexts keep the driver's default reset strategy: asking
// every context to lose itself on reset would also end the INNOCENT ones - the compositor's
// among them - on any other client's GPU fault.
// `debugKnob` false: the knob is not consulted here (the on-screen Present, so an injected loss
// lands on an offscreen client's shared-image present or readback, never on the compositor's).
Bool LatchIfDeviceLost(const char* site, Bool debugKnob = true);
#endif
// GL fence sync objects, backed by native ES fences. FenceSync returns null
// (the frontend then falls back to an always-signaled sync) when the calling
// thread does not own the ES context. Waits/queries degrade to "signaled" in
@@ -258,200 +204,6 @@ namespace MobileGL::MG_Backend::DirectGLES {
void SetEGLFuncsTable(const MG_External::EGLFunctionsTable& eglFuncs);
void SetGLESFuncsTable(const MG_External::GLESFunctionsTable& glesFuncs);
void SetGLESCapabilities(const MG_External::GLESCapabilities& capabilities);
// ---------------------------------------------------------------------------------
// P14 S4 (docs/Disaggregated/design/11-state-ownership.md): THE NATIVE TUPLE IS PER CONTEXT
// ---------------------------------------------------------------------------------
//
// The display is process state and stays one object (eglInitialize once per process, terminated
// when the last native context leaves). The native EGLContext, the config it was created with
// and the native surfaces are keyed by (session, client context token) - the identity S1 put on
// the wire and S2 gave a per-thread owner. Creating a second context therefore no longer tears
// the first one's native context down, which is what lets two contexts (and two share groups)
// be live at once in one process.
// Answers, for the CALLING THREAD, which session it belongs to and which client context token
// that session has bound. Installed once by the server layer; with no resolver installed -
// monolith, a frontend-only process, a unit case - the answer is the single key {0, 0}, which is
// exactly the process singleton this replaces. `false` also means {0,0}.
using NativeContextKeyResolver = Bool (*)(Uint64* outSessionKey, Uint64* outContextToken);
void SetNativeContextKeyResolver(NativeContextKeyResolver resolver);
#if MOBILEGL_PIPE_PUSH
// ---------------------------------------------------------------------------------
// P14 S6 (docs/Disaggregated/design/11-state-ownership.md): THE TWIN TABLES' KEY, AND ITS
// SHAPE IS S4's, ONE LEVEL DOWN. A twin is a DRIVER object, so it lives in one native
// context's object namespace; the identity a twin table must be keyed on is therefore
// {session, share group} - the SAME two words the applier's OBJECT RECORDS are filed under
// (PipeApply.h's MGPipeApplierKey, derived by the same probe and the same `0 means its own
// group` rule, so the two agree by construction rather than by two conventions).
//
// Answers, for the CALLING THREAD, which session it belongs to and which share group that
// session's current context is in. Installed once by the server layer beside the native and
// applier probes; with no probe installed - or on a thread that is no session's own, which
// is the client process, the in-process client+server shape and every unit case - the
// answer is the single key {0, 0}, exactly the process-wide table this replaces.
struct TwinKey {
Uint64 SessionKey = 0;
Uint64 ShareGroupKey = 0;
Bool operator==(const TwinKey& other) const {
return SessionKey == other.SessionKey && ShareGroupKey == other.ShareGroupKey;
}
Bool operator!=(const TwinKey& other) const { return !(*this == other); }
};
struct TwinKeyHash {
SizeT operator()(const TwinKey& key) const {
// The 64-bit mix SlotAllocator and the applier's registry already use for their own
// pair keys, so every keyed table in this tree hashes a session the same way.
Uint64 mixed = key.SessionKey ^ (key.ShareGroupKey + 0x9E3779B97F4A7C15ull +
(key.SessionKey << 6) + (key.SessionKey >> 2));
mixed ^= mixed >> 33;
mixed *= 0xFF51AFD7ED558CCDull;
mixed ^= mixed >> 33;
return static_cast<SizeT>(mixed);
}
};
using TwinKeyResolver = Bool (*)(TwinKey* outKey);
void SetTwinKeyResolver(TwinKeyResolver resolver);
// The calling thread's key. Answers false for {0, 0} - the process-wide group - which is
// also the answer when no probe has ever been installed.
Bool CurrentTwinKey(TwinKey* outKey);
#endif
// Builds the native context for `contextToken` under the calling thread's session. A
// `shareGroupToken` whose group already has a live native context in this session hands that
// context to eglCreateContext as the share argument - which is what makes two contexts see one
// set of buffer/texture objects. Idempotent: a token that already has one answers true.
Bool CreateNativeContextFor(Uint64 contextToken, Uint64 shareGroupToken);
// Destroys ONE context's native tuple (the DestroyContext control frame). The session's other
// contexts are untouched; the display is terminated only when the last context in the process
// has gone.
void DestroyNativeContextFor(Uint64 contextToken);
// ---- objects that belong to ONE native context ----
//
// Framebuffers, vertex arrays, transform feedbacks and queries are container objects: GL never
// shares them, not even between contexts of one share group, and every context numbers its own
// from 1. A process-wide scratch FBO id minted in one context and bound in another therefore
// names THAT context's own framebuffer - often an application's - and the scratch path's
// attach/scrub then rewires it onto staging textures. With one process serving several
// sessions (each with its own native contexts) that silently corrupted other clients' frames.
//
// The calling thread's current native context as a lifetime serial: assigned when the context
// is created and never reused (a recycled EGLContext address is a new serial). 0 when none was
// made current through MakeCurrent.
Uint64 CurrentNativeContextSerial();
class PerNativeContextBase {
public:
PerNativeContextBase();
PerNativeContextBase(const PerNativeContextBase&) = delete;
PerNativeContextBase& operator=(const PerNativeContextBase&) = delete;
// The context died, and its names with it: forget them (no GL call - there is no context
// left to make one in).
virtual void ForgetContext(Uint64 serial) = 0;
protected:
~PerNativeContextBase();
};
// Called where a native context is destroyed.
void ForgetNativeContextObjects(Uint64 serial);
// Moves whenever any per-context entry is dropped; a thread's cached entry is valid while
// it has not moved.
Uint64 PerNativeContextEpoch();
void BumpPerNativeContextEpoch();
// One T per native context, created on first use from that context.
template <typename T>
class PerNativeContext final : public PerNativeContextBase {
public:
T& Current() {
const Uint64 serial = CurrentNativeContextSerial();
// The draw path asks for the same entry over and over from one thread: a one-entry
// thread-local cache, invalidated by any drop anywhere (rare).
thread_local CurrentCache cache;
const Uint64 epoch = PerNativeContextEpoch();
if (cache.Owner == this && cache.Serial == serial && cache.Epoch == epoch) return *cache.Entry;
const std::lock_guard<std::mutex> lock(m_mutex);
T& entry = m_bySerial[serial]; // node-based: the reference survives other contexts' inserts
cache = {this, serial, epoch, &entry};
return entry;
}
template <typename F>
void ForEach(F&& visit) {
const std::lock_guard<std::mutex> lock(m_mutex);
for (auto& entry : m_bySerial) visit(entry.second);
}
void Clear() {
const std::lock_guard<std::mutex> lock(m_mutex);
BumpPerNativeContextEpoch();
m_bySerial.clear();
}
void ForgetContext(Uint64 serial) override {
const std::lock_guard<std::mutex> lock(m_mutex);
BumpPerNativeContextEpoch();
m_bySerial.erase(serial);
}
private:
struct CurrentCache {
const PerNativeContext* Owner = nullptr;
Uint64 Serial = 0;
Uint64 Epoch = 0;
T* Entry = nullptr;
};
std::mutex m_mutex;
std::unordered_map<Uint64, T> m_bySerial;
};
// The GL name of one per-context object, spelled like the plain `GLuint` it replaces: it reads
// as the CURRENT context's name, `= 0` resets that one, and `&name` is where glGen* writes it.
class NativeContextName {
public:
operator GLuint() const { return m_names.Current(); }
NativeContextName& operator=(GLuint name) {
m_names.Current() = name;
return *this;
}
GLuint* operator&() { return &m_names.Current(); }
private:
mutable PerNativeContext<GLuint> m_names;
};
// P14 S4. THE NATIVE HALF OF A CONTEXT SWITCH. `bind_context` moves which context the session's
// records belong to; this makes the calling thread's native tuple follow it, binding the
// session's current surface to the newly named context's native EGLContext. A no-op when the
// named context has no native context yet (the session never sent CreateContext) or when the
// native context already current on this thread IS that one - so the single-context world pays
// nothing for it. Called from the bind_context path on the apply thread.
Bool MakeNativeContextCurrentForBoundToken();
#if MOBILEGL_BUILD_DISAGGREGATED
// P14: the server's backend turn moved to the calling apply thread (ServerLoop.cpp's
// BackendTurnLock). Takes the backend's GL ownership for this thread and drops every
// binding shadow, which still describes the previous holder's native context.
void OnBackendTurnHandoff();
#endif
// How many native contexts this process holds, and how many of them belong to one session. The
// test observables for "a second context did not tear the first one down".
Uint64 NativeContextCount();
Uint64 NativeContextCountForSession(Uint64 sessionKey);
// The calling thread's session, as the resolver above reports it (0 with no resolver).
Uint64 CurrentNativeSessionKey();
// ---- Test observables (P14 S4). EGL exposes no "which EGLContext does this client context
// hold" query and no way to ask a context for its share group, so a case that must tell "the
// same native context still serves" from "a fresh one was built", or a sharing pair from two
// unrelated contexts, reads it here. These are pure reads plus one key override; neither is on
// a production path and neither changes behaviour.
EGLContext NativeContextHandleFor(Uint64 sessionKey, Uint64 contextToken);
// Overrides the key the calling thread resolves to, for the life of the call. The backend's
// ordinary answer comes from the server layer's probe; this is how a case drives exactly the
// tuple it means when no session runtime is installed.
void ForceNativeContextKeyForTesting(Uint64 sessionKey, Uint64 contextToken);
void DestroyEGLContext();
// Transform feedback capture spans, performed by the real ES driver. The
@@ -495,60 +247,28 @@ namespace MobileGL::MG_Backend::DirectGLES {
// answers from the frontend state, which this function only reads.
void SyncRenderState(Bool forColorClear = false);
void InvalidateSyncedRenderState();
// GL_SCISSOR_TEST as the driver has it in the native context current on this thread -
// what a guard that turns the test off around its own blit, and puts it back, needs to
// know. The shadow answers only while it describes this context (synced since the last
// invalidation, in this context epoch); otherwise the driver is asked. The shadow is one
// per process: once another session's context synced into it, or a context switch
// invalidated it, its bits are some other context's.
Bool DriverScissorTestEnabled();
// TESTING: the shadow as SyncRenderState leaves it in the current context epoch, with
// GL_SCISSOR_TEST `enabled`.
void SetSyncedScissorTestForTesting(Bool enabled);
// TESTING: `inside` runs within the guard the shared-image present and the readbacks
// copy under (ScopedScissorDisable).
void RunScissorDisabledForTesting(void (*inside)(void*), void* data);
} // namespace RenderStateImpl
#if MOBILEGL_BUILD_DISAGGREGATED
// ---- SHARED IMAGES (docs/Disaggregated/notes/anland/plan-ahb-dmabuf.md) ----
//
// A shared image reaches the driver only through the Android import path: its AHardwareBuffer
// becomes an EGLImage (EGL_ANDROID_get_native_client_buffer + EGL_ANDROID_image_native_buffer)
// and that EGLImage the storage of a texture or renderbuffer (GL_OES_EGL_image). On a host
// build there is no such path and every entry below declines.
namespace SharedImageImpl {
// One EGLImage over one shared image, holding the image's registry reference for as long
// as the EGLImage lives (SharedImageRegistry.h's lifetime rule). The last reference
// destroys the EGLImage, unless the display that made it has been terminated since (which
// destroyed it already). Opaque outside DirectGLES.cpp.
struct EglImage;
using EglImageRef = SharedPtr<EglImage>;
// An EGLImage for the live shared image `id`, or null with `why`. Needs a current context
// (the first call resolves the extension entry points).
EglImageRef CreateEglImage(Uint64 id, String& why);
// glEGLImageTargetTexture2DOES(GL_TEXTURE_2D, image) on what the active unit has bound to
// GL_TEXTURE_2D. False when the driver refused it (its GL error is consumed).
Bool TargetBoundTexture2D(const EglImageRef& image);
// BackendObject::BlitDefaultFramebufferToSharedImage, for the calling thread's context.
Bool BlitDefaultFramebufferTo(const SharedImageView& image, const MG_Util::Damage::Region& region);
// THE READER'S HALF of the image's sync state (SharedImageRegistry.h). Called on every use
// of a name whose level 0 is `image`, before the command that samples it: when a write
// landed since this context last waited, the context's later commands wait for its fence
// on the GPU; and the image is noted as read by the calling session's current frame.
void AcquireForSampling(const EglImageRef& image);
// The calling session's frame boundary for what it has read: hands a fence for everything
// the current context has submitted to every image noted since the last boundary. Called
// at Present and wherever the current native context stops being current (its reads can
// only be fenced from it). Nothing noted = nothing done.
void PublishPendingReads();
} // namespace SharedImageImpl
#endif
// MOBILEGL_IPC_SURFACE=host: what the client's DEFAULT framebuffer means while a host-framed
// surface is current. Zero everywhere else, because the driver's own 0 IS the EGL surface
// 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;
@@ -0,0 +1,208 @@
// MobileGL - MobileGL/MG_Backend/DirectGLES/HostFrameTarget.cpp
// Copyright (c) 2025-2026 MobileGL-Dev
// Licensed under the GNU Lesser General Public License v3.0:
// https://www.gnu.org/licenses/gpl-3.0.txt
// https://www.gnu.org/licenses/lgpl-3.0.txt
// SPDX-License-Identifier: LGPL-3.0-only
// End of Source File Header
#include "HostFrameTarget.h"
#include "DirectGLES.h"
#include "Managers.h"
#if MOBILEGL_BUILD_DISAGGREGATED && defined(__ANDROID__)
#include <android/hardware_buffer.h>
#include <cstring>
#include <format>
namespace MobileGL::MG_Backend::DirectGLES {
namespace {
// The four entry points this is spelled in are optional everywhere: the loader's own
// tables do not carry them (a missing EGL function there is MGLOG_F), so the extension
// strings decide first and the pointers are taken only once they have.
using GetNativeClientBufferFn = EGLClientBuffer (*)(const struct AHardwareBuffer*);
using CreateImageFn = EGLImageKHR (*)(EGLDisplay, EGLContext, EGLenum, EGLClientBuffer, const EGLint*);
using DestroyImageFn = EGLBoolean (*)(EGLDisplay, EGLImageKHR);
using ImageTargetRenderbufferFn = void (*)(GLenum, GLeglImageOES);
Bool HasExtensionWord(const char* list, const char* word) {
if (list == nullptr) return false;
const SizeT n = std::strlen(word);
for (const char* at = std::strstr(list, word); at != nullptr; at = std::strstr(at + 1, word)) {
const Bool startOk = at == list || at[-1] == ' ';
const Bool endOk = !at[n] || at[n] == ' ';
if (startOk && endOk) return true;
}
return false;
}
struct EntryPoints {
GetNativeClientBufferFn GetNativeClientBuffer = nullptr;
CreateImageFn CreateImage = nullptr;
DestroyImageFn DestroyImage = nullptr;
ImageTargetRenderbufferFn TargetRenderbuffer = nullptr;
};
// Resolved once per process and cached together with the refusal: a driver that lacks one
// of these does not grow it later, and the answer names what is missing.
const EntryPoints& Resolved(String& why) {
static EntryPoints points;
static Bool resolved = false;
static String refusal;
if (!resolved) {
resolved = true;
if (!g_EGLFuncs.eglGetProcAddress || !g_EGLFuncs.eglQueryString || !g_EGLFuncs.eglGetCurrentDisplay ||
!g_GLESFuncs.glGetString) {
refusal = "the loader has no eglGetProcAddress/eglQueryString/eglGetCurrentDisplay/glGetString";
} else {
const char* egl = g_EGLFuncs.eglQueryString(g_EGLFuncs.eglGetCurrentDisplay(), EGL_EXTENSIONS);
const char* gl = reinterpret_cast<const char*>(g_GLESFuncs.glGetString(GL_EXTENSIONS));
if (!HasExtensionWord(egl, "EGL_ANDROID_get_native_client_buffer")) {
refusal = "EGL_ANDROID_get_native_client_buffer is not advertised";
} else if (!HasExtensionWord(egl, "EGL_KHR_image_base")) {
refusal = "EGL_KHR_image_base is not advertised";
} else if (!HasExtensionWord(gl, "GL_OES_EGL_image")) {
refusal = "GL_OES_EGL_image is not advertised";
} else {
points.GetNativeClientBuffer = reinterpret_cast<GetNativeClientBufferFn>(
g_EGLFuncs.eglGetProcAddress("eglGetNativeClientBufferANDROID"));
points.CreateImage =
reinterpret_cast<CreateImageFn>(g_EGLFuncs.eglGetProcAddress("eglCreateImageKHR"));
points.DestroyImage =
reinterpret_cast<DestroyImageFn>(g_EGLFuncs.eglGetProcAddress("eglDestroyImageKHR"));
points.TargetRenderbuffer = reinterpret_cast<ImageTargetRenderbufferFn>(
g_EGLFuncs.eglGetProcAddress("glEGLImageTargetRenderbufferStorageOES"));
if (points.GetNativeClientBuffer == nullptr || points.CreateImage == nullptr ||
points.DestroyImage == nullptr || points.TargetRenderbuffer == nullptr) {
refusal = "eglGetProcAddress gave no eglGetNativeClientBufferANDROID / eglCreateImageKHR / "
"eglDestroyImageKHR / glEGLImageTargetRenderbufferStorageOES";
points = EntryPoints{};
}
}
}
}
why = refusal;
return points;
}
void DrainGLErrors() {
if (!g_GLESFuncs.glGetError) return;
for (Uint guard = 0; guard < 16 && g_GLESFuncs.glGetError() != GL_NO_ERROR; ++guard) {
}
}
}
Bool HostFrameTargetSupported(String& why) {
const EntryPoints& points = Resolved(why);
return points.GetNativeClientBuffer != nullptr;
}
Bool HostFrameTargetCreate(const struct AHardwareBuffer* buffer, HostFrameTarget& target, String& why) {
target = HostFrameTarget{};
if (buffer == nullptr) {
why = "no buffer";
return false;
}
const EntryPoints& points = Resolved(why);
if (points.GetNativeClientBuffer == nullptr) return false;
if (!g_GLESFuncs.glGenRenderbuffers || !g_GLESFuncs.glBindRenderbuffer || !g_GLESFuncs.glGenFramebuffers ||
!g_GLESFuncs.glBindFramebuffer || !g_GLESFuncs.glFramebufferRenderbuffer ||
!g_GLESFuncs.glCheckFramebufferStatus) {
why = "the loader has no glGenRenderbuffers/glBindRenderbuffer/glGenFramebuffers/glBindFramebuffer/"
"glFramebufferRenderbuffer/glCheckFramebufferStatus";
return false;
}
AHardwareBuffer_Desc desc{};
AHardwareBuffer_describe(buffer, &desc);
DrainGLErrors();
const EGLClientBuffer clientBuffer = points.GetNativeClientBuffer(buffer);
if (clientBuffer == nullptr) {
why = "eglGetNativeClientBufferANDROID returned null";
return false;
}
const EGLint imageAttribs[] = {EGL_IMAGE_PRESERVED_KHR, EGL_TRUE, EGL_NONE};
const EGLImageKHR image =
points.CreateImage(g_EGLFuncs.eglGetCurrentDisplay(), EGL_NO_CONTEXT, EGL_NATIVE_BUFFER_ANDROID,
clientBuffer, imageAttribs);
if (image == EGL_NO_IMAGE_KHR) {
why = "eglCreateImageKHR(EGL_NATIVE_BUFFER_ANDROID) refused the host frame";
return false;
}
GLuint renderbuffer = 0;
g_GLESFuncs.glGenRenderbuffers(1, &renderbuffer);
g_GLESFuncs.glBindRenderbuffer(GL_RENDERBUFFER, renderbuffer);
points.TargetRenderbuffer(GL_RENDERBUFFER, reinterpret_cast<GLeglImageOES>(image));
const GLenum renderbufferError = g_GLESFuncs.glGetError ? g_GLESFuncs.glGetError() : GL_NO_ERROR;
if (renderbufferError != GL_NO_ERROR) {
why = std::format("glEGLImageTargetRenderbufferStorageOES -> 0x{:04x}", renderbufferError);
g_GLESFuncs.glDeleteRenderbuffers(1, &renderbuffer);
points.DestroyImage(g_EGLFuncs.eglGetCurrentDisplay(), image);
return false;
}
GLuint framebuffer = 0;
g_GLESFuncs.glGenFramebuffers(1, &framebuffer);
g_GLESFuncs.glBindFramebuffer(GL_FRAMEBUFFER, framebuffer);
g_GLESFuncs.glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, renderbuffer);
const GLenum status = g_GLESFuncs.glCheckFramebufferStatus(GL_FRAMEBUFFER);
if (status != GL_FRAMEBUFFER_COMPLETE) {
why = std::format("the host frame as a color attachment -> framebuffer status 0x{:04x}", status);
g_GLESFuncs.glDeleteFramebuffers(1, &framebuffer);
g_GLESFuncs.glDeleteRenderbuffers(1, &renderbuffer);
points.DestroyImage(g_EGLFuncs.eglGetCurrentDisplay(), image);
return false;
}
target.Image = image;
target.Renderbuffer = renderbuffer;
target.Framebuffer = framebuffer;
target.Width = desc.width;
target.Height = desc.height;
MGLOG_I("host frame target: %ux%d as framebuffer %u (stride %u, format 0x%x)", desc.width, desc.height,
framebuffer, desc.stride, desc.format);
return true;
}
void HostFrameTargetBind(const HostFrameTarget& target) {
if (target.Framebuffer == 0) return;
// THROUGH THE ENGINE'S SHADOW, never raw: a raw bind would leave the shadow claiming
// the previous framebuffer and false-skip the next re-bind (FramebufferImpl, Managers.h).
FramebufferImpl::BindFramebufferId(GL_FRAMEBUFFER, target.Framebuffer);
}
void HostFrameTargetDestroy(HostFrameTarget& target) {
if (target.Framebuffer != 0 && g_GLESFuncs.glDeleteFramebuffers)
g_GLESFuncs.glDeleteFramebuffers(1, &target.Framebuffer);
if (target.Renderbuffer != 0 && g_GLESFuncs.glDeleteRenderbuffers)
g_GLESFuncs.glDeleteRenderbuffers(1, &target.Renderbuffer);
if (target.Image != nullptr) {
String why;
const EntryPoints& points = Resolved(why);
if (points.DestroyImage != nullptr && g_EGLFuncs.eglGetCurrentDisplay)
points.DestroyImage(g_EGLFuncs.eglGetCurrentDisplay(), static_cast<EGLImageKHR>(target.Image));
}
target = HostFrameTarget{};
}
}
#else // !(MOBILEGL_BUILD_DISAGGREGATED && __ANDROID__)
namespace MobileGL::MG_Backend::DirectGLES {
Bool HostFrameTargetSupported(String& why) {
why = "host frames are a disaggregated Android path";
return false;
}
Bool HostFrameTargetCreate(const struct AHardwareBuffer*, HostFrameTarget&, String& why) {
why = "host frames are a disaggregated Android path";
return false;
}
void HostFrameTargetBind(const HostFrameTarget&) {}
void HostFrameTargetDestroy(HostFrameTarget& target) { target = HostFrameTarget{}; }
}
#endif
@@ -0,0 +1,52 @@
// MobileGL - MobileGL/MG_Backend/DirectGLES/HostFrameTarget.h
// Copyright (c) 2025-2026 MobileGL-Dev
// Licensed under the GNU Lesser General Public License v3.0:
// https://www.gnu.org/licenses/gpl-3.0.txt
// https://www.gnu.org/licenses/lgpl-3.0.txt
// SPDX-License-Identifier: LGPL-3.0-only
// End of Source File Header
#pragma once
#include <Includes.h>
#include <EGL/egl.h>
#include <EGL/eglext.h>
struct AHardwareBuffer;
namespace MobileGL::MG_Backend::DirectGLES {
// THE FRAME THE DISPLAY HOST IS ABOUT TO SCAN OUT, AS A DRAW TARGET.
//
// The display host (the Android side that owns the screen) allocates its frames itself and
// offers each one over a socket as an AHardwareBuffer. That is not a convenience: measured
// on the device, AHardwareBuffer_createFromHandle accepts an AHardwareBuffer this side
// allocated and refuses one the display queue handed over (gralloc BAD_VALUE), so the frames
// a render server can draw into are the ones the host made for it.
//
// What this makes of such a frame: an EGLImage the driver accepts as a renderbuffer, and a
// framebuffer that is the drawing target while that frame is the current one. None of
// Android's window machinery is involved - no ANativeWindow, no SurfaceFlinger - which is
// the point: the host puts the frame on the glass when this side says it is drawn.
struct HostFrameTarget {
void* Image = nullptr; // EGLImageKHR; opaque here so this header stays free of EGL types
Uint Renderbuffer = 0;
Uint Framebuffer = 0;
Uint Width = 0;
Uint Height = 0;
};
// Whether the driver advertises what this is spelled in. False is answered with the missing
// name in `why`, never an abort: a server that cannot take host frames has to be able to
// say so.
Bool HostFrameTargetSupported(String& why);
// Imports `buffer` as a render target. On failure `target` is left empty and `why` says
// which call refused; no GL name is leaked.
Bool HostFrameTargetCreate(const struct AHardwareBuffer* buffer, HostFrameTarget& target, String& why);
// Binds the target as the current draw framebuffer, called when its frame becomes current.
void HostFrameTargetBind(const HostFrameTarget& target);
// Drops the GL names and the EGLImage. The AHardwareBuffer belongs to the bridge, which
// releases it; this never touches it.
void HostFrameTargetDestroy(HostFrameTarget& target);
}
+168 -379
View File
@@ -206,7 +206,6 @@ namespace MobileGL::MG_Backend::DirectGLES {
#else
Bool InProcessTeardown() { return g_processTeardown; }
#endif
Bool InProcessExit() { return g_processTeardown; }
void EnsureProcessTeardownSentinel() {
std::call_once(g_teardownSentinelOnce,
[] { std::atexit(+[] { g_processTeardown = true; }); });
@@ -417,41 +416,17 @@ namespace MobileGL::MG_Backend::DirectGLES {
// the textures they view, framebuffers before their attachments, VAOs before the buffers they
// fetch from), so the last reference to each twin goes here and its destructor - answered
// InProcessTeardown() - touches neither the driver nor another TU's statics.
//
// P14 S6: "EVERY TABLE" IS NOW "EVERY BUCKET OF THIS SESSION". The tables are keyed by
// {session, share group}, so the same rebuild of the eight registries would take a NEIGHBOUR
// session's twins with it - and with S2's in-process supervisor serving several sessions at
// once that is not a hypothetical: this runs from ~BackendObject_DirectGLES, on the apply
// thread of the session that is ending. So the drop is scoped to the calling thread's
// session when it has one, and is the process-wide drop (key {0, 0} and nothing else) when it
// does not - which is the shape every unit case and the fork-worker world still has.
void DropEveryTwinForEndedServerSession() {
if (g_processTeardown) return;
g_serverSessionTwinTeardown = true;
TwinKey key;
if (CurrentTwinKey(&key) && key.SessionKey != 0) {
Uint32 buckets = 0;
buckets += SamplerViewImpl::g_backendSamplerViews.DropBucketsOfSession(key.SessionKey);
buckets += FramebufferImpl::g_backendFramebufferObjects.DropBucketsOfSession(key.SessionKey);
buckets += VertexArrayImpl::g_backendVertexArrayObjects.DropBucketsOfSession(key.SessionKey);
buckets += PrgramImpl::g_backendProgramObjects.DropBucketsOfSession(key.SessionKey);
buckets += SamplerImpl::g_backendSamplerObjects.DropBucketsOfSession(key.SessionKey);
buckets += TextureImpl::g_backendTextureObjects.DropBucketsOfSession(key.SessionKey);
buckets += RenderbufferImpl::g_backendRenderbufferObjects.DropBucketsOfSession(key.SessionKey);
buckets += BufferImpl::g_backendBufferResources.DropBucketsOfSession(key.SessionKey);
MGLOG_I("DirectGLES: the ended server session dropped %u twin group(s) across eight kinds "
"(no driver call); the other sessions in this process keep theirs",
buckets);
} else {
SamplerViewImpl::g_backendSamplerViews.ResetBuckets();
FramebufferImpl::g_backendFramebufferObjects.ResetBuckets();
VertexArrayImpl::g_backendVertexArrayObjects.ResetBuckets();
PrgramImpl::g_backendProgramObjects.ResetBuckets();
SamplerImpl::g_backendSamplerObjects.ResetBuckets();
TextureImpl::g_backendTextureObjects.ResetBuckets();
RenderbufferImpl::g_backendRenderbufferObjects.ResetBuckets();
BufferImpl::g_backendBufferResources.ResetBuckets();
}
SamplerViewImpl::g_backendSamplerViews = {};
FramebufferImpl::g_backendFramebufferObjects = {};
VertexArrayImpl::g_backendVertexArrayObjects = {};
PrgramImpl::g_backendProgramObjects = {};
SamplerImpl::g_backendSamplerObjects = {};
TextureImpl::g_backendTextureObjects = {};
RenderbufferImpl::g_backendRenderbufferObjects = {};
BufferImpl::g_backendBufferResources = {};
// P12 review fix (major): AND THE UNIT SHADOWS THAT POINT AT THEM. A texture or sampler twin
// scrubs itself out of g_boundTexturesCache / g_boundSamplersCache in its destructor - but
// not under InProcessTeardown(), which answered true for every twin just dropped. Left
@@ -463,6 +438,8 @@ namespace MobileGL::MG_Backend::DirectGLES {
TextureImpl::g_activeTextureUnit = 0;
SamplerImpl::g_boundSamplersCache = {};
g_serverSessionTwinTeardown = false;
MGLOG_I("DirectGLES: the ended server session's twins are dropped (every kind, no driver call); the next "
"session in this process starts from empty twin tables");
}
#endif
@@ -1084,14 +1061,14 @@ namespace MobileGL::MG_Backend::DirectGLES {
const char* label = "";
};
// THE RINGS ARE PER NATIVE CONTEXT. Their slots are reclaimed by frame marks recorded at
// Present, which say "everything this context wrote before its fence N is done once N is".
// One process-wide set used to be shared by every session's contexts: a fence from one
// context retired bytes another context's not-yet-executed copies still had to read
// (a glTexSubImage from the unpack ring is a deferred GPU read), and the next session's
// staging overwrote them - its pixels landed, at the wrong offsets, in the first one's
// textures. With one set per context, a context's bytes wait for that context's own
// fence. (The buffers themselves are shared objects; only who stages into them is split.)
PersistentRing g_uboRing{{}, {}, {}, kUboRingInitialBytes, kUboRingMaxBytes, 0, "Global-UBO ring"};
PersistentRing g_unpackRing{{},
{},
{},
kUnpackRingInitialBytes,
kUnpackRingMaxBytes,
kUnpackRingAlignment,
"Texture unpack ring"};
// Staging ring for app buffer updates whose destination store may still be
// referenced by in-flight GPU work. Mali's glBufferSubData resolves that WAR
// hazard by BLOCKING in the call (osup_sync_object_wait) until every
@@ -1100,67 +1077,13 @@ namespace MobileGL::MG_Backend::DirectGLES {
// chunks stream in). Staging the bytes here and issuing a
// glCopyBufferSubData instead keeps the hazard on the GPU timeline where it
// is just job ordering, and the CPU never waits.
struct RingSet {
PersistentRing ubo{{}, {}, {}, kUboRingInitialBytes, kUboRingMaxBytes, 0, "Global-UBO ring"};
PersistentRing unpack{{},
{},
{},
kUnpackRingInitialBytes,
kUnpackRingMaxBytes,
kUnpackRingAlignment,
"Texture unpack ring"};
PersistentRing upload{{},
{},
{},
kUploadRingInitialBytes,
kUploadRingMaxBytes,
kUploadRingAlignment,
"Buffer upload ring"};
RingSet();
~RingSet();
RingSet(const RingSet&) = delete;
RingSet& operator=(const RingSet&) = delete;
};
// A dead context's ring buffers: shared objects, so they outlive it; deleted at the next
// Present of any context of the same share-group generation.
struct OrphanRingBuffer {
Uint id = 0;
Uint contextGeneration = 0;
};
std::mutex g_orphanRingBuffersMutex;
Vector<OrphanRingBuffer>& OrphanRingBuffers() {
static auto* orphans = new Vector<OrphanRingBuffer>();
return *orphans;
}
// Each set's generations start in a range of their own: a per-program slot cache keyed
// by (generation, offset) must never take one context's ring for another's.
std::atomic<Uint32> g_ringGenerationBases{0};
RingSet::RingSet() {
const Uint32 base = (g_ringGenerationBases.fetch_add(1, std::memory_order_relaxed) + 1) << 12;
ubo.store.generation = base;
unpack.store.generation = base;
upload.store.generation = base;
}
RingSet::~RingSet() {
const std::lock_guard<std::mutex> lock(g_orphanRingBuffersMutex);
for (const PersistentRing* ring : {&ubo, &unpack, &upload}) {
if (ring->store.id != 0) {
OrphanRingBuffers().push_back({ring->store.id, ring->store.contextGeneration});
}
for (const auto& retired : ring->retired) {
if (retired.id != 0) OrphanRingBuffers().push_back({retired.id, retired.contextGeneration});
}
}
}
DirectGLES::PerNativeContext<RingSet> g_ringSets;
PersistentRing& UboRing() { return g_ringSets.Current().ubo; }
PersistentRing& UnpackRing() { return g_ringSets.Current().unpack; }
PersistentRing& UploadRing() { return g_ringSets.Current().upload; }
PersistentRing g_uploadRing{{},
{},
{},
kUploadRingInitialBytes,
kUploadRingMaxBytes,
kUploadRingAlignment,
"Buffer upload ring"};
// The ES context the ring's id/map belonged to is gone (or was never
// seen): drop every handle without GL calls and re-arm creation. The
@@ -1438,7 +1361,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
Bool UploadRingUsableNow() {
if (MG_Config::Features.EsprytDisableUploadRing) return false;
if (!g_GLESFuncs.glCopyBufferSubData) return false;
return RingAvailable(UploadRing());
return RingAvailable(g_uploadRing);
}
// A partial range below this goes through the staging ring instead of a
@@ -1587,9 +1510,9 @@ namespace MobileGL::MG_Backend::DirectGLES {
}
SizeT ringOffset = 0;
if (ringUsable && size <= kUploadRingMaxBytes &&
RingAllocate(UploadRing(), size, ringOffset)) {
Memcpy(UploadRing().store.mappedPtr + ringOffset, hostBase + start, size);
BindBufferId(GL_COPY_READ_BUFFER, UploadRing().store.id);
RingAllocate(g_uploadRing, size, ringOffset)) {
Memcpy(g_uploadRing.store.mappedPtr + ringOffset, hostBase + start, size);
BindBufferId(GL_COPY_READ_BUFFER, g_uploadRing.store.id);
BindBufferId(GL_COPY_WRITE_BUFFER, resource.id);
g_GLESFuncs.glCopyBufferSubData(GL_COPY_READ_BUFFER, GL_COPY_WRITE_BUFFER,
(GLintptr)ringOffset, (GLintptr)start, (GLsizeiptr)size);
@@ -1666,9 +1589,9 @@ namespace MobileGL::MG_Backend::DirectGLES {
}
SizeT ringOffset = 0;
if (ringUsable && size <= kUploadRingMaxBytes &&
RingAllocate(UploadRing(), size, ringOffset)) {
Memcpy(UploadRing().store.mappedPtr + ringOffset, write.bytes.data(), size);
BindBufferId(GL_COPY_READ_BUFFER, UploadRing().store.id);
RingAllocate(g_uploadRing, size, ringOffset)) {
Memcpy(g_uploadRing.store.mappedPtr + ringOffset, write.bytes.data(), size);
BindBufferId(GL_COPY_READ_BUFFER, g_uploadRing.store.id);
BindBufferId(GL_COPY_WRITE_BUFFER, resource.id);
g_GLESFuncs.glCopyBufferSubData(GL_COPY_READ_BUFFER, GL_COPY_WRITE_BUFFER,
(GLintptr)ringOffset, (GLintptr)write.offset,
@@ -1769,7 +1692,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
Bool UploadRingUsableNow() {
if (MG_Config::Features.EsprytDisableUploadRing) return false;
if (!g_GLESFuncs.glCopyBufferSubData) return false;
return RingAvailable(UploadRing());
return RingAvailable(g_uploadRing);
}
// A partial range below this goes through the staging ring instead of a
@@ -1875,9 +1798,9 @@ namespace MobileGL::MG_Backend::DirectGLES {
}
SizeT ringOffset = 0;
if (ringUsable && size <= kUploadRingMaxBytes &&
RingAllocate(UploadRing(), size, ringOffset)) {
Memcpy(UploadRing().store.mappedPtr + ringOffset, bufferObject.MappedData() + start, size);
BindBufferId(GL_COPY_READ_BUFFER, UploadRing().store.id);
RingAllocate(g_uploadRing, size, ringOffset)) {
Memcpy(g_uploadRing.store.mappedPtr + ringOffset, bufferObject.MappedData() + start, size);
BindBufferId(GL_COPY_READ_BUFFER, g_uploadRing.store.id);
BindBufferId(GL_COPY_WRITE_BUFFER, resource.id);
g_GLESFuncs.glCopyBufferSubData(GL_COPY_READ_BUFFER, GL_COPY_WRITE_BUFFER,
(GLintptr)ringOffset, (GLintptr)start, (GLsizeiptr)size);
@@ -1921,9 +1844,9 @@ namespace MobileGL::MG_Backend::DirectGLES {
}
SizeT ringOffset = 0;
if (ringUsable && size <= kUploadRingMaxBytes &&
RingAllocate(UploadRing(), size, ringOffset)) {
Memcpy(UploadRing().store.mappedPtr + ringOffset, write.bytes.data(), size);
BindBufferId(GL_COPY_READ_BUFFER, UploadRing().store.id);
RingAllocate(g_uploadRing, size, ringOffset)) {
Memcpy(g_uploadRing.store.mappedPtr + ringOffset, write.bytes.data(), size);
BindBufferId(GL_COPY_READ_BUFFER, g_uploadRing.store.id);
BindBufferId(GL_COPY_WRITE_BUFFER, resource.id);
g_GLESFuncs.glCopyBufferSubData(GL_COPY_READ_BUFFER, GL_COPY_WRITE_BUFFER,
(GLintptr)ringOffset, (GLintptr)write.offset,
@@ -3060,67 +2983,6 @@ namespace MobileGL::MG_Backend::DirectGLES {
return imported;
}
// The POST's second round: the CPU writes region 1 through the held lock only now, after
// the import and a GPU use of it, and reads region 4 (the first round's fill) back into
// its cache; a second dispatch copies region 1 out and overwrites region 4. Appends its
// counts to `detail`.
Bool SelfTestExternalSteady(GLuint imported, GLuint out, void* heldPtr, char* detail, SizeT detailBytes) {
constexpr Uint32 kWords = 1024;
constexpr Uint32 kSteadyAtWord = kWords; // region 1
constexpr Uint32 kFillAtWord = 4 * kWords; // region 4
auto* held = static_cast<volatile Uint32*>(heldPtr);
Uint32 cached = 0;
for (Uint32 i = 0; i < kWords; ++i) {
held[kSteadyAtWord + i] = 0xA5000000u ^ (i * 40503u);
cached ^= held[kFillAtWord + i];
}
(void)cached;
static const char* kSource =
"#version 310 es\n"
"layout(local_size_x = 64) in;\n"
"layout(std430, binding = 0) buffer Ext { uint w[]; } ext;\n"
"layout(std430, binding = 1) buffer Out { uint w[]; } outb;\n"
"void main() {\n"
" uint i = gl_GlobalInvocationID.x;\n"
" outb.w[i] = ext.w[1024u + i];\n"
" ext.w[4096u + i] = 0x3D5EA11Eu ^ i;\n"
"}\n";
const GLuint program = g_GLESFuncs.glCreateShaderProgramv(GL_COMPUTE_SHADER, 1, &kSource);
GLint linked = 0;
if (program != 0) g_GLESFuncs.glGetProgramiv(program, GL_LINK_STATUS, &linked);
const SizeT used = std::strlen(detail);
if (!linked) {
if (program != 0) g_GLESFuncs.glDeleteProgram(program);
std::snprintf(detail + used, detailBytes - used, "; steady: the second program did not link");
return false;
}
g_GLESFuncs.glUseProgram(program);
g_GLESFuncs.glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 0, imported);
g_GLESFuncs.glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 1, out);
g_GLESFuncs.glMemoryBarrier(0x00004000 /*GL_CLIENT_MAPPED_BUFFER_BARRIER_BIT_EXT*/);
g_GLESFuncs.glDispatchCompute(kWords / 64, 1, 1);
g_GLESFuncs.glMemoryBarrier(GL_BUFFER_UPDATE_BARRIER_BIT | GL_SHADER_STORAGE_BARRIER_BIT |
0x00004000 /*GL_CLIENT_MAPPED_BUFFER_BARRIER_BIT_EXT*/);
g_GLESFuncs.glFinish();
Uint32 steadyRead = 0, steadySaw = 0;
for (Uint32 i = 0; i < kWords; ++i)
if (held[kFillAtWord + i] == (0x3D5EA11Eu ^ i)) ++steadySaw;
g_GLESFuncs.glBindBuffer(GL_SHADER_STORAGE_BUFFER, out);
const auto* copied = static_cast<const Uint32*>(
g_GLESFuncs.glMapBufferRange(GL_SHADER_STORAGE_BUFFER, 0, kWords * 4, GL_MAP_READ_BIT));
if (copied != nullptr) {
for (Uint32 i = 0; i < kWords; ++i)
if (copied[i] == (0xA5000000u ^ (i * 40503u))) ++steadyRead;
g_GLESFuncs.glUnmapBuffer(GL_SHADER_STORAGE_BUFFER);
}
g_GLESFuncs.glDeleteProgram(program);
std::snprintf(detail + used, detailBytes - used,
"; with the import in use, GPU read %u/%u words the CPU wrote after it, GPU write "
"seen through the held lock %u/%u words",
steadyRead, kWords, steadySaw, kWords);
return steadyRead == kWords && steadySaw == kWords;
}
// THE POST (B2, the standing rule: decide by probe, never by driver name). The AHB API
// promises CPU coherence only across an unlock/lock; T0 keeps the client's lock for the
// store's life, so the pattern it depends on is exactly what this exercises, on this
@@ -3131,9 +2993,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
// gpu - a compute dispatch copies that pattern out of the import (the GPU read) and
// fills another region of it (the GPU write);
// back - after glFinish the fill is read through the HELD pointer and the copy is
// read back from the dispatch's output;
// steady - the same again with bytes the CPU wrote AFTER the import and its first GPU
// use (VkBufferManager::SelfTestWireImport says why the first round is not enough).
// read back from the dispatch's output.
// In a throwaway ES 3.1 pbuffer context, so none of this context's state or Espryt's
// binding caches is disturbed; the caller's bind is restored before returning.
Bool Ops_H_SelfTestExternal(char* whyOut, Uint64 whyBytes) {
@@ -3186,7 +3046,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
GLuint out = 0, program = 0;
void* hostMap = nullptr;
const GLuint imported = ImportAhbAsBuffer(held.ahb, kBytes, &hostMap, why, /*throwaway=*/true);
char detail[512] = {};
char detail[256] = {};
if (imported == 0) {
std::snprintf(detail, sizeof(detail), "import: %s", why.c_str());
} else if (std::memcmp(hostMap, pattern.data(), kWords * 4) != 0) {
@@ -3236,7 +3096,6 @@ namespace MobileGL::MG_Backend::DirectGLES {
"64 KiB AHB, lock held throughout: host map read ok, GPU read %u/%u words of "
"the CPU's pattern, GPU write seen through the held lock %u/%u words",
gpuRead, kWords, heldSaw, kWords);
if (ok) ok = SelfTestExternalSteady(imported, out, held.ptr, detail, sizeof(detail));
}
}
if (program != 0) g_GLESFuncs.glDeleteProgram(program);
@@ -3324,6 +3183,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
case MG_Pipe::MGPipeResourceTarget::Tex2DMSArray: return TextureTarget::Texture2DMultisampleArray;
case MG_Pipe::MGPipeResourceTarget::TexRect: return TextureTarget::TextureRectangle;
case MG_Pipe::MGPipeResourceTarget::TexBuffer: return TextureTarget::TextureBuffer;
case MG_Pipe::MGPipeResourceTarget::TexExternalOES: return TextureTarget::TextureExternalOES;
default: return TextureTarget::Unknown;
}
}
@@ -3927,18 +3787,6 @@ namespace MobileGL::MG_Backend::DirectGLES {
g_hasDeferredBufferReleases.store(false, std::memory_order_release);
}
void OnServerSessionEndedWithOthersLive() {
#if MOBILEGL_PIPE_PUSH
// Only what belongs to the ending session: its staged bytes (both stores are
// session-scoped). The rings, the ops table and the buffer generation are the
// process's and every other session's GL buffers are still alive in the shared group.
MGL_SERVER_STAGED_DROP_ALL();
#if MOBILEGL_BUILD_DISAGGREGATED
MG_Remote::Server::ServerStagedTexture().DropAll();
#endif
#endif
}
void OnBackendContextDestroyed() {
UnregisterBufferBackendOps(); // also bumps the buffer-mutation epoch
++g_bufferContextGeneration;
@@ -3950,8 +3798,8 @@ namespace MobileGL::MG_Backend::DirectGLES {
InvalidatePixelBufferBindingCaches();
// The rings' ids and persistent maps died with the context; drop the
// handles (no GL) and let the next draw / texture upload recreate them.
ResetRingForNewContext(UboRing());
ResetRingForNewContext(UnpackRing());
ResetRingForNewContext(g_uboRing);
ResetRingForNewContext(g_unpackRing);
#if MOBILEGL_PIPE_PUSH
// R-11's server copies die with the context for the same reason the rings' ids do:
// the resource twins they are keyed by are about to be rebuilt against a new
@@ -4960,23 +4808,9 @@ namespace MobileGL::MG_Backend::DirectGLES {
return true;
}
void DeleteOrphanRingBuffers() {
const std::lock_guard<std::mutex> lock(g_orphanRingBuffersMutex);
auto& orphans = OrphanRingBuffers();
if (orphans.empty()) return;
for (const OrphanRingBuffer& orphan : orphans) {
// A buffer of a share group that is gone was reclaimed with it.
if (orphan.contextGeneration != g_bufferContextGeneration) continue;
ScrubBufferBindingShadowsForId(orphan.id);
g_GLESFuncs.glDeleteBuffers(1, &orphan.id);
}
orphans.clear();
}
// Present()-time upkeep shared by both rings.
void RingOnPresent(PersistentRing& ring) {
if (!CanTouchGLNow()) return;
DeleteOrphanRingBuffers();
// Delete grown-away stores the GPU is provably done with.
const Uint64 completed = DirectGLES::CompletedFrameSerial();
@@ -5021,36 +4855,36 @@ namespace MobileGL::MG_Backend::DirectGLES {
Bool UboRingAvailable() {
if (MG_Config::Features.EsprytDisableUboRing) return false;
return RingAvailable(UboRing());
return RingAvailable(g_uboRing);
}
Bool UboRingAllocate(SizeT size, SizeT& outOffset) { return RingAllocate(UboRing(), size, outOffset); }
Bool UboRingAllocate(SizeT size, SizeT& outOffset) { return RingAllocate(g_uboRing, size, outOffset); }
void* UboRingMappedPtr() { return UboRing().store.mappedPtr; }
Uint UboRingBufferId() { return UboRing().store.id; }
Uint32 UboRingGeneration() { return UboRing().store.generation; }
void* UboRingMappedPtr() { return g_uboRing.store.mappedPtr; }
Uint UboRingBufferId() { return g_uboRing.store.id; }
Uint32 UboRingGeneration() { return g_uboRing.store.generation; }
void UboRingOnPresent() { RingOnPresent(UboRing()); }
void UboRingOnPresent() { RingOnPresent(g_uboRing); }
Bool UnpackRingAvailable() {
if (MG_Config::Features.EsprytDisableUnpackRing) return false;
return RingAvailable(UnpackRing());
return RingAvailable(g_unpackRing);
}
Bool UnpackRingAllocate(SizeT size, SizeT& outOffset) {
// A request the ring could never satisfy even empty would otherwise walk
// the whole grow/drain ladder before failing.
if (size > kUnpackRingMaxBytes) return false;
return RingAllocate(UnpackRing(), size, outOffset);
return RingAllocate(g_unpackRing, size, outOffset);
}
void* UnpackRingMappedPtr() { return UnpackRing().store.mappedPtr; }
Uint UnpackRingBufferId() { return UnpackRing().store.id; }
void* UnpackRingMappedPtr() { return g_unpackRing.store.mappedPtr; }
Uint UnpackRingBufferId() { return g_unpackRing.store.id; }
SizeT UnpackRingMaxBytes() { return kUnpackRingMaxBytes; }
void UnpackRingOnPresent() { RingOnPresent(UnpackRing()); }
void UnpackRingOnPresent() { RingOnPresent(g_unpackRing); }
void UploadRingOnPresent() { RingOnPresent(UploadRing()); }
void UploadRingOnPresent() { RingOnPresent(g_uploadRing); }
} // namespace BufferImpl
#if MOBILEGL_PIPE_PUSH
@@ -7588,10 +7422,6 @@ namespace MobileGL::MG_Backend::DirectGLES {
}
}
#if MOBILEGL_BUILD_DISAGGREGATED
// A shared image's EGLImage lives exactly as long as the name it was bound to.
m_sharedImage = nullptr;
#endif
g_GLESFuncs.glGenTextures(1, &m_backendTextureId);
m_contextGeneration = g_backendContextGeneration;
if (m_backendTextureId == 0) {
@@ -8842,92 +8672,6 @@ namespace MobileGL::MG_Backend::DirectGLES {
#define MGB_STORAGE_KIND(obj) ((obj)->GetStorageType())
#endif
#if MOBILEGL_BUILD_DISAGGREGATED
// SHARED IMAGES (docs/Disaggregated/notes/anland/plan-ahb-dmabuf.md). The client defined
// level 0 as WxH RGBA8 with no data and then attached the image; the record's descriptor
// still says so, but the texels are the image's, so nothing below may allocate or upload.
Bool BackendTextureObject::SyncSharedImageStorage(const MG_Pipe::MGPipeResourceRecord& record) {
const Uint64 imageId = record.SharedImageId;
if (imageId == 0) {
// Respecified away from the image. The ES name is an EGLImage sibling, which must not
// be redefined in place: the immutable flag sends the normal path through
// RecreateBackendTexture, and the EGLImage goes with the name it was bound to.
m_sharedImageId = 0;
m_isInitialized = false;
m_backendStorageImmutable = true;
return false;
}
// Sub-data aimed at the image is not replayed into it - the image is written by the
// producer's present - but it must still leave the pending set, or the per-draw clean
// gate (IsDrawSyncCleanByRecord) would never close.
const auto dropPendingUploads = [&record] {
if (record.PendingUploads.empty()) return;
MGLOG_W_ONCE("Shared image texture %u: sub-data on an attached shared image is dropped",
record.Desc.GlNameForDiag);
Vector<std::pair<Uint16, Uint16>> keys;
keys.reserve(record.PendingUploads.size());
for (const auto& pending : record.PendingUploads) {
keys.emplace_back(MG_Pipe::MGPipeSubDataUploadTargetOf(pending.UploadTarget), pending.Level);
}
for (const auto& key : keys) ConsumePipeTextureUpload(record.Desc.Resource, key.first, key.second);
};
// Steady state: bound to this image already (the serial moves with sub-data and with a
// metadata respecify, neither of which changes what the name samples). A failed bind is
// retried only once the record moves.
if (m_sharedImageId == imageId && m_isInitialized &&
(m_sharedImage != nullptr || m_syncedResourceSerial == record.Serial)) {
dropPendingUploads();
m_syncedResourceSerial = record.Serial;
return true;
}
// A fresh mutable name: the current one may hold immutable storage (which no EGLImage
// can replace) or another image's sibling. RecreateBackendTexture also moves the FBO
// twins' attachment generation and forces the parameter resync the new name needs.
RecreateBackendTexture();
m_sharedImage = nullptr;
m_sharedImageId = imageId;
m_isInitialized = true;
// Whatever comes next redefines storage through a re-mint (see the imageId == 0 arm).
m_backendStorageImmutable = true;
m_syncedResourceSerial = record.Serial;
dropPendingUploads();
const TextureTarget target = BufferImpl::StagedTextureTargetForPipeTarget(record.Desc.Target);
if (ConvertTextureTargetToBackendGLEnum(target) != GL_TEXTURE_2D) {
MGLOG_E_ONCE("Shared image texture %u: target %s cannot take an EGLImage; left empty",
record.Desc.GlNameForDiag, MG_Util::ConvertTextureTargetToString(target).c_str());
return true;
}
String why;
SharedImageImpl::EglImageRef image = SharedImageImpl::CreateEglImage(imageId, why);
if (image == nullptr) {
MGLOG_E_ONCE("Shared image texture %u: image %llu cannot be bound (%s); left empty",
record.Desc.GlNameForDiag, static_cast<unsigned long long>(imageId), why.c_str());
return true;
}
Bind(GL_TEXTURE_2D);
if (!SharedImageImpl::TargetBoundTexture2D(image)) {
MGLOG_E_ONCE("Shared image texture %u: glEGLImageTargetTexture2DOES refused image %llu; left empty",
record.Desc.GlNameForDiag, static_cast<unsigned long long>(imageId));
return true;
}
m_sharedImage = std::move(image);
// The shape the name now has: the descriptor's level 0, and that one level only.
m_prevTextureInfo = {static_cast<TextureInternalFormat>(record.Desc.InternalFormat),
record.Desc.Width,
record.Desc.Height,
record.Desc.Depth,
1,
0,
record.Desc.Samples,
record.Desc.FixedSampleLocations != 0};
return true;
}
#endif
void BackendTextureObject::SyncMipmapsToBackend(
const SharedPtr<MG_State::GLState::ITextureObject>& stateTextureObject) {
// P5e (tx2): null IS the by-handle arm once a handle has been noted on this twin;
@@ -8970,17 +8714,6 @@ namespace MobileGL::MG_Backend::DirectGLES {
}
#endif
#if MOBILEGL_BUILD_DISAGGREGATED
// SHARED IMAGES: ahead of the view test and of the staged-store and serial gates below,
// none of which knows the texels belong to an image - the staged store holds none of
// them, and the storage path would allocate fresh, empty storage over the image.
if (pushedStorage != nullptr && (pushedStorage->SharedImageId != 0 || m_sharedImageId != 0) &&
SyncSharedImageStorage(*pushedStorage)) {
// EVERY use, not only the attach (the draw-clean gates never pass a bound image):
// a write that landed since the last one is waited for on this context's GPU
// before the command this sync is for, and the session's frame notes the read.
if (m_sharedImage != nullptr) SharedImageImpl::AcquireForSampling(m_sharedImage);
return;
}
// P5e (tx2), CONTRACT-P5E §5.2 (scout G-S2-2): THE VIEW TEST MOVES BEHIND THE
// RECORD. `IsTextureView()` was the one frontend read this function made BEFORE it
// had resolved anything at all, and Desc.ViewOf is the carrier - it names the storage
@@ -9879,18 +9612,8 @@ namespace MobileGL::MG_Backend::DirectGLES {
// entry's rects are then read out of the SERVER'S WHOLE LEVEL IMAGE -
// which is what the derived pointer names - and those piece-relative
// offsets are precisely the ones that must not be used here.
//
// GATED ON regionsAddressable, NOT subRectEligible: the per-region arm
// for a level the GPU may have written (m_driverMayHoldGpuWrites below)
// reads MGB_RECT_SRC_PTR too, and it runs exactly when the union box is
// the whole level - which is what two or more slab pieces always add up
// to. Checked only under subRectEligible, a damage rect split across
// pieces kept the later pieces' run-relative offsets and read their
// rows from the top of the level image (KWin's wl_shm window textures:
// the panel repeated down the desktop). bpp is valid whenever the
// regions are addressable.
Bool pendingOffsetsAgree = true;
if (pendingUpload != nullptr && regionsAddressable && carriedLayoutApplies) {
if (pendingUpload != nullptr && subRectEligible && carriedLayoutApplies) {
for (const auto& region : pendingUpload->Regions) {
const SizeT derivedOffset = static_cast<SizeT>(region.Z) * levelSliceBytes +
static_cast<SizeT>(region.Y) * levelRowBytes +
@@ -10429,7 +10152,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
@@ -11560,9 +11283,45 @@ 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<GLint>(attachmentObject.GetTextureLevel()));
// THE TEXTURE'S OWN TARGET, not the attach target: an external texture is attached
// through the GL_TEXTURE_2D upload target (TextureEnumConverter maps 0x8D65 there so the
// attach validates), so glTextureTarget is never 0x8D65 here and the arms below were
// dead - kwin's framebuffers got a storage-less texture and every draw into them failed
// with GL_INVALID_FRAMEBUFFER_OPERATION.
const Bool externalTexture =
glTextureTarget == 0x8D65 || textureObject->GetTarget() == TextureTarget::TextureExternalOES;
if (externalTexture && 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 (externalTexture && 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<GLint>(attachmentObject.GetTextureLevel()));
}
}
} else if (attachmentObject.IsRenderbuffer()) {
const auto& renderbufferObject = attachmentObject.GetRenderbuffer();
@@ -11878,6 +11637,23 @@ namespace MobileGL::MG_Backend::DirectGLES {
// nothing here is the whole of the agreement. (The legacy arm does the same.)
return true;
}
// AN IMPORTED dma-buf AT A COLOUR POINT IS THE DISPLAY HOST'S FRAME. The client marks the
// texture it bound an imported EGLImage to as GL_TEXTURE_EXTERNAL_OES (TextureObject2D's
// target), the server never received that dma-buf's storage, and the compositor's
// framebuffer over it was incomplete (measured: status 0x8cd7, every draw
// GL_INVALID_FRAMEBUFFER_OPERATION). It is bound to the host frame canvas instead - the
// storage the display host's frames are copied out of at present - before any twin or
// storage sync, which have nothing to offer a texture with no storage.
if (surface.Kind == MG_Pipe::kMGPipeSurfaceKindTexture &&
surface.TextureTarget ==
static_cast<decltype(surface.TextureTarget)>(TextureTarget::TextureExternalOES)) {
if (g_hostFrameRenderbuffer == 0) (void)TakeHostFrameForExternalTexture(1440, 3200);
if (g_hostFrameRenderbuffer != 0) {
g_GLESFuncs.glFramebufferRenderbuffer(glFBOTarget, glBackendAttachment, GL_RENDERBUFFER,
g_hostFrameRenderbuffer);
return true;
}
}
if (surface.Kind == MG_Pipe::kMGPipeSurfaceKindTexture) {
// The record's handle is validated BEFORE the frontend is consulted (N-3): it is
// the untrusted half, the frontend cross-check below is the corroboration, and
@@ -11961,9 +11737,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<GLint>(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<GLint>(surface.Level));
}
}
return true;
}
@@ -13061,16 +12866,11 @@ namespace MobileGL::MG_Backend::DirectGLES {
namespace ScratchFBOImpl {
namespace {
// ONE SET PER NATIVE CONTEXT: a framebuffer belongs to the context that made it
// (DirectGLES.h, PerNativeContext), and so does the attachment shadow kept for it.
struct ScratchSet {
ScratchFramebuffer temp;
ScratchFramebuffer blitRead;
ScratchFramebuffer blitDraw;
Uint completeTinyFBOId = 0;
Uint completeTinyRBOId = 0;
};
PerNativeContext<ScratchSet> g_scratchSets;
ScratchFramebuffer g_tempFramebuffer;
ScratchFramebuffer g_blitReadFramebuffer;
ScratchFramebuffer g_blitDrawFramebuffer;
Uint g_completeTinyFBOId = 0;
Uint g_completeTinyRBOId = 0;
// Detach every point the shadow no longer vouches for. Used when the
// shadow is unknown (context reset, texture id deleted while attached).
@@ -13125,13 +12925,13 @@ namespace MobileGL::MG_Backend::DirectGLES {
} // namespace
ScratchFramebuffer& TempFramebuffer() {
return g_scratchSets.Current().temp;
return g_tempFramebuffer;
}
ScratchFramebuffer& BlitReadFramebuffer() {
return g_scratchSets.Current().blitRead;
return g_blitReadFramebuffer;
}
ScratchFramebuffer& BlitDrawFramebuffer() {
return g_scratchSets.Current().blitDraw;
return g_blitDrawFramebuffer;
}
Uint EnsureId(ScratchFramebuffer& fb) {
@@ -13300,9 +13100,6 @@ namespace MobileGL::MG_Backend::DirectGLES {
}
Uint EnsureCompleteTinyFramebufferId() {
ScratchSet& set = g_scratchSets.Current();
Uint& g_completeTinyFBOId = set.completeTinyFBOId;
Uint& g_completeTinyRBOId = set.completeTinyRBOId;
if (g_completeTinyFBOId != 0) {
return g_completeTinyFBOId;
}
@@ -13330,18 +13127,19 @@ namespace MobileGL::MG_Backend::DirectGLES {
if (textureId == 0) {
return;
}
// Textures ARE shared, so the deleted id may sit in any context's scratch FBO.
g_scratchSets.ForEach([textureId](ScratchSet& set) {
for (ScratchFramebuffer* fb : {&set.temp, &set.blitRead, &set.blitDraw}) {
if (fb->colorTex == textureId || fb->depthTex == textureId) {
fb->attachmentsKnown = false;
}
for (ScratchFramebuffer* fb : {&g_tempFramebuffer, &g_blitReadFramebuffer, &g_blitDrawFramebuffer}) {
if (fb->colorTex == textureId || fb->depthTex == textureId) {
fb->attachmentsKnown = false;
}
});
}
}
void OnBackendContextDestroyed() {
g_scratchSets.Clear();
g_tempFramebuffer = {};
g_blitReadFramebuffer = {};
g_blitDrawFramebuffer = {};
g_completeTinyFBOId = 0;
g_completeTinyRBOId = 0;
}
} // namespace ScratchFBOImpl
@@ -14335,8 +14133,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
// re-serialised copy either way, and adopting that copy for every vertex
// shader would put every one of them through a round trip they do not need
// - which is not free: it cost the create-indirect retrace 0.15 SSIM the
// first time this gate was missing (the original capture; the case is now
// minecraft-1.21.1-neoforge-create-indirect-in-world-align1024).
// first time this gate was missing.
effectiveSpirv = &splitArrayInputSpirv;
}
@@ -14344,10 +14141,8 @@ namespace MobileGL::MG_Backend::DirectGLES {
// blocks - the optimizer hands back a re-serialised copy either way, and taking
// that copy for a module it did not rewrite is not free (it cost the
// create-indirect retrace 0.15 SSIM when the array-input split first missed
// this gate; the case is now
// minecraft-1.21.1-neoforge-create-indirect-in-world-align1024). The report has to be
// per stage, not cumulative: a fragment shader consuming the same block reports a
// name the vertex stage already reported,
// this gate). The report has to be per stage, not cumulative: a fragment shader
// consuming the same block reports a name the vertex stage already reported,
// and its own rewrite must still be taken or the two stages stop matching.
Vector<unsigned int> flattenedXfbSpirv;
if (!xfbCaptureBlockNames.empty()) {
@@ -15066,10 +14861,8 @@ namespace MobileGL::MG_Backend::DirectGLES {
// per stage below so a producer and its consumer keep naming the same block.
// Gated twice over, because a re-serialised module is not free (it cost the
// create-indirect retrace 0.15 SSIM the first time the array-input split missed
// its gate; the case is now
// minecraft-1.21.1-neoforge-create-indirect-in-world-align1024): only a tessellation
// or geometry stage can declare blocks in both directions at all, and even then the
// probe has to FIND a collision before any
// its gate): only a tessellation or geometry stage can declare blocks in both
// directions at all, and even then the probe has to FIND a collision before any
// stage is rewritten.
std::set<String> collidingIoBlockNames;
std::set<String> declaredIoBlockNames;
@@ -16937,10 +16730,6 @@ namespace MobileGL::MG_Backend::DirectGLES {
// PipeTextureStorageRecordForRecord and CONTRACT-P5E.md §5.2.
const MG_Pipe::MGPipeResourceRecord* storage = PipeTextureStorageRecordForRecord(record);
if (storage == nullptr) return false;
#if MOBILEGL_BUILD_DISAGGREGATED
// Never clean while bound to a shared image: see IsDrawSyncClean.
if (m_sharedImage != nullptr) return false;
#endif
// SyncMipmapsToBackend's own early-out, verbatim.
if (!m_isInitialized || m_syncedResourceSerial == 0 || m_syncedResourceSerial != storage->Serial ||
!storage->PendingUploads.empty()) {
+20 -115
View File
@@ -74,10 +74,6 @@ namespace MobileGL::MG_Backend::DirectGLES {
// flag while the process is very much alive.
Bool InProcessTeardown();
void EnsureProcessTeardownSentinel();
// The exit() half of InProcessTeardown alone, for an object whose release needs only the
// display, not a current context (an EGLImage): a server session's twin teardown has no
// context current but a live display, and skipping the release there would leak the image.
Bool InProcessExit();
// Generation of the backend ES context that owns the driver ids currently handed
// out. Bumped exactly once per DestroyEGLContext. Every backend twin that owns a
@@ -336,11 +332,6 @@ namespace MobileGL::MG_Backend::DirectGLES {
using const_iterator = typename BackendMap::const_iterator;
#if MOBILEGL_PIPE_PUSH
using SlotTable = BackendSlotTable<StateObject, BackendObject, kKind>;
// P14 S6: the ONE bucket of this kind the calling thread is in. Every handle-keyed entry
// below resolves through it, so the six twin registries answer per {session, share
// group} without a single call site naming a bucket.
using SlotTables = SlotTableRegistry<StateObject, BackendObject, kKind>;
using TwinKey = DirectGLES::TwinKey;
#endif
BackendPtr& GetOrCreate(const StatePtr& stateObj) {
@@ -357,7 +348,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
// insertion (D13; SlotTables.h) - so a table used outside a registry arms
// it too, which is right: it is the twin, not the registry, that owns the
// driver id a guarded destructor exists for.
return m_slotTables.ForCallingThread().GetOrCreate(stateObj);
return m_slotTable.GetOrCreate(stateObj);
}
#endif
// Twin creation is the moment a driver-owned id starts needing a guarded
@@ -416,7 +407,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
#endif
#if MOBILEGL_PIPE_PUSH
if (EsprytSlotTablesEnabled()) {
return m_slotTables.ForCallingThread().Find(stateObj);
return m_slotTable.Find(stateObj);
}
#endif
const auto entryIt = m_entries.find(stateObj);
@@ -454,7 +445,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
// backend memo stores instead of a raw pointer, a GL name or a bare lifetime id.
MG_Pipe::MGPipeHandle HandleOf(const StateObject* stateObj) const {
if (EsprytSlotTablesEnabled()) {
return m_slotTables.HandleOf(stateObj);
return m_slotTable.HandleOf(stateObj);
}
return MG_Pipe::kMGPipeNullHandle;
}
@@ -463,7 +454,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
// the lookup a backend memo that already holds a handle wants: no lifetime-id probe.
BackendPtr* FindByHandle(MG_Pipe::MGPipeHandle handle) {
if (EsprytSlotTablesEnabled()) {
return m_slotTables.FindByHandle(handle);
return m_slotTable.FindByHandle(handle);
}
return nullptr;
}
@@ -499,7 +490,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
return nullptr;
#endif
}
const Uint32 liveGen = m_slotTables.LiveGenAt(handle.Slot);
const Uint32 liveGen = m_slotTable.LiveGenAt(handle.Slot);
if (liveGen != 0 && liveGen > handle.Gen) {
#if MOBILEGL_BUILD_DISAGGREGATED
MG_Pipe::MGPipeSessionFail( // @Ph-declined (ID-P7-1): PH-2 stays Fatal, CONTRACT-P7 §12
@@ -511,7 +502,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
return nullptr;
#endif
}
return &m_slotTables.GetOrCreate(handle);
return &m_slotTable.GetOrCreate(handle);
}
// The generation of the LIVE entry at this slot, or 0. It exists so a caller can
@@ -519,7 +510,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
// performs silently.
Uint32 LiveGenAt(Uint32 slot) const {
if (!EsprytSlotTablesEnabled()) return 0;
return m_slotTables.LiveGenAt(slot);
return m_slotTable.LiveGenAt(slot);
}
// P5c (hd): the two halves of SlotTables.h's state note, forwarded. A caller holding
@@ -533,12 +524,12 @@ namespace MobileGL::MG_Backend::DirectGLES {
// which is the answer the legacy walk's own weak_ptr test already gives.
void NoteStateForHandle(MG_Pipe::MGPipeHandle handle, const StatePtr& stateObj) {
if (EsprytSlotTablesEnabled()) {
m_slotTables.NoteStateForHandle(handle, stateObj);
m_slotTable.NoteStateForHandle(handle, stateObj);
}
}
StatePtr StateForHandle(MG_Pipe::MGPipeHandle handle) const {
if (EsprytSlotTablesEnabled()) {
return m_slotTables.StateForHandle(handle);
return m_slotTable.StateForHandle(handle);
}
return nullptr;
}
@@ -600,52 +591,9 @@ namespace MobileGL::MG_Backend::DirectGLES {
template <typename Fn>
void ForEachLive(Fn&& fn) const {
if (EsprytSlotTablesEnabled()) {
m_slotTables.ForEachLive(fn);
m_slotTable.ForEachLive(fn);
}
}
// ---- P14 S6: the KEYED shape's own controls ----------------------------------------
//
// Everything above is the shape a CALL SITE sees, and it is deliberately the shape it
// saw before the rekey. These four are the shape only a caller that has to reason about
// buckets needs: the teardown of a session, a test asking whether two contexts landed in
// two namespaces, and a diagnostic.
//
// THE ONE BUCKET THIS THREAD RESOLVES TO. A by-value copy of it is exactly what a
// fixture's saved registry was, and it is what makes `= {}` and "put it back" both mean
// something under a key.
SlotTable& BucketForCallingThread() {
if (EsprytSlotTablesEnabled()) return m_slotTables.ForCallingThread();
// The legacy arm has no buckets; the empty table's Reset() is the only honest
// answer, and no shipping path asks (the arm is compiled out or the bit is clear).
return m_legacyEmptyTable;
}
Vector<SharedPtr<SlotTable>> BucketSnapshot() const {
if (EsprytSlotTablesEnabled()) return m_slotTables.Snapshot();
return {};
}
SizeT BucketCount() const {
return EsprytSlotTablesEnabled() ? m_slotTables.BucketCount() : 0;
}
// Drop one {session, share group}. Answers whether such a bucket existed.
Bool DropBucket(const TwinKey& key) {
return EsprytSlotTablesEnabled() && m_slotTables.Drop(key);
}
// Drop every bucket of one session - the difference between "this session's twins go"
// and "the process's do" - and answer how many groups that took with it.
Uint32 DropBucketsOfSession(Uint64 sessionKey) {
return EsprytSlotTablesEnabled() ? m_slotTables.DropSession(sessionKey) : 0;
}
// Empty every bucket. The teardown of a process-shaped world, where the key is {0, 0}.
void ResetBuckets() {
if (EsprytSlotTablesEnabled()) m_slotTables.Reset();
}
// Every bucket, walked with its key.
template <typename Fn>
void ForEachBucket(Fn&& fn) const {
if (EsprytSlotTablesEnabled()) m_slotTables.ForEachBucket(fn);
}
#endif
// The seven DirectGLES.cpp call sites drive the LEGACY arm and nothing else. On the
@@ -716,14 +664,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
Uint32 m_creationTick = 0;
Bool m_isCollecting = false;
#if MOBILEGL_PIPE_PUSH
// P14 S6: the ONE bucket per {session, share group}, hidden behind the same member names
// the single table had, so every handle-keyed call site above and every caller below is
// unchanged. See SlotTables.h's SlotTableRegistry for the resolution chain.
SlotTables m_slotTables;
// The legacy arm's stand-in for BucketForCallingThread(). Never read after a Reset and
// never populated: the two entries that could write it are the handle-keyed ones, which
// return early on that arm.
SlotTable m_legacyEmptyTable;
BackendSlotTable<StateObject, BackendObject, kKind> m_slotTable;
#endif
};
@@ -1140,14 +1081,8 @@ namespace MobileGL::MG_Backend::DirectGLES {
// HandleOf, no ForEachLive), and the handle overloads never look at it. Death is
// announced by the family's own ResourceDestroy call, not by the shared death notice
// (D-L), and the slot is freed by the CLIENT after that call returns.
//
// P14 S6: A BUCKET REGISTRY, like the six TwinRegistry tables. A buffer twin owns a
// driver buffer id, so the SAME {slot, gen} in two contexts that do not share a group
// must be two resources - and it was one process-wide table until this slice. The
// handle-keyed member-for-member forwarding in SlotTables.h is what leaves every
// `g_backendBufferResources.X(...)` call site below untouched.
using BackendBufferResourceTable =
SlotTableRegistry<MG_State::GLState::BufferObject, GLESBufferResource, MG_Pipe::MGPipeKind::Buffer>;
BackendSlotTable<MG_State::GLState::BufferObject, GLESBufferResource, MG_Pipe::MGPipeKind::Buffer>;
extern BackendBufferResourceTable g_backendBufferResources;
// Resolved once per process and latched, exactly like EsprytSlotTablesEnabled() and
@@ -1370,9 +1305,6 @@ namespace MobileGL::MG_Backend::DirectGLES {
void UnregisterBufferBackendOps();
// The ES context died: unregister ops, invalidate all outstanding GL ids
// (they belonged to the dead context) and drop deferred deletes.
// P14: a server session ended while another session's native context is still alive (one
// process-wide share group): drops only the ending session's own staged bytes.
void OnServerSessionEndedWithOthersLive();
void OnBackendContextDestroyed();
// Get-or-create the backend resource and bring its storage up to date
@@ -1947,6 +1879,9 @@ namespace MobileGL::MG_Backend::DirectGLES {
return TextureTarget::Texture2D;
case TextureTarget::Texture1DArray:
return TextureTarget::Texture2DArray;
// An external texture's storage is an imported EGLImage; to the driver it is 2D.
case TextureTarget::TextureExternalOES:
return TextureTarget::Texture2D;
default:
return target;
}
@@ -2103,14 +2038,6 @@ namespace MobileGL::MG_Backend::DirectGLES {
// level when the store covers it (notes/p9/W2-REMINT.md).
void RequireImageBindableStorageByHandle(MG_Pipe::MGPipeHandle res,
const MG_Pipe::MGPipeResourceRecord& record);
#endif
#if MOBILEGL_BUILD_DISAGGREGATED
// SHARED IMAGES (MGPipeResourceRecord::SharedImageId). True when this call settled the
// storage - the ES name's level 0 IS the image (glEGLImageTargetTexture2DOES), or the
// image could not be bound and the name is left empty - and SyncMipmapsToBackend must
// not go on to allocate or upload. False when the record names no image: a twin that
// was bound to one has been told to re-mint, and the normal storage path takes over.
Bool SyncSharedImageStorage(const MG_Pipe::MGPipeResourceRecord& record);
#endif
// Whether this texture's ES storage was minted in an image carrier rather than in the
// frontend format's own layout - the readback has to ask, because for a NORMALIZED
@@ -2145,12 +2072,6 @@ namespace MobileGL::MG_Backend::DirectGLES {
Bool IsDrawSyncClean(const MG_State::GLState::ITextureObject* t, Uint64 contextId,
Uint64 samplingGeneration) const {
#if MOBILEGL_BUILD_DISAGGREGATED
// A shared image's texels move with its producer's presents, which nothing here
// sees: every use goes through SyncMipmapsToBackend's shared-image arm, which waits
// for a write that landed since the last one (SharedImageImpl::AcquireForSampling).
if (m_sharedImage != nullptr) return false;
#endif
if (!m_isInitialized || m_syncedShapeContextId == 0 || m_syncedShapeContextId != contextId ||
m_syncedShapeGeneration != samplingGeneration) {
return false;
@@ -2242,14 +2163,6 @@ namespace MobileGL::MG_Backend::DirectGLES {
Bool m_isInitialized = false;
Bool m_imageBindableStorageRequired = false;
Bool m_backendStorageImmutable = false;
#if MOBILEGL_BUILD_DISAGGREGATED
// The shared image the ES name's level 0 was last bound to (0 = none; image ids are
// never reused, so this is a lifetime key), and the EGLImage that binding went through,
// which holds the image for as long as the name samples it. Null with a nonzero id when
// the image could not be bound: the name is left empty until the record moves.
Uint64 m_sharedImageId = 0;
SharedImageImpl::EglImageRef m_sharedImage;
#endif
// Whether the driver texture may hold texels the shadow never saw. Set the first time
// anything other than a texel upload can write it - an application framebuffer
// attachment, a writable image binding, a copy or blit into it, a driver-side mipmap
@@ -2276,16 +2189,10 @@ namespace MobileGL::MG_Backend::DirectGLES {
// unconditionally bumps it), the content version on every CPU pixel mutation, and
// the params version covers SetSamples/SetFixedSampleLocations, which bump neither
// of the other two but feed the shape probe. The context id pins the generation to
// the context that produced it - generations restart at 0 with a new context, so the
// id is part of the key. IT IS NOT AN OWNERSHIP CLAIM: a texture belongs to a SHARE
// GROUP (P14 S3/S6 - share groups ARE implemented, `ShareGroupState` holds the object
// tables and the twin tables are keyed by {session, share group}), so two contexts of
// one group both legitimately mutate this texture. What the id buys is only the
// cheaper half of the gate: a mutation made under a context sharing this texture
// stamps a different id and re-derives the shape, which is a spurious re-derivation
// (safe, and only on a shape mutation) rather than a missed one - the per-mutation
// versions below are what actually catch a change, and they are group-independent.
// 0 = never stamped (real context ids start at 1). Backend-side invalidation rides on
// the context that produced it - generations restart at 0 with a new context, and a
// texture is owned by exactly one context (share groups are not implemented), so a
// mutation can never happen under a context this key does not name. 0 = never
// stamped (real context ids start at 1). Backend-side invalidation rides on
// m_isInitialized: RequireImageBindableStorage and RecreateBackendTexture clear it.
Uint64 m_syncedShapeContextId = 0;
Uint64 m_syncedShapeGeneration = 0;
@@ -3735,9 +3642,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
// what makes HandleOf below resolve at all. Not one member that would dereference it is
// instantiated - no Find(StateObject*), no ForEachLive - and the handle overloads never
// look at it.
// P14 S6: and a bucket registry for the same reason the buffer one above is - a sampler
// view's twin is a driver object of the texture's group.
using BackendSamplerViewTable = SlotTableRegistry<MG_State::GLState::ITextureObject,
using BackendSamplerViewTable = BackendSlotTable<MG_State::GLState::ITextureObject,
BackendSamplerViewObject,
MG_Pipe::MGPipeKind::SamplerViewCso>;
extern BackendSamplerViewTable g_backendSamplerViews;
+1 -290
View File
@@ -11,12 +11,6 @@
#include <MG_Pipe/MGPipeHandles.h>
// P14 S6: the key this table is filed under includes the calling thread's {session, share
// group}, and the probe that answers it lives on the backend's public surface beside S4's
// native-tuple key (DirectGLES.h). Included here so this header is self-contained for the two
// translation units that include it without copying Managers.h's include order.
#include "DirectGLES.h"
#if MOBILEGL_PIPE_PUSH
#include <MG_Impl/Pipe/SlotAllocator.h>
#endif
@@ -161,250 +155,6 @@ namespace MobileGL::MG_Backend::DirectGLES {
return enabled;
}
// =====================================================================================
// P14 S6 (docs/Disaggregated/design/11-state-ownership.md): THE TWIN TABLE IS PER
// {session, share group}, NOT PER PROCESS.
// =====================================================================================
//
// WHAT WAS WRONG, in one sentence: a twin is a DRIVER object - a GL buffer id, a program, a
// texture, the storage behind them - so it belongs to one native context's object namespace,
// and a table keyed by {slot, gen} ALONE resolves the same handle value to the same twin
// whichever context asked. The frontend gives two contexts that do NOT share a group two
// independent name spaces, so the same {slot, gen} in both is legal and means two different
// objects; one process-wide table made the second context adopt the first's twin (including
// its driver ids, its persistent map and its pooled store). At the same time two contexts of
// ONE group - which must see one set of objects - were served by whichever of them twinned
// first, i.e. by luck rather than by the group the two agree on.
//
// THE KEY IS the same pair the applier files its OBJECT RECORDS under: {session, share
// group}. Same probe, same `0 means this context started its own group` rule (see
// DirectGLES.h's TwinKey and SessionRuntime.cpp's ResolveThreadTwinKey), so a record and the
// twin it describes are always in the same bucket. Session is in the key because a twin
// names a driver id and no driver id crosses a connection - two connections in one process
// are two clients, and nothing may be shared with either from the other.
//
// THE HOLDER LIST STAYS PROCESS-WIDE AND THAT IS NOT A COMPROMISE. A notice is about an
// OBJECT, not about a bucket: OnFrontendObjectDestroyed and ReleaseTwinByHandle must reach
// the by-value copies a fixture or a context reset is holding, whichever bucket they sit in,
// and "which bucket holds it" is exactly the question that produced the two-holder leak the
// list exists to fix. Each SHARED holder of the list is ONE bucket; the walk therefore covers
// every bucket of every table.
//
// THE SAME TABLE OBJECT IS REUSED, NOT REPLACED, and that is what keeps ~200 call sites
// alive: `g_backendTextureObjects.Find(...)` still answers from the bucket the calling thread
// is in, because the object the global names multiplexes on the key at each lookup. A caller
// that must address a bucket OTHER than the calling thread's - the death walks, the
// session-teardown drop - takes Shared() or calls the static entries, which walk buckets;
// and a caller that wants the whole process's view (the teardown, the tests) takes Snapshot().
// FORWARD-DECLARED, because the registry below is DEFINED before the table it holds; the
// members that name the table are defined out of line at the bottom of this header.
template <typename StateObject, typename BackendObject, MG_Pipe::MGPipeKind kKind>
class BackendSlotTable;
template <typename StateObject, typename BackendObject, MG_Pipe::MGPipeKind kKind>
class SlotTableRegistry {
public:
using Table = BackendSlotTable<StateObject, BackendObject, kKind>;
using Key = TwinKey;
using StatePtr = SharedPtr<StateObject>;
using BackendPtr = SharedPtr<BackendObject>;
// The bound the two tables that ARE a bucket registry have always spelled by name; the
// six registries reach it through their own `SlotTable` alias.
static constexpr Uint32 kMaxHandleSlot = 1u << 20;
// One bucket. SHARED, so a caller may keep it across other lookups: the map owns the
// pointee and never moves it.
SharedPtr<Table> Shared(const Key& key) const {
// The common case on the hot path: the same key as last time. One compare, no probe.
if (m_memoTable != nullptr && m_memoKey == key) return m_memoTable;
const auto found = m_buckets.find(key);
if (found != m_buckets.end()) {
m_memoKey = key;
m_memoTable = found->second;
return found->second;
}
SharedPtr<Table> fresh = MakeShared<Table>();
fresh->SetOwnerSession(key.SessionKey);
m_buckets.emplace(key, fresh);
m_memoKey = key;
m_memoTable = fresh;
return fresh;
}
// The calling thread's bucket - the ONE entry every in-place call site below resolves
// through, and the process-wide answer on a thread that belongs to no session.
//
// CONST, AND IT ANSWERS A MUTABLE BUCKET: the index is `mutable` because a LOOKUP may
// have to create the bucket it is about to miss in (a handle with no twin yet is the
// ordinary case), and the bucket's own entries are the table's business rather than the
// registry's. The alternative - a const overload returning "no table" - would make every
// read-only caller handle a case that cannot arise.
Table& ForCallingThread() const {
Key key;
CurrentTwinKey(&key);
return *Shared(key);
}
// Every bucket, in no particular order.
Vector<SharedPtr<Table>> Snapshot() const {
Vector<SharedPtr<Table>> all;
all.reserve(m_buckets.size());
for (const auto& bucket : m_buckets) all.push_back(bucket.second);
return all;
}
SizeT BucketCount() const { return m_buckets.size(); }
// THE PER-BUCKET ONE-SHOT, because a bucket held by SharedPtr is never dropped by an
// assignment: a caller that means "this context/group is gone" has to be able to say so,
// and the key is how it says which one. The bucket LEAVES the index before its twins are
// released, so a twin destructor that re-entered Shared() cannot find a half-erased one.
Bool Drop(const Key& key) {
const auto found = m_buckets.find(key);
if (found == m_buckets.end()) return false;
SharedPtr<Table> dropped = found->second;
m_buckets.erase(found);
if (m_memoTable == dropped) {
m_memoKey = Key{};
m_memoTable = nullptr;
}
dropped->Reset();
return true;
}
// EVERY bucket of one session, for the teardown of a session that owned several groups.
// The session is the key's high half, so this is one pass and no per-group bookkeeping -
// and it is the difference between "this session's twins go" and "the process's do".
Uint32 DropSession(Uint64 sessionKey) {
Uint32 dropped = 0;
for (auto bucket = m_buckets.begin(); bucket != m_buckets.end();) {
if (bucket->first.SessionKey != sessionKey) {
++bucket;
continue;
}
SharedPtr<Table> table = bucket->second;
if (m_memoTable == table) {
m_memoKey = Key{};
m_memoTable = nullptr;
}
bucket = m_buckets.erase(bucket);
table->Reset();
++dropped;
}
return dropped;
}
// Replace this registry with an empty one, releasing every bucket's twins. This is what
// `registry = {}` meant when the registry WAS one table; a caller that must keep the
// tables alive past the call takes a Snapshot() first.
void Reset() {
const Vector<SharedPtr<Table>> all = Snapshot();
m_buckets.clear();
m_memoKey = Key{};
m_memoTable = nullptr;
for (const SharedPtr<Table>& table : all) table->Reset();
}
// ---- the calling thread's bucket, member for member ---------------------------------
//
// THIS IS WHY THE SHAPE COST THE CALL SITES NOTHING. Every handle-keyed entry the table
// has is repeated here and forwarded to the bucket the calling thread resolves to, so
// `g_backendTextureObjects.FindByHandle(h)` and `g_backendBufferResources.GetOrCreate(h)`
// - unchanged source - answer from the right context's object namespace. A caller that
// must name a bucket OTHER than its own (a death walk, a case) takes Shared()/Snapshot()
// and calls the table directly.
BackendPtr& GetOrCreate(MG_Pipe::MGPipeHandle handle) {
return ForCallingThread().GetOrCreate(handle);
}
BackendPtr* FindByHandle(MG_Pipe::MGPipeHandle handle) {
return ForCallingThread().FindByHandle(handle);
}
const BackendPtr* FindByHandle(MG_Pipe::MGPipeHandle handle) const {
return ForCallingThread().FindByHandle(handle);
}
// Resolve-or-create in a bucket the caller NAMES rather than the one it is in. The
// monolith-glue frontend-keyed entry (StateBackendObjectRegistry::GetOrCreate below)
// needs it: a state object handed over on the client side of a sync is described by a
// record in the CALLING thread's group, and a twin built for it must land in the same
// bucket as that record.
BackendPtr& GetOrCreateIn(const Key& key, MG_Pipe::MGPipeHandle handle) {
return Shared(key)->GetOrCreate(handle);
}
Uint32 LiveGenAt(Uint32 slot) const { return ForCallingThread().LiveGenAt(slot); }
MG_Pipe::MGPipeHandle HandleOf(const StateObject* stateObj) const {
return ForCallingThread().HandleOf(stateObj);
}
void NoteStateForHandle(MG_Pipe::MGPipeHandle handle, const StatePtr& stateObj) {
ForCallingThread().NoteStateForHandle(handle, stateObj);
}
StatePtr StateForHandle(MG_Pipe::MGPipeHandle handle) const {
return ForCallingThread().StateForHandle(handle);
}
template <typename Fn>
void ForEachLive(Fn&& fn) const {
// THE CALLING THREAD'S BUCKET, not every bucket, and that is the semantic answer
// rather than a shortcut: a caller walking twins is asking "which of the objects I
// can see need this", and what it can see is its own share group. Every bucket in
// one process would walk a neighbour session's objects.
ForCallingThread().ForEachLive(fn);
}
// Every bucket, in one pass. The caller receives the key with the handle so it can tell
// which context a twin belongs to - the only walks that need the whole process's view
// are a diagnostic and a teardown.
template <typename Fn>
void ForEachBucket(Fn&& fn) const {
for (const auto& bucket : m_buckets) {
bucket.second->ForEachLive(
[&](MG_Pipe::MGPipeHandle handle, const BackendPtr& twin) { fn(bucket.first, handle, twin); });
}
}
// The process-wide answer for the two statics: a notice is about an OBJECT, so it must
// reach the twin in EVERY bucket of EVERY holder. They forward to the table's own
// statics, which walk the holder list - each SHARED holder of it is one bucket.
static Bool ReleaseTwinByHandle(MG_Pipe::MGPipeHandle handle) {
return Table::ReleaseTwinByHandle(handle);
}
static Bool OnFrontendObjectDestroyed(Uint64 lifetimeId) {
return Table::OnFrontendObjectDestroyed(lifetimeId);
}
// The instance spelling, and it HANDS THE TWIN OUT rather than answering a Bool: the two
// tables that ARE a bucket registry (buffers, sampler views) have always been called as
// `g_backendBufferResources.ReleaseByHandle(res)` and their callers still have to decide
// what happens to the driver id the twin owns. The bucket is the CALLING THREAD'S, which
// is the bucket that twin was created in.
BackendPtr ReleaseByHandle(MG_Pipe::MGPipeHandle handle) {
return ForCallingThread().ReleaseByHandle(handle);
}
static Uint32 HolderCount() { return Table::HolderCount(); }
Uint32 LiveCount() const { return ForCallingThread().LiveCount(); }
Uint32 CompositeLiveCount() const { return ForCallingThread().CompositeLiveCount(); }
SizeT OrdinaryCapacityForTest() const { return ForCallingThread().OrdinaryCapacityForTest(); }
SizeT CompositeCapacityForTest() const { return ForCallingThread().CompositeCapacityForTest(); }
// ---- the bucket index's own controls, for the two tables that ARE a registry --------
//
// The six TwinRegistry registries carry the same three under the names in Managers.h
// (DropBucket / DropBucketsOfSession / ResetBuckets); they are repeated here because
// SlotTableRegistry IS the public type of the buffer and sampler-view tables, so a caller
// of those has no registry object in between.
Bool DropBucket(const Key& key) { return Drop(key); }
// Drop every bucket of one session; answers how many groups that took with it.
Uint32 DropBucketsOfSession(Uint64 sessionKey) { return DropSession(sessionKey); }
// Empty every bucket (the process-shaped world's teardown, key {0, 0}).
void ResetBuckets() { Reset(); }
private:
// ONE BUCKET PER LIVE {session, share group}, held by SHARED pointer so a caller may
// snapshot one across other lookups and so `Drop` can take a bucket's twins away
// explicitly - an embedded table could do neither. `std::unordered_map` rather than the
// tree's own flat Vector: this map is probed once per twin lookup on the draw path.
mutable std::unordered_map<Key, SharedPtr<Table>, TwinKeyHash> m_buckets;
// Hot-path memo. A registry is per KIND and each kind is touched several times per draw;
// a thread only ever moves between buckets when its session binds another context.
mutable SharedPtr<Table> m_memoTable;
mutable Key m_memoKey;
};
template <typename StateObject, typename BackendObject, MG_Pipe::MGPipeKind kKind>
class BackendSlotTable {
public:
@@ -459,7 +209,6 @@ namespace MobileGL::MG_Backend::DirectGLES {
// ENTRIES and the memo; the links are the table's own and are never copied.
BackendSlotTable() { LinkHolder(); }
BackendSlotTable(const BackendSlotTable& other):
m_ownerSession(other.m_ownerSession),
m_slots(other.m_slots),
m_band(other.m_band),
m_nullTwin(other.m_nullTwin),
@@ -468,7 +217,6 @@ namespace MobileGL::MG_Backend::DirectGLES {
LinkHolder();
}
BackendSlotTable(BackendSlotTable&& other) noexcept:
m_ownerSession(other.m_ownerSession),
m_slots(std::move(other.m_slots)),
m_band(std::move(other.m_band)),
m_nullTwin(std::move(other.m_nullTwin)),
@@ -504,12 +252,6 @@ namespace MobileGL::MG_Backend::DirectGLES {
}
~BackendSlotTable() { UnlinkHolder(); }
// The served session whose bucket this table is (SlotTableRegistry::Shared), 0 for a
// table that belongs to none (the process-wide registry on a sessionless thread, a
// fixture's copy of one).
void SetOwnerSession(Uint64 session) { m_ownerSession = session; }
Uint64 OwnerSession() const { return m_ownerSession; }
// Resolve-or-create. The handle comes from the client allocator keyed on the frontend
// object's lifetime id, so two calls for the same live object always land on the same
// slot, and a successor object at the same heap address never does.
@@ -811,24 +553,12 @@ namespace MobileGL::MG_Backend::DirectGLES {
// double Free would be refused by generation anyway. Idempotent against the kind's
// own delete opcode, exactly as the notice arm is: a twin the delete already released
// fails ReleaseTwinAt's generation check and the walk moves on.
//
// ONE SESSION'S HOLDERS, WHEN THE DEATH IS ONE SESSION'S. A handle is numbered by its own
// client's allocator, so with several clients served by one process the same {slot, gen}
// names a live, unrelated object in every other session: walking every holder released
// THOSE twins too - a client deleting a texture (or exiting) deleted the compositor's
// driver texture with the same handle, and its windows sampled freed memory. On a thread
// that belongs to a session only that session's buckets answer; a sessionless thread
// (the in-library backend, a unit fixture) keeps the process-wide walk.
static Bool ReleaseTwinByHandle(MG_Pipe::MGPipeHandle handle) {
if (MG_Pipe::MGPipeHandleIsNull(handle)) return false;
TwinKey key;
const Bool sessionScoped = CurrentTwinKey(&key) && key.SessionKey != 0;
Bool released = false;
for (BackendSlotTable* holder = s_firstHolder; holder != nullptr;) {
BackendSlotTable* const next = holder->m_nextHolder;
if (!sessionScoped || holder->m_ownerSession == key.SessionKey) {
released = holder->ReleaseTwinAt(handle) || released;
}
released = holder->ReleaseTwinAt(handle) || released;
holder = next;
}
return released;
@@ -886,24 +616,6 @@ namespace MobileGL::MG_Backend::DirectGLES {
}
}
// Empty this table, releasing every twin it holds. THE SPACES ARE MOVED OUT FIRST and
// that is the whole of the care taken here: a twin's destructor is a driver call that
// could re-enter GetOrCreate on this table (SlotTables.h's ReleaseTwinAt says why), and
// destroying the entries in place would leave that re-entry resizing the vector the
// destructors are being walked out of. Here the table is already empty when the entries
// die, so a re-entrant insert grows a fresh vector.
//
// This is what `table = {}` used to mean, spelled so a caller cannot miss the ordering.
void Reset() {
Vector<Entry> slots = std::move(m_slots);
Vector<Entry> band = std::move(m_band);
BackendPtr nullTwin = std::move(m_nullTwin);
ForgetHandle();
slots.clear();
band.clear();
nullTwin.reset();
}
Uint32 LiveCount() const {
Uint32 count = 0;
for (const Entry& entry : m_slots) {
@@ -1033,7 +745,6 @@ namespace MobileGL::MG_Backend::DirectGLES {
static inline BackendSlotTable* s_firstHolder = nullptr;
BackendSlotTable* m_prevHolder = nullptr;
BackendSlotTable* m_nextHolder = nullptr;
Uint64 m_ownerSession = 0;
// Indexed by MGPipeHandle::Slot; [0] is the reserved slot and is never live.
Vector<Entry> m_slots;
@@ -332,10 +332,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
#if MOBILEGL_BUILD_DISAGGREGATED
BackendObject_DirectVulkan::~BackendObject_DirectVulkan() {
// Everything below reaches this session's renderer slot, whichever thread destroys it.
MagmaSession* const ownSession = m_magmaSession.get();
MagmaSession* const previousSession = BoundMagmaSession();
if (ownSession != nullptr) BindMagmaSessionToThisThread(ownSession);
// P12 review fix: A SERVER SESSION THAT ENDS WITHOUT A CLEAN TEARDOWN LEAVES NO RENDERER ON
// THE WINDOW. The renderer - swapchain and VkSurfaceKHR on the window - is a process global
// that only ReleaseEGLResources / a released surface drops, and a client that went away
@@ -353,11 +349,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
if (MG_Config::Transport != MG_Config::TransportMode::Monolith) {
ForgetRequestedSwapInterval();
}
// The session's state goes with it, and no thread may keep answering with it.
m_magmaSession.reset();
if (ownSession != nullptr) {
BindMagmaSessionToThisThread(previousSession == ownSession ? nullptr : previousSession);
}
}
#else
BackendObject_DirectVulkan::~BackendObject_DirectVulkan() = default;
@@ -366,15 +357,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
BackendObject_DirectVulkan::BackendObject_DirectVulkan() : m_rendererInfo{GetRendererIdentity()} {}
Bool BackendObject_DirectVulkan::InitWindowSurface() {
// A suspended surface activates its placeholder - never the window, which is gone.
const auto suspended = m_suspendedWindowSurfaces.find(m_activatingSurface);
if (suspended != m_suspendedWindowSurfaces.end()) {
if (UsesSurfaceTargets() && pVulkanRenderer) {
return ActivateSuspendedPlaceholder(m_activatingSurface, suspended->second);
}
return InitPbufferSurface(static_cast<EGLint>(suspended->second.Width),
static_cast<EGLint>(suspended->second.Height));
}
if (!m_windowHandle.Handle) {
MGLOG_E("Cannot initialize DirectVulkan window surface: native window handle is null");
return false;
@@ -382,18 +364,14 @@ namespace MobileGL::MG_Backend::DirectVulkan {
auto nativeWindow = reinterpret_cast<NativeWindowType>(m_windowHandle.Handle);
VulkanRendererConfig config;
config.SwapInterval = GetRequestedSwapInterval();
if (UsesSurfaceTargets() && pVulkanRenderer) {
return pVulkanRenderer->ActivateSurfaceTarget(SurfaceTargetKey(m_activatingSurface), nativeWindow, config);
}
// Any renderer instance this assignment replaces is destroyed here;
// fence/timer-query handles stamped with the old generation go stale.
BumpRendererGeneration();
VulkanRendererConfig config;
config.SwapInterval = GetRequestedSwapInterval();
pVulkanRenderer = MakeUnique<MG_Backend::DirectVulkan::VulkanRenderer>(nativeWindow, config);
MOBILEGL_ASSERT(pVulkanRenderer != nullptr, "InitWindowSurface: VulkanRenderer creation failed");
pVulkanRenderer->Initialize();
pVulkanRenderer->SetActiveSurfaceTargetKey(SurfaceTargetKey(m_activatingSurface));
return true;
}
@@ -401,27 +379,15 @@ namespace MobileGL::MG_Backend::DirectVulkan {
VulkanRendererConfig config;
config.SurfaceWidth = static_cast<Uint32>(std::max<EGLint>(width, 1));
config.SurfaceHeight = static_cast<Uint32>(std::max<EGLint>(height, 1));
if (UsesSurfaceTargets() && pVulkanRenderer) {
return pVulkanRenderer->ActivateSurfaceTarget(SurfaceTargetKey(m_activatingSurface), NativeWindowType{},
config);
}
// Any renderer instance this assignment replaces is destroyed here;
// fence/timer-query handles stamped with the old generation go stale.
BumpRendererGeneration();
pVulkanRenderer = MakeUnique<MG_Backend::DirectVulkan::VulkanRenderer>(NativeWindowType{}, config);
MOBILEGL_ASSERT(pVulkanRenderer != nullptr, "InitPbufferSurface: VulkanRenderer creation failed");
pVulkanRenderer->Initialize();
pVulkanRenderer->SetActiveSurfaceTargetKey(SurfaceTargetKey(m_activatingSurface));
return true;
}
void BackendObject_DirectVulkan::BindSessionStateToThisThread() {
if (m_magmaSession == nullptr) m_magmaSession = MakeUnique<MagmaSession>();
BindMagmaSessionToThisThread(m_magmaSession.get());
MGLOG_I("DirectVulkan: session state %llu bound to this apply thread",
static_cast<unsigned long long>(m_magmaSession->Id()));
}
void BackendObject_DirectVulkan::Initialize() {
#if MOBILEGL_BUILD_DISAGGREGATED
VkBufferManager::RegisterWireResourceOps();
@@ -497,22 +463,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
if (!BackendObject::ResizeEGLWindowSurface(surface, width, height)) {
return false;
}
const EGLSurfaceState* state = GetRegisteredEGLSurface(surface);
if (UsesSurfaceTargets() && pVulkanRenderer && state != nullptr && state->Kind == SurfaceKind::Pbuffer) {
// A pbuffer-backed window (a Wayland window presented through wl_shm) whose target is an
// image reader of FIXED size: a swapchain rebuild cannot follow the resize, so the target
// is rebuilt at the new size - as DirectGLES replaces its native pbuffer. A parked one is
// rebuilt when it is next activated, from the size registered above.
const Bool active = m_eglSurfaceInitialized && m_eglSurface == surface;
pVulkanRenderer->DestroySurfaceTarget(SurfaceTargetKey(surface));
if (active) {
VulkanRendererConfig config;
config.SurfaceWidth = static_cast<Uint32>(state->Width);
config.SurfaceHeight = static_cast<Uint32>(state->Height);
(void)pVulkanRenderer->ActivateSurfaceTarget(SurfaceTargetKey(surface), NativeWindowType{}, config);
}
return true;
}
if (pVulkanRenderer && m_eglSurface == surface) {
pVulkanRenderer->RequestSwapchainResize(width, height);
}
@@ -530,33 +480,7 @@ namespace MobileGL::MG_Backend::DirectVulkan {
Bool BackendObject_DirectVulkan::MakeEGLCurrent(EGLDisplay dpy, EGLSurface draw, EGLSurface read, EGLContext ctx) {
const std::lock_guard<std::recursive_mutex> lock(m_eglStateMutex);
const Bool ok = BackendObject::MakeEGLCurrent(dpy, draw, read, ctx);
if (ok && UsesSurfaceTargets() && ctx != EGL_NO_CONTEXT && draw != EGL_NO_SURFACE) {
m_contextBindings[ctx] = EGLCurrentState{.Display = dpy, .DrawSurface = draw, .ReadSurface = read,
.Context = ctx};
}
return ok;
}
void BackendObject_DirectVulkan::OnClientContextBound(Uint64 token) {
const std::lock_guard<std::recursive_mutex> lock(m_eglStateMutex);
if (!UsesSurfaceTargets() || token == 0) return;
// Each of a multi-window client's contexts draws to the surface IT was made current with
// (Qt renders every window on its own thread and context); the ring interleaves them with
// a bind_context between, and no make-current. Follow the context back to its surface.
const auto found = m_contextBindings.find(reinterpret_cast<EGLContext>(token));
if (found == m_contextBindings.end()) return;
const EGLCurrentState binding = found->second;
if (!GetRegisteredEGLSurface(binding.DrawSurface)) {
m_contextBindings.erase(found);
return;
}
const auto current = m_eglCurrentThreads.find(std::this_thread::get_id());
if (current != m_eglCurrentThreads.end() && current->second.Context == binding.Context &&
current->second.DrawSurface == binding.DrawSurface && m_eglSurface == binding.DrawSurface) {
return;
}
(void)BackendObject::MakeEGLCurrent(binding.Display, binding.DrawSurface, binding.ReadSurface, binding.Context);
return BackendObject::MakeEGLCurrent(dpy, draw, read, ctx);
}
Bool BackendObject_DirectVulkan::SwapEGLBuffers(EGLDisplay dpy, EGLSurface draw) {
@@ -568,31 +492,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
return BackendObject::SwapEGLBuffers(dpy, draw);
}
Bool BackendObject_DirectVulkan::BlitDefaultFramebufferToSharedImage(const SharedImageView& image,
const MG_Util::Damage::Region& region) {
#if MOBILEGL_BUILD_DISAGGREGATED
// Same lock as SwapEGLBuffers: the copy reads the current surface target's image.
const std::lock_guard<std::recursive_mutex> lock(m_eglStateMutex);
if (!pVulkanRenderer) {
MGLOG_E("DirectVulkan: shared image %llu: the renderer is not initialized",
static_cast<unsigned long long>(image.Id));
return false;
}
return pVulkanRenderer->BlitDefaultFramebufferToSharedImage(image, region);
#else
(void)image, (void)region;
return false;
#endif
}
// A swapchain image keeps its content through a present whatever region is drawn next: the
// damage region the client may declare is not needed here.
Int32 BackendObject_DirectVulkan::QueryCurrentBufferAge(Bool damageRegionFollows) {
(void)damageRegionFollows;
const std::lock_guard<std::recursive_mutex> lock(m_eglStateMutex);
return pVulkanRenderer ? pVulkanRenderer->CurrentDrawBufferAge() : 0;
}
void BackendObject_DirectVulkan::SetEGLSwapInterval(Int interval) {
// Same lock as SwapEGLBuffers: the renderer reads the request in Present.
const std::lock_guard<std::recursive_mutex> lock(m_eglStateMutex);
@@ -613,131 +512,11 @@ namespace MobileGL::MG_Backend::DirectVulkan {
// The reflection cache is file-scope, not renderer-owned; without this the
// deleted programs' reflection strings survive full context teardown.
ClearProgramResourceCaches();
m_suspendedWindowSurfaces.clear();
BackendObject::ReleaseEGLResources();
}
Bool BackendObject_DirectVulkan::ActivateSuspendedPlaceholder(EGLSurface surface,
const SuspendedWindowSurface& extent) {
// A pbuffer target at the window's extent: every default-framebuffer path (render passes,
// read-back, the shared-image blit, the acquire and the present) keeps a live swapchain to
// work on, and the extent it publishes is the one the client already has.
VulkanRendererConfig config;
config.SurfaceWidth = std::max<Uint32>(extent.Width, 1);
config.SurfaceHeight = std::max<Uint32>(extent.Height, 1);
return pVulkanRenderer->ActivateSurfaceTarget(SurfaceTargetKey(surface), NativeWindowType{}, config);
}
Bool BackendObject_DirectVulkan::SuspendServerWindow(void* window) {
const std::lock_guard<std::recursive_mutex> lock(m_eglStateMutex);
// The monolith's one renderer IS its window; only surface targets can be swapped under it.
if (window == nullptr || !UsesSurfaceTargets()) return false;
Vector<EGLSurface> onWindow;
for (const auto& [client, state] : m_eglSurfaces) {
if (state.Kind != SurfaceKind::Window || state.Window.Handle != window) continue;
if (m_suspendedWindowSurfaces.find(client) != m_suspendedWindowSurfaces.end()) continue;
onWindow.push_back(client);
}
for (const EGLSurface client : onWindow) {
const auto state = m_eglSurfaces.find(client);
SuspendedWindowSurface extent;
extent.Width = static_cast<Uint32>(std::max<EGLint>(state->second.Width, 1));
extent.Height = static_cast<Uint32>(std::max<EGLint>(state->second.Height, 1));
if (pVulkanRenderer) {
const Uint64 key = SurfaceTargetKey(client);
const VkExtent2D built = pVulkanRenderer->SurfaceTargetExtent(key);
if (built.width != 0 && built.height != 0) {
extent.Width = built.width;
extent.Height = built.height;
}
const Bool active = pVulkanRenderer->IsActiveSurfaceTarget(key);
// Flushes, waits the device idle, purges the render passes on the target and drops its
// swapchain and VkSurfaceKHR - nothing references the window after this.
pVulkanRenderer->DestroySurfaceTarget(key);
m_suspendedWindowSurfaces[client] = extent;
// A placeholder that cannot be built is a suspend that failed: the window is already let
// go of, and the caller ends the session by name instead (its EGL resources go).
if (active && !ActivateSuspendedPlaceholder(client, extent)) return false;
} else {
m_suspendedWindowSurfaces[client] = extent;
}
}
MGLOG_I("DirectVulkan: %zu window surface(s) on server window %p now draw into placeholder pbuffer targets; "
"the renderer, the device and every object stay",
onWindow.size(), window);
return true;
}
Bool BackendObject_DirectVulkan::ResumeServerWindow(void* window, Uint32 width, Uint32 height) {
const std::lock_guard<std::recursive_mutex> lock(m_eglStateMutex);
if (window == nullptr || !UsesSurfaceTargets()) return false;
UnorderedMap<EGLSurface, SuspendedWindowSurface> suspended;
suspended.swap(m_suspendedWindowSurfaces);
for (const auto& [client, extent] : suspended) {
(void)extent;
const auto state = m_eglSurfaces.find(client);
if (state == m_eglSurfaces.end()) continue; // released while suspended
state->second.Window.Handle = window;
state->second.Window.Width = width;
state->second.Window.Height = height;
state->second.Width = static_cast<EGLint>(std::max<Uint32>(width, 1));
state->second.Height = static_cast<EGLint>(std::max<Uint32>(height, 1));
if (m_eglSurface == client) m_windowHandle = state->second.Window;
if (!pVulkanRenderer) continue;
const Uint64 key = SurfaceTargetKey(client);
const Bool active = pVulkanRenderer->IsActiveSurfaceTarget(key);
pVulkanRenderer->DestroySurfaceTarget(key); // the placeholder
// A parked surface is built on the new window when it is next activated (InitWindowSurface).
if (!active) continue;
// The creation's own path: a new VkSurfaceKHR and swapchain with the surface's current
// pre-transform, a new target serial (render passes rebuilt), and the extent published.
VulkanRendererConfig config;
config.SurfaceWidth = std::max<Uint32>(width, 1);
config.SurfaceHeight = std::max<Uint32>(height, 1);
config.SwapInterval = GetRequestedSwapInterval();
if (!pVulkanRenderer->ActivateSurfaceTarget(key, reinterpret_cast<NativeWindowType>(window), config)) {
return false;
}
}
MGLOG_I("DirectVulkan: %zu suspended window surface(s) rebuilt on server window %p (%ux%u)", suspended.size(),
window, width, height);
return true;
}
Bool BackendObject_DirectVulkan::ServerWindowResized(void* window, Uint32 width, Uint32 height) {
const std::lock_guard<std::recursive_mutex> lock(m_eglStateMutex);
if (window == nullptr || !UsesSurfaceTargets()) return false;
Bool followed = false;
for (auto& [client, state] : m_eglSurfaces) {
if (state.Kind != SurfaceKind::Window || state.Window.Handle != window) continue;
if (m_suspendedWindowSurfaces.find(client) != m_suspendedWindowSurfaces.end()) continue;
state.Window.Width = width;
state.Window.Height = height;
state.Width = static_cast<EGLint>(std::max<Uint32>(width, 1));
state.Height = static_cast<EGLint>(std::max<Uint32>(height, 1));
if (m_eglSurface == client) m_windowHandle = state.Window;
// Magma's extent is its swapchain's, published when it is built: the active target follows
// the window now (or at the half-recorded frame's present); a parked one at its next present.
if (pVulkanRenderer && pVulkanRenderer->IsActiveSurfaceTarget(SurfaceTargetKey(client))) {
followed = pVulkanRenderer->FollowActiveWindowResize() || followed;
}
}
return followed;
}
Bool BackendObject_DirectVulkan::UsesSurfaceTargets() const {
return MG_Config::Transport != MG_Config::TransportMode::Monolith;
}
void BackendObject_DirectVulkan::OnEGLSurfaceForgotten(EGLSurface surface) {
m_suspendedWindowSurfaces.erase(surface);
if (UsesSurfaceTargets() && pVulkanRenderer) pVulkanRenderer->DestroySurfaceTarget(SurfaceTargetKey(surface));
}
void BackendObject_DirectVulkan::OnEGLSurfaceReleased(EGLSurface surface) {
// The renderer outlives its surfaces here: only this surface's target goes (in
// OnEGLSurfaceForgotten, which follows), and every fence stays valid.
if (UsesSurfaceTargets() && pVulkanRenderer) return;
(void)surface;
// Outstanding fence/timer-query handles now refer to a dead renderer;
// treat them as signaled/available with zero results from here on.
BumpRendererGeneration();
@@ -786,12 +565,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
V_OpenGL30, V_OpenGL31, V_OpenGL32, V_OpenGL33, V_OpenGL40, V_OpenGL41, V_OpenGL42, V_OpenGL43,
V_OpenGL44, V_OpenGL45, V_OpenGL46,
E_GL_ARB_draw_buffers_blend,
// The GLSL 1.00/1.10-era ARB trio plus NPOT textures: all core since GL 2.0 and
// trivially true for every context this backend claims (4.6). KWin 6's
// EglContext::checkSupported() gates desktop-GL compositing on exactly these four
// strings, so withholding them fails its renderer bring-up. Same block as DirectGLES.
E_GL_ARB_shader_objects, E_GL_ARB_vertex_shader, E_GL_ARB_fragment_shader,
E_GL_ARB_texture_non_power_of_two,
E_GL_ARB_compute_shader, E_GL_ARB_shader_storage_buffer_object, E_GL_ARB_shader_image_load_store,
E_GL_ARB_clear_buffer_object, E_GL_ARB_program_interface_query, E_GL_ARB_framebuffer_object, E_GL_ARB_draw_indirect,
E_GL_ARB_multi_draw_indirect,
@@ -886,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
@@ -9,7 +9,6 @@
#pragma once
#include <Includes.h>
#include "../BackendObject.h"
#include "MagmaSession.h"
#include <MG_Util/BackendLoaders/Vulkan/Loader.h>
namespace MobileGL::MG_Backend::DirectVulkan {
@@ -27,8 +26,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
~BackendObject_DirectVulkan() override;
void Initialize() override;
void BindSessionStateToThisThread() override;
void OnClientContextBound(Uint64 token) override;
Bool InitWindowSurface() override;
Bool InitCapabilities() override;
Bool InitializeEGLDisplay(EGLDisplay dpy, EGLint* major, EGLint* minor) override;
@@ -38,17 +35,8 @@ namespace MobileGL::MG_Backend::DirectVulkan {
Bool MakeEGLCurrent(EGLDisplay dpy, EGLSurface draw, EGLSurface read, EGLContext ctx) override;
Bool SwapEGLBuffers(EGLDisplay dpy, EGLSurface draw) override;
void SetEGLSwapInterval(Int interval) override;
Bool BlitDefaultFramebufferToSharedImage(const SharedImageView& image,
const MG_Util::Damage::Region& region) override;
// The active surface target's swapchain image ages (VulkanRenderer::CurrentDrawBufferAge).
Int32 QueryCurrentBufferAge(Bool damageRegionFollows) override;
void ReleaseEGLSurface(EGLSurface surface) override;
void ReleaseEGLResources() override;
// The server window going and coming back: the window surface's target (VkSurfaceKHR,
// swapchain) is destroyed and a pbuffer target of the same extent stands in for it, and back.
Bool SuspendServerWindow(void* window) override;
Bool ResumeServerWindow(void* window, Uint32 width, Uint32 height) override;
Bool ServerWindowResized(void* window, Uint32 width, Uint32 height) override;
const RendererInfo& GetRendererInfo() const override;
String GetBackendAPIVersionString() const override;
@@ -60,11 +48,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
private:
Bool InitPbufferSurface(EGLint width, EGLint height) override;
void OnEGLSurfaceReleased(EGLSurface surface) override;
void OnEGLSurfaceForgotten(EGLSurface surface) override;
// A served session keeps one renderer across all its client's surfaces and switches the
// renderer's surface target instead (VulkanRenderer::ActivateSurfaceTarget).
Bool UsesSurfaceTargets() const;
static Uint64 SurfaceTargetKey(EGLSurface surface) { return reinterpret_cast<Uint64>(surface); }
void UpdateAdvertisedExtensions();
void UpdateDynamicBackendParameters();
@@ -72,21 +55,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
DynamicBackendParameters m_dynamicParameters;
MG_External::VulkanCapabilities m_vulkanCaps;
RendererInfo m_rendererInfo;
// A served session's own copy of Magma's per-process state (MagmaSession.h), bound to its
// apply thread. Null in the monolith and every other single-session shape.
UniquePtr<MagmaSession> m_magmaSession;
// The binding each client context was last made current with, for OnClientContextBound.
UnorderedMap<EGLContext, EGLCurrentState> m_contextBindings;
// Window surfaces whose window is gone (SuspendServerWindow), with the extent their
// placeholder pbuffer target is built at - the window's, so the default framebuffer the
// client knows keeps its size.
struct SuspendedWindowSurface {
Uint32 Width = 1;
Uint32 Height = 1;
};
UnorderedMap<EGLSurface, SuspendedWindowSurface> m_suspendedWindowSurfaces;
// The placeholder pbuffer target of a suspended surface, made active. False: it could not be built.
Bool ActivateSuspendedPlaceholder(EGLSurface surface, const SuspendedWindowSurface& extent);
};
// Single-source-of-truth helpers shared with the driver POST
@@ -35,9 +35,8 @@
#include <spirv_reflect.h>
namespace MobileGL::MG_Backend::DirectVulkan {
// Per Magma session (MagmaSession.h); the process-wide session is leak-at-exit storage, see
// GlobalObjects.cpp.
RendererSlot pVulkanRenderer;
// Leak-at-exit storage; see GlobalObjects.cpp.
UniquePtr<VulkanRenderer>& pVulkanRenderer = *new UniquePtr<VulkanRenderer>();
namespace {
#if MOBILEGL_BUILD_DISAGGREGATED
@@ -60,14 +59,7 @@ namespace MobileGL::MG_Backend::DirectVulkan {
// current one (a new renderer restarts its frame-serial counter and
// reuses pool indices). Atomic because handles may be polled from a
// thread other than the EGL thread that recreates the renderer.
//
// One per Magma session, drawn from one process-wide source: a handle stamped by one
// session's renderer must read as stale against every other session's, never equal.
std::atomic<Uint64> g_rendererGenerationSource{1};
struct RendererGeneration {
std::atomic<Uint64> value{g_rendererGenerationSource.fetch_add(1, std::memory_order_acq_rel)};
};
SessionLocal<RendererGeneration> g_rendererGeneration;
std::atomic<Uint64> g_rendererGeneration{1};
} // namespace
#if MOBILEGL_BUILD_DISAGGREGATED && MOBILEGL_PIPE_PUSH
@@ -131,12 +123,11 @@ namespace MobileGL::MG_Backend::DirectVulkan {
#endif // MOBILEGL_BUILD_DISAGGREGATED && MOBILEGL_PIPE_PUSH
Uint64 GetRendererGeneration() {
return g_rendererGeneration->value.load(std::memory_order_acquire);
return g_rendererGeneration.load(std::memory_order_acquire);
}
void BumpRendererGeneration() {
g_rendererGeneration->value.store(g_rendererGenerationSource.fetch_add(1, std::memory_order_acq_rel),
std::memory_order_release);
g_rendererGeneration.fetch_add(1, std::memory_order_acq_rel);
}
namespace {
@@ -1283,7 +1274,7 @@ namespace MobileGL::MG_Backend::DirectVulkan {
payload.mode = mode;
// TODO: allocate draw cmd buf elsewhere
static thread_local Vector<DrawCmdParam> params;
static Vector<DrawCmdParam> params;
params.clear();
params.resize(drawcount);
@@ -1356,7 +1347,7 @@ namespace MobileGL::MG_Backend::DirectVulkan {
const Uint32 indexSizeShift = static_cast<Uint32>(std::countr_zero(indexSize));
// TODO: allocate draw cmd buf elsewhere
static thread_local Vector<DrawIndexedCmdParam> params;
static Vector<DrawIndexedCmdParam> params;
params.clear();
params.resize(drawcount);
@@ -1760,12 +1751,7 @@ namespace MobileGL::MG_Backend::DirectVulkan {
}
void Present() {
// A served session's renderer is gone once its client released its resources; a present
// that still reaches it has nothing to show and is dropped rather than dereferenced.
if (!pVulkanRenderer) {
MGLOG_E_ONCE("DirectVulkan: a present reached a session whose renderer is already released; dropped");
return;
}
MOBILEGL_ASSERT(pVulkanRenderer, "DirectVulkan::Present called with null VulkanRenderer");
pVulkanRenderer->Present();
// THE frame boundary for the MGPipe counters, at the backend entry point rather
// than inside VulkanRenderer::Present: that function has an early return for the
@@ -1777,24 +1763,23 @@ namespace MobileGL::MG_Backend::DirectVulkan {
}
namespace {
// Per session: each client asks for its own interval.
SessionLocal<Optional<Int>> g_requestedSwapInterval;
Optional<Int> g_requestedSwapInterval;
} // namespace
void SetSwapInterval(Int interval) {
*g_requestedSwapInterval = interval;
g_requestedSwapInterval = interval;
if (pVulkanRenderer) {
pVulkanRenderer->SetSwapInterval(interval);
}
}
Optional<Int> GetRequestedSwapInterval() {
return *g_requestedSwapInterval;
return g_requestedSwapInterval;
}
#if MOBILEGL_BUILD_DISAGGREGATED
void ForgetRequestedSwapInterval() {
g_requestedSwapInterval->reset();
g_requestedSwapInterval.reset();
}
#endif
@@ -9,32 +9,10 @@
#pragma once
#include <Includes.h>
#include <MG_Backend/BackendObject.h>
#include "MagmaSession.h"
#include "Renderer/VulkanRenderer.h"
namespace MobileGL::MG_Backend::DirectVulkan {
// The renderer of the calling thread's Magma session (MagmaSession.h): a served session's own on
// its apply thread, the process-wide one everywhere else. Spelled like the UniquePtr it used to
// be so the call sites read the same.
class RendererSlot {
public:
UniquePtr<VulkanRenderer>& Slot() const { return m_slot.Get(); }
VulkanRenderer* get() const { return Slot().get(); }
VulkanRenderer* operator->() const { return get(); }
VulkanRenderer& operator*() const { return *get(); }
explicit operator bool() const { return get() != nullptr; }
RendererSlot& operator=(UniquePtr<VulkanRenderer>&& renderer) {
Slot() = std::move(renderer);
return *this;
}
void reset() { Slot().reset(); }
friend Bool operator==(const RendererSlot& slot, std::nullptr_t) { return slot.get() == nullptr; }
friend Bool operator!=(const RendererSlot& slot, std::nullptr_t) { return slot.get() != nullptr; }
private:
SessionLocal<UniquePtr<VulkanRenderer>> m_slot;
};
extern RendererSlot pVulkanRenderer;
extern UniquePtr<VulkanRenderer>& pVulkanRenderer;
// Generation of the live VulkanRenderer instance, mirroring DirectGLES's
// g_syncContextGeneration. BackendObject_DirectVulkan bumps it wherever
@@ -1,87 +0,0 @@
// MobileGL - MobileGL/MG_Backend/DirectVulkan/MagmaSession.cpp
// Copyright (c) 2025-2026 MobileGL-Dev
// Licensed under the GNU Lesser General Public License v3.0:
// https://www.gnu.org/licenses/gpl-3.0.txt
// https://www.gnu.org/licenses/lgpl-3.0.txt
// SPDX-License-Identifier: LGPL-3.0-only
// End of Source File Header
#include "MagmaSession.h"
#include <atomic>
namespace MobileGL::MG_Backend::DirectVulkan {
namespace {
struct SessionLocalEntry {
Detail::SessionLocalConstruct construct;
Detail::SessionLocalDestroy destroy;
};
// Construct-on-first-use: SessionLocals are namespace-scope objects in several translation
// units and register during static initialization, in no particular order.
Vector<SessionLocalEntry>& Registry() {
static auto* registry = new Vector<SessionLocalEntry>();
return *registry;
}
std::atomic<Uint64> g_nextSessionId{1};
thread_local MagmaSession* t_boundSession = nullptr;
// Leak-at-exit, like the renderer it holds (GlobalObjects.cpp): nothing may tear the
// monolith's renderer down from a static destructor after the driver is gone.
MagmaSession& ProcessSession() {
static auto* session = new MagmaSession();
return *session;
}
} // namespace
Uint32 Detail::RegisterSessionLocal(SessionLocalConstruct construct, SessionLocalDestroy destroy) {
auto& registry = Registry();
registry.push_back({construct, destroy});
return static_cast<Uint32>(registry.size() - 1);
}
MagmaSession& Detail::CurrentMagmaSession() {
MagmaSession* bound = t_boundSession;
return bound != nullptr ? *bound : ProcessSession();
}
void* Detail::SessionLocalSlot(MagmaSession& session, Uint32 index) {
if (index >= session.m_slots.size()) session.m_slots.resize(Registry().size(), nullptr);
void*& slot = session.m_slots[index];
if (slot == nullptr) slot = Registry()[index].construct();
return slot;
}
MagmaSession::MagmaSession() : m_id(g_nextSessionId.fetch_add(1, std::memory_order_relaxed)) {
// Every slot is built up front: the process-wide session is reached from whichever thread
// the app renders on, and a lazily built slot would be a first-touch race between two.
const auto& registry = Registry();
m_slots.resize(registry.size(), nullptr);
for (SizeT i = 0; i < registry.size(); ++i) m_slots[i] = registry[i].construct();
}
MagmaSession::~MagmaSession() {
MagmaSession* const previous = t_boundSession;
t_boundSession = this;
const auto& registry = Registry();
for (SizeT i = m_slots.size(); i-- > 0;) {
if (m_slots[i] != nullptr) registry[i].destroy(m_slots[i]);
m_slots[i] = nullptr;
}
// Never back to this session: it is gone.
t_boundSession = previous == this ? nullptr : previous;
}
MagmaSessionScope::MagmaSessionScope(MagmaSession* session) : m_previous(t_boundSession) {
t_boundSession = session;
}
MagmaSessionScope::~MagmaSessionScope() { t_boundSession = m_previous; }
void BindMagmaSessionToThisThread(MagmaSession* session) { t_boundSession = session; }
MagmaSession* BoundMagmaSession() { return t_boundSession; }
} // namespace MobileGL::MG_Backend::DirectVulkan
@@ -1,100 +0,0 @@
// MobileGL - MobileGL/MG_Backend/DirectVulkan/MagmaSession.h
// Copyright (c) 2025-2026 MobileGL-Dev
// Licensed under the GNU Lesser General Public License v3.0:
// https://www.gnu.org/licenses/gpl-3.0.txt
// https://www.gnu.org/licenses/lgpl-3.0.txt
// SPDX-License-Identifier: LGPL-3.0-only
// End of Source File Header
// MAGMA'S PER-SESSION STATE. Magma was written for one renderer per process: the renderer slot,
// the active buffer manager, the dynamic-state shadow, the render-pass manager's statics and the
// renderer generation are all file-scope. A multi-session server (several clients served from one
// process, each on its own apply thread with its own BackendObject_DirectVulkan) needs one copy of
// each per session, or one session's work lands in another's tables.
//
// SessionLocal<T> is that copy. It resolves through the CALLING THREAD's bound MagmaSession, and to
// the process-wide default session on every thread nothing bound - which is the monolith, the client
// role and every unit case, i.e. exactly the old behaviour, on whatever thread the app renders from.
// A served session's backend owns its MagmaSession and binds it on its apply thread (the only thread
// that runs that session's backend), so the two never mix.
#pragma once
#include <Includes.h>
#include <cstddef>
#include <new>
#include <utility>
namespace MobileGL::MG_Backend::DirectVulkan {
class MagmaSession;
namespace Detail {
using SessionLocalConstruct = void* (*)();
using SessionLocalDestroy = void (*)(void*);
// Registers one SessionLocal<T> and returns its slot. Called from static initialization.
Uint32 RegisterSessionLocal(SessionLocalConstruct construct, SessionLocalDestroy destroy);
// The calling thread's session, or the process-wide default.
MagmaSession& CurrentMagmaSession();
void* SessionLocalSlot(MagmaSession& session, Uint32 index);
} // namespace Detail
// One served session's copy of every SessionLocal. Slots are built lazily on first use and
// destroyed in reverse registration order with the session still bound, so a destructor that
// reaches another SessionLocal finds this session's copy and not the binding thread's.
class MagmaSession {
public:
MagmaSession();
~MagmaSession();
MagmaSession(const MagmaSession&) = delete;
MagmaSession& operator=(const MagmaSession&) = delete;
// A monotonic id, unique for the process lifetime. Never an address: a later session can
// be allocated where an ended one lived.
Uint64 Id() const { return m_id; }
private:
friend void* Detail::SessionLocalSlot(MagmaSession& session, Uint32 index);
Vector<void*> m_slots;
Uint64 m_id = 0;
};
// Makes `session` the calling thread's Magma session for the scope's lifetime, restoring the
// previous binding (usually none) afterwards.
class MagmaSessionScope {
public:
explicit MagmaSessionScope(MagmaSession* session);
~MagmaSessionScope();
MagmaSessionScope(const MagmaSessionScope&) = delete;
MagmaSessionScope& operator=(const MagmaSessionScope&) = delete;
private:
MagmaSession* m_previous = nullptr;
};
// Binds `session` to the calling thread until the next call (nullptr unbinds). For the apply
// thread, which binds its backend once and runs it for the rest of its life.
void BindMagmaSessionToThisThread(MagmaSession* session);
// The calling thread's bound session, or nullptr (the process-wide default answers).
MagmaSession* BoundMagmaSession();
template <class T>
class SessionLocal {
public:
SessionLocal() : m_index(Detail::RegisterSessionLocal(&Construct, &Destroy)) {}
SessionLocal(const SessionLocal&) = delete;
SessionLocal& operator=(const SessionLocal&) = delete;
T& Get() const {
return *static_cast<T*>(Detail::SessionLocalSlot(Detail::CurrentMagmaSession(), m_index));
}
T& operator*() const { return Get(); }
T* operator->() const { return &Get(); }
private:
static void* Construct() { return new T(); }
static void Destroy(void* object) { delete static_cast<T*>(object); }
const Uint32 m_index;
};
} // namespace MobileGL::MG_Backend::DirectVulkan
@@ -300,15 +300,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
return packet;
}
VkResult FrameContext::AcquireNextImageInCurrentSlot(VkDevice device, VkSwapchainKHR swapchain,
Uint32& outImageIndex) {
auto& frame = GetCurrent();
const VkResult result = vkAcquireNextImageKHR(device, swapchain, UINT64_MAX, frame.imageAvailableSemaphore,
VK_NULL_HANDLE, &outImageIndex);
if (result == VK_SUCCESS || result == VK_SUBOPTIMAL_KHR) frame.imageAvailableSemaphoreConsumed = false;
return result;
}
VkResult FrameContext::WaitAndAcquireNextImage(VkDevice device, VkSwapchainKHR swapchain, Uint32& outImageIndex,
Uint64 timeout, VkFence acquireFence) {
auto& frame = GetCurrent();
@@ -101,13 +101,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
VkImageLayout presentLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR);
SubmitInfoPacket GetSubmitInfo(Bool shouldSubmitCommandBuffer, Uint32 swapchainImageIndex) const;
PresentInfoPacket GetPresentInfo(VkSwapchainKHR swapchain, Uint32 imageIndex) const;
// Acquires into the current slot's semaphore WITHOUT the slot-fence wait: for a surface
// brought up mid-frame, whose slot fence this frame has already waited and reset. The
// slot's semaphore must be unsignaled with no pending signal (consumed).
VkResult AcquireNextImageInCurrentSlot(VkDevice device, VkSwapchainKHR swapchain, Uint32& outImageIndex);
// The per-swapchain-image render-finished semaphores belong to one swapchain; a renderer
// that parks a surface parks them with it.
void ExchangeSwapchainSemaphores(Vector<VkSemaphore>& other) { std::swap(m_swapchainImageRenderFinishedSemaphores, other); }
VkResult WaitAndAcquireNextImage(VkDevice device, VkSwapchainKHR swapchain, Uint32& outImageIndex,
Uint64 timeout = UINT64_MAX, VkFence acquireFence = VK_NULL_HANDLE);
@@ -1,37 +0,0 @@
// MobileGL - MobileGL/MG_Backend/DirectVulkan/Renderer/OffscreenSurfaceRoute.h
// Copyright (c) 2025-2026 MobileGL-Dev
// Licensed under the GNU Lesser General Public License v3.0:
// https://www.gnu.org/licenses/gpl-3.0.txt
// https://www.gnu.org/licenses/lgpl-3.0.txt
// SPDX-License-Identifier: LGPL-3.0-only
// End of Source File Header
// How an offscreen (pbuffer) surface target gets its VkSurfaceKHR on Android, decided from what the
// INSTANCE has, not from what the loader could offer. A renderer created for a window enabled
// VK_KHR_android_surface and nothing headless, so its later offscreen targets (a second client
// surface, or the placeholder a suspended server window draws into) must take the AImageReader
// route; asking that instance for vkCreateHeadlessSurfaceEXT answers null. Pure, so a host case pins
// it without a driver.
#pragma once
#include <Includes.h>
namespace MobileGL::MG_Backend::DirectVulkan {
enum class OffscreenSurfaceRoute : Uint8 {
Headless, // vkCreateHeadlessSurfaceEXT
AndroidImageReader, // vkCreateAndroidSurfaceKHR on an AImageReader's window nobody displays
Unavailable, // neither: the target cannot be built (the caller refuses, by name)
};
// `headlessEnabled`: the instance was created with VK_EXT_headless_surface.
// `headlessEntryPoint`: vkGetInstanceProcAddr answered vkCreateHeadlessSurfaceEXT.
// `androidSurfaceEnabled`: the instance was created with VK_KHR_android_surface.
constexpr OffscreenSurfaceRoute ChooseOffscreenSurfaceRoute(Bool headlessEnabled, Bool headlessEntryPoint,
Bool androidSurfaceEnabled) {
if (headlessEnabled && headlessEntryPoint) return OffscreenSurfaceRoute::Headless;
if (androidSurfaceEnabled) return OffscreenSurfaceRoute::AndroidImageReader;
return OffscreenSurfaceRoute::Unavailable;
}
} // namespace MobileGL::MG_Backend::DirectVulkan
@@ -199,7 +199,7 @@ namespace MobileGL::MG_Backend::DirectVulkan {
UnorderedMap<HashType, PipelineCacheEntry> m_cache;
// Monotonic frame-boundary counter (bumped in OnFrameBoundary) for cache aging.
Uint64 m_frameCounter = 0;
static inline thread_local XXH64_state_t* m_hashState = XXH64_createState();
static inline XXH64_state_t* m_hashState = XXH64_createState();
static inline Bool s_suppressBlendedDepthWrite = false;
};
} // namespace MobileGL::MG_Backend::DirectVulkan
@@ -1313,30 +1313,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
}
});
if (!ok) return false;
// An access chain into the builtin (gl_FragCoord.y is one) carries an Input
// pointer type. Based on the Private copy it has to carry a Private one, and so
// does every chain built on top of it - otherwise the module hands the driver a
// pointer whose storage class disagrees with its base, which is invalid SPIR-V
// and reads an undefined value. Plan every retype before touching anything, so a
// shape this pass does not model declines the whole rewrite.
Vector<Pair<Instruction*, Uint32>> retypes;
Vector<Instruction*> chains;
for (Instruction* user : users) {
if (IsAccessChain(user->opcode())) chains.push_back(user);
}
while (!chains.empty()) {
Instruction* chain = chains.back();
chains.pop_back();
const Uint32 privateType = PrivatePointerTypeFor(chain->type_id());
if (privateType == 0) return false;
retypes.emplace_back(chain, privateType);
context()->get_def_use_mgr()->ForEachUser(chain, [&](Instruction* next) {
if (IsAccessChain(next->opcode()) && next->NumInOperands() > 0 &&
next->GetSingleWordInOperand(0) == chain->result_id()) {
chains.push_back(next);
}
});
}
for (Instruction* user : users) {
for (Uint32 i = 0; i < user->NumInOperands(); ++i) {
auto& operand = user->GetInOperand(i);
@@ -1347,32 +1323,9 @@ namespace MobileGL::MG_Backend::DirectVulkan {
}
context()->AnalyzeUses(user);
}
for (auto& [chain, privateType] : retypes) {
chain->SetResultType(privateType);
context()->AnalyzeUses(chain);
}
return true;
}
static Bool IsAccessChain(spv::Op opcode) {
return opcode == spv::Op::OpAccessChain || opcode == spv::Op::OpInBoundsAccessChain ||
opcode == spv::Op::OpPtrAccessChain || opcode == spv::Op::OpInBoundsPtrAccessChain;
}
// The Private-storage twin of an Input pointer type, or 0 when `pointerTypeId` is not
// an Input pointer (then the chain is not the shape this pass rewrites).
Uint32 PrivatePointerTypeFor(Uint32 pointerTypeId) {
using namespace spvtools::opt;
Instruction* pointerType = context()->get_def_use_mgr()->GetDef(pointerTypeId);
if (!pointerType || pointerType->opcode() != spv::Op::OpTypePointer) return 0;
if (static_cast<spv::StorageClass>(pointerType->GetSingleWordInOperand(0)) !=
spv::StorageClass::Input) {
return 0;
}
return context()->get_type_mgr()->FindPointerToType(pointerType->GetSingleWordInOperand(1),
spv::StorageClass::Private);
}
Uint32 m_framebufferHeight = 0;
};
@@ -1908,38 +1861,35 @@ namespace MobileGL::MG_Backend::DirectVulkan {
return spvtools::Optimizer::PassToken(MakeUnique<GlToVulkanPositionFixPass>(transformFlags));
}
} // namespace
Bool TransformSpirvForFragCoordYFlip(const Vector<Uint>& input, Vector<Uint>& output,
Uint32 framebufferHeight) {
if (input.empty()) {
output.clear();
return true;
}
if (framebufferHeight == 0) {
output = input;
return true;
}
Bool TransformSpirvForFragCoordYFlip(const Vector<Uint>& input, Vector<Uint>& output,
Uint32 framebufferHeight) {
if (input.empty()) {
output.clear();
return true;
}
if (framebufferHeight == 0) {
output = input;
return true;
spvtools::Optimizer optimizer(SPV_ENV_VULKAN_1_3);
spvtools::OptimizerOptions options;
options.set_run_validator(false); // see TransformSpirvForExplicitLod0Sampling
optimizer.SetMessageConsumer([](spv_message_level_t, const char*, const spv_position_t&,
const char* message) {
MGLOG_E("Vulkan: fragcoord y-flip pass: %s", message != nullptr ? message : "");
});
optimizer.RegisterPass(
spvtools::Optimizer::PassToken(MakeUnique<GlFragCoordYFlipPass>(framebufferHeight)));
const Bool success = optimizer.Run(input.data(), input.size(), &output, options);
if (!success) {
MGLOG_E("Vulkan: failed to run the gl_FragCoord y-flip pass; keeping the original module");
output = input;
}
return success;
}
spvtools::Optimizer optimizer(SPV_ENV_VULKAN_1_3);
spvtools::OptimizerOptions options;
options.set_run_validator(false); // see TransformSpirvForExplicitLod0Sampling
optimizer.SetMessageConsumer([](spv_message_level_t, const char*, const spv_position_t&,
const char* message) {
MGLOG_E("Vulkan: fragcoord y-flip pass: %s", message != nullptr ? message : "");
});
optimizer.RegisterPass(
spvtools::Optimizer::PassToken(MakeUnique<GlFragCoordYFlipPass>(framebufferHeight)));
const Bool success = optimizer.Run(input.data(), input.size(), &output, options);
if (!success) {
MGLOG_E("Vulkan: failed to run the gl_FragCoord y-flip pass; keeping the original module");
output = input;
}
return success;
}
namespace {
Bool TransformSpirvForXfbCapture(const Vector<Uint>& input, Vector<Uint>& output,
const MagmaProgramSource& program) {
if (input.empty()) {
@@ -9,7 +9,6 @@
#pragma once
#include "../VkIncludes.h"
#include "../MagmaSession.h"
#include "PipelineFactory.h"
#include "MagmaProgramSource.h"
#include "MG_State/GLState/ProgramState/ShaderObject.h"
@@ -252,7 +251,7 @@ namespace MobileGL::MG_Backend::DirectVulkan {
// entry pointer re-stamps use through a const reference (StampProgramUse).
mutable Uint64 lastUsedFrame = 0;
static inline SessionLocal<VkDevice> s_device; // per Magma session (MagmaSession.h)
static inline VkDevice s_device = VK_NULL_HANDLE;
VkProgramObject() = default;
VkProgramObject(const VkProgramObject&) = delete;
@@ -396,18 +395,18 @@ namespace MobileGL::MG_Backend::DirectVulkan {
private:
void Destroy() {
if (s_device.Get() != VK_NULL_HANDLE) {
if (s_device != VK_NULL_HANDLE) {
if (pipelineLayout != VK_NULL_HANDLE) {
vkDestroyPipelineLayout(s_device.Get(), pipelineLayout, nullptr);
vkDestroyPipelineLayout(s_device, pipelineLayout, nullptr);
pipelineLayout = VK_NULL_HANDLE;
}
if (descriptorSetLayout != VK_NULL_HANDLE) {
vkDestroyDescriptorSetLayout(s_device.Get(), descriptorSetLayout, nullptr);
vkDestroyDescriptorSetLayout(s_device, descriptorSetLayout, nullptr);
descriptorSetLayout = VK_NULL_HANDLE;
}
for (auto module : modules) {
if (module != VK_NULL_HANDLE) {
vkDestroyShaderModule(s_device.Get(), module, nullptr);
vkDestroyShaderModule(s_device, module, nullptr);
}
}
}
@@ -464,7 +463,7 @@ namespace MobileGL::MG_Backend::DirectVulkan {
m_enableSpirvValidation(enableSpirvValidation),
m_updateAfterBindLimits(updateAfterBindLimits),
m_subgroupPolicy(subgroupPolicy) {
VkProgramObject::s_device.Get() = device;
VkProgramObject::s_device = device;
}
// Destroys the pass-through tessellation control modules. Runs while the device is
// still alive for the same reason ~VkProgramObject's does: this factory outlives
@@ -656,11 +655,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
// and adds only a handful of values, so it does not move the cap in practice.
static constexpr SizeT kMaxPassthroughTessControlStages = 64;
UnorderedMap<Uint64, VkPipelineShaderStageCreateInfo> m_passthroughTessControlStages;
static inline thread_local XXH64_state_t* m_hashState = XXH64_createState();
static inline XXH64_state_t* m_hashState = XXH64_createState();
};
// The FragCoordYFlip variant's module transform: every read of gl_FragCoord goes through a
// Private copy whose y is (framebufferHeight - y). Fails open (output = input, false). Exposed
// so a unit case can validate the bytes it hands the driver.
Bool TransformSpirvForFragCoordYFlip(const Vector<Uint>& input, Vector<Uint>& output, Uint32 framebufferHeight);
} // namespace MobileGL::MG_Backend::DirectVulkan
@@ -292,8 +292,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
// Fresh swapchain images hold garbage until a render pass stores into them.
m_imageContentDefined.assign(imageCount, false);
m_depthStencilContentDefined.assign(imageCount, false);
// Nothing presented from this chain yet: every buffer age is unknown.
m_ages.Reset(imageCount);
CreateImageViews(device);
CreateDepthStencilResources(device, physicalDevice);
@@ -301,11 +299,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
MGLOG_I("Swapchain created, extent = %dx%d, swapchain imageCount = %d", m_extent.width, m_extent.height,
imageCount);
PublishDefaultFramebufferInfo();
}
void SwapchainObject::PublishDefaultFramebufferInfo() const {
const VkExtent2D defaultFramebufferExtent = m_surfaceExtent;
// Properly initialize Default FBO here
auto& defaultFBOInfo = MG_Impl::GLImpl::FramebufferImpl::pDefaultFramebufferInfo;
const Int extentWidth = static_cast<Int>(defaultFramebufferExtent.width);
@@ -495,7 +488,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
m_imageLayouts.clear();
m_imageContentDefined.clear();
m_depthStencilContentDefined.clear();
m_ages.Reset(0);
m_preTransform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
}
@@ -9,7 +9,6 @@
#pragma once
#include <Includes.h>
#include <MG_Util/Damage/Damage.h>
#include "../VkIncludes.h"
namespace MobileGL::MG_Backend::DirectVulkan {
@@ -39,9 +38,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
Uint32 presentQueueFamily, Uint32 minImageCountHint, VkExtent2D desiredExtent,
Optional<Int> swapInterval);
void Shutdown(VkDevice device);
// Tells the frontend (or, under a transport, the client) the default framebuffer's size
// and formats. Create does this; a renderer switching between surfaces repeats it.
void PublishDefaultFramebufferInfo() const;
VkSwapchainKHR GetHandle() const { return m_swapchain; }
VkPresentModeKHR GetPresentMode() const { return m_presentMode; }
@@ -81,18 +77,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
void SetDepthStencilContentDefined(Uint32 index, Bool defined);
void SetAllDepthStencilContentUndefined();
// EGL_EXT_buffer_age over this chain's images. Ages start unknown with the chain (Create).
// Until a client asks for an age (NoteBufferAgeAsked) a presented image's content is
// treated as undefined, as before; once one has, a presented image keeps it - its age is
// counted and its content stays defined, so the next frame loads it.
void NoteBufferAgeAsked() { m_bufferAgeAsked = true; }
Bool BufferAgeAsked() const { return m_bufferAgeAsked; }
Int32 BufferAgeOf(Uint32 index) const { return m_ages.AgeOf(index); }
// Image `index` was presented.
void OnImagePresented(Uint32 index) { m_ages.OnPresented(index, m_bufferAgeAsked); }
// A swapped frame reached no image: every age is unknown.
void OnFrameDropped() { m_ages.OnFrameDropped(); }
private:
void CreateImageViews(VkDevice device);
void CreateDepthStencilResources(VkDevice device, VkPhysicalDevice physicalDevice);
@@ -122,8 +106,5 @@ namespace MobileGL::MG_Backend::DirectVulkan {
Vector<VkImageLayout> m_depthStencilImageLayouts;
Vector<Bool> m_imageContentDefined;
Vector<Bool> m_depthStencilContentDefined;
MG_Util::Damage::SwapchainAgeTracker m_ages;
// Kept across a rebuild: it is the application's habit, not the chain's.
Bool m_bufferAgeAsked = false;
};
} // namespace MobileGL::MG_Backend::DirectVulkan
@@ -262,8 +262,7 @@ namespace MobileGL::MG_Backend::DirectVulkan {
info.format = format;
info.subresourceRange = {aspect, level, levels, layer, layers};
if (!storage) {
// An X-format shared image carries undefined alpha bytes, exactly like an expanded RGB.
const Bool alphaIsOne = resource->sharedImageAlphaOne || ResolveTextureFormatInfo(
const Bool alphaIsOne = ResolveTextureFormatInfo(
static_cast<TextureInternalFormat>(record.Desc.InternalFormat)).expandRgbToRgba;
const auto swizzle = [&](Uint32 channel) {
const auto value = record.Params.Swizzle[channel];
@@ -294,22 +293,11 @@ namespace MobileGL::MG_Backend::DirectVulkan {
} else {
auto samplerHandle = state.BoundSamplerStates[unit];
if (MG_Pipe::MGPipeHandleIsNull(samplerHandle)) samplerHandle = record.Params.BuiltinSampler;
// A texture's built-in sampler CSO can be missing or gone while the texture still names
// it: sampler CSOs are content-addressed and recycled at capacity, and the texture's
// record is only re-pointed by its next set_texture_params (a texture whose params never
// crossed names none at all). Sample with GL's default parameters rather than end the
// session - the DirectGLES arm declines the push in both cases.
using SamplerCsoRecord = std::decay_t<decltype(state.SamplerCsos[0])>;
static const decltype(SamplerCsoRecord::Params) kDefaultSamplerParams{};
const Bool known = !MG_Pipe::MGPipeHandleIsNull(samplerHandle) &&
samplerHandle.Slot < state.SamplerCsos.size();
const SamplerCsoRecord* sampler = known ? &state.SamplerCsos[samplerHandle.Slot] : nullptr;
const Bool stale = sampler == nullptr || !sampler->Live || sampler->Gen != samplerHandle.Gen;
if (stale) {
MGLOG_E_ONCE("Magma wire: sampler CSO {%u, %u} named by texture unit %u is missing or no longer "
"live; sampling with default parameters", samplerHandle.Slot, samplerHandle.Gen, unit);
}
out.sampler = m_samplerManager->GetOrCreateSamplerFromParameters(stale ? kDefaultSamplerParams : sampler->Params,
if (MG_Pipe::MGPipeHandleIsNull(samplerHandle) || samplerHandle.Slot >= state.SamplerCsos.size())
WireDescriptorFatal("sampler-record");
const auto& sampler = state.SamplerCsos[samplerHandle.Slot];
if (!sampler.Live || sampler.Gen != samplerHandle.Gen) WireDescriptorFatal("sampler-record-generation");
out.sampler = m_samplerManager->GetOrCreateSamplerFromParameters(sampler.Params,
static_cast<TextureInternalFormat>(record.Desc.InternalFormat),
domain == SamplerNumericDomain::SignedInteger || domain == SamplerNumericDomain::UnsignedInteger,
levels);
@@ -3195,10 +3183,7 @@ namespace MobileGL::MG_Backend::DirectVulkan {
// preparing the texture would decline a storage-less one and lose the pass.
if (storage && WireShaderImageNamesNoTexel(*m_textureManager, state.BoundShaderImages[unit]))
continue;
const auto* resource = m_textureManager->SyncTextureResourceByHandle(handle, false, storage);
if (resource == nullptr) return false;
// Another session writes it: the renderer acquires it before this use.
if (resource->sharedImageId != 0) m_textureManager->NoteSharedImageUse(*resource);
if (!m_textureManager->SyncTextureResourceByHandle(handle, false, storage)) return false;
}
}
}
@@ -19,7 +19,6 @@
#include "VertexInputStateBuilder.h"
#include "MG_State/GLState/VertexArrayState/VertexArrayObject.h"
#include <Includes.h>
#include <atomic>
#include "../VkIncludes.h"
namespace MobileGL::MG_Backend::DirectVulkan {
@@ -218,11 +217,11 @@ namespace MobileGL::MG_Backend::DirectVulkan {
// memo table is owned by this factory and dies with it, so a per-instance counter is
// enough there and the epoch shrinks back to what it looks like it should be.
#if MOBILEGL_PIPE_LEGACY_MEMOS
static inline std::atomic<Uint64> s_evictionEpochSource{0};
static inline Uint64 s_evictionEpochSource = 0;
Uint64 m_evictionEpoch = ++s_evictionEpochSource;
#else
Uint64 m_evictionEpoch = 1;
#endif
static inline thread_local XXH64_state_t* m_hashState = XXH64_createState();
static inline XXH64_state_t* m_hashState = XXH64_createState();
};
} // namespace MobileGL::MG_Backend::DirectVulkan
@@ -113,30 +113,30 @@ namespace MobileGL::MG_Backend::DirectVulkan {
using MG_State::GLState::BufferObject;
// The manager owned by the active VulkanRenderer; immediate ops route here.
SessionLocal<VkBufferManager*> g_activeBufferManager; // per Magma session (MagmaSession.h)
VkBufferManager* g_activeBufferManager = nullptr;
void Ops_Respecify(BufferObject& bufferObject) {
if (g_activeBufferManager.Get()) {
g_activeBufferManager.Get()->OnRespecify(bufferObject);
if (g_activeBufferManager) {
g_activeBufferManager->OnRespecify(bufferObject);
}
}
void Ops_SubData(BufferObject& bufferObject, SizeT offset, SizeT size) {
if (g_activeBufferManager.Get()) {
g_activeBufferManager.Get()->OnSubData(bufferObject, offset, size);
if (g_activeBufferManager) {
g_activeBufferManager->OnSubData(bufferObject, offset, size);
}
}
void Ops_ResidentSubData(BufferObject& bufferObject, SizeT offset, DataPtr data) {
if (g_activeBufferManager.Get()) {
g_activeBufferManager.Get()->OnResidentSubData(bufferObject, offset, data);
if (g_activeBufferManager) {
g_activeBufferManager->OnResidentSubData(bufferObject, offset, data);
}
}
void Ops_FlushMappedRange(BufferObject& bufferObject, Range1D range,
Flags<BufferMappingAccessBit> appAccess) {
if (g_activeBufferManager.Get()) {
g_activeBufferManager.Get()->OnFlushMappedRange(bufferObject, range, appAccess);
if (g_activeBufferManager) {
g_activeBufferManager->OnFlushMappedRange(bufferObject, range, appAccess);
}
}
@@ -154,15 +154,15 @@ namespace MobileGL::MG_Backend::DirectVulkan {
}
void* Ops_AcquirePersistentMap(BufferObject& bufferObject) {
if (g_activeBufferManager.Get()) {
return g_activeBufferManager.Get()->AcquirePersistentMap(bufferObject);
if (g_activeBufferManager) {
return g_activeBufferManager->AcquirePersistentMap(bufferObject);
}
return nullptr;
}
void Ops_OnDestroy(SharedPtr<BackendBufferResource>&& resource) {
if (g_activeBufferManager.Get()) {
g_activeBufferManager.Get()->OnResourceDestroyed(std::move(resource));
if (g_activeBufferManager) {
g_activeBufferManager->OnResourceDestroyed(std::move(resource));
}
// No active manager: the device/allocator is gone or going away and
// Shutdown() already destroyed the storage; dropping the handle here
@@ -181,39 +181,34 @@ namespace MobileGL::MG_Backend::DirectVulkan {
};
#if MOBILEGL_BUILD_DISAGGREGATED
// The session's manager, or null once its renderer is gone - a client's records can still
// arrive after its eglTerminate released it (or, surfaceless, before its first surface built
// one). Such a record is declined with one line rather than taking the whole server down.
VkBufferManager* WireManager(const char* op) {
VkBufferManager* manager = g_activeBufferManager.Get();
if (manager == nullptr) {
MGLOG_E_ONCE("Magma: a wire buffer %s reached a session with no renderer; declined", op);
VkBufferManager& WireManager() {
if (g_activeBufferManager == nullptr) {
MGLOG_F("Magma: Fatal{ResourceUnavailable, \"wire-buffer-manager\"}");
std::abort();
}
return manager;
return *g_activeBufferManager;
}
const MG_Pipe::MGPipeResourceOps g_vulkanWireResourceOps = {
.Create = [](auto res, const auto& desc) { if (auto* m = WireManager("create")) m->CreateWireBuffer(res, desc); },
.Create = [](auto res, const auto& desc) { WireManager().CreateWireBuffer(res, desc); },
.Respecify = [](auto res, const auto& desc, const void* bytes) {
if (auto* m = WireManager("respecify")) m->RespecifyWireBuffer(res, desc, bytes);
WireManager().RespecifyWireBuffer(res, desc, bytes);
},
.SubData = [](auto res, const auto& record, const void* bytes) {
if (auto* m = WireManager("write"))
m->WriteWireBuffer(res, MG_Pipe::MGPipeSubDataBufferOffset(record),
MG_Pipe::MGPipeSubDataBufferSize(record), bytes);
WireManager().WriteWireBuffer(res, MG_Pipe::MGPipeSubDataBufferOffset(record),
MG_Pipe::MGPipeSubDataBufferSize(record), bytes);
},
.SubDataResident = [](auto res, const auto& record, const void* bytes) {
if (auto* m = WireManager("write"))
m->WriteWireBuffer(res, MG_Pipe::MGPipeSubDataBufferOffset(record),
MG_Pipe::MGPipeSubDataBufferSize(record), bytes);
WireManager().WriteWireBuffer(res, MG_Pipe::MGPipeSubDataBufferOffset(record),
MG_Pipe::MGPipeSubDataBufferSize(record), bytes);
},
.FlushRange = [](auto res, const auto& record, const void* bytes) {
if (auto* m = WireManager("flush")) m->FlushWireBuffer(res, record.Offset, record.Size, bytes);
WireManager().FlushWireBuffer(res, record.Offset, record.Size, bytes);
},
.Readback = [](auto res, const auto& record) {
if (auto* m = WireManager("readback")) m->ReadbackWireBuffer(res, record.Offset, record.Size);
WireManager().ReadbackWireBuffer(res, record.Offset, record.Size);
},
.Destroy = [](auto res) { if (auto* m = WireManager("destroy")) m->DestroyWireBuffer(res); },
.Destroy = [](auto res) { WireManager().DestroyWireBuffer(res); },
// Split mapping remains T2: the client owns its map and pushes exact
// modified ranges. A server pointer is never donated across the wire.
.MapPersistent = [](MG_Pipe::MGPipeHandle, Uint64, const void*) -> void* { return nullptr; },
@@ -222,8 +217,7 @@ namespace MobileGL::MG_Backend::DirectVulkan {
// P11 B2 (T0): the one door a server pointer is still never donated through stays shut;
// what T0 adds is the other direction - the CLIENT's pages imported as the store.
.ImportExternal = [](MG_Pipe::MGPipeHandle res, void* ahb, Uint64 size) -> Bool {
auto* m = WireManager("import");
return m != nullptr && m->ImportWireBuffer(res, ahb, size);
return WireManager().ImportWireBuffer(res, ahb, size);
},
.SelfTestExternal = [](char* why, Uint64 whyBytes) -> Bool {
return VkBufferManager::SelfTestWireImport(why, whyBytes);
@@ -240,18 +234,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
}
}
namespace {
// Diagnostic memory for DescribeWireBufferHistory: the last handles created and destroyed.
struct WireBufferHistory {
static constexpr SizeT kDepth = 256;
MG_Pipe::MGPipeHandle created[kDepth]{};
MG_Pipe::MGPipeHandle destroyed[kDepth]{};
SizeT createdCount = 0;
SizeT destroyedCount = 0;
};
SessionLocal<WireBufferHistory> g_wireBufferHistory;
} // namespace
VkBufferManager::WireBufferResource* VkBufferManager::FindWireBuffer(MG_Pipe::MGPipeHandle res) {
const auto found = m_wireBuffers.find(WireBufferKey(res));
return found == m_wireBuffers.end() ? nullptr : &found->second;
@@ -264,10 +246,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
std::abort();
}
m_wireBuffers.try_emplace(WireBufferKey(res));
{
auto& history = *g_wireBufferHistory;
history.created[history.createdCount++ % 256] = res;
}
RespecifyWireBuffer(res, desc, nullptr);
}
@@ -425,10 +403,7 @@ namespace MobileGL::MG_Backend::DirectVulkan {
uploaded = StagedWireRangeCopy(*resource, bytes, static_cast<SizeT>(offset),
static_cast<SizeT>(size));
}
if (!uploaded && !WaitForWireBufferHostAccess(*resource)) {
if (LatchedOnDeviceLoss("buffer-host-write")) return;
WireBufferSyncFatal("host-write");
}
if (!uploaded && !WaitForWireBufferHostAccess(*resource)) WireBufferSyncFatal("host-write");
}
if (!uploaded) {
uploaded = resource->buffer.Upload(bytes, size, offset);
@@ -437,7 +412,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
}
}
if (!uploaded) {
if (LatchedOnDeviceLoss("buffer-upload")) return;
MGLOG_F("Magma: Fatal{ResourceUnavailable, \"buffer-upload\"}");
std::abort();
}
@@ -608,8 +582,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
const Bool t0 = resource != nullptr && resource->imported;
Vector<Uint8> bytes(t0 ? 0 : static_cast<SizeT>(size));
if (t0 ? !WaitForWireBufferHostAccess(*resource) : !ReadWireBuffer(res, offset, size, bytes.data())) {
// A lost device: the session is latched and closing; its client reads a lost context.
if (LatchedOnDeviceLoss("buffer-readback")) return;
MGLOG_F("Magma: Fatal{ResourceUnavailable, \"buffer-readback\"} {slot=%u, gen=%u}", res.Slot, res.Gen);
std::abort();
}
@@ -814,9 +786,7 @@ namespace MobileGL::MG_Backend::DirectVulkan {
// read - this server's own host map of the import reads what the CPU wrote through the lock;
// gpu - one submission copies that pattern out of the import (the GPU read) and fills another
// region of it (the GPU write), then a transfer->host barrier and a fence wait;
// back - the fill is read through the HELD pointer, the copy from a host-visible staging buffer;
// steady - the same again with bytes the CPU wrote AFTER the import and its first GPU use (the
// block at the end says why the first round alone is not enough).
// back - the fill is read through the HELD pointer, the copy from a host-visible staging buffer.
Bool VkBufferManager::SelfTestWireImport(char* whyOut, Uint64 whyBytes) {
const auto answer = [&](Bool ok, const String& text) {
std::snprintf(whyOut, static_cast<SizeT>(whyBytes), "%s", text.c_str());
@@ -939,55 +909,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
String(imported.coherent ? "coherent" : "non-coherent") + " memory), GPU read " +
std::to_string(gpuRead) + "/1024 words of the CPU's pattern, GPU write seen through the "
"held lock " + std::to_string(heldSaw) + "/1024 words";
if (!ok) break;
// STEADY STATE. The round above reads bytes the CPU wrote BEFORE the import, and an import
// can clean the CPU's caches on its way in, so it passes on a device whose GPU never sees a
// write made through the held lock afterwards - which is all of T0's real traffic (Mali-G1
// on a Dimensity: the first round passed, then Flywheel's staging scatter read stale bytes
// and the create-indirect trace lost every instanced object). So the CPU now writes a fresh
// pattern into region 1 and reads region 4 back into its cache, and one more submission
// copies region 1 out and overwrites region 4.
constexpr Uint64 kSteadyAt = 1 * 4096; // region 1
constexpr Uint32 kSteadyFillWord = 0x3D5EA11Eu;
auto* heldWrite = static_cast<volatile Uint32*>(held.ptr);
Uint32 cached = 0;
for (Uint32 i = 0; i < kWords; ++i) {
heldWrite[kSteadyAt / 4 + i] = 0xA5000000u ^ (i * 40503u);
cached ^= heldWrite[kFillAt / 4 + i];
}
(void)cached;
std::memset(staging.mapped, 0, kWords * 4);
if (vkResetFences(ctx.device, 1, &fence) != VK_SUCCESS ||
vkResetCommandPool(ctx.device, pool, 0) != VK_SUCCESS ||
vkBeginCommandBuffer(commands, &begin) != VK_SUCCESS) {
ok = false;
verdict = "steady: the second submission could not be recorded";
break;
}
vkCmdPipelineBarrier(commands, VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 1,
&hostWrites, 0, nullptr, 0, nullptr);
VkBufferCopy steadyRegion{kSteadyAt, 0, kWords * 4};
vkCmdCopyBuffer(commands, imported.buffer, staging.buffer, 1, &steadyRegion);
vkCmdFillBuffer(commands, imported.buffer, kFillAt, kWords * 4, kSteadyFillWord);
vkCmdPipelineBarrier(commands, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_HOST_BIT, 0, 1, &toHost,
0, nullptr, 0, nullptr);
vkEndCommandBuffer(commands);
if (vkQueueSubmit(ctx.queue, 1, &submit, fence) != VK_SUCCESS ||
vkWaitForFences(ctx.device, 1, &fence, VK_TRUE, 2'000'000'000ull) != VK_SUCCESS) {
ok = false;
verdict = "steady: the second submission did not complete within 2 s";
break;
}
Uint32 steadyRead = 0, steadySaw = 0;
for (Uint32 i = 0; i < kWords; ++i) {
if (copied[i] == (0xA5000000u ^ (i * 40503u))) ++steadyRead;
if (heldWords[kFillAt / 4 + i] == kSteadyFillWord) ++steadySaw;
}
ok = steadyRead == kWords && steadySaw == kWords;
verdict += "; with the import in use, GPU read " + std::to_string(steadyRead) +
"/1024 words the CPU wrote after it, GPU write seen through the held lock " +
std::to_string(steadySaw) + "/1024 words";
} while (false);
if (fence != VK_NULL_HANDLE) vkDestroyFence(ctx.device, fence, nullptr);
if (pool != VK_NULL_HANDLE) vkDestroyCommandPool(ctx.device, pool, nullptr);
@@ -1000,29 +921,7 @@ namespace MobileGL::MG_Backend::DirectVulkan {
#endif
}
void VkBufferManager::DescribeWireBufferHistory(MG_Pipe::MGPipeHandle res) const {
const auto& history = *g_wireBufferHistory;
Int createdAgo = -1, destroyedAgo = -1;
for (SizeT i = 0; i < std::min(history.createdCount, WireBufferHistory::kDepth); ++i) {
const auto& h = history.created[(history.createdCount - 1 - i) % WireBufferHistory::kDepth];
if (h.Slot == res.Slot && h.Gen == res.Gen) { createdAgo = static_cast<Int>(i); break; }
}
for (SizeT i = 0; i < std::min(history.destroyedCount, WireBufferHistory::kDepth); ++i) {
const auto& h = history.destroyed[(history.destroyedCount - 1 - i) % WireBufferHistory::kDepth];
if (h.Slot == res.Slot && h.Gen == res.Gen) { destroyedAgo = static_cast<Int>(i); break; }
}
MGLOG_E("Magma wire buffer {slot=%u, gen=%u}: live stores %zu; created %d creates ago, destroyed %d "
"destroys ago (-1 = not in the last %zu); %zu creates, %zu destroys in this session",
res.Slot, res.Gen, m_wireBuffers.size(), createdAgo, destroyedAgo, WireBufferHistory::kDepth,
history.createdCount, history.destroyedCount);
}
void VkBufferManager::DestroyWireBuffer(MG_Pipe::MGPipeHandle res) {
{
auto& history = *g_wireBufferHistory;
history.destroyed[history.destroyedCount++ % WireBufferHistory::kDepth] = res;
}
const auto found = m_wireBuffers.find(WireBufferKey(res));
if (found == m_wireBuffers.end()) return;
DeferWireRelease(std::move(found->second.buffer),
@@ -1080,7 +979,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
// budget's worth of orphans, not one per glBufferData.
if (pVulkanRenderer == nullptr ||
!pVulkanRenderer->WaitForSubmitIndex(pVulkanRenderer->GetSyncPointSubmitIndex(), UINT64_MAX, true)) {
if (LatchedOnDeviceLoss("buffer-deferred-watermark")) return;
WireBufferSyncFatal("deferred-watermark");
}
++m_wireDeferredSyncs;
@@ -1101,10 +999,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
MG_Util::PipeStats::PublishGauge(Gauge::WireDeferredSyncs, m_wireDeferredSyncs);
}
Bool VkBufferManager::LatchedOnDeviceLoss(const char* site) {
return pVulkanRenderer != nullptr && pVulkanRenderer->LatchWireDeviceLoss(site);
}
void VkBufferManager::WireBufferSyncFatal(const char* site) {
MGLOG_F("Magma: Fatal{ResourceUnavailable, \"buffer-write-sync\"} {site=%s}", site);
std::abort();
@@ -1178,7 +1072,7 @@ namespace MobileGL::MG_Backend::DirectVulkan {
if (!InitializeTransientArenas()) {
return false;
}
g_activeBufferManager.Get() = this;
g_activeBufferManager = this;
MG_State::GLState::SetBufferBackendOps(&g_vulkanBufferBackendOps);
#if MOBILEGL_BUILD_DISAGGREGATED
RegisterWireResourceOps();
@@ -1187,15 +1081,10 @@ namespace MobileGL::MG_Backend::DirectVulkan {
}
void VkBufferManager::Shutdown() {
if (g_activeBufferManager.Get() == this) {
g_activeBufferManager.Get() = nullptr;
if (g_activeBufferManager == this) {
g_activeBufferManager = nullptr;
#if MOBILEGL_BUILD_DISAGGREGATED
// Under a transport the table is the PROCESS's and serves every session: it dispatches
// to the calling session's own manager (WireManager), so one session's renderer going
// away must not take it from the others - their buffer creates would be dropped from
// then on, and every buffer born after that would be a handle the server never saw.
if (MG_Config::Transport == MG_Config::TransportMode::Monolith &&
MG_Pipe::MGPipeGetResourceOps() == &g_vulkanWireResourceOps) {
if (MG_Pipe::MGPipeGetResourceOps() == &g_vulkanWireResourceOps) {
MG_Pipe::MGPipeSetResourceOps(nullptr);
}
#endif
@@ -110,10 +110,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
// frontend BufferObject. Acquires expose the full GPU store, without a CPU
// pointer: CPU consumers must use ReadWireBuffer for ordered, current bytes.
Bool AcquireWireSlice(BufferKind kind, MG_Pipe::MGPipeHandle res, BufferSlice& outSlice);
// The handle names a store this session created (whatever its size, zero included).
Bool IsKnownWireBuffer(MG_Pipe::MGPipeHandle res) { return FindWireBuffer(res) != nullptr; }
// Names, for a Fatal about an unknown handle, whether this manager ever saw it.
void DescribeWireBufferHistory(MG_Pipe::MGPipeHandle res) const;
Bool ReadWireBuffer(MG_Pipe::MGPipeHandle res, Uint64 offset, Uint64 size, void* dst);
Bool CopyWireBufferRangeToSlice(MG_Pipe::MGPipeHandle res, Uint64 offset, Uint64 size,
const BufferSlice& dst);
@@ -362,10 +358,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
// for the census to count), shared by the host write that cannot wait for the GPU and
// the watermark that cannot. `site` says which.
[[noreturn]] static void WireBufferSyncFatal(const char* site);
// True when the wait or copy that just failed failed because the device is lost: the
// session has been latched (VulkanRenderer::LatchWireDeviceLoss) and the caller returns
// instead of taking its Fatal.
static Bool LatchedOnDeviceLoss(const char* site);
// The wbuf[] gauges (PipeStats.h, Gauge::WireBuffers..WireDeferredSyncs). The peaks are
// taken at the two points the numbers can rise - a park and a mint - and published when
// the stats channel is on; MagmaWireReclaimScenario reads them off the server's line.
@@ -235,11 +235,11 @@ namespace MobileGL::MG_Backend::DirectVulkan {
VkClearManager& clearManager, VkTextureManager& textureManager, SwapchainObject& swapchainObject):
m_device(device), m_physicalDevice(physicalDevice), m_allocator(allocator), m_config(config),
m_clearManager(clearManager), m_textureManager(textureManager), m_swapchainObject(swapchainObject) {
RenderPassEntry::s_device.Get() = m_device;
s_clearManager.Get() = &m_clearManager;
s_textureManager.Get() = &m_textureManager;
s_swapchainObject.Get() = &m_swapchainObject;
s_renderPassManager.Get() = this;
RenderPassEntry::s_device = m_device;
s_clearManager = &m_clearManager;
s_textureManager = &m_textureManager;
s_swapchainObject = &m_swapchainObject;
s_renderPassManager = this;
}
VkRenderPassManager::~VkRenderPassManager() {}
@@ -257,8 +257,8 @@ namespace MobileGL::MG_Backend::DirectVulkan {
CollectDeferredRenderbufferReleases(/*destroyAll=*/true); // caller guarantees device idle
m_pendingRenderbufferClears.clear();
RenderPassEntry::s_textureResourcesScratch.clear();
s_activeRenderPass.Get() = {};
s_hasActiveRenderPass.Get() = false;
s_activeRenderPass = {};
s_hasActiveRenderPass = false;
m_rpFastValid = false;
}
@@ -607,7 +607,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
const Bool isDefaultFbo = fbo.IsDefaultFramebuffer();
if (isDefaultFbo) {
XXHASH_VERIFY(XXH64_update(m_hashState, &swapchainImageIndex, sizeof(swapchainImageIndex)));
XXHASH_VERIFY(XXH64_update(m_hashState, &m_defaultFramebufferTarget, sizeof(m_defaultFramebufferTarget)));
}
// sRGB attachments switch between their sRGB and UNORM-twin views with this
// capability (ResolveSrgbAttachmentWriteFormat), changing the render pass formats.
@@ -1529,17 +1528,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
return &insertedIt->second;
}
void VkRenderPassManager::PurgeRenderPasses() {
Vector<VkRenderPass> destroyedRenderPasses;
destroyedRenderPasses.reserve(m_renderPasses.size());
for (auto& [_, entry] : m_renderPasses) destroyedRenderPasses.push_back(entry.renderPass);
m_renderPasses.clear();
m_rpFastValid = false;
if (!destroyedRenderPasses.empty() && m_evictionObserver != nullptr) {
m_evictionObserver->OnRenderPassesDestroyed(destroyedRenderPasses);
}
}
void VkRenderPassManager::OnPresent() {
++m_frameCounter;
@@ -1566,9 +1554,9 @@ namespace MobileGL::MG_Backend::DirectVulkan {
// immediately - and a single batched notification costs one pipeline-cache
// scan instead of one per evicted pass.
Vector<VkRenderPass> destroyedRenderPasses;
const Uint64 activeHash = s_hasActiveRenderPass.Get() ? s_activeRenderPass.Get().hash : 0;
const Uint64 activeHash = s_hasActiveRenderPass ? s_activeRenderPass.hash : 0;
for (auto it = m_renderPasses.begin(); it != m_renderPasses.end();) {
const Bool isActive = s_hasActiveRenderPass.Get() && it->first == activeHash;
const Bool isActive = s_hasActiveRenderPass && it->first == activeHash;
if (!isActive && m_frameCounter - it->second.lastUsedFrame > kRetireAgeFrames) {
if (m_rpFastValid && m_rpFastRenderPassHash == it->first) {
m_rpFastValid = false;
@@ -1613,8 +1601,8 @@ namespace MobileGL::MG_Backend::DirectVulkan {
// texture path below is immune because it re-reads the live payload).
// Same defense as ClearAttachmentsOnActiveRenderPass: prefer the live
// pending clear, fall back to the snapshot only when none is queued.
if (s_renderPassManager.Get() != nullptr &&
s_renderPassManager.Get()->GetPendingRenderbufferClear(pending.renderbuffer, clearPayload)) {
if (s_renderPassManager != nullptr &&
s_renderPassManager->GetPendingRenderbufferClear(pending.renderbuffer, clearPayload)) {
if ((clearPayload.mask & GL_COLOR_BUFFER_BIT) != 0 && pending.renderbuffer != nullptr &&
MG_Util::GetBaseInternalFormatComponentCount(pending.renderbuffer->GetInternalFormat()) ==
3) {
@@ -1626,7 +1614,7 @@ namespace MobileGL::MG_Backend::DirectVulkan {
}
} else {
if (pending.key.texture == nullptr ||
!s_clearManager.Get()->GetPendingClear(pending.key, clearPayload, liveTexture)) {
!s_clearManager->GetPendingClear(pending.key, clearPayload, liveTexture)) {
continue;
}
}
@@ -1648,29 +1636,29 @@ namespace MobileGL::MG_Backend::DirectVulkan {
vkCmdBeginRenderPass(commandBuffer, &renderPassBeginInfo, VK_SUBPASS_CONTENTS_INLINE);
// Pre-pass stream bookkeeping: this pass's attachment images are now
// referenced by the open frame recording.
if (s_textureManager.Get() != nullptr) {
if (s_textureManager != nullptr) {
for (const auto& tracked : renderPassEntry.trackedAttachmentLayouts) {
if (tracked.target == TrackedAttachmentTarget::Texture) {
if (const auto texture = tracked.texture.lock()) {
s_textureManager.Get()->StampTextureRecordingUse(texture.get());
s_textureManager->StampTextureRecordingUse(texture.get());
}
}
}
}
for (const auto& pending: renderPassEntry.pendingClearAttachments) {
if (pending.hasInlinePayload) {
if (s_renderPassManager.Get() != nullptr) {
s_renderPassManager.Get()->PopPendingRenderbufferClear(pending.renderbuffer);
if (s_renderPassManager != nullptr) {
s_renderPassManager->PopPendingRenderbufferClear(pending.renderbuffer);
}
} else {
s_clearManager.Get()->PopPendingClear(pending.key);
s_clearManager->PopPendingClear(pending.key);
}
}
s_activeRenderPass.Get().hash = renderPassEntry.hash;
s_activeRenderPass.Get().compatibilityHash = renderPassEntry.compatibilityHash;
s_activeRenderPass.Get().trackedAttachmentLayouts = renderPassEntry.trackedAttachmentLayouts;
s_activeRenderPass.Get().extent = renderPassEntry.extent;
s_hasActiveRenderPass.Get() = true;
s_activeRenderPass.hash = renderPassEntry.hash;
s_activeRenderPass.compatibilityHash = renderPassEntry.compatibilityHash;
s_activeRenderPass.trackedAttachmentLayouts = renderPassEntry.trackedAttachmentLayouts;
s_activeRenderPass.extent = renderPassEntry.extent;
s_hasActiveRenderPass = true;
return true;
}
@@ -1680,16 +1668,16 @@ namespace MobileGL::MG_Backend::DirectVulkan {
vkCmdEndRenderPass(commandBuffer);
// The fast-path memo reuses the ACTIVE render pass; once the pass ends it must not carry
// over (the next span may be a different FBO resolved before its render pass is begun).
if (s_renderPassManager.Get() != nullptr) {
s_renderPassManager.Get()->m_rpFastValid = false;
if (s_renderPassManager != nullptr) {
s_renderPassManager->m_rpFastValid = false;
}
if (activeRenderPass != nullptr && !activeRenderPass->trackedAttachmentLayouts.empty()) {
for (const auto& trackedAttachment : activeRenderPass->trackedAttachmentLayouts) {
switch (trackedAttachment.target) {
case TrackedAttachmentTarget::Texture:
MOBILEGL_ASSERT(s_textureManager.Get() != nullptr, "EndRenderPass: texture manager is null");
MOBILEGL_ASSERT(s_textureManager != nullptr, "EndRenderPass: texture manager is null");
if (const auto texture = trackedAttachment.texture.lock()) {
s_textureManager.Get()->UpdateTrackedImageLayoutAfterAttachmentWrite(
s_textureManager->UpdateTrackedImageLayoutAfterAttachmentWrite(
commandBuffer,
texture.get(),
trackedAttachment.textureMipLevel,
@@ -1697,27 +1685,27 @@ namespace MobileGL::MG_Backend::DirectVulkan {
}
break;
case TrackedAttachmentTarget::Renderbuffer:
MOBILEGL_ASSERT(s_renderPassManager.Get() != nullptr, "EndRenderPass: render pass manager is null");
MOBILEGL_ASSERT(s_renderPassManager != nullptr, "EndRenderPass: render pass manager is null");
if (const auto renderbuffer = trackedAttachment.renderbuffer.lock()) {
auto resourceIt =
s_renderPassManager.Get()->m_renderbufferResources.find(renderbuffer.get());
if (resourceIt != s_renderPassManager.Get()->m_renderbufferResources.end()) {
s_renderPassManager->m_renderbufferResources.find(renderbuffer.get());
if (resourceIt != s_renderPassManager->m_renderbufferResources.end()) {
resourceIt->second.layout = trackedAttachment.finalLayout;
}
}
break;
case TrackedAttachmentTarget::SwapchainColor:
MOBILEGL_ASSERT(s_swapchainObject.Get() != nullptr, "EndRenderPass: swapchain object is null");
s_swapchainObject.Get()->SetImageLayout(trackedAttachment.swapchainImageIndex, trackedAttachment.finalLayout);
MOBILEGL_ASSERT(s_swapchainObject != nullptr, "EndRenderPass: swapchain object is null");
s_swapchainObject->SetImageLayout(trackedAttachment.swapchainImageIndex, trackedAttachment.finalLayout);
// The pass stored into the attachment: its content is defined
// until the image is next presented.
s_swapchainObject.Get()->SetImageContentDefined(trackedAttachment.swapchainImageIndex, true);
s_swapchainObject->SetImageContentDefined(trackedAttachment.swapchainImageIndex, true);
break;
case TrackedAttachmentTarget::SwapchainDepthStencil:
MOBILEGL_ASSERT(s_swapchainObject.Get() != nullptr, "EndRenderPass: swapchain object is null");
s_swapchainObject.Get()->SetDepthStencilImageLayout(trackedAttachment.swapchainImageIndex,
MOBILEGL_ASSERT(s_swapchainObject != nullptr, "EndRenderPass: swapchain object is null");
s_swapchainObject->SetDepthStencilImageLayout(trackedAttachment.swapchainImageIndex,
trackedAttachment.finalLayout);
s_swapchainObject.Get()->SetDepthStencilContentDefined(trackedAttachment.swapchainImageIndex, true);
s_swapchainObject->SetDepthStencilContentDefined(trackedAttachment.swapchainImageIndex, true);
break;
default:
MOBILEGL_ASSERT(false, "EndRenderPass: unsupported tracked attachment target=%d",
@@ -1726,12 +1714,12 @@ namespace MobileGL::MG_Backend::DirectVulkan {
}
}
}
s_activeRenderPass.Get() = {};
s_hasActiveRenderPass.Get() = false;
s_activeRenderPass = {};
s_hasActiveRenderPass = false;
return true;
}
ActiveRenderPassInfo* VkRenderPassManager::GetActiveRenderPass() {
return s_hasActiveRenderPass.Get() ? &s_activeRenderPass.Get() : nullptr;
return s_hasActiveRenderPass ? &s_activeRenderPass : nullptr;
}
} // namespace MobileGL::MG_Backend::DirectVulkan
@@ -66,9 +66,8 @@ namespace MobileGL::MG_Backend::DirectVulkan {
VkExtent2D swapchainExtent);
struct RenderPassEntry {
// Per Magma session (MagmaSession.h): each session's renderer is its own device.
static inline SessionLocal<VkDevice> s_device;
static inline thread_local Vector<VkTextureManager::TextureResource*> s_textureResourcesScratch;
static inline VkDevice s_device;
static inline Vector<VkTextureManager::TextureResource*> s_textureResourcesScratch;
Uint64 hash = 0;
VkRenderPass renderPass = VK_NULL_HANDLE;
VkFramebuffer framebuffer = VK_NULL_HANDLE;
@@ -166,10 +165,10 @@ namespace MobileGL::MG_Backend::DirectVulkan {
~RenderPassEntry() {
if (renderPass != VK_NULL_HANDLE) {
vkDestroyRenderPass(s_device.Get(), renderPass, nullptr);
vkDestroyRenderPass(s_device, renderPass, nullptr);
}
if (framebuffer != VK_NULL_HANDLE) {
vkDestroyFramebuffer(s_device.Get(), framebuffer, nullptr);
vkDestroyFramebuffer(s_device, framebuffer, nullptr);
}
}
@@ -227,15 +226,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
Bool Initialize();
void Shutdown();
// The surface target the default framebuffer currently names (VulkanRenderer's surface
// targets): a default-framebuffer pass of one surface is not another's.
void SetDefaultFramebufferTarget(Uint64 serial) {
m_defaultFramebufferTarget = serial;
m_rpFastValid = false;
}
// Destroys every cached pass and framebuffer (not the renderbuffers). The device must be
// idle and no pass may be open: a surface target's image views are going away.
void PurgeRenderPasses();
HashType ComputeHash(
const MG_State::GLState::FramebufferObject& fbo,
@@ -312,7 +302,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
// is reused WITHOUT recomputing the expensive per-draw hash. Invalidated by FBO switch /
// version change, swapchain rotation, any attachment image recreation (the two epochs),
// or a pending clear. Portable to Vulkan 1.1 (no dynamic_rendering / imageless FB needed).
Uint64 m_defaultFramebufferTarget = 0;
Bool m_rpFastValid = false;
const MG_State::GLState::FramebufferObject* m_rpFastFbo = nullptr;
// The FBO's never-reused lifetime id joins the raw pointer + Uint16 version:
@@ -422,14 +411,12 @@ namespace MobileGL::MG_Backend::DirectVulkan {
void DeferRenderbufferBackingRelease(RenderbufferResource& resource);
void CollectDeferredRenderbufferReleases(Bool destroyAll);
static inline thread_local XXH64_state_t* m_hashState = XXH64_createState();
// Per Magma session (MagmaSession.h): one session's open render pass and managers are not
// another's.
static inline SessionLocal<ActiveRenderPassInfo> s_activeRenderPass;
static inline SessionLocal<Bool> s_hasActiveRenderPass;
static inline SessionLocal<VkClearManager*> s_clearManager;
static inline SessionLocal<VkTextureManager*> s_textureManager;
static inline SessionLocal<SwapchainObject*> s_swapchainObject;
static inline SessionLocal<VkRenderPassManager*> s_renderPassManager;
static inline XXH64_state_t* m_hashState = XXH64_createState();
static inline ActiveRenderPassInfo s_activeRenderPass{};
static inline Bool s_hasActiveRenderPass = false;
static inline VkClearManager* s_clearManager = nullptr;
static inline VkTextureManager* s_textureManager = nullptr;
static inline SwapchainObject* s_swapchainObject = nullptr;
static inline VkRenderPassManager* s_renderPassManager = nullptr;
};
} // namespace MobileGL::MG_Backend::DirectVulkan
@@ -138,6 +138,6 @@ private:
UnorderedMap<Uint64, SamplerCacheEntry> m_samplers;
// Monotonic frame-boundary counter (bumped in OnFrameBoundary) for cache aging.
Uint64 m_frameBoundaryCounter = 0;
static inline thread_local XXH64_state_t* m_hashState = XXH64_createState();
static inline XXH64_state_t* m_hashState = XXH64_createState();
};
} // namespace MobileGL::MG_Backend::DirectVulkan
@@ -22,16 +22,10 @@
// (shape) and the server's staged-texture store (texels).
#include <MG_Pipe/PipeApply.h>
#include <MG_Remote/Server/StagedTextureStore.h>
// Shared images: a texture whose level 0 is a server-allocated AHardwareBuffer.
#include <MG_Remote/Server/SharedImageRegistry.h>
#include "../DirectVulkan.h"
// P7 wave 2 package B3: rule I's tally for the silent exits on this file's wire arm.
#include "WireDeclineTally.h"
#if defined(__ANDROID__)
#include <android/hardware_buffer.h>
#endif
#endif
#include <string>
#include <algorithm>
#include <cstdio>
#include <cstdlib>
@@ -48,12 +42,9 @@ namespace MobileGL::MG_Backend::DirectVulkan {
// their feature is off (VUID-vkCmdPipelineBarrier-srcStageMask-04090/-04091), and ALL_GRAPHICS
// would also serialize against non-shader stages. The default only matters before a device
// exists, when nothing records barriers.
// Per Magma session: each session's renderer is its own device.
struct SampledReadStages {
VkPipelineStageFlags value = VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT |
VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
};
static SessionLocal<SampledReadStages> s_sampledReadStagesSlot;
static VkPipelineStageFlags s_sampledReadStages =
VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT |
VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
static Uint32 ComputeFullMipLevelCount(const IntVec3& baseTexelSize) {
Int maxDimension = std::max<Int>(baseTexelSize.x(),
@@ -212,7 +203,7 @@ namespace MobileGL::MG_Backend::DirectVulkan {
case VK_IMAGE_LAYOUT_DEPTH_READ_ONLY_STENCIL_ATTACHMENT_OPTIMAL:
case VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_STENCIL_READ_ONLY_OPTIMAL:
case VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL:
outSrcStageMask = s_sampledReadStagesSlot->value;
outSrcStageMask = s_sampledReadStages;
outSrcAccessMask = VK_ACCESS_SHADER_READ_BIT;
return;
case VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL:
@@ -276,7 +267,7 @@ namespace MobileGL::MG_Backend::DirectVulkan {
case VK_IMAGE_LAYOUT_DEPTH_READ_ONLY_STENCIL_ATTACHMENT_OPTIMAL:
case VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_STENCIL_READ_ONLY_OPTIMAL:
case VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL:
outDstStageMask = s_sampledReadStagesSlot->value;
outDstStageMask = s_sampledReadStages;
outDstAccessMask = VK_ACCESS_SHADER_READ_BIT;
return;
case VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL:
@@ -655,7 +646,7 @@ namespace MobileGL::MG_Backend::DirectVulkan {
m_commandPool = initInfo.commandPool;
m_graphicsQueue = initInfo.graphicsQueue;
m_imageFormatListSupported = initInfo.imageFormatListSupported;
s_sampledReadStagesSlot->value = initInfo.sampledReadStageMask;
s_sampledReadStages = initInfo.sampledReadStageMask;
m_currentFrameIndex = 0;
m_deferredReleases.clear();
m_deferredReleases.resize(initInfo.frameCount);
@@ -668,8 +659,8 @@ namespace MobileGL::MG_Backend::DirectVulkan {
MOBILEGL_ASSERT(initInfo.frameCount > 0,
"VkTextureManager::Initialize failed: frameCount must be > 0");
TextureResource::s_device.Get() = m_device;
TextureResource::s_allocator.Get() = m_allocator;
TextureResource::s_device = m_device;
TextureResource::s_allocator = m_allocator;
// Own pool for the recycled upload-batch command buffers. Parking a
// dozen reset-but-alive command buffers in the renderer's shared pool
@@ -707,7 +698,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
// Destroy images while the device/allocator still exist, including after context death.
m_wireTextureResources.clear();
m_wireRenderbufferResources.clear();
m_sharedImageUses.clear();
#endif
m_aliveObjects.clear();
m_storageImageTextures.clear();
@@ -1487,7 +1477,7 @@ namespace MobileGL::MG_Backend::DirectVulkan {
}
const Bool ok = TransitionImageLayout(commandBuffer, resource->image, resource->layout, targetLayout, srcStageMask,
s_sampledReadStagesSlot->value, srcAccessMask,
s_sampledReadStages, srcAccessMask,
VK_ACCESS_SHADER_READ_BIT, resource->aspect, 0, resource->mipLevels);
MOBILEGL_ASSERT(ok, "TransitionTextureForSampling: transition failed for textureId=%d", texture.GetExternalIndex());
// Pre-pass stream bookkeeping: a command referencing the image was recorded.
@@ -2115,12 +2105,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
Bool VkTextureManager::SyncWireTextureShape(const MG_Pipe::MGPipeResourceRecord& record,
TextureResource& resource, Bool requireStorage) {
const MG_Pipe::MGPResourceDesc& desc = record.Desc;
// Level 0 is a shared image: bind its buffer. An image that cannot be bound here leaves
// the texture the storage its NULL-data definition asked for, below.
if (record.SharedImageId != 0) {
const SharedImageBind bound = SyncWireSharedImage(record, resource, requireStorage);
if (bound != SharedImageBind::Unresolved) return bound == SharedImageBind::Bound;
}
if (desc.StorageKind != static_cast<Uint8>(TextureStorageType::Mipmap)) {
MGLOG_W_ONCE("Magma wire texture {slot=%u, gen=%u}: buffer-backed textures are not migrated; declined",
desc.Resource.Slot, desc.Resource.Gen);
@@ -2289,10 +2273,7 @@ namespace MobileGL::MG_Backend::DirectVulkan {
: (desc.Levels > 1 ? std::min(std::max<Uint32>(desc.Levels, fullMipLevels), fullMipLevels)
: 1u);
// A shared image never stands in for allocated storage: the attach is over (or never
// resolved), so the texture gets storage of its own, and none of the image's texels.
const Bool compatible = resource.image != VK_NULL_HANDLE && resource.sharedImageId == 0 &&
resource.format == format &&
const Bool compatible = resource.image != VK_NULL_HANDLE && resource.format == format &&
resource.extent.width == desc.Width && resource.extent.height == imageHeight &&
resource.depth == shapeInfo.depth && resource.arrayLayers == shapeInfo.arrayLayers &&
resource.viewType == shapeInfo.viewType &&
@@ -2307,8 +2288,7 @@ namespace MobileGL::MG_Backend::DirectVulkan {
// A named-level respecify changes ONLY that level; a BindMask update changes no
// storage at all. Preserve every compatible old level when growing/upgrading the
// allocation. A whole-store redefinition permits (but does not require) old texels.
const Bool preserve = resource.image != VK_NULL_HANDLE && resource.sharedImageId == 0 &&
resource.format == format &&
const Bool preserve = resource.image != VK_NULL_HANDLE && resource.format == format &&
resource.extent.width == desc.Width && resource.extent.height == imageHeight &&
resource.depth == shapeInfo.depth && resource.arrayLayers == shapeInfo.arrayLayers &&
resource.viewType == shapeInfo.viewType &&
@@ -2713,7 +2693,7 @@ namespace MobileGL::MG_Backend::DirectVulkan {
const VkImageLayout finalLayout = ResolveSampledReadOnlyLayout(aspectMask);
VkImageLayout uploadLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
ok = TransitionImageLayout(commandBuffer, resource.image, uploadLayout, finalLayout,
VK_PIPELINE_STAGE_TRANSFER_BIT, s_sampledReadStagesSlot->value,
VK_PIPELINE_STAGE_TRANSFER_BIT, s_sampledReadStages,
VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT, aspectMask, 0,
resource.mipLevels);
MOBILEGL_ASSERT(ok, "UploadPendingWireLevels: transition to the sampled layout failed");
@@ -2786,201 +2766,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
return MG_Pipe::kMGPipeNullHandle;
}
Bool VkTextureManager::ImportSharedImage(void* nativeBuffer, Uint32 width, Uint32 height,
ImportedSharedImage& out, String& why) {
out = ImportedSharedImage{};
#if defined(__ANDROID__)
auto* ahb = static_cast<AHardwareBuffer*>(nativeBuffer);
if (ahb == nullptr) {
why = "the image has no AHardwareBuffer";
return false;
}
VulkanRenderer::WireAhbImport ctx;
if (pVulkanRenderer == nullptr || !pVulkanRenderer->GetWireAhbImport(ctx)) {
why = "the device did not take VK_ANDROID_external_memory_android_hardware_buffer";
return false;
}
AHardwareBuffer_Desc desc{};
AHardwareBuffer_describe(ahb, &desc);
if (desc.width != width || desc.height != height || desc.layers != 1) {
why = "the buffer is " + std::to_string(desc.width) + "x" + std::to_string(desc.height) + "x" +
std::to_string(desc.layers) + ", not " + std::to_string(width) + "x" + std::to_string(height);
return false;
}
const auto getProperties =
reinterpret_cast<PFN_vkGetAndroidHardwareBufferPropertiesANDROID>(ctx.getAhbProperties);
VkAndroidHardwareBufferFormatPropertiesANDROID formatProperties{
VK_STRUCTURE_TYPE_ANDROID_HARDWARE_BUFFER_FORMAT_PROPERTIES_ANDROID};
VkAndroidHardwareBufferPropertiesANDROID properties{VK_STRUCTURE_TYPE_ANDROID_HARDWARE_BUFFER_PROPERTIES_ANDROID};
properties.pNext = &formatProperties;
VkResult result = getProperties(ctx.device, ahb, &properties);
if (result != VK_SUCCESS) {
why = "vkGetAndroidHardwareBufferPropertiesANDROID -> " + std::to_string(static_cast<int>(result));
return false;
}
// The RGBA8/RGBX8 buffers the registry allocates have a Vulkan format; an external-only
// format would need a YCbCr conversion and is not a colour buffer this path can write.
if (formatProperties.format == VK_FORMAT_UNDEFINED) {
why = "the buffer has no Vulkan format (external format only)";
return false;
}
// Usage is bounded by the buffer's own usage (the AHardwareBuffer usage equivalence);
// transfers need no buffer usage bit.
VkImageUsageFlags usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT;
if ((desc.usage & AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE) != 0 &&
(formatProperties.formatFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT) != 0)
usage |= VK_IMAGE_USAGE_SAMPLED_BIT;
if ((desc.usage & AHARDWAREBUFFER_USAGE_GPU_COLOR_OUTPUT) != 0 &&
(formatProperties.formatFeatures & VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT) != 0)
usage |= VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
VkExternalMemoryImageCreateInfo external{VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO};
external.handleTypes = VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID;
VkImageCreateInfo imageInfo{VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO};
imageInfo.pNext = &external;
imageInfo.imageType = VK_IMAGE_TYPE_2D;
imageInfo.format = formatProperties.format;
imageInfo.extent = {width, height, 1};
imageInfo.mipLevels = 1;
imageInfo.arrayLayers = 1;
imageInfo.samples = VK_SAMPLE_COUNT_1_BIT;
imageInfo.tiling = VK_IMAGE_TILING_OPTIMAL;
imageInfo.usage = usage;
imageInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
imageInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
result = vkCreateImage(ctx.device, &imageInfo, nullptr, &out.image);
if (result != VK_SUCCESS) {
out.image = VK_NULL_HANDLE;
why = "vkCreateImage(external AHB) -> " + std::to_string(static_cast<int>(result));
return false;
}
Int32 type = -1;
for (Uint32 i = 0; i < ctx.memory.memoryTypeCount && type < 0; ++i) {
if ((properties.memoryTypeBits & (1u << i)) != 0 &&
(ctx.memory.memoryTypes[i].propertyFlags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) != 0)
type = static_cast<Int32>(i);
}
for (Uint32 i = 0; i < ctx.memory.memoryTypeCount && type < 0; ++i) {
if ((properties.memoryTypeBits & (1u << i)) != 0) type = static_cast<Int32>(i);
}
if (type < 0) {
why = "no memory type can import it";
DestroyImportedSharedImage(ctx.device, out);
return false;
}
VkMemoryDedicatedAllocateInfo dedicated{VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO};
dedicated.image = out.image;
VkImportAndroidHardwareBufferInfoANDROID import{VK_STRUCTURE_TYPE_IMPORT_ANDROID_HARDWARE_BUFFER_INFO_ANDROID};
import.pNext = &dedicated;
import.buffer = ahb;
VkMemoryAllocateInfo allocateInfo{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO};
allocateInfo.pNext = &import;
allocateInfo.allocationSize = properties.allocationSize;
allocateInfo.memoryTypeIndex = static_cast<Uint32>(type);
result = vkAllocateMemory(ctx.device, &allocateInfo, nullptr, &out.memory);
if (result != VK_SUCCESS) {
out.memory = VK_NULL_HANDLE;
why = "vkAllocateMemory(import AHB) -> " + std::to_string(static_cast<int>(result));
DestroyImportedSharedImage(ctx.device, out);
return false;
}
result = vkBindImageMemory(ctx.device, out.image, out.memory, 0);
if (result != VK_SUCCESS) {
why = "vkBindImageMemory -> " + std::to_string(static_cast<int>(result));
DestroyImportedSharedImage(ctx.device, out);
return false;
}
out.format = formatProperties.format;
out.usage = usage;
out.features = formatProperties.formatFeatures;
out.queueFamily = ctx.queueFamily;
return true;
#else
(void)nativeBuffer, (void)width, (void)height;
why = "shared images are imported on Android only";
return false;
#endif
}
void VkTextureManager::DestroyImportedSharedImage(VkDevice device, ImportedSharedImage& image) {
if (image.image != VK_NULL_HANDLE) vkDestroyImage(device, image.image, nullptr);
if (image.memory != VK_NULL_HANDLE) vkFreeMemory(device, image.memory, nullptr);
image = ImportedSharedImage{};
}
VkTextureManager::SharedImageBind VkTextureManager::SyncWireSharedImage(
const MG_Pipe::MGPipeResourceRecord& record, TextureResource& resource, Bool requireStorage) {
const MG_Pipe::MGPResourceDesc& desc = record.Desc;
const Uint64 id = record.SharedImageId;
if (requireStorage) {
// The buffer's usage has no storage equivalent; a reallocation would drop the image.
MGLOG_E_ONCE("Magma wire texture {slot=%u, gen=%u}: shared image %llu is bound as a shader image, "
"which it cannot back; declined",
desc.Resource.Slot, desc.Resource.Gen, static_cast<unsigned long long>(id));
return SharedImageBind::Failed;
}
// Already this image: the serial moved for something else (params, the bind mask).
if (resource.sharedImageId == id && resource.image != VK_NULL_HANDLE) return SharedImageBind::Bound;
const auto image = MG_Remote::Server::SharedImages::Find(id);
if (image == nullptr) {
MGLOG_E_ONCE("Magma wire texture {slot=%u, gen=%u}: shared image %llu is no longer live; the texture "
"keeps its own (undefined) level 0",
desc.Resource.Slot, desc.Resource.Gen, static_cast<unsigned long long>(id));
return SharedImageBind::Unresolved;
}
const Bool flat2D = desc.Target == static_cast<Uint8>(MG_Pipe::MGPipeResourceTarget::Tex2D) ||
desc.Target == static_cast<Uint8>(MG_Pipe::MGPipeResourceTarget::TexRect);
if (!flat2D || desc.Width != image->Width || desc.Height != image->Height ||
!MG_Pipe::MGPipeHandleIsNull(desc.ViewOf)) {
MGLOG_E_ONCE("Magma wire texture {slot=%u, gen=%u}: pipe target %u at %ux%u cannot take shared image "
"%llu (%ux%u); the texture keeps its own level 0",
desc.Resource.Slot, desc.Resource.Gen, static_cast<Uint32>(desc.Target), desc.Width,
desc.Height, static_cast<unsigned long long>(id), image->Width, image->Height);
return SharedImageBind::Unresolved;
}
ImportedSharedImage imported;
String why;
if (!ImportSharedImage(image->Native, image->Width, image->Height, imported, why)) {
MGLOG_E_ONCE("Magma wire texture {slot=%u, gen=%u}: shared image %llu not imported - %s; the texture "
"keeps its own level 0",
desc.Resource.Slot, desc.Resource.Gen, static_cast<unsigned long long>(id), why.c_str());
return SharedImageBind::Unresolved;
}
// NOT ACQUIRED HERE. The writer (a client session's present, on its own device) releases
// the image to VK_QUEUE_FAMILY_FOREIGN_EXT in GENERAL - also the layout every wire
// descriptor samples in - once per frame it writes. Each use acquires it again when the
// write generation moved, waiting for that write's fence on the GPU, and the frame boundary
// releases it back (VulkanRenderer::AcquireSharedImage, WireSharedImage.inc).
TextureResource replacement;
replacement.image = imported.image;
replacement.importedMemory = imported.memory;
replacement.layout = VK_IMAGE_LAYOUT_GENERAL;
replacement.extent = {image->Width, image->Height};
replacement.depth = 1;
replacement.arrayLayers = 1;
replacement.mipLevels = 1;
replacement.sampledBaseMipLevel = 0;
replacement.sampledLevelCount = 1;
replacement.format = imported.format;
replacement.aspect = VK_IMAGE_ASPECT_COLOR_BIT;
replacement.viewType = VK_IMAGE_VIEW_TYPE_2D;
replacement.sampleCount = VK_SAMPLE_COUNT_1_BIT;
replacement.imageCreateFlags = 0;
replacement.usageFlags = imported.usage;
replacement.sharedImageId = id;
replacement.sharedImageOwner = image;
replacement.sharedImageAlphaOne = MG_Remote::Server::SharedImages::FourccIgnoresAlpha(image->Fourcc);
++m_textureImageEpoch; // a new attachment image invalidates cached render passes
DeferResourceRelease(Move(resource));
std::destroy_at(&resource);
std::construct_at(&resource, Move(replacement));
MGLOG_D("Magma wire texture {slot=%u, gen=%u}: level 0 is shared image %llu (%ux%u)", desc.Resource.Slot,
desc.Resource.Gen, static_cast<unsigned long long>(id), image->Width, image->Height);
return SharedImageBind::Bound;
}
VkTextureManager::TextureResource* VkTextureManager::SyncTextureResourceByHandle(
MG_Pipe::MGPipeHandle handle, Bool renderbuffer, Bool requireStorage) {
MOBILEGL_ASSERT(m_device != VK_NULL_HANDLE, "SyncTextureResourceByHandle: m_device == VK_NULL_HANDLE");
@@ -3057,7 +2842,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
handle.Slot, handle.Gen);
return nullptr;
}
resource.sharedImageKey = resource.sharedImageId != 0 ? key : 0;
resource.syncedWireSerial = record.Serial;
return &resource;
}
@@ -4789,7 +4573,7 @@ namespace MobileGL::MG_Backend::DirectVulkan {
uploadLayout,
finalLayout,
VK_PIPELINE_STAGE_TRANSFER_BIT,
s_sampledReadStagesSlot->value,
s_sampledReadStages,
VK_ACCESS_TRANSFER_WRITE_BIT,
VK_ACCESS_SHADER_READ_BIT,
aspectMask, 0, outResource.mipLevels);
@@ -9,7 +9,6 @@
#pragma once
#include "../VkIncludes.h"
#include "../MagmaSession.h"
#include <Includes.h>
#include <MG_State/GLState/FramebufferState/FramebufferObject.h>
#include <MG_State/GLState/TextureState/TextureObject.h>
@@ -357,21 +356,6 @@ public:
// on every mutation, so the first handle sync of a fresh image always re-checks.
#if MOBILEGL_BUILD_DISAGGREGATED
Uint64 syncedWireSerial = 0;
// SHARED IMAGES: level 0 is a server shared image (an imported AHardwareBuffer), not a
// VMA allocation. The resource owns the image and its dedicated imported memory, and
// holds the registry's reference so the buffer outlives every use (deferred releases
// included). `sharedImageAlphaOne`: an X-format image, whose alpha bytes are undefined.
VkDeviceMemory importedMemory = VK_NULL_HANDLE;
Uint64 sharedImageId = 0;
SharedPtr<const void> sharedImageOwner;
Bool sharedImageAlphaOne = false;
// The reading side's ownership of the image (VulkanRenderer::AcquireSharedImage): whether
// this device holds it now - acquired from the foreign family and not yet released back at
// the frame boundary - the writer's generation it last acquired, and the
// m_wireTextureResources key it lives under, by which the frame boundary finds it again.
Bool sharedImageHeld = false;
Uint64 sharedImageGeneration = 0;
Uint64 sharedImageKey = 0;
#endif
TextureResource() = default;
@@ -408,64 +392,44 @@ public:
std::swap(this->syncedShapeVersion, that.syncedShapeVersion);
#if MOBILEGL_BUILD_DISAGGREGATED
std::swap(this->syncedWireSerial, that.syncedWireSerial);
std::swap(this->importedMemory, that.importedMemory);
std::swap(this->sharedImageId, that.sharedImageId);
std::swap(this->sharedImageOwner, that.sharedImageOwner);
std::swap(this->sharedImageAlphaOne, that.sharedImageAlphaOne);
std::swap(this->sharedImageHeld, that.sharedImageHeld);
std::swap(this->sharedImageGeneration, that.sharedImageGeneration);
std::swap(this->sharedImageKey, that.sharedImageKey);
#endif
}
void Reset() {
if (fullView != VK_NULL_HANDLE) {
vkDestroyImageView(s_device.Get(), fullView, nullptr);
vkDestroyImageView(s_device, fullView, nullptr);
}
if (sampledView != VK_NULL_HANDLE) {
vkDestroyImageView(s_device.Get(), sampledView, nullptr);
vkDestroyImageView(s_device, sampledView, nullptr);
}
for (const auto attachmentView : perMipViews) {
if (attachmentView != VK_NULL_HANDLE) {
vkDestroyImageView(s_device.Get(), attachmentView, nullptr);
vkDestroyImageView(s_device, attachmentView, nullptr);
}
}
for (const auto sampledView : perMipSampledViews) {
if (sampledView != VK_NULL_HANDLE) {
vkDestroyImageView(s_device.Get(), sampledView, nullptr);
vkDestroyImageView(s_device, sampledView, nullptr);
}
}
for (const auto& [_, attachmentView] : attachmentViews) {
if (attachmentView != VK_NULL_HANDLE) {
vkDestroyImageView(s_device.Get(), attachmentView, nullptr);
vkDestroyImageView(s_device, attachmentView, nullptr);
}
}
for (const auto& [_, sampledView] : alternateSampledViews) {
if (sampledView != VK_NULL_HANDLE) {
vkDestroyImageView(s_device.Get(), sampledView, nullptr);
vkDestroyImageView(s_device, sampledView, nullptr);
}
}
for (const auto& [_, storageImageView] : storageImageViews) {
if (storageImageView != VK_NULL_HANDLE) {
vkDestroyImageView(s_device.Get(), storageImageView, nullptr);
vkDestroyImageView(s_device, storageImageView, nullptr);
}
}
if (image != VK_NULL_HANDLE && allocation != nullptr) {
vmaDestroyImage(s_allocator.Get(), image, allocation);
vmaDestroyImage(s_allocator, image, allocation);
}
#if MOBILEGL_BUILD_DISAGGREGATED
if (importedMemory != VK_NULL_HANDLE) {
if (image != VK_NULL_HANDLE) vkDestroyImage(s_device.Get(), image, nullptr);
vkFreeMemory(s_device.Get(), importedMemory, nullptr);
}
importedMemory = VK_NULL_HANDLE;
sharedImageId = 0;
sharedImageOwner.reset();
sharedImageAlphaOne = false;
sharedImageHeld = false;
sharedImageGeneration = 0;
sharedImageKey = 0;
#endif
fullView = VK_NULL_HANDLE;
sampledView = VK_NULL_HANDLE;
perMipViews.clear();
@@ -502,8 +466,8 @@ public:
Reset();
}
static inline SessionLocal<VkDevice> s_device; // per Magma session (MagmaSession.h)
static inline SessionLocal<VmaAllocator> s_allocator;
static inline VkDevice s_device = VK_NULL_HANDLE;
static inline VmaAllocator s_allocator = VK_NULL_HANDLE;
};
struct SampledTextureSnapshot {
@@ -627,41 +591,6 @@ public:
// ranges select cube faces; array and 3D levels share one staged level shadow.
void MarkWireTextureGpuWritten(MG_Pipe::MGPipeHandle handle, Uint32 mipLevel,
Uint32 baseArrayLayer = 0, Uint32 layerCount = 1);
// SHARED IMAGES (docs/Disaggregated/notes/anland/plan-ahb-dmabuf.md): a server shared image's
// AHardwareBuffer bound as a single-level 2D colour image on THIS session's device, on dedicated
// memory imported from the buffer. Android only (false with `why` elsewhere, or when the device
// did not take the AHardwareBuffer extension). The image is born UNDEFINED; whoever uses it
// acquires it from the foreign queue family first, and a writer releases it back after.
struct ImportedSharedImage {
VkImage image = VK_NULL_HANDLE;
VkDeviceMemory memory = VK_NULL_HANDLE;
VkFormat format = VK_FORMAT_UNDEFINED;
VkImageUsageFlags usage = 0;
VkFormatFeatureFlags features = 0;
Uint32 queueFamily = 0;
};
static Bool ImportSharedImage(void* nativeBuffer, Uint32 width, Uint32 height, ImportedSharedImage& out,
String& why);
static void DestroyImportedSharedImage(VkDevice device, ImportedSharedImage& image);
// The reading side's per-use hook: PrepareWireTextureResources notes every shared-image
// texture a draw or dispatch samples, and the renderer takes the list right after
// (VulkanRenderer::AcquireNotedSharedImages) to acquire each one ahead of the sampling.
void NoteSharedImageUse(const TextureResource& resource) {
if (std::find(m_sharedImageUses.begin(), m_sharedImageUses.end(), resource.sharedImageKey) ==
m_sharedImageUses.end())
m_sharedImageUses.push_back(resource.sharedImageKey);
}
Bool HasNotedSharedImageUses() const { return !m_sharedImageUses.empty(); }
void TakeNotedSharedImageUses(Vector<Uint64>& out) {
out.clear();
std::swap(out, m_sharedImageUses);
}
// The live handle-keyed texture resource under `key`, or null.
TextureResource* FindWireTextureResource(Uint64 key) {
const auto it = m_wireTextureResources.find(key);
return it != m_wireTextureResources.end() && it->second.image != VK_NULL_HANDLE ? &it->second : nullptr;
}
#endif
VkImageView GetOrCreateViewAtMipLevel(MG_State::GLState::ITextureObject& texture, Uint32 mipLevel);
VkImageView GetOrCreateAttachmentViewAtMipLevel(MG_State::GLState::ITextureObject& texture, Uint32 mipLevel,
@@ -848,18 +777,10 @@ private:
Bool requireStorage);
Bool UploadPendingWireLevels(MG_Pipe::MGPipeHandle handle, MG_Pipe::MGPipeResourceRecord& record,
TextureResource& resource);
// SyncWireTextureShape's arm for a record whose level 0 IS a shared image (SharedImageId):
// binds the imported buffer instead of allocating. Unresolved = the image is gone or cannot be
// imported here; `resource` is then untouched and the caller allocates as for any texture.
enum class SharedImageBind : Uint8 { Bound, Failed, Unresolved };
SharedImageBind SyncWireSharedImage(const MG_Pipe::MGPipeResourceRecord& record, TextureResource& resource,
Bool requireStorage);
// The handle-keyed twin of m_textureResources, keyed by StagedTextureStore::KeyForHandle.
// Node-based for the same reason m_renderbufferResources is: callers hold TextureResource*
// across map-touching calls.
std::unordered_map<Uint64, TextureResource> m_wireTextureResources;
// Shared-image textures sampled since the renderer last took the list (NoteSharedImageUse).
Vector<Uint64> m_sharedImageUses;
// Handles are per-kind; a renderbuffer and texture may have identical slot/gen.
std::unordered_map<Uint64, TextureResource> m_wireRenderbufferResources;
#endif
File diff suppressed because it is too large Load Diff
@@ -24,7 +24,6 @@
#include "VkTimerQueryManager.h"
#if MOBILEGL_BUILD_DISAGGREGATED
#include "WireRenderPassCompatibility.h"
#include <MG_Remote/Server/SharedImageRegistry.h>
#endif
#include "MG_Util/Math/VectorTypes.h"
#include <Includes.h>
@@ -180,31 +179,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
void* getAhbProperties = nullptr; // PFN_vkGetAndroidHardwareBufferPropertiesANDROID
};
Bool GetWireAhbImport(WireAhbImport& out) const;
// SHARED IMAGES (BackendObject::BlitDefaultFramebufferToSharedImage): the active surface
// target's default framebuffer, copied into `image` top row first and scaled to its
// extent. Returns once the copy is submitted, with its fence published to the image
// (SharedImages::PublishWrite); waits for it on the CPU only on a device without sync_file
// export. False (logged) when it cannot be done here: no AHardwareBuffer import, a
// quarter-turned surface, an unblittable format.
//
// `region` (GL window coordinates; Full = all) is the part to copy into an image this
// renderer has written before - the rest of it is left as it is; a first write, a scaled
// or turned copy copies all of it.
Bool BlitDefaultFramebufferToSharedImage(const SharedImageView& image, const MG_Util::Damage::Region& region);
// EGL_BUFFER_AGE_EXT of the active target's default framebuffer for the next frame: the age
// of the swapchain image acquired for it (SwapchainObject::BufferAgeOf). Asking makes the
// target keep its presented images' content from then on.
Int32 CurrentDrawBufferAge();
// The reading side's per-use hook (WireSharedImage.inc): every shared-image texture the
// wire draw or dispatch being set up samples (VkTextureManager::NoteSharedImageUse) is
// acquired from the foreign family before it, when it moved or is not held.
void AcquireNotedSharedImages() {
if (m_textureManager && m_textureManager->HasNotedSharedImageUses()) AcquireNotedSharedImagesSlow();
}
// One shared-image texture, before a use: a new write generation, or an image released at
// the last frame boundary, is acquired here - an ownership barrier recorded ahead of the
// use, the write's fence a wait of the submission carrying it - and noted as read.
void AcquireSharedImage(VkTextureManager::TextureResource& resource);
#endif
// FrameContext::IRecordingObserver: prepares the frame's timer-query
@@ -384,22 +358,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
// one is retired until the frame slot's fence is next waited. Returns
// true when a submission was made.
Bool FlushPendingCommands();
// DEVICE LOSS. A GPU fault or hang the driver reset leaves this renderer's VkDevice lost:
// every later submit and wait answers VK_ERROR_DEVICE_LOST. NoteDeviceLoss records it at
// the submit/wait sites (cheap, any result); IsDeviceLost answers from the record and,
// when nothing was recorded, asks the device once (only failure paths call it, so the
// probe's wait costs nothing on a healthy frame). Each session owns its own VkDevice, so a
// loss here is this session's alone.
void NoteDeviceLoss(VkResult result, const char* where);
Bool IsDeviceLost();
#if MOBILEGL_BUILD_DISAGGREGATED
// For a wire site whose submit or wait just failed: true when the failure is a lost
// device, in which case this session has been latched (MGPipeSessionLatch - it ends, the
// display server's other sessions do not) and the caller must return from its verb
// without recording or submitting anything more. False: an ordinary failure, the site
// keeps the death it had. `site` names it in the latch line.
Bool LatchWireDeviceLoss(const char* site);
#endif
// Flush gated on usefulness: only flushes when `submitIndex` is still
// unsubmitted, so poll loops on already-submitted fences do not split
// the frame's render pass (a full tile load/store on TBDR GPUs).
@@ -469,65 +427,7 @@ namespace MobileGL::MG_Backend::DirectVulkan {
// no new swapchain is installed and presentation must stay suspended.
Bool RecreateSwapchain();
// SURFACE TARGETS. One renderer - one device and every GL object's resources - serves
// every EGL surface of its context's client; only the presentation side (VkSurfaceKHR,
// swapchain, its render-finished semaphores, the acquired image, the pbuffer's image
// reader) belongs to a surface. `key` names the client surface. The renderer starts with
// the surface it was constructed for as its active target (SetActiveSurfaceTargetKey).
// Activating another key parks the active target - its recorded work submitted, its
// pending acquire consumed - and brings the other back, or builds it on first use.
void SetActiveSurfaceTargetKey(Uint64 key) { m_activeTargetKey = key; }
// False when a NEW target's surface could not be built (logged); the renderer is then left
// with no active target - every present drops its frame - and the caller refuses by name.
Bool ActivateSurfaceTarget(Uint64 key, NativeWindowType window, const VulkanRendererConfig& surfaceConfig);
// Drops a surface's target, active or parked. A no-op for a key that has none.
void DestroySurfaceTarget(Uint64 key);
// The default framebuffer's extent (surface space, what PublishDefaultFramebufferInfo
// publishes) of `key`'s target, active or parked; 0x0 when it has none or no swapchain.
VkExtent2D SurfaceTargetExtent(Uint64 key) const;
// The active WINDOW target's window changed size. Between frames (nothing recorded since the last
// present) its swapchain is rebuilt now - which publishes the new extent - so a client that has
// nothing to redraw learns it without presenting; with a frame half-recorded the rebuild waits
// for that frame's present (it would otherwise land half in each swapchain). False: no active
// window target.
Bool FollowActiveWindowResize();
// Whether `key` names the active target.
Bool IsActiveSurfaceTarget(Uint64 key) const { return key == m_activeTargetKey && m_surface != VK_NULL_HANDLE; }
private:
// The presentation half of the renderer, parked while another surface is active. Its
// fields mirror the renderer members ExchangeActiveTarget swaps them with.
struct SurfaceTarget {
Uint64 serial = 0;
NativeWindowType window = 0;
void* platformDisplay = nullptr;
void* platformLibrary = nullptr;
void* platformCloseDisplay = nullptr;
void* fallbackImageReader = nullptr;
Uint32 surfaceWidth = 0;
Uint32 surfaceHeight = 0;
Optional<Int> swapInterval;
Bool presentsToAppWindow = false;
Optional<Int> swapchainSwapInterval;
Bool swapchainResizeRequested = false;
Bool presentSuspended = false;
VkSurfaceKHR surface = VK_NULL_HANDLE;
SwapchainObject swapchain;
Vector<VkSemaphore> renderFinishedSemaphores;
Uint imageIndexAcquired = 0;
Uint defaultFramebufferImageIndex = 0;
};
void ExchangeActiveTarget(SurfaceTarget& target);
// Submits the active target's work, consumes its pending acquire and moves it into
// m_parkedTargets. Leaves the renderer with no target.
void ParkActiveTarget();
void OnActiveTargetChanged();
void DestroyParkedTarget(SurfaceTarget& target);
UnorderedMap<Uint64, SurfaceTarget> m_parkedTargets;
Uint64 m_activeTargetKey = 0;
Uint64 m_activeTargetSerial = 1;
Uint64 m_nextTargetSerial = 2;
// Tiered emission for an already-set-up multi-draw batch (state bound, index
// buffer bound for the indexed form). Tier 1: VK_EXT_multi_draw. Tier 2: one
// vkCmdDraw(Indexed)Indirect over a transient command array. Tier 3: unrolled
@@ -613,9 +513,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
};
void QueueClearBufferPayload(GLenum buffer, GLint drawbuffer, const ClearAttachmentPayload& clearPayload);
// See NoteDeviceLoss. Set once, never cleared: a lost VkDevice stays lost.
Bool m_deviceLost = false;
Bool m_deviceLossLatched = false;
#if MOBILEGL_BUILD_DISAGGREGATED
struct WireImage {
VkImage image = VK_NULL_HANDLE;
@@ -700,79 +597,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
// one entry point the import needs (PFN_vkGetAndroidHardwareBufferPropertiesANDROID).
Bool m_wireAhbImport = false;
void* m_wireGetAhbProperties = nullptr;
// Shared images this session presents into, imported once each and keyed by the image's
// id (monotonic, never reused). `owner` watches the registry's image: an entry whose image
// died is dropped at a later present once `lastSubmit`, its last copy, has completed.
struct SharedImagePresentTarget {
VkTextureManager::ImportedSharedImage image;
WeakPtr<const void> owner;
Uint64 lastSubmit = 0;
// A copy has written the image through this import: what it holds is a frame.
Bool written = false;
};
UnorderedMap<Uint64, SharedImagePresentTarget> m_sharedImagePresentTargets;
void DestroySharedImagePresentTargets(Bool onlyDead);
// SHARED-IMAGE SYNCHRONISATION (WireSharedImage.inc). The sync_file fences other sessions
// publish become binary semaphores: a temporary SYNC_FD import is a WAIT, an exportable
// semaphore a SIGNAL, of the next frame submission - whichever of SubmitPendingCommandBuffer
// and Present's submit comes first, which is the one carrying what was recorded since.
// Each semaphore is recycled once the submission that used it has completed.
// m_sharedImageSyncFd: the device imports and exports SYNC_FD binary semaphores; without
// it the waits happen on the CPU and nothing is exported (see WireSharedImage.inc).
Bool m_sharedImageSyncFd = false;
PFN_vkImportSemaphoreFdKHR m_importSemaphoreFd = nullptr;
PFN_vkGetSemaphoreFdKHR m_getSemaphoreFd = nullptr;
struct SharedImageWait {
VkSemaphore semaphore = VK_NULL_HANDLE;
VkPipelineStageFlags stages = 0;
};
Vector<SharedImageWait> m_sharedImageWaits; // staged for the next submission
VkSemaphore m_sharedImageSignal = VK_NULL_HANDLE; // staged for the next submission
VkSemaphore m_sharedImageSignalSubmitted = VK_NULL_HANDLE; // the last one submitted, to export
struct SharedImageSemaphoreInFlight {
VkSemaphore semaphore = VK_NULL_HANDLE;
Uint64 submitIndex = 0;
Bool exportable = false;
Bool exported = false; // a signal whose sync_file was taken (which unsignals it)
};
Vector<SharedImageSemaphoreInFlight> m_sharedImageSemaphoresInFlight; // submit order
Vector<VkSemaphore> m_freeSharedImageWaitSemaphores;
Vector<VkSemaphore> m_freeSharedImageSignalSemaphores;
// The reading side, per session: the shared-image textures this frame holds (acquired, not
// yet released; keyed as in VkTextureManager's handle map, with the submission that carries
// the acquire), and the frame's ReadTracker, published at Present.
struct SharedImageHold {
Uint64 key = 0;
Uint64 acquireSubmit = 0;
};
Vector<SharedImageHold> m_sharedImagesHeld;
MG_Remote::Server::SharedImages::ReadTracker m_sharedImageReads;
Vector<Uint64> m_sharedImageUseScratch;
// What one vkQueueSubmit carries beyond its own semaphores (AttachSharedImageSync).
struct SharedImageSubmitSync {
Bool attached = false;
Vector<VkSemaphore> waits;
Vector<VkPipelineStageFlags> stages;
Vector<VkSemaphore> signals;
};
void AttachSharedImageSync(VkSubmitInfo& info, SharedImageSubmitSync& storage);
// After the submission `storage` was attached to was submitted and registered.
void CommitSharedImageSync(const SharedImageSubmitSync& storage);
// Takes ownership of `fence` (a sync_file; -1 = nothing to wait for).
void StageSharedImageWait(int fence, VkPipelineStageFlags stages);
VkSemaphore TakeSharedImageSemaphore(Bool exportable);
// The submitted signal's sync_file (-1: it has already signaled). False: not exported.
Bool ExportSharedImageSignal(VkSemaphore semaphore, int& fence);
void RecycleSharedImageSemaphores(Uint64 completedSubmit);
void DestroySharedImageSync();
void AcquireNotedSharedImagesSlow();
// The reading side's frame boundary: release every held image back to the foreign family
// in the open recording, and - after the submission carrying it - publish its fence.
void ReleaseHeldSharedImages();
void PublishSharedImageReads();
// A frame dropped unsubmitted (Present with no usable swapchain).
void AbandonSharedImageReads();
// Runs the probe (memoized per device identity) and sets the member above. Called at the end of
// device creation, after ArmPrimGenReroute: it records on m_graphicsQueue.
void ArmWireDepthResolveOrder();
@@ -872,8 +696,7 @@ namespace MobileGL::MG_Backend::DirectVulkan {
// P8-SV: glDispatchComputeIndirect on the wire arm - vkCmdDispatchIndirect from the
// dispatch-indirect store, as the monolith arm issues it (WireDraw.inc).
void DispatchWireComputeIndirect(GLintptr offset);
// False: the device was lost and the session latched; the caller drops its draw/dispatch.
Bool RewindWireDescriptorSetsIfDue();
void RewindWireDescriptorSetsIfDue();
UniquePtr<RenderPassEntry> m_wireDrawPass;
Vector<VkImageView> m_wireDrawViews;
VkPipeline GetOrCreatePipelineWithInput(GLenum mode, const MagmaProgramSource& program,
@@ -982,12 +805,7 @@ namespace MobileGL::MG_Backend::DirectVulkan {
// a substituted window. (Android is the one exception and has its own path -
// no Mali/Adreno driver seen so far exposes the extension, so a windowless
// context is given an AImageReader ANativeWindow that is never displayed.)
// ENABLED ON THIS INSTANCE, not merely offered: a renderer created for a window never asks
// for the extension, and its later offscreen targets must not call an entry point the
// instance does not have (OffscreenSurfaceRoute.h). Hence false until CreateInstance says so.
Bool m_headlessSurfaceSupported = false;
// VK_KHR_android_surface was enabled on this instance (the AImageReader route needs it).
Bool m_androidSurfaceEnabled = false;
Bool m_headlessSurfaceSupported = true;
// Android has the same shortfall: no Mali/Adreno driver seen so far exposes
// VK_EXT_headless_surface, so a windowless (EGL pbuffer) context gets an
// AImageReader's ANativeWindow to hand the WSI instead. Nothing is ever
@@ -1117,17 +935,17 @@ namespace MobileGL::MG_Backend::DirectVulkan {
VkDeviceSize offset, VkBuffer countBuffer,
VkDeviceSize countBufferOffset, Uint32 maxDrawCount,
Uint32 stride);
PFNDrawIndexedIndirectCountFunc s_vkCmdDrawIndexedIndirectCount = nullptr;
static inline PFNDrawIndexedIndirectCountFunc s_vkCmdDrawIndexedIndirectCount = nullptr;
#if MOBILEGL_BUILD_DISAGGREGATED
// P8-D: vkCmdDrawIndirectCount (same signature, same extension), for the wire arm's
// glMultiDrawArraysIndirectCount. The monolith arm never loads it: it reads that count on
// the CPU (DirectVulkan.cpp's MultiDrawArraysIndirectCount).
PFNDrawIndexedIndirectCountFunc s_vkCmdWireDrawIndirectCount = nullptr;
static inline PFNDrawIndexedIndirectCountFunc s_vkCmdWireDrawIndirectCount = nullptr;
#endif
// VK_EXT_multi_draw entry points, loaded at device creation when the extension
// (and its multiDraw feature) is enabled; null otherwise.
PFN_vkCmdDrawMultiEXT s_vkCmdDrawMultiEXT = nullptr;
PFN_vkCmdDrawMultiIndexedEXT s_vkCmdDrawMultiIndexedEXT = nullptr;
static inline PFN_vkCmdDrawMultiEXT s_vkCmdDrawMultiEXT = nullptr;
static inline PFN_vkCmdDrawMultiIndexedEXT s_vkCmdDrawMultiIndexedEXT = nullptr;
// VK_EXT_transform_feedback (GL transform feedback capture)
Bool m_transformFeedbackFeatureEnabled = false;
@@ -1158,9 +976,9 @@ namespace MobileGL::MG_Backend::DirectVulkan {
// VK_EXT_vertex_attribute_divisor: without it every non-zero glVertexAttribDivisor
// behaves as 1, because that is all Vulkan's instance input rate can express.
Bool m_vertexAttributeDivisorEnabled = false;
PFN_vkCmdBindTransformFeedbackBuffersEXT s_vkCmdBindTransformFeedbackBuffersEXT = nullptr;
PFN_vkCmdBeginTransformFeedbackEXT s_vkCmdBeginTransformFeedbackEXT = nullptr;
PFN_vkCmdEndTransformFeedbackEXT s_vkCmdEndTransformFeedbackEXT = nullptr;
static inline PFN_vkCmdBindTransformFeedbackBuffersEXT s_vkCmdBindTransformFeedbackBuffersEXT = nullptr;
static inline PFN_vkCmdBeginTransformFeedbackEXT s_vkCmdBeginTransformFeedbackEXT = nullptr;
static inline PFN_vkCmdEndTransformFeedbackEXT s_vkCmdEndTransformFeedbackEXT = nullptr;
// Counter buffers (one 4-byte slot per capture binding) let consecutive
// draws within one glBeginTransformFeedback append GL-style. Transform feedback
// objects can each hold an open, paused span at the same time, so the counters are
@@ -2006,8 +1824,7 @@ namespace MobileGL::MG_Backend::DirectVulkan {
VkResult SetupDebugReportCallback();
void DestroyDebugReportCallback();
VkDebugUtilsMessengerCreateInfoEXT PopulateDebugMessengerCreateInfo();
// False (logged) when the target's surface cannot be built; the renderer then has no surface.
Bool CreateSurface();
void CreateSurface();
void PickPhysicalDevice();
void CreateLogicalDeviceAndQueues();
void CreateAllocator();
@@ -240,9 +240,6 @@
MGL_WIRE_DECLINE_AT(TextureResourcesUnprepared, "a sampled/storage image could not be made ready; see the Tex* tally");
return false;
}
// Shared images another session writes: acquired ahead of the recording that samples them
// (WireSharedImage.inc).
AcquireNotedSharedImages();
// Lazy image uploads/promotions can submit the old recording. Resolve
// ALL attachments before descriptor binding captures the current cmd.
for (Uint32 i = 0; i < MG_Pipe::kMGPipeMaxColorAttachments; ++i) {
@@ -309,20 +306,8 @@
"MGPipe: Fatal{ProtocolCorruption, \"Magma:client-vertex-array\"} location=%u: an "
"attribute the program reads carries no buffer handle", location);
BufferSlice slice{};
if (!m_bufferManager.AcquireWireSlice(BufferKind::Vertex, resource.Res, slice)) {
// A buffer with no data store is legal GL to bind (glGenBuffers + glBindBuffer, no
// glBufferData), and the client mints its handle at construction while the create
// only crosses with the first respecify (PipeFill.cpp's M-1) - so the handle may be
// one this server never saw, or one it holds with zero bytes. Either way the draw
// reads no storage: it is declined, as the GL draws nothing defined from it.
static Bool s_described = false;
if (!s_described && !m_bufferManager.IsKnownWireBuffer(resource.Res)) {
s_described = true;
m_bufferManager.DescribeWireBufferHistory(resource.Res);
}
MGL_WIRE_DECLINE_AT(VertexAttributeWindow, "an enabled attribute's buffer has no storage");
return false;
}
if (!m_bufferManager.AcquireWireSlice(BufferKind::Vertex, resource.Res, slice))
MagmaWireFatal("vertex-buffer-resource");
const VkDeviceSize offset = input.bindingBaseOffsets[binding];
const auto type = static_cast<DataType>(attr.Type);
const SizeT elementSize = VertexInputStateFactory::GetAttributeByteSize(type, attr.Size, attr.IsBgra);
@@ -402,16 +387,8 @@
const void* bytes = nullptr;
if (cpuIndices) bytes = reinterpret_cast<const void*>(indices->indexByteOffset);
else {
if (!m_bufferManager.AcquireWireSlice(BufferKind::Index, state.IndexBuffer.Res, indexSlice)) {
// As for a vertex buffer: a bound element buffer with no data store yet.
static Bool s_described = false;
if (!s_described && !m_bufferManager.IsKnownWireBuffer(state.IndexBuffer.Res)) {
s_described = true;
m_bufferManager.DescribeWireBufferHistory(state.IndexBuffer.Res);
}
MGL_WIRE_DECLINE_AT(IndexWindow, "the element buffer has no storage");
return false;
}
if (!m_bufferManager.AcquireWireSlice(BufferKind::Index, state.IndexBuffer.Res, indexSlice))
MagmaWireFatal("index-buffer-resource");
const Uint64 offset = state.IndexBuffer.Offset + indices->indexByteOffset;
if (offset < state.IndexBuffer.Offset || offset > indexSlice.size ||
indices->indexByteSize > indexSlice.size - offset) {
@@ -779,7 +756,6 @@
MGL_WIRE_DECLINE_AT(ComputeTextureResourcesUnprepared, "a sampled/storage image could not be made ready for the dispatch");
return;
}
AcquireNotedSharedImages(); // shared images another session writes (WireSharedImage.inc)
const auto pipeline = GetOrCreateComputePipeline(programObj);
if (!pipeline) {
MGL_WIRE_DECLINE_AT(ComputePipelineUnavailable, "no compute pipeline could be created for this dispatch");
@@ -851,7 +827,6 @@
MGL_WIRE_DECLINE_AT(ComputeTextureResourcesUnprepared, "a sampled/storage image could not be made ready for the dispatch");
return;
}
AcquireNotedSharedImages(); // shared images another session writes (WireSharedImage.inc)
const auto pipeline = GetOrCreateComputePipeline(programObj);
if (!pipeline) {
MGL_WIRE_DECLINE_AT(ComputePipelineUnavailable, "no compute pipeline could be created for this dispatch");
@@ -160,8 +160,6 @@
if (MG_Pipe::MGPipeHandleIsNull(out.storage)) MagmaWireFatal("framebuffer-view-record");
auto* resource = m_textureManager->SyncTextureResourceByHandle(out.storage, renderbuffer);
if (!resource) MagmaWireFatal("framebuffer-resource");
// Another session writes it: acquired (WireSharedImage.inc) before the layout is read below.
if (resource->sharedImageId != 0) AcquireSharedImage(*resource);
out.image = resource->image;
out.format = viewFormat != VK_FORMAT_UNDEFINED ? viewFormat : resource->format;
out.extent = {std::max(resource->extent.width >> level, 1u),
@@ -381,13 +379,7 @@
void VulkanRenderer::ReadWirePixels(GLint x, GLint y, GLsizei width, GLsizei height,
GLenum format, GLenum type, void* pixels) {
if (width <= 0 || height <= 0) return;
if (MG_Pipe::MGPipeDebugDeviceLossDue()) NoteDeviceLoss(VK_ERROR_DEVICE_LOST, "the debug knob (read-pixels)");
if (m_deviceLost && LatchWireDeviceLoss("read-pixels")) return;
if (HasPendingRecordedWork() && !FlushPendingCommands()) {
// A lost device: the session is latched and closing, the pixels stay unfilled.
if (LatchWireDeviceLoss("wire-verb-flush")) return;
MagmaWireFatal("wire-verb-flush");
}
if (HasPendingRecordedWork() && !FlushPendingCommands()) MagmaWireFatal("wire-verb-flush");
const auto* fbo = MG_Pipe::MGPipeApplier().ReadFramebuffer();
if (!fbo) MagmaWireFatal("read-framebuffer-record");
VkImageAspectFlags aspect = format == GL_DEPTH_COMPONENT ? VK_IMAGE_ASPECT_DEPTH_BIT :
@@ -408,22 +400,6 @@
"default framebuffer; the readback returns its raw pixels",
source.swapchainImageIndex);
}
if (source.isDefault && aspect == VK_IMAGE_ASPECT_COLOR_BIT) {
VkOffset2D probeOffset{};
VkExtent2D probeExtent{};
if (!MapDefaultFramebufferReadbackRect(x, y, width, height, source.extent,
m_swapchainObject.GetPreTransform(), &probeOffset, &probeExtent)) {
// A rectangle reaching past the surface: GL leaves those pixels undefined rather
// than raising an error, and the usual cause is a client reading back at its
// window's new size one frame before its surface follows the resize. Nothing is
// copied, and nothing is recorded.
MGLOG_E_ONCE("Magma wire: default-framebuffer read %dx%d at (%d,%d) does not fit surface %llx's "
"%ux%u (transform %u); the read is left unfilled", width, height, x, y,
static_cast<unsigned long long>(m_activeTargetKey), source.extent.width,
source.extent.height, static_cast<Uint32>(m_swapchainObject.GetPreTransform()));
return;
}
}
m_textureManager->FlushPendingUploads();
RecordWireReadbackWriteBarrier();
TransitionWireImage(source, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL);
@@ -452,10 +428,7 @@
auto& frame = m_frameContext.GetCurrent();
vkCmdCopyImageToBuffer(frame.commandBuffer,source.image,VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
buffer.GetHandle(),1,&region);
if (!SubmitReadbackCommandsAndWait(frame)) {
if (LatchWireDeviceLoss("read-submit")) return;
MagmaWireFatal("read-submit");
}
if (!SubmitReadbackCommandsAndWait(frame)) MagmaWireFatal("read-submit");
const auto* bytes = static_cast<const Uint8*>(buffer.Map());
if (!bytes || !buffer.Invalidate(size)) MagmaWireFatal("read-map");
Vector<Uint8> remapped;
@@ -1401,14 +1374,6 @@
&viewFormat, &layerCount);
auto* resource = m_textureManager->SyncTextureResourceByHandle(handle);
if (!resource) MagmaWireFatal("mipmap-resource");
// A shared image is one level of a buffer someone else allocated; growing the chain would
// reallocate it away from the buffer.
if (resource->sharedImageId != 0) {
MGLOG_E_ONCE("DirectVulkan::GenerateWireMipmap: the texture's level 0 is shared image %llu, which has "
"no mip chain; levels %u..%u are left as they are",
static_cast<unsigned long long>(resource->sharedImageId), logicalBase + 1, logicalEnd - 1);
return;
}
m_textureManager->FlushPendingUploads();
RetireWireDrawPass();
auto& frame = m_frameContext.GetCurrent();
@@ -1,633 +0,0 @@
// MobileGL - MobileGL/MG_Backend/DirectVulkan/Renderer/WireSharedImage.inc
// Copyright (c) 2025-2026 MobileGL-Dev
// Licensed under the GNU Lesser General Public License v3.0:
// https://www.gnu.org/licenses/gpl-3.0.txt
// https://www.gnu.org/licenses/lgpl-3.0.txt
// SPDX-License-Identifier: LGPL-3.0-only
// End of Source File Header
// SHARED IMAGES (docs/Disaggregated/notes/anland/plan-ahb-dmabuf.md). Included by VulkanRenderer.cpp
// inside the backend namespace, after WireFramebuffer.inc, whose readback the present side's copy
// is modelled on: the same flush, the same write-visibility barrier, the same transition of the
// default framebuffer's image.
//
// OWNERSHIP. The image lives on more than one device: a client session writes it, the
// compositor's session (another VulkanRenderer, another VkDevice) samples it. Each present
// acquires it from VK_QUEUE_FAMILY_FOREIGN_EXT (UNDEFINED: the copy overwrites every texel) and
// releases it back in GENERAL. A reader acquires it (GENERAL) before the first use of a frame and
// again whenever the write generation moved, and releases it back at its frame boundary, so every
// acquire on either side matches a release on the other.
//
// ORDER (MG_Remote/Server/SharedImageRegistry.h). Every fence is a sync_file. The writer's copy
// waits on its GPU for the read fences still pending, signals a semaphore exported as the write
// fence, and the present returns without waiting. A reader's use waits on its GPU for the write
// fence of the generation it acquires; its frame's submission signals a semaphore exported as the
// read fence of every image the frame used. A device without SYNC_FD semaphore import and export
// waits on the CPU instead where it would have waited on the GPU - before the writer's copy, after
// it, and before the reader's use - and exports nothing for its reads: there is no fence to give,
// and waiting for the frame on the CPU only to say it is over would stall every frame of the
// compositor. The writer's next copy is then ordered after the reads by nothing but the client's
// own buffer rotation (a Wayland client writes a buffer only after its release) - which is all
// this path had before - on a device Android's Vulkan 1.1 requirements leave rare.
#if MOBILEGL_BUILD_DISAGGREGATED
// A CPU wait on another session's fence is a fallback, and bounded: a peer that never signals
// costs a frame's worth of stall, not a hang.
static constexpr Uint32 kSharedImageCpuWaitMs = 1000;
// Every stage a reader's use of a shared image can reach: sampling (draws and dispatches), a
// blit or readback source, an attachment. The write fence's wait blocks these, and the
// acquire's first scope is the same set, so it is ordered after that wait.
static constexpr VkPipelineStageFlags kSharedImageUseStages =
VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT |
VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT | VK_PIPELINE_STAGE_TRANSFER_BIT |
VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
static void CloseSyncFile(int fd) {
#if !defined(_WIN32)
if (fd >= 0) ::close(fd);
#else
(void)fd;
#endif
}
void VulkanRenderer::DestroySharedImagePresentTargets(Bool onlyDead) {
if (onlyDead) RefreshCompletedSubmits();
for (auto it = m_sharedImagePresentTargets.begin(); it != m_sharedImagePresentTargets.end();) {
// A dead image's last copy may still be executing: the present no longer waits for it.
if (onlyDead && (!it->second.owner.expired() || it->second.lastSubmit > m_completedSubmitCounter)) {
++it;
continue;
}
VkTextureManager::DestroyImportedSharedImage(m_device, it->second.image);
it = m_sharedImagePresentTargets.erase(it);
}
}
// A copy moves bytes; a blit converts through the format. The bytes are right only between
// formats with one memory layout, which for the RGBA8 buffers means RGBA8 itself or its sRGB
// twin (a blit would decode the sRGB bytes on the way).
static Bool SharedImageCopiesAsIs(VkFormat source, VkFormat destination) {
if (source == destination) return true;
return destination == VK_FORMAT_R8G8B8A8_UNORM && source == VK_FORMAT_R8G8B8A8_SRGB;
}
Bool VulkanRenderer::BlitDefaultFramebufferToSharedImage(const SharedImageView& view,
const MG_Util::Damage::Region& region) {
if (m_device == VK_NULL_HANDLE || view.Width == 0 || view.Height == 0) return false;
// The debug knob's device check (MGPipeDebugDeviceLossDue) rides the frame boundary here.
if (MG_Pipe::MGPipeDebugDeviceLossDue()) NoteDeviceLoss(VK_ERROR_DEVICE_LOST, "the debug knob (shared-image present)");
if (m_deviceLost && LatchWireDeviceLoss("shared-image-present")) return false;
DestroySharedImagePresentTargets(true);
// The default framebuffer's image is stored in display orientation (row 0 is the top of
// the frame) on an identity surface, and turned half round on a 180 one; a blit expresses
// both. A quarter turn transposes, which no copy or blit can - and only the compositor's
// own window is ever quarter-turned, which presents to the display rather than here.
const VkSurfaceTransformFlagBitsKHR preTransform = m_swapchainObject.GetPreTransform();
if (IsQuarterTurnPreTransform(preTransform)) {
MGLOG_E_ONCE("Magma: shared image %llu: the current surface %llx is quarter-turned (transform %u); a "
"present into a shared image is declined there",
static_cast<unsigned long long>(view.Id), static_cast<unsigned long long>(m_activeTargetKey),
static_cast<Uint32>(preTransform));
return false;
}
auto found = m_sharedImagePresentTargets.find(view.Id);
if (found == m_sharedImagePresentTargets.end()) {
const auto owner = MG_Remote::Server::SharedImages::Find(view.Id);
if (owner == nullptr) {
MGLOG_E_ONCE("Magma: shared image %llu is not live; the present is declined",
static_cast<unsigned long long>(view.Id));
return false;
}
SharedImagePresentTarget target;
String why;
if (!VkTextureManager::ImportSharedImage(view.NativeBuffer, view.Width, view.Height, target.image, why)) {
MGLOG_E_ONCE("Magma: shared image %llu (%ux%u) not imported - %s; the present is declined",
static_cast<unsigned long long>(view.Id), view.Width, view.Height, why.c_str());
return false;
}
target.owner = owner;
found = m_sharedImagePresentTargets.emplace(view.Id, Move(target)).first;
}
const VkTextureManager::ImportedSharedImage& destination = found->second.image;
// The registry's record carries the image's fences. The server holds a reference for as
// long as the present runs; a lapsed one is an image released under it.
const auto image =
std::static_pointer_cast<const MG_Remote::Server::SharedImages::Image>(found->second.owner.lock());
if (image == nullptr) {
MGLOG_E_ONCE("Magma: shared image %llu is not live; the present is declined",
static_cast<unsigned long long>(view.Id));
return false;
}
// The frame's draws reach the queue first; the copy below is a later submission that the
// readback barrier orders behind them.
if (HasPendingRecordedWork() && !FlushPendingCommands()) {
MGLOG_E("Magma: shared image %llu: the frame's recorded work could not be submitted",
static_cast<unsigned long long>(view.Id));
return false;
}
MG_Pipe::MGPFramebufferState defaultFramebuffer{};
defaultFramebuffer.IsDefault = 1;
const MG_Pipe::MGPSurface noSurface{};
WireImage source = ResolveWireImage(defaultFramebuffer, noSurface, VK_IMAGE_ASPECT_COLOR_BIT,
/*isWriteTarget=*/false);
if (source.image == VK_NULL_HANDLE || source.extent.width == 0 || source.extent.height == 0) {
MGLOG_E_ONCE("Magma: shared image %llu: no default framebuffer is current; the present is declined",
static_cast<unsigned long long>(view.Id));
return false;
}
if (!m_swapchainObject.IsImageContentDefined(source.swapchainImageIndex)) {
MGLOG_W_ONCE("Magma: shared image present: no write is recorded for image %u of the default "
"framebuffer; its raw pixels are copied",
source.swapchainImageIndex);
}
const Bool sameExtent = source.extent.width == view.Width && source.extent.height == view.Height;
const Bool halfTurn = preTransform == VK_SURFACE_TRANSFORM_ROTATE_180_BIT_KHR;
const Bool copy = sameExtent && !halfTurn && SharedImageCopiesAsIs(source.format, destination.format);
// ONLY WHERE THE IMAGE DIFFERS FROM THE FRAME: an image this renderer wrote before, copied
// one to one (no scaling, no half turn). Its other texels must survive, so the acquire then
// keeps the layout the last reader released it in rather than discarding it.
MG_Util::Damage::Region part = region;
if (!part.IsFull()) part.Normalize(static_cast<Int32>(view.Width), static_cast<Int32>(view.Height));
const Bool partial = !part.IsFull() && found->second.written && sameExtent && !halfTurn;
// The region's rectangles, top row first and made disjoint: a copy's regions may not overlap.
Vector<MG_Util::Damage::Rect> rows;
if (partial) {
for (const MG_Util::Damage::Rect& rect : MG_Util::Damage::Disjoint(part.Rects()))
rows.push_back(MG_Util::Damage::FlipY(rect, static_cast<Int32>(view.Height)));
}
VkFormatProperties sourceProperties{};
vkGetPhysicalDeviceFormatProperties(m_physicalDevice.handle, source.format, &sourceProperties);
if (!copy) {
if ((sourceProperties.optimalTilingFeatures & VK_FORMAT_FEATURE_BLIT_SRC_BIT) == 0 ||
(destination.features & VK_FORMAT_FEATURE_BLIT_DST_BIT) == 0) {
MGLOG_E_ONCE("Magma: shared image %llu: a %ux%u format-%d default framebuffer needs a blit into "
"the %ux%u format-%d image, which this device cannot do; the present is declined",
static_cast<unsigned long long>(view.Id), source.extent.width, source.extent.height,
static_cast<Int>(source.format), view.Width, view.Height,
static_cast<Int>(destination.format));
return false;
}
if (vkuFormatIsSRGB(source.format) && !vkuFormatIsSRGB(destination.format)) {
MGLOG_W_ONCE("Magma: shared image present: the sRGB default framebuffer is blitted into a UNORM "
"image, which stores linear values");
}
}
m_textureManager->FlushPendingUploads();
RecordWireReadbackWriteBarrier();
TransitionWireImage(source, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL);
auto& frame = m_frameContext.GetCurrent();
// NOT OVER WHAT IS STILL READ. The reads published since this image's last write (a
// compositor frame sampling it) end before the copy starts: on the GPU, as waits of the
// submission below at the transfer stage; on the CPU, where they cannot be imported.
// The frame's draws were flushed above, so the next submission is the copy's.
namespace SI = MG_Remote::Server::SharedImages;
if (m_sharedImageSyncFd) {
for (const int fence : SI::DupPendingReadFences(*image))
StageSharedImageWait(fence, VK_PIPELINE_STAGE_TRANSFER_BIT);
} else if (!SI::WaitForReads(*image, kSharedImageCpuWaitMs)) {
MGLOG_W_ONCE("Magma: shared image %llu: a read of the previous frame did not finish within %u ms; it is "
"overwritten anyway",
static_cast<unsigned long long>(view.Id), kSharedImageCpuWaitMs);
}
// The acquire's layout transition runs after those waits: its first scope is the stage
// they block.
VkImageMemoryBarrier acquire{VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER};
acquire.srcAccessMask = 0;
acquire.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
// Every present releases the image in GENERAL, and so does every reader.
acquire.oldLayout = partial ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_UNDEFINED;
acquire.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
acquire.srcQueueFamilyIndex = VK_QUEUE_FAMILY_FOREIGN_EXT;
acquire.dstQueueFamilyIndex = destination.queueFamily;
acquire.image = destination.image;
acquire.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
vkCmdPipelineBarrier(frame.commandBuffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0,
0, nullptr, 0, nullptr, 1, &acquire);
const VkImageSubresourceLayers layers{VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1};
if (partial) {
// An empty region copies nothing: the image already is the frame.
if (copy && !rows.empty()) {
Vector<VkImageCopy> regions;
regions.reserve(rows.size());
for (const MG_Util::Damage::Rect& row : rows) {
VkImageCopy one{};
one.srcSubresource = layers;
one.dstSubresource = layers;
one.srcOffset = {row.X, row.Y, 0};
one.dstOffset = {row.X, row.Y, 0};
one.extent = {static_cast<Uint32>(row.Width), static_cast<Uint32>(row.Height), 1};
regions.push_back(one);
}
vkCmdCopyImage(frame.commandBuffer, source.image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
destination.image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
static_cast<Uint32>(regions.size()), regions.data());
} else if (!rows.empty()) {
Vector<VkImageBlit> regions;
regions.reserve(rows.size());
for (const MG_Util::Damage::Rect& row : rows) {
VkImageBlit one{};
one.srcSubresource = layers;
one.dstSubresource = layers;
one.srcOffsets[0] = {row.X, row.Y, 0};
one.srcOffsets[1] = {row.X + row.Width, row.Y + row.Height, 1};
one.dstOffsets[0] = one.srcOffsets[0];
one.dstOffsets[1] = one.srcOffsets[1];
regions.push_back(one);
}
vkCmdBlitImage(frame.commandBuffer, source.image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
destination.image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
static_cast<Uint32>(regions.size()), regions.data(), VK_FILTER_NEAREST);
}
} else if (copy) {
VkImageCopy region{};
region.srcSubresource = layers;
region.dstSubresource = layers;
region.extent = {view.Width, view.Height, 1};
vkCmdCopyImage(frame.commandBuffer, source.image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, destination.image,
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &region);
} else {
// Identity: row 0 is already the top. 180: the stored image is the frame turned half
// round, so the destination rectangle runs backwards on both axes.
const Int32 width = static_cast<Int32>(view.Width);
const Int32 height = static_cast<Int32>(view.Height);
VkImageBlit region{};
region.srcSubresource = layers;
region.srcOffsets[1] = {static_cast<Int32>(source.extent.width), static_cast<Int32>(source.extent.height),
1};
region.dstSubresource = layers;
region.dstOffsets[0] = halfTurn ? VkOffset3D{width, height, 0} : VkOffset3D{0, 0, 0};
region.dstOffsets[1] = halfTurn ? VkOffset3D{0, 0, 1} : VkOffset3D{width, height, 1};
const VkFilter filter =
!sameExtent && (sourceProperties.optimalTilingFeatures &
VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT) != 0
? VK_FILTER_LINEAR
: VK_FILTER_NEAREST;
vkCmdBlitImage(frame.commandBuffer, source.image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, destination.image,
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &region, filter);
}
VkImageMemoryBarrier release{VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER};
release.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
release.dstAccessMask = 0;
release.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
release.newLayout = VK_IMAGE_LAYOUT_GENERAL;
release.srcQueueFamilyIndex = destination.queueFamily;
release.dstQueueFamilyIndex = VK_QUEUE_FAMILY_FOREIGN_EXT;
release.image = destination.image;
release.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
vkCmdPipelineBarrier(frame.commandBuffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
0, 0, nullptr, 0, nullptr, 1, &release);
// THE WRITE FENCE. The client attaches the buffer to its surface as soon as this returns;
// what orders the compositor's read after the copy is the fence published here, which the
// compositor's session waits for on its GPU when it next acquires the image. The copy's
// submission signals a semaphore exported as that fence, and nothing waits for it here.
// The submission is an ordinary pooled-fence flush: the renderer's in-flight tracking keeps
// the command buffer and every resource it names alive until it has completed.
if (m_sharedImageSyncFd && m_sharedImageSignal == VK_NULL_HANDLE)
m_sharedImageSignal = TakeSharedImageSemaphore(/*exportable=*/true);
if (m_sharedImageSignal != VK_NULL_HANDLE) {
m_sharedImageSignalSubmitted = VK_NULL_HANDLE;
if (!FlushPendingCommands()) {
MGLOG_E("Magma: shared image %llu: the copy could not be submitted",
static_cast<unsigned long long>(view.Id));
return false;
}
found->second.lastSubmit = m_submitCounter;
found->second.written = true;
const VkSemaphore signal = std::exchange(m_sharedImageSignalSubmitted, VK_NULL_HANDLE);
int fence = -1;
if (signal != VK_NULL_HANDLE && ExportSharedImageSignal(signal, fence)) {
SI::PublishWrite(*image, fence);
return true;
}
// Submitted, but no fence came out of it: the copy is waited for, as on a device that
// exports none.
if (!WaitForSubmitsUpTo(m_submitCounter, UINT64_MAX)) {
MGLOG_E("Magma: shared image %llu: the copy could not be waited for",
static_cast<unsigned long long>(view.Id));
return false;
}
SI::PublishWrite(*image, -1);
return true;
}
if (!SubmitReadbackCommandsAndWait(frame)) {
MGLOG_E("Magma: shared image %llu: the copy could not be submitted or waited for",
static_cast<unsigned long long>(view.Id));
return false;
}
found->second.lastSubmit = m_submitCounter;
found->second.written = true;
SI::PublishWrite(*image, -1);
return true;
}
// ---- fences as semaphores ------------------------------------------------------------------
VkSemaphore VulkanRenderer::TakeSharedImageSemaphore(Bool exportable) {
auto& pool = exportable ? m_freeSharedImageSignalSemaphores : m_freeSharedImageWaitSemaphores;
if (!pool.empty()) {
const VkSemaphore semaphore = pool.back();
pool.pop_back();
return semaphore;
}
VkExportSemaphoreCreateInfo exportInfo{VK_STRUCTURE_TYPE_EXPORT_SEMAPHORE_CREATE_INFO};
exportInfo.handleTypes = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_SYNC_FD_BIT;
VkSemaphoreCreateInfo info{VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO};
if (exportable) info.pNext = &exportInfo;
VkSemaphore semaphore = VK_NULL_HANDLE;
const VkResult result = vkCreateSemaphore(m_device, &info, nullptr, &semaphore);
if (result != VK_SUCCESS) {
MGLOG_E_ONCE("Magma: a shared-image semaphore could not be created (vkCreateSemaphore -> %d)",
static_cast<Int>(result));
return VK_NULL_HANDLE;
}
return semaphore;
}
void VulkanRenderer::StageSharedImageWait(int fence, VkPipelineStageFlags stages) {
if (fence < 0) return;
if (m_sharedImageSyncFd) {
const VkSemaphore semaphore = TakeSharedImageSemaphore(/*exportable=*/false);
if (semaphore != VK_NULL_HANDLE) {
// A sync_file import is always temporary: the wait consumes it, and the semaphore
// is a plain unsignaled one again once that wait has executed.
VkImportSemaphoreFdInfoKHR import{VK_STRUCTURE_TYPE_IMPORT_SEMAPHORE_FD_INFO_KHR};
import.semaphore = semaphore;
import.flags = VK_SEMAPHORE_IMPORT_TEMPORARY_BIT;
import.handleType = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_SYNC_FD_BIT;
import.fd = fence;
const VkResult result = m_importSemaphoreFd(m_device, &import);
if (result == VK_SUCCESS) {
m_sharedImageWaits.push_back({semaphore, stages}); // the import owns `fence` now
return;
}
m_freeSharedImageWaitSemaphores.push_back(semaphore);
MGLOG_W_ONCE("Magma: a shared-image fence could not be imported (vkImportSemaphoreFdKHR -> %d); it "
"is waited for on the CPU",
static_cast<Int>(result));
}
}
// Nothing recorded since reaches the queue before this returns.
if (!MG_Remote::Server::SharedImages::SyncFile::Wait(fence, kSharedImageCpuWaitMs)) {
MGLOG_W_ONCE("Magma: a shared-image fence did not signal within %u ms; the image is used anyway",
kSharedImageCpuWaitMs);
}
CloseSyncFile(fence);
}
Bool VulkanRenderer::ExportSharedImageSignal(VkSemaphore semaphore, int& fence) {
fence = -1;
VkSemaphoreGetFdInfoKHR info{VK_STRUCTURE_TYPE_SEMAPHORE_GET_FD_INFO_KHR};
info.semaphore = semaphore;
info.handleType = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_SYNC_FD_BIT;
// A sync_file export has a wait's effect on the semaphore: it is unsignaled again, and
// reusable once the submission that signaled it has completed. -1 back means it had
// already signaled.
const VkResult result = m_getSemaphoreFd(m_device, &info, &fence);
if (result != VK_SUCCESS) {
fence = -1;
MGLOG_W_ONCE("Magma: a shared-image fence could not be exported (vkGetSemaphoreFdKHR -> %d)",
static_cast<Int>(result));
return false;
}
for (auto& entry : m_sharedImageSemaphoresInFlight) {
if (entry.semaphore == semaphore) entry.exported = true;
}
return true;
}
void VulkanRenderer::AttachSharedImageSync(VkSubmitInfo& info, SharedImageSubmitSync& storage) {
storage.attached = false;
if (m_sharedImageWaits.empty() && m_sharedImageSignal == VK_NULL_HANDLE) return;
storage.waits.assign(info.pWaitSemaphores, info.pWaitSemaphores + info.waitSemaphoreCount);
storage.stages.assign(info.pWaitDstStageMask, info.pWaitDstStageMask + info.waitSemaphoreCount);
for (const auto& wait : m_sharedImageWaits) {
storage.waits.push_back(wait.semaphore);
storage.stages.push_back(wait.stages);
}
storage.signals.assign(info.pSignalSemaphores, info.pSignalSemaphores + info.signalSemaphoreCount);
if (m_sharedImageSignal != VK_NULL_HANDLE) storage.signals.push_back(m_sharedImageSignal);
info.waitSemaphoreCount = static_cast<Uint32>(storage.waits.size());
info.pWaitSemaphores = storage.waits.data();
info.pWaitDstStageMask = storage.stages.data();
info.signalSemaphoreCount = static_cast<Uint32>(storage.signals.size());
info.pSignalSemaphores = storage.signals.data();
storage.attached = true;
}
void VulkanRenderer::CommitSharedImageSync(const SharedImageSubmitSync& storage) {
if (!storage.attached) return;
for (const auto& wait : m_sharedImageWaits)
m_sharedImageSemaphoresInFlight.push_back({wait.semaphore, m_submitCounter, false, false});
m_sharedImageWaits.clear();
if (m_sharedImageSignal != VK_NULL_HANDLE) {
m_sharedImageSemaphoresInFlight.push_back({m_sharedImageSignal, m_submitCounter, true, false});
m_sharedImageSignalSubmitted = std::exchange(m_sharedImageSignal, VK_NULL_HANDLE);
}
}
void VulkanRenderer::RecycleSharedImageSemaphores(Uint64 completedSubmit) {
SizeT done = 0;
for (; done < m_sharedImageSemaphoresInFlight.size() &&
m_sharedImageSemaphoresInFlight[done].submitIndex <= completedSubmit;
++done) {
const auto& entry = m_sharedImageSemaphoresInFlight[done];
if (entry.semaphore == m_sharedImageSignalSubmitted) m_sharedImageSignalSubmitted = VK_NULL_HANDLE;
if (!entry.exportable) {
m_freeSharedImageWaitSemaphores.push_back(entry.semaphore);
} else if (entry.exported) {
m_freeSharedImageSignalSemaphores.push_back(entry.semaphore);
} else if (m_device != VK_NULL_HANDLE) {
// Signaled and never exported, so still signaled: a binary semaphore cannot be
// signaled again until something waits on it, and nothing will.
vkDestroySemaphore(m_device, entry.semaphore, nullptr);
}
}
if (done != 0) {
m_sharedImageSemaphoresInFlight.erase(
m_sharedImageSemaphoresInFlight.begin(),
m_sharedImageSemaphoresInFlight.begin() + static_cast<std::ptrdiff_t>(done));
}
}
void VulkanRenderer::DestroySharedImageSync() {
// The device is idle: every semaphore is inert.
const auto destroy = [this](VkSemaphore semaphore) {
if (semaphore != VK_NULL_HANDLE && m_device != VK_NULL_HANDLE)
vkDestroySemaphore(m_device, semaphore, nullptr);
};
for (const auto& entry : m_sharedImageSemaphoresInFlight) destroy(entry.semaphore);
m_sharedImageSemaphoresInFlight.clear();
for (const auto& wait : m_sharedImageWaits) destroy(wait.semaphore);
m_sharedImageWaits.clear();
destroy(std::exchange(m_sharedImageSignal, VK_NULL_HANDLE));
m_sharedImageSignalSubmitted = VK_NULL_HANDLE;
for (const VkSemaphore semaphore : m_freeSharedImageWaitSemaphores) destroy(semaphore);
m_freeSharedImageWaitSemaphores.clear();
for (const VkSemaphore semaphore : m_freeSharedImageSignalSemaphores) destroy(semaphore);
m_freeSharedImageSignalSemaphores.clear();
m_sharedImagesHeld.clear();
m_sharedImageReads.PublishFrame(-1); // drops the frame's references; publishes nothing
}
// ---- the reading side ------------------------------------------------------------------------
//
// REACHED ON EVERY USE. A wire draw or dispatch prepares its sampled textures through
// PrepareWireTextureResources on every call - the wire arm keeps no sampled-set cache across
// draws (the walk-skip is the monolith arm's SetupDraw) - and that notes each shared-image
// texture it resolves; SetupWireDraw and both dispatch paths acquire the noted ones straight
// after (AcquireNotedSharedImages). ResolveWireImage, through which every attachment, blit,
// copy and readback reaches a texture's image, acquires directly. The test is the write
// generation against the one last acquired, so a generation that moves between two draws of
// one frame is caught at the second.
void VulkanRenderer::AcquireNotedSharedImagesSlow() {
m_textureManager->TakeNotedSharedImageUses(m_sharedImageUseScratch);
for (const Uint64 key : m_sharedImageUseScratch) {
if (auto* resource = m_textureManager->FindWireTextureResource(key)) AcquireSharedImage(*resource);
}
m_sharedImageUseScratch.clear();
}
void VulkanRenderer::AcquireSharedImage(VkTextureManager::TextureResource& resource) {
namespace SI = MG_Remote::Server::SharedImages;
if (resource.sharedImageId == 0 || resource.image == VK_NULL_HANDLE || resource.sharedImageOwner == nullptr)
return;
const auto image = std::static_pointer_cast<const SI::Image>(resource.sharedImageOwner);
Uint64 generation = 0;
const int fence = SI::DupWriteFence(*image, &generation);
// Held, and not written since it was acquired: every use after a frame's first.
if (resource.sharedImageHeld && generation == resource.sharedImageGeneration) {
CloseSyncFile(fence);
return;
}
// Out of any render pass, in the recording the use goes into (or one ahead of it).
auto& frame = m_frameContext.GetCurrent();
if (!frame.isCommandRecording) m_frameContext.BeginCommandRecording();
if (VkRenderPassManager::GetActiveRenderPass()) VkRenderPassManager::EndRenderPass(frame.commandBuffer);
// The write's fence gates the submission carrying the acquire: this recording's, or an
// earlier one if a flush takes it first - either way ahead of every later command.
StageSharedImageWait(fence, kSharedImageUseStages);
const Uint32 family = static_cast<Uint32>(m_physicalDevice.queueFamilies.graphicsFamily);
VkImageMemoryBarrier barrier{VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER};
barrier.image = resource.image;
barrier.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
VkPipelineStageFlags acquireAfter = kSharedImageUseStages;
if (resource.sharedImageHeld) {
// Written again while this frame holds it - a buffer reused before the compositor let
// it go. It is handed back first, so the acquire below matches a release.
barrier.srcAccessMask = VK_ACCESS_MEMORY_WRITE_BIT;
barrier.dstAccessMask = 0;
barrier.oldLayout = resource.layout;
barrier.newLayout = VK_IMAGE_LAYOUT_GENERAL;
barrier.srcQueueFamilyIndex = family;
barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_FOREIGN_EXT;
vkCmdPipelineBarrier(frame.commandBuffer, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, 0, nullptr, 0, nullptr, 1, &barrier);
acquireAfter = VK_PIPELINE_STAGE_ALL_COMMANDS_BIT;
}
// GENERAL: the layout the writer releases in, and the one every wire descriptor samples
// in. An image no present has written yet (generation 0) has nothing to keep.
barrier.srcAccessMask = 0;
barrier.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT;
barrier.oldLayout = generation == 0 ? VK_IMAGE_LAYOUT_UNDEFINED : VK_IMAGE_LAYOUT_GENERAL;
barrier.newLayout = VK_IMAGE_LAYOUT_GENERAL;
barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_FOREIGN_EXT;
barrier.dstQueueFamilyIndex = family;
vkCmdPipelineBarrier(frame.commandBuffer, acquireAfter, kSharedImageUseStages, 0, 0, nullptr, 0, nullptr, 1,
&barrier);
// The open recording names the image now: its out-of-pass work may not move ahead of it.
m_textureManager->StampResourceRecordingUse(resource);
resource.layout = VK_IMAGE_LAYOUT_GENERAL;
resource.sharedImageGeneration = generation;
if (!resource.sharedImageHeld) {
resource.sharedImageHeld = true;
// The current recording is the next submission (RetireWireObjects' rule).
m_sharedImagesHeld.push_back({resource.sharedImageKey, m_submitCounter + 1});
}
m_sharedImageReads.NoteRead(image);
}
// THE FRAME BOUNDARY (Present). Every image this frame acquired goes back to the foreign
// family in the frame's last recording, and that recording's submission signals the semaphore
// whose sync_file is published as the frame's read fence for all of them at once.
void VulkanRenderer::ReleaseHeldSharedImages() {
if (m_sharedImagesHeld.empty()) return;
const Uint32 family = static_cast<Uint32>(m_physicalDevice.queueFamilies.graphicsFamily);
Vector<VkImageMemoryBarrier> releases;
releases.reserve(m_sharedImagesHeld.size());
for (const auto& hold : m_sharedImagesHeld) {
// Gone or re-imaged since: a destroyed image needs no release, and a replacement
// acquired this frame has an entry of its own.
auto* resource = m_textureManager->FindWireTextureResource(hold.key);
if (resource == nullptr || !resource->sharedImageHeld) continue;
VkImageMemoryBarrier barrier{VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER};
barrier.srcAccessMask = VK_ACCESS_MEMORY_WRITE_BIT;
barrier.dstAccessMask = 0;
barrier.oldLayout = resource->layout;
barrier.newLayout = VK_IMAGE_LAYOUT_GENERAL;
barrier.srcQueueFamilyIndex = family;
barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_FOREIGN_EXT;
barrier.image = resource->image;
barrier.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
releases.push_back(barrier);
resource->sharedImageHeld = false;
resource->layout = VK_IMAGE_LAYOUT_GENERAL;
m_textureManager->StampResourceRecordingUse(*resource);
}
m_sharedImagesHeld.clear();
if (releases.empty()) return;
auto& frame = m_frameContext.GetCurrent();
if (!frame.isCommandRecording) m_frameContext.BeginCommandRecording();
if (VkRenderPassManager::GetActiveRenderPass()) VkRenderPassManager::EndRenderPass(frame.commandBuffer);
vkCmdPipelineBarrier(frame.commandBuffer, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, 0, 0, nullptr, 0, nullptr,
static_cast<Uint32>(releases.size()), releases.data());
}
void VulkanRenderer::PublishSharedImageReads() {
const VkSemaphore signal = std::exchange(m_sharedImageSignalSubmitted, VK_NULL_HANDLE);
int fence = -1;
// An export also unsignals the semaphore, which is what lets it be signaled again: a
// submitted signal is exported even when nothing is left to publish it to.
if (signal != VK_NULL_HANDLE && !ExportSharedImageSignal(signal, fence)) fence = -1;
if (m_sharedImageReads.Pending() == 0) {
CloseSyncFile(fence);
return;
}
// No fence (no export on this device): the frame's reads go unpublished - the file
// comment says why that is the choice.
m_sharedImageReads.PublishFrame(fence);
}
void VulkanRenderer::AbandonSharedImageReads() {
// Acquires recorded into the dropped recording never ran, so those images are not held;
// ones an earlier flush submitted are, and the next frame boundary releases them.
SizeT kept = 0;
for (const auto& hold : m_sharedImagesHeld) {
if (hold.acquireSubmit <= m_submitCounter) {
m_sharedImagesHeld[kept++] = hold;
continue;
}
if (auto* resource = m_textureManager->FindWireTextureResource(hold.key))
resource->sharedImageHeld = false;
}
m_sharedImagesHeld.resize(kept);
// Its waits and signal were never submitted. A wait semaphore's unconsumed temporary
// payload is replaced by its next import; the signal semaphore was never signaled.
for (const auto& wait : m_sharedImageWaits) m_freeSharedImageWaitSemaphores.push_back(wait.semaphore);
m_sharedImageWaits.clear();
if (m_sharedImageSignal != VK_NULL_HANDLE)
m_freeSharedImageSignalSemaphores.push_back(std::exchange(m_sharedImageSignal, VK_NULL_HANDLE));
}
#endif // MOBILEGL_BUILD_DISAGGREGATED
+737
View File
@@ -0,0 +1,737 @@
// MobileGL - MobileGL/MG_Backend/GbmFrameChannel.cpp
// Copyright (c) 2025-2026 MobileGL-Dev
// Licensed under the GNU Lesser General Public License v3.0:
// https://www.gnu.org/licenses/gpl-3.0.txt
// https://www.gnu.org/licenses/lgpl-3.0.txt
// SPDX-License-Identifier: LGPL-3.0-only
// End of Source File Header
#include "GbmFrameChannel.h"
#if MOBILEGL_BUILD_DISAGGREGATED && defined(__ANDROID__)
#include <android/hardware_buffer.h>
#include <cerrno>
#include <cstring>
#include <poll.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/un.h>
#include <unistd.h>
// WHAT THIS FILE IS WRITTEN AGAINST, AND WHAT HAS NOT BEEN RUN.
//
// The other end exists and is tested on this machine: MobileGL/MG_Gbm/GbmHostChannel.cpp dials
// this socket with SOCK_SEQPACKET, reads one message per frame, computes that message's expected
// length from the handle's own two counts, and refuses any other length. Every byte below is
// written to that parser. There is no phone attached to the machine this was written on, so the
// file is compile-verified for aarch64 Android and nothing more: the first run on a device is what
// will say whether the relay in RelayHandle() reads back the handle's bytes exactly as
// AHardwareBuffer_sendHandleToUnixSocket writes them, which is why that path is written to
// survive both layouts the platform's serializer could have (see the note there).
namespace MobileGL::MG_Backend {
namespace {
// THE LAYOUT IS A PROTOCOL, SO ITS SIZES ARE ASSERTED AND NOT ASSUMED. The container
// derives the length of a frame message from these three sizes plus the handle's counts,
// so a field added here, or the packing attribute dropped, would not be a compile error
// over there - it would be every frame skipped with a message about its length.
static_assert(sizeof(GbmFrameOffer) == 10 * sizeof(Uint32), "the offer is ten 32 bit fields on the wire");
static_assert(sizeof(GbmFrameRelease) == 3 * sizeof(Uint32), "the release is three 32 bit fields on the wire");
static_assert(sizeof(GbmNativeHandleHeader) == 3 * sizeof(Int32),
"a native handle begins with a version and two counts, on every Android ABI");
// The container reads one message per frame into a 4 KiB buffer and skips a message that
// does not fit in it (GbmHostMessageMax, GbmHostChannel.cpp), so a message larger than this
// is refused here rather than built and dropped there.
constexpr SizeT kMessageMax = 4096;
// The descriptors one handle may carry, which is the container's own cap (GbmHostMaxFds).
// Every AHardwareBuffer handle this project has seen carries one - the dma-buf - and both
// ends refuse a frame whose handle names more than they can take rather than forward a
// truncated list into a buffer of unknown memory.
constexpr Int kMaxHandleFds = 8;
// How many release messages one call reads before it returns to the frame. A cap and not a
// 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.
constexpr Int kRelayWaitMs = 2;
// close() may overwrite the errno a caller is in the middle of reporting, and every caller
// here is reporting a failure errno describes.
void CloseQuietly(Int fd) {
if (fd < 0) return;
const Int savedErrno = errno;
::close(fd);
errno = savedErrno;
}
}
GbmFrameChannel::~GbmFrameChannel() { Close(); }
Bool GbmFrameChannel::Open() {
const std::lock_guard<std::mutex> lock(m_mutex);
if (m_listen >= 0) return true;
const char* configured = ::getenv(kGbmFrameSocketEnv);
const char* path = (configured != nullptr && configured[0] != 0) ? configured : kGbmFrameSocketPath;
constexpr SizeT pathMax = sizeof(((struct sockaddr_un*)nullptr)->sun_path);
if (std::strlen(path) >= pathMax) {
MGLOG_E_ONCE("gbm frame channel: the container socket path %s does not fit in sun_path (%zu bytes); no "
"container can be served",
path, pathMax);
return false;
}
// SOCK_SEQPACKET because that is what the container dials with (GbmHostChannel::EnsureOpen
// asks for exactly this), and a stream listener answers it EPROTOTYPE - the container
// prints that as "a socket of a different type". SOCK_NONBLOCK because the accept below
// runs on the apply thread and may not wait for a container that is not there; SOCK_CLOEXEC
// because every process this server starts would otherwise inherit a socket that receives
// the phone's frames.
const Int fd = ::socket(AF_UNIX, SOCK_SEQPACKET | SOCK_NONBLOCK | SOCK_CLOEXEC, 0);
if (fd < 0) {
MGLOG_E_ONCE("gbm frame channel: socket(AF_UNIX, SOCK_SEQPACKET): %s; the frames are drawn and presented "
"without a container",
std::strerror(errno));
return false;
}
// A node left behind by a server that died is not a reason to refuse a container: bind
// would answer EADDRINUSE for a socket nobody is listening on.
::unlink(path);
struct sockaddr_un address = {};
address.sun_family = AF_UNIX;
// The terminator travels with the name: sun_path is a C string for a pathname socket, and a
// name without one is a name the kernel reads past the end of.
std::memcpy(address.sun_path, path, std::strlen(path) + 1);
if (::bind(fd, reinterpret_cast<struct sockaddr*>(&address), sizeof(address)) != 0) {
MGLOG_E_ONCE("gbm frame channel: bind(%s): %s; the frames are drawn and presented without a container",
path, std::strerror(errno));
CloseQuietly(fd);
return false;
}
// connect() to a pathname socket needs write permission on the node, and the container is
// not this process's user, so the umask's usual 0755 would leave it refused for a reason it
// could not see. 0666 is what makes the node reachable by the other half of a split run; a
// chmod that fails is not fatal, because a peer running as this uid still dials it.
if (::chmod(path, 0666) != 0) {
MGLOG_W_ONCE("gbm frame channel: chmod(%s, 0666): %s; a container running as another user cannot dial "
"this socket",
path, std::strerror(errno));
}
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);
CloseQuietly(fd);
return false;
}
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;
}
Bool GbmFrameChannel::EnsureRelay() {
if (m_relay[0] >= 0 && m_relay[1] >= 0) return true;
// Both ends are dropped before a new pair is made: half a socketpair is a socket with bytes
// in it that nothing will ever read, and the next handle read from it would be the tail of
// the last one.
DropRelay();
Int pair[2] = {-1, -1};
if (::socketpair(AF_UNIX, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0, pair) != 0) {
MGLOG_E_ONCE("gbm frame channel: socketpair for the handle relay: %s; no frame can be offered until one "
"can be made",
std::strerror(errno));
return false;
}
m_relay[0] = pair[0];
m_relay[1] = pair[1];
return true;
}
void GbmFrameChannel::DropRelay() {
CloseQuietly(m_relay[0]);
CloseQuietly(m_relay[1]);
m_relay[0] = -1;
m_relay[1] = -1;
}
Bool GbmFrameChannel::RelayHandle(struct AHardwareBuffer* buffer, Uint8* payload, SizeT capacity, SizeT& payloadBytes,
Int* fds, Int& fdCount) {
payloadBytes = 0;
fdCount = 0;
if (!EnsureRelay()) return false;
// WHY A FRAME'S HANDLE GOES THROUGH A SOCKETPAIR OF THIS CHANNEL'S OWN.
//
// The container takes ONE message per frame - the offer, then the handle's counts, then the
// arrays those counts describe, with the descriptors in that same message's SCM_RIGHTS
// control data - and it refuses a message of any other length. Two sends cannot be one
// message on a message-oriented socket, so AHardwareBuffer_sendHandleToUnixSocket, which
// sends a handle as a message of its own, is pointed at a socketpair this channel owns, and
// what comes out of the other end is both halves of what the container wants: the handle's
// own bytes, read here, and its descriptors, as SCM_RIGHTS.
//
// The alternative does not exist: the NDK's <android/hardware_buffer.h> declares no way to
// ask a buffer for its descriptors. AHardwareBuffer_getNativeHandle is a platform API and
// is absent from the NDK's copy of that header (checked against NDK 27.3.13750724 in this
// tree's build-termux toolchain), so this is the one route from an AHardwareBuffer to a
// dma-buf descriptor that an app can take.
const Int code = AHardwareBuffer_sendHandleToUnixSocket(buffer, m_relay[0]);
if (code != 0) {
MGLOG_W_ONCE("gbm frame channel: the frame's handle did not cross the relay socket (rc %d, errno %d); the "
"frame is not offered to the container",
code, errno);
// The relay is dropped rather than kept: a send that failed part way through would
// leave bytes that the next handle's read would take for its own header.
DropRelay();
return false;
}
struct iovec vector = {};
vector.iov_base = payload;
vector.iov_len = capacity;
Uint8 control[CMSG_SPACE(sizeof(Int) * (SizeT)kMaxHandleFds)] = {};
struct msghdr message = {};
message.msg_iov = &vector;
message.msg_iovlen = 1;
message.msg_control = control;
message.msg_controllen = sizeof(control);
// MSG_DONTWAIT for the promise at the top of this file, and MSG_CMSG_CLOEXEC so a descriptor
// read out of the relay does not survive into a child of this process, which would then hold
// the phone's frame until it died.
ssize_t got = ::recvmsg(m_relay[1], &message, MSG_DONTWAIT | MSG_CMSG_CLOEXEC);
if (got < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)) {
struct pollfd waiting = {};
waiting.fd = m_relay[1];
waiting.events = POLLIN;
if (::poll(&waiting, 1, kRelayWaitMs) > 0) {
// The kernel rewrites these on every call, so a retry starts from the same state as
// the first attempt.
message.msg_controllen = sizeof(control);
message.msg_flags = 0;
got = ::recvmsg(m_relay[1], &message, MSG_DONTWAIT | MSG_CMSG_CLOEXEC);
}
}
if (got < 0) {
MGLOG_W_ONCE("gbm frame channel: a relayed handle could not be read back (%d: %s); the frame is not "
"offered to the container",
errno, std::strerror(errno));
DropRelay();
return false;
}
if (got == 0) {
// Zero bytes on a connected socket is the end of it. Only this process holds either end
// of this socketpair, so this is a bug being reported rather than a peer going away.
MGLOG_W_ONCE("gbm frame channel: the handle relay is closed; the frame is not offered to the container");
DropRelay();
return false;
}
// The descriptors come out of the control data before anything is decided about the
// message, because they belong to this process from the moment they were received: a path
// that returns without closing them leaks a descriptor per frame.
Int collected = 0;
for (struct cmsghdr* header = CMSG_FIRSTHDR(&message); header != nullptr;
header = CMSG_NXTHDR(&message, header)) {
if (header->cmsg_level != SOL_SOCKET || header->cmsg_type != SCM_RIGHTS) continue;
const SizeT bytes = (SizeT)header->cmsg_len - CMSG_LEN(0);
const Int count = (Int)(bytes / sizeof(Int));
const Int* descriptors = reinterpret_cast<const Int*>(CMSG_DATA(header));
for (Int i = 0; i < count; ++i) {
if (collected < kMaxHandleFds) {
fds[collected++] = descriptors[i];
} else {
// More descriptors than a frame can carry: they are this process's now, so they
// are closed here rather than leaked.
CloseQuietly(descriptors[i]);
}
}
}
if ((message.msg_flags & MSG_CTRUNC) != 0) {
MGLOG_W_ONCE("gbm frame channel: a frame's control data did not fit in %zu bytes; the frame is not "
"offered because its descriptor list is incomplete",
sizeof(control));
for (Int i = 0; i < collected; ++i) CloseQuietly(fds[i]);
DropRelay();
return false;
}
if ((message.msg_flags & MSG_TRUNC) != 0 || (SizeT)got < sizeof(GbmNativeHandleHeader)) {
// A message longer than a handle can be, or shorter than the three counts every handle
// begins with. Either way it cannot describe a frame, and a relay that has been read
// past the end of one message must not carry the next frame's header: it is recreated.
MGLOG_W_ONCE("gbm frame channel: a relayed handle is %zd bytes and %s; the frame is not offered", got,
((message.msg_flags & MSG_TRUNC) != 0) ? "longer than a handle can be"
: "too short to hold its own counts");
for (Int i = 0; i < collected; ++i) CloseQuietly(fds[i]);
DropRelay();
return false;
}
// 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;
}
// 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<std::mutex> 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;
}
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;
}
if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) return true;
MarkDown("recv", errno);
return false;
}
void GbmFrameChannel::MarkDown(const char* what, Int error) {
if (m_client < 0) return;
CloseQuietly(m_client);
m_client = -1;
if (error != 0) {
MGLOG_W("gbm frame channel: the container connection is down: %s failed (%d: %s); the frames are still "
"drawn and presented, and the container stops receiving them until it dials again",
what, error, std::strerror(error));
} else {
MGLOG_W("gbm frame channel: the container connection is down: %s; the frames are still drawn and "
"presented, and the container stops receiving them until it dials again",
what);
}
}
Bool GbmFrameChannel::OfferFrame(struct AHardwareBuffer* buffer, const HostFrameOffer& offer) {
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<std::mutex> lock(m_mutex);
// 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<std::mutex> 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];
SizeT payloadBytes = 0;
Int fds[kMaxHandleFds];
for (Int i = 0; i < kMaxHandleFds; ++i) fds[i] = -1;
Int fdCount = 0;
if (!RelayHandle(buffer, payload, sizeof(payload), payloadBytes, fds, fdCount)) return false;
GbmNativeHandleHeader handle = {};
std::memcpy(&handle, payload, sizeof(handle));
const SizeT tail = ((SizeT)handle.NumFds + (SizeT)handle.NumInts) * sizeof(Int32);
const SizeT messageBytes = sizeof(GbmFrameOffer) + sizeof(GbmNativeHandleHeader) + tail;
// EVERY REASON THIS CHANNEL REFUSES A FRAME, IN ONE PLACE. Each of them is a frame the
// container would refuse anyway - it checks the same counts and the same geometry - and a
// frame that is refused here costs nothing: no message, no sequence number, and no entry in
// the count of frames waiting to be released.
const char* refusal = nullptr;
if (offer.Width == 0 || offer.Height == 0 || offer.StrideBytes == 0) {
refusal = "the host described it with a width, height or stride of zero, and a buffer with no size is "
"not one a compositor can render into";
} else if (handle.NumFds < 1) {
refusal = "its handle carries no descriptor, and a frame without a dma-buf is not one the container "
"can render into";
} else if (handle.NumFds > kMaxHandleFds) {
refusal = "its handle carries more descriptors than either end takes";
} else if (handle.NumInts < 0) {
refusal = "its handle claims a negative number of integers";
} else if ((SizeT)handle.NumInts > kMessageMax / sizeof(Int32)) {
// This is what keeps the message's length arithmetic from wrapping on a 32 bit ABI: a
// handle whose integer array alone is longer than a whole message cannot be carried by
// this protocol whatever the rest of it says, and the check below would otherwise be
// reading a number that had already turned into a small and plausible one.
refusal = "its handle names more integers than a whole message could carry";
} else if (fdCount < handle.NumFds) {
refusal = "fewer descriptors arrived with it than its handle names";
} else if (messageBytes > kMessageMax) {
refusal = "the message it makes is longer than the container reads";
}
Bool offered = false;
if (refusal != nullptr) {
// ONCE, not per frame: a host that describes every frame the same broken way must not
// turn this into a line per frame on the apply thread.
MGLOG_W_ONCE("gbm frame channel: frame %u (%ux%u) is not offered to the container: %s", offer.Index,
offer.Width, offer.Height, refusal);
} else {
// One message, built whole: the offer, then the handle's own three counts, then the two
// arrays the counts describe. What came back from the relay is copied in as far as it
// goes and the remainder is left zero, because the container checks the LENGTH it
// derives from those counts and never reads the arrays themselves - it takes the
// descriptors from the control data and hands the first one to GBM. So a handle whose
// bytes are shorter than its own counts imply is padded rather than refused, and one
// longer than they imply is cut to what the counts say; either way the length the
// container computes is the length it receives.
Uint8 message[kMessageMax] = {};
GbmFrameOffer out = {};
out.Magic = kGbmFrameOfferMagic;
out.Version = kGbmFrameVersion;
out.Seq = seq;
out.Index = offer.Index;
out.Width = offer.Width;
out.Height = offer.Height;
out.StrideBytes = offer.StrideBytes;
out.Format = offer.Format;
out.UsageLo = offer.UsageLo;
out.UsageHi = offer.UsageHi;
std::memcpy(message, &out, sizeof(out));
const SizeT handleBytes = (payloadBytes < sizeof(GbmNativeHandleHeader) + tail)
? payloadBytes
: (sizeof(GbmNativeHandleHeader) + tail);
std::memcpy(message + sizeof(out), payload, handleBytes);
struct iovec vector = {};
vector.iov_base = message;
vector.iov_len = messageBytes;
Uint8 control[CMSG_SPACE(sizeof(Int) * (SizeT)kMaxHandleFds)] = {};
struct msghdr outgoing = {};
outgoing.msg_iov = &vector;
outgoing.msg_iovlen = 1;
outgoing.msg_control = control;
outgoing.msg_controllen = CMSG_SPACE(sizeof(Int) * (SizeT)handle.NumFds);
struct cmsghdr* rights = CMSG_FIRSTHDR(&outgoing);
rights->cmsg_level = SOL_SOCKET;
rights->cmsg_type = SCM_RIGHTS;
rights->cmsg_len = CMSG_LEN(sizeof(Int) * (SizeT)handle.NumFds);
std::memcpy(CMSG_DATA(rights), fds, sizeof(Int) * (SizeT)handle.NumFds);
// MSG_DONTWAIT for the promise at the top of this file, and MSG_NOSIGNAL because a
// server killed by SIGPIPE when the container goes away takes the frames it was drawing
// with it. A full socket, a reset peer and a broken pipe all say the same thing here:
// this connection can no longer be trusted with a frame, so it is closed and the next
// container to dial is served.
const ssize_t sent = ::sendmsg(m_client, &outgoing, MSG_DONTWAIT | MSG_NOSIGNAL);
if (sent != (ssize_t)messageBytes) {
MarkDown("sendmsg", (sent < 0) ? errno : 0);
} else {
// 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
// either failing, so the value the host actually sends is put where a run on a
// device can be read afterwards.
MGLOG_I_ONCE("gbm frame channel: the first frame is offered to the container (seq %u index %u %ux%u "
"stride %u format 0x%08x)",
out.Seq, out.Index, out.Width, out.Height, out.StrideBytes, out.Format);
MGLOG_D("gbm frame channel: frame seq=%u index=%u offered (%zu bytes, %d descriptor(s), %llu "
"outstanding)",
out.Seq, out.Index, messageBytes, handle.NumFds, (unsigned long long)m_outstanding);
}
}
// The kernel took its own copies of these when the message was sent, and one that was not
// sent is not the container's to hold: every path closes what the relay handed over.
for (Int i = 0; i < fdCount; ++i) CloseQuietly(fds[i]);
return offered;
}
void GbmFrameChannel::Poll() {
const std::lock_guard<std::mutex> lock(m_mutex);
PollLocked();
}
void GbmFrameChannel::PollLocked() {
if (m_client < 0) return;
for (Int drained = 0; drained < kDrainMax; ++drained) {
GbmFrameRelease release = {};
struct iovec vector = {};
vector.iov_base = &release;
vector.iov_len = sizeof(release);
struct msghdr message = {};
message.msg_iov = &vector;
message.msg_iovlen = 1;
// recvmsg and not recv, for MSG_TRUNC: a message longer than a release can only be a
// peer speaking something else, and a release read out of the first twelve bytes of it
// would name a frame nobody released.
const ssize_t got = ::recvmsg(m_client, &message, MSG_DONTWAIT);
if (got < 0) {
if (errno == EINTR) continue;
// Nothing said, which is what a container that is between frames looks like.
if (errno == EAGAIN || errno == EWOULDBLOCK) return;
MarkDown("recvmsg", errno);
return;
}
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. Its replacement is taken by the next frame.
MarkDown("the container closed the connection", 0);
return;
}
if ((message.msg_flags & MSG_TRUNC) != 0 || got != (ssize_t)sizeof(release)) {
// The message is skipped, not the connection: on a message-oriented socket a
// message too long for the buffer is consumed whole, so the next one is still a
// message rather than the tail of this one.
MGLOG_W_ONCE("gbm frame channel: the container sent a message that is not a %zu byte release; it is "
"skipped",
sizeof(release));
continue;
}
if (release.Magic != kGbmFrameReleaseMagic) {
MGLOG_W_ONCE("gbm frame channel: a message from the container begins with 0x%08x rather than 'MGGR'; "
"it is skipped",
release.Magic);
continue;
}
if (release.Version != kGbmFrameVersion) {
// Refused rather than acted on: the version is what says how the rest of the message
// is laid out, and a release read with the wrong layout names a frame the container
// did not mean.
MGLOG_E_ONCE("gbm frame channel: the container speaks protocol version %u where this server speaks "
"version %u; its releases are refused until the two agree",
release.Version, (Uint32)kGbmFrameVersion);
continue;
}
++m_released;
if (m_outstanding > 0) --m_outstanding;
// The first release is the only one worth a line: it is the proof that the container
// took the descriptor and its compositor retired the frame, where every later one says
// the same thing sixty times a second.
MGLOG_I_ONCE("gbm frame channel: the container is releasing frames (first: seq %u)", release.Seq);
}
// Anything past this cap stays in the socket, whose buffer the kernel bounds, and goes out
// with the next frame: a peer that says nothing but releases may not spend the apply thread
// here.
}
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<std::mutex> 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);
m_client = -1;
DropRelay();
if (m_listen >= 0) {
// The node is this channel's to remove only while it still IS this channel's socket: a
// server that was restarted has bound the same path with a socket of its own, and a
// teardown that unlinked it would take the successor's node away with it. st_dev and
// st_ino against the listening descriptor is the cheapest way to ask, and a check that
// fails only leaves a name behind that the next Open() unlinks anyway.
struct stat node = {};
struct stat socket = {};
if (!m_path.empty() && ::stat(m_path.c_str(), &node) == 0 && ::fstat(m_listen, &socket) == 0 &&
node.st_dev == socket.st_dev && node.st_ino == socket.st_ino) {
::unlink(m_path.c_str());
}
CloseQuietly(m_listen);
m_listen = -1;
}
m_path.clear();
// The counters are history and stay: a caller that logs Outstanding() after a teardown is
// asking what happened, and IsUp() is what answers what is connected now.
}
}
#else // !(MOBILEGL_BUILD_DISAGGREGATED && __ANDROID__)
namespace MobileGL::MG_Backend {
// A build that is not the Android render server has no AHardwareBuffer to offer and no
// container beside it. The class exists so that callers do not have to be compiled
// differently, and every entry point answers the way an absent container does.
GbmFrameChannel::~GbmFrameChannel() = default;
Bool GbmFrameChannel::Open() { return false; }
Bool GbmFrameChannel::OfferFrame(struct AHardwareBuffer*, const HostFrameOffer&) { return false; }
void GbmFrameChannel::Poll() {}
void GbmFrameChannel::Close() {}
}
#endif
// End of Source File Header
+281
View File
@@ -0,0 +1,281 @@
// MobileGL - MobileGL/MG_Backend/GbmFrameChannel.h
// Copyright (c) 2025-2026 MobileGL-Dev
// Licensed under the GNU Lesser General Public License v3.0:
// https://www.gnu.org/licenses/gpl-3.0.txt
// https://www.gnu.org/licenses/lgpl-3.0.txt
// SPDX-License-Identifier: LGPL-3.0-only
// End of Source File Header
#pragma once
#include <Includes.h>
#include "HostFrameBridge.h"
struct AHardwareBuffer;
namespace MobileGL::MG_Backend {
// THE FRAME THE HOST HANDED OVER, HANDED ON TO THE CONTAINER AS A dma-buf.
//
// The display host owns a pool of AHardwareBuffers: it allocates them, this side imports the
// one it offers as a draw target (HostFrameBridge, DirectGLES::HostFrameTarget), and the host
// puts it on the glass when this side answers that it is drawn. The Wayland compositor in the
// Linux container has to render into THOSE SAME frames - it runs this project's own GBM, and a
// gbm_bo_create there answers with the phone's frame instead of a dma-heap allocation of its
// own - so every frame this side takes has to reach the container as that frame's dma-buf
// descriptor. That, and the release that comes back, is all this channel carries.
//
// The container's end is MobileGL/MG_Gbm/GbmHostChannel.cpp. It reads exactly the bytes
// declared below and answers with a release once its compositor no longer reads the frame.
// The three shapes ARE that file's GbmFrameOffer/GbmFrameRelease and GbmInternal.h's
// AHBNativeHandleHeader, field for field and packing included. They are restated here rather
// than shared because the two ends are built into different libraries from different build
// configurations: MG_Backend is the Android render server and never sees libgbm's headers,
// while MG_Gbm is built for the container and never sees Android's. 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.
//
// ONE MESSAGE PER FRAME, on SOCK_SEQPACKET, and that is part of the protocol rather than an
// implementation detail: an offer and its handle only mean anything together, and the message
// boundary is what lets the reader take the two as one thing. The container derives the
// length of the message it expects from the handle's own two counts and refuses any other
// length, so this end sends the offer immediately followed by the handle's counts and its two
// arrays, with the descriptors in the SCM_RIGHTS control data of that same sendmsg.
//
// The channel is OPTIONAL, and that is the rule the implementation is built around: a
// container that is not running, has died, or has stopped reading may cost the render path a
// syscall or two, and may never block it, fail it, or grow without bound. Every entry point
// below is non-blocking and answers silence with silence.
inline constexpr Uint32 kGbmFrameOfferMagic = 0x4647474Du; // 'M','G','G','F' in memory order
inline constexpr Uint32 kGbmFrameReleaseMagic = 0x5247474Du; // 'M','G','G','R' in memory order
inline constexpr Uint32 kGbmFrameVersion = 1u;
// WHERE THE CONTAINER DIALS. /data/local/tmp is the one directory both halves of a split run
// can be pointed at on a device, and the default lives on this end because this end is the
// server. The container's compiled-in default is /run/mobilegl-gbm.sock - the same protocol
// with the path each side can reach unaided - so a deployment that puts the two in different
// mount namespaces sets MOBILEGL_GBM_SOCKET on both; it is read here and in
// GbmHostChannelCreate, from the same variable, for that reason.
inline constexpr const char* kGbmFrameSocketPath = "/data/local/tmp/mobilegl-gbm.sock";
inline constexpr const char* kGbmFrameSocketEnv = "MOBILEGL_GBM_SOCKET";
// One frame the host offered, described for the container. Width, Height, StrideBytes and
// Format are the host's own numbers for the frame (HostFrameOffer), carried through
// unchanged: they describe the memory the descriptor points at, and this end is not the place
// where a number the other two ends agreed on gets rewritten.
struct GbmFrameOffer {
Uint32 Magic;
Uint32 Version;
Uint32 Seq; // this channel's, one per frame offered
Uint32 Index; // the host's own buffer index, echoed so the phone can match a frame
Uint32 Width;
Uint32 Height;
Uint32 StrideBytes;
Uint32 Format;
Uint32 UsageLo;
Uint32 UsageHi;
} __attribute__((packed));
// What the container says once it is done with a frame. It may arrive late, it may never
// arrive, and both are cheap here: the channel keeps a count and no per-frame record (see
// Outstanding below), so nothing is leaked and nothing grows when one is missed.
struct GbmFrameRelease {
Uint32 Magic;
Uint32 Version;
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
// AHBNativeHandleHeader. The counts are 32 bit on every Android ABI, which is why they are
// spelled out here rather than taken from a platform header this library cannot include.
struct GbmNativeHandleHeader {
Int32 Version;
Int32 NumFds;
Int32 NumInts;
} __attribute__((packed));
// ONE CONTAINER, ONE LISTENING SOCKET, TWO THREADS: the render path's, and an acceptor's.
//
// 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;
GbmFrameChannel(const GbmFrameChannel&) = delete;
GbmFrameChannel& operator=(const GbmFrameChannel&) = delete;
~GbmFrameChannel();
// 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.
// False means the frame did not go out, for any of the reasons this channel treats as
// ordinary: no container is connected, the container just died, or the frame could not be
// described. None of them is the caller's problem and none of them is fatal - the frame
// is drawn and presented exactly as it would have been without a channel at all.
Bool OfferFrame(struct AHardwareBuffer* buffer, const HostFrameOffer& offer);
// Reads whatever the container has said since the last call and marks the channel down if
// the connection has ended. OfferFrame already does this once per frame, so a caller only
// 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 {
const std::lock_guard<std::mutex> 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 {
const std::lock_guard<std::mutex> 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
// the connection end and goes back to allocating its frames locally, which is the state it
// starts in.
void Close();
private:
// The socketpair a frame's handle is handed to and read back from. Recreated on demand,
// because the one call the NDK offers for a buffer's descriptors sends them as a message
// of its own and the container takes one message per frame - see the note in the .cpp.
Bool EnsureRelay();
void DropRelay();
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 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);
Int m_listen = -1;
Int m_client = -1;
Int m_relay[2] = {-1, -1};
String m_path;
// Bumped only for a frame that actually went out, so a sequence number is never reused and
// a release can never be read as belonging to a frame of an earlier connection.
Uint32 m_nextSeq = 0;
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<Bool> 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;
};
}
+189
View File
@@ -0,0 +1,189 @@
// MobileGL - MobileGL/MG_Backend/HostFrameBridge.cpp
// Copyright (c) 2025-2026 MobileGL-Dev
// Licensed under the GNU Lesser General Public License v3.0:
// https://www.gnu.org/licenses/gpl-3.0.txt
// https://www.gnu.org/licenses/lgpl-3.0.txt
// SPDX-License-Identifier: LGPL-3.0-only
// End of Source File Header
#include "HostFrameBridge.h"
#if MOBILEGL_BUILD_DISAGGREGATED && defined(__ANDROID__)
#include <android/hardware_buffer.h>
#include <cerrno>
#include <cstring>
#include <poll.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
namespace MobileGL::MG_Backend {
namespace {
Bool ReadExactly(Int fd, void* out, SizeT n) {
Uint8* at = static_cast<Uint8*>(out);
while (n > 0) {
const ssize_t got = ::read(fd, at, n);
if (got <= 0) {
if (got < 0 && errno == EINTR) continue;
return false;
}
at += got;
n -= static_cast<SizeT>(got);
}
return true;
}
Bool WriteExactly(Int fd, const void* in, SizeT n) {
const Uint8* at = static_cast<const Uint8*>(in);
while (n > 0) {
const ssize_t put = ::write(fd, at, n);
if (put <= 0) {
if (put < 0 && errno == EINTR) continue;
return false;
}
at += put;
n -= static_cast<SizeT>(put);
}
return true;
}
}
HostFrameBridge::~HostFrameBridge() { Close(); }
Bool HostFrameBridge::Open(const char* path, Int acceptTimeoutMs, String& why) {
Close();
const char* name = (path != nullptr && path[0] != 0) ? path : kHostFrameSocket;
m_listen = ::socket(AF_UNIX, SOCK_STREAM, 0);
if (m_listen < 0) {
why = std::format("socket(AF_UNIX): {}", std::strerror(errno));
return false;
}
sockaddr_un address{};
address.sun_family = AF_UNIX;
if (std::strlen(name) >= sizeof(address.sun_path)) {
why = std::format("the socket name is longer than the kernel takes: {}", name);
Close();
return false;
}
// "@name" is the abstract namespace: sun_path[0] is NUL and the name follows it.
// Nothing is created on disk, so nothing is left behind and no file permission stands
// between two apps that may not write each other's directories.
if (name[0] == '@') {
address.sun_path[0] = 0;
std::strncpy(address.sun_path + 1, name + 1, sizeof(address.sun_path) - 2);
} else {
std::strncpy(address.sun_path, name, sizeof(address.sun_path) - 1);
// A leftover socket file from a server that died is not a reason to refuse the host.
::unlink(name);
}
if (::bind(m_listen, reinterpret_cast<sockaddr*>(&address), sizeof(address)) != 0) {
why = std::format("bind({}): {}", name, std::strerror(errno));
Close();
return false;
}
if (::listen(m_listen, 1) != 0) {
why = std::format("listen({}): {}", name, std::strerror(errno));
Close();
return false;
}
pollfd waiting{};
waiting.fd = m_listen;
waiting.events = POLLIN;
const Int ready = ::poll(&waiting, 1, acceptTimeoutMs);
if (ready <= 0) {
why = (ready == 0) ? std::format("no display host dialled {} within {} ms", name, acceptTimeoutMs)
: std::format("poll({}): {}", name, std::strerror(errno));
Close();
return false;
}
m_fd = ::accept(m_listen, nullptr, nullptr);
if (m_fd < 0) {
why = std::format("accept({}): {}", name, std::strerror(errno));
Close();
return false;
}
MGLOG_I("host frame bridge: a display host is on %s", name);
return true;
}
Bool HostFrameBridge::Acquire(struct AHardwareBuffer** buffer, HostFrameOffer& offer, String& why) {
*buffer = nullptr;
offer = HostFrameOffer{};
if (m_fd < 0) {
why = "the bridge is not open";
return false;
}
AHardwareBuffer* received = nullptr;
if (AHardwareBuffer_recvHandleFromUnixSocket(m_fd, &received) != 0 || received == nullptr) {
why = "the host stopped offering frames, or the handle did not cross";
return false;
}
if (!ReadExactly(m_fd, &offer, sizeof(offer)) || offer.Magic != kHostFrameMagic) {
// The handle is already this side's by the time this fails, so it goes back before
// the failure does: a reference held past the connection starves the host's pool.
AHardwareBuffer_release(received);
why = std::format("the frame's description did not follow its handle (magic 0x{:08x})", offer.Magic);
return false;
}
*buffer = received;
return true;
}
Bool HostFrameBridge::Complete(const HostFrameOffer& offer, Bool imported, Bool drawn, Bool fenceOk, String& why) {
if (m_fd < 0) {
why = "the bridge is not open";
return false;
}
HostFrameAck ack{};
ack.Magic = kHostFrameMagic;
ack.Version = kHostFrameVersion;
ack.Index = offer.Index;
ack.Imported = imported ? 1u : 0u;
ack.Drawn = drawn ? 1u : 0u;
ack.FenceOk = fenceOk ? 1u : 0u;
if (!WriteExactly(m_fd, &ack, sizeof(ack))) {
why = std::format("the answer to frame {} did not go out: {}", offer.Index, std::strerror(errno));
return false;
}
// The host answers with its own view of the pixels. It is what closes the round trip, so
// it is read here and kept rather than left in the socket for the next frame to trip over.
m_lastSeen = HostFrameSeen{};
if (!ReadExactly(m_fd, &m_lastSeen, sizeof(m_lastSeen)) || m_lastSeen.Magic != kHostFrameMagic) {
why = std::format("frame {} was answered but the host's readback did not arrive", offer.Index);
m_lastSeen = HostFrameSeen{};
return false;
}
return true;
}
void HostFrameBridge::Close() {
if (m_fd >= 0) ::close(m_fd);
if (m_listen >= 0) ::close(m_listen);
m_fd = -1;
m_listen = -1;
}
}
#else // !(MOBILEGL_BUILD_DISAGGREGATED && __ANDROID__)
namespace MobileGL::MG_Backend {
HostFrameBridge::~HostFrameBridge() = default;
Bool HostFrameBridge::Open(const char*, Int, String& why) {
why = "host frames are a disaggregated Android path";
return false;
}
Bool HostFrameBridge::Acquire(struct AHardwareBuffer**, HostFrameOffer&, String& why) {
why = "host frames are a disaggregated Android path";
return false;
}
Bool HostFrameBridge::Complete(const HostFrameOffer&, Bool, Bool, Bool, String& why) {
why = "host frames are a disaggregated Android path";
return false;
}
void HostFrameBridge::Close() {}
}
#endif
+103
View File
@@ -0,0 +1,103 @@
// MobileGL - MobileGL/MG_Backend/HostFrameBridge.h
// Copyright (c) 2025-2026 MobileGL-Dev
// Licensed under the GNU Lesser General Public License v3.0:
// https://www.gnu.org/licenses/gpl-3.0.txt
// https://www.gnu.org/licenses/lgpl-3.0.txt
// SPDX-License-Identifier: LGPL-3.0-only
// End of Source File Header
#pragma once
#include <Includes.h>
struct AHardwareBuffer;
namespace MobileGL::MG_Backend {
// THE DISPLAY HOST'S FRAMES, AS THEY ARRIVE.
//
// The Android side that owns the screen allocates its frames itself and offers each one over
// an AF_UNIX socket: the handle travels ahead of a fixed-size description on the same
// connection, and the host then waits for this side to say the frame is drawn before it puts
// it on the glass. Why the host allocates rather than this side asking for the display's own
// buffers is measured, not chosen: AHardwareBuffer_createFromHandle accepts an
// AHardwareBuffer this process allocated and refuses one the display queue handed over
// (gralloc BAD_VALUE), so the only frames a render server can draw into are the ones the host
// made for it.
//
// The three message shapes below ARE the host's (its ahb_bridge.h), field for field and
// packing included. They are restated here rather than shared because the two ends are built
// by different projects; 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.
inline constexpr Uint32 kHostFrameMagic = 0x4D474C41u; // the host spells it "ALGM" in memory
inline constexpr Uint32 kHostFrameVersion = 1u;
// AN ABSTRACT NAME, not a path: the two ends are separate apps, and neither may create a
// socket file in /data/local/tmp (its directory grants others traverse only). An abstract
// name lives in the kernel namespace instead of the filesystem, so there is no file
// permission to get wrong - the same reason this project names its own endpoints @mgl-*.
inline constexpr const char* kHostFrameSocket = "@mobilegl-host-frame";
struct HostFrameOffer {
Uint32 Magic;
Uint32 Version;
Uint32 Index;
Uint32 Width;
Uint32 Height;
Uint32 StrideBytes;
Uint32 Format;
Uint32 UsageLo;
Uint32 UsageHi;
char Note[64];
} __attribute__((packed));
struct HostFrameAck {
Uint32 Magic;
Uint32 Version;
Uint32 Index;
Uint32 Imported;
Uint32 Drawn;
Uint32 FenceOk;
Uint8 Color[4];
char Note[64];
} __attribute__((packed));
struct HostFrameSeen {
Uint32 Magic;
Uint32 Version;
Uint32 Index;
Uint32 Locked;
Uint8 Observed[4];
Uint8 ObservedCorner[4];
char Note[64];
} __attribute__((packed));
// One host connection at a time, which is what the host offers: it dials, hands over a frame,
// waits for the answer, and hands over the next.
class HostFrameBridge {
public:
HostFrameBridge() = default;
HostFrameBridge(const HostFrameBridge&) = delete;
HostFrameBridge& operator=(const HostFrameBridge&) = delete;
~HostFrameBridge();
// Listens on `path` (the well-known name by default) and waits for the host. A host that
// never dials is answered with false and a reason, never an abort.
Bool Open(const char* path, Int acceptTimeoutMs, String& why);
// Takes the next frame. Ownership of the returned AHardwareBuffer is the caller's, who
// must hand it back through ReleaseOwned() once the frame is off the glass.
Bool Acquire(struct AHardwareBuffer** buffer, HostFrameOffer& offer, String& why);
// Tells the host what became of the frame it offered, and reads back what the host's own
// view of the pixels holds. `drawn` is what the host waits for before it presents.
Bool Complete(const HostFrameOffer& offer, Bool imported, Bool drawn, Bool fenceOk, String& why);
// The readback the host returned for the last completed frame, as the host reported it.
const HostFrameSeen& LastSeen() const { return m_lastSeen; }
void Close();
private:
Int m_fd = -1;
Int m_listen = -1;
HostFrameSeen m_lastSeen{};
};
}
+4
View File
@@ -14,6 +14,7 @@
#if MOBILEGL_BUILD_DISAGGREGATED
#include <MG_Pipe/MGPipe.h>
#include <MG_Pipe/PipeApply.h>
#include <MG_Pipe/PipeMutation.h> // MGPipeForgetAllPublications, at the end of ShutdownSplitRoles
#include <MG_Remote/Client/ClientSession.h>
#include <MG_Remote/FatalFunnel.h> // InstallPipeSessionFailHook, installed at step 0 below
#include <MG_Remote/Server/ServerLoop.h>
@@ -398,6 +399,9 @@ namespace MobileGL::MG_Backend {
// and every later split bring-up in the process fails at CreateBackend's m_backend!=null
// guard.
MG_Remote::Server::ServerLoopInstance().Stop();
// The server's twins died with the session; the frontend objects that are destroyed after
// this (the GL context's) have nothing left on the other side to delete.
MG_Pipe::MGPipeForgetAllPublications();
}
#endif
+5 -23
View File
@@ -339,8 +339,6 @@ namespace MobileGL::MG_Pipe {
inputs.m_live = live;
inputs.m_contextIdentity = identity;
}
static void SetServerContextLive(PipeInputs& inputs, Bool live) { inputs.m_serverContextLive = live; }
static Bool ServerContextLive(const PipeInputs& inputs) { return inputs.m_serverContextLive; }
};
// ---- P5f (f1): the dual-block rehearsal's selection functions (PipeInputs.h) -----------
@@ -399,13 +397,14 @@ namespace MobileGL::MG_Pipe {
MGPipeStampAccess::SetServerStamped(MGPipeClientInputs(), false);
}
// The calling thread's block, so the calling session's (PipeInputs.h's m_serverContextLive).
namespace { Bool g_serverContextLive = false; }
void MGPipeServerSetContextLive(Bool live) {
MGPipeStampAccess::SetServerContextLive(gPipeInputs, live);
g_serverContextLive = live;
MGPipeServerBlockNoteIdentity();
}
Bool MGPipeServerContextIsLive() { return MGPipeStampAccess::ServerContextLive(gPipeInputs); }
Bool MGPipeServerContextIsLive() { return g_serverContextLive; }
#if MOBILEGL_BUILD_DISAGGREGATED
namespace { const void* g_serverOwnedWindow = nullptr; }
@@ -413,23 +412,6 @@ namespace MobileGL::MG_Pipe {
void MGPipeServerSetOwnedWindow(const void* window) { g_serverOwnedWindow = window; }
const void* MGPipeServerOwnedWindow() { return g_serverOwnedWindow; }
namespace {
Uint32 g_serverOwnedWindowWidth = 0;
Uint32 g_serverOwnedWindowHeight = 0;
} // namespace
void MGPipeServerSetOwnedWindowExtent(Uint32 width, Uint32 height) {
g_serverOwnedWindowWidth = width;
g_serverOwnedWindowHeight = height;
}
Bool MGPipeServerOwnedWindowExtent(Uint32* width, Uint32* height) {
if (g_serverOwnedWindowWidth == 0 || g_serverOwnedWindowHeight == 0) return false;
if (width != nullptr) *width = g_serverOwnedWindowWidth;
if (height != nullptr) *height = g_serverOwnedWindowHeight;
return true;
}
#endif
void MGPipeServerBlockNoteIdentity() {
@@ -451,7 +433,7 @@ namespace MobileGL::MG_Pipe {
// hands out a null slot - an unnamed crash where the rehearsal exists to produce a
// named one.
const Uint64 serial = MGPipeApplierContextSerial();
MGPipeStampAccess::SetIdentity(gPipeInputs, MGPipeServerContextIsLive(),
MGPipeStampAccess::SetIdentity(gPipeInputs, g_serverContextLive,
reinterpret_cast<const void*>(static_cast<std::uintptr_t>(
(serial << 1) | Uint64{1})));
}
+1 -57
View File
@@ -748,12 +748,6 @@ namespace MobileGL::MG_Pipe {
// ---- identity ----
const void* m_contextIdentity = nullptr;
Bool m_live = false;
// MGPipeServerSetContextLive's flag. In the block, not in a process global, because the
// in-process display server runs several sessions at once and each has its own served
// context: one session's teardown or eglMakeCurrent(NO_CONTEXT) must not mark a
// neighbour's context dead mid-frame (P14; the per-thread block resolution below is
// what makes this the calling session's).
Bool m_serverContextLive = false;
MGPipeVerb m_currentVerb = MGPipeVerb::kVerbCount;
#if MOBILEGL_PIPE_POISON
MGPipeFilledState m_filled{};
@@ -826,10 +820,6 @@ namespace MobileGL::MG_Pipe {
// The single global the backends read through MGB_CTX (ARCHITECTURE.md 9.2). An inline
// variable: no .cpp is needed for the definition.
//
// P14 S2: IT IS THE PROCESS-WIDE BLOCK, and `gPipeInputs` below is the name every reader
// spells - now one reference per THREAD, resolving to a served session's own block when the
// calling thread belongs to one. See the block after it.
//
// LEAK-AT-EXIT STORAGE, and it is the same rule Init.cpp and GlobalObjects.cpp state for
// pGLContext and pActiveBackendObject: "a process that exits without eglTerminate simply
// leaks the global singletons to the OS instead of running destructors during static
@@ -844,48 +834,7 @@ namespace MobileGL::MG_Pipe {
// about to be. So the reference is never dropped: nothing here can start such a chain.
// A live context releases these SharedPtrs the ordinary way, at the fill point.
// (P3a; the exit-time heap corruption this closes is p3a-results/exit-order-v1.md.)
inline PipeInputs& gPipeInputsDefault = *new PipeInputs();
// ============================================================================
// P14 S2: WHOSE BLOCK IS `gPipeInputs`?
// ============================================================================
//
// ONE PROCESS, SEVERAL SERVED SESSIONS. The applier writes this block and the backend reads it
// through MGB_CTX, both on the SAME apply thread - the block IS "the state the record in hand
// carries". Two sessions applying concurrently on two apply threads through one block would
// read each other's render state, which is the cross-talk a multi-session server must not
// have. Nothing about the block's contents changed; what changed is that the name resolves to
// the SESSION'S block on a thread that belongs to one.
//
// WHY A THREAD-LOCAL REFERENCE, AND NOT SOMETHING CLEVERER. MGB_CTX is
// `(&::MobileGL::MG_Pipe::gPipeInputs)` (MG_Pipe/PipeInputsSwitch.h) and is spelled at ~380
// sites in MG_Backend/MG_Impl; a reference whose TARGET varies with the calling thread is the
// only shape that keeps all of them compiling and all of them correct. The cost is one TLS
// address computation per access site - not one per field, and with no guard: the reference is
// bound once per thread on its first use.
//
// THE RESOLVER IS A HOOK because this header may not know about sessions (MG_Remote/Server
// owns them and includes THIS header, not the other way round). It is installed once by the
// server's session registry and never replaced; null - the client process, the pull build, a
// unit case - makes every thread resolve to gPipeInputsDefault, which is the old behaviour
// byte for byte.
//
// BINDING IS PER THREAD AND HAPPENS AT FIRST USE, so a thread must be inside its session's
// scope before it touches the block. Both of a session's threads are: the control thread opens
// its scope before it reads a byte of the Hello, and the apply thread opens it as its first
// act (ServerLoop::ApplyThreadMain).
using PipeInputsThreadResolver = PipeInputs* (*)();
inline PipeInputsThreadResolver g_pipeInputsThreadResolver = nullptr;
inline PipeInputs& MGPipeServerInputsForCallingThread() {
const PipeInputsThreadResolver resolve = g_pipeInputsThreadResolver;
if (resolve != nullptr) {
if (PipeInputs* const block = resolve()) return *block;
}
return gPipeInputsDefault;
}
inline thread_local PipeInputs& gPipeInputs = MGPipeServerInputsForCallingThread();
inline PipeInputs& gPipeInputs = *new PipeInputs();
#if MOBILEGL_BUILD_DISAGGREGATED
// ============================================================================
@@ -996,11 +945,6 @@ namespace MobileGL::MG_Pipe {
// earlier session relied on. Apply thread only.
void MGPipeServerSetOwnedWindow(const void* window);
const void* MGPipeServerOwnedWindow();
// That window's extent as the display last reported it (ServerLoop sets it from ServerDisplay with the
// lease and on every resize; 0x0 with no lease). The ONE size a backend publishes for it: a surface's own
// query can still answer the buffer before the resize. False while unknown. Apply thread only.
void MGPipeServerSetOwnedWindowExtent(Uint32 width, Uint32 height);
Bool MGPipeServerOwnedWindowExtent(Uint32* width, Uint32* height);
#else
// The push-without-transport build has one role and one block, so the fill side's spelling
// folds onto gPipeInputs and PipeFill.cpp reads identically in both build flavours. An
-39
View File
@@ -1,39 +0,0 @@
# MobileGL - MobileGL/MG_Gbm/CMakeLists.txt
#
# mobilegl_gbm.so: the GBM backend whose buffers are MobileGL shared images (MobileGLGbm.cpp).
# A loadable module for the system GBM loader, NOT part of libMobileGL.so - it reaches the library
# at run time through dlsym. Built against the system's <gbm.h> and <gbm_backend_abi.h> (MIT,
# shipped with the GBM loader's development files); a system without them builds without it.
#
# Usable standalone too (cmake -S MobileGL/MG_Gbm), for building just the plugin.
cmake_minimum_required(VERSION 3.16)
if (CMAKE_SOURCE_DIR STREQUAL CMAKE_CURRENT_SOURCE_DIR)
project(mobilegl_gbm CXX)
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
endif()
find_path(MOBILEGL_GBM_BACKEND_ABI_INCLUDE_DIR gbm_backend_abi.h)
find_path(MOBILEGL_GBM_INCLUDE_DIR gbm.h)
if (NOT MOBILEGL_GBM_BACKEND_ABI_INCLUDE_DIR OR NOT MOBILEGL_GBM_INCLUDE_DIR)
message(STATUS "MobileGL: gbm.h / gbm_backend_abi.h not found, mobilegl_gbm is not built")
return()
endif()
add_library(mobilegl_gbm MODULE MobileGLGbm.cpp)
set_target_properties(mobilegl_gbm PROPERTIES
PREFIX ""
OUTPUT_NAME mobilegl_gbm
CXX_VISIBILITY_PRESET hidden
VISIBILITY_INLINES_HIDDEN ON
)
target_include_directories(mobilegl_gbm PRIVATE
${MOBILEGL_GBM_INCLUDE_DIR}
${MOBILEGL_GBM_BACKEND_ABI_INCLUDE_DIR}
# SharedImageApi.h only: the plugin shares a C header with the library, not its code.
${CMAKE_CURRENT_SOURCE_DIR}/../MG_Impl
)
target_link_libraries(mobilegl_gbm PRIVATE ${CMAKE_DL_LIBS})
# Loaded into compositors: an unresolved symbol must fail the link, not the dlopen.
target_link_options(mobilegl_gbm PRIVATE "LINKER:--no-undefined")
+663
View File
@@ -0,0 +1,663 @@
// MobileGL - MobileGL/MG_Gbm/GbmApi.cpp
// SPDX-License-Identifier: LGPL-3.0-only
//
// The extern "C" surface: every entry point gbm.h declares, and nothing else.
//
// This file is a translation layer, and it is kept that way on purpose. Each entry
// point does three things - check the pointers it was handed, take the device's one
// mutex for the whole call, and hand the work to GbmDevice.cpp - so the concurrency
// rule ("one mutex per device, taken once at the API boundary, never inside the
// allocation code") is visible in one place instead of being spread over the
// backends. A missing lock is a bug that only shows up in the compositor, so the
// boilerplate is deliberately identical in every function.
//
// Two conventions are observable from outside and are stated here because they are
// the ones a caller can get wrong:
//
// * gbm_bo_get_fd and gbm_bo_get_fd_for_plane return a DUP the caller owns. The
// caller closes what it was given; the buffer's own descriptor is closed once,
// when the buffer is destroyed, and never by a caller's close.
// * Nothing here throws and nothing here aborts. A failure is reported the way
// GBM reports failures: null or -1 with errno set, so that the strerror(errno)
// a caller prints describes the failure that actually happened.
#include "GbmInternal.h"
#include <cerrno>
using namespace MobileGL;
using namespace MobileGL::MG_Gbm;
namespace
{
// The one mutex that guards a record, reached through the device that owns it.
// Null means the pointer was not one this library handed out, and every entry
// point turns that into its own failure answer rather than dereferencing it.
//
// A buffer or surface with no owner cannot exist while the library is used
// correctly - the device destroys everything it still holds before it goes away
// - so null here is a defence against a stale pointer rather than a state the
// code produces.
std::mutex* MutexOf(struct gbm_device* device) noexcept
{
return device != nullptr ? &device->Impl.Mutex : nullptr;
}
std::mutex* MutexOf(struct gbm_bo* bo) noexcept
{
return bo != nullptr ? MutexOf(bo->Impl.Owner) : nullptr;
}
std::mutex* MutexOf(struct gbm_surface* surface) noexcept
{
return surface != nullptr ? MutexOf(surface->Impl.Owner) : nullptr;
}
} // namespace
// ---------------------------------------------------------------------------
// Device
// ---------------------------------------------------------------------------
extern "C" struct gbm_device* gbm_create_device(int fd)
{
// No lock to take: the device being built is not reachable by any other thread
// until this call returns it.
return GbmDeviceCreate(fd);
}
extern "C" void gbm_device_destroy(struct gbm_device* gbm)
{
std::mutex* mutex = MutexOf(gbm);
if (mutex == nullptr)
{
return;
}
// The lock is taken and deliberately never released: the mutex lives inside the
// record this call deletes, and unlocking a destroyed mutex is worse than
// leaving a dead one locked. Any other thread touching this device after its
// owner declared it dead is already outside what GBM can be asked to survive.
mutex->lock();
GbmDeviceDestroy(*gbm);
}
extern "C" int gbm_device_get_fd(struct gbm_device* gbm)
{
std::mutex* mutex = MutexOf(gbm);
if (mutex == nullptr)
{
errno = EINVAL;
return -1;
}
std::lock_guard<std::mutex> guard(*mutex);
// The device's own dup of the fd it was created with, or -1 when it was created
// without one and no render node could be opened. That is not an error state:
// the self-allocated backend never talks to the node, so a device can be fully
// usable and still have no descriptor to report.
return gbm->Impl.DeviceFd;
}
extern "C" const char* gbm_device_get_backend_name(struct gbm_device* gbm)
{
std::mutex* mutex = MutexOf(gbm);
if (mutex == nullptr)
{
errno = EINVAL;
return nullptr;
}
std::lock_guard<std::mutex> guard(*mutex);
// The name says which memory this device hands out ("mobilegl-dma-heap" or
// "mobilegl-memfd"), because the callers that read it - a compositor logging its
// backend, a peer test recording what it got - are asking exactly that. The
// string lives in the device and outlives every call that can read it.
return gbm->Impl.BackendName.c_str();
}
extern "C" int gbm_device_is_format_supported(struct gbm_device* gbm, uint32_t format, uint32_t flags)
{
std::mutex* mutex = MutexOf(gbm);
if (mutex == nullptr)
{
errno = EINVAL;
return 0;
}
std::lock_guard<std::mutex> guard(*mutex);
// Every buffer this device produces is linear, mappable and shareable, so the
// usage flags do not narrow the answer to any of the usual combinations -
// including GBM_BO_USE_SCANOUT, which a linear dma-buf from the system heap
// satisfies. The one request the backend cannot honour is protected memory.
if ((flags & GBM_BO_USE_PROTECTED) != 0)
{
return 0;
}
return GbmFormatIsSupported(format) ? 1 : 0;
}
extern "C" int gbm_device_get_format_modifier_plane_count(struct gbm_device* gbm, uint32_t format, uint64_t modifier)
{
std::mutex* mutex = MutexOf(gbm);
if (mutex == nullptr)
{
errno = EINVAL;
return 0;
}
std::lock_guard<std::mutex> guard(*mutex);
// Only linear memory exists here, so any other modifier names a buffer this
// device will never produce and the answer is zero planes. INVALID is answered
// as well, because it means "no modifier was declared", which is the same
// layout question asked without an answer.
if (modifier != DrmFormatModLinear && modifier != DrmFormatModInvalid)
{
return 0;
}
GbmPlaneLayout planes[GbmMaxPlanes] = {};
Int planeCount = 0;
SizeT totalBytes = 0;
if (!GbmDescribeFormat(format, 1, 1, planes, planeCount, totalBytes))
{
return 0;
}
return planeCount;
}
// ---------------------------------------------------------------------------
// Buffer objects
// ---------------------------------------------------------------------------
extern "C" struct gbm_bo* gbm_bo_create(struct gbm_device* gbm, uint32_t width, uint32_t height, uint32_t format,
uint32_t flags)
{
std::mutex* mutex = MutexOf(gbm);
if (mutex == nullptr)
{
errno = EINVAL;
return nullptr;
}
std::lock_guard<std::mutex> guard(*mutex);
// No modifier list: the buffer is linear and gbm_bo_get_modifier says so.
return GbmBufferCreate(*gbm, width, height, format, flags, nullptr, 0);
}
extern "C" struct gbm_bo* gbm_bo_create_with_modifiers(struct gbm_device* gbm, uint32_t width, uint32_t height,
uint32_t format, const uint64_t* modifiers,
const unsigned int count)
{
// The modifier-less variant is the one with no flags parameter, so it is the
// flags-0 case of the other, and saying that here keeps one implementation.
return gbm_bo_create_with_modifiers2(gbm, width, height, format, modifiers, count, 0);
}
extern "C" struct gbm_bo* gbm_bo_create_with_modifiers2(struct gbm_device* gbm, uint32_t width, uint32_t height,
uint32_t format, const uint64_t* modifiers,
const unsigned int count, uint32_t flags)
{
std::mutex* mutex = MutexOf(gbm);
if (mutex == nullptr)
{
errno = EINVAL;
return nullptr;
}
std::lock_guard<std::mutex> guard(*mutex);
return GbmBufferCreate(*gbm, width, height, format, flags, modifiers, (Uint32)count);
}
extern "C" struct gbm_bo* gbm_bo_import(struct gbm_device* gbm, uint32_t type, void* buffer, uint32_t flags)
{
std::mutex* mutex = MutexOf(gbm);
if (mutex == nullptr)
{
errno = EINVAL;
return nullptr;
}
std::lock_guard<std::mutex> guard(*mutex);
return GbmBufferImport(*gbm, type, buffer, flags);
}
extern "C" void* gbm_bo_map(struct gbm_bo* bo, uint32_t x, uint32_t y, uint32_t width, uint32_t height,
uint32_t flags, uint32_t* stride, void** map_data)
{
std::mutex* mutex = MutexOf(bo);
if (mutex == nullptr)
{
errno = EINVAL;
return nullptr;
}
// The rectangle's size is not used to size the mapping: the whole buffer is
// mapped once, at its own length, and the rectangle is applied as an offset into
// it. That is what lets two overlapping maps share one address, and it is why a
// buffer's mapping stays valid for a caller that only ever asks for a corner.
(void)width;
(void)height;
(void)flags;
std::lock_guard<std::mutex> guard(*mutex);
Uint32 mapStride = 0;
void* address = GbmBufferMap(*bo, x, y, mapStride);
if (address == nullptr)
{
return nullptr;
}
if (stride != nullptr)
{
*stride = mapStride;
}
if (map_data != nullptr)
{
// The same address the function returns. Callers pass back either one to
// gbm_bo_unmap, and both have to name this mapping.
*map_data = address;
}
return address;
}
extern "C" void gbm_bo_unmap(struct gbm_bo* bo, void* map_data)
{
std::mutex* mutex = MutexOf(bo);
if (mutex == nullptr)
{
return;
}
std::lock_guard<std::mutex> guard(*mutex);
GbmBufferUnmap(*bo, map_data);
}
extern "C" uint32_t gbm_bo_get_width(struct gbm_bo* bo)
{
std::mutex* mutex = MutexOf(bo);
if (mutex == nullptr)
{
errno = EINVAL;
return 0;
}
std::lock_guard<std::mutex> guard(*mutex);
return bo->Impl.Width;
}
extern "C" uint32_t gbm_bo_get_height(struct gbm_bo* bo)
{
std::mutex* mutex = MutexOf(bo);
if (mutex == nullptr)
{
errno = EINVAL;
return 0;
}
std::lock_guard<std::mutex> guard(*mutex);
return bo->Impl.Height;
}
extern "C" uint32_t gbm_bo_get_stride(struct gbm_bo* bo)
{
std::mutex* mutex = MutexOf(bo);
if (mutex == nullptr)
{
errno = EINVAL;
return 0;
}
std::lock_guard<std::mutex> guard(*mutex);
return bo->Impl.Strides[0];
}
extern "C" uint32_t gbm_bo_get_stride_for_plane(struct gbm_bo* bo, int plane)
{
std::mutex* mutex = MutexOf(bo);
if (mutex == nullptr)
{
errno = EINVAL;
return 0;
}
std::lock_guard<std::mutex> guard(*mutex);
// A plane this buffer does not have is answered with zero, which is the only
// value a caller can tell apart from a real stride.
if (plane < 0 || plane >= bo->Impl.PlaneCount)
{
errno = EINVAL;
return 0;
}
return bo->Impl.Strides[plane];
}
extern "C" uint32_t gbm_bo_get_format(struct gbm_bo* bo)
{
std::mutex* mutex = MutexOf(bo);
if (mutex == nullptr)
{
errno = EINVAL;
return 0;
}
std::lock_guard<std::mutex> guard(*mutex);
return bo->Impl.Format;
}
extern "C" uint32_t gbm_bo_get_bpp(struct gbm_bo* bo)
{
std::mutex* mutex = MutexOf(bo);
if (mutex == nullptr)
{
errno = EINVAL;
return 0;
}
std::lock_guard<std::mutex> guard(*mutex);
// Bits per pixel: a 32 bit format answers 32, which is what a caller computing a
// row length in bits or a row length in bytes from the same number expects.
return bo->Impl.BytesPerPixel * 8;
}
extern "C" uint32_t gbm_bo_get_offset(struct gbm_bo* bo, int plane)
{
std::mutex* mutex = MutexOf(bo);
if (mutex == nullptr)
{
errno = EINVAL;
return 0;
}
std::lock_guard<std::mutex> guard(*mutex);
if (plane < 0 || plane >= bo->Impl.PlaneCount)
{
errno = EINVAL;
return 0;
}
return bo->Impl.Offsets[plane];
}
extern "C" struct gbm_device* gbm_bo_get_device(struct gbm_bo* bo)
{
std::mutex* mutex = MutexOf(bo);
if (mutex == nullptr)
{
errno = EINVAL;
return nullptr;
}
return bo->Impl.Owner;
}
extern "C" union gbm_bo_handle gbm_bo_get_handle(struct gbm_bo* bo)
{
union gbm_bo_handle handle;
handle.ptr = nullptr;
std::mutex* mutex = MutexOf(bo);
if (mutex == nullptr)
{
errno = EINVAL;
handle.s32 = -1;
return handle;
}
std::lock_guard<std::mutex> guard(*mutex);
// The kernel-level name of a dma-buf in this process is its file descriptor. A
// GEM handle would be a name that exists only relative to a DRM node, and this
// library deliberately does not require one, so the fd is the only answer here
// that is true for every buffer it hands out. Callers that need a name for a
// device should ask for the fd and pass that.
handle.s32 = bo->Impl.Fds[0];
return handle;
}
extern "C" int gbm_bo_get_fd(struct gbm_bo* bo)
{
std::mutex* mutex = MutexOf(bo);
if (mutex == nullptr)
{
errno = EINVAL;
return -1;
}
std::lock_guard<std::mutex> guard(*mutex);
// A dup, close-on-exec, owned by the caller. Closing it cannot affect the buffer
// or any other caller's copy.
return GbmBufferDupFd(*bo, 0);
}
extern "C" uint64_t gbm_bo_get_modifier(struct gbm_bo* bo)
{
std::mutex* mutex = MutexOf(bo);
if (mutex == nullptr)
{
errno = EINVAL;
return DrmFormatModInvalid;
}
std::lock_guard<std::mutex> guard(*mutex);
return bo->Impl.Modifier;
}
extern "C" int gbm_bo_get_plane_count(struct gbm_bo* bo)
{
std::mutex* mutex = MutexOf(bo);
if (mutex == nullptr)
{
errno = EINVAL;
return 0;
}
std::lock_guard<std::mutex> guard(*mutex);
return bo->Impl.PlaneCount;
}
extern "C" union gbm_bo_handle gbm_bo_get_handle_for_plane(struct gbm_bo* bo, int plane)
{
union gbm_bo_handle handle;
handle.ptr = nullptr;
std::mutex* mutex = MutexOf(bo);
if (mutex == nullptr)
{
errno = EINVAL;
handle.s32 = -1;
return handle;
}
std::lock_guard<std::mutex> guard(*mutex);
if (plane < 0 || plane >= bo->Impl.PlaneCount)
{
errno = EINVAL;
handle.s32 = -1;
return handle;
}
// Same reasoning as gbm_bo_get_handle: the fd is the buffer's kernel name. Every
// plane of a self-allocated buffer lives in the one dma-buf, so all of them
// answer with that descriptor; the plane's position inside it is
// gbm_bo_get_offset.
const Int fd = bo->Impl.Fds[plane] >= 0 ? bo->Impl.Fds[plane] : bo->Impl.Fds[0];
handle.s32 = fd;
return handle;
}
extern "C" int gbm_bo_get_fd_for_plane(struct gbm_bo* bo, int plane)
{
std::mutex* mutex = MutexOf(bo);
if (mutex == nullptr)
{
errno = EINVAL;
return -1;
}
std::lock_guard<std::mutex> guard(*mutex);
return GbmBufferDupFd(*bo, plane);
}
extern "C" int gbm_bo_write(struct gbm_bo* bo, const void* buf, size_t count)
{
std::mutex* mutex = MutexOf(bo);
if (mutex == nullptr || buf == nullptr)
{
errno = EINVAL;
return -1;
}
std::lock_guard<std::mutex> guard(*mutex);
if (count == 0)
{
return 0;
}
if (count > bo->Impl.AllocationSize)
{
// Refused rather than truncated: a caller that writes 4 MiB into a 1 MiB
// buffer and is told "0 bytes written, success" would read back memory it
// never wrote and call the result correct.
errno = EINVAL;
return -1;
}
// The write goes through the same counted mapping the rest of the API uses, so a
// caller that already holds the buffer mapped does not get a second mapping (or
// lose its own) behind its back.
Uint32 stride = 0;
void* address = GbmBufferMap(*bo, 0, 0, stride);
if (address == nullptr)
{
return -1;
}
memcpy(address, buf, count);
GbmBufferUnmap(*bo, address);
return 0;
}
extern "C" void gbm_bo_set_user_data(struct gbm_bo* bo, void* data,
void (*destroy_user_data)(struct gbm_bo*, void*))
{
std::mutex* mutex = MutexOf(bo);
if (mutex == nullptr)
{
return;
}
std::lock_guard<std::mutex> guard(*mutex);
// Assigning over existing data does not call the old callback: the record calls
// it exactly once, when the buffer goes away, which is the one moment a caller
// can still recognise the pointer it registered.
bo->Impl.UserData = data;
bo->Impl.UserDataDestroy = destroy_user_data;
}
extern "C" void* gbm_bo_get_user_data(struct gbm_bo* bo)
{
std::mutex* mutex = MutexOf(bo);
if (mutex == nullptr)
{
errno = EINVAL;
return nullptr;
}
std::lock_guard<std::mutex> guard(*mutex);
return bo->Impl.UserData;
}
extern "C" void gbm_bo_destroy(struct gbm_bo* bo)
{
std::mutex* mutex = MutexOf(bo);
if (mutex == nullptr)
{
return;
}
std::lock_guard<std::mutex> guard(*mutex);
// Drops this caller's reference. A buffer a surface still holds stays alive -
// that is what the surface's own reference is for - so destroying a buffer that
// is currently presented is not a use-after-free waiting to happen.
GbmBufferRelease(*bo->Impl.Owner, *bo);
}
// ---------------------------------------------------------------------------
// Surfaces
// ---------------------------------------------------------------------------
extern "C" struct gbm_surface* gbm_surface_create(struct gbm_device* gbm, uint32_t width, uint32_t height,
uint32_t format, uint32_t flags)
{
std::mutex* mutex = MutexOf(gbm);
if (mutex == nullptr)
{
errno = EINVAL;
return nullptr;
}
std::lock_guard<std::mutex> guard(*mutex);
return GbmSurfaceCreate(*gbm, width, height, format, flags, nullptr, 0);
}
extern "C" struct gbm_surface* gbm_surface_create_with_modifiers(struct gbm_device* gbm, uint32_t width,
uint32_t height, uint32_t format,
const uint64_t* modifiers,
const unsigned int count)
{
// As with the buffer pair: the modifier-less form is the flags-0 case.
return gbm_surface_create_with_modifiers2(gbm, width, height, format, modifiers, count, 0);
}
extern "C" struct gbm_surface* gbm_surface_create_with_modifiers2(struct gbm_device* gbm, uint32_t width,
uint32_t height, uint32_t format,
const uint64_t* modifiers,
const unsigned int count, uint32_t flags)
{
std::mutex* mutex = MutexOf(gbm);
if (mutex == nullptr)
{
errno = EINVAL;
return nullptr;
}
std::lock_guard<std::mutex> guard(*mutex);
return GbmSurfaceCreate(*gbm, width, height, format, flags, modifiers, (Uint32)count);
}
extern "C" struct gbm_bo* gbm_surface_lock_front_buffer(struct gbm_surface* surface)
{
std::mutex* mutex = MutexOf(surface);
if (mutex == nullptr)
{
errno = EINVAL;
return nullptr;
}
std::lock_guard<std::mutex> guard(*mutex);
// Null with errno = EBUSY when the compositor still holds every buffer: that is a
// state the caller has to handle, and pretending otherwise by handing out a
// buffer that is still being scanned out would be a torn frame rather than an
// error.
return GbmSurfaceLockFront(*surface);
}
extern "C" void gbm_surface_release_buffer(struct gbm_surface* surface, struct gbm_bo* bo)
{
std::mutex* mutex = MutexOf(surface);
if (mutex == nullptr || bo == nullptr)
{
return;
}
std::lock_guard<std::mutex> guard(*mutex);
GbmSurfaceReleaseBuffer(*surface, *bo);
}
extern "C" int gbm_surface_has_free_buffers(struct gbm_surface* surface)
{
std::mutex* mutex = MutexOf(surface);
if (mutex == nullptr)
{
errno = EINVAL;
return 0;
}
std::lock_guard<std::mutex> guard(*mutex);
// Truthful by construction: the swapchain exists from the moment the surface
// does, so this answers about buffers that were really allocated rather than
// about how many could still be.
return GbmSurfaceHasFreeBuffers(*surface) ? 1 : 0;
}
extern "C" void gbm_surface_destroy(struct gbm_surface* surface)
{
std::mutex* mutex = MutexOf(surface);
if (mutex == nullptr)
{
return;
}
std::lock_guard<std::mutex> guard(*mutex);
GbmSurfaceDestroy(*surface);
}
// ---------------------------------------------------------------------------
// Format names
// ---------------------------------------------------------------------------
extern "C" char* gbm_format_get_name(uint32_t gbm_format, struct gbm_format_name_desc* desc)
{
if (desc == nullptr)
{
errno = EINVAL;
return nullptr;
}
// The name of a fourcc is its four characters, most significant byte last, and
// that is all there is to it: a caller compares these strings against "AR24" and
// friends, and the big-endian bit is part of the value rather than something to
// spell out here.
desc->name[0] = (char)(gbm_format & 0xffu);
desc->name[1] = (char)((gbm_format >> 8) & 0xffu);
desc->name[2] = (char)((gbm_format >> 16) & 0xffu);
desc->name[3] = (char)((gbm_format >> 24) & 0xffu);
desc->name[4] = '\0';
return desc->name;
}
// End of Source File Header
File diff suppressed because it is too large Load Diff
+835
View File
@@ -0,0 +1,835 @@
// MobileGL - MobileGL/MG_Gbm/GbmHostChannel.cpp
// SPDX-License-Identifier: LGPL-3.0-only
//
// The host-frame backend: the socket the container receives the phone's frames on.
//
// The container half of MobileGL runs a Wayland compositor, and the frames that
// compositor renders into have to be the frames the phone already owns - the phone
// allocates them, its GPU draws into them, and its display scans them out. A buffer
// allocated from the container's own dma-heap would be a copy that has to travel back
// to the phone before anything can be shown, so when the display host is reachable this
// backend hands the compositor the phone's own buffers instead, and the fd the
// compositor passes on is the fd of a frame the display path already knows.
//
// What that costs is the one thing GBM normally promises: the geometry. A frame's
// width, height, stride and format are the display's and not the caller's, so a
// gbm_bo_create that takes an offered frame answers with the offer's geometry, and the
// caller reads it back with gbm_bo_get_width and its neighbours. That is this backend's
// documented behaviour rather than a surprise: the host decides what a frame is.
//
// Three rules keep this backend from ever being worse than not having it.
//
// * Nothing on the allocation path blocks. The socket is non-blocking and connect()
// to a pathname socket either succeeds or fails immediately, so a call that cannot
// be served from the host falls through to a local allocation inside the same call
// instead of waiting for a phone that may never answer. The one wait in this file is
// in device creation, after a display host has already accepted the connection, and
// it exists because of a measured race: the compositor builds its swapchain within
// microseconds of creating the device, while the offer for the first frame needs the
// round trip of the connection plus whatever the phone does before it sends. Without
// that wait the swapchain - the buffers that are shown for the life of the process -
// is allocated locally and the host's frames arrive for nobody to take.
// * A channel that dies is closed and marked down, and the next frame is allocated
// locally again. This library is loaded by a compositor that has to keep painting,
// so losing the display host may cost the frames their path to the screen but it
// may not cost the session.
// * A frame is released exactly once, when the record holding it is destroyed, and
// only into the connection that offered it. Releasing on gbm_bo_destroy would be a
// lie - the surface may still be scanning that frame out - and releasing an old
// frame into a new connection would free a slot belonging to another session.
//
// The device mutex is the only lock in here. Both callers of this file - the allocation
// path and the buffer record's destructor - already run under it, so there is no second
// lock to order against and no state of this file's own that another thread can see.
#include "GbmInternal.h"
#include <fcntl.h>
#include <poll.h>
#include <sys/socket.h>
#include <sys/uio.h>
#include <sys/un.h>
#include <unistd.h>
#include <cerrno>
#include <chrono>
namespace MobileGL::MG_Gbm
{
namespace
{
// One frame per message, and a message is the offer followed by the handle the
// offer describes. 4 KiB is far more than an AHardwareBuffer handle needs (a
// handle is a version, two counts and their two arrays) while still being small
// enough that a message which does not fit is a peer speaking something else -
// which is worth refusing rather than growing a buffer for.
constexpr SizeT GbmHostMessageMax = 4096;
// The descriptors one handle may carry. An AHardwareBuffer handle carries one
// (the dma-buf) in every layout this library has seen and the protocol reads only
// the first, so this sizes the control buffer rather than claiming anything about
// real handles.
constexpr Int GbmHostMaxFds = 8;
// How many messages one gbm_bo_create may look at before it gives up and
// allocates locally. An unusable message is skipped rather than fatal, so this
// bounds the work a peer that sends nothing but unusable messages can cause
// inside a single allocation.
constexpr Int GbmHostTakeAttempts = 16;
// The floor between two connection attempts. A container with no display host is
// the normal case, so a retry may not turn every allocation into a connect plus a
// log line; one attempt per second is often enough that a phone which comes up is
// picked up within a frame or two of the compositor's next allocation.
constexpr std::chrono::milliseconds GbmHostRetryInterval{1000};
// How long device creation waits for the display host's first frame once the
// connection is up. A frame the phone offers immediately needs one round trip on
// a unix socket, so this is orders of magnitude more than that and it is only
// ever spent by a device that has a host which then says nothing; a compile or a
// test run without a display host never reaches it, because the connect fails
// first.
constexpr Int GbmHostFirstOfferWaitMs = 250;
// Frame releases the socket would not take. A release is twelve bytes, so a full
// socket buffer is hundreds of frames' worth of them and this queue is only
// reached once the phone has stopped reading; the cap is what stops a peer that
// never reads from growing it without bound.
constexpr SizeT GbmHostMaxPendingReleases = 256;
// sun_path is where a pathname socket's name lives, and a name that does not fit
// is one the kernel cannot be told about at all.
constexpr SizeT GbmHostPathMax = sizeof(((struct sockaddr_un*)nullptr)->sun_path);
// close() may overwrite errno, and every caller here is in the middle of
// reporting a failure that errno describes. Saving it around the close keeps the
// reported failure the one that happened.
void GbmHostCloseQuietly(Int fd) noexcept
{
if (fd < 0)
{
return;
}
const Int savedErrno = errno;
close(fd);
errno = savedErrno;
}
} // namespace
// One connection to the display host, for the life of one device.
class GbmHostChannel
{
public:
explicit GbmHostChannel(const String& path) noexcept : Path(path) {}
~GbmHostChannel() noexcept;
GbmHostChannel(const GbmHostChannel&) = delete;
GbmHostChannel& operator=(const GbmHostChannel&) = delete;
// Connects when there is no connection and the retry interval has passed. A
// failure is never the caller's problem: the channel stays closed and the
// allocation that asked for a frame falls back to local memory.
void EnsureOpen(::gbm_device& device) noexcept;
// Waits, once, for the connection's first frame to be readable. Called from
// device creation and nowhere else: see the banner for why that one wait exists.
void AwaitFirstOffer(::gbm_device& device) noexcept;
// The next frame the host offered, or false when none is waiting.
Bool TakeFrame(::gbm_device& device, GbmHostFrame& frameOut) noexcept;
// Queues the release for one frame and tries to send what is queued.
void ReleaseFrame(::gbm_device& device, Uint32 seq, Uint64 generation) noexcept;
private:
// Turns one message into a frame. Everything it refuses is reported with the
// reason, because a peer this library cannot understand is the one thing that
// would otherwise be invisible from the outside.
Bool ParseOffer(const Uint8* payload, SizeT length, const Int* fds, Int fdCount,
GbmHostFrame& frameOut) noexcept;
// Sends what is queued. False means the connection can no longer be trusted to
// carry a twelve byte message, with errno describing what happened.
Bool FlushReleases() noexcept;
// Closes the socket and drops whatever was queued for it.
void CloseSocket() noexcept;
// Closes the socket and tells the device what that means for its backend name.
void MarkDown(::gbm_device& device, const char* what, Int error) noexcept;
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;
std::chrono::steady_clock::time_point NextRetry{};
// The errno of the last failed attempt, so that a failure which repeats once a
// second is not logged once a second.
Int LastFailureErrno = 0;
std::vector<GbmFrameRelease> PendingReleases;
Bool ReleaseOverflowLogged = false;
};
// ---- the offered-frame record ------------------------------------------
GbmHostFrame::~GbmHostFrame()
{
// The record owns the dup it was built on, which is why it is move-only: a copy
// would close the same descriptor twice.
if (Fd >= 0)
{
close(Fd);
Fd = -1;
}
}
GbmHostFrame::GbmHostFrame(GbmHostFrame&& other) noexcept
{
*this = static_cast<GbmHostFrame&&>(other);
}
GbmHostFrame& GbmHostFrame::operator=(GbmHostFrame&& other) noexcept
{
if (this == &other)
{
return *this;
}
if (Fd >= 0)
{
close(Fd);
}
Seq = other.Seq;
Index = other.Index;
Width = other.Width;
Height = other.Height;
StrideBytes = other.StrideBytes;
Format = other.Format;
BytesPerPixel = other.BytesPerPixel;
Usage = other.Usage;
Generation = other.Generation;
Fd = other.Fd;
Size = other.Size;
// The source must not close what this record now owns.
other.Fd = -1;
return *this;
}
// ---- the connection ----------------------------------------------------
GbmHostChannel::~GbmHostChannel() noexcept
{
// One last try for whatever is queued - the phone may still be reading - and
// then the socket goes away with the process.
if (SocketFd >= 0 && !PendingReleases.empty())
{
FlushReleases();
}
if (!PendingReleases.empty())
{
MGLOG_W("gbm: %zu frame release(s) could not be sent to the display host at %s; the phone reclaims "
"those slots when the session ends",
PendingReleases.size(), Path.c_str());
}
CloseSocket();
}
void GbmHostChannel::EnsureOpen(::gbm_device& device) noexcept
{
if (SocketFd >= 0)
{
return;
}
const std::chrono::steady_clock::time_point now = std::chrono::steady_clock::now();
if (now < NextRetry)
{
return;
}
NextRetry = now + GbmHostRetryInterval;
// SOCK_SEQPACKET because a frame and its descriptors are one message and the
// reader may not reassemble either half; SOCK_NONBLOCK because the caller is a
// compositor's frame loop and may not be parked on a phone; SOCK_CLOEXEC because
// every process this compositor starts would otherwise inherit a socket it can
// read frames from.
const Int fd = socket(AF_UNIX, SOCK_SEQPACKET | SOCK_NONBLOCK | SOCK_CLOEXEC, 0);
if (fd < 0)
{
MGLOG_E_ONCE("gbm: cannot create the socket to the display host (%d: %s); every frame is allocated "
"locally",
errno, strerror(errno));
return;
}
if (Path.empty() || Path.size() >= GbmHostPathMax)
{
MGLOG_E_ONCE("gbm: the display host socket path \"%s\" does not fit in sun_path (%zu bytes); every "
"frame is allocated locally",
Path.c_str(), GbmHostPathMax);
GbmHostCloseQuietly(fd);
return;
}
struct sockaddr_un address = {};
address.sun_family = AF_UNIX;
// The terminator travels with the name: sun_path is a C string for a pathname
// socket, and a name without one is a name the kernel reads past the end of.
memcpy(address.sun_path, Path.c_str(), Path.size() + 1);
if (connect(fd, reinterpret_cast<struct sockaddr*>(&address), sizeof(address)) != 0)
{
const Int connectErrno = errno;
GbmHostCloseQuietly(fd);
// A failure that repeats once a second is not news: a container with no
// display host fails here on every retry, and a line per second saying so
// would bury the rest of the log. A failure that changed is news, because it
// says the path or the peer changed.
if (connectErrno != LastFailureErrno)
{
LastFailureErrno = connectErrno;
if (connectErrno == EPROTOTYPE)
{
MGLOG_E("gbm: %s is a socket of a different type (%d: %s). The frame protocol is "
"SOCK_SEQPACKET - one message per frame, carrying that frame's descriptors - "
"because a reader cannot tell from a byte stream which frame a descriptor "
"belongs to; frames are allocated locally instead",
Path.c_str(), connectErrno, strerror(connectErrno));
}
else
{
MGLOG_I("gbm: no display host at %s (%d: %s); every frame is allocated locally until one "
"answers",
Path.c_str(), connectErrno, strerror(connectErrno));
}
}
return;
}
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++;
LastFailureErrno = 0;
device.Impl.HostAvailable = true;
device.Impl.BackendName = "mobilegl-host-frame";
MGLOG_I("gbm: connected to the display host at %s (one SOCK_SEQPACKET message per frame, up to %zu "
"bytes); frames offered over it become gbm_bos whose geometry is the offer's",
Path.c_str(), GbmHostMessageMax);
}
void GbmHostChannel::AwaitFirstOffer(::gbm_device& device) noexcept
{
if (SocketFd < 0)
{
return;
}
const std::chrono::steady_clock::time_point deadline =
std::chrono::steady_clock::now() + std::chrono::milliseconds(GbmHostFirstOfferWaitMs);
for (;;)
{
const std::chrono::milliseconds left =
std::chrono::duration_cast<std::chrono::milliseconds>(deadline - std::chrono::steady_clock::now());
if (left.count() <= 0)
{
break;
}
// poll() and not recvmsg(): the frame has to stay in the socket for the
// allocation that is about to ask for it, and a peek at a message carrying
// SCM_RIGHTS is a question with no safe answer.
struct pollfd waiting = {};
waiting.fd = SocketFd;
waiting.events = POLLIN;
const Int ready = poll(&waiting, 1, (Int)left.count());
if (ready > 0)
{
MGLOG_I("gbm: the display host at %s has a frame waiting; the buffers the compositor is about "
"to allocate come from it",
Path.c_str());
return;
}
if (ready == 0)
{
break;
}
if (errno != EINTR)
{
MarkDown(device, "poll", errno);
return;
}
}
MGLOG_W("gbm: the display host at %s accepted the connection but offered no frame within %d ms; the "
"buffers allocated before its first frame are local ones",
Path.c_str(), GbmHostFirstOfferWaitMs);
}
Bool GbmHostChannel::TakeFrame(::gbm_device& device, GbmHostFrame& frameOut) noexcept
{
EnsureOpen(device);
if (SocketFd < 0)
{
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.
if (!PendingReleases.empty() && !FlushReleases())
{
MarkDown(device, "sendmsg", errno);
return false;
}
Uint8 payload[GbmHostMessageMax];
for (Int attempt = 0; attempt < GbmHostTakeAttempts; ++attempt)
{
Int receivedFds[GbmHostMaxFds];
for (Int i = 0; i < GbmHostMaxFds; ++i)
{
receivedFds[i] = -1;
}
struct iovec payloadVector = {};
payloadVector.iov_base = payload;
payloadVector.iov_len = sizeof(payload);
Uint8 control[CMSG_SPACE(sizeof(Int) * GbmHostMaxFds)] = {};
struct msghdr message = {};
message.msg_iov = &payloadVector;
message.msg_iovlen = 1;
message.msg_control = control;
message.msg_controllen = sizeof(control);
// MSG_DONTWAIT for the promise at the top of this file, and MSG_CMSG_CLOEXEC
// so a descriptor the phone sent does not survive into a child of this
// compositor, which would then hold a frame nothing will ever release.
const ssize_t received = recvmsg(SocketFd, &message, MSG_DONTWAIT | MSG_CMSG_CLOEXEC);
if (received < 0)
{
if (errno == EAGAIN || errno == EWOULDBLOCK)
{
// Nothing offered yet, which is what an idle display looks like. The
// caller allocates locally and asks again on its next frame.
return false;
}
if (errno == EINTR)
{
continue;
}
MarkDown(device, "recvmsg", errno);
return false;
}
// The descriptors come out of the control data before anything is decided
// about the message, because they belong to this process from the moment it
// was received: a path that returns without closing them leaks a descriptor
// per unusable message.
Int fdCount = 0;
for (struct cmsghdr* header = CMSG_FIRSTHDR(&message); header != nullptr;
header = CMSG_NXTHDR(&message, header))
{
if (header->cmsg_level != SOL_SOCKET || header->cmsg_type != SCM_RIGHTS)
{
continue;
}
const SizeT bytes = (SizeT)header->cmsg_len - CMSG_LEN(0);
const Int count = (Int)(bytes / sizeof(Int));
const Int* descriptors = reinterpret_cast<const Int*>(CMSG_DATA(header));
for (Int i = 0; i < count; ++i)
{
if (fdCount < GbmHostMaxFds)
{
receivedFds[fdCount++] = descriptors[i];
}
else
{
// More descriptors than a frame can carry: they are this
// process's now, so they are closed here rather than leaked.
GbmHostCloseQuietly(descriptors[i]);
}
}
}
if ((message.msg_flags & MSG_CTRUNC) != 0)
{
MGLOG_W_ONCE("gbm: an offered frame's control data did not fit in %zu bytes; the frame is "
"skipped because its descriptor list is incomplete",
sizeof(control));
for (Int i = 0; i < fdCount; ++i)
{
GbmHostCloseQuietly(receivedFds[i]);
}
continue;
}
if (received == 0)
{
// Zero bytes on a connected socket is the end of it, whether the phone
// closed cleanly or the kernel gave up on it. Either way the frames have
// to come from somewhere else from here on.
for (Int i = 0; i < fdCount; ++i)
{
GbmHostCloseQuietly(receivedFds[i]);
}
MarkDown(device, "the display host closed the connection", 0);
return false;
}
if ((message.msg_flags & MSG_TRUNC) != 0)
{
// Longer than a frame message can be, so it is not one - and on a
// message-oriented socket the rest is already gone while the next message
// is still a whole message, which is why this skips one message instead
// of ending the channel.
MGLOG_W_ONCE("gbm: the display host sent a message longer than %zu bytes; it is skipped",
GbmHostMessageMax);
for (Int i = 0; i < fdCount; ++i)
{
GbmHostCloseQuietly(receivedFds[i]);
}
continue;
}
const Bool parsed = ParseOffer(payload, (SizeT)received, receivedFds, fdCount, frameOut);
// Whatever the frame did not keep is closed here: the copy of the dma-buf
// descriptor the phone sent (the frame owns its own dup) and the rest of the
// handle, which is a layout this library does not interpret.
for (Int i = 0; i < fdCount; ++i)
{
GbmHostCloseQuietly(receivedFds[i]);
}
if (parsed)
{
return true;
}
}
return false;
}
Bool GbmHostChannel::ParseOffer(const Uint8* payload, SizeT length, const Int* fds, Int fdCount,
GbmHostFrame& frameOut) noexcept
{
constexpr SizeT HeaderBytes = sizeof(GbmFrameOffer) + sizeof(AHBNativeHandleHeader);
if (length < HeaderBytes)
{
MGLOG_W_ONCE("gbm: the display host sent a %zu byte message where a frame message is at least %zu "
"bytes (the offer followed by the handle header); it is skipped",
length, HeaderBytes);
return false;
}
GbmFrameOffer offer = {};
memcpy(&offer, payload, sizeof(offer));
if (offer.Magic != GbmFrameOfferMagic)
{
MGLOG_W_ONCE("gbm: a message from the display host begins with 0x%08x rather than 'MGGF'; it is "
"skipped",
offer.Magic);
return false;
}
if (offer.Version != GbmHostProtocolVersion)
{
// Refused rather than read as if the versions agreed: the version is what
// says how the rest of the message is laid out, and a frame read with the
// wrong layout is memory the compositor would render into.
MGLOG_E_ONCE("gbm: the display host offers frames in protocol version %u where this library speaks "
"version %u; its frames are refused until the two agree",
offer.Version, (Uint32)GbmHostProtocolVersion);
return false;
}
AHBNativeHandleHeader handle = {};
memcpy(&handle, payload + sizeof(offer), sizeof(handle));
if (handle.NumFds < 1 || handle.NumInts < 0)
{
MGLOG_W_ONCE("gbm: an offered frame's handle carries %d descriptor(s) and %d integer(s), where the "
"dma-buf is the first descriptor and there has to be one; the frame is skipped",
handle.NumFds, handle.NumInts);
return false;
}
// The handle describes itself with its two counts, so the message has to be
// exactly as long as those counts make it. Any other length means the two ends
// disagree about the layout, and a frame built from a message whose layout was
// guessed is a buffer of unknown memory.
const SizeT expected = HeaderBytes + ((SizeT)handle.NumFds + (SizeT)handle.NumInts) * sizeof(Int32);
if (length != expected)
{
MGLOG_W_ONCE("gbm: an offered frame's message is %zu bytes where its handle (%d descriptors, %d "
"integers) makes it %zu; the frame is skipped",
length, handle.NumFds, handle.NumInts, expected);
return false;
}
if (fdCount < handle.NumFds)
{
MGLOG_W_ONCE("gbm: an offered frame's handle names %d descriptor(s) and %d arrived with the "
"message; the frame is skipped",
handle.NumFds, fdCount);
return false;
}
if (offer.Width == 0 || offer.Height == 0 || offer.StrideBytes == 0)
{
MGLOG_W_ONCE("gbm: an offered frame is %ux%u with a stride of %u bytes; a buffer with no size is "
"not one this library can hand out",
offer.Width, offer.Height, offer.StrideBytes);
return false;
}
// The frame is built on a dup of the first descriptor rather than on the
// descriptor itself: the copy that arrived belongs to the message, and the frame
// outlives it. Close-on-exec, like every other descriptor this library hands out.
const Int frameFd = fcntl(fds[0], F_DUPFD_CLOEXEC, 0);
if (frameFd < 0)
{
MGLOG_E_ONCE("gbm: cannot dup the descriptor of an offered frame (%d: %s)", errno, strerror(errno));
return false;
}
// How long the frame really is, asked of the descriptor instead of computed from
// the geometry: a gralloc dma-buf is usually larger than stride x height, and a
// mapping has to cover what exists rather than what the arithmetic expects.
SizeT size = 0;
const off_t end = lseek(frameFd, 0, SEEK_END);
if (end > 0)
{
size = (SizeT)end;
}
const SizeT described = (SizeT)offer.StrideBytes * (SizeT)offer.Height;
if (size == 0)
{
// A descriptor that does not answer for its own length - an exporter that
// does not implement llseek - leaves the offer's arithmetic as the only
// length there is.
size = described;
}
if (size < described)
{
MGLOG_W_ONCE("gbm: an offered frame's descriptor holds %zu bytes where %u rows of %u bytes need %zu; "
"the frame is skipped rather than mapped over memory that is not there",
size, offer.Height, offer.StrideBytes, described);
GbmHostCloseQuietly(frameFd);
return false;
}
frameOut.Seq = offer.Seq;
frameOut.Index = offer.Index;
frameOut.Width = offer.Width;
frameOut.Height = offer.Height;
frameOut.StrideBytes = offer.StrideBytes;
frameOut.Format = offer.Format;
frameOut.Usage = ((Uint64)offer.UsageHi << 32) | (Uint64)offer.UsageLo;
frameOut.Generation = Generation;
frameOut.Fd = frameFd;
frameOut.Size = size;
frameOut.BytesPerPixel = GbmFormatBytesPerPixel(offer.Format);
if (frameOut.BytesPerPixel == 0)
{
// A format this library has no table entry for is still a frame the phone
// drew. The offer's stride is then the only description of a pixel that
// exists: a row of Width pixels is StrideBytes long.
frameOut.BytesPerPixel = offer.StrideBytes / offer.Width;
}
MGLOG_I("gbm: frame seq=%u index=%u %ux%u stride=%u format=0x%08x (%u bytes per pixel, %zu bytes "
"measured) taken from the display host",
offer.Seq, offer.Index, offer.Width, offer.Height, offer.StrideBytes, offer.Format,
frameOut.BytesPerPixel, size);
return true;
}
void GbmHostChannel::ReleaseFrame(::gbm_device& device, Uint32 seq, Uint64 generation) noexcept
{
if (SocketFd < 0)
{
// A release only means anything on the connection that offered the frame,
// and there is none.
return;
}
if (generation != Generation)
{
// The frame was offered by a connection that has since died and been
// replaced. Sending this into the replacement would name a frame of another
// session, and the phone would recycle a slot this buffer was not made of.
MGLOG_W_ONCE("gbm: a frame offered by a display host connection that has since died is not "
"released into its replacement");
return;
}
if (PendingReleases.size() >= GbmHostMaxPendingReleases)
{
if (!ReleaseOverflowLogged)
{
ReleaseOverflowLogged = true;
MGLOG_W("gbm: %zu frame releases to the display host at %s are already waiting for room in the "
"socket; this one is dropped rather than queued without bound, and the phone reclaims "
"the slot when the session ends",
PendingReleases.size(), Path.c_str());
}
return;
}
GbmFrameRelease release = {};
release.Magic = GbmFrameReleaseMagic;
release.Version = GbmHostProtocolVersion;
release.Seq = seq;
PendingReleases.push_back(release);
if (!FlushReleases())
{
MarkDown(device, "sendmsg", errno);
}
}
Bool GbmHostChannel::FlushReleases() noexcept
{
while (!PendingReleases.empty())
{
struct iovec releaseVector = {};
releaseVector.iov_base = &PendingReleases.front();
releaseVector.iov_len = sizeof(GbmFrameRelease);
struct msghdr message = {};
message.msg_iov = &releaseVector;
message.msg_iovlen = 1;
// MSG_DONTWAIT for the same reason every other call here is non-blocking, and
// MSG_NOSIGNAL because a compositor killed by SIGPIPE when the phone goes
// away is a desktop that disappears with it.
const ssize_t sent = sendmsg(SocketFd, &message, MSG_DONTWAIT | MSG_NOSIGNAL);
if (sent == (ssize_t)sizeof(GbmFrameRelease))
{
PendingReleases.erase(PendingReleases.begin());
continue;
}
if (sent < 0 && errno == EINTR)
{
continue;
}
if (sent < 0 && (errno == EAGAIN || errno == EWOULDBLOCK))
{
// A full socket is a phone that has stopped reading rather than a dead
// one: the release stays queued and goes out with a later frame.
return true;
}
// A short send, a reset and a broken pipe all say the same thing: this
// connection can no longer be trusted to have carried a twelve byte message,
// and acting on a maybe is worse than handing the slot back when the session
// ends. errno describes which of them it was.
return false;
}
return true;
}
void GbmHostChannel::CloseSocket() noexcept
{
if (SocketFd >= 0)
{
GbmHostCloseQuietly(SocketFd);
SocketFd = -1;
}
PendingReleases.clear();
}
void GbmHostChannel::MarkDown(::gbm_device& device, const char* what, Int error) noexcept
{
if (!PendingReleases.empty())
{
MGLOG_W("gbm: %zu frame release(s) were still queued for the display host and cannot be sent over a "
"connection that is gone; the phone reclaims those slots when the session ends",
PendingReleases.size());
}
CloseSocket();
if (error != 0)
{
MGLOG_W("gbm: the display host connection at %s is down: %s failed (%d: %s); frames are allocated "
"locally from here on, and a new connection is attempted on a later allocation",
Path.c_str(), what, error, strerror(error));
}
else
{
MGLOG_W("gbm: the display host connection at %s is down: %s; frames are allocated locally from here "
"on, and a new connection is attempted on a later allocation",
Path.c_str(), what);
}
device.Impl.HostAvailable = false;
device.Impl.BackendName = device.Impl.SelfAllocatedBackendName;
}
// ---- the device-facing entry points ------------------------------------
void GbmHostChannelCreate(::gbm_device& device) noexcept
{
const char* configured = getenv("MOBILEGL_GBM_SOCKET");
const String path =
(configured != nullptr && configured[0] != '\0') ? String(configured) : String("/run/mobilegl-gbm.sock");
device.Impl.SocketPath = path;
try
{
GbmHostChannel* channel = new GbmHostChannel(path);
device.Impl.Host = channel;
// The one attempt made at creation. It is allowed to fail: a machine that is
// not the container half of a split run has no display host, and that is a
// device which allocates locally rather than a device that could not exist.
channel->EnsureOpen(device);
// A connection that came up is waited on once, and only here, so that the
// compositor's swapchain is built out of the host's frames rather than out of
// local ones it will keep for the life of the process.
channel->AwaitFirstOffer(device);
}
catch (...)
{
device.Impl.Host = nullptr;
device.Impl.HostAvailable = false;
MGLOG_W("gbm: the display host channel could not be created; every frame is allocated locally");
}
}
void GbmHostChannelDestroy(::gbm_device& device) noexcept
{
GbmHostChannel* channel = device.Impl.Host;
if (channel == nullptr)
{
return;
}
device.Impl.Host = nullptr;
device.Impl.HostAvailable = false;
delete channel;
}
Bool GbmHostChannelTakeFrame(::gbm_device& device, GbmHostFrame& frameOut) noexcept
{
GbmHostChannel* channel = device.Impl.Host;
if (channel == nullptr)
{
return false;
}
return channel->TakeFrame(device, frameOut);
}
void GbmHostChannelReleaseFrame(::gbm_device& device, Uint32 seq, Uint64 generation) noexcept
{
GbmHostChannel* channel = device.Impl.Host;
if (channel == nullptr)
{
return;
}
channel->ReleaseFrame(device, seq, generation);
}
} // namespace MobileGL::MG_Gbm
// End of Source File Header
+476
View File
@@ -0,0 +1,476 @@
// MobileGL - MobileGL/MG_Gbm/GbmInternal.h
// SPDX-License-Identifier: LGPL-3.0-only
//
// This header carries the internal model shared by the GBM front-end files: the
// device, buffer-object and surface records, the two allocation backends, and the
// wire protocol used to talk to a phone that owns the real display hardware.
//
// The reason a GBM implementation has to exist in this tree at all is that the
// container half of MobileGL runs a Wayland compositor (kwin). That compositor
// needs libgbm to allocate the buffers it renders into, and the fd of such a
// buffer is handed to the Anland display producer, which ships the frame to the
// phone. If Mesa's libgbm is loaded, the compositor renders into Mesa buffers and
// the phone ends up receiving a copy through a path that was never designed to
// carry them. When this library is loaded instead, the buffers are either frames
// the phone itself offered to us, or buffers allocated from the kernel's dma-heap
// so that they are dma-bufs the display host can consume directly.
//
// The ownership rules below are the whole contract, because every one of them is
// observable from outside this library:
//
// * A buffer record owns its descriptors. gbm_bo_get_fd and
// gbm_bo_get_fd_for_plane hand out a dup, so a caller that closes what it was
// given cannot invalidate the buffer, and the matching close happens exactly
// once, in ~GbmBufferObject.
// * A mapping is one mmap of the buffer's fd, counted rather than duplicated, so
// two overlapping gbm_bo_map calls share one address and the last matching
// gbm_bo_unmap releases it.
// * A surface owns one reference per swapchain buffer, and every
// gbm_surface_lock_front_buffer hands the caller a reference of its own. That
// is what makes gbm_bo_destroy on a locked buffer harmless: it drops the
// caller's reference and leaves the surface's bookkeeping intact.
// * One mutex per device. GBM calls arrive from the compositor's render thread
// and from its main thread, and the state they touch (the buffer table, the
// swapchains, the backends) is small enough that one lock is cheaper than
// several - and, more importantly, one lock cannot be taken in the wrong order.
//
// The helpers declared at the bottom of this file are the entire internal interface
// between GbmDevice.cpp (the records and the self-allocated backend) and GbmApi.cpp
// (the extern "C" surface). Every one of them assumes the device mutex is already
// held: the lock is taken once, in the API layer, so that a compositor call can
// never interleave with another half way through a swapchain update.
#pragma once
#include <Includes.h>
#include <gbm.h>
#include <atomic>
#include <cstdint>
#include <cstring>
#include <mutex>
#include <string>
#include <unordered_map>
#include <vector>
namespace MobileGL::MG_Gbm
{
// DRM_FORMAT_MOD_LINEAR and DRM_FORMAT_MOD_INVALID. drm_fourcc.h is not part of
// libgbm's interface, and these two values are frozen kernel UAPI, so they are
// spelled out here rather than made a build dependency on libdrm's headers.
static constexpr Uint64 DrmFormatModLinear = 0ULL;
static constexpr Uint64 DrmFormatModInvalid = 0x00ffffffffffffffULL;
// Every buffer this library hands out is described by one of these. HostFrame
// buffers are owned by the phone and only borrowed by us, so they must be
// released back over the channel instead of being freed locally.
enum class GbmBackend
{
None = 0,
HostFrame,
DmaHeap,
MemFd,
};
// The phone offers frames with this packed struct immediately followed by an
// AHardwareBuffer native handle in the payload of one message, with the handle's
// descriptors in the SCM_RIGHTS control data of that same message. The layout is
// fixed by the phone side, so the packing attribute is load bearing and the field
// order may not be rearranged.
//
// The transport below the two structs is SOCK_SEQPACKET, and that is part of the
// protocol rather than an implementation detail: a frame and its descriptors only
// mean anything together, and the message boundary is what lets the reader take
// the two as one thing. A stream socket would let a reader receive half an offer,
// or a descriptor whose position in the byte stream it had to reconstruct, and the
// failure mode of getting that arithmetic wrong is a frame silently made of
// another frame's memory.
//
// Format is a DRM fourcc and not an AHardwareBuffer format, because it is what
// gbm_bo_get_format has to answer with and a compositor compares it against
// DRM_FORMAT_* values. StrideBytes is the byte distance between two rows of plane
// 0, which is the same single-stride description GBM_BO_IMPORT_FD carries - and
// the reason a frame read from this struct is reported as linear.
struct GbmFrameOffer
{
uint32_t Magic; // 'M','G','G','F' little endian on both ends of the wire
uint32_t Version;
uint32_t Seq;
uint32_t Index;
uint32_t Width;
uint32_t Height;
uint32_t StrideBytes;
uint32_t Format;
uint32_t UsageLo;
uint32_t UsageHi;
} __attribute__((packed));
// The container replies with this once it no longer reads the frame, which is
// what lets the phone recycle the slot. Without it the display host would run
// out of buffers after a handful of frames.
struct GbmFrameRelease
{
uint32_t Magic; // 'M','G','G','R'
uint32_t Version;
uint32_t Seq;
} __attribute__((packed));
static constexpr uint32_t GbmFrameOfferMagic = 0x4647474Du; // "MGGF"
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
// rather than using the platform's native_handle_t.
struct AHBNativeHandleHeader
{
int32_t Version;
int32_t NumFds;
int32_t NumInts;
} __attribute__((packed));
static constexpr uint32_t GbmMaxPlanes = 4;
// How one plane of a buffer is laid out inside the single allocation that backs
// it. Multi-plane formats keep every plane in one dma-buf and describe the
// separation with Offsets, which is the layout a modifier of
// DRM_FORMAT_MOD_LINEAR can express and the only one this library produces.
struct GbmPlaneLayout
{
Uint32 Stride = 0;
Uint32 Offset = 0;
SizeT Size = 0;
};
// One frame the phone offered, as this process holds it: the offer's own
// description of the memory, plus the descriptor this library duped out of the
// handle the phone sent. It owns that descriptor for as long as it lives, so a
// caller that takes a frame and then fails still closes it, and the descriptor the
// phone sent is closed with the rest of the message's descriptors rather than kept.
struct GbmHostFrame
{
Uint32 Seq = 0;
Uint32 Index = 0;
Uint32 Width = 0;
Uint32 Height = 0;
Uint32 StrideBytes = 0;
Uint32 Format = 0;
// Bytes per pixel of plane 0. The offer carries a fourcc, so it comes from the
// format table when there is an entry for it and from the stride otherwise.
Uint32 BytesPerPixel = 0;
Uint64 Usage = 0;
// Which connection offered the frame. A release names a frame, and a frame only
// means anything to the connection that offered it.
Uint64 Generation = 0;
// The duped dma-buf descriptor, and how many bytes it actually backs as asked
// of the descriptor itself rather than computed from the offered geometry.
Int Fd = -1;
SizeT Size = 0;
// Move-only, because two records naming one descriptor would close it twice.
GbmHostFrame() = default;
GbmHostFrame(const GbmHostFrame&) = delete;
GbmHostFrame& operator=(const GbmHostFrame&) = delete;
GbmHostFrame(GbmHostFrame&& other) noexcept;
GbmHostFrame& operator=(GbmHostFrame&& other) noexcept;
~GbmHostFrame();
};
// One imported or locally allocated buffer. The struct is private to this
// library; gbm_bo is the public opaque name and is defined in terms of it.
struct GbmBufferObject
{
Uint32 Width = 0;
Uint32 Height = 0;
Uint32 Format = 0;
Uint32 Stride = 0;
Uint64 Modifier = DrmFormatModLinear;
Uint64 Usage = 0;
Int PlaneCount = 1;
// Bytes per pixel of plane 0. Kept beside the layout because gbm_bo_map
// needs it to place a sub-rectangle, and because a format this library can
// allocate but cannot describe in bytes would be a format it must refuse.
Uint32 BytesPerPixel = 0;
// Fds owned by this record. get_fd and get_fd_for_plane hand out dups so
// that a caller closing its fd can never invalidate the buffer. Index 0 is
// the only one a self-allocated buffer has: every plane of a linear image
// lives in that one dma-buf, and Fds[1..] stay -1 for it. An import with
// several descriptors fills several entries, and the destructor closes
// every entry that is not -1.
Int Fds[GbmMaxPlanes] = {-1, -1, -1, -1};
Uint32 Strides[GbmMaxPlanes] = {0, 0, 0, 0};
Uint32 Offsets[GbmMaxPlanes] = {0, 0, 0, 0};
Uint64 Modifiers[GbmMaxPlanes] = {0, 0, 0, 0};
// The number of bytes the descriptors actually back, rounded up to the page
// size because that is what both backends allocate. It is the only length
// that is safe to mmap: a mapping longer than the object faults on the last
// page, and a shorter one would hide the caller's own stride arithmetic.
SizeT AllocationSize = 0;
GbmBackend Backend = GbmBackend::None;
// Set only for host frames: the slot index and sequence number that the
// release message has to mention so the phone can recycle the right slot, and
// the connection the frame arrived on. A frame left over from a connection
// that has since died is never released into the one that replaced it, because
// that would free a slot belonging to another session.
Uint32 HostIndex = 0;
Uint32 HostSeq = 0;
Uint64 HostGeneration = 0;
Bool HostOwned = false;
// How many maps are outstanding. The mapping itself is kept here so that
// unmap can find and tear down the right one.
Int MapRefCount = 0;
void* MapAddress = nullptr;
SizeT MapSize = 0;
// Surfaces keep their buffers alive by count rather than by ownership, so
// the device knows when a bo is truly unreferenced.
Int RefCount = 1;
// gbm_bo_set_user_data's pair. The destroy callback is invoked with the
// gbm_bo that is going away, once, from the destructor below.
void* UserData = nullptr;
void (*UserDataDestroy)(::gbm_bo*, void*) = nullptr;
::gbm_device* Owner = nullptr;
// The record releases its own descriptors and its own mapping, so that no
// failure path anywhere in this library can leak either one - an allocation
// that fails half way through construction still cleans up when the record
// it was building is destroyed.
~GbmBufferObject();
};
// A real swapchain. The compositor asks for a buffer to render into, presents
// it, and later returns it; the three states below are exactly the states the
// GBM API can express.
struct GbmSurface
{
Uint32 Width = 0;
Uint32 Height = 0;
Uint32 Format = 0;
Uint32 Flags = 0;
std::vector<::gbm_bo*> Buffers;
// Index of the buffer currently handed to the compositor as the front
// buffer, or -1 when nothing has been locked.
Int LockedIndex = -1;
// Indices of buffers the compositor has released and that may be handed
// out again, plus the one that is locked.
std::vector<Bool> Free;
::gbm_device* Owner = nullptr;
// Dropping the surface's references here is what keeps the creation path
// free of a second failure path: if the third swapchain buffer cannot be
// allocated, unwinding the half-built surface returns the two that exist.
~GbmSurface();
};
// The device ties one backend choice, one host channel and one mutex together.
// The single mutex is deliberate: GBM calls arrive from the compositor's
// render thread and from its main thread, and the state they touch (the bo
// table, the backends) is small enough that one lock is cheaper than several.
struct GbmDevice
{
// The fd this device was created with. It is a private dup taken at
// creation, never the caller's descriptor, so gbm_device_destroy can close
// it without ever closing an fd the caller still has open. -1 when the
// caller passed none and no render node could be opened: the self-allocated
// backend does not need a DRM node, so that is a working device and not an
// error.
Int DeviceFd = -1;
// The dma-heap node this device allocates from, or -1 when none could be
// opened, in which case every allocation falls back to a memfd.
Int HeapFd = -1;
String HeapPath;
// Where the display host is reached, as configured when the device was created.
String SocketPath;
GbmBackend DefaultBackend = GbmBackend::DmaHeap;
// True while the channel below is connected and frames are arriving over it.
// False means every allocation this device answers is answered locally.
Bool HostAvailable = false;
// The name gbm_device_get_backend_name reports. It names what this device
// actually does, because a compositor that logs it is asking exactly that - so
// it changes when the host channel connects and when that connection dies, and
// SelfAllocatedBackendName is what it falls back to when it does.
String BackendName = "mobilegl";
String SelfAllocatedBackendName = "mobilegl";
std::mutex Mutex;
std::unordered_map<::gbm_bo*, GbmBufferObject*> Buffers;
std::unordered_map<::gbm_surface*, GbmSurface*> Surfaces;
// The host channel is a separate translation unit so that the socket protocol
// never leaks into the allocation paths. It lives for as long as the device
// does and is reached only under this device's mutex, which is what lets the
// allocation path ask it for a frame without a second lock to order against.
class GbmHostChannel* Host = nullptr;
// Closes the heap node and the private device dup, so that a device which
// fails to finish constructing still releases the descriptors it opened.
~GbmDevice();
};
// ---- format description ------------------------------------------------
// Fills planes[]/planeCount/totalBytes with the linear layout this library
// would allocate for format at width x height, and returns false for a format
// it cannot lay out. gbm_bo_create refuses a format this refuses, because a
// buffer whose plane layout was guessed is worse than a buffer that was not
// handed out at all.
Bool GbmDescribeFormat(Uint32 format, Uint32 width, Uint32 height, GbmPlaneLayout planes[GbmMaxPlanes],
Int& planeCount, SizeT& totalBytes) noexcept;
// Whether this library can allocate the format at all.
Bool GbmFormatIsSupported(Uint32 format) noexcept;
// Bytes per pixel of plane 0: what gbm_bo_map needs to place a sub-rectangle,
// and half of what gbm_bo_get_bpp reports.
Uint32 GbmFormatBytesPerPixel(Uint32 format) noexcept;
// ---- records and the self-allocated backend ----------------------------
// Builds a device. The only helper here that is called without the mutex,
// because no other thread can see the device it is building.
::gbm_device* GbmDeviceCreate(Int fd) noexcept;
// Tears the device down: every remaining surface, every remaining buffer, the
// heap node, the private device fd, and the record itself.
void GbmDeviceDestroy(::gbm_device& device) noexcept;
// Allocates a buffer from the device's heap node, or from a memfd when there
// is none, and records it in the device's table. Returns null with errno set.
::gbm_bo* GbmBufferCreate(::gbm_device& device, Uint32 width, Uint32 height, Uint32 format, Uint64 usage,
const Uint64* modifiers, Uint32 modifierCount) noexcept;
// Wraps descriptors the caller already owns. The descriptors are duped, so the
// caller keeps ownership of its own; type is GBM_BO_IMPORT_FD or
// GBM_BO_IMPORT_FD_MODIFIER.
::gbm_bo* GbmBufferImport(::gbm_device& device, Uint32 type, const void* buffer, Uint64 usage) noexcept;
// Drops one reference, destroying the buffer when it was the last one.
void GbmBufferRelease(::gbm_device& device, ::gbm_bo& bo) noexcept;
// Destroys a buffer outright, whatever its reference count says. Only the
// device's own teardown uses this: by then no caller's reference is meaningful.
void GbmBufferForceDestroy(::gbm_device& device, ::gbm_bo& bo) noexcept;
// Hands out a dup of the descriptor backing a plane, which the caller then owns.
// A plane this buffer does not have is refused with errno = EINVAL.
Int GbmBufferDupFd(::gbm_bo& bo, Int plane) noexcept;
// Maps the whole buffer once and counts the call; strideOut receives the
// stride of plane 0. The rect (x, y) is applied to the returned address.
void* GbmBufferMap(::gbm_bo& bo, Uint32 x, Uint32 y, Uint32& strideOut) noexcept;
// Drops one mapping; the last one unmaps.
void GbmBufferUnmap(::gbm_bo& bo, void* mapData) noexcept;
// ---- host frames -------------------------------------------------------
// Builds the channel to the display host and makes one attempt to connect it, then
// stores it in the device. A machine that is not the container half of a split run
// has nothing at that path, and that is a device which allocates locally from then
// on - not a device that failed to be created.
void GbmHostChannelCreate(::gbm_device& device) noexcept;
// Closes the channel and releases what it holds. Called from the device's
// destructor, after the buffers that still name offered frames are gone, so that
// their releases can still be sent.
void GbmHostChannelDestroy(::gbm_device& device) noexcept;
// Takes the next frame the host offered, or returns false when none is waiting or
// the channel is down. Never blocks: the socket is non-blocking, so a caller that
// finds nothing allocates locally in the same call, which is what makes this usable
// from a compositor's frame loop.
Bool GbmHostChannelTakeFrame(::gbm_device& device, GbmHostFrame& frameOut) noexcept;
// Tells the host that a frame may be recycled. Called from the buffer record's
// destructor, so a frame goes back exactly when nothing in this process can still
// read it, and only into the connection that offered it.
void GbmHostChannelReleaseFrame(::gbm_device& device, Uint32 seq, Uint64 generation) noexcept;
// ---- swapchains --------------------------------------------------------
// Builds a surface and its swapchain up front, so that
// gbm_surface_has_free_buffers can answer truthfully from the first call.
::gbm_surface* GbmSurfaceCreate(::gbm_device& device, Uint32 width, Uint32 height, Uint32 format, Uint64 usage,
const Uint64* modifiers, Uint32 modifierCount) noexcept;
// Unregisters the surface and destroys it, returning the swapchain buffers it
// still owns to the device.
void GbmSurfaceDestroy(::gbm_surface& surface) noexcept;
// Hands out the next free swapchain buffer with a reference of its own, or
// null with errno = EBUSY when the compositor still holds every one of them.
::gbm_bo* GbmSurfaceLockFront(::gbm_surface& surface) noexcept;
// Takes a locked buffer back, dropping the reference the lock handed out.
void GbmSurfaceReleaseBuffer(::gbm_surface& surface, ::gbm_bo& bo) noexcept;
Bool GbmSurfaceHasFreeBuffers(::gbm_surface& surface) noexcept;
} // namespace MobileGL::MG_Gbm
// The public opaque types are the internal records. Callers only ever see the
// pointers, so this costs nothing and removes a layer of casting.
struct gbm_device
{
MobileGL::MG_Gbm::GbmDevice Impl;
};
struct gbm_bo
{
MobileGL::MG_Gbm::GbmBufferObject Impl;
};
struct gbm_surface
{
MobileGL::MG_Gbm::GbmSurface Impl;
};
// End of Source File Header
-405
View File
@@ -1,405 +0,0 @@
// MobileGL - MobileGL/MG_Gbm/MobileGLGbm.cpp
// Copyright (c) 2025-2026 MobileGL-Dev
// Licensed under the GNU Lesser General Public License v3.0:
// https://www.gnu.org/licenses/gpl-3.0.txt
// https://www.gnu.org/licenses/lgpl-3.0.txt
// SPDX-License-Identifier: LGPL-3.0-only
// End of Source File Header
// mobilegl_gbm.so: a GBM backend (the loader's backend ABI, gbm_backend_abi.h) whose buffer
// objects are MobileGL shared images - colour buffers the MobileGL server allocates and exports
// as dma-bufs (docs/Disaggregated/notes/anland/plan-ahb-dmabuf.md). Selected with
// GBM_BACKEND=mobilegl; the loader then finds <dir>/mobilegl_gbm.so on its backend path.
//
// THE DEVICE DESCRIPTOR IS OPAQUE. The fd a gbm_device is created on is only the identity the
// caller chose (a render node, or any character device); no ioctl is ever issued on it, because
// the buffers do not come from that device's driver - they come from the server, over the
// process's MobileGL client session. Whatever node the caller holds is therefore equally good,
// and none is vendor-specific.
//
// THE LAYOUT IS THE ALLOCATOR'S. Buffers report DRM_FORMAT_MOD_INVALID and a single plane; a
// request that needs a known layout (LINEAR, or a modifier list without INVALID) is refused
// rather than answered with a buffer whose layout is not what was asked for.
//
// Buffer operations reach the server through libMobileGL.so's shared-image C ABI
// (MG_Impl/SharedImageApi.h), resolved with dlsym on first use - preferably from the instance the
// process has already loaded (its EGL vendor), so the buffers belong to the same session.
#include "SharedImageApi.h"
#include <gbm.h>
#include <gbm_backend_abi.h>
#include <atomic>
#include <cerrno>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <mutex>
#include <new>
#include <dlfcn.h>
#include <fcntl.h>
#include <unistd.h>
#define MOBILEGL_GBM_EXPORT extern "C" __attribute__((visibility("default")))
namespace {
constexpr uint64_t kModifierLinear = 0;
constexpr uint64_t kModifierInvalid = 0x00ffffffffffffffull;
// Usages no shared image can honour: a CPU-written cursor (bo_write), a guaranteed-linear
// layout, protected content. Scanout/rendering/texturing are accepted - every caller of
// gbm_bo_create passes them, and a shared image serves all three.
constexpr uint32_t kRefusedUsage = GBM_BO_USE_CURSOR | GBM_BO_USE_WRITE | GBM_BO_USE_LINEAR | GBM_BO_USE_PROTECTED;
const gbm_core* g_core = nullptr;
struct Device {
gbm_device base; // first: the loader's gbm_device* is this object
};
struct Bo {
gbm_bo base; // first: the loader's gbm_bo* is this object
uint64_t imageId;
int fd; // owned; every get_fd hands out a duplicate
uint32_t offset;
uint64_t modifier;
};
// ---- libMobileGL's shared-image ABI -----------------------------------------------------
struct SharedImageApi {
PFN_mobilegl_shared_image_allocate allocate = nullptr;
PFN_mobilegl_shared_image_import import = nullptr;
PFN_mobilegl_shared_image_release release = nullptr;
PFN_mobilegl_server_available serverAvailable = nullptr; // optional (older libraries lack it)
};
// The library the process already has (by its soname: glvnd loads it by path, which records
// the soname too), else MOBILEGL_GBM_LIBRARY, else the loader's search path, else the GLX vendor
// name it is installed under in the system library directory (the same file, so the same
// instance if glvnd loads it later). Never closed: libMobileGL leaks its globals at exit by
// design and must not be unloaded under them.
const SharedImageApi* Api() {
static std::once_flag once;
static SharedImageApi api;
static bool resolved = false;
std::call_once(once, [] {
void* lib = dlopen("libMobileGL.so", RTLD_NOW | RTLD_NOLOAD);
if (lib == nullptr) {
const char* path = std::getenv("MOBILEGL_GBM_LIBRARY");
lib = dlopen(path != nullptr && path[0] != '\0' ? path : "libMobileGL.so", RTLD_NOW | RTLD_LOCAL);
}
if (lib == nullptr) lib = dlopen("libGLX_mobilegl.so.0", RTLD_NOW | RTLD_LOCAL);
if (lib == nullptr) {
std::fprintf(stderr, "mobilegl_gbm: libMobileGL.so could not be loaded: %s\n", dlerror());
return;
}
const auto version = reinterpret_cast<PFN_mobilegl_shared_image_abi_version>(
dlsym(lib, "mobilegl_shared_image_abi_version"));
api.allocate = reinterpret_cast<PFN_mobilegl_shared_image_allocate>(dlsym(lib, "mobilegl_shared_image_allocate"));
api.import = reinterpret_cast<PFN_mobilegl_shared_image_import>(dlsym(lib, "mobilegl_shared_image_import"));
api.release = reinterpret_cast<PFN_mobilegl_shared_image_release>(dlsym(lib, "mobilegl_shared_image_release"));
api.serverAvailable = reinterpret_cast<PFN_mobilegl_server_available>(dlsym(lib, "mobilegl_server_available"));
if (version == nullptr || version() < 1 || api.allocate == nullptr || api.import == nullptr ||
api.release == nullptr) {
std::fprintf(stderr, "mobilegl_gbm: this libMobileGL.so has no shared-image ABI\n");
return;
}
resolved = true;
});
return resolved ? &api : nullptr;
}
// ---- formats ----------------------------------------------------------------------------
uint32_t Canonical(uint32_t format) {
if (g_core != nullptr && g_core->v0.format_canonicalize != nullptr) return g_core->v0.format_canonicalize(format);
// The two legacy GBM_BO_FORMAT_* enumerants are the only non-fourcc formats.
if (format == GBM_BO_FORMAT_XRGB8888) return GBM_FORMAT_XRGB8888;
if (format == GBM_BO_FORMAT_ARGB8888) return GBM_FORMAT_ARGB8888;
return format;
}
// What a shared image can be. The ARGB/XRGB orders are stored like the ABGR/XBGR ones: the
// layout is the server's (modifier INVALID, no map is offered), so no reader can tell, and
// every GL that touches the image addresses its channels logically.
bool FormatSupported(uint32_t format) {
return format == MOBILEGL_SHARED_IMAGE_FOURCC_ABGR8888 || format == MOBILEGL_SHARED_IMAGE_FOURCC_XBGR8888 ||
format == MOBILEGL_SHARED_IMAGE_FOURCC_ARGB8888 || format == MOBILEGL_SHARED_IMAGE_FOURCC_XRGB8888;
}
bool ModifierAcceptable(uint64_t modifier) { return modifier == kModifierInvalid || modifier == kModifierLinear; }
// There is no GEM handle behind a shared image; callers that only use the handle as a key
// (a buffer cache) still need it to be unique.
uint32_t NextHandle() {
static std::atomic<uint32_t> next{1};
uint32_t handle = next.fetch_add(1, std::memory_order_relaxed);
if (handle == 0) handle = next.fetch_add(1, std::memory_order_relaxed);
return handle;
}
gbm_bo* NewBo(gbm_device* gbm, uint64_t imageId, int fd, uint32_t width, uint32_t height, uint32_t format,
uint32_t stride, uint32_t offset, uint64_t modifier) {
auto* bo = new (std::nothrow) Bo{};
if (bo == nullptr) {
errno = ENOMEM;
return nullptr;
}
bo->base.gbm = gbm;
bo->base.v0.width = width;
bo->base.v0.height = height;
bo->base.v0.stride = stride;
bo->base.v0.format = format;
bo->base.v0.handle.u32 = NextHandle();
bo->imageId = imageId;
bo->fd = fd;
bo->offset = offset;
bo->modifier = modifier;
return &bo->base;
}
Bo* AsBo(gbm_bo* bo) { return reinterpret_cast<Bo*>(bo); }
// ---- device -----------------------------------------------------------------------------
void DeviceDestroy(gbm_device* gbm) { delete reinterpret_cast<Device*>(gbm); }
int IsFormatSupported(gbm_device*, uint32_t format, uint32_t usage) {
return FormatSupported(Canonical(format)) && (usage & kRefusedUsage) == 0 ? 1 : 0;
}
int GetFormatModifierPlaneCount(gbm_device*, uint32_t format, uint64_t modifier) {
if (!FormatSupported(Canonical(format)) || !ModifierAcceptable(modifier)) return -1;
return 1;
}
gbm_bo* BoCreate(gbm_device* gbm, uint32_t width, uint32_t height, uint32_t format, uint32_t usage,
const uint64_t* modifiers, const unsigned int count) {
format = Canonical(format);
if (!FormatSupported(format) || (usage & kRefusedUsage) != 0) {
errno = EINVAL;
return nullptr;
}
if (count > 0) {
// The layout is the allocator's, which only a list that admits INVALID accepts.
bool admitsImplicit = false;
for (unsigned int i = 0; i < count; ++i) admitsImplicit |= modifiers[i] == kModifierInvalid;
if (!admitsImplicit) {
errno = EINVAL;
return nullptr;
}
}
const SharedImageApi* api = Api();
if (api == nullptr) {
errno = ENOSYS;
return nullptr;
}
mobilegl_shared_image image{};
image.struct_size = sizeof(image);
image.fd = -1;
const int rc = api->allocate(width, height, format, &image);
if (rc != 0 || image.fd < 0) {
if (image.fd >= 0) ::close(image.fd);
errno = rc < 0 ? -rc : EIO;
return nullptr;
}
gbm_bo* bo = NewBo(gbm, image.id, image.fd, image.width, image.height, image.fourcc, image.stride,
image.offset, image.modifier);
if (bo == nullptr) {
api->release(image.id);
::close(image.fd);
}
return bo;
}
gbm_bo* BoImport(gbm_device* gbm, uint32_t type, void* buffer, uint32_t usage) {
(void)usage;
if (buffer == nullptr) {
errno = EINVAL;
return nullptr;
}
int fd = -1;
uint32_t width = 0, height = 0, format = 0, stride = 0, offset = 0;
uint64_t modifier = kModifierInvalid;
switch (type) {
case GBM_BO_IMPORT_FD: {
const auto* data = static_cast<const gbm_import_fd_data*>(buffer);
fd = data->fd;
width = data->width;
height = data->height;
format = data->format;
stride = data->stride;
break;
}
case GBM_BO_IMPORT_FD_MODIFIER: {
const auto* data = static_cast<const gbm_import_fd_modifier_data*>(buffer);
if (data->num_fds != 1 || !ModifierAcceptable(data->modifier)) {
errno = EINVAL;
return nullptr;
}
fd = data->fds[0];
width = data->width;
height = data->height;
format = data->format;
stride = static_cast<uint32_t>(data->strides[0]);
offset = static_cast<uint32_t>(data->offsets[0]);
modifier = data->modifier;
break;
}
default:
// A wl_buffer or an EGLImage would have to be resolved through a display this backend
// does not own; their owners can export a dma-buf and import that instead.
errno = ENOSYS;
return nullptr;
}
format = Canonical(format);
if (fd < 0 || width == 0 || height == 0 || !FormatSupported(format)) {
errno = EINVAL;
return nullptr;
}
const SharedImageApi* api = Api();
if (api == nullptr) {
errno = ENOSYS;
return nullptr;
}
// The caller keeps its descriptor; the bo holds its own.
const int owned = ::fcntl(fd, F_DUPFD_CLOEXEC, 0);
if (owned < 0) return nullptr;
uint64_t id = 0;
const int rc = api->import(owned, width, height, format, &id);
if (rc != 0) {
::close(owned);
errno = -rc;
return nullptr;
}
gbm_bo* bo = NewBo(gbm, id, owned, width, height, format, stride, offset, modifier);
if (bo == nullptr) {
api->release(id);
::close(owned);
}
return bo;
}
// CPU access is not offered: the layout is opaque, so a mapping would need the server to
// copy through a linear staging buffer, which does not exist yet.
void* BoMap(gbm_bo*, uint32_t, uint32_t, uint32_t, uint32_t, uint32_t, uint32_t*, void**) {
errno = ENOSYS;
return nullptr;
}
void BoUnmap(gbm_bo*, void*) {}
int BoWrite(gbm_bo*, const void*, size_t) {
errno = ENOSYS;
return -1;
}
int BoGetFd(gbm_bo* bo) { return ::fcntl(AsBo(bo)->fd, F_DUPFD_CLOEXEC, 0); }
int BoGetPlanes(gbm_bo*) { return 1; }
gbm_bo_handle BoGetHandle(gbm_bo* bo, int plane) {
gbm_bo_handle handle{};
if (plane != 0) {
errno = EINVAL;
handle.s32 = -1;
return handle;
}
return bo->v0.handle;
}
int BoGetPlaneFd(gbm_bo* bo, int plane) {
if (plane != 0) {
errno = EINVAL;
return -1;
}
return BoGetFd(bo);
}
uint32_t BoGetStride(gbm_bo* bo, int plane) { return plane == 0 ? bo->v0.stride : 0; }
uint32_t BoGetOffset(gbm_bo* bo, int plane) { return plane == 0 ? AsBo(bo)->offset : 0; }
uint64_t BoGetModifier(gbm_bo* bo) { return AsBo(bo)->modifier; }
void BoDestroy(gbm_bo* gbm) {
Bo* bo = AsBo(gbm);
if (const SharedImageApi* api = Api()) api->release(bo->imageId);
if (bo->fd >= 0) ::close(bo->fd);
delete bo;
}
// Window surfaces belong to the EGL platform, not to this allocator.
gbm_surface* SurfaceCreate(gbm_device*, uint32_t, uint32_t, uint32_t, uint32_t, const uint64_t*, const unsigned) {
errno = ENOSYS;
return nullptr;
}
gbm_bo* SurfaceLockFrontBuffer(gbm_surface*) { return nullptr; }
void SurfaceReleaseBuffer(gbm_surface*, gbm_bo*) {}
int SurfaceHasFreeBuffers(gbm_surface*) { return 0; }
void SurfaceDestroy(gbm_surface*) {}
// THE DEVICE IS DECLINED WHEN NOTHING COULD SERVE ITS BUFFERS. The loader takes this backend
// because GBM_BACKEND names it, and when its create_device fails it goes on to the backend the
// device's own driver names - so declining is what lets one system-wide GBM_BACKEND=mobilegl
// coexist with processes that run while no MobileGL server is reachable. Asked before any
// buffer exists, with one bounded connect (mobilegl_server_available), never a session bring-up.
gbm_device* CreateDevice(int fd, uint32_t backendVersion) {
const SharedImageApi* api = Api();
if (api == nullptr || (api->serverAvailable != nullptr && api->serverAvailable() == 0)) {
errno = ENODEV;
return nullptr;
}
auto* device = new (std::nothrow) Device{};
if (device == nullptr) return nullptr;
gbm_device_v0& v0 = device->base.v0;
v0.backend_version = backendVersion; // the loader checks this is what it asked for
v0.fd = fd;
v0.name = "mobilegl";
v0.destroy = DeviceDestroy;
v0.is_format_supported = IsFormatSupported;
v0.get_format_modifier_plane_count = GetFormatModifierPlaneCount;
v0.bo_create = BoCreate;
v0.bo_import = BoImport;
v0.bo_map = BoMap;
v0.bo_unmap = BoUnmap;
v0.bo_write = BoWrite;
v0.bo_get_fd = BoGetFd;
v0.bo_get_planes = BoGetPlanes;
v0.bo_get_handle = BoGetHandle;
v0.bo_get_plane_fd = BoGetPlaneFd;
v0.bo_get_stride = BoGetStride;
v0.bo_get_offset = BoGetOffset;
v0.bo_get_modifier = BoGetModifier;
v0.bo_destroy = BoDestroy;
v0.surface_create = SurfaceCreate;
v0.surface_lock_front_buffer = SurfaceLockFrontBuffer;
v0.surface_release_buffer = SurfaceReleaseBuffer;
v0.surface_has_free_buffers = SurfaceHasFreeBuffers;
v0.surface_destroy = SurfaceDestroy;
return &device->base;
}
// ABI 1 differs from 0 only in the loader populating usage/flags alongside modifiers, which
// this backend reads as they come; every structure here is the v0 layout.
const gbm_backend kBackend = {
.v0 =
{
.backend_version = GBM_BACKEND_ABI_VERSION,
.backend_name = "mobilegl",
.create_device = CreateDevice,
},
};
} // namespace
MOBILEGL_GBM_EXPORT const gbm_backend* GBM_GET_BACKEND_PROC(const gbm_core* core) {
g_core = core;
return &kBackend;
}
File diff suppressed because it is too large Load Diff
+13 -76
View File
@@ -8,16 +8,21 @@
#pragma once
#include <Includes.h>
// 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 <EGL/eglext.h>
#include <mutex>
namespace MobileGL::MG_Impl::EGLImpl {
// The display host's frame surface, as taken by the surfaceless-bind hook in MakeCurrent, and the
// display it belongs to. glFlush reads these: a compositor's frame boundary is glFlush, and the
// host frame's "frame is done" signal IS a swap of this surface. Null until a client marked
// MOBILEGL_HOST_FRAME_CLIENT=1 actually took the frame.
extern EGLDisplay g_hostFramePresentDisplay;
extern EGLSurface g_hostFramePresentSurface;
EGLSurface CreateWindowSurface(EGLDisplay dpy, EGLConfig config, NativeWindowType window,
const EGLint* attrib_list);
EGLBoolean SwapBuffers(EGLDisplay dpy, EGLSurface draw);
EGLBoolean SwapBuffersWithDamage(EGLDisplay dpy, EGLSurface draw, const EGLint* rects, EGLint n_rects);
EGLBoolean SetDamageRegion(EGLDisplay dpy, EGLSurface surface, const EGLint* rects, EGLint n_rects);
EGLBoolean ChooseConfig(EGLDisplay dpy, const EGLint* attrib_list, EGLConfig* configs, EGLint config_size,
EGLint* num_config);
EGLContext CreateContext(EGLDisplay dpy, EGLConfig config, EGLContext shareCtx, const EGLint* attrib_list);
@@ -58,16 +63,11 @@ 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);
EGLBoolean QueryDmaBufFormats(EGLDisplay dpy, EGLint max_formats, EGLint* formats, EGLint* num_formats);
EGLBoolean QueryDmaBufModifiers(EGLDisplay dpy, EGLint format, EGLint max_modifiers, EGLuint64KHR* modifiers,
EGLBoolean* external_only, EGLint* num_modifiers);
// Whether the active backend has shared images (MG_Backend::BackendObject::AllocateSharedImage):
// a split client's does, a monolith's does not. Decides the dma-buf EGL extensions, the
// Wayland linux-dmabuf presentation and GL_OES_EGL_image.
Bool SharedImagesAvailable();
// The shared image an EGLImage names (EGL_LINUX_DMA_BUF_EXT), for glEGLImageTargetTexture2DOES.
Bool LookupSharedImage(EGLImage image, Uint64* id, EGLint* width, EGLint* height);
EGLDisplay GetPlatformDisplay(EGLenum platform, void* native_display, const EGLAttrib* attrib_list);
EGLSurface CreatePlatformWindowSurface(EGLDisplay dpy, EGLConfig config, void* native_window,
const EGLAttrib* attrib_list);
@@ -76,67 +76,4 @@ namespace MobileGL::MG_Impl::EGLImpl {
const EGLAttrib* attrib_list);
EGLBoolean WaitSync(EGLDisplay dpy, EGLSync sync, EGLint flags);
__eglMustCastToProperFunctionPointerType GetProcAddress(const char* name);
#if MOBILEGL_BUILD_DISAGGREGATED
// THE CLIENT'S STREAM GATE. Under a split transport every thread of the process writes into
// ONE ring, and the server attributes each record to the context the last applied
// `bind_context` named - one current context per SESSION. A context, though, is current per
// THREAD, and Qt renders each window on its own QSGRenderThread: two threads' records then
// interleave on the ring with no binding between them and land in the wrong context's
// applier (empty sampler windows at a Clear, another context's buffers under an upload).
//
// So every GL entry point and every EGL operation that writes to the stream runs under one
// process-wide lock (EGLOperationMutex, which the EGL side already held), and before it
// writes, the server is re-bound to the CALLING thread's context whenever the last binding
// actually sent names a different one. A no-op scope on a monolith transport and on the
// server's own apply thread.
Bool StreamGateActive();
std::recursive_mutex& StreamMutex();
void StreamBindCallingThreadLocked();
// P14: the share-group token of the context the stream is bound to - the group whose object
// records anything written right now lands in on the server. False while the gate is inactive
// (a monolith, the server's own apply thread), where no binding crosses. Read under
// StreamMutex(), like the binding itself.
Bool StreamBoundShareGroupToken(Uint64* outToken);
class GLStreamScope {
public:
GLStreamScope() {
if (!StreamGateActive()) return;
m_mutex = &StreamMutex();
m_mutex->lock();
StreamBindCallingThreadLocked();
}
~GLStreamScope() {
if (m_mutex != nullptr) m_mutex->unlock();
}
GLStreamScope(const GLStreamScope&) = delete;
GLStreamScope& operator=(const GLStreamScope&) = delete;
private:
std::recursive_mutex* m_mutex = nullptr;
};
// The lock alone, for every EGL entry point: an EGL call may publish into the ring too (a
// surface forwarder's catch-up wait, a present, a context frame), and a second thread's GL
// record written into the middle of it is a torn record the server latches the session on.
class StreamLockScope {
public:
StreamLockScope() {
if (!StreamGateActive()) return;
m_mutex = &StreamMutex();
m_mutex->lock();
}
~StreamLockScope() {
if (m_mutex != nullptr) m_mutex->unlock();
}
StreamLockScope(const StreamLockScope&) = delete;
StreamLockScope& operator=(const StreamLockScope&) = delete;
private:
std::recursive_mutex* m_mutex = nullptr;
};
#else
class GLStreamScope {};
class StreamLockScope {};
#endif
} // namespace MobileGL::MG_Impl::EGLImpl
+145 -24
View File
@@ -1,37 +1,158 @@
// MobileGL - MobileGL/MG_Impl/EGLImpl/EGLPlatformExtensions.h
// Copyright (c) 2025-2026 MobileGL-Dev
// Licensed under the GNU Lesser General Public License v3.0:
// https://www.gnu.org/licenses/gpl-3.0.txt
// https://www.gnu.org/licenses/lgpl-3.0.txt
// SPDX-License-Identifier: LGPL-3.0-only
// End of Source File Header
#pragma once
namespace MobileGL::MG_Impl::EGLImpl {
// Keep libglvnd routing and direct queries consistent. Device/GBM extensions
// are absent until their entry points and image paths exist.
inline constexpr const char* kDeviceExtensionString = "";
// THE PLATFORMS THIS IMPLEMENTATION SERVES, in the words EGL spells them.
//
// Two callers need exactly the same list, and they disagree if it is written twice:
// eglQueryString(EGL_EXTENSIONS) is what an application reads BEFORE it decides to call
// eglGetPlatformDisplay at all - libepoxy refuses to use eglGetPlatformDisplayEXT unless the
// string names EGL_EXT_platform_base - and the glvnd vendor string is what the system's
// libEGL reads to decide which vendor library a platform request should be routed to. A
// vendor that does not claim the platform is never asked for it, and the caller is told there
// is no provider: the library can be loaded, initialized, and still never called.
//
// GBM is on the list because a compositor asks for its display on the GBM device it owns.
// This side treats that device the way it treats every other native display - the frames come
// from the display host, not from the device - so the claim is exact rather than optimistic.
inline constexpr const char* kDeviceExtensionString =
"EGL_EXT_device_base "
"EGL_EXT_device_enumeration "
"EGL_EXT_device_query "
"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.
// Wayland where a Wayland client can exist (WaylandWindow.h: window surfaces presented through
// wl_shm). Without it glvnd never hands this vendor a Wayland display at all.
#if defined(__linux__) && !defined(__ANDROID__)
// GBM is claimed as a display platform only: a display on a gbm_device is an offscreen display
// like a surfaceless one (the frames come from the backend, not from the device), and window
// surfaces on it are refused. Chromium's Wayland GPU process hands its GL implementation nothing
// but a GBM display, so without the claim it never reaches this library at all.
#define MOBILEGL_PLATFORM_WAYLAND_EXTENSIONS \
" EGL_KHR_platform_wayland EGL_EXT_platform_wayland EGL_KHR_platform_gbm EGL_MESA_platform_gbm"
#define MOBILEGL_PLATFORM_WAYLAND_EXTENSIONS " EGL_KHR_platform_wayland EGL_EXT_platform_wayland"
#else
#define MOBILEGL_PLATFORM_WAYLAND_EXTENSIONS ""
#endif
inline constexpr const char* kPlatformExtensionString =
"EGL_EXT_client_extensions EGL_EXT_platform_base EGL_KHR_platform_base "
"EGL_EXT_client_extensions "
"EGL_EXT_platform_base "
"EGL_KHR_platform_base "
"EGL_KHR_platform_gbm "
"EGL_EXT_platform_gbm "
"EGL_MESA_platform_gbm "
"EGL_EXT_platform_device "
"EGL_MESA_platform_surfaceless" MOBILEGL_PLATFORM_WAYLAND_EXTENSIONS;
// 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 EGL_EXT_platform_base EGL_KHR_platform_base "
"EGL_MESA_platform_surfaceless" MOBILEGL_PLATFORM_WAYLAND_EXTENSIONS;
// The display list again, with the dma-buf import a backend with shared images has (a split
// client: the server allocates the images and names the descriptors that come back). A
// monolith has no allocator to recognise a dma-buf with, so it never advertises these. The
// same server answers the buffer age of its surfaces and takes swap damage to its presents.
inline constexpr const char* kDisplayExtensionStringWithSharedImages =
"EGL_KHR_create_context EGL_EXT_platform_base EGL_KHR_platform_base "
"EGL_MESA_platform_surfaceless" MOBILEGL_PLATFORM_WAYLAND_EXTENSIONS
" EGL_KHR_image_base EGL_EXT_image_dma_buf_import EGL_EXT_image_dma_buf_import_modifiers"
" EGL_EXT_buffer_age EGL_KHR_partial_update EGL_KHR_swap_buffers_with_damage"
" EGL_EXT_swap_buffers_with_damage";
"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 "
"EGL_KHR_platform_gbm "
"EGL_EXT_platform_gbm "
"EGL_MESA_platform_gbm "
"EGL_MESA_platform_surfaceless";
// ... and what EGL_NO_DISPLAY answers: the same, plus the client-extension marker that tells a
// caller the no-display query is meaningful here.
inline constexpr const char* kClientExtensionString =
"EGL_EXT_client_extensions EGL_KHR_create_context EGL_EXT_platform_base "
"EGL_KHR_platform_base EGL_MESA_platform_surfaceless" MOBILEGL_PLATFORM_WAYLAND_EXTENSIONS;
"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 "
"EGL_KHR_platform_gbm "
"EGL_EXT_platform_gbm "
"EGL_MESA_platform_gbm "
"EGL_MESA_platform_surfaceless";
}
+147 -121
View File
@@ -7,36 +7,19 @@
// End of Source File Header
#include <Includes.h>
// 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 <EGL/eglext.h>
#include "../EGLImpl.h"
#include <vector>
namespace {
// The KHR/EXT spellings take EGLint attribute lists where the core 1.5 entry points take
// EGLAttrib (pointer-sized). Reinterpreting one as the other reads two EGLints as one
// attribute on 64-bit, so the list is widened instead.
std::vector<EGLAttrib> WidenAttribList(const EGLint* attribs) {
std::vector<EGLAttrib> widened;
if (attribs == nullptr) return widened;
for (; *attribs != EGL_NONE; attribs += 2) {
widened.push_back(static_cast<EGLAttrib>(attribs[0]));
widened.push_back(static_cast<EGLAttrib>(attribs[1]));
}
widened.push_back(EGL_NONE);
return widened;
}
} // namespace
MOBILEGL_EGL_API EGLSurface eglCreateWindowSurface(EGLDisplay dpy, EGLConfig config, NativeWindowType window,
const EGLint* attrib_list) {
const MobileGL::MG_Impl::EGLImpl::StreamLockScope mglStreamLock;
MGLOG_D("eglCreateWindowSurface(dpy=%p, config=%p, window=%p, attrib_list=%p)", dpy, config, window, attrib_list);
return MobileGL::MG_Impl::EGLImpl::CreateWindowSurface(dpy, config, window, attrib_list);
}
MOBILEGL_EGL_API EGLBoolean eglChooseConfig(EGLDisplay dpy, const EGLint* attrib_list, EGLConfig* configs,
EGLint config_size, EGLint* num_config) {
const MobileGL::MG_Impl::EGLImpl::StreamLockScope mglStreamLock;
MGLOG_D("eglChooseConfig(dpy=%p, attrib_list=%p, configs=%p, config_size=%d, num_config=%p)", dpy, attrib_list,
configs, config_size, num_config);
return MobileGL::MG_Impl::EGLImpl::ChooseConfig(dpy, attrib_list, configs, config_size, num_config);
@@ -44,7 +27,6 @@ MOBILEGL_EGL_API EGLBoolean eglChooseConfig(EGLDisplay dpy, const EGLint* attrib
MOBILEGL_EGL_API EGLContext eglCreateContext(EGLDisplay dpy, EGLConfig config, EGLContext shareCtx,
const EGLint* attrib_list) {
const MobileGL::MG_Impl::EGLImpl::StreamLockScope mglStreamLock;
MGLOG_D("eglCreateContext(dpy=%p, config=%p, shareCtx=%p, attrib_list=%p)", dpy, config, shareCtx, attrib_list);
#ifdef TRACY_ENABLE
tracy::StartupProfiler();
@@ -53,31 +35,26 @@ MOBILEGL_EGL_API EGLContext eglCreateContext(EGLDisplay dpy, EGLConfig config, E
}
MOBILEGL_EGL_API EGLBoolean eglInitialize(EGLDisplay dpy, EGLint* major, EGLint* minor) {
const MobileGL::MG_Impl::EGLImpl::StreamLockScope mglStreamLock;
MGLOG_D("eglInitialize(dpy=%p, major=%p, minor=%p)", dpy, major, minor);
return MobileGL::MG_Impl::EGLImpl::Initialize(dpy, major, minor);
}
MOBILEGL_EGL_API EGLDisplay eglGetDisplay(NativeDisplayType display) {
const MobileGL::MG_Impl::EGLImpl::StreamLockScope mglStreamLock;
MGLOG_D("eglGetDisplay(display=%p)", display);
return MobileGL::MG_Impl::EGLImpl::GetDisplay(display);
}
MOBILEGL_EGL_API EGLint eglGetError() {
const MobileGL::MG_Impl::EGLImpl::StreamLockScope mglStreamLock;
MGLOG_D("eglGetError()");
return MobileGL::MG_Impl::EGLImpl::GetError();
}
MOBILEGL_EGL_API EGLBoolean eglMakeCurrent(EGLDisplay dpy, EGLSurface draw, EGLSurface read, EGLContext ctx) {
const MobileGL::MG_Impl::EGLImpl::StreamLockScope mglStreamLock;
MGLOG_D("eglMakeCurrent(dpy=%p, draw=%p, read=%p, ctx=%p)", dpy, draw, read, ctx);
return MobileGL::MG_Impl::EGLImpl::MakeCurrent(dpy, draw, read, ctx);
}
MOBILEGL_EGL_API EGLBoolean eglDestroyContext(EGLDisplay dpy, EGLContext ctx) {
const MobileGL::MG_Impl::EGLImpl::StreamLockScope mglStreamLock;
MGLOG_D("eglDestroyContext(dpy=%p, ctx=%p)", dpy, ctx);
#ifdef TRACY_ENABLE
tracy::ShutdownProfiler();
@@ -86,67 +63,56 @@ MOBILEGL_EGL_API EGLBoolean eglDestroyContext(EGLDisplay dpy, EGLContext ctx) {
}
MOBILEGL_EGL_API EGLBoolean eglDestroySurface(EGLDisplay dpy, EGLSurface surface) {
const MobileGL::MG_Impl::EGLImpl::StreamLockScope mglStreamLock;
MGLOG_D("eglDestroySurface(dpy=%p, surface=%p)", dpy, surface);
return MobileGL::MG_Impl::EGLImpl::DestroySurface(dpy, surface);
}
MOBILEGL_EGL_API EGLBoolean eglTerminate(EGLDisplay dpy) {
const MobileGL::MG_Impl::EGLImpl::StreamLockScope mglStreamLock;
MGLOG_D("eglTerminate(dpy=%p)", dpy);
return MobileGL::MG_Impl::EGLImpl::Terminate(dpy);
}
MOBILEGL_EGL_API EGLBoolean eglReleaseThread(void) {
const MobileGL::MG_Impl::EGLImpl::StreamLockScope mglStreamLock;
MGLOG_D("eglReleaseThread()");
return MobileGL::MG_Impl::EGLImpl::ReleaseThread();
}
MOBILEGL_EGL_API EGLContext eglGetCurrentContext(void) {
const MobileGL::MG_Impl::EGLImpl::StreamLockScope mglStreamLock;
MGLOG_D("eglGetCurrentContext()");
return MobileGL::MG_Impl::EGLImpl::GetCurrentContext();
}
MOBILEGL_EGL_API EGLBoolean eglGetConfigAttrib(EGLDisplay dpy, EGLConfig config, EGLint attribute, EGLint* value) {
const MobileGL::MG_Impl::EGLImpl::StreamLockScope mglStreamLock;
MGLOG_D("eglGetConfigAttrib(dpy=%p, config=%p, attribute=%d, value=%p)", dpy, config, attribute, value);
return MobileGL::MG_Impl::EGLImpl::GetConfigAttrib(dpy, config, attribute, value);
}
MOBILEGL_EGL_API EGLBoolean eglBindAPI(EGLenum api) {
const MobileGL::MG_Impl::EGLImpl::StreamLockScope mglStreamLock;
MGLOG_D("eglBindAPI(api=%u)", api);
return MobileGL::MG_Impl::EGLImpl::BindAPI(api);
}
MOBILEGL_EGL_API EGLSurface eglGetCurrentSurface(EGLint readdraw) {
const MobileGL::MG_Impl::EGLImpl::StreamLockScope mglStreamLock;
MGLOG_D("eglGetCurrentSurface(readdraw=%d)", readdraw);
return MobileGL::MG_Impl::EGLImpl::GetCurrentSurface(readdraw);
}
MOBILEGL_EGL_API EGLBoolean eglQuerySurface(EGLDisplay display, EGLSurface surface, EGLint attribute, EGLint* value) {
const MobileGL::MG_Impl::EGLImpl::StreamLockScope mglStreamLock;
MGLOG_D("eglQuerySurface(display=%p, surface=%p, attribute=%d, value=%p)", display, surface, attribute, value);
return MobileGL::MG_Impl::EGLImpl::QuerySurface(display, surface, attribute, value);
}
MOBILEGL_EGL_API char const* eglQueryString(EGLDisplay display, EGLint name) {
const MobileGL::MG_Impl::EGLImpl::StreamLockScope mglStreamLock;
MGLOG_D("eglQueryString(display=%p, name=%d)", display, name);
return MobileGL::MG_Impl::EGLImpl::QueryString(display, name);
}
MOBILEGL_EGL_API EGLBoolean eglSwapInterval(EGLDisplay dpy, EGLint interval) {
const MobileGL::MG_Impl::EGLImpl::StreamLockScope mglStreamLock;
MGLOG_D("eglSwapInterval(dpy=%p, interval=%d)", dpy, interval);
return MobileGL::MG_Impl::EGLImpl::SwapInterval(dpy, interval);
}
MOBILEGL_EGL_API EGLBoolean eglSwapBuffers(EGLDisplay dpy, EGLSurface draw) {
const MobileGL::MG_Impl::EGLImpl::StreamLockScope mglStreamLock;
MGLOG_D("eglSwapBuffers(dpy=%p, draw=%p)", dpy, draw);
#ifdef TRACY_ENABLE
FrameMark;
@@ -154,67 +120,33 @@ MOBILEGL_EGL_API EGLBoolean eglSwapBuffers(EGLDisplay dpy, EGLSurface draw) {
return MobileGL::MG_Impl::EGLImpl::SwapBuffers(dpy, draw);
}
// EGL_KHR_swap_buffers_with_damage and EGL_EXT_swap_buffers_with_damage: one function, two names.
MOBILEGL_EGL_API EGLBoolean eglSwapBuffersWithDamageKHR(EGLDisplay dpy, EGLSurface draw, const EGLint* rects,
EGLint n_rects) {
const MobileGL::MG_Impl::EGLImpl::StreamLockScope mglStreamLock;
MGLOG_D("eglSwapBuffersWithDamageKHR(dpy=%p, draw=%p, n_rects=%d)", dpy, draw, n_rects);
#ifdef TRACY_ENABLE
FrameMark;
#endif
return MobileGL::MG_Impl::EGLImpl::SwapBuffersWithDamage(dpy, draw, rects, n_rects);
}
MOBILEGL_EGL_API EGLBoolean eglSwapBuffersWithDamageEXT(EGLDisplay dpy, EGLSurface draw, const EGLint* rects,
EGLint n_rects) {
const MobileGL::MG_Impl::EGLImpl::StreamLockScope mglStreamLock;
MGLOG_D("eglSwapBuffersWithDamageEXT(dpy=%p, draw=%p, n_rects=%d)", dpy, draw, n_rects);
#ifdef TRACY_ENABLE
FrameMark;
#endif
return MobileGL::MG_Impl::EGLImpl::SwapBuffersWithDamage(dpy, draw, rects, n_rects);
}
// EGL_KHR_partial_update.
MOBILEGL_EGL_API EGLBoolean eglSetDamageRegionKHR(EGLDisplay dpy, EGLSurface surface, EGLint* rects, EGLint n_rects) {
const MobileGL::MG_Impl::EGLImpl::StreamLockScope mglStreamLock;
MGLOG_D("eglSetDamageRegionKHR(dpy=%p, surface=%p, n_rects=%d)", dpy, surface, n_rects);
return MobileGL::MG_Impl::EGLImpl::SetDamageRegion(dpy, surface, rects, n_rects);
}
MOBILEGL_EGL_API EGLSurface eglCreatePbufferSurface(EGLDisplay dpy, EGLConfig config, const EGLint* attrib_list) {
const MobileGL::MG_Impl::EGLImpl::StreamLockScope mglStreamLock;
MGLOG_D("eglCreatePbufferSurface(dpy=%p, config=%p, attrib_list=%p)", dpy, config, attrib_list);
return MobileGL::MG_Impl::EGLImpl::CreatePbufferSurface(dpy, config, attrib_list);
}
MOBILEGL_EGL_API __eglMustCastToProperFunctionPointerType eglGetProcAddress(const char* name) {
const MobileGL::MG_Impl::EGLImpl::StreamLockScope mglStreamLock;
MGLOG_D("eglGetProcAddress(name=%s)", name ? name : "null");
return MobileGL::MG_Impl::EGLImpl::GetProcAddress(name);
}
MOBILEGL_EGL_API EGLBoolean eglBindTexImage(EGLDisplay dpy, EGLSurface surface, EGLint buffer) {
const MobileGL::MG_Impl::EGLImpl::StreamLockScope mglStreamLock;
MGLOG_D("eglBindTexImage(dpy=%p, surface=%p, buffer=%d)", dpy, surface, buffer);
return MobileGL::MG_Impl::EGLImpl::BindTexImage(dpy, surface, buffer);
}
MOBILEGL_EGL_API EGLBoolean eglReleaseTexImage(EGLDisplay dpy, EGLSurface surface, EGLint buffer) {
const MobileGL::MG_Impl::EGLImpl::StreamLockScope mglStreamLock;
MGLOG_D("eglReleaseTexImage(dpy=%p, surface=%p, buffer=%d)", dpy, surface, buffer);
return MobileGL::MG_Impl::EGLImpl::ReleaseTexImage(dpy, surface, buffer);
}
MOBILEGL_EGL_API EGLBoolean eglCopyBuffers(EGLDisplay dpy, EGLSurface surface, EGLNativePixmapType target) {
const MobileGL::MG_Impl::EGLImpl::StreamLockScope mglStreamLock;
MGLOG_D("eglCopyBuffers(dpy=%p, surface=%p, target=%p)", dpy, surface, target);
return MobileGL::MG_Impl::EGLImpl::CopyBuffers(dpy, surface, target);
}
MOBILEGL_EGL_API EGLSurface eglCreatePbufferFromClientBuffer(EGLDisplay dpy, EGLenum buftype, EGLClientBuffer buffer,
EGLConfig config, const EGLint* attrib_list) {
const MobileGL::MG_Impl::EGLImpl::StreamLockScope mglStreamLock;
MGLOG_D("eglCreatePbufferFromClientBuffer(dpy=%p, buftype=%u, buffer=%p, config=%p, attrib_list=%p)", dpy, buftype,
buffer, config, attrib_list);
return MobileGL::MG_Impl::EGLImpl::CreatePbufferFromClientBuffer(dpy, buftype, buffer, config, attrib_list);
@@ -222,137 +154,104 @@ MOBILEGL_EGL_API EGLSurface eglCreatePbufferFromClientBuffer(EGLDisplay dpy, EGL
MOBILEGL_EGL_API EGLSurface eglCreatePixmapSurface(EGLDisplay dpy, EGLConfig config, EGLNativePixmapType pixmap,
const EGLint* attrib_list) {
const MobileGL::MG_Impl::EGLImpl::StreamLockScope mglStreamLock;
MGLOG_D("eglCreatePixmapSurface(dpy=%p, config=%p, pixmap=%p, attrib_list=%p)", dpy, config, pixmap, attrib_list);
return MobileGL::MG_Impl::EGLImpl::CreatePixmapSurface(dpy, config, pixmap, attrib_list);
}
MOBILEGL_EGL_API EGLBoolean eglGetConfigs(EGLDisplay dpy, EGLConfig* configs, EGLint config_size, EGLint* num_config) {
const MobileGL::MG_Impl::EGLImpl::StreamLockScope mglStreamLock;
MGLOG_D("eglGetConfigs(dpy=%p, configs=%p, config_size=%d, num_config=%p)", dpy, configs, config_size, num_config);
return MobileGL::MG_Impl::EGLImpl::GetConfigs(dpy, configs, config_size, num_config);
}
MOBILEGL_EGL_API EGLDisplay eglGetCurrentDisplay(void) {
const MobileGL::MG_Impl::EGLImpl::StreamLockScope mglStreamLock;
MGLOG_D("eglGetCurrentDisplay()");
return MobileGL::MG_Impl::EGLImpl::GetCurrentDisplay();
}
MOBILEGL_EGL_API EGLenum eglQueryAPI(void) {
const MobileGL::MG_Impl::EGLImpl::StreamLockScope mglStreamLock;
MGLOG_D("eglQueryAPI()");
return MobileGL::MG_Impl::EGLImpl::QueryAPI();
}
MOBILEGL_EGL_API EGLBoolean eglQueryContext(EGLDisplay dpy, EGLContext ctx, EGLint attribute, EGLint* value) {
const MobileGL::MG_Impl::EGLImpl::StreamLockScope mglStreamLock;
MGLOG_D("eglQueryContext(dpy=%p, ctx=%p, attribute=%d, value=%p)", dpy, ctx, attribute, value);
return MobileGL::MG_Impl::EGLImpl::QueryContext(dpy, ctx, attribute, value);
}
MOBILEGL_EGL_API EGLBoolean eglSurfaceAttrib(EGLDisplay dpy, EGLSurface surface, EGLint attribute, EGLint value) {
const MobileGL::MG_Impl::EGLImpl::StreamLockScope mglStreamLock;
MGLOG_D("eglSurfaceAttrib(dpy=%p, surface=%p, attribute=%d, value=%d)", dpy, surface, attribute, value);
return MobileGL::MG_Impl::EGLImpl::SurfaceAttrib(dpy, surface, attribute, value);
}
MOBILEGL_EGL_API EGLBoolean eglWaitClient(void) {
const MobileGL::MG_Impl::EGLImpl::StreamLockScope mglStreamLock;
MGLOG_D("eglWaitClient()");
return MobileGL::MG_Impl::EGLImpl::WaitClient();
}
MOBILEGL_EGL_API EGLBoolean eglWaitGL(void) {
const MobileGL::MG_Impl::EGLImpl::StreamLockScope mglStreamLock;
MGLOG_D("eglWaitGL()");
return MobileGL::MG_Impl::EGLImpl::WaitGL();
}
MOBILEGL_EGL_API EGLBoolean eglWaitNative(EGLint engine) {
const MobileGL::MG_Impl::EGLImpl::StreamLockScope mglStreamLock;
MGLOG_D("eglWaitNative(engine=%d)", engine);
return MobileGL::MG_Impl::EGLImpl::WaitNative(engine);
}
MOBILEGL_EGL_API EGLSync eglCreateSync(EGLDisplay dpy, EGLenum type, const EGLAttrib* attrib_list) {
const MobileGL::MG_Impl::EGLImpl::StreamLockScope mglStreamLock;
MGLOG_D("eglCreateSync(dpy=%p, type=%u, attrib_list=%p)", dpy, type, attrib_list);
return MobileGL::MG_Impl::EGLImpl::CreateSync(dpy, type, attrib_list);
}
MOBILEGL_EGL_API EGLBoolean eglDestroySync(EGLDisplay dpy, EGLSync sync) {
const MobileGL::MG_Impl::EGLImpl::StreamLockScope mglStreamLock;
MGLOG_D("eglDestroySync(dpy=%p, sync=%p)", dpy, sync);
return MobileGL::MG_Impl::EGLImpl::DestroySync(dpy, sync);
}
MOBILEGL_EGL_API EGLint eglClientWaitSync(EGLDisplay dpy, EGLSync sync, EGLint flags, EGLTime timeout) {
const MobileGL::MG_Impl::EGLImpl::StreamLockScope mglStreamLock;
MGLOG_D("eglClientWaitSync(dpy=%p, sync=%p, flags=%d, timeout=%llu)", dpy, sync, flags,
static_cast<unsigned long long>(timeout));
return MobileGL::MG_Impl::EGLImpl::ClientWaitSync(dpy, sync, flags, timeout);
}
MOBILEGL_EGL_API EGLBoolean eglGetSyncAttrib(EGLDisplay dpy, EGLSync sync, EGLint attribute, EGLAttrib* value) {
const MobileGL::MG_Impl::EGLImpl::StreamLockScope mglStreamLock;
MGLOG_D("eglGetSyncAttrib(dpy=%p, sync=%p, attribute=%d, value=%p)", dpy, sync, attribute, value);
return MobileGL::MG_Impl::EGLImpl::GetSyncAttrib(dpy, sync, attribute, value);
}
MOBILEGL_EGL_API EGLImage eglCreateImage(EGLDisplay dpy, EGLContext ctx, EGLenum target, EGLClientBuffer buffer,
const EGLAttrib* attrib_list) {
const MobileGL::MG_Impl::EGLImpl::StreamLockScope mglStreamLock;
MGLOG_D("eglCreateImage(dpy=%p, ctx=%p, target=%u, buffer=%p, attrib_list=%p)", dpy, ctx, target, buffer,
attrib_list);
return MobileGL::MG_Impl::EGLImpl::CreateImage(dpy, ctx, target, buffer, attrib_list);
}
MOBILEGL_EGL_API EGLBoolean eglDestroyImage(EGLDisplay dpy, EGLImage image) {
const MobileGL::MG_Impl::EGLImpl::StreamLockScope mglStreamLock;
MGLOG_D("eglDestroyImage(dpy=%p, image=%p)", dpy, image);
return MobileGL::MG_Impl::EGLImpl::DestroyImage(dpy, image);
}
// EGL_KHR_image_base's spellings. KWin loads these two by name and calls eglDestroyImageKHR
// for every cached client buffer when it dies, wl_shm ones included; a null answer from
// eglGetProcAddress made that a jump to address 0.
MOBILEGL_EGL_API EGLImage eglCreateImageKHR(EGLDisplay dpy, EGLContext ctx, EGLenum target, EGLClientBuffer buffer,
// 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) {
const MobileGL::MG_Impl::EGLImpl::StreamLockScope mglStreamLock;
MGLOG_D("eglCreateImageKHR(dpy=%p, ctx=%p, target=%u, buffer=%p, attrib_list=%p)", dpy, ctx, target, buffer,
attrib_list);
const std::vector<EGLAttrib> attribs = WidenAttribList(attrib_list);
return MobileGL::MG_Impl::EGLImpl::CreateImage(dpy, ctx, target, buffer, attrib_list ? attribs.data() : nullptr);
// 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, EGLImage image) {
const MobileGL::MG_Impl::EGLImpl::StreamLockScope mglStreamLock;
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);
}
// EGL_EXT_image_dma_buf_import_modifiers: the formats eglCreateImage(EGL_LINUX_DMA_BUF_EXT) takes,
// and (none) explicit modifiers - a compositor then imports with the implicit one.
MOBILEGL_EGL_API EGLBoolean eglQueryDmaBufFormatsEXT(EGLDisplay dpy, EGLint max_formats, EGLint* formats,
EGLint* num_formats) {
const MobileGL::MG_Impl::EGLImpl::StreamLockScope mglStreamLock;
MGLOG_D("eglQueryDmaBufFormatsEXT(dpy=%p, max_formats=%d)", dpy, max_formats);
return MobileGL::MG_Impl::EGLImpl::QueryDmaBufFormats(dpy, max_formats, formats, num_formats);
}
MOBILEGL_EGL_API EGLBoolean eglQueryDmaBufModifiersEXT(EGLDisplay dpy, EGLint format, EGLint max_modifiers,
EGLuint64KHR* modifiers, EGLBoolean* external_only,
EGLint* num_modifiers) {
const MobileGL::MG_Impl::EGLImpl::StreamLockScope mglStreamLock;
MGLOG_D("eglQueryDmaBufModifiersEXT(dpy=%p, format=0x%08x, max_modifiers=%d)", dpy, format, max_modifiers);
return MobileGL::MG_Impl::EGLImpl::QueryDmaBufModifiers(dpy, format, max_modifiers, modifiers, external_only,
num_modifiers);
}
MOBILEGL_EGL_API EGLDisplay eglGetPlatformDisplay(EGLenum platform, void* native_display,
const EGLAttrib* attrib_list) {
const MobileGL::MG_Impl::EGLImpl::StreamLockScope mglStreamLock;
MGLOG_D("eglGetPlatformDisplay(platform=%u, native_display=%p, attrib_list=%p)", platform, native_display,
attrib_list);
return MobileGL::MG_Impl::EGLImpl::GetPlatformDisplay(platform, native_display, attrib_list);
@@ -360,32 +259,159 @@ MOBILEGL_EGL_API EGLDisplay eglGetPlatformDisplay(EGLenum platform, void* native
MOBILEGL_EGL_API EGLDisplay eglGetPlatformDisplayEXT(EGLenum platform, void* native_display,
const EGLint* attrib_list) {
const MobileGL::MG_Impl::EGLImpl::StreamLockScope mglStreamLock;
MGLOG_D("eglGetPlatformDisplayEXT(platform=%u, native_display=%p, attrib_list=%p)", platform, native_display,
attrib_list);
const std::vector<EGLAttrib> attribs = WidenAttribList(attrib_list);
return MobileGL::MG_Impl::EGLImpl::GetPlatformDisplay(platform, native_display,
attrib_list ? attribs.data() : nullptr);
return MobileGL::MG_Impl::EGLImpl::GetPlatformDisplay(
platform, native_display, reinterpret_cast<const EGLAttrib*>(attrib_list));
}
MOBILEGL_EGL_API EGLSurface eglCreatePlatformWindowSurface(EGLDisplay dpy, EGLConfig config, void* native_window,
const EGLAttrib* attrib_list) {
const MobileGL::MG_Impl::EGLImpl::StreamLockScope mglStreamLock;
MGLOG_D("eglCreatePlatformWindowSurface(dpy=%p, config=%p, native_window=%p, attrib_list=%p)", dpy, config,
native_window, attrib_list);
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<EGLAttrib>(attrib_list[index]);
attributes[count++] = static_cast<EGLAttrib>(attrib_list[index + 1]);
}
}
attributes[count] = EGL_NONE;
return reinterpret_cast<EGLSyncKHR>(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<EGLSync>(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<EGLSync>(sync), flags,
static_cast<EGLTime>(timeout));
}
MOBILEGL_EGL_API EGLBoolean eglWaitSyncKHR(EGLDisplay dpy, EGLSyncKHR sync, EGLint flags) {
return MobileGL::MG_Impl::EGLImpl::WaitSync(dpy, reinterpret_cast<EGLSync>(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<EGLSync>(sync), attribute, &answered)) {
return EGL_FALSE;
}
if (value != nullptr) {
*value = static_cast<EGLint>(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<EGLDeviceEXT>(&g_deviceToken);
return EGL_TRUE;
}
MOBILEGL_EGL_API EGLBoolean eglQueryDeviceAttribEXT(EGLDeviceEXT device, EGLint attribute, EGLAttrib* value) {
if (device != reinterpret_cast<EGLDeviceEXT>(&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<EGLAttrib>("/dev/dri/renderD128");
return EGL_TRUE;
default:
return EGL_FALSE;
}
}
MOBILEGL_EGL_API const char* eglQueryDeviceStringEXT(EGLDeviceEXT device, EGLint name) {
if (device != reinterpret_cast<EGLDeviceEXT>(&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<EGLAttrib>(&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) {
const MobileGL::MG_Impl::EGLImpl::StreamLockScope mglStreamLock;
MGLOG_D("eglCreatePlatformPixmapSurface(dpy=%p, config=%p, native_pixmap=%p, attrib_list=%p)", dpy, config,
native_pixmap, attrib_list);
return MobileGL::MG_Impl::EGLImpl::CreatePlatformPixmapSurface(dpy, config, native_pixmap, attrib_list);
}
MOBILEGL_EGL_API EGLBoolean eglWaitSync(EGLDisplay dpy, EGLSync sync, EGLint flags) {
const MobileGL::MG_Impl::EGLImpl::StreamLockScope mglStreamLock;
MGLOG_D("eglWaitSync(dpy=%p, sync=%p, flags=%d)", dpy, sync, flags);
return MobileGL::MG_Impl::EGLImpl::WaitSync(dpy, sync, flags);
}
@@ -28,27 +28,31 @@
#include <Includes.h>
#include <glvnd/libeglabi.h>
// EGLImageKHR, for the KHR spellings the entry-point table below answers: Includes.h brings in the
// core egl.h only.
#include <EGL/eglext.h>
#include "../EGLImpl.h"
#include "../EGLPlatformExtensions.h"
#include <Init.h>
#include <mutex>
// Defined in Definitions.cpp; eglext.h declares them only under EGL_EGLEXT_PROTOTYPES.
extern "C" EGLImage eglCreateImageKHR(EGLDisplay dpy, EGLContext ctx, EGLenum target, EGLClientBuffer buffer,
// 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, EGLImage image);
extern "C" EGLBoolean eglSwapBuffersWithDamageKHR(EGLDisplay dpy, EGLSurface draw, const EGLint* rects,
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 draw, const EGLint* rects,
extern "C" EGLBoolean eglSwapBuffersWithDamageEXT(EGLDisplay dpy, EGLSurface surface, const EGLint* rects,
EGLint n_rects);
extern "C" EGLBoolean eglSetDamageRegionKHR(EGLDisplay dpy, EGLSurface surface, EGLint* rects, EGLint n_rects);
extern "C" EGLBoolean eglQueryDmaBufFormatsEXT(EGLDisplay dpy, EGLint max_formats, EGLint* formats,
EGLint* num_formats);
extern "C" EGLBoolean eglQueryDmaBufModifiersEXT(EGLDisplay dpy, EGLint format, EGLint max_modifiers,
EGLuint64KHR* modifiers, EGLBoolean* external_only,
EGLint* num_modifiers);
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;
@@ -68,27 +72,14 @@ namespace {
return MG_Impl::EGLImpl::QueryString(dpy, name);
}
// DECLINING IS HOW THIS VENDOR STEPS ASIDE. glvnd asks its vendors for a display in order and
// takes the first that answers, so a vendor installed ahead of the system's own one must answer
// EGL_NO_DISPLAY whenever it cannot actually serve: no MobileGL server reachable (asked before
// the bring-up, so an absent server costs one refused connect rather than the bring-up's wait),
// or a split session that was tried and did not come up. The application then gets the next
// vendor's display instead of one of ours that fails at eglInitialize.
EGLDisplay EGLAPIENTRY VendorGetPlatformDisplay(EGLenum platform, void* native_display,
const EGLAttrib* attrib_list) {
if (!MobileGL::ImplementationAvailable()) {
return EGL_NO_DISPLAY;
}
// EGL_NONE means the application called eglGetDisplay(EGL_DEFAULT_DISPLAY): the vendor is
// being asked to name its own default display.
const EGLDisplay display = platform == EGL_NONE
? MG_Impl::EGLImpl::GetDisplay(EGL_DEFAULT_DISPLAY)
: MG_Impl::EGLImpl::GetPlatformDisplay(platform, native_display, attrib_list);
// The bring-up above may itself have failed (a server that refused this client).
if (display != EGL_NO_DISPLAY && !MobileGL::ImplementationAvailable()) {
return EGL_NO_DISPLAY;
if (platform == EGL_NONE) {
return MG_Impl::EGLImpl::GetDisplay(EGL_DEFAULT_DISPLAY);
}
return display;
return MG_Impl::EGLImpl::GetPlatformDisplay(platform, native_display, attrib_list);
}
EGLBoolean EGLAPIENTRY VendorGetSupportsAPI(EGLenum api) {
@@ -127,16 +118,8 @@ namespace {
const char* DrmRenderNode() {
// MOBILEGL_DEVICE_DRM_NODE names another node: a machine with more than one GPU, or a test
// that wants the mismatch refused rather than papered over.
// Read like every other setting (environment over the system configuration), once: the
// answer is handed out as a pointer.
static std::once_flag once;
static String node;
std::call_once(once, [] {
if (!MG_ConfigLoader::LookupSetting("MOBILEGL_DEVICE_DRM_NODE", node) || node.empty()) {
node = "/dev/dri/renderD128";
}
});
return node.c_str();
const char* configured = std::getenv("MOBILEGL_DEVICE_DRM_NODE");
return (configured != nullptr && configured[0] != '\0') ? configured : "/dev/dri/renderD128";
}
// One device, one identity. A pointer to a private object rather than a number, so that a
@@ -148,12 +131,6 @@ namespace {
if (num_devices == nullptr) {
return EGL_FALSE;
}
// No server, no device: a device this vendor could never open a display on would only lead
// the caller to it (glvnd merges every vendor's list; an error here would fail the merge).
if (!MobileGL::ImplementationAvailable()) {
*num_devices = 0;
return EGL_TRUE;
}
*num_devices = 1;
if (devices != nullptr && max_devices >= 1) {
devices[0] = reinterpret_cast<EGLDeviceEXT>(&g_deviceToken);
@@ -162,13 +139,20 @@ namespace {
}
EGLBoolean EGLAPIENTRY VendorQueryDeviceAttribEXT(EGLDeviceEXT device, EGLint attribute, EGLAttrib* value) {
MGLOG_I("vendor eglQueryDeviceAttribEXT(device=%p, attribute=0x%04x)", static_cast<void*>(device),
static_cast<unsigned>(attribute));
if (device != reinterpret_cast<EGLDeviceEXT>(&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<EGLAttrib>(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<EGLAttrib>("/dev/dri/renderD128");
return EGL_TRUE;
default:
return EGL_FALSE;
@@ -176,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<void*>(device),
static_cast<unsigned>(name));
if (device != reinterpret_cast<EGLDeviceEXT>(&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;
}
@@ -266,15 +257,31 @@ namespace {
{"eglWaitSync", reinterpret_cast<void*>(eglWaitSync)},
{"eglCreateImage", reinterpret_cast<void*>(eglCreateImage)},
{"eglDestroyImage", reinterpret_cast<void*>(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<void*>(eglCreateImageKHR)},
{"eglDestroyImageKHR", reinterpret_cast<void*>(eglDestroyImageKHR)},
{"eglQueryDmaBufFormatsEXT", reinterpret_cast<void*>(eglQueryDmaBufFormatsEXT)},
{"eglSwapBuffersWithDamageKHR", reinterpret_cast<void*>(eglSwapBuffersWithDamageKHR)},
{"eglSwapBuffersWithDamageEXT", reinterpret_cast<void*>(eglSwapBuffersWithDamageEXT)},
{"eglSetDamageRegionKHR", reinterpret_cast<void*>(eglSetDamageRegionKHR)},
{"eglQueryDmaBufModifiersEXT", reinterpret_cast<void*>(eglQueryDmaBufModifiersEXT)},
{"eglCreatePlatformWindowSurface", reinterpret_cast<void*>(eglCreatePlatformWindowSurface)},
{"eglCreatePlatformPixmapSurface", reinterpret_cast<void*>(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<void*>(eglCreatePlatformWindowSurface)},
{"eglCreatePlatformPixmapSurfaceEXT", reinterpret_cast<void*>(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<void*>(eglGetDisplay)},
@@ -292,6 +299,15 @@ namespace {
{"eglQueryDeviceAttribEXT", reinterpret_cast<void*>(VendorQueryDeviceAttribEXT)},
{"eglQueryDeviceStringEXT", reinterpret_cast<void*>(VendorQueryDeviceStringEXT)},
{"eglQueryDisplayAttribEXT", reinterpret_cast<void*>(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<void*>(eglSwapBuffersWithDamageKHR)},
{"eglSwapBuffersWithDamageEXT", reinterpret_cast<void*>(eglSwapBuffersWithDamageEXT)},
{"eglCreateSyncKHR", reinterpret_cast<void*>(eglCreateSyncKHR)},
{"eglDestroySyncKHR", reinterpret_cast<void*>(eglDestroySyncKHR)},
{"eglClientWaitSyncKHR", reinterpret_cast<void*>(eglClientWaitSyncKHR)},
{"eglWaitSyncKHR", reinterpret_cast<void*>(eglWaitSyncKHR)},
{"eglGetSyncAttribKHR", reinterpret_cast<void*>(eglGetSyncAttribKHR)},
{"eglDebugMessageControlKHR", reinterpret_cast<void*>(VendorDebugMessageControlKHR)},
{"eglQueryDebugKHR", reinterpret_cast<void*>(VendorQueryDebugKHR)},
{"eglLabelObjectKHR", reinterpret_cast<void*>(VendorLabelObjectKHR)},
@@ -333,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<void*>(MG_Impl::EGLImpl::GetProcAddress(procName));
}
} // namespace
extern "C" MOBILEGL_EGL_API EGLBoolean __egl_Main(uint32_t version, const __EGLapiExports* exports,
@@ -360,10 +388,7 @@ extern "C" MOBILEGL_EGL_API EGLBoolean __egl_Main(uint32_t version, const __EGLa
imports->getDispatchAddress = VendorGetDispatchAddress;
imports->setDispatchIndex = VendorSetDispatchIndex;
// DEBUG, not INFO: as the system's vendor this runs in every EGL process, including the many
// that end up served by another vendor, and the first line a process logs opens (and
// truncates) its log file - one it may share with the process that launched it.
MGLOG_D("glvnd vendor: MobileGL is serving EGL through libglvnd (ABI %u.%u, platforms: %s)",
MGLOG_I("glvnd vendor: MobileGL is serving EGL through libglvnd (ABI %u.%u, platforms: %s)",
static_cast<unsigned>(EGL_VENDOR_ABI_MAJOR_VERSION), static_cast<unsigned>(EGL_VENDOR_ABI_MINOR_VERSION),
kPlatformExtensions);
return EGL_TRUE;
+66 -403
View File
@@ -10,8 +10,6 @@
#if MOBILEGL_WAYLAND_WINDOWS
#include "EGLImpl.h"
#include <MG_Backend/BackendObjects.h>
#include <MG_Impl/GLImpl/Buffer/GL_Buffer.h>
#include <MG_Impl/GLImpl/Framebuffer/GL_Framebuffer.h>
#include <MG_Impl/GLImpl/Getter/GL_Getter.h>
@@ -25,71 +23,15 @@
#include <fcntl.h>
#include <mutex>
#include <sys/mman.h>
#include <sys/uio.h>
#include <unistd.h>
namespace MobileGL::MG_Impl::EGLImpl {
void ReadBackFrameBGRA(EGLint width, EGLint height, Vector<Uint8>& scratch, Uint8* dst, SizeT dstStride) {
namespace GL = MG_Impl::GLImpl;
GLint readFramebuffer = 0, packBuffer = 0, alignment = 4, rowLength = 0, skipRows = 0, skipPixels = 0;
GL::GetIntegerv(GL_READ_FRAMEBUFFER_BINDING, &readFramebuffer);
GL::GetIntegerv(GL_PIXEL_PACK_BUFFER_BINDING, &packBuffer);
GL::GetIntegerv(GL_PACK_ALIGNMENT, &alignment);
GL::GetIntegerv(GL_PACK_ROW_LENGTH, &rowLength);
GL::GetIntegerv(GL_PACK_SKIP_ROWS, &skipRows);
GL::GetIntegerv(GL_PACK_SKIP_PIXELS, &skipPixels);
if (readFramebuffer != 0) GL::BindFramebuffer(GL_READ_FRAMEBUFFER, 0);
if (packBuffer != 0) GL::BindBuffer(GL_PIXEL_PACK_BUFFER, 0);
GL::PixelStorei(GL_PACK_ALIGNMENT, 4);
GL::PixelStorei(GL_PACK_ROW_LENGTH, 0);
GL::PixelStorei(GL_PACK_SKIP_ROWS, 0);
GL::PixelStorei(GL_PACK_SKIP_PIXELS, 0);
const SizeT rowBytes = static_cast<SizeT>(width) * 4;
scratch.resize(rowBytes * static_cast<SizeT>(height));
GL::ReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, scratch.data());
GL::PixelStorei(GL_PACK_ALIGNMENT, alignment);
GL::PixelStorei(GL_PACK_ROW_LENGTH, rowLength);
GL::PixelStorei(GL_PACK_SKIP_ROWS, skipRows);
GL::PixelStorei(GL_PACK_SKIP_PIXELS, skipPixels);
if (packBuffer != 0) GL::BindBuffer(GL_PIXEL_PACK_BUFFER, static_cast<GLuint>(packBuffer));
if (readFramebuffer != 0) GL::BindFramebuffer(GL_READ_FRAMEBUFFER, static_cast<GLuint>(readFramebuffer));
for (EGLint y = 0; y < height; ++y) {
const Uint8* src = scratch.data() + static_cast<SizeT>(height - 1 - y) * rowBytes;
Uint8* row = dst + static_cast<SizeT>(y) * dstStride;
for (EGLint x = 0; x < width; ++x) {
row[x * 4 + 0] = src[x * 4 + 2];
row[x * 4 + 1] = src[x * 4 + 1];
row[x * 4 + 2] = src[x * 4 + 0];
row[x * 4 + 3] = src[x * 4 + 3];
}
}
}
} // namespace MobileGL::MG_Impl::EGLImpl
namespace MobileGL::MG_Impl::EGLImpl::Wayland {
namespace {
// libwayland-client's objects are opaque here: everything goes through wl_proxy_* and the
// interface descriptions, and nothing reads a field of a proxy.
// libwayland-client's types are opaque here: everything goes through wl_proxy_* and the
// exported interface descriptions, and nothing reads a field of either.
struct wl_proxy;
struct wl_event_queue;
// wayland-util.h's protocol descriptors. libwayland-client exports the core protocol's;
// linux-dmabuf's are written out below (LinuxDmabuf), as its generated code would.
struct wl_interface;
struct wl_message {
const char* name;
const char* signature;
const wl_interface** types;
};
struct wl_interface {
const char* name;
int version;
int method_count;
const wl_message* methods;
int event_count;
const wl_message* events;
};
struct wl_event_queue;
// wayland-egl-backend.h, WL_EGL_WINDOW_VERSION 3: the struct libwayland-egl allocates for
// wl_egl_window_create and the driver reads. The ABI is versioned by its first word.
@@ -124,18 +66,6 @@ namespace MobileGL::MG_Impl::EGLImpl::Wayland {
// B, G, R, A for both (little-endian 0xAARRGGBB).
constexpr uint32_t kShmFormatArgb8888 = 0;
constexpr uint32_t kShmFormatXrgb8888 = 1;
// linux-dmabuf (linux-dmabuf-v1.xml) request opcodes.
constexpr uint32_t kDmabufDestroy = 0;
constexpr uint32_t kDmabufCreateParams = 1;
constexpr uint32_t kParamsDestroy = 0;
constexpr uint32_t kParamsAdd = 1;
constexpr uint32_t kParamsCreate = 2;
// The highest linux-dmabuf version spoken here: 4 adds feedback objects this never asks for.
constexpr uint32_t kDmabufMaxVersion = 3;
// DRM fourccs of the server's shared images: R, G, B, A in memory - GL's RGBA8, so the
// frame lands in the buffer with no reordering.
constexpr uint32_t kDrmFormatAbgr8888 = 0x34324241u; // 'AB24'
constexpr uint32_t kDrmFormatXbgr8888 = 0x34324258u; // 'XB24'
struct Api {
Bool loaded = false;
@@ -211,90 +141,6 @@ namespace MobileGL::MG_Impl::EGLImpl::Wayland {
// The compositor is done with a buffer: it may be drawn into again.
void OnBufferRelease(void* data, wl_proxy*) { static_cast<ShmBuffer*>(data)->busy = false; }
void (*const kBufferListener[])(void) = {reinterpret_cast<void (*)(void)>(&OnBufferRelease)};
// zwp_linux_dmabuf_v1 and zwp_linux_buffer_params_v1 as their generated protocol code
// describes them (version 3: what is bound here at most). A request's `types` name the
// interface of each new_id/object argument, null for every other argument.
struct LinuxDmabufProtocol {
const wl_interface* createParamsTypes[1] = {};
const wl_interface* noObjectTypes[6] = {};
const wl_interface* createImmedTypes[5] = {};
const wl_interface* createdTypes[1] = {};
wl_message dmabufRequests[2] = {};
wl_message dmabufEvents[2] = {};
wl_message paramsRequests[4] = {};
wl_message paramsEvents[2] = {};
wl_interface dmabuf = {};
wl_interface params = {};
};
// Null when libwayland-client is not usable. Filled once: the wl_buffer interface it
// refers to is libwayland-client's, known only after it is loaded.
const LinuxDmabufProtocol* LinuxDmabuf() {
static LinuxDmabufProtocol protocol;
static std::once_flag once;
static Bool ready = false;
std::call_once(once, [] {
const Api& api = WaylandApi();
if (!api.loaded) return;
LinuxDmabufProtocol& p = protocol;
p.createParamsTypes[0] = &p.params;
p.createImmedTypes[0] = api.bufferInterface;
p.createdTypes[0] = api.bufferInterface;
p.dmabufRequests[0] = {"destroy", "", p.noObjectTypes};
p.dmabufRequests[1] = {"create_params", "n", p.createParamsTypes};
p.dmabufEvents[0] = {"format", "u", p.noObjectTypes};
p.dmabufEvents[1] = {"modifier", "3uuu", p.noObjectTypes};
p.paramsRequests[0] = {"destroy", "", p.noObjectTypes};
p.paramsRequests[1] = {"add", "huuuuu", p.noObjectTypes};
p.paramsRequests[2] = {"create", "iiuu", p.noObjectTypes};
p.paramsRequests[3] = {"create_immed", "2niiuu", p.createImmedTypes};
p.paramsEvents[0] = {"created", "n", p.createdTypes};
p.paramsEvents[1] = {"failed", "", p.noObjectTypes};
p.dmabuf = {"zwp_linux_dmabuf_v1", static_cast<int>(kDmabufMaxVersion), 2, p.dmabufRequests, 2,
p.dmabufEvents};
p.params = {"zwp_linux_buffer_params_v1", static_cast<int>(kDmabufMaxVersion), 4, p.paramsRequests,
2, p.paramsEvents};
ready = true;
});
return ready ? &protocol : nullptr;
}
// The format table a compositor announces is not consulted: the server's images are one
// of the two formats every linux-dmabuf compositor takes, and a refusal is answered by
// `failed` below anyway.
void OnDmabufFormat(void*, wl_proxy*, uint32_t) {}
void OnDmabufModifier(void*, wl_proxy*, uint32_t, uint32_t, uint32_t) {}
void (*const kDmabufListener[])(void) = {reinterpret_cast<void (*)(void)>(&OnDmabufFormat),
reinterpret_cast<void (*)(void)>(&OnDmabufModifier)};
// The answer to a `create`: the new wl_buffer, or `failed`.
struct ParamsOutcome {
wl_proxy* buffer = nullptr;
Bool failed = false;
};
void OnParamsCreated(void* data, wl_proxy*, wl_proxy* buffer) { static_cast<ParamsOutcome*>(data)->buffer = buffer; }
void OnParamsFailed(void* data, wl_proxy*) { static_cast<ParamsOutcome*>(data)->failed = true; }
void (*const kParamsListener[])(void) = {reinterpret_cast<void (*)(void)>(&OnParamsCreated),
reinterpret_cast<void (*)(void)>(&OnParamsFailed)};
// One server shared image, shown to the compositor as a linux-dmabuf wl_buffer.
struct DmabufBuffer {
wl_proxy* buffer = nullptr;
Uint64 imageId = 0;
EGLint width = 0;
EGLint height = 0;
Bool busy = false;
};
void OnDmabufBufferRelease(void* data, wl_proxy*) { static_cast<DmabufBuffer*>(data)->busy = false; }
void (*const kDmabufBufferListener[])(void) = {reinterpret_cast<void (*)(void)>(&OnDmabufBufferRelease)};
// MOBILEGL_WAYLAND_DMABUF=0 keeps every window on wl_shm.
Bool DmabufPresentationAllowed() {
const char* value = std::getenv("MOBILEGL_WAYLAND_DMABUF");
return value == nullptr || std::strcmp(value, "0") != 0;
}
} // namespace
struct WindowSurface::Impl {
@@ -311,28 +157,9 @@ namespace MobileGL::MG_Impl::EGLImpl::Wayland {
ShmBuffer buffers[3];
Vector<Uint8> scratch;
// THE LINUX-DMABUF PATH. With a backend that has shared images, the frame never leaves
// the GPU: each buffer is a server-allocated image exported as a dma-buf, the server
// copies the frame into it at the swap, and the compositor (a client of the same server)
// samples the very same image. wl_shm stays bound as the fallback.
Bool dmabufWanted = false;
wl_proxy* dmabuf = nullptr;
Bool useDmabuf = false;
uint32_t fourcc = kDrmFormatXbgr8888;
DmabufBuffer dmabufBuffers[3];
// Per shared image, what the frames written into the other images changed since this one
// was last written: what its next write has to bring over besides the frame's own damage.
MG_Util::Damage::BufferDamageTracker dmabufDamage{3};
// The size of the last buffer committed: a commit at another size (or the first) damages
// the whole buffer, whatever the frame says.
EGLint committedWidth = 0;
EGLint committedHeight = 0;
~Impl() {
const Api& api = WaylandApi();
for (auto& buffer : buffers) Release(buffer);
for (auto& buffer : dmabufBuffers) Release(buffer);
if (dmabuf) api.marshalFlags(dmabuf, kDmabufDestroy, nullptr, api.getVersion(dmabuf), kMarshalFlagDestroy);
// Neither wl_shm (version 1) nor wl_registry has a destroy request: the proxies go
// on this side only.
if (shm) api.destroy(shm);
@@ -419,163 +246,14 @@ namespace MobileGL::MG_Impl::EGLImpl::Wayland {
if (api.dispatchQueue(display, queue) < 0) return nullptr;
}
}
// The wl_buffer goes before the image: the compositor's own import holds the image for
// as long as it still shows it.
void Release(DmabufBuffer& buffer) {
const Api& api = WaylandApi();
if (buffer.buffer) api.marshalFlags(buffer.buffer, kBufferDestroy, nullptr, api.getVersion(buffer.buffer),
kMarshalFlagDestroy);
if (buffer.imageId != 0) {
if (auto* backendObject = MG_Backend::pActiveBackendObject.get()) {
(void)backendObject->ReleaseSharedImage(buffer.imageId);
}
}
buffer = DmabufBuffer{};
}
// A shared image of the window's size, as a wl_buffer. `create` and a round trip, never
// create_immed: a compositor that cannot import the buffer answers create_immed with a
// protocol error, fatal to the application's whole connection, where `create` answers
// `failed` and the window simply stays on wl_shm.
Bool Allocate(DmabufBuffer& buffer) {
const Api& api = WaylandApi();
const LinuxDmabufProtocol* protocol = LinuxDmabuf();
Release(buffer);
auto* backendObject = MG_Backend::pActiveBackendObject.get();
if (protocol == nullptr || dmabuf == nullptr || backendObject == nullptr) return false;
MG_Backend::SharedImageExport image;
if (!backendObject->AllocateSharedImage(static_cast<Uint32>(width), static_cast<Uint32>(height), fourcc,
&image)) {
MGLOG_E("Wayland: the server allocated no %dx%d shared image", width, height);
return false;
}
const auto dropImage = [&] {
if (image.Fd >= 0) close(image.Fd);
(void)backendObject->ReleaseSharedImage(image.Id);
};
if (image.Fd < 0 || image.Width != static_cast<Uint32>(width) ||
image.Height != static_cast<Uint32>(height)) {
MGLOG_E("Wayland: a %dx%d shared image came back as %ux%u (fd %d)", width, height, image.Width,
image.Height, image.Fd);
dropImage();
return false;
}
const uint32_t version = api.getVersion(dmabuf);
wl_proxy* params = api.marshalFlags(dmabuf, kDmabufCreateParams, &protocol->params, version, 0, nullptr);
if (params == nullptr) {
dropImage();
return false;
}
ParamsOutcome outcome;
api.addListener(params, const_cast<void (**)(void)>(kParamsListener), &outcome);
// The descriptor is duplicated into the request, so it is closed below either way.
api.marshalFlags(params, kParamsAdd, nullptr, version, 0, image.Fd, 0u, image.Offset, image.Stride,
static_cast<uint32_t>(image.Modifier >> 32),
static_cast<uint32_t>(image.Modifier & 0xffffffffu));
api.marshalFlags(params, kParamsCreate, nullptr, version, 0, width, height, fourcc, 0u);
const Bool settled = api.roundtripQueue(display, queue) >= 0;
api.marshalFlags(params, kParamsDestroy, nullptr, version, kMarshalFlagDestroy);
wl_proxy* wlBuffer = outcome.buffer;
if (!settled || outcome.failed || wlBuffer == nullptr) {
MGLOG_E("Wayland: the compositor refused a %dx%d linux-dmabuf buffer", width, height);
if (wlBuffer)
api.marshalFlags(wlBuffer, kBufferDestroy, nullptr, api.getVersion(wlBuffer), kMarshalFlagDestroy);
dropImage();
return false;
}
close(image.Fd);
// A new image holds nothing of any frame yet.
dmabufDamage.Invalidate(static_cast<SizeT>(&buffer - dmabufBuffers));
buffer.buffer = wlBuffer;
buffer.imageId = image.Id;
buffer.width = width;
buffer.height = height;
buffer.busy = false;
api.addListener(wlBuffer, const_cast<void (**)(void)>(kDmabufBufferListener), &buffer);
return true;
}
// As NextFree, over the shared images.
DmabufBuffer* NextFreeDmabuf() {
const Api& api = WaylandApi();
for (;;) {
if (api.dispatchQueuePending(display, queue) < 0) return nullptr;
for (auto& buffer : dmabufBuffers) {
if (buffer.buffer == nullptr || buffer.busy) continue;
if (buffer.width != width || buffer.height != height) {
if (!Allocate(buffer)) return nullptr;
}
return &buffer;
}
for (auto& buffer : dmabufBuffers) {
if (buffer.buffer == nullptr) return Allocate(buffer) ? &buffer : nullptr;
}
if (api.dispatchQueue(display, queue) < 0) return nullptr;
}
}
// The rest of this window's life is wl_shm's.
void FallBackToShm() {
for (auto& buffer : dmabufBuffers) Release(buffer);
dmabufDamage.InvalidateAll();
useDmabuf = false;
}
// `wlBuffer` becomes the window's content: attach, damage, commit. `damage` is the frame's
// (GL window coordinates); a buffer's rows run top-down, so each rectangle is flipped. A
// compositor without damage_buffer (wl_surface < 4), a new size or the first commit is
// damaged whole.
void Commit(wl_proxy* wlBuffer, const MG_Util::Damage::Region& damage) {
const Api& api = WaylandApi();
wl_proxy* surface = window->surface;
const uint32_t surfaceVersion = api.getVersion(surface);
api.marshalFlags(surface, kSurfaceAttach, nullptr, surfaceVersion, 0, wlBuffer, window->dx, window->dy);
const Bool whole = damage.IsFull() || surfaceVersion < 4 || committedWidth != width ||
committedHeight != height || window->dx != 0 || window->dy != 0;
if (!whole) {
for (const MG_Util::Damage::Rect& rect : damage.FlippedY(height).Rects()) {
api.marshalFlags(surface, kSurfaceDamageBuffer, nullptr, surfaceVersion, 0, rect.X, rect.Y,
rect.Width, rect.Height);
}
} else if (surfaceVersion >= 4) {
api.marshalFlags(surface, kSurfaceDamageBuffer, nullptr, surfaceVersion, 0, 0, 0, width, height);
} else {
api.marshalFlags(surface, kSurfaceDamage, nullptr, surfaceVersion, 0, 0, 0, width, height);
}
committedWidth = width;
committedHeight = height;
api.marshalFlags(surface, kSurfaceCommit, nullptr, surfaceVersion, 0);
window->attached_width = width;
window->attached_height = height;
window->dx = 0;
window->dy = 0;
api.flush(display);
}
};
namespace {
void OnRegistryGlobal(void* data, wl_proxy* registry, uint32_t name, const char* interface,
uint32_t version) {
void OnRegistryGlobal(void* data, wl_proxy* registry, uint32_t name, const char* interface, uint32_t) {
auto* impl = static_cast<WindowSurface::Impl*>(data);
if (impl->shm != nullptr || std::strcmp(interface, "wl_shm") != 0) return;
const Api& api = WaylandApi();
if (impl->shm == nullptr && std::strcmp(interface, "wl_shm") == 0) {
impl->shm =
api.marshalFlags(registry, kRegistryBind, api.shmInterface, 1, 0, name, "wl_shm", 1u, nullptr);
return;
}
if (impl->dmabufWanted && impl->dmabuf == nullptr &&
std::strcmp(interface, "zwp_linux_dmabuf_v1") == 0) {
const LinuxDmabufProtocol* protocol = LinuxDmabuf();
if (protocol == nullptr) return;
const uint32_t bindVersion = std::min(version, kDmabufMaxVersion);
impl->dmabuf = api.marshalFlags(registry, kRegistryBind, &protocol->dmabuf, bindVersion, 0, name,
"zwp_linux_dmabuf_v1", bindVersion, nullptr);
if (impl->dmabuf != nullptr) {
api.addListener(impl->dmabuf, const_cast<void (**)(void)>(kDmabufListener), impl);
}
}
impl->shm = api.marshalFlags(registry, kRegistryBind, api.shmInterface, 1, 0, name, "wl_shm", 1u, nullptr);
}
void OnRegistryGlobalRemove(void*, wl_proxy*, uint32_t) {}
void (*const kRegistryListener[])(void) = {reinterpret_cast<void (*)(void)>(&OnRegistryGlobal),
@@ -585,32 +263,12 @@ namespace MobileGL::MG_Impl::EGLImpl::Wayland {
void OnWindowDestroyed(void* data) { static_cast<WindowSurface::Impl*>(data)->window = nullptr; }
} // namespace
namespace {
// Copies `size` bytes at `address` of this process, or answers false where nothing is
// mapped - the kernel does the reading, so a wild pointer is an error code, not a fault.
Bool ReadOwnMemory(const void* address, void* out, SizeT size) {
iovec local{out, size};
iovec remote{const_cast<void*>(address), size};
return process_vm_readv(getpid(), &local, 1, &remote, 1, 0) == static_cast<ssize_t>(size);
}
} // namespace
Bool IsWaylandDisplay(Uint64 nativeDisplay, EGLenum platform) {
if (platform == kPlatformWayland) return true;
if (nativeDisplay == 0 || (platform != EGL_NONE && platform != 0)) return false;
const Api& api = WaylandApi();
if (!api.loaded) return false;
const void* interface = *reinterpret_cast<const void* const*>(static_cast<uintptr_t>(nativeDisplay));
if (interface == api.displayInterface) return true;
// AN APPLICATION WITH ITS OWN COPY OF LIBWAYLAND-CLIENT (Chromium links one in statically)
// has its own wl_display_interface, at its own address. The interface is still the
// protocol's: a wl_interface whose first member names it "wl_display". Whatever else the
// first word of a native display is (a gbm_device's is a function address), the probe
// only reads through the kernel.
const char* name = nullptr;
char text[sizeof("wl_display")] = {};
return interface != nullptr && ReadOwnMemory(interface, &name, sizeof(name)) && name != nullptr &&
ReadOwnMemory(name, text, sizeof(text)) && std::memcmp(text, "wl_display", sizeof(text)) == 0;
return *reinterpret_cast<const void* const*>(static_cast<uintptr_t>(nativeDisplay)) == api.displayInterface;
}
Bool IsWaylandWindow(const void* window) {
@@ -644,8 +302,6 @@ namespace MobileGL::MG_Impl::EGLImpl::Wayland {
impl->width = width;
impl->height = height;
impl->format = hasAlpha ? kShmFormatArgb8888 : kShmFormatXrgb8888;
impl->fourcc = hasAlpha ? kDrmFormatAbgr8888 : kDrmFormatXbgr8888;
impl->dmabufWanted = DmabufPresentationAllowed() && SharedImagesAvailable();
// A queue of this surface's own, so the application's dispatching never sees these events
// and this never dispatches the application's.
impl->queue = api.createQueue(wlDisplay);
@@ -661,73 +317,80 @@ namespace MobileGL::MG_Impl::EGLImpl::Wayland {
MGLOG_E("Wayland: the compositor offers no wl_shm; a window surface cannot be presented");
return nullptr;
}
// The first shared image is made here, so a server or compositor that cannot do the
// dma-buf path is found out before the window shows anything, and the window starts on
// wl_shm instead.
if (impl->dmabuf != nullptr) impl->useDmabuf = impl->Allocate(impl->dmabufBuffers[0]);
if (!impl->useDmabuf && impl->dmabuf != nullptr) {
api.marshalFlags(impl->dmabuf, kDmabufDestroy, nullptr, api.getVersion(impl->dmabuf), kMarshalFlagDestroy);
impl->dmabuf = nullptr;
}
impl->window->driver_private = impl.get();
impl->window->destroy_window_callback = &OnWindowDestroyed;
if (impl->useDmabuf) {
MGLOG_I("Wayland: window surface %dx%d presented through linux-dmabuf shared images (%s)", width, height,
hasAlpha ? "ABGR8888" : "XBGR8888");
} else {
MGLOG_I("Wayland: window surface %dx%d presented through wl_shm (%s)", width, height,
hasAlpha ? "ARGB8888" : "XRGB8888");
}
MGLOG_I("Wayland: window surface %dx%d presented through wl_shm (%s)", width, height,
hasAlpha ? "ARGB8888" : "XRGB8888");
return UniquePtr<WindowSurface>(new WindowSurface(std::move(impl)));
}
Bool WindowSurface::TakeResize(EGLint* width, EGLint* height) {
Impl& impl = *m_impl;
if (impl.window == nullptr || impl.window->width <= 0 || impl.window->height <= 0) return false;
if (impl.window->width == impl.width && impl.window->height == impl.height) return false;
impl.width = impl.window->width;
impl.height = impl.window->height;
*width = impl.width;
*height = impl.height;
return true;
}
Bool WindowSurface::Present(const MG_Util::Damage::Region& damage) {
Bool WindowSurface::Present() {
Impl& impl = *m_impl;
if (impl.window == nullptr) return false;
if (impl.useDmabuf) {
// The server copies the frame into the image GPU-side, top row first - a wl_buffer's
// first row - and answers once the copy has completed, so the compositor reads a
// finished frame. Only where the image differs from the frame: the rest of it already
// is the frame.
DmabufBuffer* buffer = impl.NextFreeDmabuf();
auto* backendObject = MG_Backend::pActiveBackendObject.get();
if (buffer != nullptr && backendObject != nullptr) {
const SizeT index = static_cast<SizeT>(buffer - impl.dmabufBuffers);
const MG_Util::Damage::Region copy = impl.dmabufDamage.TakeForWrite(index, damage, impl.width, impl.height);
if (backendObject->PresentToSharedImage(buffer->imageId, copy)) {
impl.Commit(buffer->buffer, damage);
buffer->busy = true;
return true;
}
}
MGLOG_E_ONCE("Wayland: a frame could not be presented through a linux-dmabuf shared image; the window "
"falls back to wl_shm");
impl.FallBackToShm();
}
const Api& api = WaylandApi();
ShmBuffer* buffer = impl.NextFree();
if (buffer == nullptr) {
MGLOG_E_ONCE("Wayland: no wl_shm buffer could be taken for the frame; it is not shown");
return false;
}
// The frame, out of the default framebuffer, through this library's own entry points: the
// application's read framebuffer, pack buffer and pack state are saved and put back, so
// the readback is invisible to it.
namespace GL = MG_Impl::GLImpl;
GLint readFramebuffer = 0, packBuffer = 0, alignment = 4, rowLength = 0, skipRows = 0, skipPixels = 0;
GL::GetIntegerv(GL_READ_FRAMEBUFFER_BINDING, &readFramebuffer);
GL::GetIntegerv(GL_PIXEL_PACK_BUFFER_BINDING, &packBuffer);
GL::GetIntegerv(GL_PACK_ALIGNMENT, &alignment);
GL::GetIntegerv(GL_PACK_ROW_LENGTH, &rowLength);
GL::GetIntegerv(GL_PACK_SKIP_ROWS, &skipRows);
GL::GetIntegerv(GL_PACK_SKIP_PIXELS, &skipPixels);
if (readFramebuffer != 0) GL::BindFramebuffer(GL_READ_FRAMEBUFFER, 0);
if (packBuffer != 0) GL::BindBuffer(GL_PIXEL_PACK_BUFFER, 0);
GL::PixelStorei(GL_PACK_ALIGNMENT, 4);
GL::PixelStorei(GL_PACK_ROW_LENGTH, 0);
GL::PixelStorei(GL_PACK_SKIP_ROWS, 0);
GL::PixelStorei(GL_PACK_SKIP_PIXELS, 0);
const SizeT rowBytes = static_cast<SizeT>(impl.width) * 4;
impl.scratch.resize(rowBytes * static_cast<SizeT>(impl.height));
GL::ReadPixels(0, 0, impl.width, impl.height, GL_RGBA, GL_UNSIGNED_BYTE, impl.scratch.data());
GL::PixelStorei(GL_PACK_ALIGNMENT, alignment);
GL::PixelStorei(GL_PACK_ROW_LENGTH, rowLength);
GL::PixelStorei(GL_PACK_SKIP_ROWS, skipRows);
GL::PixelStorei(GL_PACK_SKIP_PIXELS, skipPixels);
if (packBuffer != 0) GL::BindBuffer(GL_PIXEL_PACK_BUFFER, static_cast<GLuint>(packBuffer));
if (readFramebuffer != 0) GL::BindFramebuffer(GL_READ_FRAMEBUFFER, static_cast<GLuint>(readFramebuffer));
// GL's rows run bottom-up and RGBA; a wl_shm buffer's run top-down and B, G, R, A.
ReadBackFrameBGRA(impl.width, impl.height, impl.scratch, static_cast<Uint8*>(buffer->map),
static_cast<SizeT>(buffer->stride));
impl.Commit(buffer->buffer, MG_Util::Damage::Region::Full());
auto* dst = static_cast<Uint8*>(buffer->map);
for (EGLint y = 0; y < impl.height; ++y) {
const Uint8* src = impl.scratch.data() + static_cast<SizeT>(impl.height - 1 - y) * rowBytes;
Uint8* row = dst + static_cast<SizeT>(y) * static_cast<SizeT>(buffer->stride);
for (EGLint x = 0; x < impl.width; ++x) {
row[x * 4 + 0] = src[x * 4 + 2];
row[x * 4 + 1] = src[x * 4 + 1];
row[x * 4 + 2] = src[x * 4 + 0];
row[x * 4 + 3] = src[x * 4 + 3];
}
}
wl_proxy* surface = impl.window->surface;
const uint32_t surfaceVersion = api.getVersion(surface);
api.marshalFlags(surface, kSurfaceAttach, nullptr, surfaceVersion, 0, buffer->buffer, impl.window->dx,
impl.window->dy);
if (surfaceVersion >= 4) {
api.marshalFlags(surface, kSurfaceDamageBuffer, nullptr, surfaceVersion, 0, 0, 0, impl.width,
impl.height);
} else {
api.marshalFlags(surface, kSurfaceDamage, nullptr, surfaceVersion, 0, 0, 0, impl.width, impl.height);
}
api.marshalFlags(surface, kSurfaceCommit, nullptr, surfaceVersion, 0);
buffer->busy = true;
impl.window->attached_width = impl.width;
impl.window->attached_height = impl.height;
impl.window->dx = 0;
impl.window->dy = 0;
api.flush(impl.display);
return true;
}
} // namespace MobileGL::MG_Impl::EGLImpl::Wayland
+10 -38
View File
@@ -12,13 +12,7 @@
// the compositor shows is whatever wl_buffer the client attaches to that window's wl_surface. The
// pixels of a MobileGL frame are drawn where the backend is - on a split build, in another process
// on another OS - so a window surface here is a pbuffer the backend draws into, plus this: at every
// swap the frame is put into a wl_buffer and attached to the wl_surface.
//
// Two kinds of wl_buffer. With a backend that has shared images (a split client) and a compositor
// offering zwp_linux_dmabuf_v1, each buffer is a server-allocated image exported as a dma-buf and
// the server copies the frame into it GPU-side: nothing crosses the CPU. Otherwise - no such
// global, no shared images, a refused import, MOBILEGL_WAYLAND_DMABUF=0 - the frame is read back
// into a wl_shm buffer.
// swap the frame is read back and attached to the wl_surface as a wl_shm buffer.
//
// libwayland-client is loaded at run time (it is already in every Wayland client's process), so the
// library neither links it nor needs its headers to build.
@@ -34,16 +28,6 @@
#if MOBILEGL_WAYLAND_WINDOWS
#include <EGL/egl.h>
#include <MG_Util/Damage/Damage.h>
namespace MobileGL::MG_Impl::EGLImpl {
// The current context's default-framebuffer frame, `width` x `height`, written top-down in
// B, G, R, A byte order (a wl_shm ARGB8888 buffer and a 24/32-bit little-endian X image both
// hold that) to `dst`, one row every `dstStride` bytes. Through this library's own entry
// points: the application's read framebuffer, pack buffer and pack state are saved and put
// back, so the readback is invisible to it. `scratch` is the caller's, reused across frames.
void ReadBackFrameBGRA(EGLint width, EGLint height, Vector<Uint8>& scratch, Uint8* dst, SizeT dstStride);
} // namespace MobileGL::MG_Impl::EGLImpl
namespace MobileGL::MG_Impl::EGLImpl::Wayland {
// EGL_PLATFORM_WAYLAND_KHR and EGL_PLATFORM_WAYLAND_EXT are the same enum.
@@ -51,8 +35,7 @@ namespace MobileGL::MG_Impl::EGLImpl::Wayland {
// Whether a display is a Wayland one: asked for as EGL_PLATFORM_WAYLAND, or (eglGetDisplay with
// no platform) a native display that is a wl_display - recognised the way Mesa does, by its
// first word being libwayland-client's wl_display_interface (or, for an application with its
// own copy of libwayland, an interface named "wl_display").
// first word being libwayland-client's wl_display_interface.
Bool IsWaylandDisplay(Uint64 nativeDisplay, EGLenum platform);
// Whether `window` looks like a wl_egl_window this library can present to.
@@ -61,9 +44,9 @@ namespace MobileGL::MG_Impl::EGLImpl::Wayland {
// The size the application last gave its wl_egl_window.
Bool WindowSize(const void* window, EGLint* width, EGLint* height);
// One window surface's presentation: the dma-buf or shm buffers, the event queue they are
// dispatched on, and the readback scratch. Created for a wl_egl_window on a wl_display; null
// with the reason logged when libwayland-client or the compositor's wl_shm is not there.
// One window surface's presentation: the shm buffers, the event queue they are dispatched on,
// and the readback scratch. Created for a wl_egl_window on a wl_display; null with the reason
// logged when libwayland-client or the compositor's wl_shm is not there.
class WindowSurface {
public:
static UniquePtr<WindowSurface> Create(void* wlDisplay, void* wlEglWindow, EGLint width, EGLint height,
@@ -72,22 +55,11 @@ namespace MobileGL::MG_Impl::EGLImpl::Wayland {
WindowSurface(const WindowSurface&) = delete;
WindowSurface& operator=(const WindowSurface&) = delete;
// Puts the current context's default-framebuffer frame on the window: copied into a
// shared image (or read back into a wl_shm buffer, the application's read-framebuffer and
// pack state put back exactly as they were), then attach, damage, commit. A shared-image
// present that fails moves the window to wl_shm for good. False (logged) when the frame
// did not reach the window; the swap itself goes on regardless.
//
// `damage` (GL window coordinates, clipped to the window; Full = all of it) is what the
// frame changed. A shared image is copied only where it differs from the frame - the
// frame's damage and every frame's since that image was last written - and the surface is
// damaged only where the frame changed, flipped to the buffer's top-left origin.
Bool Present(const MG_Util::Damage::Region& damage);
// wl_egl_window_resize's effect, taken: true (with the new size) when the application gave
// its wl_egl_window a size this presentation is not at yet. The presentation adopts it -
// its next buffer is that size - and the caller resizes the drawable behind it.
Bool TakeResize(EGLint* width, EGLint* height);
// Reads the frame back out of the current context's default framebuffer and puts it on
// the window: attach, damage, commit. The application's read-framebuffer and pack state
// are put back exactly as they were. False (logged) when the frame did not reach the
// window; the swap itself goes on regardless.
Bool Present();
struct Impl;
+475 -19
View File
@@ -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 <MG_Remote/Client/DmaBufImport.h>
#include <Includes.h>
#include "../Buffer/GL_Buffer.h"
#include "../Getter/GL_Getter.h"
@@ -22,6 +25,12 @@
#include "../Sync/GL_Sync.h"
#include "../Debug/GL_Debug.h"
#include <MG_State/GLState/Core.h>
// 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 <MG_State/EGLState/Core.h>
// The compositor's frame boundary: glFlush presents the display host's frame when the surfaceless
// bind hook took one (see EGLImpl.cpp). The EGL side declares the pair and the swap entry.
#include <MG_Impl/EGLImpl/EGLImpl.h>
#define DECLARE_GL_FUNCTION_STUB_HEAD(type, name, ...) MOBILEGL_GL_API type gl##name(__VA_ARGS__) {
@@ -41,26 +50,22 @@
#define DECLARE_GL_FUNCTION_END(type, name, ...) \
ZoneScopedC(TRACY_ZONECOLOR_ENTRY); \
MGLOG_D("Implementing function: %s(...)", __FUNCTION__); \
const MobileGL::MG_Impl::EGLImpl::GLStreamScope mglStreamScope; \
return MobileGL::MG_Impl::GLImpl::name(__VA_ARGS__); \
}
#define DECLARE_GL_FUNCTION_END_NO_RETURN(type, name, ...) \
ZoneScopedC(TRACY_ZONECOLOR_ENTRY); \
MGLOG_D("Implementing function: %s(...)", __FUNCTION__); \
const MobileGL::MG_Impl::EGLImpl::GLStreamScope mglStreamScope; \
MobileGL::MG_Impl::GLImpl::name(__VA_ARGS__); \
}
#else
#define DECLARE_GL_FUNCTION_END(type, name, ...) \
MGLOG_D("Implementing function: %s(...)", __FUNCTION__); \
const MobileGL::MG_Impl::EGLImpl::GLStreamScope mglStreamScope; \
return MobileGL::MG_Impl::GLImpl::name(__VA_ARGS__); \
}
#define DECLARE_GL_FUNCTION_END_NO_RETURN(type, name, ...) \
MGLOG_D("Implementing function: %s(...)", __FUNCTION__); \
const MobileGL::MG_Impl::EGLImpl::GLStreamScope mglStreamScope; \
MobileGL::MG_Impl::GLImpl::name(__VA_ARGS__); \
}
#endif
@@ -121,17 +126,26 @@ DECLARE_GL_FUNCTION_HEAD(void, EnableVertexAttribArray, GLuint index) DECLARE_GL
// call really did have nothing to do; MGPipeClientFinish answers false-cheap there too.
MOBILEGL_GL_API void glFinish() {
MGLOG_D("Implementing function: %s(...)", __FUNCTION__);
const MobileGL::MG_Impl::EGLImpl::GLStreamScope mglStreamScope;
#if MOBILEGL_BUILD_DISAGGREGATED
MobileGL::MG_Pipe::MGPipeClientFinish();
#endif
}
MOBILEGL_GL_API void glFlush() {
MGLOG_D("Implementing function: %s(...)", __FUNCTION__);
const MobileGL::MG_Impl::EGLImpl::GLStreamScope mglStreamScope;
#if MOBILEGL_BUILD_DISAGGREGATED
MobileGL::MG_Pipe::MGPipeClientFlush();
#endif
// A COMPOSITOR'S FRAME BOUNDARY. kwin binds the display host's frame surface and draws the
// desktop into it, then calls glFlush - and glFlush alone. It never calls eglSwapBuffers, so
// without this the stream reached the server and the server drew, but the display host was
// never told a frame was done: the host's own present loop (AHardwareBuffer_acquire ->
// draw -> notify) is what puts pixels on the glass, and its notify is exactly this swap.
// Guarded by whether the surfaceless-bind hook actually took the host frame.
if (MobileGL::MG_Impl::EGLImpl::g_hostFramePresentSurface != nullptr &&
MobileGL::MG_Impl::EGLImpl::g_hostFramePresentDisplay != nullptr) {
MobileGL::MG_Impl::EGLImpl::SwapBuffers(MobileGL::MG_Impl::EGLImpl::g_hostFramePresentDisplay,
MobileGL::MG_Impl::EGLImpl::g_hostFramePresentSurface);
}
}
DECLARE_GL_FUNCTION_HEAD(void, FramebufferRenderbuffer, GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer) DECLARE_GL_FUNCTION_END_NO_RETURN(void, FramebufferRenderbuffer, target, attachment, renderbuffertarget, renderbuffer)
DECLARE_GL_FUNCTION_HEAD(void, FramebufferTexture2D, GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level) DECLARE_GL_FUNCTION_END_NO_RETURN(void, FramebufferTexture2D, target, attachment, textarget, texture, level)
@@ -156,7 +170,7 @@ DECLARE_GL_FUNCTION_HEAD(void, GetProgramInfoLog, GLuint program, GLsizei bufSiz
DECLARE_GL_FUNCTION_HEAD(void, GetRenderbufferParameteriv, GLenum target, GLenum pname, GLint* params) DECLARE_GL_FUNCTION_END_NO_RETURN(void, GetRenderbufferParameteriv, target, pname, params)
DECLARE_GL_FUNCTION_HEAD(void, GetShaderiv, GLuint shader, GLenum pname, GLint* params) DECLARE_GL_FUNCTION_END_NO_RETURN(void, GetShaderiv, shader, pname, params)
DECLARE_GL_FUNCTION_HEAD(void, GetShaderInfoLog, GLuint shader, GLsizei bufSize, GLsizei* length, GLchar* infoLog) DECLARE_GL_FUNCTION_END_NO_RETURN(void, GetShaderInfoLog, shader, bufSize, length, infoLog)
DECLARE_GL_FUNCTION_HEAD(void, GetShaderPrecisionFormat, GLenum shadertype, GLenum precisiontype, GLint* range, GLint* precision) DECLARE_GL_FUNCTION_END_NO_RETURN(void, GetShaderPrecisionFormat, shadertype, precisiontype, range, precision)
DECLARE_GL_FUNCTION_STUB_HEAD(void, GetShaderPrecisionFormat, GLenum shadertype, GLenum precisiontype, GLint* range, GLint* precision) DECLARE_GL_FUNCTION_STUB_END_NO_RETURN(void, GetShaderPrecisionFormat, shadertype, precisiontype, range, precision)
DECLARE_GL_FUNCTION_HEAD(void, GetShaderSource, GLuint shader, GLsizei bufSize, GLsizei* length, GLchar* source) DECLARE_GL_FUNCTION_END_NO_RETURN(void, GetShaderSource, shader, bufSize, length, source)
DECLARE_GL_FUNCTION_HEAD(void, GetTexParameterfv, GLenum target, GLenum pname, GLfloat* params) DECLARE_GL_FUNCTION_END_NO_RETURN(void, GetTexParameterfv, target, pname, params)
DECLARE_GL_FUNCTION_HEAD(void, GetTexParameteriv, GLenum target, GLenum pname, GLint* params) DECLARE_GL_FUNCTION_END_NO_RETURN(void, GetTexParameteriv, target, pname, params)
@@ -192,7 +206,6 @@ DECLARE_GL_FUNCTION_HEAD(void, StencilMaskSeparate, GLenum face, GLuint mask) DE
DECLARE_GL_FUNCTION_HEAD(void, StencilOp, GLenum fail, GLenum zfail, GLenum zpass) DECLARE_GL_FUNCTION_END_NO_RETURN(void, StencilOp, fail, zfail, zpass)
DECLARE_GL_FUNCTION_HEAD(void, StencilOpSeparate, GLenum face, GLenum sfail, GLenum dpfail, GLenum dppass) DECLARE_GL_FUNCTION_END_NO_RETURN(void, StencilOpSeparate, face, sfail, dpfail, dppass)
DECLARE_GL_FUNCTION_HEAD(void, TexImage2D, GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const void* pixels) DECLARE_GL_FUNCTION_END_NO_RETURN(void, TexImage2D, target, level, internalformat, width, height, border, format, type, pixels)
DECLARE_GL_FUNCTION_HEAD(void, EGLImageTargetTexture2DOES, GLenum target, GLeglImageOES image) DECLARE_GL_FUNCTION_END_NO_RETURN(void, EGLImageTargetTexture2DOES, target, image)
DECLARE_GL_FUNCTION_HEAD(void, TexParameterf, GLenum target, GLenum pname, GLfloat param) DECLARE_GL_FUNCTION_END_NO_RETURN(void, TexParameterf, target, pname, param)
DECLARE_GL_FUNCTION_HEAD(void, TexParameterfv, GLenum target, GLenum pname, const GLfloat* params) DECLARE_GL_FUNCTION_END_NO_RETURN(void, TexParameterfv, target, pname, params)
DECLARE_GL_FUNCTION_HEAD(void, TexParameteri, GLenum target, GLenum pname, GLint param) DECLARE_GL_FUNCTION_END_NO_RETURN(void, TexParameteri, target, pname, param)
@@ -1305,17 +1318,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 <typename H = GLhandleARB>
static GLhandleARB ToGLHandleARB(GLuint name) {
if constexpr (std::is_pointer_v<H>) {
return reinterpret_cast<H>(static_cast<std::uintptr_t>(name));
} else {
return static_cast<H>(name);
}
}
template <typename H = GLhandleARB>
static GLuint FromGLHandleARB(GLhandleARB handle) {
if constexpr (std::is_pointer_v<H>) {
return static_cast<GLuint>(reinterpret_cast<std::uintptr_t>(static_cast<H>(handle)));
} else {
return static_cast<GLuint>(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<MobileGL::GenericErrorInfo>(
"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<MobileGL::GenericErrorInfo>(
"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<GLuint>(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<GLfloat>(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<GLuint> shaders(maxCount > 0 ? static_cast<MobileGL::SizeT>(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)
@@ -1721,6 +2042,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<MobileGL::GenericErrorInfo>("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<MobileGL::GenericErrorInfo>("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<unsigned>(target), static_cast<void*>(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<MobileGL::Uint32>(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<int>(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<int>(plane), planeFds[plane]);
(void)MobileGL::MG_Remote::Client::ShareImportedDmaBuf(
static_cast<MobileGL::Uint32>(target), texName, static_cast<MobileGL::Uint32>(imageWidth),
static_cast<MobileGL::Uint32>(imageHeight), static_cast<MobileGL::Uint32>(imageFourCC),
static_cast<MobileGL::Uint32>(plane), static_cast<MobileGL::Uint32>(planeCount), planeFds[plane],
planePitches[plane], planeOffsets[plane], planeModifiers[plane], planeHasModifier[plane]);
MGLOG_I("dma-buf import: plane %d shared", static_cast<int>(plane));
}
}
}
}
MOBILEGL_GL_API void glEGLImageTargetRenderbufferStorageOES(GLenum target, GLeglImageOES image) {
if (target != GL_RENDERBUFFER) {
MobileGL::MG_State::pGLContext->RecordError(
MobileGL::ErrorCode::InvalidEnum,
MobileGL::MakeUnique<MobileGL::GenericErrorInfo>("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<MobileGL::GenericErrorInfo>("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)
@@ -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;
@@ -611,7 +618,9 @@ namespace MobileGL::MG_Impl::GLImpl {
const auto expectedTextureTarget = MG_Util::ConvertTextureUploadTargetToTextureTarget(textureUploadTarget);
if (expectedTextureTarget == TextureTarget::Unknown ||
textureObject->GetTarget() != expectedTextureTarget) {
(textureObject->GetTarget() != expectedTextureTarget &&
!(textureObject->GetTarget() == TextureTarget::TextureExternalOES &&
expectedTextureTarget == TextureTarget::Texture2D))) {
MG_State::pGLContext->RecordError(
ErrorCode::InvalidOperation,
MakeUnique<GenericErrorInfo>(
@@ -1382,7 +1391,9 @@ namespace MobileGL::MG_Impl::GLImpl {
const auto expectedTextureTarget = MG_Util::ConvertTextureUploadTargetToTextureTarget(textureUploadTarget);
if (expectedTextureTarget == TextureTarget::Unknown ||
textureObject->GetTarget() != expectedTextureTarget) {
(textureObject->GetTarget() != expectedTextureTarget &&
!(textureObject->GetTarget() == TextureTarget::TextureExternalOES &&
expectedTextureTarget == TextureTarget::Texture2D))) {
MG_State::pGLContext->RecordError(
ErrorCode::InvalidOperation,
MakeUnique<GenericErrorInfo>(
@@ -1532,7 +1543,9 @@ namespace MobileGL::MG_Impl::GLImpl {
const auto expectedTextureTarget = MG_Util::ConvertTextureUploadTargetToTextureTarget(textureUploadTarget);
if (expectedTextureTarget == TextureTarget::Unknown ||
textureObject->GetTarget() != expectedTextureTarget) {
(textureObject->GetTarget() != expectedTextureTarget &&
!(textureObject->GetTarget() == TextureTarget::TextureExternalOES &&
expectedTextureTarget == TextureTarget::Texture2D))) {
MG_State::pGLContext->RecordError(
ErrorCode::InvalidOperation,
MakeUnique<GenericErrorInfo>(
+2 -28
View File
@@ -38,7 +38,6 @@
#include <MG_Util/ShaderTranspiler/Types.h>
#include <MG_Backend/BackendObjects.h>
#include <MG_Impl/Pipe/PipeFill.h>
#include <MG_Impl/EGLImpl/EGLImpl.h>
// CONTRACT-P5.md §7 / ID-14: a null check on a GLFunctionsTable slot may not survive into the
// client under split - it becomes a caps-mirror read. SlotCaps.h carries the rule and the test
// that decides which of its two spellings a site takes; in a pull build both expand to exactly
@@ -591,15 +590,6 @@ namespace MobileGL::MG_Impl::GLImpl {
return maxSamples;
}
namespace {
// GL_OES_EGL_image binds the EGL side's dma-buf images, which only a backend with shared
// images has (EGLImpl::SharedImagesAvailable). The backend's own list - the server's,
// under split - cannot know that, so the extension is appended after it.
const char* ClientSideExtension() {
return MG_Impl::EGLImpl::SharedImagesAvailable() ? "GL_OES_EGL_image" : nullptr;
}
} // namespace
/* @INSERTION_POINT:FUNCTION_IMPLEMENTATION@ */
const GLubyte* GetString(GLenum name) {
static String vendorString;
@@ -627,19 +617,11 @@ namespace MobileGL::MG_Impl::GLImpl {
MGLOG_D("vendorString: %s", vendorString.c_str());
return (const GLubyte*)vendorString.c_str();
case GL_VERSION: {
// "OpenGL ES" must not appear anywhere in a desktop GL_VERSION: some callers (ANGLE's GL
// backend among them) search the whole string for it rather than its prefix, and
// then take this for an ES driver, read the version from the wrong offsets and look
// for ES-named extensions. The backend is named "GLES" here for that reason only.
String backendName = rendererInfo.BackendName;
if (const auto at = backendName.find("OpenGL ES"); at != String::npos) {
backendName.replace(at, sizeof("OpenGL ES") - 1, "GLES");
}
versionStr =
std::format("{} {} {}, {} Backend, GIT@" GIT_COMMIT_HASH_SHORT,
rendererInfo.RendererGLInfo.TargetGLVersion.toString(), MG_Config::ProjectName,
MG_Config::CoreVersion.toFormattedString(MG_Config::DefaultVersionStringFormatAttrib),
backendName);
rendererInfo.BackendName);
MGLOG_D("versionStr: %s", versionStr.c_str());
return (const GLubyte*)versionStr.c_str();
}
@@ -664,10 +646,6 @@ namespace MobileGL::MG_Impl::GLImpl {
}
extensionsString += MG_Util::ConvertGLExtToString(ext);
}
if (const char* extra = ClientSideExtension()) {
if (!extensionsString.empty()) extensionsString += " ";
extensionsString += extra;
}
return (const GLubyte*)extensionsString.c_str();
default:
return (const GLubyte*)"Unknown Enum";
@@ -688,9 +666,6 @@ namespace MobileGL::MG_Impl::GLImpl {
const auto& rendererInfo = activeBackendObject->GetRendererInfo();
const auto& exts = rendererInfo.RendererGLInfo.Extensions;
if (index == exts.size()) {
if (const char* extra = ClientSideExtension()) return (const GLubyte*)extra;
}
if (index >= exts.size()) {
return nullptr;
}
@@ -2812,8 +2787,7 @@ namespace MobileGL::MG_Impl::GLImpl {
*params = rendererInfo.RendererGLInfo.TargetGLVersion.Minor;
break;
case GL_NUM_EXTENSIONS:
*params = static_cast<Int>(rendererInfo.RendererGLInfo.Extensions.size()) +
(ClientSideExtension() != nullptr ? 1 : 0);
*params = static_cast<Int>(rendererInfo.RendererGLInfo.Extensions.size());
break;
case GL_POINT_SIZE_GRANULARITY:
*params = static_cast<GLint>(dynamicParameters.PointSizeGranularity);

Some files were not shown because too many files have changed in this diff Show More