mirror of
https://github.com/MobileGL-Dev/MobileGL
synced 2026-11-20 00:11:56 +09:00
[Feature] (SharedImage): server-allocated AHB images over a shared_image pipe verb, with dma-buf fds on the aux socket
This commit is contained in:
@@ -10,6 +10,7 @@
|
||||
|
||||
#include "../Transport/FdPassing.h"
|
||||
|
||||
#include <MG_Pipe/MGPipeTypes.h>
|
||||
#include <MG_Util/Debug/Log.h>
|
||||
|
||||
#include <chrono>
|
||||
@@ -40,17 +41,31 @@ namespace MobileGL::MG_Remote::Server {
|
||||
|
||||
AdoptInbox::Outcome AdoptInbox::Take(Uint64 seq, Uint32 timeoutMs, int* outFd,
|
||||
Transport::AdoptT0::Offer* outOffer, std::string& why) {
|
||||
return TakeKind(Kind::T0, seq, timeoutMs, outFd, outOffer, why);
|
||||
}
|
||||
|
||||
AdoptInbox::Outcome AdoptInbox::TakeSharedImageFd(Uint64 seq, Uint32 timeoutMs, int* outFd, std::string& why) {
|
||||
Transport::AdoptT0::Offer unused{};
|
||||
return TakeKind(Kind::SharedImage, seq, timeoutMs, outFd, &unused, why);
|
||||
}
|
||||
|
||||
// Both kinds are 32-byte sidebands keyed by the record's seq. A shared-image offer
|
||||
// (MGPSharedImageFdOffer) is carried in the T0 Offer's storage - only its magic and seq are read.
|
||||
AdoptInbox::Outcome AdoptInbox::TakeKind(Kind kind, Uint64 seq, Uint32 timeoutMs, int* outFd,
|
||||
Transport::AdoptT0::Offer* outOffer, std::string& why) {
|
||||
using Clock = std::chrono::steady_clock;
|
||||
static_assert(sizeof(MG_Pipe::MGPSharedImageFdOffer) == sizeof(Transport::AdoptT0::Offer),
|
||||
"the two aux sidebands share one size");
|
||||
*outFd = -1;
|
||||
*outOffer = Transport::AdoptT0::Offer{};
|
||||
if (auto it = m_kept.find(seq); it != m_kept.end()) {
|
||||
if (auto it = m_kept.find(KeyFor(kind, seq)); it != m_kept.end()) {
|
||||
*outFd = it->second.fd;
|
||||
*outOffer = it->second.offer;
|
||||
m_kept.erase(it);
|
||||
return Outcome::Taken;
|
||||
}
|
||||
if (m_transport == nullptr) {
|
||||
why = "the session has no control transport to receive the store on";
|
||||
why = "the session has no control transport to receive the descriptor on";
|
||||
return Outcome::Closed;
|
||||
}
|
||||
const auto deadline = Clock::now() + std::chrono::milliseconds(timeoutMs);
|
||||
@@ -64,57 +79,61 @@ namespace MobileGL::MG_Remote::Server {
|
||||
const MobileGLResult received = m_transport->ReceiveFd(
|
||||
&fd, MobileGLMutableByteSpan{sideband, sizeof(sideband)}, &sidebandSize, left);
|
||||
if (received == MOBILEGL_ERR_TIMEOUT) {
|
||||
why = "no store arrived on the aux socket within " + std::to_string(timeoutMs) +
|
||||
why = "no descriptor arrived on the aux socket within " + std::to_string(timeoutMs) +
|
||||
" ms of its record";
|
||||
return Outcome::TimedOut;
|
||||
}
|
||||
if (received != MOBILEGL_OK) {
|
||||
why = "the aux socket closed (rc=" + std::to_string(static_cast<int>(received)) +
|
||||
") before the store arrived";
|
||||
") before the descriptor arrived";
|
||||
return Outcome::Closed;
|
||||
}
|
||||
Transport::AdoptT0::Offer offer{};
|
||||
if (sidebandSize != sizeof(offer)) {
|
||||
++m_malformed;
|
||||
MGLOG_W("MG_Remote server: T0 - an aux descriptor with a %llu-byte sideband is not a store "
|
||||
"offer; closed",
|
||||
MGLOG_W("MG_Remote server: an aux descriptor with a %llu-byte sideband is neither a T0 store nor a "
|
||||
"shared image; closed",
|
||||
static_cast<unsigned long long>(sidebandSize));
|
||||
CloseFd(fd);
|
||||
continue;
|
||||
}
|
||||
std::memcpy(&offer, sideband, sizeof(offer));
|
||||
if (offer.magic != Transport::AdoptT0::kOfferMagic ||
|
||||
offer.version != Transport::AdoptT0::kOfferVersion) {
|
||||
Kind arrived;
|
||||
if (offer.magic == Transport::AdoptT0::kOfferMagic && offer.version == Transport::AdoptT0::kOfferVersion) {
|
||||
arrived = Kind::T0;
|
||||
} else if (offer.magic == MG_Pipe::kMGPSharedImageFdMagic) {
|
||||
arrived = Kind::SharedImage;
|
||||
} else {
|
||||
++m_malformed;
|
||||
MGLOG_W("MG_Remote server: T0 - an aux descriptor whose sideband is not an Offer "
|
||||
"(magic 0x%08x version %u); closed",
|
||||
MGLOG_W("MG_Remote server: an aux descriptor whose sideband is neither a T0 Offer nor a shared "
|
||||
"image (magic 0x%08x version %u); closed",
|
||||
offer.magic, offer.version);
|
||||
CloseFd(fd);
|
||||
continue;
|
||||
}
|
||||
if (offer.seq == seq) {
|
||||
if (arrived == kind && offer.seq == seq) {
|
||||
*outFd = fd;
|
||||
*outOffer = offer;
|
||||
return Outcome::Taken;
|
||||
}
|
||||
if (offer.seq < seq) {
|
||||
// Its record already timed out and was declined; the client has released the
|
||||
// store on that answer, and this late copy of the handle is only a reference.
|
||||
// Its record already timed out and was declined; this late copy is only a reference.
|
||||
++m_stale;
|
||||
MGLOG_W("MG_Remote server: T0 - the store for record %llu arrived after its record was "
|
||||
MGLOG_W("MG_Remote server: the descriptor for record %llu arrived after its record was "
|
||||
"answered; closed (stale)",
|
||||
static_cast<unsigned long long>(offer.seq));
|
||||
CloseFd(fd);
|
||||
continue;
|
||||
}
|
||||
// For a later record: keep it for that record. Replacing a kept one would leak it.
|
||||
if (auto it = m_kept.find(offer.seq); it != m_kept.end()) {
|
||||
const Uint64 key = KeyFor(arrived, offer.seq);
|
||||
if (auto it = m_kept.find(key); it != m_kept.end()) {
|
||||
++m_malformed;
|
||||
CloseFd(it->second.fd);
|
||||
it->second = KeptOffer{fd, offer};
|
||||
continue;
|
||||
}
|
||||
m_kept.emplace(offer.seq, KeptOffer{fd, offer});
|
||||
m_kept.emplace(key, KeptOffer{fd, offer});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -51,6 +51,11 @@ namespace MobileGL::MG_Remote::Server {
|
||||
Outcome Take(Uint64 seq, Uint32 timeoutMs, int* outFd, Transport::AdoptT0::Offer* outOffer,
|
||||
std::string& why);
|
||||
|
||||
// A shared image's descriptor for record `seq` (an Import; sideband MGPSharedImageFdOffer).
|
||||
// Same matching and the same bound as Take; the two kinds share the aux socket and are kept
|
||||
// apart by their sideband's magic.
|
||||
Outcome TakeSharedImageFd(Uint64 seq, Uint32 timeoutMs, int* outFd, std::string& why);
|
||||
|
||||
// Closes every kept descriptor (session teardown).
|
||||
void Clear();
|
||||
|
||||
@@ -59,10 +64,14 @@ namespace MobileGL::MG_Remote::Server {
|
||||
SizeT Kept() const { return m_kept.size(); }
|
||||
|
||||
private:
|
||||
enum class Kind : Uint8 { T0, SharedImage };
|
||||
struct KeptOffer {
|
||||
int fd = -1;
|
||||
Transport::AdoptT0::Offer offer{};
|
||||
};
|
||||
static Uint64 KeyFor(Kind kind, Uint64 seq) { return (seq << 1) | (kind == Kind::SharedImage ? 1u : 0u); }
|
||||
Outcome TakeKind(Kind kind, Uint64 seq, Uint32 timeoutMs, int* outFd, Transport::AdoptT0::Offer* outOffer,
|
||||
std::string& why);
|
||||
Transport::ITransport* m_transport = nullptr;
|
||||
std::map<Uint64, KeptOffer> m_kept;
|
||||
Uint64 m_stale = 0;
|
||||
|
||||
@@ -31,6 +31,9 @@
|
||||
#include <MG_Util/Metrics/TextureMetrics.h>
|
||||
|
||||
#include <cstdlib>
|
||||
#if !defined(_WIN32)
|
||||
#include <unistd.h>
|
||||
#endif
|
||||
#include <cstring>
|
||||
#include <limits>
|
||||
|
||||
@@ -1472,6 +1475,109 @@ namespace MobileGL::MG_Remote::Server {
|
||||
// never created is corruption, not a late record. Token 0 is the release edge and is always
|
||||
// legal (a session whose client released its context has no context, which is exactly the
|
||||
// value a session that never bound one already answers).
|
||||
Bool ServerVerbSink::OnSharedImage(const MG_Pipe::MGPSharedImageOp& op, Uint64 seq,
|
||||
MG_Pipe::MGPSharedImageReply& reply) {
|
||||
namespace SI = SharedImages;
|
||||
ServerSession* session = ServerSession::Active();
|
||||
if (session == nullptr) return false;
|
||||
SI::SessionHolder& holder = session->SharedImageHolder();
|
||||
const auto fill = [&reply](const SI::Image& image) {
|
||||
reply.ImageId = image.Id;
|
||||
reply.Modifier = image.Modifier;
|
||||
reply.Width = image.Width;
|
||||
reply.Height = image.Height;
|
||||
reply.Format = image.Fourcc;
|
||||
reply.Stride = image.Stride;
|
||||
reply.Offset = image.Offset;
|
||||
};
|
||||
switch (op.Op) {
|
||||
case MG_Pipe::kMGPSharedImageAllocate: {
|
||||
std::string why;
|
||||
SI::ImageRef image = SI::Allocate(op.Width, op.Height, op.Format, why);
|
||||
if (image == nullptr) {
|
||||
MGLOG_E("MG_Remote server: shared image %ux%u (fourcc 0x%08x) not allocated: %s", op.Width, op.Height,
|
||||
op.Format, why.c_str());
|
||||
return false;
|
||||
}
|
||||
Transport::ITransport* transport = session->ControlTransport();
|
||||
// The descriptor goes out BEFORE the reply is posted, so the client finds it queued.
|
||||
MG_Pipe::MGPSharedImageFdOffer offer{MG_Pipe::kMGPSharedImageFdMagic, 1, seq, image->Id, 0};
|
||||
const MobileGLResult shared = transport != nullptr
|
||||
? transport->ShareFd(image->Fd, MobileGLByteSpan{&offer, sizeof(offer)})
|
||||
: MOBILEGL_ERR_NOT_INITIALIZED;
|
||||
if (shared != MOBILEGL_OK) {
|
||||
MGLOG_E("MG_Remote server: shared image %llu could not be sent on the aux socket (rc=%d)",
|
||||
static_cast<unsigned long long>(image->Id), static_cast<int>(shared));
|
||||
return false;
|
||||
}
|
||||
holder.Hold(image);
|
||||
fill(*image);
|
||||
MGLOG_D("MG_Remote server: shared image %llu allocated, %ux%u stride %u",
|
||||
static_cast<unsigned long long>(image->Id), image->Width, image->Height, image->Stride);
|
||||
return true;
|
||||
}
|
||||
case MG_Pipe::kMGPSharedImageImport: {
|
||||
int fd = -1;
|
||||
std::string why;
|
||||
if (session->T0Inbox().TakeSharedImageFd(seq, Transport::AdoptT0::kOfferWaitMs, &fd, why) !=
|
||||
AdoptInbox::Outcome::Taken) {
|
||||
MGLOG_E("MG_Remote server: shared-image import (record %llu) has no descriptor: %s",
|
||||
static_cast<unsigned long long>(seq), why.c_str());
|
||||
return false;
|
||||
}
|
||||
SI::ImageRef image = SI::Identify(fd, why);
|
||||
#if !defined(_WIN32)
|
||||
::close(fd);
|
||||
#endif
|
||||
if (image == nullptr) {
|
||||
MGLOG_W_ONCE("MG_Remote server: a dma-buf import was refused: %s", why.c_str());
|
||||
return false;
|
||||
}
|
||||
if (image->Width != op.Width || image->Height != op.Height || !SI::FourccSupported(op.Format)) {
|
||||
MGLOG_W("MG_Remote server: a dma-buf import of image %llu (%ux%u) as %ux%u fourcc 0x%08x was refused",
|
||||
static_cast<unsigned long long>(image->Id), image->Width, image->Height, op.Width, op.Height,
|
||||
op.Format);
|
||||
return false;
|
||||
}
|
||||
holder.Hold(image);
|
||||
fill(*image);
|
||||
return true;
|
||||
}
|
||||
case MG_Pipe::kMGPSharedImageRelease:
|
||||
reply.ImageId = op.ImageId;
|
||||
return holder.Release(op.ImageId);
|
||||
case MG_Pipe::kMGPSharedImagePresent: {
|
||||
SI::ImageRef image = holder.Get(op.ImageId);
|
||||
MG_Backend::BackendObject* backend = ServerLoopInstance().Backend();
|
||||
if (image == nullptr || backend == nullptr) return false;
|
||||
MG_Backend::SharedImageView view;
|
||||
view.Id = image->Id;
|
||||
view.Width = image->Width;
|
||||
view.Height = image->Height;
|
||||
view.Fourcc = image->Fourcc;
|
||||
view.NativeBuffer = image->Native;
|
||||
if (!backend->BlitDefaultFramebufferToSharedImage(view)) return false;
|
||||
fill(*image);
|
||||
return true;
|
||||
}
|
||||
case MG_Pipe::kMGPSharedImageAttach: {
|
||||
SI::ImageRef image = holder.Get(op.ImageId);
|
||||
if (image == nullptr) return false;
|
||||
if (!MG_Pipe::MGPipeApplyAttachSharedImage(op.Texture, image->Id)) {
|
||||
MGLOG_E("MG_Remote server: shared image %llu could not be attached to texture {slot=%u, gen=%u}: the "
|
||||
"texture has no record",
|
||||
static_cast<unsigned long long>(image->Id), op.Texture.Slot, op.Texture.Gen);
|
||||
return false;
|
||||
}
|
||||
fill(*image);
|
||||
return true;
|
||||
}
|
||||
default:
|
||||
MGLOG_E("MG_Remote server: shared_image operation %u is not one this server knows", op.Op);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
Bool ServerVerbSink::OnBindContext(const MG_Pipe::MGPBindContext& bind) {
|
||||
// NO SESSION IS A DECLINE, NOT A FAULT, and it is the one case here that a peer's bytes
|
||||
// cannot cause: a bind is answered by the session's own table, so with no accepted
|
||||
|
||||
@@ -254,6 +254,12 @@ namespace MobileGL::MG_Remote::Server {
|
||||
// rather than a silent bind. Token 0 (the release) is always legal.
|
||||
Bool OnBindContext(const MG_Pipe::MGPBindContext& bind) override;
|
||||
|
||||
// shared_image, opcode 85 (docs/Disaggregated/notes/anland/plan-ahb-dmabuf.md): the
|
||||
// session's image table (allocate / import / release) and the two GL-ordered operations
|
||||
// (present the default framebuffer into an image, attach an image to a texture).
|
||||
Bool OnSharedImage(const MG_Pipe::MGPSharedImageOp& op, Uint64 seq,
|
||||
MG_Pipe::MGPSharedImageReply& reply) override;
|
||||
|
||||
// P5c ct's tallies, for the same reason every other row's tally exists (R-16: a probe
|
||||
// may not arm against a stub). ApplierResets counts the records ACCEPTED (serial
|
||||
// checked, reset run); ObjectDeaths counts every record the sink dispatched.
|
||||
|
||||
@@ -728,6 +728,7 @@ namespace MobileGL::MG_Remote::Server {
|
||||
m_t0Stores = m_t0Bytes = m_t0Declined = m_t0Refusals = 0;
|
||||
m_adoptInbox.Clear();
|
||||
m_adoptInbox.Attach(&transport);
|
||||
m_sharedImages.Clear();
|
||||
// P14 S1: the context registry is the session's, so it is emptied with the rest of the
|
||||
// per-session state this Accept resets. A session that never crossed a bind_context
|
||||
// leaves the current token at 0, which is the single-context shape's answer.
|
||||
@@ -1110,6 +1111,7 @@ namespace MobileGL::MG_Remote::Server {
|
||||
}
|
||||
m_adoptInbox.Clear();
|
||||
m_adoptInbox.Attach(nullptr);
|
||||
m_sharedImages.Clear();
|
||||
m_adoptT0Asked = m_adoptT0Settled = m_adoptT0 = m_adoptT0Quiet = false;
|
||||
m_adoptAsk = 2;
|
||||
m_consumer.Detach();
|
||||
|
||||
@@ -58,6 +58,7 @@
|
||||
#include "../Transport/SessionRings.h"
|
||||
#include "../Wire/PipeWireCodec.h"
|
||||
#include "AdoptInbox.h"
|
||||
#include "SharedImageRegistry.h"
|
||||
#include "ApplyThreadPolicy.h"
|
||||
#include "PipeApplier.h"
|
||||
|
||||
@@ -331,6 +332,12 @@ namespace MobileGL::MG_Remote::Server {
|
||||
Bool AdoptT0Quiet() const { return m_adoptT0Quiet; }
|
||||
AdoptInbox& T0Inbox() { return m_adoptInbox; }
|
||||
|
||||
// ---- shared images (docs/Disaggregated/notes/anland/plan-ahb-dmabuf.md) -------------
|
||||
// The images this session allocated or imported and has not released; emptied when the
|
||||
// session closes. The control transport is where an allocation's descriptor goes out.
|
||||
SharedImages::SessionHolder& SharedImageHolder() { return m_sharedImages; }
|
||||
Transport::ITransport* ControlTransport() const { return m_transport; }
|
||||
|
||||
// ---- P14 S1 (docs/Disaggregated/design/11-state-ownership.md): the session's contexts -
|
||||
//
|
||||
// THE PLACEHOLDER TABLE. `CreateContext`/`DestroyContext` on the control plane build and
|
||||
@@ -416,6 +423,7 @@ namespace MobileGL::MG_Remote::Server {
|
||||
Bool m_adoptT0Settled = false;
|
||||
Bool m_adoptT0 = false;
|
||||
AdoptInbox m_adoptInbox;
|
||||
SharedImages::SessionHolder m_sharedImages;
|
||||
Uint64 m_t0Stores = 0;
|
||||
Uint64 m_t0Bytes = 0;
|
||||
Uint64 m_t0Declined = 0;
|
||||
|
||||
@@ -0,0 +1,306 @@
|
||||
// MobileGL - MobileGL/MG_Remote/Server/SharedImageRegistry.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 "SharedImageRegistry.h"
|
||||
|
||||
#include <MG_Util/Debug/Log.h>
|
||||
|
||||
#include <atomic>
|
||||
#include <cerrno>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <map>
|
||||
#include <utility>
|
||||
|
||||
#if defined(__ANDROID__)
|
||||
#include <android/hardware_buffer.h>
|
||||
#endif
|
||||
#if !defined(_WIN32)
|
||||
#include <sys/mman.h>
|
||||
#include <sys/socket.h>
|
||||
#include <sys/stat.h>
|
||||
#include <unistd.h>
|
||||
#endif
|
||||
|
||||
namespace MobileGL::MG_Remote::Server::SharedImages {
|
||||
|
||||
namespace {
|
||||
std::string Format(const char* fmt, long long a, long long b = 0, long long c = 0) {
|
||||
char buffer[256];
|
||||
std::snprintf(buffer, sizeof(buffer), fmt, a, b, c);
|
||||
return buffer;
|
||||
}
|
||||
|
||||
struct Registry {
|
||||
std::mutex mutex;
|
||||
std::atomic<Uint64> nextId{1};
|
||||
UnorderedMap<Uint64, std::weak_ptr<const Image>> byId;
|
||||
std::map<std::pair<Uint64, Uint64>, std::weak_ptr<const Image>> byIdentity;
|
||||
// Set once two live images were seen with one identity: the kernel shares an inode
|
||||
// between dma-bufs, so a descriptor can no longer say which image it is.
|
||||
Bool identityAmbiguous = false;
|
||||
};
|
||||
|
||||
Registry& Reg() {
|
||||
static Registry* registry = new Registry(); // outlives every holder at process exit
|
||||
return *registry;
|
||||
}
|
||||
|
||||
#if !defined(_WIN32)
|
||||
Bool IdentityOf(int fd, Uint64* dev, Uint64* ino) {
|
||||
struct stat st {};
|
||||
if (::fstat(fd, &st) != 0) return false;
|
||||
*dev = static_cast<Uint64>(st.st_dev);
|
||||
*ino = static_cast<Uint64>(st.st_ino);
|
||||
return true;
|
||||
}
|
||||
#endif
|
||||
|
||||
#if defined(__ANDROID__)
|
||||
// Every descriptor of the buffer's native handle, through the public NDK only: the
|
||||
// handle is written to a socket pair and read back, and only the SCM_RIGHTS payload is
|
||||
// looked at - never the flattened bytes, whose layout is the platform's.
|
||||
Bool NativeHandleFds(const AHardwareBuffer* ahb, Vector<int>& fds, std::string& why) {
|
||||
int pair[2] = {-1, -1};
|
||||
if (::socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0, pair) != 0) {
|
||||
why = Format("socketpair errno=%lld", errno);
|
||||
return false;
|
||||
}
|
||||
const int sent = AHardwareBuffer_sendHandleToUnixSocket(ahb, pair[0]);
|
||||
::close(pair[0]);
|
||||
if (sent != 0) {
|
||||
why = Format("AHardwareBuffer_sendHandleToUnixSocket rc=%lld errno=%lld", sent, errno);
|
||||
::close(pair[1]);
|
||||
return false;
|
||||
}
|
||||
for (;;) {
|
||||
Uint8 data[4096];
|
||||
alignas(cmsghdr) Uint8 control[CMSG_SPACE(sizeof(int) * 64)];
|
||||
iovec iov{data, sizeof(data)};
|
||||
msghdr msg{};
|
||||
msg.msg_iov = &iov;
|
||||
msg.msg_iovlen = 1;
|
||||
msg.msg_control = control;
|
||||
msg.msg_controllen = sizeof(control);
|
||||
const ssize_t got = ::recvmsg(pair[1], &msg, MSG_CMSG_CLOEXEC);
|
||||
if (got < 0 && errno == EINTR) continue;
|
||||
if (got <= 0) break;
|
||||
for (cmsghdr* c = CMSG_FIRSTHDR(&msg); c != nullptr; c = CMSG_NXTHDR(&msg, c)) {
|
||||
if (c->cmsg_level != SOL_SOCKET || c->cmsg_type != SCM_RIGHTS) continue;
|
||||
const SizeT n = (c->cmsg_len - CMSG_LEN(0)) / sizeof(int);
|
||||
const int* in = reinterpret_cast<const int*>(CMSG_DATA(c));
|
||||
for (SizeT i = 0; i < n; ++i) fds.push_back(in[i]);
|
||||
}
|
||||
}
|
||||
::close(pair[1]);
|
||||
if (fds.empty()) {
|
||||
why = "the buffer's native handle carries no descriptor";
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
Bool AllocateNative(Image& image, std::string& why) {
|
||||
AHardwareBuffer_Desc desc{};
|
||||
desc.width = image.Width;
|
||||
desc.height = image.Height;
|
||||
desc.layers = 1;
|
||||
desc.format = image.Fourcc == kFourccXbgr8888 ? AHARDWAREBUFFER_FORMAT_R8G8B8X8_UNORM
|
||||
: AHARDWAREBUFFER_FORMAT_R8G8B8A8_UNORM;
|
||||
desc.usage = AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE | AHARDWAREBUFFER_USAGE_GPU_COLOR_OUTPUT;
|
||||
AHardwareBuffer* ahb = nullptr;
|
||||
const int allocated = AHardwareBuffer_allocate(&desc, &ahb);
|
||||
if (allocated != 0 || ahb == nullptr) {
|
||||
why = Format("AHardwareBuffer_allocate(%lldx%lld) rc=%lld", image.Width, image.Height, allocated);
|
||||
return false;
|
||||
}
|
||||
AHardwareBuffer_Desc described{};
|
||||
AHardwareBuffer_describe(ahb, &described);
|
||||
Vector<int> fds;
|
||||
if (!NativeHandleFds(ahb, fds, why)) {
|
||||
AHardwareBuffer_release(ahb);
|
||||
return false;
|
||||
}
|
||||
image.Native = ahb;
|
||||
image.Fd = fds[0];
|
||||
for (SizeT i = 1; i < fds.size(); ++i) ::close(fds[i]);
|
||||
image.Stride = described.stride * 4;
|
||||
image.Offset = 0;
|
||||
return true;
|
||||
}
|
||||
|
||||
void ReleaseNative(void* native) {
|
||||
if (native != nullptr) AHardwareBuffer_release(static_cast<AHardwareBuffer*>(native));
|
||||
}
|
||||
#elif !defined(_WIN32)
|
||||
// A host has no AHardwareBuffer. A memfd stands in for the dma-buf so the registry, the
|
||||
// descriptor round trip and identification can be exercised by the unit tests; no backend
|
||||
// binds one.
|
||||
Bool AllocateNative(Image& image, std::string& why) {
|
||||
image.Stride = image.Width * 4;
|
||||
image.Offset = 0;
|
||||
const int fd = ::memfd_create("mobilegl-shared-image", MFD_CLOEXEC);
|
||||
if (fd < 0) {
|
||||
why = Format("memfd_create errno=%lld", errno);
|
||||
return false;
|
||||
}
|
||||
if (::ftruncate(fd, static_cast<off_t>(image.Stride) * image.Height) != 0) {
|
||||
why = Format("ftruncate errno=%lld", errno);
|
||||
::close(fd);
|
||||
return false;
|
||||
}
|
||||
image.Fd = fd;
|
||||
return true;
|
||||
}
|
||||
|
||||
void ReleaseNative(void*) {}
|
||||
#else
|
||||
Bool AllocateNative(Image&, std::string& why) {
|
||||
why = "shared images need POSIX descriptors";
|
||||
return false;
|
||||
}
|
||||
|
||||
void ReleaseNative(void*) {}
|
||||
#endif
|
||||
} // namespace
|
||||
|
||||
Image::~Image() {
|
||||
Registry& reg = Reg();
|
||||
{
|
||||
const std::lock_guard<std::mutex> lock(reg.mutex);
|
||||
// Only this image's own entries: the weak pointer is already expired, but a newer
|
||||
// image may have taken the identity over (the kernel recycles inodes).
|
||||
if (auto it = reg.byId.find(Id); it != reg.byId.end() && it->second.expired()) reg.byId.erase(it);
|
||||
const auto key = std::make_pair(IdentityDev, IdentityIno);
|
||||
if (auto it = reg.byIdentity.find(key); it != reg.byIdentity.end() && it->second.expired())
|
||||
reg.byIdentity.erase(it);
|
||||
}
|
||||
#if !defined(_WIN32)
|
||||
if (Fd >= 0) ::close(Fd);
|
||||
#endif
|
||||
ReleaseNative(Native);
|
||||
}
|
||||
|
||||
Bool FourccSupported(Uint32 fourcc) { return fourcc == kFourccAbgr8888 || fourcc == kFourccXbgr8888; }
|
||||
|
||||
ImageRef Allocate(Uint32 width, Uint32 height, Uint32 fourcc, std::string& why) {
|
||||
if (width == 0 || height == 0 || width > 16384 || height > 16384) {
|
||||
why = Format("%lldx%lld is not an image size", width, height);
|
||||
return nullptr;
|
||||
}
|
||||
if (!FourccSupported(fourcc)) {
|
||||
why = Format("fourcc 0x%08llx is not a shared-image format", fourcc);
|
||||
return nullptr;
|
||||
}
|
||||
Registry& reg = Reg();
|
||||
auto image = std::make_shared<Image>();
|
||||
image->Id = reg.nextId.fetch_add(1, std::memory_order_relaxed);
|
||||
image->Width = width;
|
||||
image->Height = height;
|
||||
image->Fourcc = fourcc;
|
||||
if (!AllocateNative(*image, why)) return nullptr;
|
||||
#if !defined(_WIN32)
|
||||
if (!IdentityOf(image->Fd, &image->IdentityDev, &image->IdentityIno)) {
|
||||
why = Format("fstat on the exported descriptor errno=%lld", errno);
|
||||
return nullptr;
|
||||
}
|
||||
#endif
|
||||
const std::lock_guard<std::mutex> lock(reg.mutex);
|
||||
reg.byId[image->Id] = image;
|
||||
const auto key = std::make_pair(image->IdentityDev, image->IdentityIno);
|
||||
if (auto it = reg.byIdentity.find(key); it != reg.byIdentity.end() && !it->second.expired()) {
|
||||
if (!reg.identityAmbiguous) {
|
||||
MGLOG_E("MG_Remote server: two live shared images have one dma-buf identity (dev %llu ino %llu); "
|
||||
"this kernel does not keep dma-buf inodes unique, so a returned descriptor cannot name its "
|
||||
"image and every shared-image import is refused from here on",
|
||||
static_cast<unsigned long long>(key.first), static_cast<unsigned long long>(key.second));
|
||||
}
|
||||
reg.identityAmbiguous = true;
|
||||
}
|
||||
reg.byIdentity[key] = image;
|
||||
return image;
|
||||
}
|
||||
|
||||
ImageRef Identify(int fd, std::string& why) {
|
||||
#if defined(_WIN32)
|
||||
(void)fd;
|
||||
why = "shared images need POSIX descriptors";
|
||||
return nullptr;
|
||||
#else
|
||||
Uint64 dev = 0, ino = 0;
|
||||
if (!IdentityOf(fd, &dev, &ino)) {
|
||||
why = Format("fstat on the imported descriptor errno=%lld", errno);
|
||||
return nullptr;
|
||||
}
|
||||
Registry& reg = Reg();
|
||||
const std::lock_guard<std::mutex> lock(reg.mutex);
|
||||
if (reg.identityAmbiguous) {
|
||||
why = "dma-buf identities are not unique on this kernel";
|
||||
return nullptr;
|
||||
}
|
||||
const auto it = reg.byIdentity.find(std::make_pair(dev, ino));
|
||||
ImageRef image = it != reg.byIdentity.end() ? it->second.lock() : nullptr;
|
||||
if (image == nullptr) {
|
||||
why = Format("the descriptor (dev %llu ino %llu) was not exported by this server", static_cast<long long>(dev),
|
||||
static_cast<long long>(ino));
|
||||
}
|
||||
return image;
|
||||
#endif
|
||||
}
|
||||
|
||||
ImageRef Find(Uint64 id) {
|
||||
Registry& reg = Reg();
|
||||
const std::lock_guard<std::mutex> lock(reg.mutex);
|
||||
const auto it = reg.byId.find(id);
|
||||
return it != reg.byId.end() ? it->second.lock() : nullptr;
|
||||
}
|
||||
|
||||
SizeT LiveCount() {
|
||||
Registry& reg = Reg();
|
||||
const std::lock_guard<std::mutex> lock(reg.mutex);
|
||||
SizeT live = 0;
|
||||
for (const auto& [id, weak] : reg.byId) live += weak.expired() ? 0 : 1;
|
||||
return live;
|
||||
}
|
||||
|
||||
void SessionHolder::Hold(const ImageRef& image) {
|
||||
if (image == nullptr) return;
|
||||
const std::lock_guard<std::mutex> lock(m_mutex);
|
||||
m_images[image->Id] = image;
|
||||
}
|
||||
|
||||
Bool SessionHolder::Release(Uint64 id) {
|
||||
ImageRef dropped;
|
||||
const std::lock_guard<std::mutex> lock(m_mutex);
|
||||
const auto it = m_images.find(id);
|
||||
if (it == m_images.end()) return false;
|
||||
dropped = std::move(it->second); // destroyed after the unlock: ~Image takes the registry lock
|
||||
m_images.erase(it);
|
||||
return true;
|
||||
}
|
||||
|
||||
ImageRef SessionHolder::Get(Uint64 id) const {
|
||||
const std::lock_guard<std::mutex> lock(m_mutex);
|
||||
const auto it = m_images.find(id);
|
||||
return it != m_images.end() ? it->second : nullptr;
|
||||
}
|
||||
|
||||
void SessionHolder::Clear() {
|
||||
UnorderedMap<Uint64, ImageRef> dropped;
|
||||
{
|
||||
const std::lock_guard<std::mutex> lock(m_mutex);
|
||||
dropped.swap(m_images);
|
||||
}
|
||||
}
|
||||
|
||||
SizeT SessionHolder::Count() const {
|
||||
const std::lock_guard<std::mutex> lock(m_mutex);
|
||||
return m_images.size();
|
||||
}
|
||||
|
||||
} // namespace MobileGL::MG_Remote::Server::SharedImages
|
||||
@@ -0,0 +1,98 @@
|
||||
// MobileGL - MobileGL/MG_Remote/Server/SharedImageRegistry.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
|
||||
|
||||
// SHARED IMAGES: colour buffers the server allocates and hands to clients as dma-buf descriptors,
|
||||
// so a frame one client renders can be sampled by another (a Wayland window by its compositor)
|
||||
// without leaving GPU memory (docs/Disaggregated/notes/anland/plan-ahb-dmabuf.md).
|
||||
//
|
||||
// THE SERVER IS THE ALLOCATOR AND THE ONLY IMPORTER. An image is an AHardwareBuffer; what leaves
|
||||
// the process is a duplicate of its first native-handle descriptor, which on every Android kernel
|
||||
// with dma-buf heaps is a dma-buf. A descriptor that comes BACK (a compositor importing a client's
|
||||
// wl_buffer) is never imported as raw memory - its layout is the allocator's business - it is
|
||||
// IDENTIFIED: the kernel gives each dma-buf its own inode, so (st_dev, st_ino) names the image it
|
||||
// was exported from, and the backends bind that AHardwareBuffer through the Android import paths.
|
||||
// Nothing here reads a vendor's handle layout or assumes a memory layout.
|
||||
//
|
||||
// LIFETIME. The registry holds weak references only. Whoever still needs an image holds an
|
||||
// ImageRef: the session that allocated or imported it (until its release or the session's end)
|
||||
// and a backend object built on it (an EGLImage, a VkImage) for as long as that object lives.
|
||||
|
||||
#pragma once
|
||||
#include <Includes.h>
|
||||
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
|
||||
namespace MobileGL::MG_Remote::Server::SharedImages {
|
||||
|
||||
// DRM fourcc codes (drm_fourcc.h). Little-endian packed: ABGR8888 is R, G, B, A in memory,
|
||||
// which is GL's RGBA8 and AHardwareBuffer's R8G8B8A8.
|
||||
inline constexpr Uint32 FourCC(char a, char b, char c, char d) {
|
||||
return static_cast<Uint32>(static_cast<Uint8>(a)) | (static_cast<Uint32>(static_cast<Uint8>(b)) << 8) |
|
||||
(static_cast<Uint32>(static_cast<Uint8>(c)) << 16) | (static_cast<Uint32>(static_cast<Uint8>(d)) << 24);
|
||||
}
|
||||
inline constexpr Uint32 kFourccAbgr8888 = FourCC('A', 'B', '2', '4');
|
||||
inline constexpr Uint32 kFourccXbgr8888 = FourCC('X', 'B', '2', '4');
|
||||
// "The layout is the allocator's": what an AHardwareBuffer is to anybody but its allocator.
|
||||
inline constexpr Uint64 kModifierInvalid = 0x00ffffffffffffffull;
|
||||
inline constexpr Uint64 kModifierLinear = 0;
|
||||
|
||||
// Whether images of this fourcc can be allocated (and so imported) at all.
|
||||
Bool FourccSupported(Uint32 fourcc);
|
||||
|
||||
struct Image {
|
||||
Uint64 Id = 0;
|
||||
Uint32 Width = 0;
|
||||
Uint32 Height = 0;
|
||||
Uint32 Fourcc = 0;
|
||||
Uint32 Stride = 0; // bytes
|
||||
Uint32 Offset = 0;
|
||||
Uint64 Modifier = kModifierInvalid;
|
||||
// AHardwareBuffer* on Android; null on a host, where the memory is a memfd (unit tests).
|
||||
void* Native = nullptr;
|
||||
// The descriptor clients receive duplicates of. Owned.
|
||||
int Fd = -1;
|
||||
Uint64 IdentityDev = 0;
|
||||
Uint64 IdentityIno = 0;
|
||||
|
||||
Image() = default;
|
||||
Image(const Image&) = delete;
|
||||
Image& operator=(const Image&) = delete;
|
||||
~Image();
|
||||
};
|
||||
using ImageRef = SharedPtr<const Image>;
|
||||
|
||||
// A new image of `width` x `height` `fourcc`, registered. Null with `why` on failure.
|
||||
ImageRef Allocate(Uint32 width, Uint32 height, Uint32 fourcc, std::string& why);
|
||||
|
||||
// The live image `fd` was exported from, or null (`why` says which test failed): a descriptor
|
||||
// this server never exported, or one whose identity the kernel does not keep unique.
|
||||
ImageRef Identify(int fd, std::string& why);
|
||||
|
||||
// The live image with this id, or null.
|
||||
ImageRef Find(Uint64 id);
|
||||
|
||||
// Live images, for tests and diagnostics.
|
||||
SizeT LiveCount();
|
||||
|
||||
// One session's references: what it allocated or imported and has not released yet. Dropping
|
||||
// the holder (the session ending) drops every one of them.
|
||||
class SessionHolder {
|
||||
public:
|
||||
void Hold(const ImageRef& image);
|
||||
Bool Release(Uint64 id);
|
||||
ImageRef Get(Uint64 id) const;
|
||||
void Clear();
|
||||
SizeT Count() const;
|
||||
|
||||
private:
|
||||
mutable std::mutex m_mutex;
|
||||
UnorderedMap<Uint64, ImageRef> m_images;
|
||||
};
|
||||
|
||||
} // namespace MobileGL::MG_Remote::Server::SharedImages
|
||||
Reference in New Issue
Block a user