mirror of
https://github.com/MobileGL-Dev/MobileGL
synced 2026-11-17 06:53:22 +09:00
Compare commits
20
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4ed1c9cef2 | ||
|
|
ebc552a048 | ||
|
|
6fb880cdf2 | ||
|
|
d52c031c50 | ||
|
|
4156ca6e36 | ||
|
|
2f64ede8c6 | ||
|
|
a5b463a5e8 | ||
|
|
32c79f4135 | ||
|
|
f458924360 | ||
|
|
0dad3fcaa1 | ||
|
|
75f83b20fc | ||
|
|
57781688ce | ||
|
|
7308668488 | ||
|
|
134791b4b9 | ||
|
|
c24926cafe | ||
|
|
c5fa722be7 | ||
|
|
b7aa8d2011 | ||
|
|
378020adf3 | ||
|
|
028cf4eb62 | ||
|
|
08124c99f1 |
Vendored
-538
@@ -1,538 +0,0 @@
|
||||
/*
|
||||
* 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
|
||||
+8
-86
@@ -437,14 +437,10 @@ 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
|
||||
@@ -468,6 +464,7 @@ 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
|
||||
@@ -647,7 +644,6 @@ if (MOBILEGL_BUILD_DISAGGREGATED)
|
||||
MobileGL/MG_Remote/FatalFunnel.cpp
|
||||
MobileGL/MG_Remote/Wire/PipeWireCodec.cpp
|
||||
MobileGL/MG_Remote/Client/ClientSession.cpp
|
||||
MobileGL/MG_Remote/Client/DmaBufImport.cpp
|
||||
MobileGL/MG_Remote/Client/EmitTables.cpp
|
||||
MobileGL/MG_Remote/Client/CapsMirror.cpp
|
||||
# P5 c1: the client role's BackendObject. pActiveBackendObject holds one of these
|
||||
@@ -667,6 +663,10 @@ MobileGL/MG_Remote/Client/DmaBufImport.cpp
|
||||
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.
|
||||
@@ -682,6 +682,8 @@ MobileGL/MG_Remote/Client/DmaBufImport.cpp
|
||||
# (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 -
|
||||
@@ -826,17 +828,6 @@ 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}
|
||||
@@ -846,7 +837,7 @@ target_compile_definitions(${CMAKE_PROJECT_NAME}
|
||||
|
||||
if(UNIX AND NOT APPLE AND NOT ANDROID)
|
||||
foreach(MOBILEGL_LOADER_ALIAS
|
||||
libEGL.so libEGL.so.1)
|
||||
libEGL.so libEGL.so.1 libGL.so libGL.so.1)
|
||||
add_custom_command(TARGET ${CMAKE_PROJECT_NAME} POST_BUILD
|
||||
COMMAND ${CMAKE_COMMAND} -E create_symlink
|
||||
"$<TARGET_FILE_NAME:${CMAKE_PROJECT_NAME}>"
|
||||
@@ -903,68 +894,6 @@ 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)
|
||||
@@ -1253,10 +1182,3 @@ 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()
|
||||
|
||||
+3
-12
@@ -423,8 +423,9 @@ 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 (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.
|
||||
// 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.
|
||||
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
|
||||
@@ -499,7 +500,6 @@ 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,15 +730,6 @@ 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
|
||||
|
||||
@@ -494,8 +494,8 @@ namespace MobileGL::MG_ConfigLoader {
|
||||
}
|
||||
}
|
||||
|
||||
// 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.
|
||||
// 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.
|
||||
{
|
||||
String surface;
|
||||
QueryEnvVariable("MOBILEGL_IPC_SURFACE", surface, "offscreen");
|
||||
@@ -505,11 +505,9 @@ 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|host, using offscreen",
|
||||
"offscreen|server, using offscreen",
|
||||
surface.c_str());
|
||||
ipc.Surface = MG_Config::IpcSurface::Offscreen;
|
||||
}
|
||||
@@ -517,14 +515,12 @@ 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::Offscreen && !serverProcess &&
|
||||
if (ipc.Surface == MG_Config::IpcSurface::Server && !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=%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");
|
||||
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");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+2
-4
@@ -8,8 +8,6 @@
|
||||
|
||||
#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
|
||||
@@ -112,8 +110,8 @@
|
||||
#define MOBILEGL_ASSERT(condition, ...) \
|
||||
do { \
|
||||
if (!(condition)) { \
|
||||
fprintf(stderr, "Assertion failed" __VA_OPT__(": ") "%s", "" __VA_ARGS__); \
|
||||
fprintf(stderr, " at %s:%d (%s)\n", __FILE__, __LINE__, __func__); \
|
||||
MGLOG_F("Assertion failed" __VA_OPT__(": ") __VA_ARGS__); \
|
||||
MGLOG_F(" at %s:%d (%s)", __FILE__, __LINE__, __func__); \
|
||||
TRAP; \
|
||||
} \
|
||||
} while (0)
|
||||
|
||||
@@ -213,28 +213,6 @@ 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);
|
||||
@@ -316,11 +294,6 @@ 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;
|
||||
@@ -346,29 +319,6 @@ 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");
|
||||
@@ -441,12 +391,6 @@ namespace MobileGL::MG_Backend {
|
||||
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();
|
||||
if (!backendFunctions.Present) {
|
||||
MGLOG_E("SwapEGLBuffers failed: backend Present function is null");
|
||||
@@ -464,27 +408,6 @@ 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;
|
||||
|
||||
@@ -595,18 +595,6 @@ namespace MobileGL {
|
||||
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);
|
||||
// Forwards the app-requested eglSwapInterval to the backend's native
|
||||
@@ -628,11 +616,7 @@ namespace MobileGL {
|
||||
enum class SurfaceKind {
|
||||
None,
|
||||
Window,
|
||||
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
|
||||
Pbuffer
|
||||
};
|
||||
|
||||
struct EGLCurrentState {
|
||||
|
||||
@@ -6,12 +6,6 @@
|
||||
// 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"
|
||||
@@ -982,8 +976,17 @@ 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.
|
||||
if (m_eglSurfaceInitialized) {
|
||||
DestroyEGLContext();
|
||||
ResetEGLRuntimeState();
|
||||
}
|
||||
|
||||
@@ -1014,8 +1017,9 @@ 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().
|
||||
if (m_eglSurfaceInitialized) {
|
||||
DestroyEGLContext();
|
||||
ResetEGLRuntimeState();
|
||||
}
|
||||
|
||||
@@ -1034,241 +1038,6 @@ namespace MobileGL::MG_Backend::DirectGLES {
|
||||
#endif
|
||||
}
|
||||
|
||||
#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 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);
|
||||
}
|
||||
@@ -1293,42 +1062,13 @@ namespace MobileGL::MG_Backend::DirectGLES {
|
||||
MGLOG_E("MakeEGLCurrent failed: EGL display mismatch or 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 (!m_eglSurfaceInitialized) {
|
||||
MGLOG_E("MakeEGLCurrent failed: EGL surface is not initialized");
|
||||
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 (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
|
||||
@@ -1356,9 +1096,9 @@ namespace MobileGL::MG_Backend::DirectGLES {
|
||||
// function table instead of 1), or make NativeBindCanBeSkippedFor answer true for any tuple
|
||||
// (the ID-67 control's different tuple stays at 1 native bind where 2 are required).
|
||||
const Bool nativelyCurrentAlready = MG_Config::Transport != MG_Config::TransportMode::Monolith &&
|
||||
m_eglSurfaceInitialized && m_eglSurface == draw &&
|
||||
DirectGLES::IsBackendContextCurrentOnThisThread() &&
|
||||
(surfaceless || (m_eglSurfaceInitialized && m_eglSurface == draw &&
|
||||
NativeBindCanBeSkippedFor(dpy, draw, read, ctx)));
|
||||
NativeBindCanBeSkippedFor(dpy, draw, read, ctx);
|
||||
if (!nativelyCurrentAlready && !DirectGLES::MakeCurrent()) {
|
||||
NoteNativeContextGone();
|
||||
return false;
|
||||
@@ -1377,15 +1117,6 @@ 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;
|
||||
}
|
||||
|
||||
@@ -1542,40 +1273,7 @@ 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,
|
||||
// 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};
|
||||
E_GL_ARB_get_program_binary};
|
||||
// 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,9 +8,6 @@
|
||||
|
||||
#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>
|
||||
|
||||
@@ -59,46 +56,8 @@ 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;
|
||||
|
||||
// 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;
|
||||
MG_External::EGLFunctionsTable m_EGLFunctions;
|
||||
MG_External::GLESFunctionsTable m_GLESFunctions;
|
||||
|
||||
@@ -87,10 +87,6 @@ namespace MobileGL::MG_Backend::DirectGLES {
|
||||
#endif
|
||||
|
||||
MG_External::EGLFunctionsTable g_EGLFuncs;
|
||||
Uint g_hostFrameFramebufferId = 0;
|
||||
Uint g_hostFrameRenderbuffer = 0;
|
||||
Uint g_hostFrameWidth = 0;
|
||||
Uint g_hostFrameHeight = 0;
|
||||
MG_External::GLESFunctionsTable g_GLESFuncs;
|
||||
MG_External::GLESCapabilities g_GLESCapabilities;
|
||||
|
||||
@@ -6519,7 +6515,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
|
||||
// Through the shadow: a raw bind here would leave the shadow claiming
|
||||
// the previous user FBO, false-skipping its next re-bind.
|
||||
FramebufferImpl::BindFramebufferId(
|
||||
target == FramebufferTarget::Draw ? GL_DRAW_FRAMEBUFFER : GL_READ_FRAMEBUFFER, g_hostFrameFramebufferId);
|
||||
target == FramebufferTarget::Draw ? GL_DRAW_FRAMEBUFFER : GL_READ_FRAMEBUFFER, 0);
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -6588,7 +6584,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
|
||||
// Through the shadow: a raw bind here would leave the shadow claiming
|
||||
// the previous user FBO, false-skipping its next re-bind.
|
||||
FramebufferImpl::BindFramebufferId(
|
||||
target == FramebufferTarget::Draw ? GL_DRAW_FRAMEBUFFER : GL_READ_FRAMEBUFFER, g_hostFrameFramebufferId);
|
||||
target == FramebufferTarget::Draw ? GL_DRAW_FRAMEBUFFER : GL_READ_FRAMEBUFFER, 0);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6608,7 +6604,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
|
||||
FramebufferImpl::g_integerColorDrawBufferMask = 0;
|
||||
}
|
||||
FramebufferImpl::BindFramebufferId(
|
||||
target == FramebufferTarget::Draw ? GL_DRAW_FRAMEBUFFER : GL_READ_FRAMEBUFFER, g_hostFrameFramebufferId);
|
||||
target == FramebufferTarget::Draw ? GL_DRAW_FRAMEBUFFER : GL_READ_FRAMEBUFFER, 0);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -6649,7 +6645,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
|
||||
FramebufferImpl::g_integerColorDrawBufferMask = 0;
|
||||
}
|
||||
FramebufferImpl::BindFramebufferId(
|
||||
target == FramebufferTarget::Draw ? GL_DRAW_FRAMEBUFFER : GL_READ_FRAMEBUFFER, g_hostFrameFramebufferId);
|
||||
target == FramebufferTarget::Draw ? GL_DRAW_FRAMEBUFFER : GL_READ_FRAMEBUFFER, 0);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -16184,10 +16180,225 @@ namespace MobileGL::MG_Backend::DirectGLES {
|
||||
g_GLESCapabilities = capabilities;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------
|
||||
// P14 S4 (docs/Disaggregated/design/11-state-ownership.md): the native tuple is per context.
|
||||
//
|
||||
// THE DISPLAY STAYS ONE OBJECT. eglInitialize is once per process and eglTerminate runs when the
|
||||
// last native context has gone, so a second context - or a second session - never terminates the
|
||||
// display the first one is still using.
|
||||
//
|
||||
// EVERYTHING ELSE THAT WAS A FILE-LEVEL SINGLETON IS KEYED. A 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 (bind_context / SurfaceOp.context) and S2 gave a per-thread owner.
|
||||
// The key is resolved on the calling thread through a probe the server layer installs
|
||||
// (SetNativeContextKeyResolver); with none installed the answer is the single key {0, 0}, which
|
||||
// is byte-for-byte the process singleton this replaces - monolith, a frontend-only process and
|
||||
// every unit case keep exactly one tuple.
|
||||
//
|
||||
// WHY THE SURFACES ARE KEYED BY SESSION AND NOT BY CONTEXT: an EGLSurface is not owned by an
|
||||
// EGLContext (EGL has no such relationship - only the draw/read BINDING is per context), so a
|
||||
// session's surfaces are one set and each context records which of them it currently draws to.
|
||||
// That is also what makes pbuffer -> window -> pbuffer keep its objects: creating the second
|
||||
// surface does not touch the context, so the twins the first surface's draws built are still
|
||||
// there when the third one is bound.
|
||||
|
||||
static EGLDisplay g_Display = EGL_NO_DISPLAY;
|
||||
static EGLContext g_Context = EGL_NO_CONTEXT;
|
||||
static EGLSurface g_Surface = EGL_NO_SURFACE;
|
||||
static EGLConfig g_Config = nullptr;
|
||||
// eglInitialize/eglTerminate pairing: the display is terminated only when the count drops to 0.
|
||||
static Uint32 g_displayUsers = 0;
|
||||
|
||||
struct NativeContextTuple {
|
||||
Uint64 SessionKey = 0;
|
||||
Uint64 ContextToken = 0;
|
||||
Uint64 ShareGroupToken = 0;
|
||||
EGLContext Context = EGL_NO_CONTEXT;
|
||||
EGLConfig Config = nullptr;
|
||||
// The session surface this context draws to / reads from, as last made current for it.
|
||||
EGLSurface Draw = EGL_NO_SURFACE;
|
||||
EGLSurface Read = EGL_NO_SURFACE;
|
||||
};
|
||||
|
||||
struct NativeSessionState {
|
||||
Uint64 SessionKey = 0;
|
||||
// Every native surface this session created, so its teardown destroys its own and only its own.
|
||||
Vector<EGLSurface> Surfaces;
|
||||
// The surface the session currently draws to / reads from - what a bind to another context
|
||||
// re-makes current, and what Present/eglSwapBuffers names.
|
||||
EGLSurface Draw = EGL_NO_SURFACE;
|
||||
EGLSurface Read = EGL_NO_SURFACE;
|
||||
};
|
||||
|
||||
static std::mutex g_nativeRegistryMutex;
|
||||
// Bumped on every registry mutation. The per-thread active-tuple cache below is keyed on it, so
|
||||
// a destroyed tuple can never be handed out from a stale cache entry.
|
||||
static std::atomic<Uint64> g_nativeRegistryEpoch{1};
|
||||
// Never erased while the process lives: a context teardown marks its tuple dead (Context =
|
||||
// EGL_NO_CONTEXT) instead of freeing it, so a cached pointer is never dangling between the
|
||||
// epoch bump and the next resolution.
|
||||
static Vector<NativeContextTuple*>& NativeContexts() {
|
||||
static Vector<NativeContextTuple*>* contexts = new Vector<NativeContextTuple*>();
|
||||
return *contexts;
|
||||
}
|
||||
static Vector<NativeSessionState*>& NativeSessions() {
|
||||
static Vector<NativeSessionState*>* sessions = new Vector<NativeSessionState*>();
|
||||
return *sessions;
|
||||
}
|
||||
|
||||
static std::atomic<NativeContextKeyResolver> g_nativeContextKeyResolver{nullptr};
|
||||
|
||||
// A one-way override for a case that drives the registry with no session runtime installed:
|
||||
// when `t_forcedNativeKeyValid` is set, the key is the forced pair instead of the probe's
|
||||
// answer. The setter clears the active-tuple cache, which is keyed on the effective key.
|
||||
thread_local Bool t_forcedNativeKeyValid = false;
|
||||
thread_local Uint64 t_forcedNativeSession = 0;
|
||||
thread_local Uint64 t_forcedNativeToken = 0;
|
||||
|
||||
void SetNativeContextKeyResolver(NativeContextKeyResolver resolver) {
|
||||
g_nativeContextKeyResolver.store(resolver, std::memory_order_release);
|
||||
}
|
||||
|
||||
static void ResolveNativeKey(Uint64& outSession, Uint64& outToken) {
|
||||
if (t_forcedNativeKeyValid) {
|
||||
outSession = t_forcedNativeSession;
|
||||
outToken = t_forcedNativeToken;
|
||||
return;
|
||||
}
|
||||
outSession = 0;
|
||||
outToken = 0;
|
||||
const NativeContextKeyResolver resolver = g_nativeContextKeyResolver.load(std::memory_order_acquire);
|
||||
if (resolver != nullptr) (void)resolver(&outSession, &outToken);
|
||||
}
|
||||
|
||||
Uint64 CurrentNativeSessionKey() {
|
||||
Uint64 session = 0;
|
||||
Uint64 token = 0;
|
||||
ResolveNativeKey(session, token);
|
||||
return session;
|
||||
}
|
||||
|
||||
namespace {
|
||||
// The active tuple for this thread. The fast path is a key compare against a thread-local
|
||||
// cache, because IsBackendContextCurrentOnThisThread sits under every draw; the slow path
|
||||
// (a first call, a bind_context switch, or any registry mutation) walks the registry, which
|
||||
// holds one tuple per live client context.
|
||||
thread_local NativeContextTuple* t_activeNativeTuple = nullptr;
|
||||
thread_local Uint64 t_activeNativeEpoch = 0;
|
||||
thread_local Uint64 t_activeNativeSession = 0;
|
||||
thread_local Uint64 t_activeNativeToken = 0;
|
||||
// The native context THIS THREAD last made current. An EGLContext can be current on only one
|
||||
// thread, and MakeCurrent is the only writer, so a plain thread-local is exact - and it is
|
||||
// what makes MakeNativeContextCurrentForBoundToken a no-op when the bind did not actually
|
||||
// change the native context (the single-context world's every bind).
|
||||
thread_local EGLContext t_boundNativeContext = EGL_NO_CONTEXT;
|
||||
} // namespace
|
||||
|
||||
static NativeSessionState& AcquireNativeSession(Uint64 sessionKey) {
|
||||
for (auto* session : NativeSessions()) {
|
||||
if (session->SessionKey == sessionKey) return *session;
|
||||
}
|
||||
auto* created = new NativeSessionState{};
|
||||
created->SessionKey = sessionKey;
|
||||
NativeSessions().push_back(created);
|
||||
g_nativeRegistryEpoch.fetch_add(1, std::memory_order_acq_rel);
|
||||
return *created;
|
||||
}
|
||||
|
||||
static NativeSessionState& ActiveNativeSession() {
|
||||
Uint64 session = 0;
|
||||
Uint64 token = 0;
|
||||
ResolveNativeKey(session, token);
|
||||
const std::lock_guard<std::mutex> lock(g_nativeRegistryMutex);
|
||||
return AcquireNativeSession(session);
|
||||
}
|
||||
|
||||
// The tuple the calling thread works on, created on first use. Lazy creation is what keeps the
|
||||
// pre-S4 shapes working unchanged: a session that never crossed a CreateContext - the whole
|
||||
// single-context world, and every existing fixture - resolves to its token-0 tuple and gets
|
||||
// exactly the one native context it always had.
|
||||
static NativeContextTuple& ActiveNativeContext() {
|
||||
Uint64 session = 0;
|
||||
Uint64 token = 0;
|
||||
ResolveNativeKey(session, token);
|
||||
const Uint64 epoch = g_nativeRegistryEpoch.load(std::memory_order_acquire);
|
||||
if (t_activeNativeTuple != nullptr && t_activeNativeEpoch == epoch &&
|
||||
t_activeNativeSession == session && t_activeNativeToken == token) {
|
||||
return *t_activeNativeTuple;
|
||||
}
|
||||
const std::lock_guard<std::mutex> lock(g_nativeRegistryMutex);
|
||||
NativeContextTuple* found = nullptr;
|
||||
for (auto* tuple : NativeContexts()) {
|
||||
if (tuple->SessionKey == session && tuple->ContextToken == token) {
|
||||
found = tuple;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (found == nullptr) {
|
||||
found = new NativeContextTuple{};
|
||||
found->SessionKey = session;
|
||||
found->ContextToken = token;
|
||||
NativeContexts().push_back(found);
|
||||
(void)AcquireNativeSession(session);
|
||||
g_nativeRegistryEpoch.fetch_add(1, std::memory_order_acq_rel);
|
||||
}
|
||||
t_activeNativeTuple = found;
|
||||
t_activeNativeEpoch = g_nativeRegistryEpoch.load(std::memory_order_acquire);
|
||||
t_activeNativeSession = session;
|
||||
t_activeNativeToken = token;
|
||||
return *found;
|
||||
}
|
||||
|
||||
static NativeContextTuple* FindNativeContext(Uint64 sessionKey, Uint64 contextToken) {
|
||||
for (auto* tuple : NativeContexts()) {
|
||||
if (tuple->SessionKey == sessionKey && tuple->ContextToken == contextToken) return tuple;
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
Uint64 NativeContextCount() {
|
||||
const std::lock_guard<std::mutex> lock(g_nativeRegistryMutex);
|
||||
Uint64 count = 0;
|
||||
for (auto* tuple : NativeContexts()) {
|
||||
if (tuple->Context != EGL_NO_CONTEXT) ++count;
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
Uint64 NativeContextCountForSession(Uint64 sessionKey) {
|
||||
const std::lock_guard<std::mutex> lock(g_nativeRegistryMutex);
|
||||
Uint64 count = 0;
|
||||
for (auto* tuple : NativeContexts()) {
|
||||
if (tuple->SessionKey == sessionKey && tuple->Context != EGL_NO_CONTEXT) ++count;
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
EGLContext NativeContextHandleFor(Uint64 sessionKey, Uint64 contextToken) {
|
||||
const std::lock_guard<std::mutex> lock(g_nativeRegistryMutex);
|
||||
const NativeContextTuple* tuple = FindNativeContext(sessionKey, contextToken);
|
||||
return tuple != nullptr ? tuple->Context : EGL_NO_CONTEXT;
|
||||
}
|
||||
|
||||
void ForceNativeContextKeyForTesting(Uint64 sessionKey, Uint64 contextToken) {
|
||||
t_forcedNativeSession = sessionKey;
|
||||
t_forcedNativeToken = contextToken;
|
||||
t_forcedNativeKeyValid = true;
|
||||
// The cache is keyed on the effective key, so drop it rather than let a stale entry answer.
|
||||
t_activeNativeTuple = nullptr;
|
||||
t_activeNativeEpoch = 0;
|
||||
}
|
||||
|
||||
// The display's one-time initialization. Returns false only when there is no EGL to talk to.
|
||||
static Bool EnsureDisplayInitialized() {
|
||||
if (g_Display != EGL_NO_DISPLAY) return true;
|
||||
if (!g_EGLFuncs.eglGetDisplay) return false;
|
||||
g_Display = g_EGLFuncs.eglGetDisplay(EGL_DEFAULT_DISPLAY);
|
||||
if (g_Display == EGL_NO_DISPLAY) return false;
|
||||
if (!g_EGLFuncs.eglInitialize(g_Display, nullptr, nullptr)) {
|
||||
g_Display = EGL_NO_DISPLAY;
|
||||
return false;
|
||||
}
|
||||
if (g_EGLFuncs.eglBindAPI) g_EGLFuncs.eglBindAPI(EGL_OPENGL_ES_API);
|
||||
return true;
|
||||
}
|
||||
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
// P12 (on-screen server window), D3: true only while InitWindowSurface publishes the default
|
||||
@@ -16199,14 +16410,17 @@ namespace MobileGL::MG_Backend::DirectGLES {
|
||||
static Bool QueryCurrentSurfaceSize(Int& outWidth, Int& outHeight) {
|
||||
outWidth = 0;
|
||||
outHeight = 0;
|
||||
if (!g_EGLFuncs.eglQuerySurface || g_Display == EGL_NO_DISPLAY || g_Surface == EGL_NO_SURFACE) {
|
||||
// P14 S4: the surface is the SESSION's, not the process's - the tuple that draws to it is
|
||||
// one of the session's contexts.
|
||||
const EGLSurface surface = ActiveNativeSession().Draw;
|
||||
if (!g_EGLFuncs.eglQuerySurface || g_Display == EGL_NO_DISPLAY || surface == EGL_NO_SURFACE) {
|
||||
return false;
|
||||
}
|
||||
|
||||
EGLint width = 0;
|
||||
EGLint height = 0;
|
||||
if (!g_EGLFuncs.eglQuerySurface(g_Display, g_Surface, EGL_WIDTH, &width) ||
|
||||
!g_EGLFuncs.eglQuerySurface(g_Display, g_Surface, EGL_HEIGHT, &height) ||
|
||||
if (!g_EGLFuncs.eglQuerySurface(g_Display, surface, EGL_WIDTH, &width) ||
|
||||
!g_EGLFuncs.eglQuerySurface(g_Display, surface, EGL_HEIGHT, &height) ||
|
||||
width <= 0 || height <= 0) {
|
||||
return false;
|
||||
}
|
||||
@@ -16277,15 +16491,17 @@ namespace MobileGL::MG_Backend::DirectGLES {
|
||||
#endif
|
||||
|
||||
// A driver that refuses the query leaves both at 0. Fall back to what the EGL config
|
||||
// was chosen with, which is what the surface actually has.
|
||||
// was chosen with, which is what the surface actually has. P14 S4: the config belongs to the
|
||||
// context the surface is bound to, so it is the active tuple's.
|
||||
const EGLConfig activeConfig = ActiveNativeContext().Config;
|
||||
if (depthBits == 0 && stencilBits == 0 && g_EGLFuncs.eglGetConfigAttrib && g_Display != EGL_NO_DISPLAY &&
|
||||
g_Config != nullptr) {
|
||||
activeConfig != nullptr) {
|
||||
EGLint eglDepth = 0;
|
||||
EGLint eglStencil = 0;
|
||||
if (g_EGLFuncs.eglGetConfigAttrib(g_Display, g_Config, EGL_DEPTH_SIZE, &eglDepth)) {
|
||||
if (g_EGLFuncs.eglGetConfigAttrib(g_Display, activeConfig, EGL_DEPTH_SIZE, &eglDepth)) {
|
||||
depthBits = static_cast<GLint>(eglDepth);
|
||||
}
|
||||
if (g_EGLFuncs.eglGetConfigAttrib(g_Display, g_Config, EGL_STENCIL_SIZE, &eglStencil)) {
|
||||
if (g_EGLFuncs.eglGetConfigAttrib(g_Display, activeConfig, EGL_STENCIL_SIZE, &eglStencil)) {
|
||||
stencilBits = static_cast<GLint>(eglStencil);
|
||||
}
|
||||
}
|
||||
@@ -16295,9 +16511,9 @@ namespace MobileGL::MG_Backend::DirectGLES {
|
||||
// PREVIOUS surface published in place, which would be stale - this function runs
|
||||
// once per surface activation, not once per process. It is written this way anyway
|
||||
// because the branch is unreachable for a surface MobileGL chose itself:
|
||||
// InitDisplayAndContext asks eglChooseConfig for EGL_DEPTH_SIZE 24 and
|
||||
// EGL_STENCIL_SIZE 8, and so does its alpha-free retry, so g_Config always has both
|
||||
// and the EGL fallback above always answers. A caller that supplies its own
|
||||
// ChooseConfigForSurface asks eglChooseConfig for EGL_DEPTH_SIZE 24 and
|
||||
// EGL_STENCIL_SIZE 8, and so does its alpha-free retry, so the context's config always
|
||||
// has both and the EGL fallback above always answers. A caller that supplies its own
|
||||
// depth-less config would keep the previous surface's description; publishing a
|
||||
// guess instead would be a different lie, and the placeholder attachment model has
|
||||
// no way to say "this buffer does not exist" short of detaching it.
|
||||
@@ -16569,32 +16785,54 @@ namespace MobileGL::MG_Backend::DirectGLES {
|
||||
return true;
|
||||
}
|
||||
|
||||
static Bool InitDisplayAndContext(EGLint surfaceBit, NativeWindowType window = static_cast<NativeWindowType>(0)) {
|
||||
DestroyEGLContext();
|
||||
|
||||
// P14 S4. THE CONTEXT FOR `tuple`, AND THE SURFACE'S CONFIG, WITH NO TEARDOWN IN FRONT.
|
||||
//
|
||||
// The S4 deletion is the first statement this function used to begin with: `DestroyEGLContext()`
|
||||
// ran UNCONDITIONALLY, so creating a second surface (let alone a second context) destroyed the
|
||||
// native context the first one's objects lived in. A tuple that already has a native context
|
||||
// keeps it and only (re)chooses the config the new surface is created with; a tuple that has
|
||||
// none builds one, sharing with the group leader when CreateNativeContextFor named a group.
|
||||
//
|
||||
// A CONFIG THAT IS ALREADY SET IS NOT RE-CHOSEN FOR A DIFFERENT SURFACE KIND, and that is the
|
||||
// deliberate trade: an EGLSurface's config must be compatible with the context's, so re-choosing
|
||||
// would mean recreating the context - exactly the teardown this slice deletes. A driver that
|
||||
// refuses the resulting eglCreate*Surface refuses it by name, which is the honest failure.
|
||||
// P14 S4. THE BRING-UP DIAGNOSIS, in one place because BOTH surface paths owe it (it used to be
|
||||
// the first statement of InitDisplayAndContext, which both went through). Extracted rather than
|
||||
// duplicated when that function was replaced by the per-tuple EnsureNativeContext.
|
||||
//
|
||||
// Diagnose, and deliberately NOT resolve: resolving raises
|
||||
// Fatal{PipeLegacyMemosDisabled}, and this function runs inside eglMakeCurrent, which
|
||||
// the integration harness pre-flights in a FORKED CHILD
|
||||
// (MG_IntegrationTest/Harness/HeadlessGL.cpp). A child that dies on a signal is reported
|
||||
// to the parent as "no usable GPU/display/ICD" and every scenario in the lane is
|
||||
// SKIPPED - so the stop became a green lane that ran nothing, on exactly the two env
|
||||
// vars the D14/D18 A/B is driven with (ROADMAP.md:7). The stop now belongs to the first
|
||||
// twin lookup, which happens in a scenario body where a crash IS a test failure.
|
||||
static void DiagnoseEsprytSlotArmAtBringUp() {
|
||||
#if MOBILEGL_PIPE_PUSH
|
||||
// DIAGNOSE the twin-table arm here, at backend startup, so an operator who set
|
||||
// MOBILEGL_PIPE_PUSH and MOBILEGL_PIPE_LEGACY_MEMOS into a combination that leaves no
|
||||
// arm at all is told so by name, in the log, before the first draw.
|
||||
//
|
||||
// Diagnose, and deliberately NOT resolve: resolving raises
|
||||
// Fatal{PipeLegacyMemosDisabled}, and this function runs inside eglMakeCurrent, which
|
||||
// the integration harness pre-flights in a FORKED CHILD
|
||||
// (MG_IntegrationTest/Harness/HeadlessGL.cpp). A child that dies on a signal is reported
|
||||
// to the parent as "no usable GPU/display/ICD" and every scenario in the lane is
|
||||
// SKIPPED - so the stop became a green lane that ran nothing, on exactly the two env
|
||||
// vars the D14/D18 A/B is driven with (ROADMAP.md:7). The stop now belongs to the first
|
||||
// twin lookup, which happens in a scenario body where a crash IS a test failure.
|
||||
DiagnoseEsprytSlotArm();
|
||||
#endif
|
||||
}
|
||||
|
||||
g_Display = g_EGLFuncs.eglGetDisplay(EGL_DEFAULT_DISPLAY);
|
||||
if (g_Display == EGL_NO_DISPLAY) return false;
|
||||
static Bool EnsureNativeContext(NativeContextTuple& tuple, EGLint surfaceBit, NativeWindowType window) {
|
||||
if (!EnsureDisplayInitialized()) return false;
|
||||
if (tuple.Context != EGL_NO_CONTEXT) return true;
|
||||
|
||||
if (!g_EGLFuncs.eglInitialize(g_Display, nullptr, nullptr)) return false;
|
||||
g_EGLFuncs.eglBindAPI(EGL_OPENGL_ES_API);
|
||||
if (tuple.Config == nullptr && !ChooseConfigForSurface(surfaceBit, tuple.Config, window)) return false;
|
||||
|
||||
if (!ChooseConfigForSurface(surfaceBit, g_Config, window)) return false;
|
||||
// A share group whose leader has a live native context hands it to eglCreateContext: this is
|
||||
// the whole of "shared contexts see the same objects" on the server. The group is recorded
|
||||
// by CreateNativeContextFor before this runs; a tuple nobody named a group for starts one.
|
||||
EGLContext share = EGL_NO_CONTEXT;
|
||||
for (auto* other : NativeContexts()) {
|
||||
if (other != &tuple && other->SessionKey == tuple.SessionKey &&
|
||||
other->Context != EGL_NO_CONTEXT && tuple.ShareGroupToken != 0 &&
|
||||
other->ShareGroupToken == tuple.ShareGroupToken) {
|
||||
share = other->Context;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Negotiate the highest ES 3.x context. Version-strict EGL implementations
|
||||
// (ANGLE) return exactly the requested minor, and a bare CLIENT_VERSION 3
|
||||
@@ -16605,15 +16843,83 @@ namespace MobileGL::MG_Backend::DirectGLES {
|
||||
const EGLint contextAttribs[] = {EGL_CONTEXT_MAJOR_VERSION, 3,
|
||||
EGL_CONTEXT_MINOR_VERSION, minorVersion,
|
||||
EGL_NONE};
|
||||
g_Context = g_EGLFuncs.eglCreateContext(g_Display, g_Config, EGL_NO_CONTEXT, contextAttribs);
|
||||
if (g_Context != EGL_NO_CONTEXT) {
|
||||
tuple.Context = g_EGLFuncs.eglCreateContext(g_Display, tuple.Config, share, contextAttribs);
|
||||
if (tuple.Context != EGL_NO_CONTEXT) {
|
||||
++g_displayUsers;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
const EGLint legacyContextAttribs[] = {EGL_CONTEXT_CLIENT_VERSION, 3, EGL_NONE};
|
||||
g_Context = g_EGLFuncs.eglCreateContext(g_Display, g_Config, EGL_NO_CONTEXT, legacyContextAttribs);
|
||||
return g_Context != EGL_NO_CONTEXT;
|
||||
tuple.Context = g_EGLFuncs.eglCreateContext(g_Display, tuple.Config, share, legacyContextAttribs);
|
||||
if (tuple.Context == EGL_NO_CONTEXT) return false;
|
||||
++g_displayUsers;
|
||||
return true;
|
||||
}
|
||||
|
||||
Bool CreateNativeContextFor(Uint64 contextToken, Uint64 shareGroupToken) {
|
||||
if (contextToken == 0) return false;
|
||||
const Uint64 sessionKey = CurrentNativeSessionKey();
|
||||
NativeContextTuple* tuple = nullptr;
|
||||
{
|
||||
const std::lock_guard<std::mutex> lock(g_nativeRegistryMutex);
|
||||
AcquireNativeSession(sessionKey);
|
||||
for (auto* candidate : NativeContexts()) {
|
||||
if (candidate->SessionKey == sessionKey && candidate->ContextToken == contextToken) {
|
||||
tuple = candidate;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (tuple == nullptr) {
|
||||
tuple = new NativeContextTuple{};
|
||||
tuple->SessionKey = sessionKey;
|
||||
tuple->ContextToken = contextToken;
|
||||
NativeContexts().push_back(tuple);
|
||||
g_nativeRegistryEpoch.fetch_add(1, std::memory_order_acq_rel);
|
||||
}
|
||||
}
|
||||
if (tuple->Context != EGL_NO_CONTEXT) return true; // idempotent
|
||||
tuple->ShareGroupToken = shareGroupToken;
|
||||
return EnsureNativeContext(*tuple, EGL_PBUFFER_BIT, static_cast<NativeWindowType>(0));
|
||||
}
|
||||
|
||||
void DestroyNativeContextFor(Uint64 contextToken) {
|
||||
const Uint64 sessionKey = CurrentNativeSessionKey();
|
||||
if (contextToken == 0) return;
|
||||
const std::lock_guard<std::mutex> lock(g_nativeRegistryMutex);
|
||||
NativeContextTuple* tuple = FindNativeContext(sessionKey, contextToken);
|
||||
if (tuple == nullptr || tuple->Context == EGL_NO_CONTEXT) return;
|
||||
if (g_EGLFuncs.eglDestroyContext && g_Display != EGL_NO_DISPLAY) {
|
||||
// The context may be current on this very thread; unbinding first is what EGL requires
|
||||
// (eglDestroyContext of a current context is EGL_BAD_ACCESS).
|
||||
if (g_EGLFuncs.eglGetCurrentContext && g_EGLFuncs.eglGetCurrentContext() == tuple->Context &&
|
||||
g_EGLFuncs.eglMakeCurrent) {
|
||||
g_EGLFuncs.eglMakeCurrent(g_Display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
|
||||
}
|
||||
g_EGLFuncs.eglDestroyContext(g_Display, tuple->Context);
|
||||
}
|
||||
tuple->Context = EGL_NO_CONTEXT;
|
||||
tuple->Config = nullptr;
|
||||
tuple->Draw = EGL_NO_SURFACE;
|
||||
tuple->Read = EGL_NO_SURFACE;
|
||||
g_nativeRegistryEpoch.fetch_add(1, std::memory_order_acq_rel);
|
||||
if (g_displayUsers > 0) --g_displayUsers;
|
||||
if (g_displayUsers == 0 && g_Display != EGL_NO_DISPLAY && g_EGLFuncs.eglTerminate) {
|
||||
g_EGLFuncs.eglTerminate(g_Display);
|
||||
g_Display = EGL_NO_DISPLAY;
|
||||
}
|
||||
}
|
||||
|
||||
// P14 S4. THE NATIVE HALF OF A CONTEXT SWITCH. See DirectGLES.h; in one line, `bind_context`
|
||||
// moves the session's context attribution and this makes the calling thread's native tuple
|
||||
// follow it, binding the session's current surface to the newly named context's EGLContext.
|
||||
Bool MakeNativeContextCurrentForBoundToken() {
|
||||
NativeContextTuple& tuple = ActiveNativeContext();
|
||||
// Nothing to switch to: a session that never sent CreateContext has no native context for
|
||||
// this token, and building one here would bind a context the client does not know it has.
|
||||
if (tuple.Context == EGL_NO_CONTEXT) return true;
|
||||
if (t_boundNativeContext == tuple.Context) return true;
|
||||
return MakeCurrent();
|
||||
}
|
||||
|
||||
namespace {
|
||||
@@ -16624,7 +16930,8 @@ namespace MobileGL::MG_Backend::DirectGLES {
|
||||
|
||||
void ApplyRequestedSwapInterval() {
|
||||
if (g_requestedSwapInterval < 0) return;
|
||||
if (!g_EGLFuncs.eglSwapInterval || g_Display == EGL_NO_DISPLAY || g_Surface == EGL_NO_SURFACE) return;
|
||||
const EGLSurface surface = ActiveNativeSession().Draw;
|
||||
if (!g_EGLFuncs.eglSwapInterval || g_Display == EGL_NO_DISPLAY || surface == EGL_NO_SURFACE) return;
|
||||
const EGLBoolean ok = g_EGLFuncs.eglSwapInterval(g_Display, g_requestedSwapInterval);
|
||||
MGLOG_D("DirectGLES: applied native swap interval %d (%s)", g_requestedSwapInterval,
|
||||
ok ? "ok" : "failed");
|
||||
@@ -16643,10 +16950,19 @@ namespace MobileGL::MG_Backend::DirectGLES {
|
||||
Bool InitWindowSurface(NativeWindowType window) {
|
||||
if (!window) return false;
|
||||
|
||||
if (!InitDisplayAndContext(EGL_WINDOW_BIT, window)) return false;
|
||||
DiagnoseEsprytSlotArmAtBringUp();
|
||||
|
||||
g_Surface = g_EGLFuncs.eglCreateWindowSurface(g_Display, g_Config, window, nullptr);
|
||||
if (g_Surface == EGL_NO_SURFACE) return false;
|
||||
NativeContextTuple& tuple = ActiveNativeContext();
|
||||
if (!EnsureNativeContext(tuple, EGL_WINDOW_BIT, window)) return false;
|
||||
|
||||
const EGLSurface surface = g_EGLFuncs.eglCreateWindowSurface(g_Display, tuple.Config, window, nullptr);
|
||||
if (surface == EGL_NO_SURFACE) return false;
|
||||
NativeSessionState& session = ActiveNativeSession();
|
||||
session.Surfaces.push_back(surface);
|
||||
session.Draw = surface;
|
||||
session.Read = surface;
|
||||
tuple.Draw = surface;
|
||||
tuple.Read = surface;
|
||||
|
||||
if (!MakeCurrent()) return false;
|
||||
|
||||
@@ -16663,25 +16979,35 @@ namespace MobileGL::MG_Backend::DirectGLES {
|
||||
PublishDefaultFramebufferDepthStencilFormat();
|
||||
#endif
|
||||
|
||||
MGLOG_D("EGL context created successfully: display=%p, surface=%p, context=%p. window=%p", g_Display, g_Surface,
|
||||
g_Context, window);
|
||||
MGLOG_D("EGL window surface created successfully: display=%p, surface=%p, context=%p. window=%p", g_Display,
|
||||
surface, tuple.Context, window);
|
||||
return true;
|
||||
}
|
||||
|
||||
Bool InitPbufferSurface(EGLint width, EGLint height) {
|
||||
if (width <= 0 || height <= 0) return false;
|
||||
if (!InitDisplayAndContext(EGL_PBUFFER_BIT)) return false;
|
||||
|
||||
DiagnoseEsprytSlotArmAtBringUp();
|
||||
|
||||
NativeContextTuple& tuple = ActiveNativeContext();
|
||||
if (!EnsureNativeContext(tuple, EGL_PBUFFER_BIT, static_cast<NativeWindowType>(0))) return false;
|
||||
|
||||
const EGLint surfaceAttribs[] = {EGL_WIDTH, width, EGL_HEIGHT, height, EGL_NONE};
|
||||
g_Surface = g_EGLFuncs.eglCreatePbufferSurface(g_Display, g_Config, surfaceAttribs);
|
||||
if (g_Surface == EGL_NO_SURFACE) return false;
|
||||
const EGLSurface surface = g_EGLFuncs.eglCreatePbufferSurface(g_Display, tuple.Config, surfaceAttribs);
|
||||
if (surface == EGL_NO_SURFACE) return false;
|
||||
NativeSessionState& session = ActiveNativeSession();
|
||||
session.Surfaces.push_back(surface);
|
||||
session.Draw = surface;
|
||||
session.Read = surface;
|
||||
tuple.Draw = surface;
|
||||
tuple.Read = surface;
|
||||
|
||||
if (!MakeCurrent()) return false;
|
||||
|
||||
PublishDefaultFramebufferDepthStencilFormat();
|
||||
|
||||
MGLOG_D("EGL pbuffer context created successfully: display=%p, surface=%p, context=%p. size=%dx%d", g_Display,
|
||||
g_Surface, g_Context, width, height);
|
||||
MGLOG_D("EGL pbuffer surface created successfully: display=%p, surface=%p, context=%p. size=%dx%d", g_Display,
|
||||
surface, tuple.Context, width, height);
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -16749,17 +17075,24 @@ namespace MobileGL::MG_Backend::DirectGLES {
|
||||
void InvalidateEglVerifiedStamp();
|
||||
|
||||
Bool MakeCurrent() {
|
||||
if (!g_EGLFuncs.eglMakeCurrent || g_Display == EGL_NO_DISPLAY || g_Surface == EGL_NO_SURFACE ||
|
||||
g_Context == EGL_NO_CONTEXT) {
|
||||
// P14 S4: the context comes from the calling thread's tuple (the session's bound token),
|
||||
// the surface from the session. Both halves used to be file-level singletons.
|
||||
NativeContextTuple& tuple = ActiveNativeContext();
|
||||
NativeSessionState& session = ActiveNativeSession();
|
||||
tuple.Draw = session.Draw;
|
||||
tuple.Read = session.Read;
|
||||
if (!g_EGLFuncs.eglMakeCurrent || g_Display == EGL_NO_DISPLAY || session.Draw == EGL_NO_SURFACE ||
|
||||
tuple.Context == EGL_NO_CONTEXT) {
|
||||
MGLOG_E_ONCE("DirectGLES::MakeCurrent failed: EGL display/surface/context is not initialized");
|
||||
return false;
|
||||
}
|
||||
if (!g_EGLFuncs.eglMakeCurrent(g_Display, g_Surface, g_Surface, g_Context)) {
|
||||
if (!g_EGLFuncs.eglMakeCurrent(g_Display, session.Draw, session.Draw, tuple.Context)) {
|
||||
const EGLint error = g_EGLFuncs.eglGetError ? g_EGLFuncs.eglGetError() : EGL_SUCCESS;
|
||||
MGLOG_E_ONCE("DirectGLES::MakeCurrent failed: native eglMakeCurrent returned error 0x%04x", error);
|
||||
return false;
|
||||
}
|
||||
InvalidateEglVerifiedStamp();
|
||||
t_boundNativeContext = tuple.Context;
|
||||
g_backendContextOwnerThread.store(std::this_thread::get_id(), std::memory_order_release);
|
||||
// The ops table may have been unregistered when a previous ES context was
|
||||
// destroyed (e.g. a probe context); re-register now that GL is usable.
|
||||
@@ -16802,6 +17135,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
|
||||
// legally arrive on a thread other than the current owner); erring towards
|
||||
// "not current" only defers buffer ops, which is always safe.
|
||||
InvalidateEglVerifiedStamp();
|
||||
t_boundNativeContext = EGL_NO_CONTEXT;
|
||||
g_backendContextOwnerThread.store(std::thread::id{}, std::memory_order_release);
|
||||
return true;
|
||||
}
|
||||
@@ -16832,7 +17166,8 @@ namespace MobileGL::MG_Backend::DirectGLES {
|
||||
}
|
||||
|
||||
Bool IsBackendContextCurrentOnThisThread() {
|
||||
if (g_Context == EGL_NO_CONTEXT) {
|
||||
const NativeContextTuple& tuple = ActiveNativeContext();
|
||||
if (tuple.Context == EGL_NO_CONTEXT) {
|
||||
return false;
|
||||
}
|
||||
if (g_backendContextOwnerThread.load(std::memory_order_acquire) != std::this_thread::get_id()) {
|
||||
@@ -16850,7 +17185,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
|
||||
g_eglVerifiedContextGeneration.load(std::memory_order_relaxed) == g_syncContextGeneration) {
|
||||
return true;
|
||||
}
|
||||
if (g_EGLFuncs.eglGetCurrentContext && g_EGLFuncs.eglGetCurrentContext() != g_Context) {
|
||||
if (g_EGLFuncs.eglGetCurrentContext && g_EGLFuncs.eglGetCurrentContext() != tuple.Context) {
|
||||
return false;
|
||||
}
|
||||
g_eglVerifiedFrameSerial.store(frameSerial, std::memory_order_relaxed);
|
||||
@@ -17267,7 +17602,8 @@ namespace MobileGL::MG_Backend::DirectGLES {
|
||||
slot = {g_GLESFuncs.glFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0), g_syncContextGeneration, serial};
|
||||
}
|
||||
|
||||
g_EGLFuncs.eglSwapBuffers(g_Display, g_Surface);
|
||||
// P14 S4: the session's surface, not the process's.
|
||||
g_EGLFuncs.eglSwapBuffers(g_Display, ActiveNativeSession().Draw);
|
||||
|
||||
if (canFence && g_GLESFuncs.glGetSynciv) {
|
||||
// Fences signal in submission order within one context, so the highest
|
||||
@@ -17301,6 +17637,17 @@ namespace MobileGL::MG_Backend::DirectGLES {
|
||||
}
|
||||
}
|
||||
|
||||
// P14 S4: THE FULL TEARDOWN, SCOPED TO THE CALLING THREAD'S SESSION.
|
||||
//
|
||||
// This used to destroy the process's one context, its one surface and terminate the display.
|
||||
// The callers (ReleaseEGLResources, ~BackendObject_DirectGLES) mean "this session's EGL world
|
||||
// goes away", so under S4 it destroys EVERY native context that session holds, its surfaces, and
|
||||
// terminates the display only when no context anywhere in the process is left - which is what
|
||||
// keeps a second live session (S2) serving while this one closes. With no resolver installed
|
||||
// there is exactly one session (key 0) and this is the old statement, byte for word.
|
||||
//
|
||||
// ONE CONTEXT's teardown is DestroyNativeContextFor (the DestroyContext control frame); this is
|
||||
// the session's.
|
||||
void DestroyEGLContext() {
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
if (MG_Config::Transport != MG_Config::TransportMode::Monolith)
|
||||
@@ -17332,16 +17679,39 @@ namespace MobileGL::MG_Backend::DirectGLES {
|
||||
for (FrameFence& slot : g_frameFenceRing) slot = {};
|
||||
g_completedFrameSerial.store(g_currentFrameSerial.load(std::memory_order_relaxed),
|
||||
std::memory_order_relaxed);
|
||||
if (g_Display != EGL_NO_DISPLAY) {
|
||||
g_EGLFuncs.eglMakeCurrent(g_Display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
|
||||
if (g_Context != EGL_NO_CONTEXT) {
|
||||
g_EGLFuncs.eglDestroyContext(g_Display, g_Context);
|
||||
g_Context = EGL_NO_CONTEXT;
|
||||
|
||||
const Uint64 sessionKey = CurrentNativeSessionKey();
|
||||
if (g_Display == EGL_NO_DISPLAY) return;
|
||||
{
|
||||
const std::lock_guard<std::mutex> lock(g_nativeRegistryMutex);
|
||||
if (g_EGLFuncs.eglMakeCurrent) {
|
||||
g_EGLFuncs.eglMakeCurrent(g_Display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
|
||||
}
|
||||
if (g_Surface != EGL_NO_SURFACE) {
|
||||
g_EGLFuncs.eglDestroySurface(g_Display, g_Surface);
|
||||
g_Surface = EGL_NO_SURFACE;
|
||||
for (auto* tuple : NativeContexts()) {
|
||||
if (tuple->SessionKey != sessionKey || tuple->Context == EGL_NO_CONTEXT) continue;
|
||||
if (g_EGLFuncs.eglDestroyContext) g_EGLFuncs.eglDestroyContext(g_Display, tuple->Context);
|
||||
tuple->Context = EGL_NO_CONTEXT;
|
||||
tuple->Config = nullptr;
|
||||
tuple->Draw = EGL_NO_SURFACE;
|
||||
tuple->Read = EGL_NO_SURFACE;
|
||||
if (g_displayUsers > 0) --g_displayUsers;
|
||||
}
|
||||
for (auto* session : NativeSessions()) {
|
||||
if (session->SessionKey != sessionKey) continue;
|
||||
if (g_EGLFuncs.eglDestroySurface) {
|
||||
for (const EGLSurface surface : session->Surfaces) {
|
||||
if (surface != EGL_NO_SURFACE) g_EGLFuncs.eglDestroySurface(g_Display, surface);
|
||||
}
|
||||
}
|
||||
session->Surfaces.clear();
|
||||
session->Draw = EGL_NO_SURFACE;
|
||||
session->Read = EGL_NO_SURFACE;
|
||||
}
|
||||
g_nativeRegistryEpoch.fetch_add(1, std::memory_order_acq_rel);
|
||||
}
|
||||
// THE LAST CONTEXT ANYWHERE IN THE PROCESS IS WHAT TERMINATES THE DISPLAY. A session that
|
||||
// closes while another is rendering must not take eglTerminate with it.
|
||||
if (g_displayUsers == 0 && g_EGLFuncs.eglTerminate) {
|
||||
g_EGLFuncs.eglTerminate(g_Display);
|
||||
g_Display = EGL_NO_DISPLAY;
|
||||
}
|
||||
|
||||
@@ -204,6 +204,61 @@ 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);
|
||||
|
||||
// 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);
|
||||
|
||||
// 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();
|
||||
// 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
|
||||
@@ -249,26 +304,6 @@ namespace MobileGL::MG_Backend::DirectGLES {
|
||||
void InvalidateSyncedRenderState();
|
||||
} // namespace RenderStateImpl
|
||||
|
||||
// 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;
|
||||
|
||||
@@ -1,208 +0,0 @@
|
||||
// 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
|
||||
@@ -1,52 +0,0 @@
|
||||
// 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);
|
||||
}
|
||||
@@ -2983,6 +2983,67 @@ 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
|
||||
@@ -2993,7 +3054,9 @@ 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.
|
||||
// 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).
|
||||
// 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) {
|
||||
@@ -3046,7 +3109,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[256] = {};
|
||||
char detail[512] = {};
|
||||
if (imported == 0) {
|
||||
std::snprintf(detail, sizeof(detail), "import: %s", why.c_str());
|
||||
} else if (std::memcmp(hostMap, pattern.data(), kWords * 4) != 0) {
|
||||
@@ -3096,6 +3159,7 @@ 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);
|
||||
@@ -3183,7 +3247,6 @@ 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;
|
||||
}
|
||||
}
|
||||
@@ -10152,7 +10215,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() : (SizeT)0,
|
||||
m_backendTextureId, backendId, buffer ? buffer->GetSize() : rangeSize,
|
||||
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
|
||||
@@ -11283,45 +11346,9 @@ 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);
|
||||
// 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()));
|
||||
}
|
||||
g_GLESFuncs.glFramebufferTexture2D(glFBOTarget, glBackendAttachment, glTextureTarget,
|
||||
backendTextureObject->GetBackendTextureId(),
|
||||
static_cast<GLint>(attachmentObject.GetTextureLevel()));
|
||||
}
|
||||
} else if (attachmentObject.IsRenderbuffer()) {
|
||||
const auto& renderbufferObject = attachmentObject.GetRenderbuffer();
|
||||
@@ -11637,23 +11664,6 @@ 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
|
||||
@@ -11737,38 +11747,9 @@ 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);
|
||||
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));
|
||||
}
|
||||
g_GLESFuncs.glFramebufferTexture2D(glFBOTarget, glBackendAttachment, glTextureTarget,
|
||||
backendTextureObject->GetBackendTextureId(),
|
||||
static_cast<GLint>(surface.Level));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
@@ -14133,7 +14114,8 @@ 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.
|
||||
// first time this gate was missing (the original capture; the case is now
|
||||
// minecraft-1.21.1-neoforge-create-indirect-in-world-align1024).
|
||||
effectiveSpirv = &splitArrayInputSpirv;
|
||||
}
|
||||
|
||||
@@ -14141,8 +14123,10 @@ 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 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 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,
|
||||
// and its own rewrite must still be taken or the two stages stop matching.
|
||||
Vector<unsigned int> flattenedXfbSpirv;
|
||||
if (!xfbCaptureBlockNames.empty()) {
|
||||
@@ -14861,8 +14845,10 @@ 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): 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; 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
|
||||
// stage is rewritten.
|
||||
std::set<String> collidingIoBlockNames;
|
||||
std::set<String> declaredIoBlockNames;
|
||||
|
||||
@@ -1879,9 +1879,6 @@ 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;
|
||||
}
|
||||
|
||||
@@ -659,38 +659,7 @@ 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,
|
||||
// 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};
|
||||
E_GL_ARB_get_program_binary};
|
||||
// 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
|
||||
|
||||
@@ -786,7 +786,9 @@ 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.
|
||||
// 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).
|
||||
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());
|
||||
@@ -909,6 +911,55 @@ 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);
|
||||
|
||||
@@ -1,737 +0,0 @@
|
||||
// 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
|
||||
@@ -1,281 +0,0 @@
|
||||
// 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;
|
||||
};
|
||||
}
|
||||
@@ -1,189 +0,0 @@
|
||||
// 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
|
||||
@@ -1,103 +0,0 @@
|
||||
// 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{};
|
||||
};
|
||||
}
|
||||
@@ -14,7 +14,6 @@
|
||||
#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>
|
||||
@@ -399,9 +398,6 @@ 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
|
||||
|
||||
|
||||
@@ -820,6 +820,10 @@ 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
|
||||
@@ -834,7 +838,48 @@ 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& gPipeInputs = *new PipeInputs();
|
||||
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();
|
||||
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
// ============================================================================
|
||||
|
||||
@@ -1,663 +0,0 @@
|
||||
// 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
@@ -1,835 +0,0 @@
|
||||
// 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
|
||||
@@ -1,476 +0,0 @@
|
||||
// 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
|
||||
@@ -17,41 +17,18 @@
|
||||
// MG_Config::ServerOwnedWindowSurfaces (P12, MOBILEGL_IPC_SURFACE). Split-only: the pull build's
|
||||
// translation unit is unchanged (G1).
|
||||
#include <Config.h>
|
||||
// P14 S1 (docs/Disaggregated/design/11-state-ownership.md). The EGL context lifecycle's
|
||||
// client half: eglCreateContext/eglDestroyContext cross as two control frames, and a
|
||||
// context switch emits the in-band bind_context record. Reached through MG_Remote::Client
|
||||
// because that is the seam MG_Impl already uses for its other wire producers
|
||||
// (PipeFill.cpp's emitters) and because the frame channel belongs to the server role - this
|
||||
// file must not name ServerLoop's forwarders directly.
|
||||
#include <MG_Remote/Client/WireTables.h>
|
||||
#endif
|
||||
#include <mutex>
|
||||
#include <sstream>
|
||||
#include <type_traits>
|
||||
|
||||
// The KHR spellings of the image entry points, exported by Exporting/Definitions.cpp. Declared
|
||||
// here because the bundled EGL headers declare them only under EGL_EGLEXT_PROTOTYPES, which no
|
||||
// build of this library defines, and because eglGetProcAddress below answers them by name.
|
||||
extern "C" EGLImageKHR eglCreateImageKHR(EGLDisplay dpy, EGLContext ctx, EGLenum target, EGLClientBuffer buffer,
|
||||
const EGLint* attrib_list);
|
||||
extern "C" EGLBoolean eglDestroyImageKHR(EGLDisplay dpy, EGLImageKHR image);
|
||||
|
||||
// The swap-and-sync family the compositor resolves by name while bringing its EGL backend up; defined
|
||||
// in Exporting/Definitions.cpp and answered from GetProcAddress below (see the definitions).
|
||||
extern "C" EGLBoolean eglSwapBuffersWithDamageKHR(EGLDisplay dpy, EGLSurface surface, const EGLint* rects,
|
||||
EGLint n_rects);
|
||||
extern "C" EGLBoolean eglSwapBuffersWithDamageEXT(EGLDisplay dpy, EGLSurface surface, const EGLint* rects,
|
||||
EGLint n_rects);
|
||||
extern "C" EGLSyncKHR eglCreateSyncKHR(EGLDisplay dpy, EGLenum type, const EGLint* attrib_list);
|
||||
extern "C" EGLBoolean eglDestroySyncKHR(EGLDisplay dpy, EGLSyncKHR sync);
|
||||
extern "C" EGLint eglClientWaitSyncKHR(EGLDisplay dpy, EGLSyncKHR sync, EGLint flags, EGLTimeKHR timeout);
|
||||
extern "C" EGLBoolean eglWaitSyncKHR(EGLDisplay dpy, EGLSyncKHR sync, EGLint flags);
|
||||
extern "C" EGLBoolean eglGetSyncAttribKHR(EGLDisplay dpy, EGLSyncKHR sync, EGLint attribute, EGLint* value);
|
||||
// THE DEVICE-QUERY FAMILY, exported by Exporting/Definitions.cpp and answered by name below: kwin
|
||||
// reaches eglQueryDisplayAttribEXT through libepoxy's pointer (that is how finding a render device
|
||||
// starts), and libepoxy asks for it by name. See the definitions for why these had to exist.
|
||||
extern "C" EGLBoolean eglQueryDevicesEXT(EGLint max_devices, EGLDeviceEXT* devices, EGLint* num_devices);
|
||||
extern "C" EGLBoolean eglQueryDeviceAttribEXT(EGLDeviceEXT device, EGLint attribute, EGLAttrib* value);
|
||||
extern "C" const char* eglQueryDeviceStringEXT(EGLDeviceEXT device, EGLint name);
|
||||
extern "C" EGLBoolean eglQueryDisplayAttribEXT(EGLDisplay dpy, EGLint attribute, EGLAttrib* value);
|
||||
extern "C" EGLSurface eglCreatePlatformWindowSurfaceEXT(EGLDisplay dpy, EGLConfig config, void* native_window,
|
||||
const EGLAttrib* attrib_list);
|
||||
extern "C" EGLSurface eglCreatePlatformPixmapSurfaceEXT(EGLDisplay dpy, EGLConfig config, void* native_pixmap,
|
||||
const EGLAttrib* attrib_list);
|
||||
|
||||
namespace MobileGL::MG_Impl::EGLImpl {
|
||||
namespace {
|
||||
using EGLStateContext = MG_State::EGLState::EGLContext;
|
||||
@@ -82,6 +59,35 @@ namespace MobileGL::MG_Impl::EGLImpl {
|
||||
return backendObject;
|
||||
}
|
||||
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
// P14 S1 (docs/Disaggregated/design/11-state-ownership.md). THE CONTEXT BINDING, AND
|
||||
// THE ONE PLACE IT IS EMITTED.
|
||||
//
|
||||
// `bind_context` is the ring's half of eglMakeCurrent: the MakeCurrent control frame
|
||||
// tells the server which native tuple to hold, and this record tells it which CONTEXT
|
||||
// every record after it belongs to - the attribution the session table was built for.
|
||||
//
|
||||
// IT IS EMITTED AFTER THE SWITCH HAS SUCCEEDED AND BEFORE eglMakeCurrent RETURNS, and
|
||||
// that is the whole ordering argument: the app thread cannot publish a record of the
|
||||
// new context until this call has returned, and the ring is FIFO, so the binding is
|
||||
// behind no verb of the context it names and ahead of every one that follows. Waiting
|
||||
// for the first verb instead would need the emitter to know which context the tracker
|
||||
// is about to prime; this needs only the token EGLState already holds.
|
||||
//
|
||||
// An unchanged token emits NOTHING: an identical eglMakeCurrent is a legal no-op in
|
||||
// EGL and the session is already bound to that context.
|
||||
void EmitContextBinding(EGLStateContext* state, EGLContext switched, Uint64 previousToken) {
|
||||
if (MG_Config::Transport == MG_Config::TransportMode::Monolith) return;
|
||||
// The apply thread IS the server in this process; a record emitted there would
|
||||
// wait on the thread that has to apply it (EmitAndWait), which is a deadlock and
|
||||
// not a slow path.
|
||||
if (MG_Remote::Client::RunsAsTheServerRole()) return;
|
||||
const Uint64 token = switched == EGL_NO_CONTEXT ? 0 : state->GetContextClientToken(switched);
|
||||
if (token == previousToken) return;
|
||||
(void)MG_Remote::Client::EmitBindContextRecord(token);
|
||||
}
|
||||
#endif
|
||||
|
||||
std::recursive_mutex& EGLOperationMutex() {
|
||||
static std::recursive_mutex mutex;
|
||||
return mutex;
|
||||
@@ -246,11 +252,8 @@ namespace MobileGL::MG_Impl::EGLImpl {
|
||||
// the window is the SERVER's: a headless client passes none, so NULL is not
|
||||
// EGL_BAD_NATIVE_WINDOW here. Whatever the client passed never reaches the wire - the
|
||||
// remote backend sends WindowKind::ServerOwned with token 0 (BackendObject_Remote).
|
||||
// Either on-screen shape leaves this side without a window of its own: =server asks the
|
||||
// server for its own window, =host draws into the frames the display host offers.
|
||||
const Bool windowlessOnScreen =
|
||||
MG_Config::ServerOwnedWindowSurfaces() || MG_Config::HostFrameWindowSurfaces();
|
||||
if (IsNullNativeHandle(window) && !windowlessOnScreen) {
|
||||
const Bool serverOwnedWindow = MG_Config::ServerOwnedWindowSurfaces();
|
||||
if (IsNullNativeHandle(window) && !serverOwnedWindow) {
|
||||
#else
|
||||
if (IsNullNativeHandle(window)) {
|
||||
#endif
|
||||
@@ -269,15 +272,15 @@ namespace MobileGL::MG_Impl::EGLImpl {
|
||||
// alike; the same game in a landscape window was right). The native window it handed us
|
||||
// knows the size the game believes it has: ask for THAT, and the server fixes its window
|
||||
// buffer to it and aspect-fits the view (MobileGLDisplayActivity), letterboxed.
|
||||
if (windowlessOnScreen && requestedWidth == 0 && requestedHeight == 0 && !IsNullNativeHandle(window)) {
|
||||
if (serverOwnedWindow && requestedWidth == 0 && requestedHeight == 0 && !IsNullNativeHandle(window)) {
|
||||
auto* native = reinterpret_cast<ANativeWindow*>(ToVoidHandle(window));
|
||||
const int32_t nativeWidth = ANativeWindow_getWidth(native);
|
||||
const int32_t nativeHeight = ANativeWindow_getHeight(native);
|
||||
if (nativeWidth > 0 && nativeHeight > 0) {
|
||||
requestedWidth = static_cast<Uint32>(nativeWidth);
|
||||
requestedHeight = static_cast<Uint32>(nativeHeight);
|
||||
MGLOG_I("eglCreateWindowSurface: no EGL_WIDTH/EGL_HEIGHT; the on-screen surface is asked for "
|
||||
"the native window's %dx%d", nativeWidth, nativeHeight);
|
||||
MGLOG_I("eglCreateWindowSurface: no EGL_WIDTH/EGL_HEIGHT; the server-owned window is asked for the "
|
||||
"native window's %dx%d", nativeWidth, nativeHeight);
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -289,20 +292,11 @@ namespace MobileGL::MG_Impl::EGLImpl {
|
||||
};
|
||||
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
EGLSurface surface = EGL_NO_SURFACE;
|
||||
if (MG_Config::ServerOwnedWindowSurfaces()) {
|
||||
// The server's own window: it makes one and draws into it.
|
||||
surface = state->CreateServerOwnedWindowSurface(
|
||||
dpy, config, windowHandle.Handle, static_cast<EGLint>(windowHandle.Width),
|
||||
static_cast<EGLint>(windowHandle.Height), /*platformWindow=*/false);
|
||||
} else if (MG_Config::HostFrameWindowSurfaces()) {
|
||||
// The display host's frames, as above: no window of the client's either way.
|
||||
surface = state->CreateHostFrameWindowSurface(
|
||||
dpy, config, windowHandle.Handle, static_cast<EGLint>(windowHandle.Width),
|
||||
static_cast<EGLint>(windowHandle.Height), /*platformWindow=*/false);
|
||||
} else {
|
||||
surface = state->CreateWindowSurface(dpy, config, window, attrib_list);
|
||||
}
|
||||
EGLSurface surface = serverOwnedWindow
|
||||
? state->CreateServerOwnedWindowSurface(
|
||||
dpy, config, windowHandle.Handle, static_cast<EGLint>(windowHandle.Width),
|
||||
static_cast<EGLint>(windowHandle.Height), /*platformWindow=*/false)
|
||||
: state->CreateWindowSurface(dpy, config, window, attrib_list);
|
||||
#else
|
||||
EGLSurface surface = state->CreateWindowSurface(dpy, config, window, attrib_list);
|
||||
#endif
|
||||
@@ -332,7 +326,6 @@ namespace MobileGL::MG_Impl::EGLImpl {
|
||||
return EGL_FALSE;
|
||||
}
|
||||
if (!state->ValidateSurfaceOnDisplay(dpy, draw)) {
|
||||
MGLOG_E_ONCE("eglSwapBuffers: surface %p is not a surface of display %p (EGL_BAD_SURFACE)", draw, dpy);
|
||||
state->SetError(EGL_BAD_SURFACE);
|
||||
return EGL_FALSE;
|
||||
}
|
||||
@@ -345,7 +338,10 @@ namespace MobileGL::MG_Impl::EGLImpl {
|
||||
#if MOBILEGL_WAYLAND_WINDOWS
|
||||
// A Wayland window shows what is attached to it: the frame is read back and attached
|
||||
// BEFORE the swap, while it is still the drawable's content.
|
||||
if (auto it = WaylandSurfaces().find(draw); it != WaylandSurfaces().end()) (void)it->second->Present();
|
||||
if (auto it = WaylandSurfaces().find(draw); it != WaylandSurfaces().end() && !it->second->Present()) {
|
||||
state->SetError(EGL_BAD_SURFACE);
|
||||
return EGL_FALSE;
|
||||
}
|
||||
#endif
|
||||
if (!backendObject->SwapEGLBuffers(dpy, draw)) {
|
||||
MGLOG_E_ONCE("eglSwapBuffers failed on thread=%s dpy=%p draw=%p", CurrentThreadIdString().c_str(), dpy, draw);
|
||||
@@ -357,13 +353,7 @@ namespace MobileGL::MG_Impl::EGLImpl {
|
||||
|
||||
EGLBoolean ChooseConfig(EGLDisplay dpy, const EGLint* attrib_list, EGLConfig* configs, EGLint config_size,
|
||||
EGLint* num_config) {
|
||||
// eglChooseConfig can be an application's first EGL call after eglGetPlatformDisplay + eglInitialize,
|
||||
// and for a display built from an EGLDeviceEXT nothing has brought MobileGL up yet: GetState()
|
||||
// then answers NULL and the call lands in EGLContext::ChooseConfig with a null this - measured as
|
||||
// a crash inside that function (pc/lr both resolved to it) with kwin's own "pEGLContext is null.
|
||||
// MG_State may not be initialized." as the only warning, and reported one layer up as
|
||||
// "Could not initialize rendering context".
|
||||
auto* state = GetStateEnsureInitialized();
|
||||
auto* state = GetState();
|
||||
if (!state) {
|
||||
return EGL_FALSE;
|
||||
}
|
||||
@@ -371,25 +361,38 @@ namespace MobileGL::MG_Impl::EGLImpl {
|
||||
}
|
||||
|
||||
EGLContext CreateContext(EGLDisplay dpy, EGLConfig config, EGLContext shareCtx, const EGLint* attrib_list) {
|
||||
// WHICH CONTEXT IS BEING ASKED FOR, and what came back. kwin's OpenGL compositing fails with
|
||||
// "Could not initialize rendering context" while the same path succeeds from a probe against
|
||||
// this same library (probe10: a 3.3 core context on a GBM surface, makeCurrent answered 1),
|
||||
// so the difference has to be in this argument list - and an EGL vendor cannot see it from the
|
||||
// outside. The list is dumped in EGL_NONE-terminated pairs; EGL_NONE is 0x3038, not 0.
|
||||
MGLOG_I("eglCreateContext(dpy=%p, config=%p, share=%p)", dpy, config, shareCtx);
|
||||
if (attrib_list != nullptr) {
|
||||
for (int index = 0; attrib_list[index] != EGL_NONE; index += 2) {
|
||||
MGLOG_I(" attrib 0x%04x = %d", attrib_list[index], attrib_list[index + 1]);
|
||||
}
|
||||
} else {
|
||||
MGLOG_I(" (no attribute list)");
|
||||
}
|
||||
auto* state = GetStateEnsureInitialized();
|
||||
auto* state = GetState();
|
||||
if (!state) {
|
||||
return EGL_NO_CONTEXT;
|
||||
}
|
||||
EGLContext context = state->CreateContext(dpy, config, shareCtx, attrib_list);
|
||||
MGLOG_I("eglCreateContext -> %p", static_cast<void*>(context));
|
||||
const EGLContext context = state->CreateContext(dpy, config, shareCtx, attrib_list);
|
||||
if (context == EGL_NO_CONTEXT) {
|
||||
return EGL_NO_CONTEXT;
|
||||
}
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
// P14 S1 (docs/Disaggregated/design/11-state-ownership.md). THE TOKEN CROSSES BEFORE
|
||||
// eglCreateContext RETURNS. EGLState minted it, together with the share group it was
|
||||
// derived into (the sharing context's group, or a fresh one), and the server tables it
|
||||
// here through the same blocking handshake the surface forwarders use - so the first
|
||||
// bind_context after this call names a context the session already has, and the
|
||||
// sink's "this session never created that token" refusal is unreachable on the
|
||||
// well-behaved path.
|
||||
//
|
||||
// A REFUSAL DROPS THE CLIENT'S CONTEXT AGAIN. Keeping it would hand the application a
|
||||
// handle whose first verb the server refuses - a late failure where an early one is
|
||||
// available, and EGL_NO_CONTEXT with EGL_BAD_ACCESS is the early one. NoWire (the
|
||||
// pre-Start bring-up, the server role) keeps it: there is no server to refuse.
|
||||
if (MG_Config::Transport != MG_Config::TransportMode::Monolith &&
|
||||
!MG_Remote::Client::RunsAsTheServerRole()) {
|
||||
const auto emitted = MG_Remote::Client::SendCreateContextFrame(
|
||||
state->GetContextClientToken(context), state->GetContextShareGroupToken(context), 0);
|
||||
if (emitted == MG_Remote::Client::ContextFrameEmit::Refused) {
|
||||
state->DestroyContext(dpy, context);
|
||||
state->SetError(EGL_BAD_ACCESS);
|
||||
return EGL_NO_CONTEXT;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
return context;
|
||||
}
|
||||
|
||||
@@ -430,13 +433,6 @@ namespace MobileGL::MG_Impl::EGLImpl {
|
||||
return state->ConsumeError();
|
||||
}
|
||||
|
||||
// THE DISPLAY HOST'S FRAME, AS THE COMPOSITOR PRESENTS IT. Set by the surfaceless-bind hook in
|
||||
// MakeCurrent when this client (the compositor) takes the host frame; read by glFlush, which is
|
||||
// that compositor's only frame boundary - it never calls eglSwapBuffers, and without a present
|
||||
// the display host is never told a frame is done, so nothing ever reaches the glass.
|
||||
EGLDisplay g_hostFramePresentDisplay = nullptr;
|
||||
EGLSurface g_hostFramePresentSurface = nullptr;
|
||||
|
||||
EGLBoolean MakeCurrent(EGLDisplay dpy, EGLSurface draw, EGLSurface read, EGLContext ctx) {
|
||||
const std::lock_guard<std::recursive_mutex> operationLock(EGLOperationMutex());
|
||||
auto* state = GetState();
|
||||
@@ -448,86 +444,17 @@ namespace MobileGL::MG_Impl::EGLImpl {
|
||||
const auto oldDraw = state->GetCurrentSurface(EGL_DRAW);
|
||||
const auto oldRead = state->GetCurrentSurface(EGL_READ);
|
||||
const auto oldContext = state->GetCurrentContext();
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
// P14 S1. The context the calling thread had current BEFORE this call, as the wire
|
||||
// knows it. Read here because `state->MakeCurrent` below has already committed the
|
||||
// new one by the time the emission points are reached.
|
||||
const Uint64 oldContextToken = state->GetContextClientToken(oldContext);
|
||||
#endif
|
||||
const String threadId = CurrentThreadIdString();
|
||||
|
||||
MGLOG_D("eglMakeCurrent begin thread=%s dpy=%p draw=%p read=%p ctx=%p oldDpy=%p oldDraw=%p oldRead=%p oldCtx=%p",
|
||||
threadId.c_str(), dpy, draw, read, ctx, oldDisplay, oldDraw, oldRead, oldContext);
|
||||
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
// THE DISPLAY HOST'S FRAMES, TO A CLIENT THAT ASKS FOR NO SURFACE.
|
||||
//
|
||||
// A compositor on this route never calls eglCreateWindowSurface: it imports the display host's
|
||||
// dma-bufs and draws into them through framebuffers, binding its contexts with EGL_NO_SURFACE.
|
||||
// The host frame bridge, though, is opened by exactly one thing - a surface being CREATED and
|
||||
// activated (ServerLoop's CreateWindowSurface with the host-frame window backend ->
|
||||
// InitHostFrameSurface) - so with no surface ever created the bridge stayed shut, the display
|
||||
// host kept offering frames into a name nobody served ("offer buffer 0: bridge fd=-1"), and no
|
||||
// frame could reach the glass no matter how much was drawn. So: when the session asked for
|
||||
// host-framed surfaces and a real context is being bound with no surface, make it the surface
|
||||
// eglCreatePlatformWindowSurface would have made, once, and bind that. The size is the display
|
||||
// host's own frame size; the client's window value is not on this path at all.
|
||||
// ONLY THE COMPOSITOR TAKES THE HOST FRAME. A desktop is full of processes that bind a
|
||||
// context with no surface - konsole, plasmashell, kactivitymanagerd - and measured with
|
||||
// probe15 as the second client: such a bind from a NON-compositor process made the host-frame
|
||||
// activation fail (makeCurrent=0) and the process aborted. The compositor is marked by its
|
||||
// launcher with MOBILEGL_HOST_FRAME_CLIENT=1; everyone else keeps the plain surfaceless bind,
|
||||
// which is all they ever wanted.
|
||||
if (draw == EGL_NO_SURFACE && read == EGL_NO_SURFACE && ctx != EGL_NO_CONTEXT &&
|
||||
MG_Config::HostFrameWindowSurfaces() &&
|
||||
(std::getenv("MOBILEGL_HOST_FRAME_CLIENT") != nullptr &&
|
||||
std::string("1") == std::getenv("MOBILEGL_HOST_FRAME_CLIENT"))) {
|
||||
static Bool hostFrameSurfaceTaken = false;
|
||||
if (!hostFrameSurfaceTaken) {
|
||||
hostFrameSurfaceTaken = true;
|
||||
EGLConfig hostFrameConfig = nullptr;
|
||||
EGLint hostFrameConfigCount = 0;
|
||||
const EGLint hostFrameChoose[] = {EGL_SURFACE_TYPE, EGL_WINDOW_BIT, EGL_NONE};
|
||||
if (state->ChooseConfig(dpy, hostFrameChoose, &hostFrameConfig, 1,
|
||||
&hostFrameConfigCount) &&
|
||||
hostFrameConfigCount > 0 && hostFrameConfig != nullptr) {
|
||||
// BOTH HALVES, exactly as eglCreateWindowSurface makes one: the EGL state's
|
||||
// registration (without it every later bind and swap of this surface was refused
|
||||
// as EGL_BAD_SURFACE - measured: "eglMakeCurrent rejected by EGLState
|
||||
// error=0x300d", and glFlush's swaps returned before reaching the backend), then
|
||||
// the backend's own window-surface entry, which the remote backend routes to the
|
||||
// host frame (BackendObject_Remote::CreateHostFrameWindowSurface) - the call that
|
||||
// puts a CreateWindowSurface frame with the host-frame window backend on the wire.
|
||||
const EGLSurface hostFrameSurface = state->CreateHostFrameWindowSurface(
|
||||
dpy, hostFrameConfig, nullptr, 1440, 3200, /*platformWindow=*/false);
|
||||
MG_Backend::WindowHandle hostFrameHandle{};
|
||||
hostFrameHandle.Width = 1440;
|
||||
hostFrameHandle.Height = 3200;
|
||||
if (hostFrameSurface == EGL_NO_SURFACE) {
|
||||
MGLOG_E("host frame: the EGL state refused the display host's frame surface");
|
||||
} else if (!MG_Backend::pActiveBackendObject->CreateEGLWindowSurface(hostFrameSurface,
|
||||
hostFrameHandle)) {
|
||||
MGLOG_E("host frame: the backend refused the display host's frame surface");
|
||||
state->DestroySurface(dpy, hostFrameSurface);
|
||||
} else {
|
||||
// The frame boundary of a compositor that never swaps is its glFlush. glFlush
|
||||
// has no EGL context of its own, so remember HERE which surface presents the
|
||||
// display host's frame; glFlush presents it (see the host-frame present in
|
||||
// glFlush's implementation).
|
||||
g_hostFramePresentDisplay = dpy;
|
||||
g_hostFramePresentSurface = hostFrameSurface;
|
||||
MGLOG_I("host frame: the first surfaceless eglMakeCurrent made the display host's "
|
||||
"frame surface %p (%dx%d)",
|
||||
hostFrameSurface, 1440, 3200);
|
||||
}
|
||||
} else {
|
||||
MGLOG_E("host frame: no config for the display host's frame surface");
|
||||
}
|
||||
}
|
||||
// EVERY surfaceless bind, not only the first: the compositor rebinds with EGL_NO_SURFACE
|
||||
// all the time, and a bind without the surface leaves nothing current for glFlush's swap
|
||||
// to present (BackendObject::SwapEGLBuffers: "draw surface is not current on this thread").
|
||||
if (g_hostFramePresentSurface != nullptr && dpy == g_hostFramePresentDisplay) {
|
||||
draw = g_hostFramePresentSurface;
|
||||
read = g_hostFramePresentSurface;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
if (!state->MakeCurrent(dpy, draw, read, ctx)) {
|
||||
const EGLint error = state->ConsumeError();
|
||||
MGLOG_D("eglMakeCurrent rejected by EGLState thread=%s error=0x%04x", threadId.c_str(), error);
|
||||
@@ -547,6 +474,9 @@ namespace MobileGL::MG_Impl::EGLImpl {
|
||||
}
|
||||
}
|
||||
MGLOG_D("eglMakeCurrent release succeeded thread=%s", threadId.c_str());
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
EmitContextBinding(state, EGL_NO_CONTEXT, oldContextToken);
|
||||
#endif
|
||||
return EGL_TRUE;
|
||||
}
|
||||
|
||||
@@ -565,6 +495,9 @@ namespace MobileGL::MG_Impl::EGLImpl {
|
||||
}
|
||||
MGLOG_D("eglMakeCurrent attach succeeded thread=%s dpy=%p draw=%p read=%p ctx=%p", threadId.c_str(), dpy, draw,
|
||||
read, ctx);
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
EmitContextBinding(state, ctx, oldContextToken);
|
||||
#endif
|
||||
return EGL_TRUE;
|
||||
}
|
||||
|
||||
@@ -573,7 +506,29 @@ namespace MobileGL::MG_Impl::EGLImpl {
|
||||
if (!state) {
|
||||
return EGL_FALSE;
|
||||
}
|
||||
return state->DestroyContext(dpy, ctx) ? EGL_TRUE : EGL_FALSE;
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
// P14 S1. Read BEFORE the client's own book drops the context: after DestroyContext
|
||||
// the handle no longer resolves and the token is unrecoverable. The frame is sent
|
||||
// AFTER the client's state machine has accepted the destroy, so one EGL refused (a
|
||||
// context still current on some thread, EGL_BAD_ACCESS) never reaches the server - the
|
||||
// two ends stay in step without the server having to guess why a token vanished.
|
||||
const Uint64 contextToken = state->GetContextClientToken(ctx);
|
||||
#endif
|
||||
if (!state->DestroyContext(dpy, ctx)) {
|
||||
return EGL_FALSE;
|
||||
}
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
if (contextToken != 0 && MG_Config::Transport != MG_Config::TransportMode::Monolith &&
|
||||
!MG_Remote::Client::RunsAsTheServerRole()) {
|
||||
const auto emitted = MG_Remote::Client::SendDestroyContextFrame(contextToken);
|
||||
if (emitted == MG_Remote::Client::ContextFrameEmit::Refused) {
|
||||
MGLOG_E_ONCE("eglDestroyContext: the server holds no context token %llu; the "
|
||||
"session's table and this client's EGL book have drifted apart",
|
||||
static_cast<unsigned long long>(contextToken));
|
||||
}
|
||||
}
|
||||
#endif
|
||||
return EGL_TRUE;
|
||||
}
|
||||
|
||||
EGLBoolean DestroySurface(EGLDisplay dpy, EGLSurface surface) {
|
||||
@@ -611,6 +566,10 @@ namespace MobileGL::MG_Impl::EGLImpl {
|
||||
// re-initializes lazily via GetStateEnsureInitialized(); process exit
|
||||
// then has nothing left to destroy.
|
||||
if (!state->HasAnyInitializedDisplay() && !state->HasAnyCurrentContext()) {
|
||||
// P14 S3: the process default context (and with it the GL objects the frontend
|
||||
// built while no EGL context was current) goes before Destroy() does, so nothing
|
||||
// it owns outlives glslang::FinalizeProcess() through a thread's fallback binding.
|
||||
MG_State::ReleaseProcessDefaultGLContext();
|
||||
MobileGL::Destroy();
|
||||
}
|
||||
return EGL_TRUE;
|
||||
@@ -934,23 +893,6 @@ namespace MobileGL::MG_Impl::EGLImpl {
|
||||
return state->DestroyImage(dpy, image) ? EGL_TRUE : EGL_FALSE;
|
||||
}
|
||||
|
||||
EGLImageKHR CreateImageKHR(EGLDisplay dpy, EGLContext ctx, EGLenum target, EGLClientBuffer buffer,
|
||||
const EGLint* attrib_list) {
|
||||
// EGL_KHR_image_base spells its attribute list in EGLint pairs and the core eglCreateImage
|
||||
// in EGLAttrib pairs, and the two are not the same memory: on a 64-bit build one entry is
|
||||
// twice the width of the other, so the caller's array cannot be handed over as it stands.
|
||||
// Re-spelling it is therefore part of the entry point rather than a detail of the state.
|
||||
Vector<EGLAttrib> attribs;
|
||||
if (attrib_list != nullptr) {
|
||||
for (SizeT i = 0; attrib_list[i] != EGL_NONE; i += 2) {
|
||||
attribs.push_back(static_cast<EGLAttrib>(attrib_list[i]));
|
||||
attribs.push_back(static_cast<EGLAttrib>(attrib_list[i + 1]));
|
||||
}
|
||||
attribs.push_back(static_cast<EGLAttrib>(EGL_NONE));
|
||||
}
|
||||
return CreateImage(dpy, ctx, target, buffer, attribs.empty() ? nullptr : attribs.data());
|
||||
}
|
||||
|
||||
EGLDisplay GetPlatformDisplay(EGLenum platform, void* native_display, const EGLAttrib* attrib_list) {
|
||||
(void)attrib_list;
|
||||
|
||||
@@ -980,11 +922,8 @@ namespace MobileGL::MG_Impl::EGLImpl {
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
// P12 (on-screen server window), D1: as CreateWindowSurface - with MOBILEGL_IPC_SURFACE=server
|
||||
// the window is the server's, and a headless client's NULL is accepted.
|
||||
// Either on-screen shape leaves this side without a window of its own: =server asks the
|
||||
// server for its own window, =host draws into the frames the display host offers.
|
||||
const Bool windowlessOnScreen =
|
||||
MG_Config::ServerOwnedWindowSurfaces() || MG_Config::HostFrameWindowSurfaces();
|
||||
if (native_window == nullptr && !windowlessOnScreen) {
|
||||
const Bool serverOwnedWindow = MG_Config::ServerOwnedWindowSurfaces();
|
||||
if (native_window == nullptr && !serverOwnedWindow) {
|
||||
#else
|
||||
if (native_window == nullptr) {
|
||||
#endif
|
||||
@@ -1008,21 +947,11 @@ namespace MobileGL::MG_Impl::EGLImpl {
|
||||
};
|
||||
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
EGLSurface surface = EGL_NO_SURFACE;
|
||||
if (MG_Config::ServerOwnedWindowSurfaces()) {
|
||||
// The server's own window: it makes one and draws into it.
|
||||
surface = state->CreateServerOwnedWindowSurface(
|
||||
dpy, config, native_window, static_cast<EGLint>(windowHandle.Width),
|
||||
static_cast<EGLint>(windowHandle.Height), /*platformWindow=*/true);
|
||||
} else if (MG_Config::HostFrameWindowSurfaces()) {
|
||||
// The display host's frames: it allocates them, the server draws into them,
|
||||
// and the host puts each one on the glass when the server says it is drawn.
|
||||
surface = state->CreateHostFrameWindowSurface(
|
||||
dpy, config, native_window, static_cast<EGLint>(windowHandle.Width),
|
||||
static_cast<EGLint>(windowHandle.Height), /*platformWindow=*/true);
|
||||
} else {
|
||||
surface = state->CreatePlatformWindowSurface(dpy, config, native_window, attrib_list);
|
||||
}
|
||||
EGLSurface surface = serverOwnedWindow
|
||||
? state->CreateServerOwnedWindowSurface(
|
||||
dpy, config, native_window, static_cast<EGLint>(windowHandle.Width),
|
||||
static_cast<EGLint>(windowHandle.Height), /*platformWindow=*/true)
|
||||
: state->CreatePlatformWindowSurface(dpy, config, native_window, attrib_list);
|
||||
#else
|
||||
EGLSurface surface = state->CreatePlatformWindowSurface(dpy, config, native_window, attrib_list);
|
||||
#endif
|
||||
@@ -1091,72 +1020,6 @@ namespace MobileGL::MG_Impl::EGLImpl {
|
||||
MobileGL::EnsureInitialized();
|
||||
|
||||
MGLOG_D("eglGetProcAddress(%s)", name);
|
||||
|
||||
// THE KHR SPELLINGS ARE ENTRY POINTS OF THEIR OWN, and by name is the only way anything
|
||||
// asks for them. Measured in the Fedora container that runs this library as the glvnd EGL
|
||||
// vendor, before they were answered here: eglGetProcAddress("eglCreateImageKHR") -> NULL and
|
||||
// eglGetProcAddress("eglDestroyImageKHR") -> NULL. kwin_wayland's anland backend imports
|
||||
// the display daemon's dma-bufs through exactly these two (AnlandEglLayer::importBuffers ->
|
||||
// EglBackend::importDmaBufAsTexture -> EglDisplay::importBufferAsImage ->
|
||||
// EglDisplay::createImage, which calls the pointer without a null check), so a NULL here is
|
||||
// a compositor that cannot draw a single pixel into the frames the daemon hands it. The
|
||||
// core spellings were already in the table below; these are the same functions under the
|
||||
// names EGL_KHR_image_base gives them, which is also why they answer in the glvnd vendor
|
||||
// table beside them (Exporting/GlvndVendor.cpp).
|
||||
if (std::strcmp(name, "eglCreateImageKHR") == 0) {
|
||||
return reinterpret_cast<__eglMustCastToProperFunctionPointerType>(eglCreateImageKHR);
|
||||
}
|
||||
if (std::strcmp(name, "eglDestroyImageKHR") == 0) {
|
||||
return reinterpret_cast<__eglMustCastToProperFunctionPointerType>(eglDestroyImageKHR);
|
||||
}
|
||||
// The device-query family and the EXT platform-surface spellings. Measured in the container
|
||||
// before they were answered here: eglGetProcAddress returned NULL for eglQueryDisplayAttribEXT,
|
||||
// eglQueryDevicesEXT, eglQueryDeviceAttribEXT, eglQueryDeviceStringEXT and
|
||||
// eglCreatePlatformWindowSurfaceEXT while the extension strings announced EGL_EXT_device_query -
|
||||
// a NULL libepoxy then called (kwin crashed at pc=0), and withdrawing the announcement instead
|
||||
// left kwin without a render device and its compositing inactive.
|
||||
if (std::strcmp(name, "eglQueryDevicesEXT") == 0) {
|
||||
return reinterpret_cast<__eglMustCastToProperFunctionPointerType>(eglQueryDevicesEXT);
|
||||
}
|
||||
if (std::strcmp(name, "eglQueryDeviceAttribEXT") == 0) {
|
||||
return reinterpret_cast<__eglMustCastToProperFunctionPointerType>(eglQueryDeviceAttribEXT);
|
||||
}
|
||||
if (std::strcmp(name, "eglQueryDeviceStringEXT") == 0) {
|
||||
return reinterpret_cast<__eglMustCastToProperFunctionPointerType>(eglQueryDeviceStringEXT);
|
||||
}
|
||||
if (std::strcmp(name, "eglQueryDisplayAttribEXT") == 0) {
|
||||
return reinterpret_cast<__eglMustCastToProperFunctionPointerType>(eglQueryDisplayAttribEXT);
|
||||
}
|
||||
if (std::strcmp(name, "eglCreatePlatformWindowSurfaceEXT") == 0) {
|
||||
return reinterpret_cast<__eglMustCastToProperFunctionPointerType>(eglCreatePlatformWindowSurfaceEXT);
|
||||
}
|
||||
if (std::strcmp(name, "eglCreatePlatformPixmapSurfaceEXT") == 0) {
|
||||
return reinterpret_cast<__eglMustCastToProperFunctionPointerType>(eglCreatePlatformPixmapSurfaceEXT);
|
||||
}
|
||||
// The swap-and-sync spellings kwin resolves by name while it is still bringing its EGL backend
|
||||
// up (see the definitions: EGL_KHR_fence_sync, the damage variants, EGL_EXT_buffer_age).
|
||||
if (std::strcmp(name, "eglSwapBuffersWithDamageKHR") == 0) {
|
||||
return reinterpret_cast<__eglMustCastToProperFunctionPointerType>(eglSwapBuffersWithDamageKHR);
|
||||
}
|
||||
if (std::strcmp(name, "eglSwapBuffersWithDamageEXT") == 0) {
|
||||
return reinterpret_cast<__eglMustCastToProperFunctionPointerType>(eglSwapBuffersWithDamageEXT);
|
||||
}
|
||||
if (std::strcmp(name, "eglCreateSyncKHR") == 0) {
|
||||
return reinterpret_cast<__eglMustCastToProperFunctionPointerType>(eglCreateSyncKHR);
|
||||
}
|
||||
if (std::strcmp(name, "eglDestroySyncKHR") == 0) {
|
||||
return reinterpret_cast<__eglMustCastToProperFunctionPointerType>(eglDestroySyncKHR);
|
||||
}
|
||||
if (std::strcmp(name, "eglClientWaitSyncKHR") == 0) {
|
||||
return reinterpret_cast<__eglMustCastToProperFunctionPointerType>(eglClientWaitSyncKHR);
|
||||
}
|
||||
if (std::strcmp(name, "eglWaitSyncKHR") == 0) {
|
||||
return reinterpret_cast<__eglMustCastToProperFunctionPointerType>(eglWaitSyncKHR);
|
||||
}
|
||||
if (std::strcmp(name, "eglGetSyncAttribKHR") == 0) {
|
||||
return reinterpret_cast<__eglMustCastToProperFunctionPointerType>(eglGetSyncAttribKHR);
|
||||
}
|
||||
|
||||
void* proc = MG_Impl::GetProcAddress(name);
|
||||
if (!proc) {
|
||||
MGLOG_D("Failed to get function: %s", name);
|
||||
|
||||
@@ -8,18 +8,8 @@
|
||||
|
||||
#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>
|
||||
|
||||
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);
|
||||
@@ -63,10 +53,6 @@ namespace MobileGL::MG_Impl::EGLImpl {
|
||||
EGLBoolean GetSyncAttrib(EGLDisplay dpy, EGLSync sync, EGLint attribute, EGLAttrib* value);
|
||||
EGLImage CreateImage(EGLDisplay dpy, EGLContext ctx, EGLenum target, EGLClientBuffer buffer,
|
||||
const EGLAttrib* attrib_list);
|
||||
// The same image under EGL_KHR_image_base's name and its EGLint attribute list: the two lists
|
||||
// are pairs of different widths, so the caller's array is re-spelled rather than cast.
|
||||
EGLImageKHR CreateImageKHR(EGLDisplay dpy, EGLContext ctx, EGLenum target, EGLClientBuffer buffer,
|
||||
const EGLint* attrib_list);
|
||||
EGLBoolean DestroyImage(EGLDisplay dpy, EGLImage image);
|
||||
EGLDisplay GetPlatformDisplay(EGLenum platform, void* native_display, const EGLAttrib* attrib_list);
|
||||
EGLSurface CreatePlatformWindowSurface(EGLDisplay dpy, EGLConfig config, void* native_window,
|
||||
|
||||
@@ -1,158 +1,22 @@
|
||||
// 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 {
|
||||
// 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.
|
||||
// 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 = "";
|
||||
#if defined(__linux__) && !defined(__ANDROID__)
|
||||
#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_KHR_platform_gbm "
|
||||
"EGL_EXT_platform_gbm "
|
||||
"EGL_MESA_platform_gbm "
|
||||
"EGL_EXT_platform_device "
|
||||
"EGL_EXT_client_extensions EGL_EXT_platform_base EGL_KHR_platform_base "
|
||||
"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 "
|
||||
// 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.
|
||||
"EGL_KHR_create_context EGL_EXT_platform_base EGL_KHR_platform_base "
|
||||
"EGL_MESA_platform_surfaceless" MOBILEGL_PLATFORM_WAYLAND_EXTENSIONS;
|
||||
inline constexpr const char* kClientExtensionString =
|
||||
"EGL_EXT_client_extensions "
|
||||
"EGL_KHR_create_context "
|
||||
"EGL_KHR_image_base "
|
||||
"EGL_EXT_image_dma_buf_import "
|
||||
"EGL_KHR_no_config_context "
|
||||
"EGL_KHR_surfaceless_context "
|
||||
// ANNOUNCED BECAUSE IT IS NOW ANSWERED: the four names below are published as real entry
|
||||
// points and eglGetProcAddress answers them (see Exporting/Definitions.cpp and
|
||||
// EGLImpl::GetProcAddress). Both earlier states were measured failures: announcing the
|
||||
// extension while the names resolved to NULL made kwin jump to that NULL (signal 11,
|
||||
// pc=0x0, from KWin::EglDisplay::determineRenderNode()), and withdrawing the announcement
|
||||
// left kwin without a render device so its compositing never became active and nothing was
|
||||
// ever painted.
|
||||
"EGL_EXT_device_base "
|
||||
"EGL_EXT_device_enumeration "
|
||||
"EGL_EXT_device_query "
|
||||
"EGL_EXT_device_drm "
|
||||
"EGL_EXT_device_drm_render_node "
|
||||
// KWin::EglDisplay::determineRenderNode() at libkwin.so.6+0x308b9c. A compositor that is
|
||||
// never told the extension exists cannot take that path; announcing it again is the right
|
||||
// move once these four names are really published and resolvable.
|
||||
"EGL_EXT_platform_device "
|
||||
"EGL_EXT_platform_base "
|
||||
"EGL_KHR_platform_base "
|
||||
"EGL_KHR_platform_gbm "
|
||||
"EGL_EXT_platform_gbm "
|
||||
"EGL_MESA_platform_gbm "
|
||||
"EGL_MESA_platform_surfaceless";
|
||||
"EGL_EXT_client_extensions EGL_KHR_create_context EGL_EXT_platform_base "
|
||||
"EGL_KHR_platform_base EGL_MESA_platform_surfaceless" MOBILEGL_PLATFORM_WAYLAND_EXTENSIONS;
|
||||
}
|
||||
|
||||
@@ -7,9 +7,6 @@
|
||||
// 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"
|
||||
|
||||
MOBILEGL_EGL_API EGLSurface eglCreateWindowSurface(EGLDisplay dpy, EGLConfig config, NativeWindowType window,
|
||||
@@ -231,25 +228,6 @@ MOBILEGL_EGL_API EGLBoolean eglDestroyImage(EGLDisplay dpy, EGLImage image) {
|
||||
return MobileGL::MG_Impl::EGLImpl::DestroyImage(dpy, image);
|
||||
}
|
||||
|
||||
// EGL_KHR_image_base's spellings of the same two entry points, exported under their own names
|
||||
// because that is the only thing that answers for them: measured in the Fedora container that runs
|
||||
// this library as the glvnd EGL vendor, eglGetProcAddress("eglCreateImageKHR") and
|
||||
// eglGetProcAddress("eglDestroyImageKHR") both returned NULL, and kwin_wayland's anland backend
|
||||
// imports the display daemon's dma-bufs through exactly these two.
|
||||
MOBILEGL_EGL_API EGLImageKHR eglCreateImageKHR(EGLDisplay dpy, EGLContext ctx, EGLenum target, EGLClientBuffer buffer,
|
||||
const EGLint* attrib_list) {
|
||||
MGLOG_D("eglCreateImageKHR(dpy=%p, ctx=%p, target=%u, buffer=%p, attrib_list=%p)", dpy, ctx, target, buffer,
|
||||
attrib_list);
|
||||
// Not an alias of eglCreateImage: this list is EGLint pairs and the core one EGLAttrib pairs.
|
||||
return MobileGL::MG_Impl::EGLImpl::CreateImageKHR(dpy, ctx, target, buffer, attrib_list);
|
||||
}
|
||||
|
||||
MOBILEGL_EGL_API EGLBoolean eglDestroyImageKHR(EGLDisplay dpy, EGLImageKHR image) {
|
||||
MGLOG_D("eglDestroyImageKHR(dpy=%p, image=%p)", dpy, image);
|
||||
// One handle under two spellings: EGLImageKHR and EGLImage are the same pointer.
|
||||
return MobileGL::MG_Impl::EGLImpl::DestroyImage(dpy, image);
|
||||
}
|
||||
|
||||
MOBILEGL_EGL_API EGLDisplay eglGetPlatformDisplay(EGLenum platform, void* native_display,
|
||||
const EGLAttrib* attrib_list) {
|
||||
MGLOG_D("eglGetPlatformDisplay(platform=%u, native_display=%p, attrib_list=%p)", platform, native_display,
|
||||
@@ -272,138 +250,6 @@ MOBILEGL_EGL_API EGLSurface eglCreatePlatformWindowSurface(EGLDisplay dpy, EGLCo
|
||||
return MobileGL::MG_Impl::EGLImpl::CreatePlatformWindowSurface(dpy, config, native_window, attrib_list);
|
||||
}
|
||||
|
||||
// THE SWAP-AND-SYNC FAMILY, which kwin asks for in EglBackend::init right after the rendering
|
||||
// context is up and BEFORE it creates any surface: EGL_KHR_fence_sync, EGL_KHR_swap_buffers_with_damage
|
||||
// and EGL_EXT_buffer_age are checked there, and a compositing mode whose backend init returns false
|
||||
// is exactly the "Could not fulfill the requested compositing mode in KWIN_COMPOSE: 1" this run
|
||||
// reports. Each of these names is a spelling of something this library already implements (the core
|
||||
// eglSwapBuffers and the state layer's sync objects), so they are published as real exports rather
|
||||
// than promised and not delivered.
|
||||
MOBILEGL_EGL_API EGLBoolean eglSwapBuffersWithDamageKHR(EGLDisplay dpy, EGLSurface surface, const EGLint* rects,
|
||||
EGLint n_rects) {
|
||||
// The damage rectangles are a hint about what changed; this side swaps the whole surface either
|
||||
// way, so the honest answer is the core swap.
|
||||
(void)rects;
|
||||
(void)n_rects;
|
||||
return MobileGL::MG_Impl::EGLImpl::SwapBuffers(dpy, surface) ? EGL_TRUE : EGL_FALSE;
|
||||
}
|
||||
|
||||
MOBILEGL_EGL_API EGLBoolean eglSwapBuffersWithDamageEXT(EGLDisplay dpy, EGLSurface surface, const EGLint* rects,
|
||||
EGLint n_rects) {
|
||||
return eglSwapBuffersWithDamageKHR(dpy, surface, rects, n_rects);
|
||||
}
|
||||
|
||||
MOBILEGL_EGL_API EGLSyncKHR eglCreateSyncKHR(EGLDisplay dpy, EGLenum type, const EGLint* attrib_list) {
|
||||
// EGL_KHR_fence_sync's list is EGLint pairs; the state layer takes EGLAttrib pairs.
|
||||
EGLAttrib attributes[16];
|
||||
int count = 0;
|
||||
if (attrib_list != nullptr) {
|
||||
for (int index = 0; attrib_list[index] != EGL_NONE && count + 1 < 16; index += 2) {
|
||||
attributes[count++] = static_cast<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) {
|
||||
MGLOG_D("eglCreatePlatformPixmapSurface(dpy=%p, config=%p, native_pixmap=%p, attrib_list=%p)", dpy, config,
|
||||
|
||||
@@ -28,32 +28,10 @@
|
||||
|
||||
#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"
|
||||
|
||||
// The KHR spellings of the image entry points, declared here because the bundled EGL headers
|
||||
// declare them only under EGL_EGLEXT_PROTOTYPES and because glvnd asks for entry points BY NAME -
|
||||
// the table below is where it finds this one.
|
||||
extern "C" EGLImageKHR eglCreateImageKHR(EGLDisplay dpy, EGLContext ctx, EGLenum target, EGLClientBuffer buffer,
|
||||
const EGLint* attrib_list);
|
||||
extern "C" EGLBoolean eglDestroyImageKHR(EGLDisplay dpy, EGLImageKHR image);
|
||||
|
||||
// THE SWAP-AND-SYNC EXPORTS, declared here for the same reason the image pair is: they are defined in
|
||||
// Exporting/Definitions.cpp and this file only names them in the vendor table below.
|
||||
extern "C" EGLBoolean eglSwapBuffersWithDamageKHR(EGLDisplay dpy, EGLSurface surface, const EGLint* rects,
|
||||
EGLint n_rects);
|
||||
extern "C" EGLBoolean eglSwapBuffersWithDamageEXT(EGLDisplay dpy, EGLSurface surface, const EGLint* rects,
|
||||
EGLint n_rects);
|
||||
extern "C" EGLSyncKHR eglCreateSyncKHR(EGLDisplay dpy, EGLenum type, const EGLint* attrib_list);
|
||||
extern "C" EGLBoolean eglDestroySyncKHR(EGLDisplay dpy, EGLSyncKHR sync);
|
||||
extern "C" EGLint eglClientWaitSyncKHR(EGLDisplay dpy, EGLSyncKHR sync, EGLint flags, EGLTimeKHR timeout);
|
||||
extern "C" EGLBoolean eglWaitSyncKHR(EGLDisplay dpy, EGLSyncKHR sync, EGLint flags);
|
||||
extern "C" EGLBoolean eglGetSyncAttribKHR(EGLDisplay dpy, EGLSyncKHR sync, EGLint attribute, EGLint* value);
|
||||
|
||||
namespace {
|
||||
using namespace MobileGL;
|
||||
|
||||
@@ -139,20 +117,13 @@ 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:
|
||||
// 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");
|
||||
*value = reinterpret_cast<EGLAttrib>(DrmRenderNode());
|
||||
return EGL_TRUE;
|
||||
default:
|
||||
return EGL_FALSE;
|
||||
@@ -160,26 +131,19 @@ 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;
|
||||
}
|
||||
// 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.
|
||||
// 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.
|
||||
if (name == EGL_DRM_DEVICE_FILE_EXT || name == EGL_DRM_RENDER_NODE_FILE_EXT) {
|
||||
return "/dev/dri/renderD128";
|
||||
return DrmRenderNode();
|
||||
}
|
||||
if (name == EGL_EXTENSIONS) {
|
||||
return "EGL_EXT_device_drm_render_node";
|
||||
return "EGL_EXT_device_drm EGL_EXT_device_drm_render_node";
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
@@ -257,31 +221,8 @@ 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)},
|
||||
{"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)},
|
||||
@@ -299,15 +240,6 @@ 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)},
|
||||
@@ -349,19 +281,7 @@ namespace {
|
||||
(void)index;
|
||||
}
|
||||
|
||||
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));
|
||||
}
|
||||
void* EGLAPIENTRY VendorGetDispatchAddress(const char* procName) { return LookupEntryPoint(procName); }
|
||||
} // namespace
|
||||
|
||||
extern "C" MOBILEGL_EGL_API EGLBoolean __egl_Main(uint32_t version, const __EGLapiExports* exports,
|
||||
|
||||
@@ -6,9 +6,6 @@
|
||||
// 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"
|
||||
@@ -25,13 +22,6 @@
|
||||
#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__) {
|
||||
|
||||
@@ -135,17 +125,6 @@ MOBILEGL_GL_API void glFlush() {
|
||||
#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)
|
||||
@@ -1318,325 +1297,17 @@ 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, )
|
||||
// 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, 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)
|
||||
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)
|
||||
@@ -2042,141 +1713,6 @@ 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,13 +100,6 @@ 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;
|
||||
@@ -618,9 +611,7 @@ namespace MobileGL::MG_Impl::GLImpl {
|
||||
|
||||
const auto expectedTextureTarget = MG_Util::ConvertTextureUploadTargetToTextureTarget(textureUploadTarget);
|
||||
if (expectedTextureTarget == TextureTarget::Unknown ||
|
||||
(textureObject->GetTarget() != expectedTextureTarget &&
|
||||
!(textureObject->GetTarget() == TextureTarget::TextureExternalOES &&
|
||||
expectedTextureTarget == TextureTarget::Texture2D))) {
|
||||
textureObject->GetTarget() != expectedTextureTarget) {
|
||||
MG_State::pGLContext->RecordError(
|
||||
ErrorCode::InvalidOperation,
|
||||
MakeUnique<GenericErrorInfo>(
|
||||
@@ -1391,9 +1382,7 @@ namespace MobileGL::MG_Impl::GLImpl {
|
||||
|
||||
const auto expectedTextureTarget = MG_Util::ConvertTextureUploadTargetToTextureTarget(textureUploadTarget);
|
||||
if (expectedTextureTarget == TextureTarget::Unknown ||
|
||||
(textureObject->GetTarget() != expectedTextureTarget &&
|
||||
!(textureObject->GetTarget() == TextureTarget::TextureExternalOES &&
|
||||
expectedTextureTarget == TextureTarget::Texture2D))) {
|
||||
textureObject->GetTarget() != expectedTextureTarget) {
|
||||
MG_State::pGLContext->RecordError(
|
||||
ErrorCode::InvalidOperation,
|
||||
MakeUnique<GenericErrorInfo>(
|
||||
@@ -1543,9 +1532,7 @@ namespace MobileGL::MG_Impl::GLImpl {
|
||||
|
||||
const auto expectedTextureTarget = MG_Util::ConvertTextureUploadTargetToTextureTarget(textureUploadTarget);
|
||||
if (expectedTextureTarget == TextureTarget::Unknown ||
|
||||
(textureObject->GetTarget() != expectedTextureTarget &&
|
||||
!(textureObject->GetTarget() == TextureTarget::TextureExternalOES &&
|
||||
expectedTextureTarget == TextureTarget::Texture2D))) {
|
||||
textureObject->GetTarget() != expectedTextureTarget) {
|
||||
MG_State::pGLContext->RecordError(
|
||||
ErrorCode::InvalidOperation,
|
||||
MakeUnique<GenericErrorInfo>(
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
#include "../EGLImpl/EGLImpl.h"
|
||||
#include "../GetProcAddress.h"
|
||||
#include <Init.h>
|
||||
#include <Config.h>
|
||||
|
||||
namespace MobileGL::MG_Impl::GLXImpl {
|
||||
namespace {
|
||||
@@ -187,6 +188,7 @@ namespace MobileGL::MG_Impl::GLXImpl {
|
||||
Uint32 Width = 0;
|
||||
Uint32 Height = 0;
|
||||
std::chrono::steady_clock::time_point LastSizePoll{};
|
||||
Bool RemotePbuffer = false;
|
||||
};
|
||||
|
||||
std::recursive_mutex& RegistryMutex() {
|
||||
@@ -294,6 +296,10 @@ namespace MobileGL::MG_Impl::GLXImpl {
|
||||
if (width == surface.Width && height == surface.Height) {
|
||||
return;
|
||||
}
|
||||
// A remote X drawable is backed by a pbuffer; an XID has no meaning
|
||||
// to the Android worker. Its allocation cannot be resized by the
|
||||
// native-window hook. Keep the current allocation until recreated.
|
||||
if (surface.RemotePbuffer) return;
|
||||
if (EGLImpl::ResizePlatformWindowSurface(surface.Display, surface.Surface,
|
||||
static_cast<EGLint>(width),
|
||||
static_cast<EGLint>(height))) {
|
||||
@@ -323,8 +329,13 @@ namespace MobileGL::MG_Impl::GLXImpl {
|
||||
EGL_HEIGHT, static_cast<EGLAttrib>(height),
|
||||
EGL_NONE,
|
||||
};
|
||||
EGLSurface surface = EGLImpl::CreatePlatformWindowSurface(
|
||||
context.Display, context.Config, reinterpret_cast<void*>(drawable), attribs);
|
||||
const Bool remotePbuffer = MG_Config::Transport == MG_Config::TransportMode::Spawn;
|
||||
const EGLint pbufferAttribs[] = {EGL_WIDTH, static_cast<EGLint>(width),
|
||||
EGL_HEIGHT, static_cast<EGLint>(height), EGL_NONE};
|
||||
EGLSurface surface = remotePbuffer
|
||||
? EGLImpl::CreatePbufferSurface(context.Display, context.Config, pbufferAttribs)
|
||||
: EGLImpl::CreatePlatformWindowSurface(
|
||||
context.Display, context.Config, reinterpret_cast<void*>(drawable), attribs);
|
||||
if (surface == EGL_NO_SURFACE) {
|
||||
MGLOG_E_ONCE("glx: failed to create window surface for drawable 0x%lx (%ux%u)", drawable,
|
||||
width, height);
|
||||
@@ -336,6 +347,7 @@ namespace MobileGL::MG_Impl::GLXImpl {
|
||||
record.Surface = surface;
|
||||
record.Width = width;
|
||||
record.Height = height;
|
||||
record.RemotePbuffer = remotePbuffer;
|
||||
record.LastSizePoll = std::chrono::steady_clock::now();
|
||||
auto [inserted, _] = surfaces.emplace(drawable, record);
|
||||
return &inserted->second;
|
||||
|
||||
@@ -869,55 +869,6 @@ namespace MobileGL::MG_Impl {
|
||||
GETPROC(glNamedBufferPageCommitmentARB, name);
|
||||
GETPROC(glTexPageCommitmentARB, name);
|
||||
GETPROC(glTexBufferARB, name);
|
||||
// ARB_shader_objects and ARB_vertex_shader, by name, because a name is the only way an
|
||||
// application ever asks for an extension entry point. Measured path: kwin_wayland resolves GL
|
||||
// through libepoxy, and libepoxy asks eglGetProcAddress -> EGLImpl::GetProcAddress -> this
|
||||
// table. Before these lines the callers that need the extension whose STRINGS make
|
||||
// checkSupported() pass got a nullptr for every function of it - dlsym on the library found
|
||||
// them, this table did not. The strings and the implementations are advertised from
|
||||
// MG_Impl/GLImpl/Exporting/Definitions.cpp and the two BackendObject_* extension lists.
|
||||
GETPROC(glDeleteObjectARB, name);
|
||||
GETPROC(glGetHandleARB, name);
|
||||
GETPROC(glDetachObjectARB, name);
|
||||
GETPROC(glCreateShaderObjectARB, name);
|
||||
GETPROC(glShaderSourceARB, name);
|
||||
GETPROC(glCompileShaderARB, name);
|
||||
GETPROC(glCreateProgramObjectARB, name);
|
||||
GETPROC(glAttachObjectARB, name);
|
||||
GETPROC(glLinkProgramARB, name);
|
||||
GETPROC(glUseProgramObjectARB, name);
|
||||
GETPROC(glValidateProgramARB, name);
|
||||
GETPROC(glUniform1fARB, name);
|
||||
GETPROC(glUniform2fARB, name);
|
||||
GETPROC(glUniform3fARB, name);
|
||||
GETPROC(glUniform4fARB, name);
|
||||
GETPROC(glUniform1iARB, name);
|
||||
GETPROC(glUniform2iARB, name);
|
||||
GETPROC(glUniform3iARB, name);
|
||||
GETPROC(glUniform4iARB, name);
|
||||
GETPROC(glUniform1fvARB, name);
|
||||
GETPROC(glUniform2fvARB, name);
|
||||
GETPROC(glUniform3fvARB, name);
|
||||
GETPROC(glUniform4fvARB, name);
|
||||
GETPROC(glUniform1ivARB, name);
|
||||
GETPROC(glUniform2ivARB, name);
|
||||
GETPROC(glUniform3ivARB, name);
|
||||
GETPROC(glUniform4ivARB, name);
|
||||
GETPROC(glUniformMatrix2fvARB, name);
|
||||
GETPROC(glUniformMatrix3fvARB, name);
|
||||
GETPROC(glUniformMatrix4fvARB, name);
|
||||
GETPROC(glGetObjectParameterfvARB, name);
|
||||
GETPROC(glGetObjectParameterivARB, name);
|
||||
GETPROC(glGetInfoLogARB, name);
|
||||
GETPROC(glGetAttachedObjectsARB, name);
|
||||
GETPROC(glGetUniformLocationARB, name);
|
||||
GETPROC(glGetActiveUniformARB, name);
|
||||
GETPROC(glGetUniformfvARB, name);
|
||||
GETPROC(glGetUniformivARB, name);
|
||||
GETPROC(glGetShaderSourceARB, name);
|
||||
GETPROC(glBindAttribLocationARB, name);
|
||||
GETPROC(glGetActiveAttribARB, name);
|
||||
GETPROC(glGetAttribLocationARB, name);
|
||||
GETPROC(glDepthRangeArraydvNV, name);
|
||||
GETPROC(glDepthRangeIndexeddNV, name);
|
||||
GETPROC(glBlendBarrierKHR, name);
|
||||
@@ -935,8 +886,6 @@ namespace MobileGL::MG_Impl {
|
||||
GETPROC(glBeginPerfMonitorAMD, name);
|
||||
GETPROC(glEndPerfMonitorAMD, name);
|
||||
GETPROC(glGetPerfMonitorCounterDataAMD, name);
|
||||
GETPROC(glEGLImageTargetTexture2DOES, name);
|
||||
GETPROC(glEGLImageTargetRenderbufferStorageOES, name);
|
||||
GETPROC(glEGLImageTargetTexStorageEXT, name);
|
||||
GETPROC(glEGLImageTargetTextureStorageEXT, name);
|
||||
GETPROC(glLabelObjectEXT, name);
|
||||
|
||||
@@ -48,6 +48,10 @@ namespace MobileGL::MG_Impl {
|
||||
MakeUnique<GLImpl::FramebufferImpl::DefaultFramebufferInfo>(fbo0, colorTex, depthTex, stencilTex);
|
||||
MG_State::pGLContext->GetFramebufferBindingSlot(FramebufferTarget::Draw).Bind(fbo0);
|
||||
MG_State::pGLContext->GetFramebufferBindingSlot(FramebufferTarget::Read).Bind(fbo0);
|
||||
// P14 S3: every GLContext a later eglCreateContext builds starts with this same default
|
||||
// framebuffer, so a context the application creates after this one is not left with an
|
||||
// unbound framebuffer 0.
|
||||
MG_State::SetDefaultFramebuffer(fbo0);
|
||||
#if defined(__APPLE__) && !defined(MOBILEGL_IOS)
|
||||
NSOpenGLImpl::InstallHooks();
|
||||
#endif
|
||||
|
||||
@@ -1828,11 +1828,6 @@ namespace MobileGL::MG_Pipe {
|
||||
*entry = Entry{};
|
||||
}
|
||||
|
||||
void Clear() {
|
||||
for (auto& table : m_kinds) table.clear();
|
||||
m_band.clear();
|
||||
}
|
||||
|
||||
private:
|
||||
struct Entry {
|
||||
Uint32 Gen = 0;
|
||||
@@ -1897,15 +1892,6 @@ namespace MobileGL::MG_Pipe {
|
||||
PublicationLatch().NoteUnpublished(kind, handle);
|
||||
}
|
||||
|
||||
void MGPipeForgetAllPublications() {
|
||||
PublicationLatch().Clear();
|
||||
// The two families whose death asks their own record rather than the latch: vertex
|
||||
// elements (MGPipeEmitVertexElementsDestroyAndFree's RecordIsPublished) and buffers
|
||||
// (MGPipeEmitResourceDestroyAndFree's WasPublished).
|
||||
MGPipeVertexInputEmitterInstance().ForgetAllRecords();
|
||||
MGPipeResourceTrackerInstance().ForgetAllPublished();
|
||||
}
|
||||
|
||||
// THE GATE ITSELF, AS AN OBSERVABLE (ID-39, widened by S-3 / ID-41). Every P4a birth hook
|
||||
// below and every `wants()` row in the walk resolve through FamilyIsLive /
|
||||
// P4aFamilyHasItsConsumer / P4aFamilyDependenciesAreSet, and none of the three is reachable
|
||||
|
||||
@@ -340,10 +340,6 @@ namespace MobileGL::MG_Pipe {
|
||||
const SizeT slot = handle.Slot;
|
||||
return slot < m_bySlot.size() && m_bySlot[slot].Published;
|
||||
}
|
||||
// The session that held every buffer's record is gone (MGPipeForgetAllPublications).
|
||||
void ForgetAllPublished() {
|
||||
for (Entry& entry : m_bySlot) entry.Published = false;
|
||||
}
|
||||
|
||||
// The sticky everBoundAs mask. Sticky exactly as MGPResourceDesc::ImageBindableHint's
|
||||
// everImageBound is: ORed, never cleared, so a buffer that was an element array once
|
||||
|
||||
@@ -351,14 +351,6 @@ namespace MobileGL::MG_Pipe {
|
||||
m_boundLifetimeId = 0;
|
||||
}
|
||||
|
||||
// The session that held the records is gone (MGPipeForgetAllPublications): both halves go,
|
||||
// the record half included, because no applier holds any of them any more.
|
||||
void ForgetAllRecords() {
|
||||
for (Latch& latch : m_latch) latch = Latch{};
|
||||
m_boundHandle = kMGPipeNullHandle;
|
||||
m_boundLifetimeId = 0;
|
||||
}
|
||||
|
||||
void ResetCounters() { m_creates = m_binds = m_bufferSets = m_indexSets = 0; }
|
||||
|
||||
private:
|
||||
|
||||
@@ -3119,12 +3119,10 @@ if (MOBILEGL_BUILD_DISAGGREGATED)
|
||||
"MOBILEGL_IPC_LOG_FORWARD=1" "MOBILEGL_IPC_TOKEN="
|
||||
"MGITEST_TCP_LANE=1" "MOBILEGL_ITEST_REQUIRE_GPU=1")
|
||||
set(mglD2Extra FIXTURES_REQUIRED mobilegl-tcp)
|
||||
# The loopback supervisor used to serve ONE session (a second Hello was answered
|
||||
# Refuse{Busy}), and `ctest -L integration-gpu -j N` ran this case beside another Tcp
|
||||
# case so that whichever client connected second died Refuse{Busy} ->
|
||||
# Fatal{CapsBeforeFirstSnapshot}. It serves several side by side now (ServerMain.cpp
|
||||
# TcpSupervisor, fork shape); every Tcp entry still holds this lock, so the cases do not
|
||||
# share the fixture's one server and its log while they run.
|
||||
# The loopback supervisor serves ONE session (ServerMain.cpp answers a second Hello
|
||||
# Refuse{Busy}), and every other Tcp entry holds this lock. Without it `ctest -L
|
||||
# integration-gpu -j N` ran this case beside another Tcp case and whichever client
|
||||
# connected second died Refuse{Busy} -> Fatal{CapsBeforeFirstSnapshot}.
|
||||
# scripts/ci/spawn_lane_parity.py and junit_tally.py --discovery now refuse any entry
|
||||
# on the fixture that does not hold it.
|
||||
set(mglD2Locks "${mglD2LogName}\;mobilegl-tcp")
|
||||
|
||||
@@ -10,8 +10,9 @@
|
||||
//
|
||||
// Before P8-D every wire indirect draw read its commands (and its count word) through
|
||||
// ReadWireBuffer and expanded them on the CPU, and a store a shader had written turned that read
|
||||
// into a whole-GPU wait per draw (create-indirect: 321 expansions, 327 waits, ~4-8 s of waiting
|
||||
// per replay on lavapipe). The cases pin both halves of the change:
|
||||
// into a whole-GPU wait per draw (the create-indirect trace, now
|
||||
// minecraft-1.21.1-neoforge-create-indirect-in-world-align1024: 321 expansions, 327 waits, ~4-8 s of
|
||||
// waiting per replay on lavapipe). The cases pin both halves of the change:
|
||||
// * PIXELS, on every arm and both backends where the backend's own semantics allow it - each
|
||||
// indirect form draws exactly the strips its commands name, and GPU-written commands are the
|
||||
// ones the draw sees (the poison the buffers start with names the OTHER strips);
|
||||
@@ -336,8 +337,9 @@ void main() { words[gl_GlobalInvocationID.x] = source[gl_GlobalInvocationID.x];
|
||||
EXPECT_EQ(delta.barriers, 2u) << "one barrier per draw whose count store a shader wrote";
|
||||
}
|
||||
|
||||
// Flywheel's shape (create-indirect's trace: 322 cull-then-draw rounds, no glMemoryBarrier
|
||||
// between them). GL leaves it undefined; the wire arm orders it anyway, once per write,
|
||||
// Flywheel's shape (minecraft-1.21.1-neoforge-create-indirect-in-world-align1024: 322
|
||||
// cull-then-draw rounds, no glMemoryBarrier between them). GL leaves it undefined; the
|
||||
// wire arm orders it anyway, once per write,
|
||||
// because the CPU path it replaced did (by waiting). Magma's split arms only: the monolith
|
||||
// arm records no dependency here (recorded for dev), and Espryt's is its driver's.
|
||||
TEST_F(WireIndirectDrawScenario, ShaderWrittenCommandsWithoutAnApplicationBarrierAreOrdered) {
|
||||
|
||||
@@ -214,8 +214,6 @@ namespace MobileGL::MG_Pipe {
|
||||
TexCubeArray,
|
||||
Tex2DMS,
|
||||
Tex2DMSArray,
|
||||
// GL_TEXTURE_EXTERNAL_OES
|
||||
TexExternalOES,
|
||||
Renderbuffer,
|
||||
TexBuffer,
|
||||
TexRect,
|
||||
@@ -265,10 +263,6 @@ namespace MobileGL::MG_Pipe {
|
||||
return static_cast<Uint32>(MGPipeResourceTarget::TexCubeArray);
|
||||
case MobileGL::TextureTarget::Texture2DMultisampleArray:
|
||||
return static_cast<Uint32>(MGPipeResourceTarget::Tex2DMSArray);
|
||||
// GL_TEXTURE_EXTERNAL_OES gets its own row for the same reason TextureRectangle has one: it is
|
||||
// a real target a descriptor may carry (the compositor's imported dma-buf textures live on it).
|
||||
case MobileGL::TextureTarget::TextureExternalOES:
|
||||
return static_cast<Uint32>(MGPipeResourceTarget::TexExternalOES);
|
||||
// NOT TEXTURE TARGETS. Listed rather than defaulted so the completeness assert still
|
||||
// sees them, and mapped to the sentinel because no descriptor may carry either: the
|
||||
// count is the enum's bound and Unknown is what an unresolved GL enum becomes.
|
||||
@@ -1972,6 +1966,19 @@ namespace MobileGL::MG_Pipe {
|
||||
// object (§5.2), so a null handle arriving is Fatal{ProtocolCorruption,
|
||||
// "ObjectDeath.Handle"} at the sink.
|
||||
|
||||
// bind_context = opcode 84, P14 S1 (docs/Disaggregated/design/11-state-ownership.md).
|
||||
// The client's CURRENT context token, minted by EGLState::CreateContext and carried to the
|
||||
// server by the matching CreateContext control frame. 0 means "no context": a release, and
|
||||
// it is the value a session that never bound one already has - so the single-context shape
|
||||
// P5c shipped (one context per session, every record implicitly its own) needs no record at
|
||||
// all and no server change. The token is Uint64 because the control frame's is: one width
|
||||
// on both planes, or the two would have to be narrowed at one end.
|
||||
struct MGPBindContext {
|
||||
Uint64 ClientContextToken;
|
||||
};
|
||||
MGP_ASSERT_POD(MGPBindContext, 8);
|
||||
|
||||
|
||||
// set_context_values = opcode 79, P5c rv (CONTRACT-P5C.md §5.3): the rv field table as
|
||||
// ONE fixed-width POD. It carries every value-class field that no set_* call supplies -
|
||||
// the two texture-unit counters, the per-target touched-buffer-binding high-water marks
|
||||
|
||||
+349
-186
@@ -477,11 +477,173 @@ namespace MobileGL::MG_Pipe {
|
||||
static_assert(kCapabilityCount <= 64,
|
||||
"ResidualValueBlock::CapabilityBits is a Uint64; 35 bits fit, 65 would not");
|
||||
|
||||
// ============================================================================
|
||||
// P14 S5: THE APPLIER REGISTRY.
|
||||
// ============================================================================
|
||||
//
|
||||
// A REFERENCE TO A NEVER-DESTROYED BLOCK, for MGPipeSlots()' reason
|
||||
// (MG_Impl/Pipe/SlotAllocator.cpp): resource_destroy and delete_vertex_elements are
|
||||
// raised from ~BufferObject / ~VertexArrayObject, and those objects are released by
|
||||
// exit handlers that run after this translation unit's own globals are gone.
|
||||
MGPipeApplierState& g_applier = *new MGPipeApplierState{};
|
||||
//
|
||||
// THE DEFAULT IS THE OLD SINGLETON, unrenamed in what it means: the applier of a thread
|
||||
// that belongs to nobody - the client process, the monolith, the inproc one-process
|
||||
// shape, every unit case. Its object records are the group it owns alone.
|
||||
MGPipeObjectRecords& g_defaultObjects = *new MGPipeObjectRecords{};
|
||||
MGPipeApplierState& g_defaultApplier = *new MGPipeApplierState(g_defaultObjects);
|
||||
|
||||
// Installed once by the session registry (MG_Remote/Server/SessionRuntime.cpp), never
|
||||
// replaced. Null in every process that serves no session, which is what keeps the
|
||||
// monolith's `MGPipeApplier()` a load and a branch.
|
||||
MGPipeApplierKeyResolver g_applierKeyResolver = nullptr;
|
||||
|
||||
// One served session's appliers. Groups own object records; Contexts own working state
|
||||
// and point at their group. Both are held through UniquePtr so a table's ADDRESS is
|
||||
// stable across a rehash - MGPipeApplierState binds its group by reference - and the
|
||||
// maps are std::unordered_map rather than the house UnorderedMap (a flat hash map) for
|
||||
// that same reason at the map level: a reference into it may not be invalidated by an
|
||||
// insert somewhere else in the same call.
|
||||
struct ApplierSession {
|
||||
std::unordered_map<Uint64, UniquePtr<MGPipeObjectRecords>> Groups;
|
||||
std::unordered_map<Uint64, UniquePtr<MGPipeApplierState>> Contexts;
|
||||
std::unordered_map<Uint64, Uint64> ContextGroup;
|
||||
std::unordered_map<Uint64, Uint32> GroupContexts;
|
||||
};
|
||||
std::unordered_map<Uint64, ApplierSession> g_applierSessions;
|
||||
std::mutex g_applierSessionsMutex;
|
||||
// Bumped by EVERY registry mutation. A thread's cached applier pointer is only trusted
|
||||
// while it was bound at this generation, which is what makes "a context was destroyed on
|
||||
// another thread" unable to leave a dangling cache behind.
|
||||
std::atomic<Uint64> g_applierRegistryGeneration{1};
|
||||
|
||||
// A context that started its own share group is keyed by its own token, in a namespace
|
||||
// of its own: the frontend mints share-group tokens and context tokens from separate
|
||||
// counters, so without this a group 7 and a context 7 would be one group.
|
||||
constexpr Uint64 kMGPipeOwnShareGroupBit = Uint64{1} << 63;
|
||||
|
||||
// `shareGroupToken` 0 means "this context started its own group" - the sentinel S1's
|
||||
// ContextRuntime documents and the one a caller that frames a context by hand (a test,
|
||||
// the in-process server helpers) leaves behind.
|
||||
Uint64 ApplierShareGroupKey(Uint64 contextToken, Uint64 shareGroupToken) {
|
||||
return shareGroupToken != 0 ? shareGroupToken : (contextToken | kMGPipeOwnShareGroupBit);
|
||||
}
|
||||
|
||||
// The three tables of the applier this thread's records are being applied through.
|
||||
// `generation` is the registry's, read here so a caller can bind a pointer under one
|
||||
// generation and publish it under the same one.
|
||||
MGPipeApplierState* FindApplierForKey(const MGPipeApplierKey& key) {
|
||||
std::lock_guard<std::mutex> guard(g_applierSessionsMutex);
|
||||
ApplierSession& session = g_applierSessions[key.SessionKey];
|
||||
const auto found = session.Contexts.find(key.ContextToken);
|
||||
if (found != session.Contexts.end() && found->second) return found->second.get();
|
||||
// A context the session never registered - a token that predates the first
|
||||
// CreateContext, or the 0 of a session that has not bound one yet. It gets the same
|
||||
// shape as any other: a working state in a group of its own.
|
||||
const Uint64 groupKey = ApplierShareGroupKey(key.ContextToken, 0);
|
||||
auto group = session.Groups.find(groupKey);
|
||||
if (group == session.Groups.end()) {
|
||||
group = session.Groups.emplace(groupKey, MakeUnique<MGPipeObjectRecords>()).first;
|
||||
}
|
||||
auto applier = MakeUnique<MGPipeApplierState>(*group->second);
|
||||
MGPipeApplierState* const raw = applier.get();
|
||||
session.Contexts.emplace(key.ContextToken, std::move(applier));
|
||||
session.ContextGroup.emplace(key.ContextToken, groupKey);
|
||||
++session.GroupContexts[groupKey];
|
||||
return raw;
|
||||
}
|
||||
|
||||
thread_local MGPipeApplierState* t_applierCached = nullptr;
|
||||
thread_local Uint64 t_applierCachedSession = 0;
|
||||
thread_local Uint64 t_applierCachedContext = 0;
|
||||
thread_local Uint64 t_applierCachedGeneration = 0;
|
||||
} // namespace
|
||||
|
||||
MGPipeApplierState& MGPipeApplier() {
|
||||
const MGPipeApplierKeyResolver resolve = g_applierKeyResolver;
|
||||
if (resolve == nullptr) return g_defaultApplier;
|
||||
MGPipeApplierKey key;
|
||||
if (!resolve(&key)) return g_defaultApplier;
|
||||
// THE FAST PATH, and the reason this is a cache rather than a lookup: this function is
|
||||
// called from the backend per state read. A hit is three TLS loads, one atomic load and
|
||||
// two compares; a miss is the registry, which only moves when a context is created,
|
||||
// destroyed or made current.
|
||||
const Uint64 generation = g_applierRegistryGeneration.load(std::memory_order_acquire);
|
||||
if (t_applierCached != nullptr && t_applierCachedGeneration == generation &&
|
||||
t_applierCachedSession == key.SessionKey && t_applierCachedContext == key.ContextToken) {
|
||||
return *t_applierCached;
|
||||
}
|
||||
MGPipeApplierState* const applier = FindApplierForKey(key);
|
||||
t_applierCached = applier;
|
||||
t_applierCachedSession = key.SessionKey;
|
||||
t_applierCachedContext = key.ContextToken;
|
||||
t_applierCachedGeneration = generation;
|
||||
return *applier;
|
||||
}
|
||||
|
||||
void MGPipeSetApplierKeyResolver(MGPipeApplierKeyResolver resolver) { g_applierKeyResolver = resolver; }
|
||||
|
||||
void MGPipeApplierRegisterContext(Uint64 sessionKey, Uint64 contextToken, Uint64 shareGroupToken) {
|
||||
std::lock_guard<std::mutex> guard(g_applierSessionsMutex);
|
||||
ApplierSession& session = g_applierSessions[sessionKey];
|
||||
const Uint64 groupKey = ApplierShareGroupKey(contextToken, shareGroupToken);
|
||||
auto group = session.Groups.find(groupKey);
|
||||
if (group == session.Groups.end()) {
|
||||
group = session.Groups.emplace(groupKey, MakeUnique<MGPipeObjectRecords>()).first;
|
||||
}
|
||||
const auto existing = session.Contexts.find(contextToken);
|
||||
if (existing != session.Contexts.end() && existing->second) {
|
||||
// Idempotent: the same token registered twice keeps the state it already has. The
|
||||
// session refuses a duplicate CreateContext before reaching here, so this arm is a
|
||||
// caller that re-registers deliberately.
|
||||
g_applierRegistryGeneration.fetch_add(1, std::memory_order_acq_rel);
|
||||
return;
|
||||
}
|
||||
session.Contexts.emplace(contextToken, MakeUnique<MGPipeApplierState>(*group->second));
|
||||
session.ContextGroup[contextToken] = groupKey;
|
||||
++session.GroupContexts[groupKey];
|
||||
g_applierRegistryGeneration.fetch_add(1, std::memory_order_acq_rel);
|
||||
}
|
||||
|
||||
void MGPipeApplierUnregisterContext(Uint64 sessionKey, Uint64 contextToken) {
|
||||
std::lock_guard<std::mutex> guard(g_applierSessionsMutex);
|
||||
const auto sessionIt = g_applierSessions.find(sessionKey);
|
||||
if (sessionIt == g_applierSessions.end()) return;
|
||||
ApplierSession& session = sessionIt->second;
|
||||
const auto context = session.Contexts.find(contextToken);
|
||||
if (context == session.Contexts.end()) return;
|
||||
const auto groupIt = session.ContextGroup.find(contextToken);
|
||||
const Uint64 groupKey = groupIt != session.ContextGroup.end() ? groupIt->second : 0;
|
||||
// The OBJECT RECORDS GO WITH THE LAST CONTEXT OF THE GROUP, which is the per-group
|
||||
// spelling of MGPipeApplierReleaseObjectRecords' scope. A surviving context of the same
|
||||
// group keeps every record - that is what sharing means.
|
||||
const auto refs = session.GroupContexts.find(groupKey);
|
||||
const Bool lastOfGroup = refs != session.GroupContexts.end() && refs->second <= 1;
|
||||
session.Contexts.erase(context);
|
||||
if (groupIt != session.ContextGroup.end()) session.ContextGroup.erase(groupIt);
|
||||
if (lastOfGroup) {
|
||||
if (refs != session.GroupContexts.end()) session.GroupContexts.erase(refs);
|
||||
const auto group = session.Groups.find(groupKey);
|
||||
if (group != session.Groups.end()) session.Groups.erase(group);
|
||||
} else if (refs != session.GroupContexts.end()) {
|
||||
--refs->second;
|
||||
}
|
||||
if (session.Contexts.empty()) g_applierSessions.erase(sessionIt);
|
||||
g_applierRegistryGeneration.fetch_add(1, std::memory_order_acq_rel);
|
||||
}
|
||||
|
||||
void MGPipeApplierReleaseSession(Uint64 sessionKey) {
|
||||
std::lock_guard<std::mutex> guard(g_applierSessionsMutex);
|
||||
if (g_applierSessions.erase(sessionKey) == 0) return;
|
||||
g_applierRegistryGeneration.fetch_add(1, std::memory_order_acq_rel);
|
||||
}
|
||||
|
||||
Uint64 MGPipeApplierShareGroupCountForTesting(Uint64 sessionKey) {
|
||||
std::lock_guard<std::mutex> guard(g_applierSessionsMutex);
|
||||
const auto sessionIt = g_applierSessions.find(sessionKey);
|
||||
return sessionIt == g_applierSessions.end() ? 0 : static_cast<Uint64>(sessionIt->second.Groups.size());
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
// The installed handle-shaped resource table. Null until a backend registers one,
|
||||
// which is what makes the client half landable on its own: with nothing here every
|
||||
@@ -490,8 +652,8 @@ namespace MobileGL::MG_Pipe {
|
||||
const MGPipeResourceOps* g_resourceOps = nullptr;
|
||||
|
||||
MGPipeRenderStateCsoRecord* FindCso(MGPipeHandle handle) {
|
||||
if (handle.Slot >= g_applier.RenderStateCsos.size()) return nullptr;
|
||||
MGPipeRenderStateCsoRecord& record = g_applier.RenderStateCsos[handle.Slot];
|
||||
if (handle.Slot >= MGPipeApplier().RenderStateCsos.size()) return nullptr;
|
||||
MGPipeRenderStateCsoRecord& record = MGPipeApplier().RenderStateCsos[handle.Slot];
|
||||
if (!record.Live || record.Gen != handle.Gen) return nullptr;
|
||||
return &record;
|
||||
}
|
||||
@@ -527,15 +689,15 @@ namespace MobileGL::MG_Pipe {
|
||||
// that is not live, or a handle whose generation has moved on because the slot was
|
||||
// recycled under it. FindCso above is the same three questions for the CSO store.
|
||||
MGPipeResourceRecord* FindResource(MGPipeHandle res) {
|
||||
if (res.Slot >= g_applier.Resources.size()) return nullptr;
|
||||
MGPipeResourceRecord& record = g_applier.Resources[res.Slot];
|
||||
if (res.Slot >= MGPipeApplier().Resources.size()) return nullptr;
|
||||
MGPipeResourceRecord& record = MGPipeApplier().Resources[res.Slot];
|
||||
if (!record.Live || record.Gen != res.Gen) return nullptr;
|
||||
return &record;
|
||||
}
|
||||
|
||||
MGPipeVertexElementsRecord* FindVertexElements(MGPipeHandle cso) {
|
||||
if (cso.Slot >= g_applier.VertexElementsCsos.size()) return nullptr;
|
||||
MGPipeVertexElementsRecord& record = g_applier.VertexElementsCsos[cso.Slot];
|
||||
if (cso.Slot >= MGPipeApplier().VertexElementsCsos.size()) return nullptr;
|
||||
MGPipeVertexElementsRecord& record = MGPipeApplier().VertexElementsCsos[cso.Slot];
|
||||
if (!record.Live || record.Gen != cso.Gen) return nullptr;
|
||||
return &record;
|
||||
}
|
||||
@@ -562,15 +724,15 @@ namespace MobileGL::MG_Pipe {
|
||||
// respecify or destroy an unrelated LIVE object that happens to hold the same slot in
|
||||
// another kind's space, and that is the "act outside its own storage" class.
|
||||
Vector<MGPipeResourceRecord>* ResourceTableForTarget(Uint8 target) {
|
||||
if (target == kMGPipeResourceTargetBuffer) return &g_applier.Resources;
|
||||
if (target == kMGPipeResourceTargetBuffer) return &MGPipeApplier().Resources;
|
||||
if (target == static_cast<Uint8>(MGPipeResourceTarget::Renderbuffer)) {
|
||||
return &g_applier.RenderbufferResources;
|
||||
return &MGPipeApplier().RenderbufferResources;
|
||||
}
|
||||
if (target < static_cast<Uint8>(MGPipeResourceTarget::Count)) {
|
||||
// Every remaining enumerator is a texture target, and they share one table
|
||||
// because they share one kind: MGPipeKind::Texture. Tex1D..TexCubeArray,
|
||||
// Tex2DMS/MSArray, TexBuffer and TexRect are all one slot space.
|
||||
return &g_applier.TextureResources;
|
||||
return &MGPipeApplier().TextureResources;
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
@@ -579,11 +741,11 @@ namespace MobileGL::MG_Pipe {
|
||||
Vector<MGPipeResourceRecord>* ResourceTableForKind(Uint32 kind) {
|
||||
switch (static_cast<MGPipeKind>(kind)) {
|
||||
case MGPipeKind::Buffer:
|
||||
return &g_applier.Resources;
|
||||
return &MGPipeApplier().Resources;
|
||||
case MGPipeKind::Texture:
|
||||
return &g_applier.TextureResources;
|
||||
return &MGPipeApplier().TextureResources;
|
||||
case MGPipeKind::Renderbuffer:
|
||||
return &g_applier.RenderbufferResources;
|
||||
return &MGPipeApplier().RenderbufferResources;
|
||||
default:
|
||||
return nullptr;
|
||||
}
|
||||
@@ -710,7 +872,7 @@ namespace MobileGL::MG_Pipe {
|
||||
MGPipeResourceRecord* record = FindResource(res);
|
||||
MOBILEGL_ASSERT(record != nullptr, "%s named {slot=%u, gen=%u}: %s", call, res.Slot, res.Gen,
|
||||
kResourceRefusalNote);
|
||||
if (record == nullptr) ++g_applier.RefusedResourceCalls;
|
||||
if (record == nullptr) ++MGPipeApplier().RefusedResourceCalls;
|
||||
return record;
|
||||
}
|
||||
|
||||
@@ -723,7 +885,7 @@ namespace MobileGL::MG_Pipe {
|
||||
MGPipeResourceRecord* record = FindIn(table, res);
|
||||
MOBILEGL_ASSERT(record != nullptr, "%s named {slot=%u, gen=%u}: %s", call, res.Slot, res.Gen,
|
||||
kResourceRefusalNote);
|
||||
if (record == nullptr) ++g_applier.RefusedResourceCalls;
|
||||
if (record == nullptr) ++MGPipeApplier().RefusedResourceCalls;
|
||||
return record;
|
||||
}
|
||||
|
||||
@@ -736,7 +898,7 @@ namespace MobileGL::MG_Pipe {
|
||||
Record* record = FindIn(table, handle);
|
||||
MOBILEGL_ASSERT(record != nullptr, "%s named {slot=%u, gen=%u}: %s", call, handle.Slot,
|
||||
handle.Gen, kResourceRefusalNote);
|
||||
if (record == nullptr) ++g_applier.RefusedObjectCalls;
|
||||
if (record == nullptr) ++MGPipeApplier().RefusedObjectCalls;
|
||||
return record;
|
||||
}
|
||||
|
||||
@@ -744,7 +906,7 @@ namespace MobileGL::MG_Pipe {
|
||||
MGPipeVertexElementsRecord* record = FindVertexElements(cso);
|
||||
MOBILEGL_ASSERT(record != nullptr, "%s named {slot=%u, gen=%u}: %s", call, cso.Slot, cso.Gen,
|
||||
kResourceRefusalNote);
|
||||
if (record == nullptr) ++g_applier.RefusedVertexInputCalls;
|
||||
if (record == nullptr) ++MGPipeApplier().RefusedVertexInputCalls;
|
||||
return record;
|
||||
}
|
||||
|
||||
@@ -1198,7 +1360,7 @@ namespace MobileGL::MG_Pipe {
|
||||
// hook; the monolith shape of everything above them is unchanged.
|
||||
Bool ApplyTextureUpload(const MGPSubData& record, const void* bytes, const MGPSubRegion* regions) {
|
||||
MGPipeResourceRecord* stored =
|
||||
ResolveResourceIn(g_applier.TextureResources, "resource_subdata", record.Res);
|
||||
ResolveResourceIn(MGPipeApplier().TextureResources, "resource_subdata", record.Res);
|
||||
if (stored == nullptr) return false;
|
||||
|
||||
const char* fault = SubDataTextureFault(record, regions);
|
||||
@@ -1319,28 +1481,28 @@ namespace MobileGL::MG_Pipe {
|
||||
// ----------------------------------------------------------------------------
|
||||
MGPipeShaderCsoRecord* ShaderCsoRecordAt(Uint32 slot) {
|
||||
if (MGPipeIsCompositeShaderSlot(slot)) {
|
||||
return RecordAt(g_applier.CompositeShaderCsos, slot - kMGPipeShaderCsoCompositeSlotBase,
|
||||
return RecordAt(MGPipeApplier().CompositeShaderCsos, slot - kMGPipeShaderCsoCompositeSlotBase,
|
||||
kMGPipeShaderCsoSlotLimit - kMGPipeShaderCsoCompositeSlotBase);
|
||||
}
|
||||
// The ordinary table is bounded by the BAND'S BASE and not by the slot limit: an
|
||||
// ordinary program can never be handed a band slot (the allocator refuses it), so a
|
||||
// slot at or above the base that is not a composite is out of range by definition.
|
||||
return RecordAt(g_applier.ShaderCsos, slot, kMGPipeShaderCsoCompositeSlotBase);
|
||||
return RecordAt(MGPipeApplier().ShaderCsos, slot, kMGPipeShaderCsoCompositeSlotBase);
|
||||
}
|
||||
|
||||
MGPipeShaderCsoRecord* FindShaderCso(MGPipeHandle cso) {
|
||||
if (MGPipeIsCompositeShaderSlot(cso.Slot)) {
|
||||
return FindIn(g_applier.CompositeShaderCsos,
|
||||
return FindIn(MGPipeApplier().CompositeShaderCsos,
|
||||
MGPipeHandle{cso.Slot - kMGPipeShaderCsoCompositeSlotBase, cso.Gen});
|
||||
}
|
||||
return FindIn(g_applier.ShaderCsos, cso);
|
||||
return FindIn(MGPipeApplier().ShaderCsos, cso);
|
||||
}
|
||||
|
||||
MGPipeShaderCsoRecord* ResolveShaderCso(const char* call, MGPipeHandle cso) {
|
||||
MGPipeShaderCsoRecord* record = FindShaderCso(cso);
|
||||
MOBILEGL_ASSERT(record != nullptr, "%s named {slot=%u, gen=%u}: %s", call, cso.Slot, cso.Gen,
|
||||
kResourceRefusalNote);
|
||||
if (record == nullptr) ++g_applier.RefusedObjectCalls;
|
||||
if (record == nullptr) ++MGPipeApplier().RefusedObjectCalls;
|
||||
return record;
|
||||
}
|
||||
|
||||
@@ -1388,13 +1550,14 @@ namespace MobileGL::MG_Pipe {
|
||||
#endif
|
||||
} // namespace
|
||||
|
||||
MGPipeApplierState& MGPipeApplier() { return g_applier; }
|
||||
// MGPipeApplier() is defined with the registry at the top of this file: it is the one
|
||||
// function that has to know whose applier the calling thread is in.
|
||||
|
||||
// P5c (rv, CONTRACT-P5C.md §5.3): the three texture shutters' server-side answers. See
|
||||
// MGPipeApplierState::TextureShutterSerial / ContextSerial for the bump rule.
|
||||
Uint64 MGPipeApplierTextureShutterSerial() { return g_applier.TextureShutterSerial; }
|
||||
Uint64 MGPipeApplierContextSerial() { return g_applier.ContextSerial; }
|
||||
void MGPipeApplierNoteTextureStateMoved() { ++g_applier.TextureShutterSerial; }
|
||||
Uint64 MGPipeApplierTextureShutterSerial() { return MGPipeApplier().TextureShutterSerial; }
|
||||
Uint64 MGPipeApplierContextSerial() { return MGPipeApplier().ContextSerial; }
|
||||
void MGPipeApplierNoteTextureStateMoved() { ++MGPipeApplier().TextureShutterSerial; }
|
||||
|
||||
void MGPipeSetResourceOps(const MGPipeResourceOps* ops) { g_resourceOps = ops; }
|
||||
const MGPipeResourceOps* MGPipeGetResourceOps() { return g_resourceOps; }
|
||||
@@ -1427,7 +1590,7 @@ namespace MobileGL::MG_Pipe {
|
||||
}
|
||||
#endif
|
||||
if (g_resourceOps != nullptr) return false;
|
||||
++g_applier.RefusedNoConsumer;
|
||||
++MGPipeApplier().RefusedNoConsumer;
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -1438,11 +1601,11 @@ namespace MobileGL::MG_Pipe {
|
||||
// zero" rule is written out.
|
||||
void ClearShaderBufferWindows() {
|
||||
for (Uint32 cls = 0; cls < kMGPipeShaderBufferClassCount; ++cls) {
|
||||
g_applier.BoundShaderBuffers[cls] = {};
|
||||
g_applier.ShaderBufferStart[cls] = 0;
|
||||
g_applier.ShaderBufferCount[cls] = 0;
|
||||
MGPipeApplier().BoundShaderBuffers[cls] = {};
|
||||
MGPipeApplier().ShaderBufferStart[cls] = 0;
|
||||
MGPipeApplier().ShaderBufferCount[cls] = 0;
|
||||
for (Uint32 w = 0; w < kMGPipeShaderBufferWritableMaskWords; ++w) {
|
||||
g_applier.ShaderBufferWritableMask[cls][w] = 0;
|
||||
MGPipeApplier().ShaderBufferWritableMask[cls][w] = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1480,15 +1643,15 @@ namespace MobileGL::MG_Pipe {
|
||||
std::abort();
|
||||
}
|
||||
#endif
|
||||
g_applier.RenderStateCsos.clear();
|
||||
g_applier.BoundRenderStateCso = kMGPipeNullHandle;
|
||||
g_applier.Residual = ResidualValueBlock{};
|
||||
g_applier.HasResidual = false;
|
||||
g_applier.ScatteredChunkBits = 0;
|
||||
g_applier.ResidualCapabilitiesCompared = 0;
|
||||
g_applier.ResidualDivergences = 0;
|
||||
g_applier.PatchCarrierComparisons = 0;
|
||||
g_applier.PatchCarrierDivergences = 0;
|
||||
MGPipeApplier().RenderStateCsos.clear();
|
||||
MGPipeApplier().BoundRenderStateCso = kMGPipeNullHandle;
|
||||
MGPipeApplier().Residual = ResidualValueBlock{};
|
||||
MGPipeApplier().HasResidual = false;
|
||||
MGPipeApplier().ScatteredChunkBits = 0;
|
||||
MGPipeApplier().ResidualCapabilitiesCompared = 0;
|
||||
MGPipeApplier().ResidualDivergences = 0;
|
||||
MGPipeApplier().PatchCarrierComparisons = 0;
|
||||
MGPipeApplier().PatchCarrierDivergences = 0;
|
||||
// P3a. THIS RUNS AT EVERY CHANGE OF THE CURRENT CONTEXT, not once per fresh one:
|
||||
// MGPipeTracker::Update resets itself whenever the context pointer moves and the
|
||||
// emitter calls this from the walk that follows, so a make-current BACK to a context
|
||||
@@ -1505,16 +1668,16 @@ namespace MobileGL::MG_Pipe {
|
||||
//
|
||||
// The OP TABLE is deliberately not cleared either - it is installed and uninstalled by
|
||||
// the backend's own bring-up and teardown, not by a state reset.
|
||||
g_applier.RefusedResourceCalls = 0;
|
||||
g_applier.RefusedVertexInputCalls = 0;
|
||||
g_applier.RefusedObjectCalls = 0;
|
||||
g_applier.RefusedNoConsumer = 0;
|
||||
g_applier.BoundVertexElements = kMGPipeNullHandle;
|
||||
g_applier.VertexBuffers = {};
|
||||
g_applier.VertexBufferStart = 0;
|
||||
g_applier.VertexBufferCount = 0;
|
||||
g_applier.VertexFetchBaseInstance = 0;
|
||||
g_applier.IndexBuffer = MGPIndexBuffer{};
|
||||
MGPipeApplier().RefusedResourceCalls = 0;
|
||||
MGPipeApplier().RefusedVertexInputCalls = 0;
|
||||
MGPipeApplier().RefusedObjectCalls = 0;
|
||||
MGPipeApplier().RefusedNoConsumer = 0;
|
||||
MGPipeApplier().BoundVertexElements = kMGPipeNullHandle;
|
||||
MGPipeApplier().VertexBuffers = {};
|
||||
MGPipeApplier().VertexBufferStart = 0;
|
||||
MGPipeApplier().VertexBufferCount = 0;
|
||||
MGPipeApplier().VertexFetchBaseInstance = 0;
|
||||
MGPipeApplier().IndexBuffer = MGPIndexBuffer{};
|
||||
// m6 / wire n6, written down rather than left to be rediscovered: THIS counter is
|
||||
// per-applier and is zeroed at every make-current, while MG_Util::PipeStats' `mpr` -
|
||||
// emitted from the CLIENT at MG_Impl/Pipe/PipeFill.cpp's MGPipeEmitMapPersistent - is
|
||||
@@ -1529,7 +1692,7 @@ namespace MobileGL::MG_Pipe {
|
||||
// MG_IntegrationTest/Harness/PipeStatsWindow.h - they cannot link this symbol at all, on
|
||||
// Android or anywhere else - so a make-current inside a scenario cannot silently reset
|
||||
// what they measure. Nothing outside MG_Test reads the member below.
|
||||
g_applier.MapPersistentRoundtrips = 0;
|
||||
MGPipeApplier().MapPersistentRoundtrips = 0;
|
||||
// THE TWO SERIALS ADVANCE; THEY ARE NOT ZEROED. They are MGGens, and an MGGen that
|
||||
// walks backwards is not one. There are exactly three things a reset can do to a
|
||||
// version whose data it has just cleared:
|
||||
@@ -1543,15 +1706,15 @@ namespace MobileGL::MG_Pipe {
|
||||
// count is stable lands on a stamped value every time;
|
||||
// - advance: the clearing is itself announced, no stamped value can ever recur, and
|
||||
// the first compare after the switch is a mismatch, which is the safe direction.
|
||||
++g_applier.VertexBuffersSerial;
|
||||
++g_applier.IndexBufferSerial;
|
||||
++MGPipeApplier().VertexBuffersSerial;
|
||||
++MGPipeApplier().IndexBufferSerial;
|
||||
// P5c (rv): a make-current is a fresh server, and the two shutter serials are what the
|
||||
// PipeInputs texture-shutter accessors answer with - so both ADVANCE here, for the
|
||||
// serials' own reason: a counter that restarts walks back through values already
|
||||
// stamped into a memo that outlived the switch. ContextSerial's move is also
|
||||
// GetTextureContextId's whole job (the backends key their per-context memos on it).
|
||||
++g_applier.TextureShutterSerial;
|
||||
++g_applier.ContextSerial;
|
||||
++MGPipeApplier().TextureShutterSerial;
|
||||
++MGPipeApplier().ContextSerial;
|
||||
|
||||
// ---- P4a's working state, cleared for the same reason and with the same serial rule
|
||||
// (D-J4). The OBJECT records - texture and renderbuffer resources, sampler CSOs,
|
||||
@@ -1566,21 +1729,21 @@ namespace MobileGL::MG_Pipe {
|
||||
// a null Fbo. FramebufferRecords stays because a framebuffer that is only ever addressed
|
||||
// BY NAME - the DSA blit and clear entry points - has no re-emission trigger at all, so
|
||||
// dropping its record here would lose it for the life of the process.
|
||||
g_applier.BoundFramebuffer = {};
|
||||
g_applier.BoundSamplerViews = {};
|
||||
g_applier.SamplerViewStart = 0;
|
||||
g_applier.SamplerViewCount = 0;
|
||||
g_applier.BoundSamplerStates = {};
|
||||
g_applier.SamplerStateStart = 0;
|
||||
g_applier.SamplerStateCount = 0;
|
||||
g_applier.BoundShaderImages = {};
|
||||
g_applier.ShaderImageStart = 0;
|
||||
g_applier.ShaderImageCount = 0;
|
||||
g_applier.DrawProgram = kMGPipeNullHandle;
|
||||
g_applier.DispatchProgram = kMGPipeNullHandle;
|
||||
g_applier.BoundShaderCso = kMGPipeNullHandle;
|
||||
MGPipeApplier().BoundFramebuffer = {};
|
||||
MGPipeApplier().BoundSamplerViews = {};
|
||||
MGPipeApplier().SamplerViewStart = 0;
|
||||
MGPipeApplier().SamplerViewCount = 0;
|
||||
MGPipeApplier().BoundSamplerStates = {};
|
||||
MGPipeApplier().SamplerStateStart = 0;
|
||||
MGPipeApplier().SamplerStateCount = 0;
|
||||
MGPipeApplier().BoundShaderImages = {};
|
||||
MGPipeApplier().ShaderImageStart = 0;
|
||||
MGPipeApplier().ShaderImageCount = 0;
|
||||
MGPipeApplier().DrawProgram = kMGPipeNullHandle;
|
||||
MGPipeApplier().DispatchProgram = kMGPipeNullHandle;
|
||||
MGPipeApplier().BoundShaderCso = kMGPipeNullHandle;
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
g_applier.BoundStreamOutputLifetimeId = 0;
|
||||
MGPipeApplier().BoundStreamOutputLifetimeId = 0;
|
||||
// Begin is emitted once per span, not on make-current. Its immutable object
|
||||
// snapshot survives with the resource/program records until End or release;
|
||||
// set_context_values restores the returning context's bound lifetime id.
|
||||
@@ -1595,12 +1758,12 @@ namespace MobileGL::MG_Pipe {
|
||||
// invalidates the three suppressor slots), or the first emission after a make-current
|
||||
// would be suppressed as unchanged and the server would draw with a cleared window.
|
||||
ClearShaderBufferWindows();
|
||||
++g_applier.FramebufferSerial;
|
||||
++g_applier.SamplerViewsSerial;
|
||||
++g_applier.SamplerStatesSerial;
|
||||
++g_applier.ShaderImagesSerial;
|
||||
++g_applier.ProgramBindingSerial;
|
||||
++g_applier.ShaderBuffersSerial;
|
||||
++MGPipeApplier().FramebufferSerial;
|
||||
++MGPipeApplier().SamplerViewsSerial;
|
||||
++MGPipeApplier().SamplerStatesSerial;
|
||||
++MGPipeApplier().ShaderImagesSerial;
|
||||
++MGPipeApplier().ProgramBindingSerial;
|
||||
++MGPipeApplier().ShaderBuffersSerial;
|
||||
}
|
||||
|
||||
void MGPipeApplierReleaseObjectRecords() {
|
||||
@@ -1615,37 +1778,37 @@ namespace MobileGL::MG_Pipe {
|
||||
// context, so nothing wires this - see PipeApply.h. The two serials advance here for
|
||||
// MGPipeApplierReset's reason: state was cleared, and a twin that outlives it must not
|
||||
// be able to match a value it has already seen.
|
||||
g_applier.Resources.clear();
|
||||
g_applier.VertexElementsCsos.clear();
|
||||
g_applier.BoundVertexElements = kMGPipeNullHandle;
|
||||
++g_applier.VertexBuffersSerial;
|
||||
++g_applier.IndexBufferSerial;
|
||||
MGPipeApplier().Resources.clear();
|
||||
MGPipeApplier().VertexElementsCsos.clear();
|
||||
MGPipeApplier().BoundVertexElements = kMGPipeNullHandle;
|
||||
++MGPipeApplier().VertexBuffersSerial;
|
||||
++MGPipeApplier().IndexBufferSerial;
|
||||
// P5c (rv): same rule for the shutter serials - the served context is going away, and
|
||||
// a memo that outlives it must not match a value these have already answered with.
|
||||
++g_applier.TextureShutterSerial;
|
||||
++g_applier.ContextSerial;
|
||||
++MGPipeApplier().TextureShutterSerial;
|
||||
++MGPipeApplier().ContextSerial;
|
||||
// P4a's five object tables go with them, and the working handles they could name go
|
||||
// too - a bound shader CSO whose record has just been dropped must not survive as a
|
||||
// handle the next call resolves against.
|
||||
g_applier.TextureResources.clear();
|
||||
g_applier.RenderbufferResources.clear();
|
||||
g_applier.SamplerCsos.clear();
|
||||
g_applier.SamplerViewCsos.clear();
|
||||
g_applier.ShaderCsos.clear();
|
||||
g_applier.CompositeShaderCsos.clear();
|
||||
MGPipeApplier().TextureResources.clear();
|
||||
MGPipeApplier().RenderbufferResources.clear();
|
||||
MGPipeApplier().SamplerCsos.clear();
|
||||
MGPipeApplier().SamplerViewCsos.clear();
|
||||
MGPipeApplier().ShaderCsos.clear();
|
||||
MGPipeApplier().CompositeShaderCsos.clear();
|
||||
// AND THE FRAMEBUFFER RECORDS, which MGPipeApplierReset above deliberately keeps. Here
|
||||
// there is nothing for them to outlive: the served context is going away and the
|
||||
// framebuffers it owned are container objects that go with it. A table left standing
|
||||
// would answer a lookup from the NEXT context on a slot the allocator has re-minted -
|
||||
// with the same generation, if the next context happens to reach the same one - and
|
||||
// that is the aliasing every other table is cleared to prevent.
|
||||
g_applier.FramebufferRecords.clear();
|
||||
g_applier.DrawProgram = kMGPipeNullHandle;
|
||||
g_applier.DispatchProgram = kMGPipeNullHandle;
|
||||
g_applier.BoundShaderCso = kMGPipeNullHandle;
|
||||
MGPipeApplier().FramebufferRecords.clear();
|
||||
MGPipeApplier().DrawProgram = kMGPipeNullHandle;
|
||||
MGPipeApplier().DispatchProgram = kMGPipeNullHandle;
|
||||
MGPipeApplier().BoundShaderCso = kMGPipeNullHandle;
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
g_applier.BoundStreamOutputLifetimeId = 0;
|
||||
g_applier.StreamOutputSpans.clear();
|
||||
MGPipeApplier().BoundStreamOutputLifetimeId = 0;
|
||||
MGPipeApplier().StreamOutputSpans.clear();
|
||||
#endif
|
||||
// AND "THE WORKING HANDLES THEY COULD NAME" IS ALL OF THEM, NOT JUST THE THREE ABOVE.
|
||||
// Every framebuffer record holds eleven MGPSurface::Res naming texture and renderbuffer
|
||||
@@ -1657,35 +1820,35 @@ namespace MobileGL::MG_Pipe {
|
||||
// else's record. So this takes the same working state MGPipeApplierReset does - which is
|
||||
// the honest reading of the rule as well: Reset keeps the object records BECAUSE they
|
||||
// outlive a make-current, and here they do not outlive anything.
|
||||
g_applier.BoundFramebuffer = {};
|
||||
g_applier.BoundSamplerViews = {};
|
||||
g_applier.SamplerViewStart = 0;
|
||||
g_applier.SamplerViewCount = 0;
|
||||
g_applier.BoundSamplerStates = {};
|
||||
g_applier.SamplerStateStart = 0;
|
||||
g_applier.SamplerStateCount = 0;
|
||||
g_applier.BoundShaderImages = {};
|
||||
g_applier.ShaderImageStart = 0;
|
||||
g_applier.ShaderImageCount = 0;
|
||||
MGPipeApplier().BoundFramebuffer = {};
|
||||
MGPipeApplier().BoundSamplerViews = {};
|
||||
MGPipeApplier().SamplerViewStart = 0;
|
||||
MGPipeApplier().SamplerViewCount = 0;
|
||||
MGPipeApplier().BoundSamplerStates = {};
|
||||
MGPipeApplier().SamplerStateStart = 0;
|
||||
MGPipeApplier().SamplerStateCount = 0;
|
||||
MGPipeApplier().BoundShaderImages = {};
|
||||
MGPipeApplier().ShaderImageStart = 0;
|
||||
MGPipeApplier().ShaderImageCount = 0;
|
||||
// P5e (sb): and the three binding-point windows, for the paragraph above's reason in
|
||||
// its own words - every MGPBufferRange::Res names a resource record this function has
|
||||
// just dropped, so a window left populated here is a set of handles into an empty
|
||||
// table, which the next resolve either refuses or answers with somebody else's record
|
||||
// on a slot the next context re-mints.
|
||||
ClearShaderBufferWindows();
|
||||
++g_applier.FramebufferSerial;
|
||||
++g_applier.SamplerViewsSerial;
|
||||
++g_applier.SamplerStatesSerial;
|
||||
++g_applier.ShaderImagesSerial;
|
||||
++g_applier.ProgramBindingSerial;
|
||||
++g_applier.ShaderBuffersSerial;
|
||||
++MGPipeApplier().FramebufferSerial;
|
||||
++MGPipeApplier().SamplerViewsSerial;
|
||||
++MGPipeApplier().SamplerStatesSerial;
|
||||
++MGPipeApplier().ShaderImagesSerial;
|
||||
++MGPipeApplier().ProgramBindingSerial;
|
||||
++MGPipeApplier().ShaderBuffersSerial;
|
||||
}
|
||||
|
||||
void MGPipeApplyCreateRenderState(const MGPRenderStateDesc& desc, const void* chunkBytes) {
|
||||
MOBILEGL_ASSERT(desc.Cso.Slot >= kMGPipeFirstAllocatableSlot,
|
||||
"create_render_state named the reserved slot 0");
|
||||
MGPipeRenderStateCsoRecord* recordAt =
|
||||
RecordAt(g_applier.RenderStateCsos, desc.Cso.Slot, kMGPipeMaxRenderStateCsoSlots);
|
||||
RecordAt(MGPipeApplier().RenderStateCsos, desc.Cso.Slot, kMGPipeMaxRenderStateCsoSlots);
|
||||
if (recordAt == nullptr) {
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
MGPipeSessionFail(MGPipeFatalFamily::ProtocolCorruption,
|
||||
@@ -1753,12 +1916,12 @@ namespace MobileGL::MG_Pipe {
|
||||
MGPipeScatterPipelineBytes(record->PipelineBytes.data(),
|
||||
MGPipeApplyAccess::RenderState(inputs));
|
||||
MGPipeApplyAccess::SetRenderStateVersions(inputs, bind.Version, bind.PipelineVersion);
|
||||
g_applier.BoundRenderStateCso = bind.Cso;
|
||||
MGPipeApplier().BoundRenderStateCso = bind.Cso;
|
||||
// A bind scatters the WHOLE pipeline half - the record is always a complete one,
|
||||
// whatever mask minted it - so the pipeline chunks are all "moved" here, and all
|
||||
// enter the applier's ledger of the bytes it owns.
|
||||
const Uint32 moved = MGPipeGlobalChunkBitsOfPipelineMask(kAllPipelineChunks);
|
||||
g_applier.ScatteredChunkBits |= moved;
|
||||
MGPipeApplier().ScatteredChunkBits |= moved;
|
||||
MGPipeDeriveRenderStateFieldsForChunks(inputs, moved);
|
||||
}
|
||||
|
||||
@@ -1771,8 +1934,8 @@ namespace MobileGL::MG_Pipe {
|
||||
// The Gen stays: it is the CLIENT allocator that bumps it when the slot is handed
|
||||
// out again (MGPipeHandles.h: "Gen increments only when a SLOT IS REUSED"), and a
|
||||
// server-side bump here would put the two identities out of step.
|
||||
if (g_applier.BoundRenderStateCso == handle.Handle) {
|
||||
g_applier.BoundRenderStateCso = kMGPipeNullHandle;
|
||||
if (MGPipeApplier().BoundRenderStateCso == handle.Handle) {
|
||||
MGPipeApplier().BoundRenderStateCso = kMGPipeNullHandle;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1781,7 +1944,7 @@ namespace MobileGL::MG_Pipe {
|
||||
MGPipeScatterDynamicChunks(chunkBytes, dyn.ChunkMask, MGPipeApplyAccess::RenderState(inputs));
|
||||
MGPipeApplyAccess::SetRenderStateParametersVersion(inputs, dyn.Version);
|
||||
const Uint32 moved = MGPipeGlobalChunkBitsOfDynamicMask(dyn.ChunkMask);
|
||||
g_applier.ScatteredChunkBits |= moved;
|
||||
MGPipeApplier().ScatteredChunkBits |= moved;
|
||||
MGPipeDeriveRenderStateFieldsForChunks(inputs, moved);
|
||||
}
|
||||
|
||||
@@ -1805,9 +1968,9 @@ namespace MobileGL::MG_Pipe {
|
||||
// filling, so a predicate that read the answer out of THERE would be reading the very
|
||||
// memory the rule exists to stop it reading. One store, inert until the caps bit is
|
||||
// published, and it is what makes the two roles' third clause the same clause.
|
||||
g_applier.IsTransformFeedbackActive = values.IsTransformFeedbackActive != 0;
|
||||
MGPipeApplier().IsTransformFeedbackActive = values.IsTransformFeedbackActive != 0;
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
g_applier.BoundStreamOutputLifetimeId = values.BoundTransformFeedbackLifetimeId;
|
||||
MGPipeApplier().BoundStreamOutputLifetimeId = values.BoundTransformFeedbackLifetimeId;
|
||||
#endif
|
||||
}
|
||||
|
||||
@@ -1839,13 +2002,13 @@ namespace MobileGL::MG_Pipe {
|
||||
// It runs in the shipped push build too, because a wire that is compiled out of
|
||||
// every build a device runs is not a wire. The cost is a 24-byte memcmp on a call
|
||||
// that is emitted when the tessellation state CHANGES, i.e. about once per program.
|
||||
if ((g_applier.ScatteredChunkBits & kChunksPatchTrio) == kChunksPatchTrio) {
|
||||
++g_applier.PatchCarrierComparisons;
|
||||
if ((MGPipeApplier().ScatteredChunkBits & kChunksPatchTrio) == kChunksPatchTrio) {
|
||||
++MGPipeApplier().PatchCarrierComparisons;
|
||||
const Bool agrees = working.PatchVertices == patch.Vertices &&
|
||||
std::memcmp(&working.PatchDefaultOuterLevel, &outer, sizeof(outer)) == 0 &&
|
||||
std::memcmp(&working.PatchDefaultInnerLevel, &inner, sizeof(inner)) == 0;
|
||||
if (!agrees) {
|
||||
++g_applier.PatchCarrierDivergences;
|
||||
++MGPipeApplier().PatchCarrierDivergences;
|
||||
MGP_TRIP_WIRE_REPORT("MGPipe: " MGP_TRIP_WIRE_TAG("PipePatchCarriersDiffer")
|
||||
" set_patch_state says vertices=%u outer=(%g,%g,%g,%g) inner=(%g,%g); "
|
||||
"chunk P0 delivered vertices=%u outer=(%g,%g,%g,%g) inner=(%g,%g)",
|
||||
@@ -1921,9 +2084,9 @@ namespace MobileGL::MG_Pipe {
|
||||
}
|
||||
|
||||
void MGPipeApplySetResidualValueState(const ResidualValueBlock& block) {
|
||||
g_applier.Residual = block;
|
||||
g_applier.HasResidual = true;
|
||||
g_applier.ResidualCapabilitiesCompared = 0;
|
||||
MGPipeApplier().Residual = block;
|
||||
MGPipeApplier().HasResidual = true;
|
||||
MGPipeApplier().ResidualCapabilitiesCompared = 0;
|
||||
|
||||
// THE TRIP WIRE (ARCHITECTURE.md 9.4, P2 brief D9). CapabilityBits is redundant with
|
||||
// the assembled working block by design: every one of the 35 capabilities is
|
||||
@@ -1953,16 +2116,16 @@ namespace MobileGL::MG_Pipe {
|
||||
// tautology. The redundancy this wire exists to check is between the CARRIED bits and
|
||||
// the ASSEMBLED block.
|
||||
const RenderStateParameters& working = MGPipeApplyAccess::RenderState(gPipeInputs);
|
||||
const Uint32 owned = g_applier.ScatteredChunkBits;
|
||||
const Uint32 owned = MGPipeApplier().ScatteredChunkBits;
|
||||
for (SizeT i = 0; i < kCapabilityCount; ++i) {
|
||||
const CapabilityInput cap = static_cast<CapabilityInput>(i);
|
||||
const Uint32 sources = CapabilitySourceChunks(cap);
|
||||
if ((owned & sources) != sources) continue;
|
||||
++g_applier.ResidualCapabilitiesCompared;
|
||||
++MGPipeApplier().ResidualCapabilitiesCompared;
|
||||
const Bool carried = ((block.CapabilityBits >> i) & 1ull) != 0;
|
||||
const Bool assembledBit = MGPipeApplyAccess::DeriveCapability(working, cap);
|
||||
if (carried == assembledBit) continue;
|
||||
++g_applier.ResidualDivergences;
|
||||
++MGPipeApplier().ResidualDivergences;
|
||||
MGP_TRIP_WIRE_REPORT("MGPipe: " MGP_TRIP_WIRE_TAG("PipeResidualDiverged, \"%s\"")
|
||||
" carried=%d assembled=%d",
|
||||
kCapabilityNames[i], static_cast<int>(carried),
|
||||
@@ -2279,7 +2442,7 @@ namespace MobileGL::MG_Pipe {
|
||||
|
||||
// THE FOUR BUFFER-ONLY CALLS, AND WHAT POLICES THAT. resource_flush_range,
|
||||
// resource_readback and map_persistent resolve through ResolveResource - i.e. against
|
||||
// g_applier.Resources and never the texture or renderbuffer table - which is right, because
|
||||
// MGPipeApplier().Resources and never the texture or renderbuffer table - which is right, because
|
||||
// a mapped range, a readback and a persistent donation exist for buffers only. They are
|
||||
// buffer-only BY CATALOGUE and not by check: MGPFlushRange and MGPReadback carry no kind
|
||||
// at all, and map_persistent's MGPHandleOnly is not asked for one, so there is nothing here
|
||||
@@ -2428,7 +2591,7 @@ namespace MobileGL::MG_Pipe {
|
||||
// Defined that way the number is identical in both modes, equals "one per storage
|
||||
// definition", and is non-zero and assertable today; defined as "round trips actually
|
||||
// taken" it would be 0 by construction in monolith and could never go red.
|
||||
++g_applier.MapPersistentRoundtrips;
|
||||
++MGPipeApplier().MapPersistentRoundtrips;
|
||||
|
||||
MGPipeResourceRecord* record = ResolveResource("map_persistent", handle.Handle);
|
||||
if (record == nullptr) return nullptr;
|
||||
@@ -2586,7 +2749,7 @@ namespace MobileGL::MG_Pipe {
|
||||
}
|
||||
|
||||
MGPipeVertexElementsRecord* recordAt =
|
||||
RecordAt(g_applier.VertexElementsCsos, desc.Cso.Slot, kMGPipeMaxVertexElementsSlots);
|
||||
RecordAt(MGPipeApplier().VertexElementsCsos, desc.Cso.Slot, kMGPipeMaxVertexElementsSlots);
|
||||
if (recordAt == nullptr) {
|
||||
MGP_TRIP_WIRE_REPORT("MGPipe: " MGP_TRIP_WIRE_TAG("ProtocolCorruption")
|
||||
" create_vertex_elements {slot=%u, gen=%u}: the slot is outside the record "
|
||||
@@ -2634,14 +2797,14 @@ namespace MobileGL::MG_Pipe {
|
||||
// The null handle is legal and means "no vertex array bound" - GL's unbound state is a
|
||||
// state, not an error, and the backend has a branch for it.
|
||||
if (MGPipeHandleIsNull(handle.Handle)) {
|
||||
g_applier.BoundVertexElements = kMGPipeNullHandle;
|
||||
MGPipeApplier().BoundVertexElements = kMGPipeNullHandle;
|
||||
return;
|
||||
}
|
||||
// A dead handle leaves the PREVIOUS binding untouched, which is bind_render_state's
|
||||
// precedent for the same question, and is counted like every other refusal.
|
||||
const MGPipeVertexElementsRecord* record = ResolveVertexElements("bind_vertex_elements", handle.Handle);
|
||||
if (record == nullptr) return;
|
||||
g_applier.BoundVertexElements = handle.Handle;
|
||||
MGPipeApplier().BoundVertexElements = handle.Handle;
|
||||
}
|
||||
|
||||
void MGPipeApplyDeleteVertexElements(const MGPHandleOnly& handle) {
|
||||
@@ -2663,8 +2826,8 @@ namespace MobileGL::MG_Pipe {
|
||||
const Uint32 gen = record->Gen;
|
||||
*record = MGPipeVertexElementsRecord{};
|
||||
record->Gen = gen;
|
||||
if (g_applier.BoundVertexElements == handle.Handle) {
|
||||
g_applier.BoundVertexElements = kMGPipeNullHandle;
|
||||
if (MGPipeApplier().BoundVertexElements == handle.Handle) {
|
||||
MGPipeApplier().BoundVertexElements = kMGPipeNullHandle;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2692,10 +2855,10 @@ namespace MobileGL::MG_Pipe {
|
||||
// are not cleared: this record is "the last set as received", and a set that names
|
||||
// four entries has said nothing about the rest.
|
||||
for (Uint32 i = 0; i < hdr.Count; ++i) {
|
||||
g_applier.VertexBuffers[hdr.Start + i] = tail[i];
|
||||
MGPipeApplier().VertexBuffers[hdr.Start + i] = tail[i];
|
||||
}
|
||||
g_applier.VertexBufferStart = hdr.Start;
|
||||
g_applier.VertexBufferCount = hdr.Count;
|
||||
MGPipeApplier().VertexBufferStart = hdr.Start;
|
||||
MGPipeApplier().VertexBufferCount = hdr.Count;
|
||||
|
||||
// THE RAW VALUE IS STORED, NOT A RESOLVED SHIFT, and the resolution is one step
|
||||
// further out on purpose. Whether the fetch shift has to be emulated at all is a
|
||||
@@ -2710,8 +2873,8 @@ namespace MobileGL::MG_Pipe {
|
||||
// input: set_vertex_buffers is suppressed on an unchanged hash, so a base instance
|
||||
// that moved while the buffer set did not would otherwise never arrive and the server
|
||||
// would keep the previous shift.
|
||||
g_applier.VertexFetchBaseInstance = hdr.BaseInstance;
|
||||
++g_applier.VertexBuffersSerial;
|
||||
MGPipeApplier().VertexFetchBaseInstance = hdr.BaseInstance;
|
||||
++MGPipeApplier().VertexBuffersSerial;
|
||||
}
|
||||
|
||||
void MGPipeApplySetIndexBuffer(const MGPIndexBuffer& record) {
|
||||
@@ -2725,8 +2888,8 @@ namespace MobileGL::MG_Pipe {
|
||||
// - it is an INDEPENDENT call and NOT a subset of the vertex-elements configuration
|
||||
// (D5): a rebind of the index slot must move this serial without touching the
|
||||
// configuration's, which is exactly what the backend's two separate compares need.
|
||||
g_applier.IndexBuffer = record;
|
||||
++g_applier.IndexBufferSerial;
|
||||
MGPipeApplier().IndexBuffer = record;
|
||||
++MGPipeApplier().IndexBufferSerial;
|
||||
}
|
||||
|
||||
void MGPipeDeriveRenderStateFields(PipeInputs& inputs) {
|
||||
@@ -2839,7 +3002,7 @@ namespace MobileGL::MG_Pipe {
|
||||
if (NoP4aConsumer()) return;
|
||||
|
||||
MGPipeFramebufferRecord* record =
|
||||
RecordAt(g_applier.FramebufferRecords, state.Fbo.Slot, kMGPipeMaxFramebufferSlots);
|
||||
RecordAt(MGPipeApplier().FramebufferRecords, state.Fbo.Slot, kMGPipeMaxFramebufferSlots);
|
||||
// Unreachable: the bound was checked above, before anything moved. The null check is
|
||||
// what makes that an argument rather than an assumption.
|
||||
if (record == nullptr) return;
|
||||
@@ -2851,11 +3014,11 @@ namespace MobileGL::MG_Pipe {
|
||||
// target: "this record describes the framebuffer it names; no binding changes".
|
||||
if (state.Target == static_cast<Uint8>(MGPipeFramebufferTarget::Draw) ||
|
||||
state.Target == static_cast<Uint8>(MGPipeFramebufferTarget::Both)) {
|
||||
g_applier.BoundFramebuffer[static_cast<SizeT>(MGPipeFramebufferTarget::Draw)] = state.Fbo;
|
||||
MGPipeApplier().BoundFramebuffer[static_cast<SizeT>(MGPipeFramebufferTarget::Draw)] = state.Fbo;
|
||||
}
|
||||
if (state.Target == static_cast<Uint8>(MGPipeFramebufferTarget::Read) ||
|
||||
state.Target == static_cast<Uint8>(MGPipeFramebufferTarget::Both)) {
|
||||
g_applier.BoundFramebuffer[static_cast<SizeT>(MGPipeFramebufferTarget::Read)] = state.Fbo;
|
||||
MGPipeApplier().BoundFramebuffer[static_cast<SizeT>(MGPipeFramebufferTarget::Read)] = state.Fbo;
|
||||
}
|
||||
// ONE SERIAL FOR THE FAMILY, and it moves once per applied record - a Both record is one
|
||||
// record and a Named record is one record. It is what retires the four g_fboSynced*
|
||||
@@ -2864,7 +3027,7 @@ namespace MobileGL::MG_Pipe {
|
||||
// serial still the server's". A Named record moves it for the same reason a bound one
|
||||
// does - a twin that memoised a framebuffer's attachments has to hear that they moved,
|
||||
// and whether the framebuffer happens to be bound is not that question.
|
||||
++g_applier.FramebufferSerial;
|
||||
++MGPipeApplier().FramebufferSerial;
|
||||
}
|
||||
|
||||
// THE READ SIDE OF THE TABLE (ID-19(b)/(d)). Package D asks it by handle at every DSA entry
|
||||
@@ -2941,7 +3104,7 @@ namespace MobileGL::MG_Pipe {
|
||||
}
|
||||
|
||||
MGPipeSamplerCsoRecord* recordAt =
|
||||
RecordAt(g_applier.SamplerCsos, desc.Cso.Slot, kMGPipeMaxSamplerCsoSlots);
|
||||
RecordAt(MGPipeApplier().SamplerCsos, desc.Cso.Slot, kMGPipeMaxSamplerCsoSlots);
|
||||
if (recordAt == nullptr) {
|
||||
MGP_TRIP_WIRE_REPORT("MGPipe: " MGP_TRIP_WIRE_TAG("ProtocolCorruption")
|
||||
" create_sampler_state {slot=%u, gen=%u}: the slot is outside the record "
|
||||
@@ -2978,7 +3141,7 @@ namespace MobileGL::MG_Pipe {
|
||||
MOBILEGL_ASSERT(handle.Kind == static_cast<Uint32>(MGPipeKind::SamplerCso),
|
||||
"delete_sampler_state on kind %u", handle.Kind);
|
||||
MGPipeSamplerCsoRecord* record =
|
||||
ResolveObject(g_applier.SamplerCsos, "delete_sampler_state", handle.Handle);
|
||||
ResolveObject(MGPipeApplier().SamplerCsos, "delete_sampler_state", handle.Handle);
|
||||
if (record == nullptr) return;
|
||||
|
||||
// Dropped whole, generation kept, for resource_destroy's reason: the client allocator
|
||||
@@ -3000,7 +3163,7 @@ namespace MobileGL::MG_Pipe {
|
||||
if (view.Cso.Slot < kMGPipeFirstAllocatableSlot) return;
|
||||
|
||||
MGPipeSamplerViewRecord* recordAt =
|
||||
RecordAt(g_applier.SamplerViewCsos, view.Cso.Slot, kMGPipeMaxSamplerViewSlots);
|
||||
RecordAt(MGPipeApplier().SamplerViewCsos, view.Cso.Slot, kMGPipeMaxSamplerViewSlots);
|
||||
if (recordAt == nullptr) {
|
||||
MGP_TRIP_WIRE_REPORT("MGPipe: " MGP_TRIP_WIRE_TAG("ProtocolCorruption")
|
||||
" create_sampler_view {slot=%u, gen=%u}: the slot is outside the record "
|
||||
@@ -3031,7 +3194,7 @@ namespace MobileGL::MG_Pipe {
|
||||
// arriving before - or without - the texture record is an ordering fact and not a
|
||||
// refusal. When the record is there this is the back-pointer that lets a sync reach a
|
||||
// texture's view without walking every view the applier holds.
|
||||
MGPipeResourceRecord* texture = FindIn(g_applier.TextureResources, view.Texture);
|
||||
MGPipeResourceRecord* texture = FindIn(MGPipeApplier().TextureResources, view.Texture);
|
||||
if (texture != nullptr) texture->ViewCso = view.Cso;
|
||||
}
|
||||
|
||||
@@ -3039,13 +3202,13 @@ namespace MobileGL::MG_Pipe {
|
||||
MOBILEGL_ASSERT(handle.Kind == static_cast<Uint32>(MGPipeKind::SamplerViewCso),
|
||||
"delete_sampler_view on kind %u", handle.Kind);
|
||||
MGPipeSamplerViewRecord* record =
|
||||
ResolveObject(g_applier.SamplerViewCsos, "delete_sampler_view", handle.Handle);
|
||||
ResolveObject(MGPipeApplier().SamplerViewCsos, "delete_sampler_view", handle.Handle);
|
||||
if (record == nullptr) return;
|
||||
|
||||
// The back-pointer goes first, while the record that names the texture still exists,
|
||||
// and only if that texture still names THIS view - a texture whose view has already
|
||||
// been re-minted must not have the new handle cleared out from under it.
|
||||
MGPipeResourceRecord* texture = FindIn(g_applier.TextureResources, record->View.Texture);
|
||||
MGPipeResourceRecord* texture = FindIn(MGPipeApplier().TextureResources, record->View.Texture);
|
||||
if (texture != nullptr && texture->ViewCso == handle.Handle) {
|
||||
texture->ViewCso = kMGPipeNullHandle;
|
||||
}
|
||||
@@ -3066,7 +3229,7 @@ namespace MobileGL::MG_Pipe {
|
||||
// READ-attachment case reaches no parameter push at all today. The record exists the
|
||||
// moment the parameters move, whether or not anything is bound.
|
||||
MGPipeResourceRecord* record =
|
||||
ResolveObject(g_applier.TextureResources, "set_texture_params", params.Res);
|
||||
ResolveObject(MGPipeApplier().TextureResources, "set_texture_params", params.Res);
|
||||
if (record == nullptr) return false;
|
||||
|
||||
// EVERY ITextureObject OWNS A SamplerObject, so the built-in sampler CSO is not
|
||||
@@ -3121,11 +3284,11 @@ namespace MobileGL::MG_Pipe {
|
||||
void MGPipeApplySetSamplerViews(const MGPSamplerViews& hdr, const MGPBoundView* tail) {
|
||||
if (NoP4aConsumer()) return;
|
||||
if (!ApplyUnitWindow("set_sampler_views", hdr.Start, hdr.Count, hdr.ContentHash, tail,
|
||||
g_applier.BoundSamplerViews, g_applier.SamplerViewStart,
|
||||
g_applier.SamplerViewCount)) {
|
||||
MGPipeApplier().BoundSamplerViews, MGPipeApplier().SamplerViewStart,
|
||||
MGPipeApplier().SamplerViewCount)) {
|
||||
return;
|
||||
}
|
||||
++g_applier.SamplerViewsSerial;
|
||||
++MGPipeApplier().SamplerViewsSerial;
|
||||
// P5c (rv): a texture bind is what the bind-generation shutter guarded.
|
||||
MGPipeApplierNoteTextureStateMoved();
|
||||
}
|
||||
@@ -3133,11 +3296,11 @@ namespace MobileGL::MG_Pipe {
|
||||
void MGPipeApplyBindSamplerStates(const MGPSamplerStates& hdr, const MGPipeHandle* tail) {
|
||||
if (NoP4aConsumer()) return;
|
||||
if (!ApplyUnitWindow("bind_sampler_states", hdr.Start, hdr.Count, hdr.ContentHash, tail,
|
||||
g_applier.BoundSamplerStates, g_applier.SamplerStateStart,
|
||||
g_applier.SamplerStateCount)) {
|
||||
MGPipeApplier().BoundSamplerStates, MGPipeApplier().SamplerStateStart,
|
||||
MGPipeApplier().SamplerStateCount)) {
|
||||
return;
|
||||
}
|
||||
++g_applier.SamplerStatesSerial;
|
||||
++MGPipeApplier().SamplerStatesSerial;
|
||||
// P5c (rv): a sampler bind or parameter change is what the shutters guarded.
|
||||
MGPipeApplierNoteTextureStateMoved();
|
||||
}
|
||||
@@ -3150,11 +3313,11 @@ namespace MobileGL::MG_Pipe {
|
||||
// formats on Adreno will accept is the backend's, not this applier's.
|
||||
if (NoP4aConsumer()) return;
|
||||
if (!ApplyUnitWindow("set_shader_images", hdr.Start, hdr.Count, hdr.ContentHash, tail,
|
||||
g_applier.BoundShaderImages, g_applier.ShaderImageStart,
|
||||
g_applier.ShaderImageCount)) {
|
||||
MGPipeApplier().BoundShaderImages, MGPipeApplier().ShaderImageStart,
|
||||
MGPipeApplier().ShaderImageCount)) {
|
||||
return;
|
||||
}
|
||||
++g_applier.ShaderImagesSerial;
|
||||
++MGPipeApplier().ShaderImagesSerial;
|
||||
// P5c (rv): an image bind moves the texture bind generation's guarded set too.
|
||||
MGPipeApplierNoteTextureStateMoved();
|
||||
}
|
||||
@@ -3211,18 +3374,18 @@ namespace MobileGL::MG_Pipe {
|
||||
// unit sets and set_vertex_buffers work: the record is "the last set as received", and
|
||||
// a binding at or above Count means "nothing bound" to every reader (the frontend
|
||||
// array's default says the same thing, which is what makes the two pictures agree).
|
||||
auto& destination = g_applier.BoundShaderBuffers[hdr.Class];
|
||||
auto& destination = MGPipeApplier().BoundShaderBuffers[hdr.Class];
|
||||
for (Uint32 i = 0; i < hdr.Count; ++i) destination[hdr.Start + i] = tail[i];
|
||||
g_applier.ShaderBufferStart[hdr.Class] = hdr.Start;
|
||||
g_applier.ShaderBufferCount[hdr.Class] = hdr.Count;
|
||||
MGPipeApplier().ShaderBufferStart[hdr.Class] = hdr.Start;
|
||||
MGPipeApplier().ShaderBufferCount[hdr.Class] = hdr.Count;
|
||||
for (Uint32 w = 0; w < kMGPipeShaderBufferWritableMaskWords; ++w) {
|
||||
g_applier.ShaderBufferWritableMask[hdr.Class][w] = hdr.WritableMask[w];
|
||||
MGPipeApplier().ShaderBufferWritableMask[hdr.Class][w] = hdr.WritableMask[w];
|
||||
}
|
||||
// ONE SERIAL FOR ALL THREE CLASSES, and it moves on EVERY applied record - a backend
|
||||
// memo that asks "have the binding points moved since I last bound them" must hear
|
||||
// about a uniform set exactly as it hears about a storage set, and splitting the serial
|
||||
// per class would make each of the four consumers pick which one to read.
|
||||
++g_applier.ShaderBuffersSerial;
|
||||
++MGPipeApplier().ShaderBuffersSerial;
|
||||
}
|
||||
|
||||
// P5e (pg) WRITES THE SECOND BODY. The three post-link mutable reflection fields -
|
||||
@@ -3501,14 +3664,14 @@ namespace MobileGL::MG_Pipe {
|
||||
// error; a DEAD handle leaves the previous binding untouched and is counted, which is
|
||||
// bind_render_state's precedent for the same question.
|
||||
if (MGPipeHandleIsNull(handle.Handle)) {
|
||||
g_applier.BoundShaderCso = kMGPipeNullHandle;
|
||||
++g_applier.ProgramBindingSerial;
|
||||
MGPipeApplier().BoundShaderCso = kMGPipeNullHandle;
|
||||
++MGPipeApplier().ProgramBindingSerial;
|
||||
return;
|
||||
}
|
||||
const MGPipeShaderCsoRecord* record = ResolveShaderCso("bind_shader_state", handle.Handle);
|
||||
if (record == nullptr) return;
|
||||
g_applier.BoundShaderCso = handle.Handle;
|
||||
++g_applier.ProgramBindingSerial;
|
||||
MGPipeApplier().BoundShaderCso = handle.Handle;
|
||||
++MGPipeApplier().ProgramBindingSerial;
|
||||
}
|
||||
|
||||
void MGPipeApplyDeleteShaderState(const MGPHandleOnly& handle) {
|
||||
@@ -3532,19 +3695,19 @@ namespace MobileGL::MG_Pipe {
|
||||
// next verb resolving a binding to a record this applier no longer has, which is the
|
||||
// refusal counter firing for a state the applier itself created.
|
||||
Bool cleared = false;
|
||||
if (g_applier.BoundShaderCso == handle.Handle) {
|
||||
g_applier.BoundShaderCso = kMGPipeNullHandle;
|
||||
if (MGPipeApplier().BoundShaderCso == handle.Handle) {
|
||||
MGPipeApplier().BoundShaderCso = kMGPipeNullHandle;
|
||||
cleared = true;
|
||||
}
|
||||
if (g_applier.DrawProgram == handle.Handle) {
|
||||
g_applier.DrawProgram = kMGPipeNullHandle;
|
||||
if (MGPipeApplier().DrawProgram == handle.Handle) {
|
||||
MGPipeApplier().DrawProgram = kMGPipeNullHandle;
|
||||
cleared = true;
|
||||
}
|
||||
if (g_applier.DispatchProgram == handle.Handle) {
|
||||
g_applier.DispatchProgram = kMGPipeNullHandle;
|
||||
if (MGPipeApplier().DispatchProgram == handle.Handle) {
|
||||
MGPipeApplier().DispatchProgram = kMGPipeNullHandle;
|
||||
cleared = true;
|
||||
}
|
||||
if (cleared) ++g_applier.ProgramBindingSerial;
|
||||
if (cleared) ++MGPipeApplier().ProgramBindingSerial;
|
||||
}
|
||||
|
||||
// TWO CALLS AND NOT ONE, because the frontend has two joins and two PipeInputs slots: a
|
||||
@@ -3555,14 +3718,14 @@ namespace MobileGL::MG_Pipe {
|
||||
"set_draw_program on kind %u", handle.Kind);
|
||||
if (NoP4aConsumer()) return; // P4a's belt, for MGPipeApplyBindShaderState's reason.
|
||||
if (MGPipeHandleIsNull(handle.Handle)) {
|
||||
g_applier.DrawProgram = kMGPipeNullHandle;
|
||||
++g_applier.ProgramBindingSerial;
|
||||
MGPipeApplier().DrawProgram = kMGPipeNullHandle;
|
||||
++MGPipeApplier().ProgramBindingSerial;
|
||||
return;
|
||||
}
|
||||
const MGPipeShaderCsoRecord* record = ResolveShaderCso("set_draw_program", handle.Handle);
|
||||
if (record == nullptr) return;
|
||||
g_applier.DrawProgram = handle.Handle;
|
||||
++g_applier.ProgramBindingSerial;
|
||||
MGPipeApplier().DrawProgram = handle.Handle;
|
||||
++MGPipeApplier().ProgramBindingSerial;
|
||||
}
|
||||
|
||||
void MGPipeApplySetDispatchProgram(const MGPHandleOnly& handle) {
|
||||
@@ -3570,14 +3733,14 @@ namespace MobileGL::MG_Pipe {
|
||||
"set_dispatch_program on kind %u", handle.Kind);
|
||||
if (NoP4aConsumer()) return; // P4a's belt, for MGPipeApplyBindShaderState's reason.
|
||||
if (MGPipeHandleIsNull(handle.Handle)) {
|
||||
g_applier.DispatchProgram = kMGPipeNullHandle;
|
||||
++g_applier.ProgramBindingSerial;
|
||||
MGPipeApplier().DispatchProgram = kMGPipeNullHandle;
|
||||
++MGPipeApplier().ProgramBindingSerial;
|
||||
return;
|
||||
}
|
||||
const MGPipeShaderCsoRecord* record = ResolveShaderCso("set_dispatch_program", handle.Handle);
|
||||
if (record == nullptr) return;
|
||||
g_applier.DispatchProgram = handle.Handle;
|
||||
++g_applier.ProgramBindingSerial;
|
||||
MGPipeApplier().DispatchProgram = handle.Handle;
|
||||
++MGPipeApplier().ProgramBindingSerial;
|
||||
}
|
||||
|
||||
void MGPipeApplySetGlobalConstants(const MGPGlobalConstants& record, const void* bytes) {
|
||||
|
||||
+186
-65
@@ -513,7 +513,88 @@ namespace MobileGL::MG_Pipe {
|
||||
MGPFramebufferState State{};
|
||||
};
|
||||
|
||||
struct MGPipeApplierState {
|
||||
// =====================================================================================
|
||||
// P14 S5: THE SHARE-GROUP HALF OF THE APPLIER'S STATE.
|
||||
// =====================================================================================
|
||||
//
|
||||
// THE TWO HALVES HAVE DIFFERENT LIVES, and until this slice they were one struct with one
|
||||
// owner (the process), which is what made a second served context either share working state
|
||||
// it must not share or lose object records it must not lose. They are two structs now because
|
||||
// they are two OWNERS:
|
||||
//
|
||||
// MGPipeObjectRecords a GL object lives in a SHARE GROUP, so these records are keyed by
|
||||
// {session, share group}: two contexts of one group see one set, two
|
||||
// NON-shared contexts of one session see two sets - which is the whole
|
||||
// reason the frontend gives each context its own name space
|
||||
// (MG_State/GLState/ShareGroupState). A GL object survives a
|
||||
// make-current and its record is the only thing the backend has left to
|
||||
// read that object's storage extent and mutation serial out of (D-A4
|
||||
// re-keys IsBufferDrawClean onto exactly those two); dropping them at a
|
||||
// make-current made every subsequent glBufferSubData on a pre-existing
|
||||
// buffer resolve to nothing.
|
||||
//
|
||||
// MGPipeWorkingState what the next draw fetches with - bindings, current program, the unit
|
||||
// windows, the CSO store, the serials. Keyed by {session, context}: a
|
||||
// returning context may not inherit another's bindings, and two
|
||||
// contexts of one share group may not overwrite each other's.
|
||||
//
|
||||
// THEY ARE CLEARED BY DIFFERENT EVENTS. A record here is cleared by the object's OWN death
|
||||
// signal - resource_destroy, delete_vertex_elements, which is what D-L makes the buffer's death
|
||||
// crossing - and by the share group's own teardown (MGPipeApplierReleaseGroupRecords) when its
|
||||
// last context goes away. MGPipeApplierReset does NOT touch this struct; MGPipeApplierState's
|
||||
// working half is what a make-current resets.
|
||||
struct MGPipeObjectRecords {
|
||||
// ---- object records: indexed by MGPipeHandle::Slot of kind Buffer /
|
||||
// VertexElementsCso, and NOT part of the working state. They are cleared by the object's
|
||||
// OWN death signal and by the group's teardown. Nothing else.
|
||||
Vector<MGPipeResourceRecord> Resources;
|
||||
Vector<MGPipeVertexElementsRecord> VertexElementsCsos;
|
||||
|
||||
// ---- P4a's object records. FIVE MORE TABLES, and the two resource ones are separate
|
||||
// Vectors rather than more rows of `Resources` above because the slot space is PER
|
||||
// KIND: a Buffer, a Texture and a Renderbuffer can all hold slot 7 at once, so a
|
||||
// single slot-indexed table would alias three different objects onto one record. The
|
||||
// record TYPE is shared - one discriminated descriptor for buffers, every texture
|
||||
// target and renderbuffers - and the bound is shared; only the table is per kind.
|
||||
//
|
||||
// Like the two above they are share-group state: MGPipeApplierReset does not touch
|
||||
// them, and only the object's own death signal and the group's teardown clear them.
|
||||
Vector<MGPipeResourceRecord> TextureResources;
|
||||
Vector<MGPipeResourceRecord> RenderbufferResources;
|
||||
Vector<MGPipeSamplerCsoRecord> SamplerCsos;
|
||||
Vector<MGPipeSamplerViewRecord> SamplerViewCsos;
|
||||
Vector<MGPipeShaderCsoRecord> ShaderCsos;
|
||||
// The ShaderCso COMPOSITE band's records, indexed by (slot - the band's base), for the
|
||||
// same reason MGPipeSlotAllocator keeps the band in a table of its own: the band
|
||||
// starts at 983040, so one program-pipeline composite in the slot-indexed vector above
|
||||
// would grow it to ~983k records of ~240 bytes each. THE SERVER STILL NEVER LEARNS IT
|
||||
// IS A COMPOSITE - the split is an indexing detail on this side of the wire, the
|
||||
// handle is an ordinary ShaderCso handle, and create/bind/delete_shader_state name it
|
||||
// exactly as they name any other program.
|
||||
Vector<MGPipeShaderCsoRecord> CompositeShaderCsos;
|
||||
// AND THE SIXTH, WHICH IS THE ONE ID-19 ADDED. Keyed by the FRAMEBUFFER HANDLE's slot,
|
||||
// for the reason MGPipeFramebufferRecord states: the two bound-target records the phase
|
||||
// started with could not describe a framebuffer that is bound to neither binding, and
|
||||
// the five DSA entry points (BlitNamedFramebuffer, the four ClearNamedFramebuffer*) hand
|
||||
// Espryt exactly that.
|
||||
//
|
||||
// IT IS AN OBJECT TABLE AND IT LIVES WHERE THE OTHER OBJECT TABLES LIVE, which is also
|
||||
// its make-current rule: MGPipeApplierReset does NOT clear it. An FBO is not shared
|
||||
// between contexts, but its record is addressed by a slot out of one global allocator,
|
||||
// so nothing aliases across a switch - and dropping the table would leave a
|
||||
// DSA-only framebuffer with no record and no event that would ever re-emit one (the
|
||||
// client's suppressor invalidation re-emits the two BOUND records and nothing else).
|
||||
//
|
||||
// P14 S5 keys it by SHARE GROUP like its siblings, which is safe for the reason just
|
||||
// given: the slot space is global, so a group's table can only ever answer for handles
|
||||
// its own contexts minted, and a shared group holding both contexts' records is a wider
|
||||
// table rather than an aliasing one.
|
||||
Vector<MGPipeFramebufferRecord> FramebufferRecords;
|
||||
};
|
||||
|
||||
// The per-context half. Everything here is cleared by MGPipeApplierReset, EXCEPT the serials,
|
||||
// which only ever advance (see there).
|
||||
struct MGPipeWorkingState {
|
||||
// Indexed by slot; slot 0 is the reserved null handle and is never live
|
||||
// (MGPipeHandles.h kMGPipeFirstAllocatableSlot).
|
||||
Vector<MGPipeRenderStateCsoRecord> RenderStateCsos;
|
||||
@@ -553,69 +634,6 @@ namespace MobileGL::MG_Pipe {
|
||||
Uint32 PatchCarrierComparisons = 0; // cumulative, armed set_patch_state calls only
|
||||
Uint32 PatchCarrierDivergences = 0; // cumulative
|
||||
|
||||
// ---- P3a (D-G4). ----
|
||||
//
|
||||
// THE TWO HALVES BELOW HAVE DIFFERENT LIVES, and MGPipeApplierReset is where the
|
||||
// difference is spent: the OBJECT RECORDS describe GL objects and outlive a
|
||||
// make-current; the WORKING STATE describes what the next draw fetches with and does
|
||||
// not. Reading the whole block as "per context" is what dropped a shared buffer's
|
||||
// record at every context switch and made the write that followed it disappear.
|
||||
|
||||
// ---- object records: indexed by MGPipeHandle::Slot of kind Buffer /
|
||||
// VertexElementsCso, and NOT part of the working state.
|
||||
//
|
||||
// A GL object lives in a SHARE GROUP, not in a context: a buffer created before a
|
||||
// make-current is the same buffer, with the same storage, after it, and its record is
|
||||
// the only thing the backend has left to read that storage's extent and mutation
|
||||
// serial out of (D-A4 re-keys IsBufferDrawClean onto exactly those two). Dropping the
|
||||
// records at a make-current would therefore make every subsequent glBufferSubData on a
|
||||
// pre-existing buffer resolve to nothing and be refused - a lost write, in a build
|
||||
// where the refusal's assertion has compiled out.
|
||||
//
|
||||
// They are cleared by the object's OWN death signal - resource_destroy,
|
||||
// delete_vertex_elements, which is what D-L makes the buffer's death crossing - and by
|
||||
// MGPipeApplierReleaseObjectRecords when the served context and its applier go away.
|
||||
// Nothing else.
|
||||
Vector<MGPipeResourceRecord> Resources;
|
||||
Vector<MGPipeVertexElementsRecord> VertexElementsCsos;
|
||||
|
||||
// ---- P4a's object records. FIVE MORE TABLES, and the two resource ones are separate
|
||||
// Vectors rather than more rows of `Resources` above because the slot space is PER
|
||||
// KIND: a Buffer, a Texture and a Renderbuffer can all hold slot 7 at once, so a
|
||||
// single slot-indexed table would alias three different objects onto one record. The
|
||||
// record TYPE is shared - one discriminated descriptor for buffers, every texture
|
||||
// target and renderbuffers - and the bound is shared; only the table is per kind.
|
||||
//
|
||||
// Like the two above they are share-group state: MGPipeApplierReset does not touch
|
||||
// them, and only the object's own death signal and MGPipeApplierReleaseObjectRecords
|
||||
// clear them.
|
||||
Vector<MGPipeResourceRecord> TextureResources;
|
||||
Vector<MGPipeResourceRecord> RenderbufferResources;
|
||||
Vector<MGPipeSamplerCsoRecord> SamplerCsos;
|
||||
Vector<MGPipeSamplerViewRecord> SamplerViewCsos;
|
||||
Vector<MGPipeShaderCsoRecord> ShaderCsos;
|
||||
// The ShaderCso COMPOSITE band's records, indexed by (slot - the band's base), for the
|
||||
// same reason MGPipeSlotAllocator keeps the band in a table of its own: the band
|
||||
// starts at 983040, so one program-pipeline composite in the slot-indexed vector above
|
||||
// would grow it to ~983k records of ~240 bytes each. THE SERVER STILL NEVER LEARNS IT
|
||||
// IS A COMPOSITE - the split is an indexing detail on this side of the wire, the
|
||||
// handle is an ordinary ShaderCso handle, and create/bind/delete_shader_state name it
|
||||
// exactly as they name any other program.
|
||||
Vector<MGPipeShaderCsoRecord> CompositeShaderCsos;
|
||||
// AND THE SIXTH, WHICH IS THE ONE ID-19 ADDED. Keyed by the FRAMEBUFFER HANDLE's slot,
|
||||
// for the reason MGPipeFramebufferRecord states: the two bound-target records the phase
|
||||
// started with could not describe a framebuffer that is bound to neither binding, and
|
||||
// the five DSA entry points (BlitNamedFramebuffer, the four ClearNamedFramebuffer*) hand
|
||||
// Espryt exactly that.
|
||||
//
|
||||
// IT IS AN OBJECT TABLE AND IT LIVES WHERE THE OTHER OBJECT TABLES LIVE, which is also
|
||||
// its make-current rule: MGPipeApplierReset does NOT clear it. An FBO is not shared
|
||||
// between contexts, but its record is addressed by a slot out of one global allocator,
|
||||
// so nothing aliases across a switch - and dropping the table would leave a
|
||||
// DSA-only framebuffer with no record and no event that would ever re-emit one (the
|
||||
// client's suppressor invalidation re-emits the two BOUND records and nothing else).
|
||||
Vector<MGPipeFramebufferRecord> FramebufferRecords;
|
||||
|
||||
// Every call this applier REFUSED because it named a record this applier does not
|
||||
// have: an unknown slot, a slot that is not live, or a generation that has moved on
|
||||
// under it. The refusal is a defined no-op - nothing stored, nothing dispatched, no
|
||||
@@ -911,6 +929,53 @@ namespace MobileGL::MG_Pipe {
|
||||
}
|
||||
#endif
|
||||
|
||||
};
|
||||
|
||||
// =====================================================================================
|
||||
// P14 S5: ONE CONTEXT'S APPLIER = ITS OWN WORKING STATE + ITS SHARE GROUP'S RECORDS.
|
||||
// =====================================================================================
|
||||
//
|
||||
// THE INHERITANCE IS THE POINT AND NOT A SHORTCUT: everything the backend spells as
|
||||
// `MGPipeApplier().X` for a WORKING field keeps working unchanged (there are ~380 such reads
|
||||
// in MG_Backend), and every read of an OBJECT record moves to `MGPipeApplier().Objects.X` -
|
||||
// which is what makes the two lifetimes visible at exactly the sites where confusing them
|
||||
// would be a defect. The reference is to a MGPipeObjectRecords that OUTLIVES this object by
|
||||
// construction: the registry owns the group's records and this context's applier together,
|
||||
// and drops them in that order.
|
||||
//
|
||||
// A context that started its own share group still has one - a group of one - so every
|
||||
// applier has somewhere for its objects to live and there is no "no group" case.
|
||||
struct MGPipeApplierState : MGPipeWorkingState {
|
||||
// The share group this context's objects live in.
|
||||
MGPipeObjectRecords& Objects;
|
||||
|
||||
// ---- THE OBJECT TABLES, UNDER THE NAMES EVERY CALLER ALREADY SPELLS. --------------
|
||||
//
|
||||
// These nine are the group's tables, not copies of them: ~200 call sites in
|
||||
// MG_Backend, MG_IntegrationTest and MG_Test read `st.Resources`, `state.TextureResources`
|
||||
// and their siblings, and the name they use has ALWAYS meant "the share group's record
|
||||
// for this object". Binding them here keeps every one of those reads correct by
|
||||
// construction - through the group its own context belongs to - instead of turning a
|
||||
// keying change into a renaming change. `Objects.X` and `X` therefore name the same
|
||||
// vector; this file spells the group half explicitly where it CREATES the two halves,
|
||||
// the backend keeps the name it has.
|
||||
Vector<MGPipeResourceRecord>& Resources;
|
||||
Vector<MGPipeVertexElementsRecord>& VertexElementsCsos;
|
||||
Vector<MGPipeResourceRecord>& TextureResources;
|
||||
Vector<MGPipeResourceRecord>& RenderbufferResources;
|
||||
Vector<MGPipeSamplerCsoRecord>& SamplerCsos;
|
||||
Vector<MGPipeSamplerViewRecord>& SamplerViewCsos;
|
||||
Vector<MGPipeShaderCsoRecord>& ShaderCsos;
|
||||
Vector<MGPipeShaderCsoRecord>& CompositeShaderCsos;
|
||||
Vector<MGPipeFramebufferRecord>& FramebufferRecords;
|
||||
|
||||
explicit MGPipeApplierState(MGPipeObjectRecords& objects)
|
||||
: Objects(objects), Resources(objects.Resources), VertexElementsCsos(objects.VertexElementsCsos),
|
||||
TextureResources(objects.TextureResources), RenderbufferResources(objects.RenderbufferResources),
|
||||
SamplerCsos(objects.SamplerCsos), SamplerViewCsos(objects.SamplerViewCsos),
|
||||
ShaderCsos(objects.ShaderCsos), CompositeShaderCsos(objects.CompositeShaderCsos),
|
||||
FramebufferRecords(objects.FramebufferRecords) {}
|
||||
|
||||
// ---- THE THREE FRAMEBUFFER ACCESSORS (ID-19(b)/(d)). They are functions rather than
|
||||
// members because the storage moved under them and their callers must not have to know
|
||||
// it did: `DrawFramebuffer()` / `ReadFramebuffer()` answer the question the two members
|
||||
@@ -932,9 +997,65 @@ namespace MobileGL::MG_Pipe {
|
||||
const MGPFramebufferState* ReadFramebuffer() const;
|
||||
};
|
||||
|
||||
// The monolith's single applier. Under split there is one per served context.
|
||||
// The calling thread's applier. On a thread that belongs to a served session this is that
|
||||
// session's CURRENT CONTEXT's working state bound to its share group's object records; on
|
||||
// every other thread - the client process, the in-process client+server shape, a unit case,
|
||||
// the whole monolith - it is the process-wide applier, which is what it has always been and
|
||||
// is byte-for-byte the old behaviour.
|
||||
MGPipeApplierState& MGPipeApplier();
|
||||
|
||||
// =====================================================================================
|
||||
// P14 S5 (docs/Disaggregated/design/11-state-ownership.md): WHOSE APPLIER IS IT?
|
||||
// =====================================================================================
|
||||
//
|
||||
// THE SAME SHAPE AS P14 S2's gPipeInputs RESOLVER AND S4's NATIVE TUPLE KEY, one level down:
|
||||
// a process-wide hook the server's session registry installs ONCE, which answers for the
|
||||
// CALLING thread. Nothing in MG_Backend or MG_Impl names a session, and no call site moved.
|
||||
//
|
||||
// THE KEY IS TWO PAIRS, because the two halves have two owners:
|
||||
//
|
||||
// {SessionKey, ContextToken} the WORKING state, one per served context;
|
||||
// {SessionKey, ShareGroupKey} the OBJECT records, one per share group within the session.
|
||||
//
|
||||
// A SHARE GROUP DOES NOT CROSS A SESSION, and this is not a limitation: an EGL share group
|
||||
// is a property of one client's connection (EGL 1.5 3.7.1 - contexts of one share group must
|
||||
// belong to one display), and the two sessions are two connections. Cross-session sharing is
|
||||
// an explicit non-goal of the phase, so keying the first by session is the whole of the rule.
|
||||
//
|
||||
// REGISTRATION, NOT INFERENCE. The session layer registers a context the moment the
|
||||
// CreateContext control frame reaches the apply thread (ServerSession::CreateContext) and
|
||||
// unregisters it at DestroyContext, so the resolver above stays a two-word read of state the
|
||||
// session already keeps (its current token) and never has to reach into the session's map
|
||||
// from a thread that does not own it. A context that was never registered resolves to its
|
||||
// session's "no context" applier, which is the same object the session's bring-up reads.
|
||||
struct MGPipeApplierKey {
|
||||
Uint64 SessionKey = 0;
|
||||
Uint64 ContextToken = 0;
|
||||
};
|
||||
// Answers false for "this thread is not a session's" (the process-wide applier). Installed by
|
||||
// the session registry; null in every process that serves no session.
|
||||
using MGPipeApplierKeyResolver = Bool (*)(MGPipeApplierKey* outKey);
|
||||
void MGPipeSetApplierKeyResolver(MGPipeApplierKeyResolver resolver);
|
||||
|
||||
// Mints (or finds) the working state for {session, context} and the object records of the
|
||||
// share group it belongs to. `shareGroupToken` is the frontend's own share-group identity
|
||||
// (EGLState::CreateContext mints it, a sharing context inherits its parent's); 0 means this
|
||||
// context started its own group, and is keyed by the context token in a namespace of its own
|
||||
// so it cannot alias a group that happens to carry that number.
|
||||
void MGPipeApplierRegisterContext(Uint64 sessionKey, Uint64 contextToken, Uint64 shareGroupToken);
|
||||
// Drops {session, context}'s working state, and its share group's object records when the
|
||||
// last context of that group has gone (MGPipeApplierReleaseObjectRecords' scope, per group
|
||||
// instead of per process).
|
||||
void MGPipeApplierUnregisterContext(Uint64 sessionKey, Uint64 contextToken);
|
||||
// Every context of a served session, at session teardown.
|
||||
void MGPipeApplierReleaseSession(Uint64 sessionKey);
|
||||
|
||||
// The observables that make the keying testable without reading a private map: how many
|
||||
// groups one context's session holds, and how many object records the group the CALLING
|
||||
// thread is in holds. Both are the numbers a case asserts on to tell "isolated" from
|
||||
// "shared" apart from the behaviour they exist to explain.
|
||||
Uint64 MGPipeApplierShareGroupCountForTesting(Uint64 sessionKey);
|
||||
|
||||
// ---------------------------------------------------------------------------------
|
||||
// P5e: THE BARRIERED PREDICATE (MG_Remote/CONTRACT-P5E.md §2.1, ruling 3)
|
||||
// ---------------------------------------------------------------------------------
|
||||
|
||||
@@ -72,8 +72,9 @@
|
||||
// that the expansion, the two generated tables and this number agree.
|
||||
//
|
||||
// class entries group (as the plan tabulates it)
|
||||
// kScreen 12 screen: caps 1 + resource 3 + persistent map 2 + fence 4, plus the
|
||||
// appended server-side fence wait 1 and P5c's applier_reset 1
|
||||
// kScreen 13 screen: caps 1 + resource 3 + persistent map 2 + fence 4, plus the
|
||||
// appended server-side fence wait 1 and P5c's applier_reset 1 and
|
||||
// P14 S1's bind_context 1
|
||||
// kCtxQuery 8 query object namespace 6, plus the appended timestamp pair 2
|
||||
// kCtxCso 13 CSO create/bind/delete
|
||||
// kCtxState 19 16 of the 18 set_* calls + the temporary set_residual_value_state
|
||||
@@ -84,7 +85,7 @@
|
||||
// P5b-appended verbs (bind_shader_image, patch_parameter,
|
||||
// bind_stream_output, set_storage_block_binding,
|
||||
// copy_framebuffer_to_texture - MG_Remote/CONTRACT-P5B.md)
|
||||
// total 80
|
||||
// total 81
|
||||
//
|
||||
// Reconciliation with the plan's headline numbers (section 4.4 / appendix A), because they
|
||||
// do not add up to a set of UNIQUE records and this file has to hold unique records:
|
||||
@@ -145,9 +146,16 @@
|
||||
// read_pixels_to_buffer and get_texture_image_to_buffer, the pack-buffer halves of the two
|
||||
// readbacks, answered by nothing (ID-57's fire-and-forget). Like P5b's five they reach
|
||||
// WireVerbSink only and have no monolith producer. 83 unique records.
|
||||
// - P14 S1 (docs/Disaggregated/design/11-state-ownership.md) appended ONE more (opcode 84):
|
||||
// bind_context, the in-band record that carries the client's CURRENT context token. It has
|
||||
// the applier_reset shape - a kScreen control record, no MGPipeApply* entry point, no
|
||||
// monolith producer - because what it moves is session attribution, not context state. The
|
||||
// design's per-record ContextSlot was NOT taken here: the token is announced at the edge
|
||||
// (a context change) instead of stamped on every verb, which costs one record per
|
||||
// make-current and leaves the 71 context-family payloads untouched. 84 unique records.
|
||||
// ---------------------------------------------------------------------------------------
|
||||
|
||||
#define MGP_CALL_LIST_DOCUMENTED_COUNT 83
|
||||
#define MGP_CALL_LIST_DOCUMENTED_COUNT 84
|
||||
|
||||
// clang-format off
|
||||
#define MGP_CALL_LIST(X) \
|
||||
@@ -355,7 +363,18 @@
|
||||
/* ---- has an MGPipeApply* entry point or a monolith producer: monolith reads into its ---- */ \
|
||||
/* ---- driver PBO inside the backend's own ReadPixels, as before (G1). ---- */ \
|
||||
X(ReadPixelsToBuffer, MGPReadbackToBuffer, kCtxVerb, kNone, kWaitNone) \
|
||||
X(GetTextureImageToBuffer, MGPReadbackToBuffer, kCtxObject, kNone, kWaitNone)
|
||||
X(GetTextureImageToBuffer, MGPReadbackToBuffer, kCtxObject, kNone, kWaitNone) \
|
||||
/* ---- APPENDED BY P14 S1 (docs/Disaggregated/design/11-state-ownership.md), opcode 84: ---- */ \
|
||||
/* ---- the in-band context binding. THE WHOLE RECORD IS ONE Uint64: the client's current ---- */ \
|
||||
/* ---- context token, 0 meaning "no context" (a release). It is emitted at the make-current ---- */ \
|
||||
/* ---- edge, ahead of the block's client-side resets and ahead of applier_reset, so the ---- */ \
|
||||
/* ---- server attributes every record that follows to the context that produced it - the ---- */ \
|
||||
/* ---- multi-context shape the final design reaches without stamping a slot on all 71 ---- */ \
|
||||
/* ---- context-family rows. kScreen like applier_reset: it is a whole-session edge, not a ---- */ \
|
||||
/* ---- context-family verb, and it has no MGPipeApply* entry point and no monolith producer. ---- */ \
|
||||
/* ---- kWaitNone: the apply reads no client memory and the record's placement in the ring ---- */ \
|
||||
/* ---- is the whole of its ordering. ---- */ \
|
||||
X(BindContext, MGPBindContext, kScreen, kNone, kWaitNone)
|
||||
// clang-format on
|
||||
|
||||
// Explicitly NOT migrated (plan 4.4.6 / appendix A "explicit deletions"):
|
||||
|
||||
@@ -297,6 +297,10 @@
|
||||
#define MGP_FIELDS_MGPApplierReset(F) \
|
||||
F(ContextSerial)
|
||||
|
||||
// P14 S1: bind_context's POD, one row for its one member.
|
||||
#define MGP_FIELDS_MGPBindContext(F) \
|
||||
F(ClientContextToken)
|
||||
|
||||
// P5c rv (CONTRACT-P5C.md §5.3): set_context_values' POD, one row per member. The 15-entry
|
||||
// array is one field, exactly as MGPFramebufferState's Color[8] is one.
|
||||
#define MGP_FIELDS_MGPContextValues(F) \
|
||||
@@ -423,7 +427,7 @@
|
||||
P(MGPSurfaceInfo) \
|
||||
P(MGPImageBind) P(MGPPatchParameter) P(MGPStreamOutputBind) P(MGPStorageBlockBinding) \
|
||||
P(MGPCopyFromFramebuffer) \
|
||||
P(MGPApplierReset) P(MGPContextValues) \
|
||||
P(MGPApplierReset) P(MGPBindContext) P(MGPContextValues) \
|
||||
P(MGPProgramBindings) P(MGPProgramSamplerUnit) P(MGPProgramStorageOverride) \
|
||||
P(RenderStateParameters) P(PixelStoreParameters) P(SamplerParameters) P(PerBufferBlendState) \
|
||||
P(StencilFaceState) \
|
||||
|
||||
@@ -341,12 +341,6 @@ namespace MobileGL::MG_Pipe {
|
||||
void MGPipeNoteHandlePublished(MGPipeKind kind, MGPipeHandle handle);
|
||||
Bool MGPipeHandleIsPublished(MGPipeKind kind, MGPipeHandle handle);
|
||||
void MGPipeNoteHandleUnpublished(MGPipeKind kind, MGPipeHandle handle);
|
||||
// THE SESSION IS GONE, AND EVERYTHING IT HELD WITH IT. Called once the split roles are shut
|
||||
// down: every object the server twinned died with the session, so nothing is published any
|
||||
// more - and the frontend objects that die after it (MobileGL::Destroy resets the GL context
|
||||
// after ShutdownSplitRoles, by design) must not route a delete for a twin that no longer
|
||||
// exists to whichever applier is installed now, which asserts on the unknown handle.
|
||||
void MGPipeForgetAllPublications();
|
||||
|
||||
// ---- the four mints (pure allocator work, no family knowledge) ----
|
||||
//
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
// Regenerate with `python3 scripts/gen_pipe.py`; CI runs it and diffs the result.
|
||||
// This file is included from MG_Pipe/MGPipe.h inside namespace MobileGL::MG_Pipe.
|
||||
|
||||
// share group: 12 calls. A null entry means the backend does not implement this
|
||||
// share group: 13 calls. A null entry means the backend does not implement this
|
||||
// call and the frontend keeps its own path (plan B section 4.1).
|
||||
struct MGPipeScreen {
|
||||
void (*GetCaps)(const MGPCaps* payload, const void* blobBytes, Uint64 blobByteCount, MGPReplySlot* reply);
|
||||
@@ -27,6 +27,7 @@ struct MGPipeScreen {
|
||||
void (*FenceDestroy)(const MGPHandleOnly* payload);
|
||||
void (*FenceWaitServer)(const MGPFenceWait* payload);
|
||||
void (*ApplierReset)(const MGPApplierReset* payload);
|
||||
void (*BindContext)(const MGPBindContext* payload);
|
||||
};
|
||||
|
||||
// context: 71 calls. A null entry means the backend does not implement this
|
||||
@@ -105,9 +106,9 @@ struct MGPipeContext {
|
||||
void (*GetTextureImageToBuffer)(const MGPReadbackToBuffer* payload);
|
||||
};
|
||||
|
||||
inline constexpr SizeT kMGPipeScreenCallCount = 12;
|
||||
inline constexpr SizeT kMGPipeScreenCallCount = 13;
|
||||
inline constexpr SizeT kMGPipeContextCallCount = 71;
|
||||
inline constexpr SizeT kMGPipeCallCount = 83;
|
||||
inline constexpr SizeT kMGPipeCallCount = 84;
|
||||
|
||||
// A table that is not exactly its call count of function pointers has grown a
|
||||
// member that no generator knows about.
|
||||
|
||||
@@ -348,3 +348,7 @@ inline void MGP_ReadPixelsToBuffer(const MGPReadbackToBuffer* payload) {
|
||||
inline void MGP_GetTextureImageToBuffer(const MGPReadbackToBuffer* payload) {
|
||||
gMGPipeContext.GetTextureImageToBuffer(payload);
|
||||
}
|
||||
|
||||
inline void MGP_BindContext(const MGPBindContext* payload) {
|
||||
gMGPipeScreen.BindContext(payload);
|
||||
}
|
||||
|
||||
@@ -114,6 +114,7 @@ inline Bool MGPipeVerify(const MGPStreamOutputBind& a, const MGPStreamOutputBind
|
||||
inline Bool MGPipeVerify(const MGPStorageBlockBinding& a, const MGPStorageBlockBinding& b, const char** outField);
|
||||
inline Bool MGPipeVerify(const MGPCopyFromFramebuffer& a, const MGPCopyFromFramebuffer& b, const char** outField);
|
||||
inline Bool MGPipeVerify(const MGPApplierReset& a, const MGPApplierReset& b, const char** outField);
|
||||
inline Bool MGPipeVerify(const MGPBindContext& a, const MGPBindContext& b, const char** outField);
|
||||
inline Bool MGPipeVerify(const MGPContextValues& a, const MGPContextValues& b, const char** outField);
|
||||
inline Bool MGPipeVerify(const MGPProgramBindings& a, const MGPProgramBindings& b, const char** outField);
|
||||
inline Bool MGPipeVerify(const MGPProgramSamplerUnit& a, const MGPProgramSamplerUnit& b, const char** outField);
|
||||
@@ -269,6 +270,8 @@ struct MGPipeHasFieldVerifier<MGPCopyFromFramebuffer> : std::true_type {};
|
||||
template <>
|
||||
struct MGPipeHasFieldVerifier<MGPApplierReset> : std::true_type {};
|
||||
template <>
|
||||
struct MGPipeHasFieldVerifier<MGPBindContext> : std::true_type {};
|
||||
template <>
|
||||
struct MGPipeHasFieldVerifier<MGPContextValues> : std::true_type {};
|
||||
template <>
|
||||
struct MGPipeHasFieldVerifier<MGPProgramBindings> : std::true_type {};
|
||||
@@ -690,6 +693,11 @@ inline Bool MGPipeVerify(const MGPApplierReset& a, const MGPApplierReset& b, con
|
||||
return true;
|
||||
}
|
||||
|
||||
inline Bool MGPipeVerify(const MGPBindContext& a, const MGPBindContext& b, const char** outField) {
|
||||
MGP_FIELDS_MGPBindContext(MGP_VERIFY_FIELD)
|
||||
return true;
|
||||
}
|
||||
|
||||
inline Bool MGPipeVerify(const MGPContextValues& a, const MGPContextValues& b, const char** outField) {
|
||||
MGP_FIELDS_MGPContextValues(MGP_VERIFY_FIELD)
|
||||
return true;
|
||||
@@ -757,4 +765,4 @@ inline Bool MGPipeVerify(const MGPVertexBindingPointWire& a, const MGPVertexBind
|
||||
|
||||
#undef MGP_VERIFY_FIELD
|
||||
|
||||
inline constexpr SizeT kMGPipeVerifiedPayloadCount = 83;
|
||||
inline constexpr SizeT kMGPipeVerifiedPayloadCount = 84;
|
||||
|
||||
@@ -153,7 +153,8 @@ enum class MGPWireOp : Uint16 {
|
||||
DeleteStreamOutput = 81,
|
||||
ReadPixelsToBuffer = 82,
|
||||
GetTextureImageToBuffer = 83,
|
||||
kOpCount = 84,
|
||||
BindContext = 84,
|
||||
kOpCount = 85,
|
||||
};
|
||||
|
||||
// THE FLAGS, EXPORTED ONCE, INDEXED BY OPCODE (P5 R-13.4). MGPWireRecHeader::Flags is
|
||||
@@ -258,6 +259,7 @@ inline constexpr Uint32 kMGPipeCallFlags[static_cast<SizeT>(MGPWireOp::kOpCount)
|
||||
/* 81 DeleteStreamOutput */ static_cast<Uint32>(kNone),
|
||||
/* 82 ReadPixelsToBuffer */ static_cast<Uint32>(kNone),
|
||||
/* 83 GetTextureImageToBuffer */ static_cast<Uint32>(kNone),
|
||||
/* 84 BindContext */ static_cast<Uint32>(kNone),
|
||||
};
|
||||
static_assert(sizeof(kMGPipeCallFlags) / sizeof(kMGPipeCallFlags[0]) ==
|
||||
static_cast<SizeT>(MGPWireOp::kOpCount),
|
||||
@@ -361,6 +363,7 @@ inline constexpr Uint8 kMGPipeCallClasses[static_cast<SizeT>(MGPWireOp::kOpCount
|
||||
/* 81 DeleteStreamOutput */ static_cast<Uint8>(kCtxVerb),
|
||||
/* 82 ReadPixelsToBuffer */ static_cast<Uint8>(kCtxVerb),
|
||||
/* 83 GetTextureImageToBuffer */ static_cast<Uint8>(kCtxObject),
|
||||
/* 84 BindContext */ static_cast<Uint8>(kScreen),
|
||||
};
|
||||
static_assert(sizeof(kMGPipeCallClasses) / sizeof(kMGPipeCallClasses[0]) ==
|
||||
static_cast<SizeT>(MGPWireOp::kOpCount),
|
||||
@@ -468,6 +471,7 @@ inline constexpr Uint8 kMGPipeWaitClasses[static_cast<SizeT>(MGPWireOp::kOpCount
|
||||
/* 81 DeleteStreamOutput */ static_cast<Uint8>(kWaitNone),
|
||||
/* 82 ReadPixelsToBuffer */ static_cast<Uint8>(kWaitNone),
|
||||
/* 83 GetTextureImageToBuffer */ static_cast<Uint8>(kWaitNone),
|
||||
/* 84 BindContext */ static_cast<Uint8>(kWaitNone),
|
||||
};
|
||||
static_assert(sizeof(kMGPipeWaitClasses) / sizeof(kMGPipeWaitClasses[0]) ==
|
||||
static_cast<SizeT>(MGPWireOp::kOpCount),
|
||||
@@ -1198,6 +1202,14 @@ static_assert(sizeof(MGPWireRec_GetTextureImageToBuffer) ==
|
||||
((sizeof(MGPWireRecHeader) + sizeof(MGPReadbackToBuffer) + 7u) & ~SizeT(7u)),
|
||||
"MGPWireRec_GetTextureImageToBuffer gained padding; the wire format moved");
|
||||
|
||||
struct alignas(8) MGPWireRec_BindContext {
|
||||
MGPWireRecHeader Header;
|
||||
MGPBindContext Payload;
|
||||
};
|
||||
static_assert(sizeof(MGPWireRec_BindContext) ==
|
||||
((sizeof(MGPWireRecHeader) + sizeof(MGPBindContext) + 7u) & ~SizeT(7u)),
|
||||
"MGPWireRec_BindContext gained padding; the wire format moved");
|
||||
|
||||
[[noreturn]] inline void MGPipeWireProtocolFatal(const char* call, Uint64 size, Uint64 remaining) {
|
||||
MGLOG_F("MGPipe: protocol corruption applying %s: size=%llu remaining=%llu", call,
|
||||
static_cast<unsigned long long>(size), static_cast<unsigned long long>(remaining));
|
||||
@@ -1496,6 +1508,9 @@ inline Bool MGPipeApplyWireRecord(MGPWireOp op, const void* record, Uint64 size,
|
||||
case MGPWireOp::GetTextureImageToBuffer:
|
||||
MGP_WIRE_CHECK_BOUNDS(MGPWireRec_GetTextureImageToBuffer, "GetTextureImageToBuffer");
|
||||
break;
|
||||
case MGPWireOp::BindContext:
|
||||
MGP_WIRE_CHECK_BOUNDS(MGPWireRec_BindContext, "BindContext");
|
||||
break;
|
||||
case MGPWireOp::kInvalid:
|
||||
case MGPWireOp::kOpCount:
|
||||
default:
|
||||
|
||||
@@ -431,6 +431,8 @@ inline constexpr WireLayoutMember kMGPipeWireLayoutMembers[] = {
|
||||
{"MGPCopyFromFramebuffer.SubImage", offsetof(MGPCopyFromFramebuffer, SubImage), sizeof(((MGPCopyFromFramebuffer*)nullptr)->SubImage)},
|
||||
{"MGPApplierReset", 0, sizeof(MGPApplierReset)},
|
||||
{"MGPApplierReset.ContextSerial", offsetof(MGPApplierReset, ContextSerial), sizeof(((MGPApplierReset*)nullptr)->ContextSerial)},
|
||||
{"MGPBindContext", 0, sizeof(MGPBindContext)},
|
||||
{"MGPBindContext.ClientContextToken", offsetof(MGPBindContext, ClientContextToken), sizeof(((MGPBindContext*)nullptr)->ClientContextToken)},
|
||||
{"MGPContextValues", 0, sizeof(MGPContextValues)},
|
||||
{"MGPContextValues.ActiveTextureUnit", offsetof(MGPContextValues, ActiveTextureUnit), sizeof(((MGPContextValues*)nullptr)->ActiveTextureUnit)},
|
||||
{"MGPContextValues.MaxTouchedTextureUnit", offsetof(MGPContextValues, MaxTouchedTextureUnit), sizeof(((MGPContextValues*)nullptr)->MaxTouchedTextureUnit)},
|
||||
@@ -762,4 +764,5 @@ inline constexpr WireCallLayout kMGPipeWireCallLayouts[] = {
|
||||
{"DeleteStreamOutput", "MGPStreamOutputBind", static_cast<Uint64>(MGPWireOp::DeleteStreamOutput), static_cast<Uint64>(kNone), static_cast<Uint64>(kWaitNone)},
|
||||
{"ReadPixelsToBuffer", "MGPReadbackToBuffer", static_cast<Uint64>(MGPWireOp::ReadPixelsToBuffer), static_cast<Uint64>(kNone), static_cast<Uint64>(kWaitNone)},
|
||||
{"GetTextureImageToBuffer", "MGPReadbackToBuffer", static_cast<Uint64>(MGPWireOp::GetTextureImageToBuffer), static_cast<Uint64>(kNone), static_cast<Uint64>(kWaitNone)},
|
||||
{"BindContext", "MGPBindContext", static_cast<Uint64>(MGPWireOp::BindContext), static_cast<Uint64>(kNone), static_cast<Uint64>(kWaitNone)},
|
||||
};
|
||||
|
||||
@@ -264,10 +264,13 @@
|
||||
|
||||
### POST(`kCapAdoptT0` 的前提)
|
||||
|
||||
持续持锁形状:分配 64 KiB AHB,**整个测试期间 CPU lock 不放**,导入,GPU 读 CPU 写的图案、GPU 写一段,经持有的指针读回比较。
|
||||
- Espryt(`Ops_H_SelfTestExternal`):一次性 ES 3.1 pbuffer 上下文(不碰 Espryt 的绑定缓存),`glBufferStorageExternalEXT` + 持久 coherent 映射,映射读一遍,compute shader 把 region 0 拷到输出、在 word 4096 起写 `0x6C0FFEE0 ^ i`。
|
||||
- Magma(`VkBufferManager::SelfTestWireImport`,`VkBufferManager.cpp:768`):renderer 的设备,`vkCmdCopyBuffer` region 0 → staging、`vkCmdFillBuffer` region 4,栅栏等 2 s。
|
||||
- 结果一行 I `T0 POST (<后端>, sustained-lock pattern) PASSED|FAILED - …`。红米(Adreno 830)两后端 PASSED。
|
||||
持续持锁形状:分配 64 KiB AHB,**整个测试期间 CPU lock 不放**,导入,GPU 读 CPU 写的图案、GPU 写一段,经持有的指针读回比较。**两轮**:
|
||||
- 第一轮读的是导入**之前**写进去的图案。导入会顺手清 CPU 缓存,所以只有这一轮的 POST 在「导入之后经持有指针的写 GPU 永远看不见」的设备上照样通过——而 T0 的真实流量全是导入之后的写。
|
||||
- 第二轮(steady,2026-09-30 补):导入且 GPU 用过之后,CPU 才经持有的指针写 region 1、把 region 4(第一轮的 GPU 写)读进缓存;再一次 GPU 工作把 region 1 拷出、改写 region 4,两个方向都比对。两轮都全对才 PASSED。
|
||||
- 实测:Mali-G1-Ultra(天玑,`3B159D009VZ00000`)第一轮全对、第二轮 Magma 读到 0/1024 词、写回 16/1024(import 内存 non-coherent),Espryt 48/1024、160/1024 → FAILED,T0 回退 T2。改之前该机 T0 被授予,`create-indirect-in-world-align1024` × Magma 的 inproc / spawn 丢掉全部 Flywheel 实例物体(0.867 / 0.848),同 trace 的 T2 0.99998;改之后两臂 0.999984。红米(Adreno 830)两后端两轮全对(Magma coherent),T0 照旧授予。
|
||||
- Espryt(`Ops_H_SelfTestExternal`,第二轮 `SelfTestExternalSteady`):一次性 ES 3.1 pbuffer 上下文(不碰 Espryt 的绑定缓存),`glBufferStorageExternalEXT` + 持久 coherent 映射,映射读一遍,compute shader 把 region 0 拷到输出、在 word 4096 起写 `0x6C0FFEE0 ^ i`;第二轮另一个 compute program 拷 word 1024 起、在 word 4096 起写 `0x3D5EA11E ^ i`。
|
||||
- Magma(`VkBufferManager::SelfTestWireImport`,`VkBufferManager.cpp:768`):renderer 的设备,`vkCmdCopyBuffer` region 0 → staging、`vkCmdFillBuffer` region 4,栅栏等 2 s;第二轮同一命令池重录:region 1 → staging、region 4 填 `0x3D5EA11E`。
|
||||
- 结果一行 I `T0 POST (<后端>, sustained-lock pattern) PASSED|FAILED - …`,两轮的计数都在这一行。红米(Adreno 830)两后端 PASSED;Mali-G1-Ultra 两后端 FAILED(缺省旋钮下这行降为 D,见上表)。
|
||||
|
||||
### server 端存储
|
||||
|
||||
|
||||
@@ -216,10 +216,6 @@ namespace MobileGL::MG_Remote::Client {
|
||||
WaitForApplyBeforeEglForwarder("CreateEGLWindowSurface");
|
||||
// P12 (D1): unless the window is the SERVER's - then there is no handle of ours to tell.
|
||||
if (MG_Config::ServerOwnedWindowSurfaces()) return CreateServerOwnedWindowSurface(surface, handle);
|
||||
// The other on-screen shape: the frames belong to the display host, and the server takes
|
||||
// them from the bridge. As for the server-owned shape, no window of the client's crosses
|
||||
// the wire - only the size it asked for.
|
||||
if (MG_Config::HostFrameWindowSurfaces()) return CreateHostFrameWindowSurface(surface, handle);
|
||||
Server::ServerSetWindowHandle(handle);
|
||||
if (!Server::ServerCreateEGLWindowSurface(surface, handle)) return false;
|
||||
// The server's surface init published the default framebuffer's shape as a
|
||||
@@ -299,10 +295,6 @@ namespace MobileGL::MG_Remote::Client {
|
||||
// dereferenced - the client's InitWindowSurface is a no-op - and never crosses the wire
|
||||
// (the ServerOwned frame carries token 0).
|
||||
char g_serverOwnedWindowPlaceholder = 0;
|
||||
// The host-framed shape names no window of the client's either; the base class still wants
|
||||
// a handle to register the surface with, and this is the same stand-in the server-owned
|
||||
// shape uses.
|
||||
char g_hostFrameWindowPlaceholder = 0;
|
||||
} // namespace
|
||||
|
||||
Bool BackendObject_Remote::CreateServerOwnedWindowSurface(EGLSurface surface,
|
||||
@@ -368,46 +360,6 @@ namespace MobileGL::MG_Remote::Client {
|
||||
return MG_Backend::BackendObject::CreateEGLWindowSurface(surface, local);
|
||||
}
|
||||
|
||||
Bool BackendObject_Remote::CreateHostFrameWindowSurface(EGLSurface surface,
|
||||
const MG_Backend::WindowHandle& handle) {
|
||||
// The size crosses the wire and nothing else of the client's does: the server takes frames
|
||||
// from the display host at that size and answers with the extent the surface has.
|
||||
const Server::ServerOwnedWindowReply reply =
|
||||
Server::ServerCreateHostFrameWindowSurface(surface, handle.Width, handle.Height);
|
||||
if (!reply.ok) {
|
||||
// FAILS BY NAME ON THIS SIDE TOO, as the server-owned shape does: the server logged its
|
||||
// reason, and the refusal code is what lets this line say the same thing.
|
||||
switch (reply.refusal) {
|
||||
case Server::SurfaceRefusalCode::SurfaceModeMismatch:
|
||||
MGLOG_E("MG_Remote client: Refuse HostFrame (SurfaceModeMismatch) - MOBILEGL_IPC_SURFACE=host "
|
||||
"asked for this %ux%u window surface in a session that already chose a pbuffer: only "
|
||||
"one rendering path is active per session. eglCreateWindowSurface fails with "
|
||||
"EGL_BAD_NATIVE_WINDOW",
|
||||
handle.Width, handle.Height);
|
||||
break;
|
||||
case Server::SurfaceRefusalCode::NoServerWindow:
|
||||
MGLOG_E("MG_Remote client: Refuse HostFrame (NoServerWindow) - the server could not take a frame "
|
||||
"from the display host for this %ux%u surface; its log names what the host or the "
|
||||
"bridge said (its own answer was %ux%u)",
|
||||
handle.Width, handle.Height, reply.width, reply.height);
|
||||
break;
|
||||
default:
|
||||
MGLOG_E("MG_Remote client: Refuse HostFrame (code %u) for this %ux%u window surface",
|
||||
static_cast<Uint>(reply.refusal), handle.Width, handle.Height);
|
||||
break;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
// From here the frames are the server's and the host's business; this side only registers the
|
||||
// surface, exactly as it does for the server-owned shape.
|
||||
MG_Backend::WindowHandle local = handle;
|
||||
if (local.Backend == MG_Backend::WindowBackend::Unknown) local.Backend = MG_Backend::WindowBackend::Android;
|
||||
if (local.Handle == nullptr) local.Handle = &g_hostFrameWindowPlaceholder;
|
||||
local.Width = reply.width;
|
||||
local.Height = reply.height;
|
||||
return MG_Backend::BackendObject::CreateEGLWindowSurface(surface, local);
|
||||
}
|
||||
|
||||
Bool BackendObject_Remote::MakeEGLCurrent(EGLDisplay dpy, EGLSurface draw, EGLSurface read,
|
||||
EGLContext ctx) {
|
||||
// FORWARD FIRST, THEN RUN THE BASE. The server has to own the context before the base
|
||||
|
||||
@@ -91,9 +91,6 @@ namespace MobileGL::MG_Remote::Client {
|
||||
// CreateEGLWindowSurface - ONE ServerOwned frame, no SetWindowHandle, the server's real
|
||||
// geometry adopted before it returns, and every refusal named in this process's log.
|
||||
Bool CreateServerOwnedWindowSurface(EGLSurface surface, const MG_Backend::WindowHandle& handle);
|
||||
// MOBILEGL_IPC_SURFACE=host: the frames are the display host's, and the server takes
|
||||
// them from the host frame bridge. Nothing of the client's crosses the wire here either.
|
||||
Bool CreateHostFrameWindowSurface(EGLSurface surface, const MG_Backend::WindowHandle& handle);
|
||||
|
||||
// The generation of the snapshot m_formatCapabilities was filled from. Exposed only
|
||||
// through the log line on a refresh: a cache that silently stopped tracking the mirror
|
||||
|
||||
@@ -1,43 +0,0 @@
|
||||
// MobileGL - MobileGL/MG_Remote/Client/DmaBufImport.cpp
|
||||
// SPDX-License-Identifier: LGPL-3.0-only
|
||||
// End of Source File Header
|
||||
|
||||
#include "DmaBufImport.h"
|
||||
|
||||
#include "ClientSession.h"
|
||||
#include "../Protocol/mg_protocol_base.h"
|
||||
#include "../Transport/ITransport.h"
|
||||
|
||||
namespace MobileGL::MG_Remote::Client {
|
||||
|
||||
Bool ShareImportedDmaBuf(Uint32 target, Uint32 texName, Uint32 width, Uint32 height, Uint32 fourCC,
|
||||
Uint32 planeIndex, Uint32 planeCount, Int planeFd, Int stride, Int offset,
|
||||
Uint64 modifier, Bool hasModifier) {
|
||||
if (planeFd < 0 || planeCount == 0 || planeCount > kDmaBufImportMaxPlanes) return false;
|
||||
// The session's control-plane transport is where the descriptor channel lives; no session or
|
||||
// no channel (a TCP session whose aux came up without SCM_RIGHTS) is a named refusal here.
|
||||
ClientSession* session = ClientSession::Active();
|
||||
if (session == nullptr) return false;
|
||||
Transport::ITransport* transport = session->Control_Plane();
|
||||
if (transport == nullptr) return false;
|
||||
|
||||
DmaBufImportRequest request{};
|
||||
request.Magic = kDmaBufImportRequestMagic;
|
||||
request.Version = kDmaBufImportVersion;
|
||||
request.Target = target;
|
||||
request.TexName = texName;
|
||||
request.Width = width;
|
||||
request.Height = height;
|
||||
request.FourCC = fourCC;
|
||||
request.PlaneCount = planeCount;
|
||||
request.Stride[planeIndex % kDmaBufImportMaxPlanes] = stride;
|
||||
request.Offset[planeIndex % kDmaBufImportMaxPlanes] = offset;
|
||||
request.Modifier[planeIndex % kDmaBufImportMaxPlanes] = modifier;
|
||||
request.HasModifier[planeIndex % kDmaBufImportMaxPlanes] = hasModifier ? 1u : 0u;
|
||||
|
||||
MobileGLByteSpan sideband{};
|
||||
sideband.data = &request;
|
||||
sideband.size = sizeof(request);
|
||||
return transport->ShareFd(planeFd, sideband) == MOBILEGL_OK;
|
||||
}
|
||||
} // namespace MobileGL::MG_Remote::Client
|
||||
@@ -1,53 +0,0 @@
|
||||
// MobileGL - MobileGL/MG_Remote/Client/DmaBufImport.h
|
||||
// SPDX-License-Identifier: LGPL-3.0-only
|
||||
// End of Source File Header
|
||||
|
||||
// TELLING THE RENDER SERVER WHICH TEXTURE A dma-buf BACKS.
|
||||
//
|
||||
// The compositor's scene reaches the display daemon's buffers through glEGLImageTargetTexture2DOES:
|
||||
// eglCreateImageKHR already holds a dup() of every plane's descriptor, and a texture bound to that
|
||||
// image has NO storage on the server - so a framebuffer built over it is not complete and kwin aborts
|
||||
// on its own RenderTarget assertion (measured, twice: "taking target 0x8d65 over an EGLImage of
|
||||
// 1440x3200 fourcc 0x34324241 ... the render server has NOT been told which texture that dma-buf
|
||||
// backs yet"). This is the client's half of closing that: one message per plane, each carrying one
|
||||
// descriptor in the SCM_RIGHTS control data of the session transport's aux socket (ITransport::ShareFd,
|
||||
// FdPassing.h - "a dedicated AF_UNIX SOCK_DGRAM socketpair, so one sendmsg is exactly one recvmsg").
|
||||
//
|
||||
// The byte layout is restated from the server's reader rather than shared with it, for the same reason
|
||||
// the GBM frame shapes are (MG_Backend/GbmFrameChannel.h): the two ends are built into different
|
||||
// libraries from different build configurations. A change on either side is a protocol change, and the
|
||||
// magic is what makes a mismatched pair fail loudly instead of being read as plausible numbers.
|
||||
|
||||
#pragma once
|
||||
#include <Includes.h>
|
||||
|
||||
namespace MobileGL::MG_Remote::Client {
|
||||
|
||||
inline constexpr Uint32 kDmaBufImportRequestMagic = 0x4947474Du; // 'M','G','G','I' in memory order
|
||||
inline constexpr Uint32 kDmaBufImportVersion = 1u;
|
||||
inline constexpr Uint32 kDmaBufImportMaxPlanes = 4u;
|
||||
|
||||
struct DmaBufImportRequest {
|
||||
Uint32 Magic;
|
||||
Uint32 Version;
|
||||
Uint32 Target; // the GL texture target the image was bound to (0x8D65 = GL_TEXTURE_EXTERNAL_OES)
|
||||
Uint32 TexName; // THIS side's texture name; the server resolves its twin
|
||||
Uint32 Width;
|
||||
Uint32 Height;
|
||||
Uint32 FourCC;
|
||||
Uint32 PlaneCount;
|
||||
Int32 Stride[kDmaBufImportMaxPlanes];
|
||||
Int32 Offset[kDmaBufImportMaxPlanes];
|
||||
Uint64 Modifier[kDmaBufImportMaxPlanes];
|
||||
Uint32 HasModifier[kDmaBufImportMaxPlanes];
|
||||
} __attribute__((packed));
|
||||
|
||||
// Shares one plane's descriptor with the server, describing the buffer in the same fields
|
||||
// drmModeAddFB2 takes. Answers false when the session has no descriptor channel (auxFd == -1:
|
||||
// SocketTransport answers MOBILEGL_ERR_UNSUPPORTED) or when the send failed - the caller keeps
|
||||
// treating the texture as having no storage, which is the honest state, rather than rendering
|
||||
// into nothing.
|
||||
Bool ShareImportedDmaBuf(Uint32 target, Uint32 texName, Uint32 width, Uint32 height, Uint32 fourCC,
|
||||
Uint32 planeIndex, Uint32 planeCount, Int planeFd, Int stride, Int offset,
|
||||
Uint64 modifier, Bool hasModifier);
|
||||
} // namespace MobileGL::MG_Remote::Client
|
||||
@@ -513,18 +513,6 @@ namespace MobileGL::MG_Remote::Client {
|
||||
if (CreateIsSuspect(handle) || g_createSuspects.size() >= kCreateSuspectMax) return;
|
||||
g_createSuspects.push_back(handle);
|
||||
}
|
||||
// THE WINDOW IS A SESSION'S, NOT THE PROCESS'S. Every entry names a sequence number of the
|
||||
// session that wrote it, and a process can run several sessions one after another (eglinfo
|
||||
// terminates one display and initializes the next). An entry left by the previous session
|
||||
// made the new session's first create wait for a sequence number the new server would not
|
||||
// reach for a long time (measured: the second session hung on its first texture create, in
|
||||
// DrainCreateWindow's blocking WaitForApplied). Its answer, and the object it was about,
|
||||
// died with that session; the suspects are that session's handles too.
|
||||
void ForgetPreviousSessionCreates() {
|
||||
g_createWindowHead = 0;
|
||||
g_createWindowCount = 0;
|
||||
g_createSuspects.clear();
|
||||
}
|
||||
void ClearCreateSuspect(MG_Pipe::MGPipeHandle handle) {
|
||||
for (SizeT i = 0; i < g_createSuspects.size(); ++i) {
|
||||
if (g_createSuspects[i].Slot != handle.Slot || g_createSuspects[i].Gen != handle.Gen)
|
||||
@@ -1132,6 +1120,52 @@ namespace MobileGL::MG_Remote::Client {
|
||||
Uint64 g_applierResetContextSerial = 0;
|
||||
} // namespace
|
||||
|
||||
// P14 S1: the EGL context lifecycle's two frames. NO SESSION IS AN ANSWER, not a Fatal:
|
||||
// eglCreateContext/eglDestroyContext can legally run before ClientSession::Start (the
|
||||
// bring-up window) and on the server role's own thread, and in both there is no wire for the
|
||||
// frame to cross - the caller falls back to what it did before this slice, which is to keep
|
||||
// the client's own EGL books and nothing else.
|
||||
namespace {
|
||||
// The window test both senders below open with, and the reason it is a function rather
|
||||
// than two copies of the same if: a sender that answered Refused for "no wire" would make
|
||||
// eglCreateContext return EGL_NO_CONTEXT during the bring-up, which is the exact failure
|
||||
// the pre-Start exception exists to prevent.
|
||||
Bool ContextFramesCanCross() {
|
||||
ClientSession* session = ClientSession::Active();
|
||||
return session != nullptr && session->Started() &&
|
||||
!g_clientTablesUninstalled.load(std::memory_order_acquire);
|
||||
}
|
||||
} // namespace
|
||||
|
||||
ContextFrameEmit SendCreateContextFrame(Uint64 clientContextToken, Uint64 shareGroupToken, Uint32 flags) {
|
||||
if (!ContextFramesCanCross()) return ContextFrameEmit::NoWire;
|
||||
return Server::ServerCreateEGLContext(clientContextToken, shareGroupToken, flags) ? ContextFrameEmit::Sent
|
||||
: ContextFrameEmit::Refused;
|
||||
}
|
||||
|
||||
ContextFrameEmit SendDestroyContextFrame(Uint64 clientContextToken) {
|
||||
if (!ContextFramesCanCross()) return ContextFrameEmit::NoWire;
|
||||
return Server::ServerDestroyEGLContext(clientContextToken) ? ContextFrameEmit::Sent
|
||||
: ContextFrameEmit::Refused;
|
||||
}
|
||||
|
||||
// P14 S1: bind_context. The same four windows as EmitApplierResetRecord below answer false,
|
||||
// and for the same reason: a binding that cannot cross leaves the session on the default it
|
||||
// already has (one context per session, every record its own), which is what the server
|
||||
// answers with no record at all. The token is minted by EGLState and passed in rather than
|
||||
// read here, so this table holds no second opinion about which context is current.
|
||||
Bool EmitBindContextRecord(Uint64 clientContextToken) {
|
||||
ClientSession* session = ClientSession::Active();
|
||||
if (session == nullptr || !session->Started()) return false;
|
||||
if (g_clientTablesUninstalled.load(std::memory_order_acquire)) return false;
|
||||
MG_Pipe::MGPBindContext record{};
|
||||
record.ClientContextToken = clientContextToken;
|
||||
session->EmitAndWait(MGPWireOp::BindContext, &record, sizeof(record), nullptr, 0, nullptr, 0,
|
||||
nullptr);
|
||||
++g_emitted;
|
||||
return true;
|
||||
}
|
||||
|
||||
Bool EmitApplierResetRecord() {
|
||||
// NO SESSION, NO RECORD - and false rather than the RequireSession Fatal, because a
|
||||
// validate can legitimately prime with a transport CONFIGURED but no live session:
|
||||
@@ -1221,7 +1255,6 @@ namespace MobileGL::MG_Remote::Client {
|
||||
|
||||
void InstallClientWireTables() {
|
||||
using namespace MG_Pipe;
|
||||
ForgetPreviousSessionCreates();
|
||||
|
||||
// DirectGLES normally installs this notice while creating its handle
|
||||
// backend. An independent client never creates that backend: without a
|
||||
|
||||
@@ -125,6 +125,43 @@ namespace MobileGL::MG_Remote::Client {
|
||||
// caller then makes the direct call the record replaced.
|
||||
Bool EmitApplierResetRecord();
|
||||
|
||||
// ---- P14 S1: the EGL context lifecycle's control-plane half -----------------------------
|
||||
//
|
||||
// NOT ring records and NOT routed rows: eglCreateContext/eglDestroyContext are the EGL
|
||||
// lifecycle, which the catalogue deliberately keeps off the record plane (PipeCalls.def's
|
||||
// "the eight EGL lifecycle entry points stay virtual functions on pActiveBackendObject"),
|
||||
// so they cross as two SurfaceOp kinds through the same blocking frame channel the nine
|
||||
// surface forwarders use. Called by MG_Impl's EGLImpl on the app thread, in the same order
|
||||
// as the EGL calls themselves - which is the ordering the server's context table needs.
|
||||
//
|
||||
// THREE ANSWERS, NOT TWO, for the reason ObjectDeathEmit below has three: "the server said
|
||||
// no" and "there is no wire for the question to cross" are different facts and the caller's
|
||||
// answer to each is different. NoWire is the bring-up window before ClientSession::Start and
|
||||
// the server role's own thread - in both, the pre-S1 shape (the client keeps its own EGL
|
||||
// books and no server table exists) is the correct one and the context must be KEPT; Refused
|
||||
// is a server that answered, and eglCreateContext turns it into EGL_NO_CONTEXT, because a
|
||||
// context whose token the server did not table is one the first bind_context after it would
|
||||
// be refused for.
|
||||
enum class ContextFrameEmit : Uint8 { Sent, NoWire, Refused };
|
||||
ContextFrameEmit SendCreateContextFrame(Uint64 clientContextToken, Uint64 shareGroupToken, Uint32 flags);
|
||||
// A destroy has the same three answers; the client's EGL book is dropped either way (that is
|
||||
// the caller's own state machine), and what a refusal changes is only what the server holds.
|
||||
ContextFrameEmit SendDestroyContextFrame(Uint64 clientContextToken);
|
||||
|
||||
// P14 S1 (docs/Disaggregated/design/11-state-ownership.md): bind_context, opcode 84.
|
||||
//
|
||||
// Emitted on the GL thread from EGLImpl::MakeCurrent, after the switch has succeeded and
|
||||
// before eglMakeCurrent returns - which puts it ahead of the applier_reset the NEXT GL call's
|
||||
// validate emits (PipeFill.cpp's FreshlyPrimed arm), so the reset is already attributed to
|
||||
// the context that primed. `clientContextToken` is the token
|
||||
// EGLState minted for the context the calling thread now has current (0 = none, the release
|
||||
// edge) - the caller reads it rather than this table owning a second copy, so the two planes
|
||||
// cannot disagree about which context is bound. Returns false - nothing emitted - in exactly
|
||||
// the windows EmitApplierResetRecord documents (no live session, the pre-Start bring-up, a
|
||||
// server-role-only fixture, teardown), where there is no wire for the binding to cross and
|
||||
// the session's single-context default is what the server already answers.
|
||||
Bool EmitBindContextRecord(Uint64 clientContextToken);
|
||||
|
||||
// P5c (rv), CONTRACT-P5C.md §5.3: whether set_context_values can cross right now (a live,
|
||||
// started session, tables not being torn down). PipeFill.cpp gates the record's emission
|
||||
// AND the residual-fill skip for its eight fields on this one answer, so the two halves
|
||||
|
||||
@@ -19,6 +19,7 @@
|
||||
#include <cstdarg>
|
||||
#include <cstdio>
|
||||
#include <mutex>
|
||||
#include <unordered_map>
|
||||
|
||||
#include <flatbuffers/flatbuffers.h>
|
||||
|
||||
@@ -96,37 +97,92 @@ namespace MobileGL::MG_Remote {
|
||||
// PH-1 (3): the latch's state. Armed once, by the session child; latched once, by the
|
||||
// first fault. The line is written under the mutex BEFORE the release store that
|
||||
// publishes `g_latched`, so a reader that saw true reads a whole line.
|
||||
std::atomic<bool> g_latchArmed{false};
|
||||
std::atomic<bool> g_latched{false};
|
||||
std::atomic<std::uint64_t> g_latchCount{0};
|
||||
std::mutex g_latchMutex;
|
||||
MGFatalFamily g_latchedFamily = MGFatalFamily::ProtocolCorruption;
|
||||
char g_latchedLine[512] = {};
|
||||
//
|
||||
// P14 S2: ONE OF THESE PER SESSION (FatalFunnel.h's domain block). A domain's storage is
|
||||
// heap-allocated by FatalLatchDomainOpen and lives until FatalLatchDomainClose; domain 0
|
||||
// is this process-wide one, which is what every thread that binds nothing uses.
|
||||
struct LatchState {
|
||||
int id = 0;
|
||||
std::atomic<bool> armed{false};
|
||||
std::atomic<bool> latched{false};
|
||||
std::atomic<std::uint64_t> count{0};
|
||||
std::mutex mutex;
|
||||
MGFatalFamily latchedFamily = MGFatalFamily::ProtocolCorruption;
|
||||
char latchedLine[512] = {};
|
||||
};
|
||||
|
||||
LatchState g_defaultLatch;
|
||||
|
||||
thread_local LatchState* t_latch = &g_defaultLatch;
|
||||
|
||||
std::mutex g_domainsMutex;
|
||||
std::unordered_map<int, LatchState*> g_domains;
|
||||
int g_nextDomain = 1;
|
||||
|
||||
LatchState& Latch() { return *t_latch; }
|
||||
} // namespace
|
||||
|
||||
void ArmSessionLatch() { g_latchArmed.store(true, std::memory_order_release); }
|
||||
int FatalLatchDomainOpen() {
|
||||
const std::lock_guard<std::mutex> lock(g_domainsMutex);
|
||||
if (g_nextDomain <= 0 || g_nextDomain > kMaxLatchDomains) return 0;
|
||||
LatchState* state = new LatchState{};
|
||||
state->id = g_nextDomain++;
|
||||
g_domains.emplace(state->id, state);
|
||||
return state->id;
|
||||
}
|
||||
|
||||
void FatalLatchDomainClose(int domain) {
|
||||
if (domain == 0) return;
|
||||
LatchState* state = nullptr;
|
||||
{
|
||||
const std::lock_guard<std::mutex> lock(g_domainsMutex);
|
||||
const auto found = g_domains.find(domain);
|
||||
if (found == g_domains.end()) return;
|
||||
state = found->second;
|
||||
g_domains.erase(found);
|
||||
}
|
||||
delete state;
|
||||
}
|
||||
|
||||
int FatalLatchDomainBind(int domain) {
|
||||
LatchState* const previous = t_latch;
|
||||
if (domain == 0) {
|
||||
t_latch = &g_defaultLatch;
|
||||
return previous->id;
|
||||
}
|
||||
{
|
||||
const std::lock_guard<std::mutex> lock(g_domainsMutex);
|
||||
const auto found = g_domains.find(domain);
|
||||
t_latch = found == g_domains.end() ? &g_defaultLatch : found->second;
|
||||
}
|
||||
return previous->id;
|
||||
}
|
||||
|
||||
void ArmSessionLatch() { Latch().armed.store(true, std::memory_order_release); }
|
||||
|
||||
void ResetSessionLatch() {
|
||||
const std::lock_guard<std::mutex> lock(g_latchMutex);
|
||||
g_latchArmed.store(false, std::memory_order_release);
|
||||
g_latchCount.store(0, std::memory_order_relaxed);
|
||||
g_latchedFamily = MGFatalFamily::ProtocolCorruption;
|
||||
g_latchedLine[0] = '\0';
|
||||
g_latched.store(false, std::memory_order_release);
|
||||
LatchState& latch = Latch();
|
||||
const std::lock_guard<std::mutex> lock(latch.mutex);
|
||||
latch.armed.store(false, std::memory_order_release);
|
||||
latch.count.store(0, std::memory_order_relaxed);
|
||||
latch.latchedFamily = MGFatalFamily::ProtocolCorruption;
|
||||
latch.latchedLine[0] = '\0';
|
||||
latch.latched.store(false, std::memory_order_release);
|
||||
}
|
||||
|
||||
bool SessionLatchArmed() { return g_latchArmed.load(std::memory_order_acquire); }
|
||||
bool SessionLatchArmed() { return Latch().armed.load(std::memory_order_acquire); }
|
||||
|
||||
bool SessionLatched() { return g_latched.load(std::memory_order_acquire); }
|
||||
bool SessionLatched() { return Latch().latched.load(std::memory_order_acquire); }
|
||||
|
||||
MGFatalFamily SessionLatchedFamily() {
|
||||
const std::lock_guard<std::mutex> lock(g_latchMutex);
|
||||
return g_latchedFamily;
|
||||
LatchState& latch = Latch();
|
||||
const std::lock_guard<std::mutex> lock(latch.mutex);
|
||||
return latch.latchedFamily;
|
||||
}
|
||||
|
||||
const char* SessionLatchedLine() { return g_latchedLine; }
|
||||
const char* SessionLatchedLine() { return Latch().latchedLine; }
|
||||
|
||||
std::uint64_t SessionLatchCount() { return g_latchCount.load(std::memory_order_relaxed); }
|
||||
std::uint64_t SessionLatchCount() { return Latch().count.load(std::memory_order_relaxed); }
|
||||
|
||||
bool SessionLatch(MGFatalFamily family, const char* fmt, ...) {
|
||||
char line[512];
|
||||
@@ -135,23 +191,25 @@ namespace MobileGL::MG_Remote {
|
||||
FormatFaultLine(line, fmt, args);
|
||||
va_end(args);
|
||||
|
||||
LatchState& latch = Latch();
|
||||
|
||||
// UNARMED IS SessionFail, byte for byte: the inproc server, the client and every unit
|
||||
// death test keep the death they had (FatalFunnel.h's block says why inproc must).
|
||||
if (!g_latchArmed.load(std::memory_order_acquire)) {
|
||||
if (!latch.armed.load(std::memory_order_acquire)) {
|
||||
SessionFail(family, "%s", line);
|
||||
}
|
||||
|
||||
g_sessionFaultCount.fetch_add(1, std::memory_order_relaxed);
|
||||
g_latchCount.fetch_add(1, std::memory_order_relaxed);
|
||||
latch.count.fetch_add(1, std::memory_order_relaxed);
|
||||
LogFaultLine(line);
|
||||
|
||||
bool first = false;
|
||||
{
|
||||
const std::lock_guard<std::mutex> lock(g_latchMutex);
|
||||
if (!g_latched.load(std::memory_order_relaxed)) {
|
||||
std::snprintf(g_latchedLine, sizeof(g_latchedLine), "%s", line);
|
||||
g_latchedFamily = family;
|
||||
g_latched.store(true, std::memory_order_release);
|
||||
const std::lock_guard<std::mutex> lock(latch.mutex);
|
||||
if (!latch.latched.load(std::memory_order_relaxed)) {
|
||||
std::snprintf(latch.latchedLine, sizeof(latch.latchedLine), "%s", line);
|
||||
latch.latchedFamily = family;
|
||||
latch.latched.store(true, std::memory_order_release);
|
||||
first = true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -62,8 +62,10 @@ namespace MobileGL::MG_Remote {
|
||||
// crash (ID-P7-1: "下一连接照常服务" is the supervisor's, not the latch's).
|
||||
//
|
||||
// WHERE IT IS ARMED, AND WHY ONLY THERE. ArmSessionLatch() is called by exactly one site:
|
||||
// ServerMain::RunSession, i.e. the spawn / TCP session child (with or without --serve), whose
|
||||
// process IS the session. Unarmed, SessionLatch IS SessionFail - same line, same abort - and
|
||||
// ServerMain::RunSession, i.e. a served session - the spawn / TCP session child (with or
|
||||
// without --serve), whose process IS the session, and (P14 S2) each session the in-process
|
||||
// display server runs, which arms ITS OWN latch domain so a fault there ends that session and
|
||||
// no other. Unarmed, SessionLatch IS SessionFail - same line, same abort - and
|
||||
// that is the answer everywhere else, deliberately:
|
||||
// * INPROC keeps Fatal. CONTRACT-P5's R-2 arms (rules A/B/C, the four honesty arms) are
|
||||
// Fatal{ProtocolCorruption} in the formal wording, and under inproc the client and the
|
||||
@@ -85,6 +87,10 @@ namespace MobileGL::MG_Remote {
|
||||
// Between sessions the latch is unarmed, so a fault there is a SessionFail - which in the
|
||||
// in-process shape takes the display Activity's process down with it: the crash isolation a
|
||||
// forked session child gave is what running in-process gives up (documented, D5).
|
||||
//
|
||||
// P14 S2: it now clears the CALLING THREAD'S DOMAIN (below), which between sessions is the
|
||||
// process default - a session that opened its own domain cannot leave a latch behind for the
|
||||
// next one to inherit, because the next one does not read that domain at all.
|
||||
void ResetSessionLatch();
|
||||
// True once the first fault has latched. One acquire load: DrainRing asks it before every pop.
|
||||
bool SessionLatched();
|
||||
@@ -95,6 +101,31 @@ namespace MobileGL::MG_Remote {
|
||||
// Every fault this armed process latched or declined after the first (>= 1 once latched).
|
||||
::std::uint64_t SessionLatchCount();
|
||||
|
||||
// ---- P14 S2: ONE LATCH DOMAIN PER SERVED SESSION ------------------------------------
|
||||
//
|
||||
// THE LATCH IS PER SESSION NOW, and that is a correctness requirement of serving several in
|
||||
// one process, not a tidy-up. Its three readers sit on a session's own threads - the apply
|
||||
// loop's park, DrainRing's per-pop check, ServerMain's control loop - so a latch raised by
|
||||
// session A used to stop session B's apply thread mid-ring and end B's control loop: one
|
||||
// peer's bad bytes took down its neighbours. ResetSessionLatch had the mirror problem: the
|
||||
// reap of a finished session cleared the latch a live one was standing on.
|
||||
//
|
||||
// A DOMAIN is the latch state, and a THREAD IS BOUND TO ONE. SessionRuntime opens a domain per
|
||||
// served session and ThreadSessionScope binds both of that session's threads to it. A thread
|
||||
// that has bound nothing uses DOMAIN 0, the process default - which is exactly the old
|
||||
// behaviour, and is what the client, the inproc one-process shape and every unit case get.
|
||||
//
|
||||
// 0 IS RESERVED FOR THE PROCESS DEFAULT and FatalLatchDomainOpen never returns it (0 on
|
||||
// exhaustion, which degrades to "shares the default" rather than to a crash).
|
||||
inline constexpr int kMaxLatchDomains = 64;
|
||||
int FatalLatchDomainOpen();
|
||||
// The domain's state goes; no thread may still be bound to it (the session's apply thread is
|
||||
// joined and its control thread's scope has been destroyed by then).
|
||||
void FatalLatchDomainClose(int domain);
|
||||
// Binds the CALLING THREAD to `domain`, returning the domain it was bound to before so a
|
||||
// scope can put it back.
|
||||
int FatalLatchDomainBind(int domain);
|
||||
|
||||
// The session child's exit status when its session ended on a latched fault. Distinct from
|
||||
// RunSession's other codes (64-74) so the supervisor's reap line names it; nonzero, so it is
|
||||
// counted in `sessionsFaulted` like every other fault.
|
||||
|
||||
@@ -51,18 +51,23 @@ namespace MobileGL::MG_Remote {
|
||||
// cp's one schema addition, on the same append-only terms.
|
||||
static_assert(static_cast<Uint8>(SurfaceControlOp::InitCapabilities) ==
|
||||
static_cast<Uint8>(::MobileGL::Wire::SurfaceOpKind::InitCapabilities));
|
||||
// P14 S1's two appends, on the same append-only terms. The VALUES are pinned because they
|
||||
// are wire ABI, and pinned SEPARATELY from the identity cast beside them: the cast would
|
||||
// stay green if both enums moved together to 20/21, and a peer built before the move
|
||||
// would then read the two ops as two others.
|
||||
static_assert(static_cast<Uint8>(SurfaceControlOp::CreateContext) ==
|
||||
static_cast<Uint8>(::MobileGL::Wire::SurfaceOpKind::CreateContext));
|
||||
static_assert(static_cast<Uint8>(SurfaceControlOp::DestroyContext) ==
|
||||
static_cast<Uint8>(::MobileGL::Wire::SurfaceOpKind::DestroyContext));
|
||||
static_assert(static_cast<Uint8>(::MobileGL::Wire::SurfaceOpKind::SetSwapInterval) == 8 &&
|
||||
static_cast<Uint8>(::MobileGL::Wire::SurfaceOpKind::ReleaseResources) == 9 &&
|
||||
static_cast<Uint8>(::MobileGL::Wire::SurfaceOpKind::SetWindowHandle) == 10 &&
|
||||
static_cast<Uint8>(::MobileGL::Wire::SurfaceOpKind::InitCapabilities) == 11);
|
||||
static_cast<Uint8>(::MobileGL::Wire::SurfaceOpKind::InitCapabilities) == 11 &&
|
||||
static_cast<Uint8>(::MobileGL::Wire::SurfaceOpKind::CreateContext) == 12 &&
|
||||
static_cast<Uint8>(::MobileGL::Wire::SurfaceOpKind::DestroyContext) == 13);
|
||||
static_assert(static_cast<Uint8>(::MobileGL::Wire::WindowKind::MetalLayer) == 6);
|
||||
// P12's append, on the same terms: the value is wire ABI.
|
||||
static_assert(static_cast<Uint8>(::MobileGL::Wire::WindowKind::ServerOwned) == 7);
|
||||
static_assert(static_cast<Uint8>(::MobileGL::Wire::WindowKind::HostFrame) == 8);
|
||||
static_assert(static_cast<Uint8>(::MobileGL::Wire::SurfaceRefusal::HostFrameOnSetWindowHandle) ==
|
||||
static_cast<Uint8>(Server::SurfaceRefusalCode::HostFrameOnSetWindowHandle));
|
||||
static_assert(Server::kHostFrameWindowBackend > Server::kServerOwnedWindowBackend,
|
||||
"kHostFrameWindowBackend must not collide with the server-owned tag");
|
||||
// The frame's refusal codes ARE the wire's SurfaceRefusal (SurfaceControlFrame.h), pinned
|
||||
// value by value so a schema edit that renumbers either side fails here.
|
||||
using Server::SurfaceRefusalCode;
|
||||
@@ -99,8 +104,6 @@ namespace MobileGL::MG_Remote {
|
||||
case SurfaceWireError::AndroidNativeWindowArrived: return "AndroidNativeWindowArrived";
|
||||
case SurfaceWireError::ServerOwnedTokenNotZero: return "ServerOwnedTokenNotZero";
|
||||
case SurfaceWireError::ServerOwnedOnSetWindowHandle: return "ServerOwnedOnSetWindowHandle";
|
||||
case SurfaceWireError::HostFrameTokenNotZero: return "HostFrameTokenNotZero";
|
||||
case SurfaceWireError::HostFrameOnSetWindowHandle: return "HostFrameOnSetWindowHandle";
|
||||
}
|
||||
return "<unknown SurfaceWireError>";
|
||||
}
|
||||
@@ -119,7 +122,7 @@ namespace MobileGL::MG_Remote {
|
||||
// Fatal{ProtocolCorruption} at ServerApplyWireSurfaceOp rather than as
|
||||
// the missing row it is.
|
||||
if (::flatbuffers::IsOutRange(kind, ::MobileGL::Wire::SurfaceOpKind::InitializeDisplay,
|
||||
::MobileGL::Wire::SurfaceOpKind::InitCapabilities)) {
|
||||
::MobileGL::Wire::SurfaceOpKind::DestroyContext)) {
|
||||
return false;
|
||||
}
|
||||
const SurfaceControlOp op = static_cast<SurfaceControlOp>(static_cast<Uint8>(kind));
|
||||
@@ -174,15 +177,6 @@ namespace MobileGL::MG_Remote {
|
||||
}
|
||||
windowKind = ::MobileGL::Wire::WindowKind::ServerOwned;
|
||||
nativeToken = 0;
|
||||
} else if (frame.windowBackend == Server::kHostFrameWindowBackend) {
|
||||
// MOBILEGL_IPC_SURFACE=host: the frames are the DISPLAY HOST's, taken by the
|
||||
// server from the host frame bridge. As for the server-owned tag - a creation
|
||||
// only, and the token is 0 whatever the frame carried.
|
||||
if (frame.kind != SurfaceControlOp::CreateWindowSurface) {
|
||||
return SurfaceWireError::HostFrameOnSetWindowHandle;
|
||||
}
|
||||
windowKind = ::MobileGL::Wire::WindowKind::HostFrame;
|
||||
nativeToken = 0;
|
||||
} else if (!WireWindowKindForWindowBackend(
|
||||
static_cast<MG_Backend::WindowBackend>(frame.windowBackend), &windowKind)) {
|
||||
return SurfaceWireError::UnknownWindowKind;
|
||||
@@ -190,7 +184,8 @@ namespace MobileGL::MG_Remote {
|
||||
}
|
||||
const auto op = ::MobileGL::Wire::CreateSurfaceOp(
|
||||
*builder, frame.seq, kind, frame.display, frame.surface, windowKind, nativeToken,
|
||||
frame.width, frame.height, frame.swapInterval, frame.readSurface, frame.context);
|
||||
frame.width, frame.height, frame.swapInterval, frame.readSurface, frame.context,
|
||||
frame.shareGroupToken, frame.contextFlags);
|
||||
const auto envelope = ::MobileGL::Wire::CreateCtrlEnvelope(*builder, ::MobileGL::Wire::CtrlMsg::SurfaceOp, op.Union());
|
||||
::MobileGL::Wire::FinishCtrlEnvelopeBuffer(*builder, envelope);
|
||||
return SurfaceWireError::None;
|
||||
@@ -211,6 +206,8 @@ namespace MobileGL::MG_Remote {
|
||||
decoded.width = op.width();
|
||||
decoded.height = op.height();
|
||||
decoded.swapInterval = op.swapInterval();
|
||||
decoded.shareGroupToken = op.shareGroupToken();
|
||||
decoded.contextFlags = op.contextFlags();
|
||||
if (OpNeedsAWindowBackend(kind)) {
|
||||
if (op.windowKind() == ::MobileGL::Wire::WindowKind::ServerOwned) {
|
||||
// P12 (D2). Asked BEFORE the Android refusal below, which it is not: the window is
|
||||
@@ -229,21 +226,6 @@ namespace MobileGL::MG_Remote {
|
||||
*frame = decoded;
|
||||
return SurfaceWireError::None;
|
||||
}
|
||||
if (op.windowKind() == ::MobileGL::Wire::WindowKind::HostFrame) {
|
||||
// MOBILEGL_IPC_SURFACE=host. As above: a creation only, and a token of 0
|
||||
// only - anything else is a value from the peer's window system trying to
|
||||
// cross (Rule G), which is corruption rather than a refusal.
|
||||
if (kind != SurfaceControlOp::CreateWindowSurface) {
|
||||
return SurfaceWireError::HostFrameOnSetWindowHandle;
|
||||
}
|
||||
if (op.nativeToken() != 0) {
|
||||
return SurfaceWireError::HostFrameTokenNotZero;
|
||||
}
|
||||
decoded.windowBackend = Server::kHostFrameWindowBackend;
|
||||
decoded.nativeToken = 0;
|
||||
*frame = decoded;
|
||||
return SurfaceWireError::None;
|
||||
}
|
||||
if (op.windowKind() == ::MobileGL::Wire::WindowKind::AndroidNativeWindow) {
|
||||
// The one refusal that is not corruption: the window kind is LEGAL and the token
|
||||
// is an ANativeWindow*, which names memory in the CLIENT's process. Real window
|
||||
@@ -256,10 +238,10 @@ namespace MobileGL::MG_Remote {
|
||||
}
|
||||
MG_Backend::WindowBackend backend;
|
||||
if (!WindowBackendForWireWindowKind(op.windowKind(), &backend)) {
|
||||
// THE UPPER BOUND IS THE LAST APPENDED KIND (P12: HostFrame), for the reason
|
||||
// THE UPPER BOUND IS THE LAST APPENDED KIND (P12: ServerOwned), for the reason
|
||||
// SurfaceControlOpForWireKind's bound gives.
|
||||
return ::flatbuffers::IsOutRange(op.windowKind(), ::MobileGL::Wire::WindowKind::None,
|
||||
::MobileGL::Wire::WindowKind::HostFrame)
|
||||
::MobileGL::Wire::WindowKind::ServerOwned)
|
||||
? SurfaceWireError::UnknownWindowKind
|
||||
: SurfaceWireError::WindowKindNamesNoBackend;
|
||||
}
|
||||
|
||||
@@ -68,9 +68,6 @@ namespace MobileGL::MG_Remote {
|
||||
// CreateWindowSurface only, and only with nativeToken 0:
|
||||
ServerOwnedTokenNotZero, // -> Fatal{ProtocolCorruption, "SurfaceOp.nativeToken"}, latched
|
||||
ServerOwnedOnSetWindowHandle, // -> a NAMED REFUSAL (reply ok=false), not a latch
|
||||
// MOBILEGL_IPC_SURFACE=host, the same two rules for the other on-screen shape:
|
||||
HostFrameTokenNotZero, // -> Fatal{ProtocolCorruption, "SurfaceOp.nativeToken"}, latched
|
||||
HostFrameOnSetWindowHandle, // -> a NAMED REFUSAL (reply ok=false), not a latch
|
||||
};
|
||||
|
||||
const char* SurfaceWireErrorName(SurfaceWireError error);
|
||||
|
||||
@@ -285,11 +285,13 @@ enum class SurfaceOpKind : uint8_t {
|
||||
ReleaseResources = 9,
|
||||
SetWindowHandle = 10,
|
||||
InitCapabilities = 11,
|
||||
CreateContext = 12,
|
||||
DestroyContext = 13,
|
||||
MIN = None,
|
||||
MAX = InitCapabilities
|
||||
MAX = DestroyContext
|
||||
};
|
||||
|
||||
inline const SurfaceOpKind (&EnumValuesSurfaceOpKind())[12] {
|
||||
inline const SurfaceOpKind (&EnumValuesSurfaceOpKind())[14] {
|
||||
static const SurfaceOpKind values[] = {
|
||||
SurfaceOpKind::None,
|
||||
SurfaceOpKind::InitializeDisplay,
|
||||
@@ -302,13 +304,15 @@ inline const SurfaceOpKind (&EnumValuesSurfaceOpKind())[12] {
|
||||
SurfaceOpKind::SetSwapInterval,
|
||||
SurfaceOpKind::ReleaseResources,
|
||||
SurfaceOpKind::SetWindowHandle,
|
||||
SurfaceOpKind::InitCapabilities
|
||||
SurfaceOpKind::InitCapabilities,
|
||||
SurfaceOpKind::CreateContext,
|
||||
SurfaceOpKind::DestroyContext
|
||||
};
|
||||
return values;
|
||||
}
|
||||
|
||||
inline const char * const *EnumNamesSurfaceOpKind() {
|
||||
static const char * const names[13] = {
|
||||
static const char * const names[15] = {
|
||||
"None",
|
||||
"InitializeDisplay",
|
||||
"CreateWindowSurface",
|
||||
@@ -321,13 +325,15 @@ inline const char * const *EnumNamesSurfaceOpKind() {
|
||||
"ReleaseResources",
|
||||
"SetWindowHandle",
|
||||
"InitCapabilities",
|
||||
"CreateContext",
|
||||
"DestroyContext",
|
||||
nullptr
|
||||
};
|
||||
return names;
|
||||
}
|
||||
|
||||
inline const char *EnumNameSurfaceOpKind(SurfaceOpKind e) {
|
||||
if (::flatbuffers::IsOutRange(e, SurfaceOpKind::None, SurfaceOpKind::InitCapabilities)) return "";
|
||||
if (::flatbuffers::IsOutRange(e, SurfaceOpKind::None, SurfaceOpKind::DestroyContext)) return "";
|
||||
const size_t index = static_cast<size_t>(e);
|
||||
return EnumNamesSurfaceOpKind()[index];
|
||||
}
|
||||
@@ -341,12 +347,11 @@ enum class WindowKind : uint8_t {
|
||||
Pbuffer = 5,
|
||||
MetalLayer = 6,
|
||||
ServerOwned = 7,
|
||||
HostFrame = 8,
|
||||
MIN = None,
|
||||
MAX = HostFrame
|
||||
MAX = ServerOwned
|
||||
};
|
||||
|
||||
inline const WindowKind (&EnumValuesWindowKind())[9] {
|
||||
inline const WindowKind (&EnumValuesWindowKind())[8] {
|
||||
static const WindowKind values[] = {
|
||||
WindowKind::None,
|
||||
WindowKind::AndroidNativeWindow,
|
||||
@@ -355,14 +360,13 @@ inline const WindowKind (&EnumValuesWindowKind())[9] {
|
||||
WindowKind::Surfaceless,
|
||||
WindowKind::Pbuffer,
|
||||
WindowKind::MetalLayer,
|
||||
WindowKind::ServerOwned,
|
||||
WindowKind::HostFrame
|
||||
WindowKind::ServerOwned
|
||||
};
|
||||
return values;
|
||||
}
|
||||
|
||||
inline const char * const *EnumNamesWindowKind() {
|
||||
static const char * const names[10] = {
|
||||
static const char * const names[9] = {
|
||||
"None",
|
||||
"AndroidNativeWindow",
|
||||
"X11",
|
||||
@@ -371,14 +375,13 @@ inline const char * const *EnumNamesWindowKind() {
|
||||
"Pbuffer",
|
||||
"MetalLayer",
|
||||
"ServerOwned",
|
||||
"HostFrame",
|
||||
nullptr
|
||||
};
|
||||
return names;
|
||||
}
|
||||
|
||||
inline const char *EnumNameWindowKind(WindowKind e) {
|
||||
if (::flatbuffers::IsOutRange(e, WindowKind::None, WindowKind::HostFrame)) return "";
|
||||
if (::flatbuffers::IsOutRange(e, WindowKind::None, WindowKind::ServerOwned)) return "";
|
||||
const size_t index = static_cast<size_t>(e);
|
||||
return EnumNamesWindowKind()[index];
|
||||
}
|
||||
@@ -389,38 +392,35 @@ enum class SurfaceRefusal : uint8_t {
|
||||
NoServerWindow = 2,
|
||||
SurfaceModeMismatch = 3,
|
||||
ServerOwnedOnSetWindowHandle = 4,
|
||||
HostFrameOnSetWindowHandle = 5,
|
||||
MIN = None,
|
||||
MAX = HostFrameOnSetWindowHandle
|
||||
MAX = ServerOwnedOnSetWindowHandle
|
||||
};
|
||||
|
||||
inline const SurfaceRefusal (&EnumValuesSurfaceRefusal())[6] {
|
||||
inline const SurfaceRefusal (&EnumValuesSurfaceRefusal())[5] {
|
||||
static const SurfaceRefusal values[] = {
|
||||
SurfaceRefusal::None,
|
||||
SurfaceRefusal::NoServerDisplay,
|
||||
SurfaceRefusal::NoServerWindow,
|
||||
SurfaceRefusal::SurfaceModeMismatch,
|
||||
SurfaceRefusal::ServerOwnedOnSetWindowHandle,
|
||||
SurfaceRefusal::HostFrameOnSetWindowHandle
|
||||
SurfaceRefusal::ServerOwnedOnSetWindowHandle
|
||||
};
|
||||
return values;
|
||||
}
|
||||
|
||||
inline const char * const *EnumNamesSurfaceRefusal() {
|
||||
static const char * const names[7] = {
|
||||
static const char * const names[6] = {
|
||||
"None",
|
||||
"NoServerDisplay",
|
||||
"NoServerWindow",
|
||||
"SurfaceModeMismatch",
|
||||
"ServerOwnedOnSetWindowHandle",
|
||||
"HostFrameOnSetWindowHandle",
|
||||
nullptr
|
||||
};
|
||||
return names;
|
||||
}
|
||||
|
||||
inline const char *EnumNameSurfaceRefusal(SurfaceRefusal e) {
|
||||
if (::flatbuffers::IsOutRange(e, SurfaceRefusal::None, SurfaceRefusal::HostFrameOnSetWindowHandle)) return "";
|
||||
if (::flatbuffers::IsOutRange(e, SurfaceRefusal::None, SurfaceRefusal::ServerOwnedOnSetWindowHandle)) return "";
|
||||
const size_t index = static_cast<size_t>(e);
|
||||
return EnumNamesSurfaceRefusal()[index];
|
||||
}
|
||||
@@ -1815,7 +1815,9 @@ struct SurfaceOp FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table {
|
||||
VT_HEIGHT = 18,
|
||||
VT_SWAPINTERVAL = 20,
|
||||
VT_READSURFACE = 22,
|
||||
VT_CONTEXT = 24
|
||||
VT_CONTEXT = 24,
|
||||
VT_SHAREGROUPTOKEN = 26,
|
||||
VT_CONTEXTFLAGS = 28
|
||||
};
|
||||
uint64_t seq() const {
|
||||
return GetField<uint64_t>(VT_SEQ, 0);
|
||||
@@ -1850,6 +1852,12 @@ struct SurfaceOp FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table {
|
||||
uint64_t context() const {
|
||||
return GetField<uint64_t>(VT_CONTEXT, 0);
|
||||
}
|
||||
uint64_t shareGroupToken() const {
|
||||
return GetField<uint64_t>(VT_SHAREGROUPTOKEN, 0);
|
||||
}
|
||||
uint32_t contextFlags() const {
|
||||
return GetField<uint32_t>(VT_CONTEXTFLAGS, 0);
|
||||
}
|
||||
template <bool B = false>
|
||||
bool Verify(::flatbuffers::VerifierTemplate<B> &verifier) const {
|
||||
return VerifyTableStart(verifier) &&
|
||||
@@ -1864,6 +1872,8 @@ struct SurfaceOp FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table {
|
||||
VerifyField<int32_t>(verifier, VT_SWAPINTERVAL, 4) &&
|
||||
VerifyField<uint64_t>(verifier, VT_READSURFACE, 8) &&
|
||||
VerifyField<uint64_t>(verifier, VT_CONTEXT, 8) &&
|
||||
VerifyField<uint64_t>(verifier, VT_SHAREGROUPTOKEN, 8) &&
|
||||
VerifyField<uint32_t>(verifier, VT_CONTEXTFLAGS, 4) &&
|
||||
verifier.EndTable();
|
||||
}
|
||||
};
|
||||
@@ -1905,6 +1915,12 @@ struct SurfaceOpBuilder {
|
||||
void add_context(uint64_t context) {
|
||||
fbb_.AddElement<uint64_t>(SurfaceOp::VT_CONTEXT, context, 0);
|
||||
}
|
||||
void add_shareGroupToken(uint64_t shareGroupToken) {
|
||||
fbb_.AddElement<uint64_t>(SurfaceOp::VT_SHAREGROUPTOKEN, shareGroupToken, 0);
|
||||
}
|
||||
void add_contextFlags(uint32_t contextFlags) {
|
||||
fbb_.AddElement<uint32_t>(SurfaceOp::VT_CONTEXTFLAGS, contextFlags, 0);
|
||||
}
|
||||
explicit SurfaceOpBuilder(::flatbuffers::FlatBufferBuilder &_fbb)
|
||||
: fbb_(_fbb) {
|
||||
start_ = fbb_.StartTable();
|
||||
@@ -1928,14 +1944,18 @@ inline ::flatbuffers::Offset<SurfaceOp> CreateSurfaceOp(
|
||||
int32_t height = 0,
|
||||
int32_t swapInterval = 0,
|
||||
uint64_t readSurface = 0,
|
||||
uint64_t context = 0) {
|
||||
uint64_t context = 0,
|
||||
uint64_t shareGroupToken = 0,
|
||||
uint32_t contextFlags = 0) {
|
||||
SurfaceOpBuilder builder_(_fbb);
|
||||
builder_.add_shareGroupToken(shareGroupToken);
|
||||
builder_.add_context(context);
|
||||
builder_.add_readSurface(readSurface);
|
||||
builder_.add_nativeToken(nativeToken);
|
||||
builder_.add_surface(surface);
|
||||
builder_.add_display(display);
|
||||
builder_.add_seq(seq);
|
||||
builder_.add_contextFlags(contextFlags);
|
||||
builder_.add_swapInterval(swapInterval);
|
||||
builder_.add_height(height);
|
||||
builder_.add_width(width);
|
||||
|
||||
@@ -70,7 +70,9 @@ extern "C" {
|
||||
// 4 P11 PAIR: the PairBind message - a socket client's control and aux connections pair by
|
||||
// the nonce each presents first, not by arrival order.
|
||||
// 5 P11 B2: LinkTerms.adoptTier - the client's persistent-map adoption tier ask (T0 or T2).
|
||||
#define MOBILEGL_PROTOCOL_CONTROL_REVISION 5
|
||||
// 6 P14 S1 (docs/Disaggregated/design/11-state-ownership.md): SurfaceOpKind.CreateContext /
|
||||
// DestroyContext, plus SurfaceOp.shareGroupToken and SurfaceOp.contextFlags.
|
||||
#define MOBILEGL_PROTOCOL_CONTROL_REVISION 6
|
||||
|
||||
#define MOBILEGL_ABI_VERSION(major, minor) (((uint32_t)(major) << 16) | (uint32_t)(minor))
|
||||
#define MOBILEGL_ABI_MAJOR_OF(version) ((uint32_t)(version) >> 16)
|
||||
|
||||
@@ -256,6 +256,25 @@ enum SurfaceOpKind : ubyte {
|
||||
// (Client/BackendObject_Remote.cpp). Without the tag the codec refused it by
|
||||
// name and every spawned eglMakeCurrent failed with InprocOnlyOpOnTheWire.
|
||||
InitCapabilities = 11,
|
||||
// P14 S1 (docs/Disaggregated/design/11-state-ownership.md). THE EGL CONTEXT LIFECYCLE, as two
|
||||
// more ops on the same frame the nine surface ops ride - the shape §"wire changes" 2 prescribes,
|
||||
// and deliberately NOT two new CtrlMsg tables: a context is created, destroyed and made current
|
||||
// by the SAME caller on the SAME thread as a surface, through the same blocking frame channel,
|
||||
// and a second channel would only be a second place for the two orderings to disagree.
|
||||
//
|
||||
// CreateContext `context` is the clientContextToken EGLState minted, `shareGroupToken` the
|
||||
// group it was derived into (the sharing context's group, or a fresh one),
|
||||
// `contextFlags` the frame's reserved extension word (0 today). `display` and
|
||||
// `surface` are 0: a context is display-scoped in EGL but the server's display
|
||||
// is the session's own, so nothing is named.
|
||||
// DestroyContext `context` is the token to drop. The server forgets it and, if it was the
|
||||
// bound one, unbinds it.
|
||||
//
|
||||
// Both are answered by the ordinary SurfaceReply (ok, plus the refusal enum) - S1 creates a
|
||||
// PLACEHOLDER runtime (token, share group, flags) and no native context, so there is nothing
|
||||
// for the reply to carry that a Bool does not say already.
|
||||
CreateContext = 12,
|
||||
DestroyContext = 13,
|
||||
}
|
||||
|
||||
enum WindowKind : ubyte {
|
||||
@@ -274,12 +293,6 @@ enum WindowKind : ubyte {
|
||||
// SurfaceView) and has none of its own to name, so `nativeToken` is always 0 and no pointer
|
||||
// crosses (Rule G/H). Legal on CreateWindowSurface only; SetWindowHandle may not name it.
|
||||
ServerOwned = 7,
|
||||
// P12, appended: the OTHER on-screen shape, and its mirror image. The client names no
|
||||
// window here either - but the frames are the DISPLAY HOST's: it allocates them, offers
|
||||
// each one over the host frame bridge, and puts them on the glass itself, while the
|
||||
// server draws into them. `nativeToken` is always 0, as for ServerOwned, and it is legal
|
||||
// on CreateWindowSurface only.
|
||||
HostFrame = 8,
|
||||
}
|
||||
|
||||
// P12, appended: WHY A SURFACE OP WAS DECLINED, so the client can name the refusal in its own log
|
||||
@@ -291,7 +304,6 @@ enum SurfaceRefusal : ubyte {
|
||||
NoServerWindow = 2, // the server owns a display, but no window came within its wait
|
||||
SurfaceModeMismatch = 3, // the session's surface mode (on-screen / offscreen) is the other one
|
||||
ServerOwnedOnSetWindowHandle = 4, // SetWindowHandle named the server's own window
|
||||
HostFrameOnSetWindowHandle = 5, // SetWindowHandle named the display host's frames
|
||||
}
|
||||
|
||||
table SurfaceOp {
|
||||
@@ -310,6 +322,12 @@ table SurfaceOp {
|
||||
// ("no surface" / "no context") for every other op and for a ReleaseCurrent.
|
||||
readSurface: ulong;
|
||||
context: ulong;
|
||||
// P14 S1, appended (a FlatBuffers table field's id IS its vtable slot - append only). The two
|
||||
// values CreateContext carries beyond the token itself: the share group the new context was
|
||||
// derived into, and a reserved flags word so a later context attribute (a profile, a robustness
|
||||
// ask) has a slot to land in without moving the fields beside it. 0 on every other op.
|
||||
shareGroupToken: ulong;
|
||||
contextFlags: uint;
|
||||
}
|
||||
|
||||
table SurfaceReply {
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
// SPDX-License-Identifier: LGPL-3.0-only
|
||||
#include "EmbeddedServer.h"
|
||||
#include "ServerDisplay.h"
|
||||
|
||||
#if defined(__ANDROID__)
|
||||
#include <android/native_window.h>
|
||||
#endif
|
||||
|
||||
namespace {
|
||||
using namespace MobileGL::MG_Remote::Server;
|
||||
|
||||
int DetachResult(ServerWindowDetach result) {
|
||||
switch (result) {
|
||||
case ServerWindowDetach::NoWindow: return MOBILEGL_SERVER_WINDOW_NO_WINDOW;
|
||||
case ServerWindowDetach::Released: return MOBILEGL_SERVER_WINDOW_RELEASED;
|
||||
case ServerWindowDetach::ReleasedBySession: return MOBILEGL_SERVER_WINDOW_RELEASED_BY_SESSION;
|
||||
case ServerWindowDetach::TimedOut: return MOBILEGL_SERVER_WINDOW_TIMED_OUT;
|
||||
}
|
||||
return MOBILEGL_SERVER_WINDOW_TIMED_OUT;
|
||||
}
|
||||
}
|
||||
|
||||
extern "C" int mobilegl_server_display_install(const struct mobilegl_server_display_hooks* hooks) {
|
||||
if (hooks == nullptr || hooks->acquire == nullptr || hooks->release == nullptr)
|
||||
return MOBILEGL_SERVER_DISPLAY_INVALID_ARGUMENT;
|
||||
auto& display = ServerDisplayInstance();
|
||||
if (display.HasDisplay() || display.Attached() || display.Leased())
|
||||
return MOBILEGL_SERVER_DISPLAY_ALREADY_INSTALLED;
|
||||
ServerDisplayHooks nativeHooks;
|
||||
nativeHooks.acquire = hooks->acquire;
|
||||
nativeHooks.release = hooks->release;
|
||||
nativeHooks.requestGeometry = hooks->request_geometry;
|
||||
nativeHooks.user = hooks->user;
|
||||
display.Install(nativeHooks);
|
||||
return MOBILEGL_SERVER_DISPLAY_OK;
|
||||
}
|
||||
|
||||
extern "C" int mobilegl_server_display_install_android(mobilegl_server_geometry_callback request_geometry, void* user) {
|
||||
#if defined(__ANDROID__)
|
||||
const auto androidHooks = AndroidNativeWindowHooks(request_geometry, user);
|
||||
const mobilegl_server_display_hooks hooks{androidHooks.acquire, androidHooks.release,
|
||||
androidHooks.requestGeometry, androidHooks.user};
|
||||
return mobilegl_server_display_install(&hooks);
|
||||
#else
|
||||
(void)request_geometry;
|
||||
(void)user;
|
||||
return MOBILEGL_SERVER_DISPLAY_UNSUPPORTED_PLATFORM;
|
||||
#endif
|
||||
}
|
||||
|
||||
extern "C" int mobilegl_server_display_attach(void* window, uint32_t width, uint32_t height) {
|
||||
if (window == nullptr) return MOBILEGL_SERVER_DISPLAY_INVALID_ARGUMENT;
|
||||
auto& display = ServerDisplayInstance();
|
||||
if (!display.HasDisplay()) return MOBILEGL_SERVER_DISPLAY_NOT_INSTALLED;
|
||||
display.Attach(window, width, height);
|
||||
return MOBILEGL_SERVER_DISPLAY_OK;
|
||||
}
|
||||
|
||||
extern "C" int mobilegl_server_display_attach_android(struct ANativeWindow* window, uint32_t width, uint32_t height) {
|
||||
#if defined(__ANDROID__)
|
||||
if (window == nullptr) return MOBILEGL_SERVER_DISPLAY_INVALID_ARGUMENT;
|
||||
if (width == 0) {
|
||||
const int32_t actual = ANativeWindow_getWidth(window);
|
||||
if (actual > 0) width = static_cast<uint32_t>(actual);
|
||||
}
|
||||
if (height == 0) {
|
||||
const int32_t actual = ANativeWindow_getHeight(window);
|
||||
if (actual > 0) height = static_cast<uint32_t>(actual);
|
||||
}
|
||||
return mobilegl_server_display_attach(window, width, height);
|
||||
#else
|
||||
(void)window;
|
||||
(void)width;
|
||||
(void)height;
|
||||
return MOBILEGL_SERVER_DISPLAY_UNSUPPORTED_PLATFORM;
|
||||
#endif
|
||||
}
|
||||
|
||||
extern "C" int mobilegl_server_display_detach(uint32_t timeout_ms) {
|
||||
return DetachResult(ServerDisplayInstance().Detach(timeout_ms));
|
||||
}
|
||||
|
||||
extern "C" int mobilegl_server_display_uninstall(uint32_t timeout_ms) {
|
||||
auto& display = ServerDisplayInstance();
|
||||
const int result = DetachResult(display.Detach(timeout_ms));
|
||||
// Detach has already removed the attached window even if its lease is still live. Uninstall
|
||||
// keeps the original hooks for EndLease's deferred release, without another timeout budget.
|
||||
display.Uninstall(0);
|
||||
return result;
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
// SPDX-License-Identifier: LGPL-3.0-only
|
||||
// Public C interface for an application that owns a MobileGL split server.
|
||||
#pragma once
|
||||
|
||||
#include <stdint.h>
|
||||
|
||||
#if defined(_WIN32)
|
||||
#define MOBILEGL_SERVER_EXPORT
|
||||
#else
|
||||
#define MOBILEGL_SERVER_EXPORT __attribute__((visibility("default")))
|
||||
#endif
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
struct ANativeWindow;
|
||||
|
||||
typedef void (*mobilegl_server_geometry_callback)(void* user, uint32_t width, uint32_t height);
|
||||
|
||||
// Opaque-window hooks also let non-Android hosts embed the display without depending on
|
||||
// MobileGL's C++ headers. Both reference callbacks are required. Geometry may be null.
|
||||
struct mobilegl_server_display_hooks {
|
||||
void (*acquire)(void* user, void* window);
|
||||
void (*release)(void* user, void* window);
|
||||
mobilegl_server_geometry_callback request_geometry;
|
||||
void* user;
|
||||
};
|
||||
|
||||
enum mobilegl_server_display_result {
|
||||
MOBILEGL_SERVER_DISPLAY_OK = 0,
|
||||
MOBILEGL_SERVER_DISPLAY_INVALID_ARGUMENT = -1,
|
||||
MOBILEGL_SERVER_DISPLAY_ALREADY_INSTALLED = -2,
|
||||
MOBILEGL_SERVER_DISPLAY_NOT_INSTALLED = -3,
|
||||
MOBILEGL_SERVER_DISPLAY_UNSUPPORTED_PLATFORM = -4
|
||||
};
|
||||
|
||||
enum mobilegl_server_window_detach {
|
||||
MOBILEGL_SERVER_WINDOW_NO_WINDOW = 0,
|
||||
MOBILEGL_SERVER_WINDOW_RELEASED = 1,
|
||||
MOBILEGL_SERVER_WINDOW_RELEASED_BY_SESSION = 2,
|
||||
MOBILEGL_SERVER_WINDOW_TIMED_OUT = 3
|
||||
};
|
||||
|
||||
// Install once before serving; owner lifecycle calls must be serialized. A live display or
|
||||
// an old lease awaiting release refuses a replacement, so its window always uses its original
|
||||
// reference hooks. The geometry callback runs on the apply thread and must return promptly.
|
||||
// A positive size requests fixed buffer dimensions; 0/0 requests the host's layout dimensions.
|
||||
// Report the resulting dimensions with attach, for example from SurfaceHolder.surfaceChanged.
|
||||
// Callback user data must live until uninstall has returned and any timed-out lease has ended.
|
||||
MOBILEGL_SERVER_EXPORT int mobilegl_server_display_install(const struct mobilegl_server_display_hooks* hooks);
|
||||
MOBILEGL_SERVER_EXPORT int mobilegl_server_display_install_android(mobilegl_server_geometry_callback request_geometry,
|
||||
void* user);
|
||||
|
||||
// Attach retains its own reference. Attaching the same window updates its dimensions without
|
||||
// another retain. A different window detaches the previous one first (up to 3 seconds).
|
||||
// Android attach uses ANativeWindow_getWidth/Height for zero dimensions; the caller may release
|
||||
// its ANativeWindow_fromSurface reference immediately after this call.
|
||||
MOBILEGL_SERVER_EXPORT int mobilegl_server_display_attach(void* window, uint32_t width, uint32_t height);
|
||||
MOBILEGL_SERVER_EXPORT int mobilegl_server_display_attach_android(struct ANativeWindow* window, uint32_t width,
|
||||
uint32_t height);
|
||||
|
||||
// Returns mobilegl_server_window_detach. A timeout never drops a reference while the backend
|
||||
// is rendering: release happens when the apply thread ends its lease. Surface loss currently
|
||||
// ends the live split session; a fresh client session can use a newly attached window.
|
||||
MOBILEGL_SERVER_EXPORT int mobilegl_server_display_detach(uint32_t timeout_ms);
|
||||
MOBILEGL_SERVER_EXPORT int mobilegl_server_display_uninstall(uint32_t timeout_ms);
|
||||
|
||||
// Blocking serve on the caller's thread; stop is non-blocking and safe on the UI thread.
|
||||
// Endpoint: filesystem path, @abstract AF_UNIX name (SCM_RIGHTS + shared-memory rings), or
|
||||
// tcp://host:port. One client session per process; independent workers need distinct endpoints.
|
||||
// Before loading libMobileGL set MOBILEGL_IPC_ROLE=server and MOBILEGL_IPC_DIAL=no, and unset
|
||||
// MOBILEGL_TRANSPORT, MOBILEGL_IPC_SERVER_PATH, MOBILEGL_IPC_RING_MB, MOBILEGL_IPC_STAGE_MB.
|
||||
MOBILEGL_SERVER_EXPORT int mobilegl_server_serve_inprocess(const char* endpoint);
|
||||
MOBILEGL_SERVER_EXPORT void mobilegl_server_stop_inprocess(void);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
@@ -404,15 +404,6 @@ namespace MobileGL::MG_Remote::Server {
|
||||
// was wanted, recorded here so a future swap-without-present is looked for rather than
|
||||
// assumed impossible. Presents() is exposed for a lane that wants to make the comparison.
|
||||
table->Present();
|
||||
// A HOST-FRAMED SURFACE IS PRESENTED BY TELLING THE HOST, not by the swap above (which
|
||||
// swaps the pbuffer the context was made with). BackendObject::SwapEGLBuffers is the
|
||||
// only other route to PresentHostFrame and a split client never reaches it, so this is
|
||||
// where the display host learns the frame is drawn - before the credit goes back, so a
|
||||
// client released by it is released by a frame that is on its way to the glass.
|
||||
if (m_backend != nullptr) {
|
||||
if (!m_backend->PresentHostFrameIfCurrent())
|
||||
MGLOG_E_ONCE("OnPresent: the host frame was not presented (PresentHostFrame failed; see above)");
|
||||
}
|
||||
++m_presents;
|
||||
// FrameSerial 0 means "the server stamps its own" (c1-v1 8.3): P5 has no client-side
|
||||
// present credit, so the client sends 0 and the frame count on this side IS the serial.
|
||||
@@ -1471,6 +1462,53 @@ namespace MobileGL::MG_Remote::Server {
|
||||
return true;
|
||||
}
|
||||
|
||||
// P14 S1. THE RING'S DOOR INTO THE SESSION'S CONTEXT TABLE.
|
||||
//
|
||||
// The record carries the client's current context token and this is where a session's
|
||||
// attribution moves. It is deliberately NOT an assertion like OnApplierReset's serial: the
|
||||
// client's EGL layer mints the token and the server has no second count to compare against,
|
||||
// so what is checked is a FACT ABOUT THIS SESSION'S OWN TABLE - a token that CreateContext
|
||||
// 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::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
|
||||
// session there is nothing to attribute the record to and nothing to refuse. (The window
|
||||
// is Close() clearing the active session while the apply thread is still draining.)
|
||||
ServerSession* session = ServerSession::Active();
|
||||
if (session == nullptr) return false;
|
||||
// PH-1 (3): the refusal latches in an armed session child (the peer wrote the token);
|
||||
// unarmed it dies, like every other contract fact about a peer.
|
||||
if (!session->BindContext(bind.ClientContextToken)) {
|
||||
return SessionLatch(MGFatalFamily::ProtocolCorruption, "MGPipe: Fatal{ProtocolCorruption, \"BindContext.ClientContextToken\"} - the "
|
||||
"record binds token %llu, which this session never created; a bind_context "
|
||||
"names a context CreateContext put in the session's table, and 0 (the "
|
||||
"release) is the only token that needs no entry",
|
||||
static_cast<unsigned long long>(bind.ClientContextToken));
|
||||
}
|
||||
++m_bindContexts;
|
||||
#if MOBILEGL_BUILD_DISAGGREGATED
|
||||
// P14 S4 (docs/Disaggregated/design/11-state-ownership.md). THE NATIVE HALF OF THE SWITCH.
|
||||
//
|
||||
// `bind_context` is where the session's context attribution moves, and it is also the ONLY
|
||||
// point at which the apply thread's native context may move: the MakeCurrent control frame
|
||||
// that precedes it still carries the OLD context (the client emits the binding after the
|
||||
// binding has taken effect, which is the ordering S1 chose on purpose), so a native switch
|
||||
// driven from there would bind the context the client just left. Frontend GL state is the
|
||||
// backend's per-tuple business; this call makes the tuple the resolver now names current.
|
||||
//
|
||||
// It is a no-op for the shapes S4 did not change: with no resolver installed (monolith, a
|
||||
// unit case, the inproc one-process shape) the key is {0,0}, and the single-context world's
|
||||
// bind does not move the native context - MakeNativeContextCurrentForBoundToken returns
|
||||
// without a driver call when the context it resolves to is already the one bound here.
|
||||
if (MG_Config::Transport != MG_Config::TransportMode::Monolith) {
|
||||
(void)MG_Backend::DirectGLES::MakeNativeContextCurrentForBoundToken();
|
||||
}
|
||||
#endif
|
||||
return true;
|
||||
}
|
||||
|
||||
Bool ServerVerbSink::OnObjectDeath(const MG_Pipe::MGPHandleOnly& death) {
|
||||
// §1's zero ruling: a null handle means "the object never crossed", and the client
|
||||
// emits NOTHING in that case (§5.2) - so a null handle arriving here is corruption,
|
||||
|
||||
@@ -245,11 +245,21 @@ namespace MobileGL::MG_Remote::Server {
|
||||
Bool OnApplierReset(const MG_Pipe::MGPApplierReset& reset) override;
|
||||
Bool OnObjectDeath(const MG_Pipe::MGPHandleOnly& death) override;
|
||||
|
||||
// ---- P14 S1 (docs/Disaggregated/design/11-state-ownership.md): bind_context, opcode 84.
|
||||
//
|
||||
// The session's current context token becomes the record's, on the apply thread. Unlike
|
||||
// OnApplierReset's serial the token is NOT an assertion about a count the two ends both
|
||||
// hold - the client mints it and the server keeps the table CreateContext built - so the
|
||||
// refusal here is "this session never created that token", a named ProtocolCorruption
|
||||
// rather than a silent bind. Token 0 (the release) is always legal.
|
||||
Bool OnBindContext(const MG_Pipe::MGPBindContext& bind) 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.
|
||||
Uint64 ApplierResets() const { return m_applierResets; }
|
||||
Uint64 ObjectDeaths() const { return m_objectDeaths; }
|
||||
Uint64 BindContexts() const { return m_bindContexts; }
|
||||
// The ContextSerial the NEXT applier_reset record must carry. Exposed so a case can
|
||||
// assert the sequence rather than only the count.
|
||||
Uint64 ExpectedApplierResetSerial() const { return m_applierResetSerial; }
|
||||
@@ -377,6 +387,11 @@ namespace MobileGL::MG_Remote::Server {
|
||||
Uint64 m_applierResetSerial = 0;
|
||||
Uint64 m_applierResets = 0;
|
||||
Uint64 m_objectDeaths = 0;
|
||||
// P14 S1. BindContexts counts the records the sink dispatched and bound on the session;
|
||||
// the token itself lives on the session (ServerSession::CurrentContextToken), which is
|
||||
// the object the control plane's CreateContext/DestroyContext also own - one table, one
|
||||
// owner, and the sink is only the ring's door into it.
|
||||
Uint64 m_bindContexts = 0;
|
||||
// ReadPixels' destination. The pixels go into the reply slot, but GLFunctionsTable::
|
||||
// ReadPixels writes into a caller buffer, so one staging vector per session sits
|
||||
// between them. Grown, never shrunk, and never handed out past the call.
|
||||
|
||||
@@ -82,7 +82,10 @@ namespace MobileGL::MG_Remote::Server {
|
||||
NoWindow, // a display, but no window was attached within the wait
|
||||
Cancelled, // the caller's cancel predicate said so
|
||||
Interrupted, // Interrupt() (the in-process server is stopping)
|
||||
LeasedElsewhere, // another holder has the window (sessions are sequential: a bug if seen)
|
||||
// P14 S2: NOT A BUG ANY MORE. Several sessions share one process and the display's window
|
||||
// is one window, so a second ON-SCREEN session asking for it is refused by name here
|
||||
// (ServerLoop logs the holder); offscreen sessions take no lease and are unaffected.
|
||||
LeasedElsewhere, // another session in this process holds the window: see the note above
|
||||
};
|
||||
|
||||
enum class ServerWindowDetach : Uint8 {
|
||||
|
||||
@@ -10,12 +10,14 @@
|
||||
|
||||
#include "ServerLoop.h"
|
||||
#include "ApplyThreadPolicy.h"
|
||||
#include "SessionRuntime.h"
|
||||
#include <MG_Remote/FatalFunnel.h>
|
||||
#include <MG_Remote/Transport/LinkMetrics.h>
|
||||
#include <MG_Backend/MGPipe/PipeInputs.h>
|
||||
|
||||
#include <Config.h>
|
||||
#include <MG_Backend/BackendObjects.h>
|
||||
#include <MG_Backend/DirectGLES/DirectGLES.h>
|
||||
#include <MG_Util/Debug/Log.h>
|
||||
#include <MG_Util/Metrics/PipeStats.h>
|
||||
|
||||
@@ -284,10 +286,11 @@ namespace MobileGL::MG_Remote::Server {
|
||||
m_haveCurrentTuple = false;
|
||||
// P12 (D4, D6): a new session decides its own surface mode, holds no window lease yet and
|
||||
// has no window-lost request pending. The apply thread that reads these is not started yet.
|
||||
// P14 S2: and it is THIS session's latch - the loop is the session's, so a second session
|
||||
// in the same process starts here too and neither's first surface decides the other's.
|
||||
m_surfaceMode = SessionSurfaceMode::None;
|
||||
m_holdsWindowLease = false;
|
||||
m_serverOwnedSurfaces.clear();
|
||||
m_hostFrameSurfaces.clear();
|
||||
m_windowLostRequested.store(false, std::memory_order_release);
|
||||
m_serverWindowsLost.store(0, std::memory_order_release);
|
||||
m_testLogFloodLines = ApplyLogFloodLinesForTest();
|
||||
@@ -346,6 +349,11 @@ namespace MobileGL::MG_Remote::Server {
|
||||
// Apply thread only (RunSurfaceControlFrame's dispatch put us here), so
|
||||
// m_haveCurrentTuple/m_cur* need no
|
||||
// lock. The counters are atomic for the reader on the test thread.
|
||||
//
|
||||
// P14 S4 left this classification alone on purpose - ServerLoop.h states the argument (the
|
||||
// currently bound tuple IS the unit ID-67 is about, and only one EGLContext can be current on
|
||||
// this thread). What S4 changed is one layer down: the tuple now names the (session, context)
|
||||
// registry's native context instead of the process's one.
|
||||
MakeCurrentOutcome outcome;
|
||||
const EglBindAction action = ClassifyEglMakeCurrent(m_haveCurrentTuple, m_curDpy, m_curDraw,
|
||||
m_curRead, m_curCtx, dpy, draw, read, ctx);
|
||||
@@ -410,9 +418,18 @@ namespace MobileGL::MG_Remote::Server {
|
||||
// THE IDENTITY IS PUBLISHED FIRST, BEFORE THE THREAD HAS A NAME OR AN AFFINITY. Every
|
||||
// role guard in the tree reads it, and the very first record this thread applies must
|
||||
// already answer "yes" to OnApplyThread() - otherwise the applier's own reads would
|
||||
// look like client reads to the guards. Relaxed for the reason stated beside the key's
|
||||
// declaration: it is an identity, not a handshake, and this thread is the only writer.
|
||||
Detail::g_applyThreadKey.store(Detail::CurrentThreadKey(), std::memory_order_relaxed);
|
||||
// look like client reads to the guards.
|
||||
//
|
||||
// P14 S2: two words, both about THIS thread. t_onApplyThread is the guard's answer; the
|
||||
// process counter beside it is what MG_Backend/DirectGLES/Managers.cpp reads as "an apply
|
||||
// thread is running" (ServerLoop.h's block). The scope is opened BEFORE either, because
|
||||
// every read below - the session's peer, its rings, the applier it attaches - must already
|
||||
// resolve to this session rather than to the process's default.
|
||||
ServerSession& session = *m_session;
|
||||
std::unique_ptr<Detail::ThreadSessionScope> scope;
|
||||
if (m_runtime != nullptr) scope = std::make_unique<Detail::ThreadSessionScope>(*m_runtime);
|
||||
Detail::t_onApplyThread = true;
|
||||
Detail::g_applyThreadKey.fetch_add(1, std::memory_order_relaxed);
|
||||
NameThisThread("mgl-srv-apply");
|
||||
// P6: THIS THREAD IS THE SERVER, and saying so is what sends its lines to the server's
|
||||
// own log. Under spawn the process role already answers this; under INPROC it is the
|
||||
@@ -427,7 +444,6 @@ namespace MobileGL::MG_Remote::Server {
|
||||
// "an affinity that silently did nothing looks exactly like one that worked"
|
||||
// (CONTRACT-P5 5). P11 B1: `auto` now depends on who the client is (ApplyThreadPolicy.h),
|
||||
// and so does the spin before each park.
|
||||
ServerSession& session = *m_session;
|
||||
const char* raw = AffinityStringFromConfig();
|
||||
const Bool automatic = raw == nullptr || raw[0] == '\0' || std::strcmp(raw, "auto") == 0;
|
||||
Uint64 bigCores = 0, primeCores = 0;
|
||||
@@ -692,7 +708,12 @@ namespace MobileGL::MG_Remote::Server {
|
||||
// thread could ever give. The integration lane - a real EGL teardown - is the only
|
||||
// thing that would catch that, and it would catch it as a hang, not as a failed
|
||||
// assertion.
|
||||
Detail::g_applyThreadKey.store(0, std::memory_order_relaxed);
|
||||
//
|
||||
// P14 S2: the guard's own word is lowered here too, and for the same reason - with
|
||||
// N sessions it can only ever have been this thread's, and the thread is about to
|
||||
// stop being an apply thread. The scope is destroyed by this function's frame.
|
||||
Detail::t_onApplyThread = false;
|
||||
Detail::g_applyThreadKey.fetch_sub(1, std::memory_order_relaxed);
|
||||
}
|
||||
m_controlDone.notify_all();
|
||||
|
||||
@@ -1190,6 +1211,10 @@ namespace MobileGL::MG_Remote::Server {
|
||||
}
|
||||
|
||||
ServerLoop& ServerLoopInstance() {
|
||||
// P14 S2: the session of the CALLING THREAD, else the process's one instance. The client
|
||||
// process (the forwarders, whose sink makes them cross the wire), the inproc one-process
|
||||
// client+server shape and every unit case have no thread session and keep this instance.
|
||||
if (ServerLoop* const own = Detail::CurrentLoop()) return *own;
|
||||
// ID-8: leak at exit, like every MG_Remote singleton.
|
||||
static ServerLoop& instance = *new ServerLoop{};
|
||||
return instance;
|
||||
@@ -1339,8 +1364,6 @@ namespace MobileGL::MG_Remote::Server {
|
||||
// P12 (D3): the SERVER's window, asked for by a headless client. Before the unpack,
|
||||
// which would refuse the frame-local tag as a WindowBackend out of range.
|
||||
if (frame.windowBackend == kServerOwnedWindowBackend) return ApplyServerOwnedWindowSurface(backend, frame);
|
||||
// The mirror image: the frames are the display host's, and it presents them.
|
||||
if (frame.windowBackend == kHostFrameWindowBackend) return ApplyHostFrameWindowSurface(backend, frame);
|
||||
MG_Backend::WindowHandle window;
|
||||
if (!UnpackWindowHandle(frame, &window)) {
|
||||
frame.ok = false;
|
||||
@@ -1363,7 +1386,9 @@ namespace MobileGL::MG_Remote::Server {
|
||||
return MOBILEGL_OK;
|
||||
case SurfaceControlOp::CreatePbufferSurface:
|
||||
// P12 (D4): a pbuffer in a session that went on-screen is the other mode, refused by
|
||||
// name and not latched - the session and its window surface carry on.
|
||||
// name and not latched - the session and its window surface carry on. P14 S2: the mode
|
||||
// is the session's own - latched by its first surface, on its own loop - and never
|
||||
// another session's.
|
||||
if (!SessionSurfaceModeAdmits(m_surfaceMode, /*serverOwnedWindow=*/false)) {
|
||||
frame.ok = false;
|
||||
frame.refusal = static_cast<Uint8>(SurfaceRefusalCode::SurfaceModeMismatch);
|
||||
@@ -1440,6 +1465,48 @@ namespace MobileGL::MG_Remote::Server {
|
||||
frame.ok = outcome.ok;
|
||||
return MOBILEGL_OK;
|
||||
}
|
||||
case SurfaceControlOp::CreateContext: {
|
||||
// P14 S1 built the session's table entry; P14 S4 gives it its NATIVE context. The
|
||||
// share group is what makes two client contexts see one set of buffer/texture objects:
|
||||
// a group whose leader already has a native EGLContext hands it to eglCreateContext as
|
||||
// the share argument, so this arm is the whole of "server-side sharing".
|
||||
//
|
||||
// An `ok = false` here is a named refusal the client's eglCreateContext turns into
|
||||
// EGL_NO_CONTEXT, which is what a server that declined to table the token must produce -
|
||||
// a token the server never heard of is worse than no context at all. A native context
|
||||
// that could not be built rolls the table entry back, or the session would hold a token
|
||||
// whose every MakeCurrent fails one layer down.
|
||||
ServerSession* session = ServerSession::Active();
|
||||
if (session == nullptr) {
|
||||
frame.ok = false;
|
||||
return MOBILEGL_ERR_NOT_INITIALIZED;
|
||||
}
|
||||
frame.ok = session->CreateContext(frame.context, frame.shareGroupToken, frame.contextFlags);
|
||||
if (frame.ok && backend != nullptr &&
|
||||
backend->GetBackendType() == BackendType::DirectGLES) {
|
||||
if (!MG_Backend::DirectGLES::CreateNativeContextFor(frame.context, frame.shareGroupToken)) {
|
||||
(void)session->DestroyContext(frame.context);
|
||||
frame.ok = false;
|
||||
}
|
||||
}
|
||||
return MOBILEGL_OK;
|
||||
}
|
||||
case SurfaceControlOp::DestroyContext: {
|
||||
ServerSession* session = ServerSession::Active();
|
||||
if (session == nullptr) {
|
||||
frame.ok = false;
|
||||
return MOBILEGL_ERR_NOT_INITIALIZED;
|
||||
}
|
||||
frame.ok = session->DestroyContext(frame.context);
|
||||
// P14 S4: the native context goes with the entry, and ONLY that one - the session's
|
||||
// other contexts, and every other session's, are untouched. The display is terminated
|
||||
// only when the last native context in the process has gone.
|
||||
if (frame.ok && backend != nullptr &&
|
||||
backend->GetBackendType() == BackendType::DirectGLES) {
|
||||
MG_Backend::DirectGLES::DestroyNativeContextFor(frame.context);
|
||||
}
|
||||
return MOBILEGL_OK;
|
||||
}
|
||||
case SurfaceControlOp::SetSwapInterval:
|
||||
backend->SetEGLSwapInterval(frame.swapInterval);
|
||||
frame.ok = true;
|
||||
@@ -1448,7 +1515,6 @@ namespace MobileGL::MG_Remote::Server {
|
||||
const EGLSurface surface = HandleFromToken<EGLSurface>(frame.surface);
|
||||
backend->ReleaseEGLSurface(surface);
|
||||
ForgetServerOwnedSurface(surface);
|
||||
ForgetHostFrameSurface(surface);
|
||||
// N-3: a released surface the held tuple names may have taken the context with it
|
||||
// (BackendObject::ReleaseEGLSurface -> OnEGLSurfaceReleased -> DestroyEGLContext once
|
||||
// nothing holds it current). Forgetting when the base class only DEFERRED the destroy
|
||||
@@ -1594,10 +1660,17 @@ namespace MobileGL::MG_Remote::Server {
|
||||
break;
|
||||
}
|
||||
if (refusal != nullptr) *refusal = SurfaceRefusalCode::NoServerWindow;
|
||||
// P14 S2: LeasedElsewhere IS NOT A BUG ANY MORE. The display's window has one holder at a
|
||||
// time and a session per holder, so a second ON-SCREEN session asking for it is refused -
|
||||
// by name, not latched, exactly as a display with no window up. Offscreen (pbuffer)
|
||||
// sessions take no lease at all and are unaffected.
|
||||
MGLOG_E("MG_Remote server: Refuse ServerOwned: this server owns a display but no window for a %ux%u surface "
|
||||
"(%s after at most %u ms) - the display's surface is not up. Refused (NoServerWindow); the "
|
||||
"session is not latched",
|
||||
width, height, ServerWindowAcquireName(acquired), timeoutMs);
|
||||
"(%s after at most %u ms)%s. Refused (NoServerWindow); the session is not latched",
|
||||
width, height, ServerWindowAcquireName(acquired), timeoutMs,
|
||||
acquired == ServerWindowAcquire::LeasedElsewhere
|
||||
? " - the server's window is leased by another session, and one on-screen session at a time is "
|
||||
"the display's own rule"
|
||||
: " - the display's surface is not up");
|
||||
return MOBILEGL_ERR_TIMEOUT;
|
||||
}
|
||||
|
||||
@@ -1607,7 +1680,9 @@ namespace MobileGL::MG_Remote::Server {
|
||||
frame.refusal = static_cast<Uint8>(SurfaceRefusalCode::None);
|
||||
const Uint32 wantWidth = frame.width > 0 ? static_cast<Uint32>(frame.width) : 0u;
|
||||
const Uint32 wantHeight = frame.height > 0 ? static_cast<Uint32>(frame.height) : 0u;
|
||||
// D4 FIRST: an offscreen session may not go on-screen, display or no display.
|
||||
// D4 FIRST: an offscreen session may not go on-screen, display or no display. P14 S2: the
|
||||
// refusal is against THIS session's own latch - a second on-screen session in the same
|
||||
// process is a different refusal (no free window), never a mode mismatch.
|
||||
if (!SessionSurfaceModeAdmits(m_surfaceMode, /*serverOwnedWindow=*/true)) {
|
||||
frame.refusal = static_cast<Uint8>(SurfaceRefusalCode::SurfaceModeMismatch);
|
||||
MGLOG_E("MG_Remote server: SurfaceModeMismatch - a ServerOwned CreateWindowSurface (seq %llu, %ux%u) in a "
|
||||
@@ -1662,52 +1737,6 @@ namespace MobileGL::MG_Remote::Server {
|
||||
return MOBILEGL_OK;
|
||||
}
|
||||
|
||||
MobileGLResult ServerLoop::ApplyHostFrameWindowSurface(MG_Backend::BackendObject* backend,
|
||||
SurfaceControlFrame& frame) {
|
||||
frame.ok = false;
|
||||
frame.refusal = static_cast<Uint8>(SurfaceRefusalCode::None);
|
||||
const Uint32 wantWidth = frame.width > 0 ? static_cast<Uint32>(frame.width) : 0u;
|
||||
const Uint32 wantHeight = frame.height > 0 ? static_cast<Uint32>(frame.height) : 0u;
|
||||
// Both on-screen shapes are the same session mode: one rendering path per session, and
|
||||
// this is the on-screen one whichever side owns the window.
|
||||
if (!SessionSurfaceModeAdmits(m_surfaceMode, /*serverOwnedWindow=*/true)) {
|
||||
frame.refusal = static_cast<Uint8>(SurfaceRefusalCode::SurfaceModeMismatch);
|
||||
MGLOG_E("MG_Remote server: SurfaceModeMismatch - a HostFrame CreateWindowSurface (seq %llu, "
|
||||
"%ux%u) in a session whose surface mode is %s. Refused, the session is not latched",
|
||||
static_cast<unsigned long long>(frame.seq), wantWidth, wantHeight,
|
||||
SessionSurfaceModeName(m_surfaceMode));
|
||||
return MOBILEGL_ERR_INVALID_ARGUMENT;
|
||||
}
|
||||
const EGLSurface surface = HandleFromToken<EGLSurface>(frame.surface);
|
||||
// THE SUBSTITUTION, the other way round from ServerOwned: nothing of the client's and
|
||||
// nothing of the server's goes into the backend call - the backend takes the frames from
|
||||
// the display host, and every swap hands the next one back to it.
|
||||
frame.ok = backend->CreateEGLHostFrameSurface(surface, wantWidth, wantHeight);
|
||||
if (!frame.ok) {
|
||||
MGLOG_E("MG_Remote server: the backend could not take the display host frames (seq %llu, %ux%u)",
|
||||
static_cast<unsigned long long>(frame.seq), wantWidth, wantHeight);
|
||||
return MOBILEGL_OK;
|
||||
}
|
||||
ForgetCurrentTuple();
|
||||
m_surfaceMode = SessionSurfaceMode::OnScreen;
|
||||
if (!IsHostFrameSurface(surface)) m_hostFrameSurfaces.push_back(surface);
|
||||
frame.width = static_cast<Int>(wantWidth);
|
||||
frame.height = static_cast<Int>(wantHeight);
|
||||
MGLOG_I("MG_Remote server: surface=window %ux%u owner=host (HostFrame seq %llu)", wantWidth,
|
||||
wantHeight, static_cast<unsigned long long>(frame.seq));
|
||||
return MOBILEGL_OK;
|
||||
}
|
||||
|
||||
Bool ServerLoop::IsHostFrameSurface(EGLSurface surface) const {
|
||||
return std::find(m_hostFrameSurfaces.begin(), m_hostFrameSurfaces.end(), surface) !=
|
||||
m_hostFrameSurfaces.end();
|
||||
}
|
||||
|
||||
void ServerLoop::ForgetHostFrameSurface(EGLSurface surface) {
|
||||
m_hostFrameSurfaces.erase(std::remove(m_hostFrameSurfaces.begin(), m_hostFrameSurfaces.end(), surface),
|
||||
m_hostFrameSurfaces.end());
|
||||
}
|
||||
|
||||
Bool ServerLoop::IsServerOwnedSurface(EGLSurface surface) const {
|
||||
return std::find(m_serverOwnedSurfaces.begin(), m_serverOwnedSurfaces.end(), surface) !=
|
||||
m_serverOwnedSurfaces.end();
|
||||
@@ -1820,25 +1849,6 @@ namespace MobileGL::MG_Remote::Server {
|
||||
return rc == MOBILEGL_OK && frame.ok;
|
||||
}
|
||||
|
||||
ServerOwnedWindowReply ServerCreateHostFrameWindowSurface(EGLSurface surface, Uint32 width, Uint32 height) {
|
||||
// One frame, and no SetWindowHandle in front of it: the client names no window, and this
|
||||
// side does not make one - the frames are the display host's, taken from the bridge.
|
||||
SurfaceControlFrame frame;
|
||||
frame.kind = SurfaceControlOp::CreateWindowSurface;
|
||||
frame.surface = TokenFromHandle(surface);
|
||||
frame.windowBackend = kHostFrameWindowBackend;
|
||||
frame.nativeToken = 0;
|
||||
frame.width = static_cast<Int>(width);
|
||||
frame.height = static_cast<Int>(height);
|
||||
const MobileGLResult rc = ServerLoopInstance().RunSurfaceControlFrame(frame);
|
||||
ServerOwnedWindowReply reply;
|
||||
reply.transport = rc;
|
||||
reply.ok = rc == MOBILEGL_OK && frame.ok;
|
||||
reply.refusal = static_cast<SurfaceRefusalCode>(frame.refusal);
|
||||
reply.width = frame.width > 0 ? static_cast<Uint32>(frame.width) : 0u;
|
||||
reply.height = frame.height > 0 ? static_cast<Uint32>(frame.height) : 0u;
|
||||
return reply;
|
||||
}
|
||||
ServerOwnedWindowReply ServerCreateServerOwnedWindowSurface(EGLSurface surface, Uint32 width, Uint32 height) {
|
||||
// P12 (D1/D2): ONE frame, and no SetWindowHandle in front of it - the window is the
|
||||
// server's, so there is nothing of the client's to name. The frame-local tag is what the
|
||||
@@ -1893,6 +1903,30 @@ namespace MobileGL::MG_Remote::Server {
|
||||
return rc == MOBILEGL_OK && frame.ok;
|
||||
}
|
||||
|
||||
// P14 S1. A context creation is a frame like any other: `context` IS the client token (the
|
||||
// schema's field, not a bit-cast handle - a context has no handle the server could name),
|
||||
// `shareGroupToken` and `contextFlags` the two values CreateContext adds to it. Same blocking
|
||||
// handshake, so eglCreateContext cannot return a token the server has not tabled - which is
|
||||
// what keeps bind_context's "this session never created that token" refusal unreachable on
|
||||
// the well-behaved path.
|
||||
Bool ServerCreateEGLContext(Uint64 clientContextToken, Uint64 shareGroupToken, Uint32 flags) {
|
||||
SurfaceControlFrame frame;
|
||||
frame.kind = SurfaceControlOp::CreateContext;
|
||||
frame.context = clientContextToken;
|
||||
frame.shareGroupToken = shareGroupToken;
|
||||
frame.contextFlags = flags;
|
||||
const MobileGLResult rc = ServerLoopInstance().RunSurfaceControlFrame(frame);
|
||||
return rc == MOBILEGL_OK && frame.ok;
|
||||
}
|
||||
|
||||
Bool ServerDestroyEGLContext(Uint64 clientContextToken) {
|
||||
SurfaceControlFrame frame;
|
||||
frame.kind = SurfaceControlOp::DestroyContext;
|
||||
frame.context = clientContextToken;
|
||||
const MobileGLResult rc = ServerLoopInstance().RunSurfaceControlFrame(frame);
|
||||
return rc == MOBILEGL_OK && frame.ok;
|
||||
}
|
||||
|
||||
Bool ServerSwapEGLBuffers(EGLDisplay dpy, EGLSurface draw) {
|
||||
SurfaceControlFrame frame;
|
||||
frame.kind = SurfaceControlOp::SwapBuffersInprocOnly;
|
||||
|
||||
@@ -112,81 +112,44 @@ namespace MobileGL::MG_Remote::Server {
|
||||
// window in which a live-but-exiting apply thread answers true is byte-for-byte the old
|
||||
// one. The ServerLoop object still OWNS the key - nothing but ApplyThreadMain writes it -
|
||||
// it simply no longer has to be reached through the singleton to be read.
|
||||
// P14 S2: AND THE ANSWER IS PER THREAD NOW, NOT PER PROCESS. One word cannot hold N apply
|
||||
// threads: two sessions' threads would each publish their own key and the second store would
|
||||
// make the FIRST thread answer "no" to every role guard it owns - which is not a slower guard
|
||||
// but a dead one (a draw would take the client arm on the apply thread, and
|
||||
// RunSurfaceControlFrame would lose its re-entrancy shortcut and deadlock the EGL teardown).
|
||||
// The question is "am I an apply thread", a fact about the CALLER, so it is asked in the
|
||||
// caller's own TLS - one constant-initialized word, no guard, no atomic:
|
||||
//
|
||||
// t_onApplyThread the calling thread IS an apply thread.
|
||||
// g_applyThreadKey HOW MANY are running in this process. Kept because
|
||||
// MG_Backend/DirectGLES/Managers.cpp (outside this package's file set)
|
||||
// reads this name `!= 0` - "an apply thread is running somewhere" - which
|
||||
// is the count's zero-ness exactly. It is no longer a key and nothing on
|
||||
// the hot paths reads it.
|
||||
//
|
||||
// ZERO MEANS "NO APPLY THREAD IS RUNNING" still: t_onApplyThread is raised as the apply
|
||||
// thread's FIRST act and lowered in the same m_controlMutex critical section that clears
|
||||
// m_running on the way out, so the window in which a live-but-exiting apply thread answers
|
||||
// true is byte-for-byte the old one.
|
||||
//
|
||||
// WHAT WENT WITH IT, so nobody re-derives it: the aarch64 TPIDR_EL0 fast path, the
|
||||
// std::thread::id fallback with its no-padding static_assert, the MOBILEGL_DETAIL_
|
||||
// APPLY_THREAD_POINTER build knob and the relaxed-load argument about a recycled TLS block.
|
||||
// They existed to make "is the process's one apply thread mine" cheap; the question is now
|
||||
// "is the caller an apply thread", whose cheap answer is the caller's own word - and a word
|
||||
// cannot be recycled, because the thread that inherits a dead apply thread's TLS block is
|
||||
// not an apply thread until it runs ApplyThreadMain.
|
||||
namespace Detail {
|
||||
// RELAXED ON BOTH SIDES, and that is a claim about recycling, not a shrug. The only
|
||||
// dangerous outcome would be a NEW thread that reuses the exited apply thread's TLS
|
||||
// block (hence its thread pointer) while still reading the pre-clear key. It cannot
|
||||
// happen: the clear is sequenced before the apply thread's exit, the exit releases the
|
||||
// TLS block under libc's own lock, and the thread that later receives that block takes
|
||||
// the same lock - so the clear happens-before any load the new thread performs, and
|
||||
// coherence forbids a relaxed load from reading a value that a happens-before store
|
||||
// overwrote. A stale ZERO is harmless in the other direction: a thread that is not the
|
||||
// apply thread wants "false" anyway, and the apply thread always reads its own store.
|
||||
//
|
||||
// No acquire is needed for a second reason: this is an IDENTITY, not a handshake. No
|
||||
// caller publishes data through it; the real ordering lives in the ring, the doorbell
|
||||
// and m_controlMutex.
|
||||
inline std::atomic<Uint64> g_applyThreadKey{0};
|
||||
// A fresh thread's TLS word is zero-initialized, so a thread that inherits the exited
|
||||
// apply thread's TLS block - the recycling case the old relaxed-load argument was about -
|
||||
// starts out answering false and can only become the apply thread by running
|
||||
// ApplyThreadMain. There is no stale value to read and nothing to order.
|
||||
inline thread_local Bool t_onApplyThread = false;
|
||||
|
||||
// The calling thread's identity as the same integer. aarch64 - the split's only
|
||||
// measured target - reads TPIDR_EL0 with a single instruction and no call. Everywhere
|
||||
// else falls back to std::this_thread::get_id() memcpy'd into the key: still one libc
|
||||
// call, but the atomic<thread::id> load and the out-of-line pthread_equal that
|
||||
// dominated the old body are gone either way. x86_64 is deliberately NOT on the
|
||||
// builtin path - __builtin_thread_pointer only grew x86 support in clang 17 / GCC 11
|
||||
// and older toolchains accept __has_builtin for it and then fail in codegen, which is
|
||||
// a build break on the desktop ctest lane for a target whose frame rate nobody
|
||||
// measures.
|
||||
//
|
||||
// A LIVE THREAD'S KEY IS NEVER 0 on either path (a thread pointer is a real TLS
|
||||
// address; std::this_thread::get_id() on a running thread is never the
|
||||
// default-constructed id, whose object representation is the all-zero one on every
|
||||
// library in scope), which is what lets 0 mean "nobody".
|
||||
//
|
||||
// THE SELECTOR IS A BUILD KNOB, NOT A HEADER SECRET (review round 3). This header is
|
||||
// pulled into MG_State, MG_Impl and MG_Test translation units now, so the name carries
|
||||
// the MOBILEGL_DETAIL_ prefix to read as internal, it is #ifndef-guarded so a toolchain
|
||||
// whose __has_builtin(__builtin_thread_pointer) answers 1 and then fails in codegen can
|
||||
// be steered off the path with -DMOBILEGL_DETAIL_APPLY_THREAD_POINTER=0 instead of a
|
||||
// header edit, and it is always DEFINED - to 0 when unavailable - and tested with #if
|
||||
// rather than #ifdef, so that a -D...=0 really disables it instead of being ignored.
|
||||
#ifndef MOBILEGL_DETAIL_APPLY_THREAD_POINTER
|
||||
#if defined(__aarch64__) && defined(__has_builtin)
|
||||
#if __has_builtin(__builtin_thread_pointer)
|
||||
#define MOBILEGL_DETAIL_APPLY_THREAD_POINTER 1
|
||||
#endif
|
||||
#endif
|
||||
#endif
|
||||
#ifndef MOBILEGL_DETAIL_APPLY_THREAD_POINTER
|
||||
#define MOBILEGL_DETAIL_APPLY_THREAD_POINTER 0
|
||||
#endif
|
||||
inline Uint64 CurrentThreadKey() {
|
||||
#if MOBILEGL_DETAIL_APPLY_THREAD_POINTER
|
||||
return static_cast<Uint64>(reinterpret_cast<std::uintptr_t>(__builtin_thread_pointer()));
|
||||
#else
|
||||
const std::thread::id id = std::this_thread::get_id();
|
||||
static_assert(sizeof(std::thread::id) <= sizeof(Uint64),
|
||||
"std::thread::id does not fit the apply-thread key; this fallback has "
|
||||
"to hash rather than copy on that platform");
|
||||
// AND IT MUST HAVE NO PADDING (review round 3). Copying the OBJECT REPRESENTATION of
|
||||
// a type that has padding bytes would let two calls ON THE SAME THREAD return
|
||||
// different keys, and OnApplyThread() would then answer FALSE ON THE APPLY THREAD -
|
||||
// a role guard that has stopped guarding, which is the one direction CONTRACT-P5C
|
||||
// rule E says a guard may never fail in (RunSurfaceControlFrame would also lose its
|
||||
// re-entrancy shortcut and the EGL teardown post would deadlock on m_controlDone).
|
||||
// Every library this fallback is built against today wraps a single scalar
|
||||
// (libstdc++ __gthread_t, libc++ __libcpp_thread_id, MSVC unsigned int) and
|
||||
// satisfies this; one that did not is a BUILD ERROR here rather than a silently
|
||||
// dead guard at run time.
|
||||
static_assert(std::has_unique_object_representations_v<std::thread::id>,
|
||||
"std::thread::id has padding on this platform: copying its object "
|
||||
"representation would make the apply-thread key unstable within one "
|
||||
"thread. Hash the id (std::hash<std::thread::id>) instead.");
|
||||
Uint64 key = 0;
|
||||
std::memcpy(&key, &id, sizeof(id));
|
||||
return key;
|
||||
#endif
|
||||
}
|
||||
// The count of live apply threads, as a relaxed atomic: an identity-like gauge, not a
|
||||
// handshake (the real ordering lives in the ring, the doorbell and m_controlMutex), and
|
||||
// its one reader wants "is it zero".
|
||||
inline std::atomic<Uint64> g_applyThreadKey{0};
|
||||
} // namespace Detail
|
||||
|
||||
// ---------------------------------------------------------------------------------
|
||||
@@ -200,11 +163,26 @@ namespace MobileGL::MG_Remote::Server {
|
||||
// session NOT latched). Windows the client names itself (the X11/Win32/None tokens CONTRACT-P6
|
||||
// D8 has yet to close) are neither kind and neither latch nor are refused: nothing about them
|
||||
// changes here. Reset by ServerLoop::Start, i.e. per session.
|
||||
//
|
||||
// P14 S2: AND THE LATCH IS PER SESSION, WHICH IS ALL THIS SLICE NEEDS. The mode is a member of
|
||||
// the loop and a served session owns its loop, so two sessions in one process latch
|
||||
// independently and neither's first surface decides the other's - the semantics above are
|
||||
// otherwise unchanged (design/11-state-ownership.md §4.5: the latch stays at the session layer
|
||||
// and is never hoisted to the process). A mode DECLARED before a session's first surface would
|
||||
// have to travel on the wire - the Hello, or a SurfaceOp the client sends - because one
|
||||
// process's MOBILEGL_IPC_SURFACE cannot speak for the several sessions a unified server runs;
|
||||
// that is P14d's. Reading that env here instead refused a dialled-in ServerOwned client with
|
||||
// SurfaceModeMismatch before the display was ever consulted (ServerOwnedSurfaceTest).
|
||||
enum class SessionSurfaceMode : Uint8 { None, OnScreen, Offscreen };
|
||||
const char* SessionSurfaceModeName(SessionSurfaceMode mode);
|
||||
// The decision, pure, so a unit case can drive all six pairs without a backend.
|
||||
Bool SessionSurfaceModeAdmits(SessionSurfaceMode current, Bool serverOwnedWindow);
|
||||
|
||||
// P14 S2 (SessionRuntime.h): WHICH SESSION THIS LOOP IS, when it is one of several served by
|
||||
// the process. Set by ServerMain::RunSession before Start(); null for every other shape (the
|
||||
// inproc one-process client+server, a unit case), which is what keeps those byte-for-byte.
|
||||
class SessionRuntime;
|
||||
|
||||
class ServerLoop {
|
||||
public:
|
||||
// Creates the apply thread, names it mgl-srv-apply, applies
|
||||
@@ -214,6 +192,11 @@ namespace MobileGL::MG_Remote::Server {
|
||||
// landing on fast cores.
|
||||
MobileGLResult Start(ServerSession& session);
|
||||
|
||||
// P14 S2. The session this loop belongs to, so its apply thread can open the same thread
|
||||
// scope the control thread has (session/loop/inputs/latch domain/segment resolver).
|
||||
void SetRuntime(SessionRuntime& runtime) { m_runtime = &runtime; }
|
||||
SessionRuntime* Runtime() const { return m_runtime; }
|
||||
|
||||
// Kill the doorbell, join the thread (bounded), then destroy the private backend object
|
||||
// ON THAT THREAD before it exits. Blocking by contract - see the header note.
|
||||
void Stop();
|
||||
@@ -327,11 +310,9 @@ namespace MobileGL::MG_Remote::Server {
|
||||
// or more per draw, so the call itself - a cross-library PLT hop - was a measurable
|
||||
// share of the cost of the answer.
|
||||
static Bool OnApplyThread() {
|
||||
const Uint64 key = Detail::g_applyThreadKey.load(std::memory_order_relaxed);
|
||||
// Short-circuit ON PURPOSE: with TransportMode::Monolith, and in every process
|
||||
// before Start() and after Stop(), the key is 0 and the caller pays one relaxed
|
||||
// load and one branch - it never even reads its own identity.
|
||||
return key != 0 && key == Detail::CurrentThreadKey();
|
||||
// P14 S2: the caller's own TLS word. One constant-initialized load, no atomic, no
|
||||
// comparison and - unlike the process-wide key - the right answer with N sessions.
|
||||
return Detail::t_onApplyThread;
|
||||
}
|
||||
|
||||
// The CPU mask MOBILEGL_IPC_SERVER_AFFINITY resolved to and sched_setaffinity accepted.
|
||||
@@ -459,9 +440,6 @@ namespace MobileGL::MG_Remote::Server {
|
||||
|
||||
// P12. The ServerOwned arm of the CreateWindowSurface dispatch (D3, D4).
|
||||
MobileGLResult ApplyServerOwnedWindowSurface(MG_Backend::BackendObject* backend, SurfaceControlFrame& frame);
|
||||
MobileGLResult ApplyHostFrameWindowSurface(MG_Backend::BackendObject* backend, SurfaceControlFrame& frame);
|
||||
Bool IsHostFrameSurface(EGLSurface surface) const;
|
||||
void ForgetHostFrameSurface(EGLSurface surface);
|
||||
// P12 (D6), apply thread: the lost window's backend surface goes, the lease ends, and the
|
||||
// session latches ServerWindowLost. Runs from PumpControlRequest when Detach asked.
|
||||
void ReleaseLostServerWindow();
|
||||
@@ -474,17 +452,16 @@ namespace MobileGL::MG_Remote::Server {
|
||||
void ForgetServerOwnedSurface(EGLSurface surface);
|
||||
// Apply thread only: this session's surfaces created on the server's window; reset by Start().
|
||||
std::vector<EGLSurface> m_serverOwnedSurfaces;
|
||||
// The surfaces whose drawing target is a frame the display host owns. Kept apart from
|
||||
// the server-owned list because the two are different paths with different owners,
|
||||
// and a resize or a release has to reach the right one.
|
||||
std::vector<EGLSurface> m_hostFrameSurfaces;
|
||||
// ServerDisplay's lost hook: called under the display's lock from Detach's thread. Sets the
|
||||
// request and rings the apply thread's bell; never blocks.
|
||||
static void ServerWindowLostThunk(void* self);
|
||||
// AcquireFor's cancel predicate: the loop is stopping, or the session latched.
|
||||
static Bool ServerWindowWaitCancelled(void* self);
|
||||
// D4: latched at the session's first successful surface creation; reset by Start().
|
||||
// D4: latched at the session's first successful surface creation; reset by Start(). Per
|
||||
// session, because the loop is (P14 S2).
|
||||
SessionSurfaceMode m_surfaceMode = SessionSurfaceMode::None;
|
||||
// P14 S2: the session this loop serves, when the process serves several; see SetRuntime.
|
||||
SessionRuntime* m_runtime = nullptr;
|
||||
// Apply thread only: this loop holds the display's lease.
|
||||
Bool m_holdsWindowLease = false;
|
||||
// Set by ServerWindowLostThunk (any thread), taken by the apply thread. Part of the park
|
||||
@@ -583,6 +560,18 @@ namespace MobileGL::MG_Remote::Server {
|
||||
// C7 / ID-54: the (dpy, draw, read, ctx) currently bound on the apply thread. Written and
|
||||
// read ONLY on the apply thread inside ApplyMakeCurrent, so it needs no lock; the two
|
||||
// counters beside it are atomic because a test reads them from another thread.
|
||||
//
|
||||
// P14 S4 LOOKED AT MAKING THIS A PER-CONTEXT TABLE AND DID NOT, with the reason recorded
|
||||
// here rather than in a review thread: ID-67's pinned control
|
||||
// (ServerLoopEglTest.ADifferentTupleBindsNativelyAndRepublishesAnIdenticalRepeatDoesNeither)
|
||||
// defines "a different tuple" as a change of the CURRENTLY BOUND tuple, and asserts that
|
||||
// A -> B -> A costs three native binds. A table that remembered each context's tuple would
|
||||
// make the third one a RepeatNoOp - and it would be wrong for a real reason, not just for
|
||||
// the assertion: only ONE EGLContext can be current on the apply thread, so coming back to A
|
||||
// really does have to run the driver call that DirectGLES' seven frontend-context
|
||||
// invalidations hang off. "Each context holds its own native triple" is satisfied by the
|
||||
// backend's per-(session, token) registry; the dedup here is about the thread's CURRENT
|
||||
// binding and stays one tuple.
|
||||
Bool m_haveCurrentTuple = false;
|
||||
EGLDisplay m_curDpy = EGL_NO_DISPLAY;
|
||||
EGLSurface m_curDraw = EGL_NO_SURFACE;
|
||||
@@ -666,10 +655,6 @@ namespace MobileGL::MG_Remote::Server {
|
||||
Uint32 height = 0;
|
||||
};
|
||||
ServerOwnedWindowReply ServerCreateServerOwnedWindowSurface(EGLSurface surface, Uint32 width, Uint32 height);
|
||||
// The host-framed on-screen shape (MOBILEGL_IPC_SURFACE=host): the client names no window
|
||||
// either, but the frames come from the display host over the host frame bridge, and the
|
||||
// host presents them. The reply carries the size the surface was made at.
|
||||
ServerOwnedWindowReply ServerCreateHostFrameWindowSurface(EGLSurface surface, Uint32 width, Uint32 height);
|
||||
// P12 review fix: ResizeWindowSurface for a surface created on the server's window. The server
|
||||
// resizes its WINDOW (a geometry request) and replies with the window's real extent.
|
||||
ServerOwnedWindowReply ServerResizeServerOwnedWindowSurface(EGLSurface surface, Uint32 width, Uint32 height);
|
||||
@@ -679,6 +664,15 @@ namespace MobileGL::MG_Remote::Server {
|
||||
// and a SECOND arrival IS the invalidation signal, which is how DirectGLES, which has no
|
||||
// OnCapsInvalidated producer at all, tells the client without a dev-shaped backend edit.
|
||||
Bool ServerMakeEGLCurrent(EGLDisplay dpy, EGLSurface draw, EGLSurface read, EGLContext ctx);
|
||||
// P14 S1 (docs/Disaggregated/design/11-state-ownership.md). The EGL CONTEXT LIFECYCLE's two
|
||||
// frames, on the same channel and with the same blocking handshake as the twelve above.
|
||||
// `clientContextToken` is the token EGLState minted for the new context (never 0), and
|
||||
// `shareGroupToken` the group it joins - the sharing context's group, or a fresh one.
|
||||
// S1 creates a PLACEHOLDER server-side runtime: the token enters the session's table and
|
||||
// nothing native is built (S4 is what gives the entry a native context). DestroyContext
|
||||
// drops the entry and unbinds it if it was the current one.
|
||||
Bool ServerCreateEGLContext(Uint64 clientContextToken, Uint64 shareGroupToken, Uint32 flags);
|
||||
Bool ServerDestroyEGLContext(Uint64 clientContextToken);
|
||||
Bool ServerSwapEGLBuffers(EGLDisplay dpy, EGLSurface draw);
|
||||
void ServerSetEGLSwapInterval(Int interval);
|
||||
void ServerReleaseEGLSurface(EGLSurface surface);
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
#include "ServerDisplay.h"
|
||||
#include "ServerLoop.h"
|
||||
#include "ServerSession.h"
|
||||
#include "SessionRuntime.h"
|
||||
#include "SurfaceControlFrame.h"
|
||||
#include <Config.h>
|
||||
#include <Init.h>
|
||||
@@ -343,7 +344,7 @@ std::atomic<int> g_inProcessBackendPin{-1};
|
||||
// in the disaggregated server, does nothing unless set, and says so when it is.
|
||||
void DelaySessionHandshakeForTest() {
|
||||
const char* text = std::getenv("MOBILEGL_TEST_DELAY_SESSION_HANDSHAKE_MS");
|
||||
if (text == nullptr || *text == '\0') return;
|
||||
if (text == nullptr || text[0] == 0) return;
|
||||
const long ms = std::strtol(text, nullptr, 10);
|
||||
if (ms <= 0) return;
|
||||
WireLogError("MG_Remote server: pid=%d MOBILEGL_TEST_DELAY_SESSION_HANDSHAKE_MS=%ld - this session child "
|
||||
@@ -468,14 +469,25 @@ int RunSession(std::unique_ptr<SocketTransport> control, std::vector<std::uint8_
|
||||
// else: inproc keeps every Fatal (client and server share that process), and the supervisor
|
||||
// that forked this child never applies a record.
|
||||
//
|
||||
// P12 (D5): and the in-process display server arms it for EVERY session, here, the same way;
|
||||
// its supervisor resets it between sessions (ResetSessionLatch), so a session that latched does
|
||||
// not decline the next one.
|
||||
// P12 (D5): and the in-process display server arms it for EVERY session, here, the same way.
|
||||
// P14 S2: "IT" IS PER SESSION NOW - the scope below binds this thread to this session's latch
|
||||
// domain (FatalFunnel.h), so the arm that follows arms THAT domain and no other: a session
|
||||
// that latched cannot decline its neighbour, and the supervisor's ResetSessionLatch touches
|
||||
// only its own (process-default) domain.
|
||||
// P14 S2: THIS SESSION'S OWN RUNTIME, AND BOTH OF ITS THREADS ON IT. The object holds the
|
||||
// session, the apply loop and the PipeInputs block; the scope makes them what this thread's
|
||||
// reads of ServerSessionInstance()/ServerLoopInstance()/gPipeInputs resolve to, and binds this
|
||||
// session's latch domain and segment resolver. Everything below - the backend bring-up, the
|
||||
// arm, the EGL frames - therefore runs against THIS session, which is what lets one process
|
||||
// serve several at once. The apply thread opens the same scope as its first act
|
||||
// (ServerLoop::ApplyThreadMain, via SetRuntime below).
|
||||
auto runtime = std::make_unique<Server::SessionRuntime>();
|
||||
Server::Detail::ThreadSessionScope threadScope(*runtime);
|
||||
ArmSessionLatch();
|
||||
// The child bypasses MobileGL::Initialize: arm its own role counters.
|
||||
MobileGL::MG_Util::PipeStats::Init();
|
||||
auto& session = Server::ServerSessionInstance();
|
||||
auto& loop = Server::ServerLoopInstance();
|
||||
auto& session = runtime->Session();
|
||||
auto& loop = runtime->Loop();
|
||||
// P12 (D5): WHAT A PROCESS EXIT CLEANED UP FOR FREE, THE IN-PROCESS SHAPE CLEANS UP BY HAND,
|
||||
// on every way out from here - so the next session in this process starts where a fresh
|
||||
// session child would. A no-op for every forked / single-session shape: those `_exit` with the
|
||||
@@ -659,6 +671,9 @@ int RunSession(std::unique_ptr<SocketTransport> control, std::vector<std::uint8_
|
||||
// below) and is the one that says "still running" while the apply thread runs it. Cleared
|
||||
// after the loop, on this same thread, so no post can be in flight when it goes.
|
||||
loop.SetControlProgressSink(&SendSurfaceProgress, control.get());
|
||||
// P14 S2: the apply thread opens the same scope this thread is on, so its reads of the
|
||||
// session, this loop and the PipeInputs block resolve to THIS session's.
|
||||
loop.SetRuntime(*runtime);
|
||||
if (loop.Start(session) != MOBILEGL_OK) return endSession(70);
|
||||
WireLogError("MG_Remote server: pid=%d transport=spawn role=server ready control=%s data=%s",
|
||||
selfPid, tcp ? "tcp" : "unix", tcp ? "stream" : "shm");
|
||||
@@ -1035,32 +1050,12 @@ private:
|
||||
};
|
||||
|
||||
bool Reap() {
|
||||
if (m_handoffShape == Handoff::Thread) {
|
||||
const bool reaped = ReapSessionThread();
|
||||
if (m_active <= 0 && m_handoff >= 0) { ::close(m_handoff); m_handoff = -1; }
|
||||
return reaped;
|
||||
}
|
||||
// The fork shape: every live child is asked, and a reaped one takes its hand-off with it.
|
||||
bool reaped = false;
|
||||
for (auto child = m_children.begin(); child != m_children.end();) {
|
||||
if (ReapActiveSession(child->pid, m_sessionsFaulted)) {
|
||||
if (child->handoff >= 0) ::close(child->handoff);
|
||||
child = m_children.erase(child);
|
||||
reaped = true;
|
||||
} else {
|
||||
++child;
|
||||
}
|
||||
}
|
||||
m_active = m_children.empty() ? -1 : m_children.back().pid;
|
||||
const bool reaped = m_handoffShape == Handoff::Thread ? ReapSessionThread()
|
||||
: ReapActiveSession(m_active, m_sessionsFaulted);
|
||||
if (m_active <= 0 && m_handoff >= 0) { ::close(m_handoff); m_handoff = -1; }
|
||||
return reaped;
|
||||
}
|
||||
|
||||
// Whether an authenticated Hello has to be told Busy: the thread shape serves one session, the
|
||||
// fork shape up to kMaxForkedSessions side by side.
|
||||
bool SessionsFull() const {
|
||||
return m_handoffShape == Handoff::Thread ? m_active > 0 : m_children.size() >= kMaxForkedSessions;
|
||||
}
|
||||
|
||||
// P12 (D5): the thread shape's reap - the same line a forked child's reap prints, and the same
|
||||
// count, then the latch put back for the next session (ResetSessionLatch: the thread took no
|
||||
// process with it, so the latch it armed and maybe latched is still this process's).
|
||||
@@ -1102,7 +1097,7 @@ private:
|
||||
// make the loop wait here; a DataBind's routing takes one look (Judge, fix round).
|
||||
void WaitOutAnExitingSession() {
|
||||
const auto reapDeadline = Clock::now() + std::chrono::milliseconds(50);
|
||||
while (SessionsFull() && Clock::now() < reapDeadline) {
|
||||
while (m_active > 0 && Clock::now() < reapDeadline) {
|
||||
if (Reap()) break;
|
||||
::usleep(1000);
|
||||
}
|
||||
@@ -1196,15 +1191,7 @@ private:
|
||||
// either has cut its hand-off already (the send below fails and is refused by name) or
|
||||
// refuses what is queued on its way out (ExitBeforeAccept / CloseHandoffRefusingQueued).
|
||||
Reap();
|
||||
// WHICH SESSION IT BELONGS TO. The thread shape has one; the fork shape knows every
|
||||
// child's nonce (it minted them, Fork) and hands the connection to the child it names.
|
||||
int handoff = m_active > 0 ? m_handoff : -1;
|
||||
if (m_handoffShape == Handoff::Fork) {
|
||||
handoff = -1;
|
||||
for (const auto& child : m_children)
|
||||
if (ConstantTimeNonceMatch(child.nonce, nonce)) handoff = child.handoff;
|
||||
}
|
||||
if (handoff < 0) {
|
||||
if (m_active <= 0) {
|
||||
// StreamLink's frames may already follow the DataBind; read them away so the close
|
||||
// does not become an RST that discards the refusal.
|
||||
DrainUnread(fd);
|
||||
@@ -1214,7 +1201,7 @@ private:
|
||||
// The send is MSG_DONTWAIT and the child cuts its end the moment its own data
|
||||
// connection is bound (CloseHandoffRefusingQueued), so this either queues the
|
||||
// descriptor for a child that will read or refuse it, or fails and is refused here.
|
||||
if (FdPassing::SendFd(handoff, fd, MobileGLByteSpan{nonce, sizeof(nonce)},
|
||||
if (m_handoff >= 0 && FdPassing::SendFd(m_handoff, fd, MobileGLByteSpan{nonce, sizeof(nonce)},
|
||||
/*dontWait=*/true) == MOBILEGL_OK) {
|
||||
// The child holds its own descriptor now; ours goes without a shutdown(2), which
|
||||
// would disconnect the child's too.
|
||||
@@ -1245,11 +1232,9 @@ private:
|
||||
}
|
||||
m_backoff.NoteSuccess(peer.address);
|
||||
WaitOutAnExitingSession();
|
||||
if (SessionsFull()) {
|
||||
if (m_active > 0) {
|
||||
// The frame is consumed, so closing cannot RST the refusal away.
|
||||
Refuse(*connection, Protocol::RefuseCode::Busy,
|
||||
m_handoffShape == Handoff::Thread ? "one session is already active"
|
||||
: "the session limit is reached");
|
||||
Refuse(*connection, Protocol::RefuseCode::Busy, "one session is already active");
|
||||
return;
|
||||
}
|
||||
Fork(std::move(connection), payload);
|
||||
@@ -1265,25 +1250,12 @@ private:
|
||||
StartSessionThread(std::move(connection), hello, pair);
|
||||
return;
|
||||
}
|
||||
// The child's data nonce, minted HERE so this supervisor can route the child's DataBind to it
|
||||
// among other live sessions; the child adopts it instead of minting its own.
|
||||
LiveChild live;
|
||||
if (SocketTransport::MintNonce(live.nonce, sizeof(live.nonce)) != MOBILEGL_OK) {
|
||||
::close(pair[0]);
|
||||
::close(pair[1]);
|
||||
Refuse(*connection, Protocol::RefuseCode::Busy, "could not mint the session's data nonce");
|
||||
return;
|
||||
}
|
||||
std::fflush(nullptr);
|
||||
const pid_t supervisor = ::getpid();
|
||||
const pid_t child = ::fork();
|
||||
if (child == 0) {
|
||||
// P12 (D8): the child dies with this supervisor, not after its client has gone.
|
||||
DieWithSupervisor(supervisor);
|
||||
Server::PresetDataNonceForThisProcess(live.nonce, sizeof(live.nonce));
|
||||
// The other live sessions' hand-offs are the supervisor's.
|
||||
for (const auto& other : m_children)
|
||||
if (other.handoff >= 0) ::close(other.handoff);
|
||||
// The child owns this one connection and its end of the hand-off. Every OTHER pending
|
||||
// peer's descriptor is closed here, or the supervisor's refusal of that peer would not
|
||||
// end its connection while this session lives.
|
||||
@@ -1303,11 +1275,9 @@ private:
|
||||
Refuse(*connection, Protocol::RefuseCode::Busy, "could not create session child");
|
||||
return;
|
||||
}
|
||||
live.pid = child;
|
||||
live.handoff = pair[0];
|
||||
m_children.push_back(live);
|
||||
m_active = child;
|
||||
::close(pair[1]);
|
||||
m_handoff = pair[0];
|
||||
connection->CloseLocalCopy();
|
||||
}
|
||||
|
||||
@@ -1355,21 +1325,10 @@ private:
|
||||
std::atomic<bool> m_sessionDone{false};
|
||||
std::atomic<int> m_sessionExit{0};
|
||||
unsigned long m_sessionOrdinal = 0;
|
||||
// A live session: the newest child's pid for the fork shape, this process's for the thread shape.
|
||||
pid_t m_active = -1;
|
||||
// The thread shape's end of its session's data-connection hand-off (PH-7 (4)); -1 while no
|
||||
// session is live. It goes with the session: a reaped session can be handed nothing.
|
||||
// The supervisor's end of the live child's data-connection hand-off (PH-7 (4)); -1 while no
|
||||
// session is live. It goes with the child: a reaped session can be handed nothing.
|
||||
int m_handoff = -1;
|
||||
// THE FORK SHAPE'S LIVE SESSIONS, side by side: a desktop is a compositor AND the GL programs
|
||||
// run inside it, each its own client with its own session. Each child keeps its end of the
|
||||
// hand-off and the data nonce this supervisor minted for it, which is how a DataBind finds it.
|
||||
struct LiveChild {
|
||||
pid_t pid = -1;
|
||||
int handoff = -1;
|
||||
std::uint8_t nonce[kDataNonceBytes] = {};
|
||||
};
|
||||
static constexpr std::size_t kMaxForkedSessions = 8;
|
||||
std::vector<LiveChild> m_children;
|
||||
std::vector<PendingPeer> m_pending;
|
||||
std::vector<PendingPeer> m_ready;
|
||||
// Accepting resumes at this time after accept(2) ran out of descriptors or memory.
|
||||
@@ -1383,17 +1342,44 @@ private:
|
||||
// shm segments' descriptors cross by SCM_RIGHTS, so there is no DataBind to route and no pre-auth
|
||||
// gate - both are TCP exposure machinery, and a unix peer is local by construction (the forked
|
||||
// unix supervisor runs without either). Sessions take the TCP in-process shape's thread hand-off:
|
||||
// one at a time, Busy for a second client, the latch reset between sessions, stop by
|
||||
// g_inProcessStop.
|
||||
// a thread per session, up to MOBILEGL_IPC_INPROC_MAX_SESSIONS (default 16) and Refuse{Busy}
|
||||
// over it, the latch per session, stop by
|
||||
// g_inProcessStop. P14 S2: THE SESSIONS ARE CONCURRENT - each one owns its ServerSession, its
|
||||
// ServerLoop and its PipeInputs block through its own ThreadSessionScope (SessionRuntime.h), so a
|
||||
// session's close, latch or fault reaches no other, and the server's own stop waits for all of
|
||||
// them rather than for the one.
|
||||
class UnixInProcessSupervisor {
|
||||
public:
|
||||
UnixInProcessSupervisor(int listener, unsigned long& sessionsFaulted)
|
||||
: m_listener(listener), m_pairs(listener), m_sessionsFaulted(sessionsFaulted) {}
|
||||
// P14 S2: MAX SESSIONS AT ONCE. Each live session is one control thread (RunSession) plus its
|
||||
// own mgl-srv-apply, both carrying their own ServerSession/ServerLoop/PipeInputs block, so the
|
||||
// cap is a resource limit and not a correctness one. The default is the display server's
|
||||
// (mobilegl_server_serve_inprocess), which is where this class is used.
|
||||
static constexpr unsigned kDefaultMaxSessions = 16;
|
||||
|
||||
// MOBILEGL_IPC_INPROC_MAX_SESSIONS, capped, 0/unset/invalid = the default. An environment
|
||||
// knob rather than a new argument to mobilegl_server_serve_inprocess: the embedded ABI has one
|
||||
// parameter (the endpoint) and the display server passes none of this, exactly as it passes
|
||||
// none of the transport knobs.
|
||||
static unsigned MaxSessionsFromEnvironment() {
|
||||
const char* text = std::getenv("MOBILEGL_IPC_INPROC_MAX_SESSIONS");
|
||||
if (text == nullptr || text[0] == 0) return kDefaultMaxSessions;
|
||||
char* end = nullptr;
|
||||
const long parsed = std::strtol(text, &end, 10);
|
||||
if (end == text || parsed <= 0) return kDefaultMaxSessions;
|
||||
return static_cast<unsigned>(std::min<long>(parsed, 256));
|
||||
}
|
||||
|
||||
UnixInProcessSupervisor(int listener, unsigned long& sessionsFaulted,
|
||||
unsigned maxSessions = kDefaultMaxSessions)
|
||||
: m_listener(listener), m_pairs(listener), m_sessionsFaulted(sessionsFaulted),
|
||||
m_maxSessions(maxSessions == 0 ? kDefaultMaxSessions : maxSessions) {}
|
||||
|
||||
~UnixInProcessSupervisor() {
|
||||
// Run() only returns with the session thread joined; a listener failure (73) is the
|
||||
// one way out with it live, and it is never left running behind the supervisor.
|
||||
if (m_sessionThread.joinable()) m_sessionThread.join();
|
||||
// Run() only returns with every session thread joined; a listener failure (73) is the one
|
||||
// way out with one live, and a session is never left running behind the supervisor.
|
||||
for (auto& session : m_live) {
|
||||
if (session->thread.joinable()) session->thread.join();
|
||||
}
|
||||
}
|
||||
|
||||
int Run() {
|
||||
@@ -1408,15 +1394,11 @@ public:
|
||||
static_cast<int>(accepted));
|
||||
return 73;
|
||||
}
|
||||
// exit_group's close window, as the forked loop's: a client reconnecting the moment
|
||||
// its session ended must not be told Busy by a session that is exiting.
|
||||
const auto reapDeadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(50);
|
||||
while (m_active > 0 && std::chrono::steady_clock::now() < reapDeadline) {
|
||||
if (Reap()) break;
|
||||
::usleep(1000);
|
||||
}
|
||||
if (m_active > 0) {
|
||||
RefuseBusy(*control, "one session is already active");
|
||||
// P14 S2: THE CAP, NOT "ONE AT A TIME". A peer over the limit is refused by the same
|
||||
// words the forked `--max-sessions` supervisor uses, and is not a latch: the sessions
|
||||
// already running carry on and the connection is simply closed.
|
||||
if (m_live.size() >= m_maxSessions) {
|
||||
RefuseBusy(*control, "the session limit is reached");
|
||||
continue;
|
||||
}
|
||||
StartSessionThread(std::move(control));
|
||||
@@ -1424,48 +1406,71 @@ public:
|
||||
}
|
||||
|
||||
private:
|
||||
// The same reap as the TCP shape's ReapSessionThread: join, count faults, reset the latch
|
||||
// for the next session in this process.
|
||||
bool Reap() {
|
||||
if (m_active <= 0 || !m_sessionDone.load(std::memory_order_acquire)) return false;
|
||||
if (m_sessionThread.joinable()) m_sessionThread.join();
|
||||
const int code = m_sessionExit.load(std::memory_order_acquire);
|
||||
m_active = -1;
|
||||
if (code != 0) ++m_sessionsFaulted;
|
||||
ResetSessionLatch();
|
||||
WireLogError("MG_Remote server: in-process unix session #%lu pid=%d reaped exit=%d%s sessionsFaulted=%lu",
|
||||
m_sessionOrdinal, static_cast<int>(::getpid()), code,
|
||||
code == kSessionLatchedExitCode ? " (latched fault)" : "", m_sessionsFaulted);
|
||||
return true;
|
||||
// One live session: its control thread, and the two facts the reap needs from it. The session
|
||||
// itself (its ServerSession, its apply thread, its PipeInputs block) is owned by RunSession's
|
||||
// own frame, on that thread - nothing here reaches into it.
|
||||
struct LiveSession {
|
||||
std::thread thread;
|
||||
std::atomic<bool> done{false};
|
||||
std::atomic<int> exit{0};
|
||||
unsigned long long ordinal = 0;
|
||||
};
|
||||
|
||||
// The same reap as the TCP shape's ReapSessionThread: join, count faults, reset the latch for
|
||||
// the next session in this process. Every finished session is reaped, in whatever order they
|
||||
// finished.
|
||||
void Reap() {
|
||||
for (auto session = m_live.begin(); session != m_live.end();) {
|
||||
LiveSession& live = **session;
|
||||
if (!live.done.load(std::memory_order_acquire)) {
|
||||
++session;
|
||||
continue;
|
||||
}
|
||||
if (live.thread.joinable()) live.thread.join();
|
||||
const int code = live.exit.load(std::memory_order_acquire);
|
||||
if (code != 0) ++m_sessionsFaulted;
|
||||
ResetSessionLatch();
|
||||
WireLogError("MG_Remote server: in-process unix session #%llu pid=%d reaped exit=%d%s "
|
||||
"sessionsFaulted=%lu (live %zu)",
|
||||
static_cast<unsigned long long>(live.ordinal),
|
||||
static_cast<int>(::getpid()), code,
|
||||
code == kSessionLatchedExitCode ? " (latched fault)" : "", m_sessionsFaulted,
|
||||
m_live.size() - 1);
|
||||
session = m_live.erase(session);
|
||||
}
|
||||
}
|
||||
|
||||
void StartSessionThread(std::unique_ptr<SocketTransport> connection) {
|
||||
if (m_sessionThread.joinable()) m_sessionThread.join(); // reaped already; never live here
|
||||
m_sessionDone.store(false, std::memory_order_release);
|
||||
m_sessionExit.store(0, std::memory_order_release);
|
||||
++m_sessionOrdinal;
|
||||
// No hand-off pair and no pre-read Hello: the session reads its own first frame and binds
|
||||
// its shm segments from the fds the pair's second connection carries.
|
||||
auto live = std::make_unique<LiveSession>();
|
||||
live->ordinal = ++m_sessionOrdinal;
|
||||
try {
|
||||
// No hand-off pair and no pre-read Hello: the session reads its own first frame and
|
||||
// binds its shm segments from the fds the pair's second connection carries.
|
||||
m_sessionThread = std::thread([this, conn = std::move(connection)]() mutable {
|
||||
live->thread = std::thread([live = live.get(), conn = std::move(connection)]() mutable {
|
||||
const int code = RunSession(std::move(conn), {}, {}, -1, DataSource::None, 10000,
|
||||
/*inProcess=*/true);
|
||||
m_sessionExit.store(code, std::memory_order_release);
|
||||
m_sessionDone.store(true, std::memory_order_release);
|
||||
live->exit.store(code, std::memory_order_release);
|
||||
live->done.store(true, std::memory_order_release);
|
||||
});
|
||||
} catch (...) {
|
||||
WireLogError("MG_Remote server: could not start the in-process unix session thread; the "
|
||||
"connection is closed (it cannot be refused: it moved into the failed thread)");
|
||||
return;
|
||||
}
|
||||
m_active = ::getpid();
|
||||
WireLogError("MG_Remote server: in-process unix session #%lu started on a thread (pid=%d)",
|
||||
m_sessionOrdinal, static_cast<int>(::getpid()));
|
||||
m_live.push_back(std::move(live));
|
||||
WireLogError("MG_Remote server: in-process unix session #%llu started on a thread (pid=%d, "
|
||||
"%zu live of at most %u; %u accepted in this process)",
|
||||
static_cast<unsigned long long>(m_sessionOrdinal),
|
||||
static_cast<int>(::getpid()), m_live.size(), m_maxSessions,
|
||||
Server::LiveServerSessionCount());
|
||||
}
|
||||
|
||||
int StopServing() {
|
||||
while (m_active > 0) {
|
||||
if (!Reap()) ::usleep(10000);
|
||||
// P14 S2: EVERY live session, not one. Each reads g_inProcessStop on its own control
|
||||
// slice, so this is the same orderly end the single-session shape had, N times over.
|
||||
while (!m_live.empty()) {
|
||||
Reap();
|
||||
if (!m_live.empty()) ::usleep(10000);
|
||||
}
|
||||
WireLogError("MG_Remote server: pid=%d in-process display server stopped", static_cast<int>(::getpid()));
|
||||
return 0;
|
||||
@@ -1475,11 +1480,10 @@ private:
|
||||
// The connections that have not been paired yet live here between Accept calls.
|
||||
Server::PairAcceptor m_pairs;
|
||||
unsigned long& m_sessionsFaulted;
|
||||
std::thread m_sessionThread;
|
||||
std::atomic<bool> m_sessionDone{false};
|
||||
std::atomic<int> m_sessionExit{0};
|
||||
unsigned long m_sessionOrdinal = 0;
|
||||
pid_t m_active = -1;
|
||||
unsigned m_maxSessions;
|
||||
// P14 S2: every live session, not one. Reaped by Run()'s Reap and by StopServing.
|
||||
std::vector<std::unique_ptr<LiveSession>> m_live;
|
||||
unsigned long long m_sessionOrdinal = 0;
|
||||
};
|
||||
|
||||
// The server's environment preconditions, shared by the exec'd supervisor and the in-process
|
||||
@@ -1514,20 +1518,24 @@ extern "C" __attribute__((visibility("default"))) int mobilegl_server_main(int a
|
||||
if (const int refused = CheckServerEnvironment(); refused != 0) return refused;
|
||||
std::string endpoint;
|
||||
bool serve = false;
|
||||
unsigned long maxSessions = 1;
|
||||
for (int i = 1; i < argc; ++i) {
|
||||
const std::string arg(argv[i]);
|
||||
if (arg == "--serve") serve = true;
|
||||
else if (arg == "--max-sessions" && i + 1 < argc) {
|
||||
char* end = nullptr;
|
||||
const auto count = std::strtoul(argv[++i], &end, 10);
|
||||
// This is a concurrency limit, not a cumulative session budget.
|
||||
// P6.5 deliberately supports one active rendering session.
|
||||
if (*end || count != 1) return 71;
|
||||
// Opt-in concurrency is only for an offscreen unix supervisor: each client gets
|
||||
// a process and independent backend state. In-process displays remain singleton.
|
||||
if (*end || count < 1 || count > 64) return 71;
|
||||
maxSessions = count;
|
||||
} else if (endpoint.empty() && arg.compare(0, 2, "--") != 0) endpoint = arg;
|
||||
else return 71;
|
||||
}
|
||||
if (endpoint.empty()) if (const char* value = std::getenv("MOBILEGL_IPC_ENDPOINT")) endpoint = value;
|
||||
if (endpoint.empty()) return 71;
|
||||
const bool tcpEndpoint = endpoint.compare(0, 6, "tcp://") == 0;
|
||||
if (maxSessions > 1 && (!serve || tcpEndpoint)) return 71;
|
||||
int listener = -1;
|
||||
if (SocketTransport::Listen(endpoint, &listener) != MOBILEGL_OK) return 72;
|
||||
WireLogError("MG_Remote server: pid=%d listening on %s", static_cast<int>(::getpid()), endpoint.c_str());
|
||||
@@ -1545,7 +1553,6 @@ extern "C" __attribute__((visibility("default"))) int mobilegl_server_main(int a
|
||||
reserved, rule);
|
||||
}
|
||||
unsigned long sessionsFaulted = 0;
|
||||
const bool tcpEndpoint = endpoint.compare(0, 6, "tcp://") == 0;
|
||||
const auto knobs = Server::PreAuthKnobs::FromEnvironment();
|
||||
if (tcpEndpoint && serve) {
|
||||
// PH-7 (5): the TCP supervisor reads and authenticates every first frame before it forks.
|
||||
@@ -1556,8 +1563,20 @@ extern "C" __attribute__((visibility("default"))) int mobilegl_server_main(int a
|
||||
return failed;
|
||||
}
|
||||
// From here: the unix endpoint (--serve or not), and the single-session TCP shape.
|
||||
pid_t active = -1;
|
||||
const auto reap = [&]() { return ReapActiveSession(active, sessionsFaulted); };
|
||||
std::vector<pid_t> active;
|
||||
active.reserve(maxSessions);
|
||||
const auto reap = [&]() {
|
||||
bool reaped = false;
|
||||
for (auto child = active.begin(); child != active.end();) {
|
||||
if (ReapActiveSession(*child, sessionsFaulted)) {
|
||||
child = active.erase(child);
|
||||
reaped = true;
|
||||
} else {
|
||||
++child;
|
||||
}
|
||||
}
|
||||
return reaped;
|
||||
};
|
||||
// P11 PAIR: a unix client's two connections, paired by the nonce each presents first. The
|
||||
// connections not yet paired stay in it between calls.
|
||||
std::unique_ptr<Server::PairAcceptor> pairs;
|
||||
@@ -1596,12 +1615,12 @@ extern "C" __attribute__((visibility("default"))) int mobilegl_server_main(int a
|
||||
// exit_group closes files just before waitpid can observe the exit.
|
||||
// Allow that small scheduling window; a live peer remains Busy.
|
||||
const auto reapDeadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(50);
|
||||
while (active > 0 && std::chrono::steady_clock::now() < reapDeadline) {
|
||||
while (active.size() >= maxSessions && std::chrono::steady_clock::now() < reapDeadline) {
|
||||
if (reap()) break;
|
||||
::usleep(1000);
|
||||
}
|
||||
if (active > 0) {
|
||||
RefuseBusy(*control, "one session is already active");
|
||||
if (active.size() >= maxSessions) {
|
||||
RefuseBusy(*control, maxSessions == 1 ? "one session is already active" : "the session limit is reached");
|
||||
continue;
|
||||
}
|
||||
std::fflush(nullptr);
|
||||
@@ -1621,7 +1640,7 @@ extern "C" __attribute__((visibility("default"))) int mobilegl_server_main(int a
|
||||
RefuseBusy(*control, "could not create session child");
|
||||
continue;
|
||||
}
|
||||
active = child;
|
||||
active.push_back(child);
|
||||
control->CloseLocalCopy();
|
||||
}
|
||||
LogSupervisorSummary(sessionsFaulted);
|
||||
@@ -1679,7 +1698,8 @@ extern "C" __attribute__((visibility("default"))) int mobilegl_server_serve_inpr
|
||||
TcpSupervisor::Handoff::Thread, &g_inProcessStop);
|
||||
result = supervisor.Run();
|
||||
} else {
|
||||
UnixInProcessSupervisor supervisor(listener, sessionsFaulted);
|
||||
UnixInProcessSupervisor supervisor(listener, sessionsFaulted,
|
||||
UnixInProcessSupervisor::MaxSessionsFromEnvironment());
|
||||
result = supervisor.Run();
|
||||
}
|
||||
LogSupervisorSummary(sessionsFaulted);
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
|
||||
#include "../Transport/SocketTransport.h"
|
||||
#include "ServerSession.h"
|
||||
#include "SessionRuntime.h"
|
||||
#include <MG_Remote/FatalFunnel.h>
|
||||
|
||||
#include "../CapsCodec.h"
|
||||
@@ -42,24 +43,6 @@
|
||||
#endif
|
||||
|
||||
namespace MobileGL::MG_Remote::Server {
|
||||
namespace {
|
||||
Uint8 g_presetDataNonce[Transport::kDataNonceBytes] = {};
|
||||
Bool g_presetDataNonceSet = false;
|
||||
|
||||
Bool TakePresetDataNonce(Uint8* out, SizeT size) {
|
||||
if (!g_presetDataNonceSet || size != sizeof(g_presetDataNonce)) return false;
|
||||
std::memcpy(out, g_presetDataNonce, size);
|
||||
g_presetDataNonceSet = false;
|
||||
return true;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
void PresetDataNonceForThisProcess(const Uint8* nonce, SizeT size) {
|
||||
if (nonce == nullptr || size != sizeof(g_presetDataNonce)) return;
|
||||
std::memcpy(g_presetDataNonce, nonce, size);
|
||||
g_presetDataNonceSet = true;
|
||||
}
|
||||
|
||||
|
||||
namespace {
|
||||
// F1 (P7 wave 2). THE ONLY KNOB THAT CAN MAKE THE FIRST CapsSnapshot LATE.
|
||||
@@ -546,11 +529,24 @@ namespace MobileGL::MG_Remote::Server {
|
||||
// One callback table and one process segment resolver: an in-progress Accept
|
||||
// reserves their owner too. CAS closes the race between distinct session objects
|
||||
// without making concurrent sessions a supported mode.
|
||||
//
|
||||
// P14 S2: THE TABLE IS STILL ONE PER PROCESS, and that is now deliberate rather than a
|
||||
// limit. Its entries are the same five functions for every session; what makes them route
|
||||
// to the right session is that they resolve it per calling thread
|
||||
// (ServerSession::Active()), and every one of them is called by a backend that runs on a
|
||||
// session's own apply thread. So the owner word below is a CLAIM on a shared, idempotent
|
||||
// installation, not a claim on "the session".
|
||||
std::atomic<ServerSession*> g_sessionOwner{nullptr};
|
||||
// P14 S2: accepted and not yet closed. The claim above is released by a Close only when
|
||||
// this reaches zero - one session ending may not uninstall the table another is using.
|
||||
std::atomic<Uint32> g_liveSessions{0};
|
||||
|
||||
} // namespace
|
||||
|
||||
Uint32 ServerSessionCount() { return g_liveSessions.load(std::memory_order_acquire); }
|
||||
|
||||
ServerSession& ServerSessionInstance() {
|
||||
if (ServerSession* const own = Detail::CurrentSession()) return *own;
|
||||
// Leak at exit, deliberately and per ID-8: frontend destructors reach pipe and backend
|
||||
// state from exit handlers, and a session destroyed before them would be a
|
||||
// use-after-free rather than a tidy teardown.
|
||||
@@ -558,7 +554,10 @@ namespace MobileGL::MG_Remote::Server {
|
||||
return *instance;
|
||||
}
|
||||
|
||||
ServerSession* ServerSession::Active() { return g_active.load(std::memory_order_acquire); }
|
||||
ServerSession* ServerSession::Active() {
|
||||
if (ServerSession* const own = Detail::CurrentSession()) return own;
|
||||
return g_active.load(std::memory_order_acquire);
|
||||
}
|
||||
|
||||
ServerSession::ServerSession() {
|
||||
m_link = Transport::CreateSharedLink(Transport::TransportRoleTag::ServerConsumer);
|
||||
@@ -602,8 +601,17 @@ namespace MobileGL::MG_Remote::Server {
|
||||
|
||||
MobileGLResult ServerSession::Accept(Transport::ITransport& transport,
|
||||
const std::vector<Uint8>* firstFrame) {
|
||||
// P14 S2: A SERVED SESSION DOES NOT CLAIM THE PROCESS TABLE, because the table is SHARED.
|
||||
// Its entries are the same five functions for every session and they route by the calling
|
||||
// thread (ServerSession::Active()), so a second session installing them is the idempotent
|
||||
// repeat InstallReverseCallback already allows - and a second session REFUSING to install
|
||||
// them is what a one-session process would have. The claim below therefore belongs to the
|
||||
// shapes whose process really is one session (the inproc client+server role, FvSession and
|
||||
// its peers in ServerLoopTest): there a second ServerSession object is still the named
|
||||
// Fatal{callback-double-install} the single-session ruling asks for.
|
||||
const Bool sharedTable = Detail::CurrentSession() == this;
|
||||
ServerSession* expectedOwner = nullptr;
|
||||
if (!g_sessionOwner.compare_exchange_strong(expectedOwner, this,
|
||||
if (!sharedTable && !g_sessionOwner.compare_exchange_strong(expectedOwner, this,
|
||||
std::memory_order_acq_rel, std::memory_order_acquire)) {
|
||||
if (expectedOwner == this) return MOBILEGL_ERR_INVALID_ARGUMENT;
|
||||
SessionFail(MGFatalFamily::RoleViolation, "MGPipe: Fatal{RoleViolation, \"callback-double-install\"} - another "
|
||||
@@ -720,6 +728,19 @@ namespace MobileGL::MG_Remote::Server {
|
||||
m_t0Stores = m_t0Bytes = m_t0Declined = m_t0Refusals = 0;
|
||||
m_adoptInbox.Clear();
|
||||
m_adoptInbox.Attach(&transport);
|
||||
// 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.
|
||||
//
|
||||
// P14 S5: the APPLIERS of those contexts go with them - one registry entry per context
|
||||
// and one per share group, released here because a session that is re-accepted must not
|
||||
// inherit the previous client's object records. Accept can run on the control thread
|
||||
// while nothing is applying (this is the accept path, before the first Hello is
|
||||
// answered), so the release is safe here in a way it would not be mid-session.
|
||||
MG_Pipe::MGPipeApplierReleaseSession(reinterpret_cast<Uint64>(this));
|
||||
m_contexts.clear();
|
||||
m_currentContextToken.store(0, std::memory_order_release);
|
||||
m_contextsCreated = m_contextsDestroyed = m_contextBinds = 0;
|
||||
|
||||
// ---- 3. the four segments, both control pages, the rings.
|
||||
MobileGLResult created = MOBILEGL_ERR_UNSUPPORTED;
|
||||
@@ -734,9 +755,7 @@ namespace MobileGL::MG_Remote::Server {
|
||||
if (socket == nullptr || !socket->IsTcp() || !m_dataSource)
|
||||
return RefuseHandshake(transport, ::MobileGL::Wire::RefuseCode::LinkTerms,
|
||||
"stream needs a TCP control connection and a data-connection source");
|
||||
created = TakePresetDataNonce(dataNonce, sizeof(dataNonce))
|
||||
? MOBILEGL_OK
|
||||
: Transport::SocketTransport::MintNonce(dataNonce, sizeof(dataNonce));
|
||||
created = Transport::SocketTransport::MintNonce(dataNonce, sizeof(dataNonce));
|
||||
if (created != MOBILEGL_OK) {
|
||||
// (F fix round) The peer is told by name instead of seeing a bare close. The
|
||||
// return value stays the fault it is - exit 67 in ServerMain, counted in
|
||||
@@ -864,6 +883,10 @@ namespace MobileGL::MG_Remote::Server {
|
||||
m_segments.InstallProcessResolver();
|
||||
|
||||
m_accepted = true;
|
||||
m_closed = false;
|
||||
// P14 S2: this session is live. The reverse-channel table and the segment resolver are
|
||||
// process-wide and shared; they are released by whichever Close finds this back at zero.
|
||||
g_liveSessions.fetch_add(1, std::memory_order_acq_rel);
|
||||
|
||||
// ---- P5c ev: the four reverse-channel producers are THIS session's (CONTRACT-P5C
|
||||
// §4.1), installed before the apply thread can apply a record that produces one and
|
||||
@@ -1026,29 +1049,41 @@ namespace MobileGL::MG_Remote::Server {
|
||||
}
|
||||
|
||||
void ServerSession::Close() {
|
||||
// P14 S2: idempotent (ServerSession.h). A served session is a stack object whose owner
|
||||
// closes it explicitly and whose destructor closes it again.
|
||||
if (m_closed) return;
|
||||
m_closed = true;
|
||||
ServerSession* expectedActive = this;
|
||||
g_active.compare_exchange_strong(expectedActive, nullptr,
|
||||
std::memory_order_acq_rel, std::memory_order_acquire);
|
||||
if (m_accepted) {
|
||||
// Uninstall AFTER the apply thread has joined, never before: a record still in
|
||||
// flight can still resolve a segment offset (table 3's fourth column).
|
||||
Wire::SegmentTable::UninstallProcessResolver();
|
||||
// The reverse-channel producers go with the session that owns them - release
|
||||
// only the entries that are still OURS, never one a later owner installed.
|
||||
if (MG_Pipe::gMGPipeCallbacks.OnGlError == &ServerOnGlError) {
|
||||
MG_Pipe::gMGPipeCallbacks.OnGlError = nullptr;
|
||||
}
|
||||
if (MG_Pipe::gMGPipeCallbacks.OnBufferWriteback == &ServerOnBufferWriteback) {
|
||||
MG_Pipe::gMGPipeCallbacks.OnBufferWriteback = nullptr;
|
||||
}
|
||||
if (MG_Pipe::gMGPipeCallbacks.OnGpuWritten == &ServerOnGpuWritten) {
|
||||
MG_Pipe::gMGPipeCallbacks.OnGpuWritten = nullptr;
|
||||
}
|
||||
if (MG_Pipe::gMGPipeCallbacks.OnSurfaceChanged == &ServerOnSurfaceChanged) {
|
||||
MG_Pipe::gMGPipeCallbacks.OnSurfaceChanged = nullptr;
|
||||
}
|
||||
if (MG_Pipe::gMGPipeEventRingCapacityBytes == &ServerEventRingCapacityBytes) {
|
||||
MG_Pipe::gMGPipeEventRingCapacityBytes = nullptr;
|
||||
// P14 S2: DROP THIS SESSION FIRST, THEN ASK WHETHER ANY IS LEFT. The two process-wide
|
||||
// hooks below (the segment resolver and the reverse-channel table) are shared by every
|
||||
// session in the process, so a session that ends while another is live must leave both
|
||||
// installed - its own threads are done with them (the apply thread is joined above and
|
||||
// this control thread unbinds its own binding on the way out of RunSession).
|
||||
const Uint32 remaining = g_liveSessions.fetch_sub(1, std::memory_order_acq_rel) - 1;
|
||||
if (remaining == 0) {
|
||||
// Uninstall AFTER the apply thread has joined, never before: a record still in
|
||||
// flight can still resolve a segment offset (table 3's fourth column).
|
||||
Wire::SegmentTable::UninstallProcessResolver();
|
||||
// The reverse-channel producers go with the session that owns them - release
|
||||
// only the entries that are still OURS, never one a later owner installed.
|
||||
if (MG_Pipe::gMGPipeCallbacks.OnGlError == &ServerOnGlError) {
|
||||
MG_Pipe::gMGPipeCallbacks.OnGlError = nullptr;
|
||||
}
|
||||
if (MG_Pipe::gMGPipeCallbacks.OnBufferWriteback == &ServerOnBufferWriteback) {
|
||||
MG_Pipe::gMGPipeCallbacks.OnBufferWriteback = nullptr;
|
||||
}
|
||||
if (MG_Pipe::gMGPipeCallbacks.OnGpuWritten == &ServerOnGpuWritten) {
|
||||
MG_Pipe::gMGPipeCallbacks.OnGpuWritten = nullptr;
|
||||
}
|
||||
if (MG_Pipe::gMGPipeCallbacks.OnSurfaceChanged == &ServerOnSurfaceChanged) {
|
||||
MG_Pipe::gMGPipeCallbacks.OnSurfaceChanged = nullptr;
|
||||
}
|
||||
if (MG_Pipe::gMGPipeEventRingCapacityBytes == &ServerEventRingCapacityBytes) {
|
||||
MG_Pipe::gMGPipeEventRingCapacityBytes = nullptr;
|
||||
}
|
||||
}
|
||||
}
|
||||
// P11 B2: the T0 arm's proof for this session, then the inbox's leftovers (an Offer whose
|
||||
@@ -1225,6 +1260,61 @@ namespace MobileGL::MG_Remote::Server {
|
||||
return true;
|
||||
}
|
||||
|
||||
// ---- P14 S1: the context registry ------------------------------------------------------
|
||||
//
|
||||
// ALL THREE RUN ON THE APPLY THREAD. CreateContext/DestroyContext are the control plane's
|
||||
// frames, dispatched through RunSurfaceControlFrame; BindContext is a ring record, dispatched
|
||||
// through the decoder's verb sink. Neither ever runs anywhere else, which is what makes the
|
||||
// map lock-free here.
|
||||
Bool ServerSession::CreateContext(Uint64 token, Uint64 shareGroupToken, Uint32 flags) {
|
||||
if (token == 0) return false;
|
||||
if (m_contexts.find(token) != m_contexts.end()) return false;
|
||||
ContextRuntime runtime;
|
||||
runtime.Token = token;
|
||||
runtime.ShareGroupToken = shareGroupToken;
|
||||
runtime.Flags = flags;
|
||||
m_contexts.emplace(token, runtime);
|
||||
++m_contextsCreated;
|
||||
// P14 S5: and the applier this context's records are applied through - its own working
|
||||
// state, in the share group `shareGroupToken` names (0 = one it starts itself). The key
|
||||
// is THIS object's address, which is what the session's key resolver
|
||||
// (SessionRuntime.cpp) hands back, so registration and lookup agree by construction.
|
||||
// Registering here rather than inferring at lookup time is what keeps the resolver a
|
||||
// two-word read: this runs on the apply thread, where the frame channel delivers, and
|
||||
// is the only writer of the contexts map.
|
||||
MG_Pipe::MGPipeApplierRegisterContext(reinterpret_cast<Uint64>(this), token, shareGroupToken);
|
||||
return true;
|
||||
}
|
||||
|
||||
Bool ServerSession::DestroyContext(Uint64 token) {
|
||||
if (token == 0) return false;
|
||||
const auto it = m_contexts.find(token);
|
||||
if (it == m_contexts.end()) return false;
|
||||
m_contexts.erase(it);
|
||||
++m_contextsDestroyed;
|
||||
// P14 S5: the working state goes with it, and this group's object records go when its
|
||||
// last context does.
|
||||
MG_Pipe::MGPipeApplierUnregisterContext(reinterpret_cast<Uint64>(this), token);
|
||||
// A destroyed context cannot stay current: leaving the token bound would attribute every
|
||||
// record after the destroy to a context the session no longer has. The client's own
|
||||
// eglDestroyContext is refused while the context is current (EGL_BAD_ACCESS), so this
|
||||
// arm is reached with the token already released in the well-behaved sequence - and with
|
||||
// the release MISSING it is still the safe direction.
|
||||
Uint64 expected = token;
|
||||
m_currentContextToken.compare_exchange_strong(expected, 0, std::memory_order_acq_rel);
|
||||
return true;
|
||||
}
|
||||
|
||||
Bool ServerSession::BindContext(Uint64 token) {
|
||||
// 0 is the release edge and is always legal: the client has context A current, releases
|
||||
// it, and a verb on the app thread follows - the session binds "nothing" rather than
|
||||
// answering to a stale token.
|
||||
if (token != 0 && m_contexts.find(token) == m_contexts.end()) return false;
|
||||
m_currentContextToken.store(token, std::memory_order_release);
|
||||
++m_contextBinds;
|
||||
return true;
|
||||
}
|
||||
|
||||
Transport::RingConsumer& ServerSession::CommandRing() { return *m_commands; }
|
||||
|
||||
Transport::RingControl& ServerSession::Control() {
|
||||
|
||||
@@ -63,15 +63,12 @@
|
||||
|
||||
namespace MobileGL::MG_Remote::Server {
|
||||
|
||||
// THE DATA NONCE A FORKED SESSION CHILD IS BORN WITH. The TCP supervisor serves sessions side by
|
||||
// side and routes each data connection (DataBind) to the child whose nonce it presents, so it has
|
||||
// to know every child's nonce: it mints the nonce itself just before fork() and the child adopts
|
||||
// it here instead of minting its own. One use: the session that takes it clears it. Never set in
|
||||
// a process that runs more than one session, so the shared storage is the child's alone.
|
||||
void PresetDataNonceForThisProcess(const Uint8* nonce, SizeT size);
|
||||
|
||||
class ServerSession {
|
||||
public:
|
||||
// P14 S2: THE SESSION OF THE CALLING THREAD, else the process's active one. Every
|
||||
// server-role caller that matters (the reverse-channel producers, the applier's role
|
||||
// guards, the decoder, ServerMain's control loop) runs on a session's own thread and
|
||||
// therefore gets ITS session - which is what makes one process able to serve several.
|
||||
static ServerSession* Active();
|
||||
|
||||
ServerSession();
|
||||
@@ -197,6 +194,11 @@ namespace MobileGL::MG_Remote::Server {
|
||||
Bool PeerSharedSegments() const { return m_peerSharedSegments; }
|
||||
// Teardown: after the apply thread has been joined, never before - a record still in
|
||||
// flight can still resolve a segment offset (table 3's fourth column).
|
||||
//
|
||||
// P14 S2: AND IT IS IDEMPOTENT, because a served session is now a stack object. A session
|
||||
// that has been closed once (RunSession closes it explicitly) is closed again by its
|
||||
// destructor; the second call must not run the teardown twice. Accept re-opens it, so the
|
||||
// in-process display server's accept/close/accept cycle is unchanged.
|
||||
void Close();
|
||||
|
||||
Transport::SessionSegments& Shm();
|
||||
@@ -329,6 +331,45 @@ namespace MobileGL::MG_Remote::Server {
|
||||
Bool AdoptT0Quiet() const { return m_adoptT0Quiet; }
|
||||
AdoptInbox& T0Inbox() { return m_adoptInbox; }
|
||||
|
||||
// ---- P14 S1 (docs/Disaggregated/design/11-state-ownership.md): the session's contexts -
|
||||
//
|
||||
// THE PLACEHOLDER TABLE. `CreateContext`/`DestroyContext` on the control plane build and
|
||||
// destroy an entry per client token; `BindContext` on the ring makes one of them the
|
||||
// session's current context. What lives in an entry in THIS slice is the token and the
|
||||
// share group it was derived from - no native EGLContext, no GLContext, no working state
|
||||
// (that is S4's). The table exists so that a token the client names can be proved to
|
||||
// have been created before anything is attributed to it, and so that the S4 slice has a
|
||||
// place to put the runtime it will own.
|
||||
//
|
||||
// WRITES ARE THE APPLY THREAD'S. CreateContext/DestroyContext arrive as control frames
|
||||
// dispatched through the frame channel, BindContext as a record through the decoder, and
|
||||
// both run on mgl-srv-apply - so the table needs no lock. CurrentContextToken() is
|
||||
// atomic because a test reads it from the case's own thread.
|
||||
struct ContextRuntime {
|
||||
Uint64 Token = 0; // the client's context token, dense from 1
|
||||
Uint64 ShareGroupToken = 0; // 0 = this context started a share group
|
||||
Uint32 Flags = 0; // reserved; the control frame's `flags` field, carried verbatim
|
||||
};
|
||||
|
||||
// False when a context with this token already exists, or when the token is 0 (0 is
|
||||
// "no context" everywhere on both planes and is never a creatable context).
|
||||
Bool CreateContext(Uint64 token, Uint64 shareGroupToken, Uint32 flags);
|
||||
// False when no such token exists - a destroy the peer did not create is the control
|
||||
// frame's own refusal to make, not a silent no-op.
|
||||
Bool DestroyContext(Uint64 token);
|
||||
// Binds the session's current context. Token 0 is legal and means "no context" (the
|
||||
// release edge); any other token must have been created, or this is a named refusal.
|
||||
Bool BindContext(Uint64 token);
|
||||
// 0 = no context is bound. Every record the session has applied so far belongs to this
|
||||
// token; a session that never crossed a bind_context has never bound one.
|
||||
Uint64 CurrentContextToken() const { return m_currentContextToken.load(std::memory_order_acquire); }
|
||||
Bool HasContext(Uint64 token) const { return m_contexts.find(token) != m_contexts.end(); }
|
||||
Uint64 ContextCount() const { return static_cast<Uint64>(m_contexts.size()); }
|
||||
Uint64 ContextsCreated() const { return m_contextsCreated; }
|
||||
Uint64 ContextsDestroyed() const { return m_contextsDestroyed; }
|
||||
// The per-session tallies the sink keeps for the two control frames it dispatched.
|
||||
Uint64 ContextBinds() const { return m_contextBinds; }
|
||||
|
||||
private:
|
||||
MobileGLResult BindDataConnection(Transport::ITransport& control, Transport::ILink& link,
|
||||
const Uint8* nonce);
|
||||
@@ -354,6 +395,9 @@ namespace MobileGL::MG_Remote::Server {
|
||||
Bool m_consumedSet = false;
|
||||
Bool m_sizesSet = false;
|
||||
Bool m_accepted = false;
|
||||
// P14 S2: Close() has run for the current accept. Cleared by Accept, which is what keeps
|
||||
// the in-process display server's accept/close/accept cycle working.
|
||||
Bool m_closed = false;
|
||||
ApplyPeer m_peer = ApplyPeer::InProcess;
|
||||
Bool m_peerSharedSegments = true;
|
||||
// PH-6. Written by the apply thread (the only SEG_EVENT producer), reset by Accept.
|
||||
@@ -376,10 +420,27 @@ namespace MobileGL::MG_Remote::Server {
|
||||
Uint64 m_t0Bytes = 0;
|
||||
Uint64 m_t0Declined = 0;
|
||||
Uint64 m_t0Refusals = 0;
|
||||
// P14 S1. Apply-thread-only map (see ContextRuntime); the current token is atomic for
|
||||
// the reader on a test thread. Reset by Accept.
|
||||
UnorderedMap<Uint64, ContextRuntime> m_contexts;
|
||||
std::atomic<Uint64> m_currentContextToken{0};
|
||||
Uint64 m_contextsCreated = 0;
|
||||
Uint64 m_contextsDestroyed = 0;
|
||||
Uint64 m_contextBinds = 0;
|
||||
};
|
||||
|
||||
// Leak-at-exit like every other MG_Remote singleton (ID-8): no frontend destructor may
|
||||
// reach pipe or backend state from an exit handler.
|
||||
//
|
||||
// P14 S2 (SessionRuntime.h): THE SINGLETON IS THE FALLBACK, NOT THE SESSION. On a thread that
|
||||
// belongs to a served session (ServerMain::RunSession's control thread, or that session's
|
||||
// mgl-srv-apply) this answers with THAT session; every other thread - the client process, the
|
||||
// inproc one-process client+server shape, a unit case - keeps getting the leaked instance.
|
||||
ServerSession& ServerSessionInstance();
|
||||
|
||||
// P14 S2: sessions accepted and not yet closed in this process. A process-wide fact that must
|
||||
// outlive one session (the reverse-channel callback table, the segment resolver) is released
|
||||
// only when this reaches zero.
|
||||
Uint32 ServerSessionCount();
|
||||
|
||||
} // namespace MobileGL::MG_Remote::Server
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
// MobileGL - MobileGL/MG_Remote/Server/SessionRuntime.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
|
||||
|
||||
// P14 S2: the per-session runtime and the thread routing (SessionRuntime.h states the shape).
|
||||
|
||||
#include "SessionRuntime.h"
|
||||
|
||||
#include <MG_Backend/DirectGLES/DirectGLES.h>
|
||||
#include <MG_Remote/FatalFunnel.h>
|
||||
#include <MG_Remote/Wire/PipeWireCodec.h>
|
||||
|
||||
#include <atomic>
|
||||
|
||||
namespace MobileGL::MG_Remote::Server {
|
||||
|
||||
namespace {
|
||||
// The calling thread's session. nullptr on every thread that is not one of a session's own
|
||||
// two, which is the whole of the fallback rule.
|
||||
thread_local SessionRuntime* t_runtime = nullptr;
|
||||
|
||||
// The resolver MG_Pipe asks per thread. Installing it is a single store of a function
|
||||
// pointer that is never replaced, so it needs no lock and no teardown: the server role
|
||||
// lives for the process (ID-8).
|
||||
MG_Pipe::PipeInputs* ResolveThreadInputs() {
|
||||
SessionRuntime* runtime = t_runtime;
|
||||
return runtime != nullptr ? &runtime->Inputs() : nullptr;
|
||||
}
|
||||
|
||||
// P14 S4 (docs/Disaggregated/design/11-state-ownership.md). THE NATIVE TUPLE'S KEY. The
|
||||
// backend keys its per-context native state - the EGLContext, its config, the draw/read
|
||||
// binding - on (session, client context token); this is the one place that answers the pair
|
||||
// for the calling thread. The session half is the runtime's ADDRESS, which is stable for the
|
||||
// session's whole life and unique among live sessions in the process; the token half is what
|
||||
// `bind_context` last set on the ring. False (== the {0,0} key) on any thread that is not a
|
||||
// session's own, which is the client process, the inproc one-process shape and every unit
|
||||
// case - i.e. exactly the single-context world the backend still serves unchanged.
|
||||
Bool ResolveThreadNativeContextKey(Uint64* outSessionKey, Uint64* outContextToken) {
|
||||
SessionRuntime* runtime = t_runtime;
|
||||
if (runtime == nullptr) return false;
|
||||
*outSessionKey = reinterpret_cast<Uint64>(runtime);
|
||||
*outContextToken = runtime->Session().CurrentContextToken();
|
||||
return true;
|
||||
}
|
||||
|
||||
// P14 S5 (docs/Disaggregated/design/11-state-ownership.md). WHOSE APPLIER IS THIS THREAD
|
||||
// IN? The same two-word answer as the native key above, and deliberately the same
|
||||
// spelling: the session half is the ServerSession's own address - which is the key the
|
||||
// registration side uses (ServerSession::CreateContext passes `this`), so the two agree
|
||||
// by construction rather than by two conventions - and the token half is what
|
||||
// `bind_context` last set on this session's ring. A thread that is not a session's
|
||||
// answers false and gets the process-wide applier, i.e. the single-context world every
|
||||
// other shape in this tree still runs.
|
||||
Bool ResolveThreadApplierKey(MG_Pipe::MGPipeApplierKey* outKey) {
|
||||
SessionRuntime* runtime = t_runtime;
|
||||
if (runtime == nullptr) return false;
|
||||
outKey->SessionKey = reinterpret_cast<Uint64>(&runtime->Session());
|
||||
outKey->ContextToken = runtime->Session().CurrentContextToken();
|
||||
return true;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
void Detail::InstallSessionRuntimeHooks() {
|
||||
if (MG_Pipe::g_pipeInputsThreadResolver != &ResolveThreadInputs) {
|
||||
MG_Pipe::g_pipeInputsThreadResolver = &ResolveThreadInputs;
|
||||
}
|
||||
MG_Backend::DirectGLES::SetNativeContextKeyResolver(&ResolveThreadNativeContextKey);
|
||||
MG_Pipe::MGPipeSetApplierKeyResolver(&ResolveThreadApplierKey);
|
||||
}
|
||||
|
||||
SessionRuntime* Detail::CurrentRuntime() { return t_runtime; }
|
||||
|
||||
ServerSession* Detail::CurrentSession() {
|
||||
SessionRuntime* runtime = t_runtime;
|
||||
return runtime != nullptr ? &runtime->Session() : nullptr;
|
||||
}
|
||||
|
||||
ServerLoop* Detail::CurrentLoop() {
|
||||
SessionRuntime* runtime = t_runtime;
|
||||
return runtime != nullptr ? &runtime->Loop() : nullptr;
|
||||
}
|
||||
|
||||
MG_Pipe::PipeInputs* Detail::CurrentInputs() { return ResolveThreadInputs(); }
|
||||
|
||||
Detail::ThreadSessionScope::ThreadSessionScope(SessionRuntime& runtime) {
|
||||
InstallSessionRuntimeHooks();
|
||||
m_previous = t_runtime;
|
||||
t_runtime = &runtime;
|
||||
m_previousLatchDomain = FatalLatchDomainBind(runtime.LatchDomain());
|
||||
// The segment resolver is the OTHER process-wide hook that used to mean "one session": the
|
||||
// thunk is one function pointer for the process, and which TABLE it answers from is now
|
||||
// per thread (PipeWireCodec.h). Bound before anything on this thread can decode a record.
|
||||
runtime.Session().Segments().BindThreadResolver();
|
||||
}
|
||||
|
||||
Detail::ThreadSessionScope::~ThreadSessionScope() {
|
||||
if (m_previous != nullptr) {
|
||||
m_previous->Session().Segments().BindThreadResolver();
|
||||
} else {
|
||||
Wire::SegmentTable::UnbindThreadResolver();
|
||||
}
|
||||
FatalLatchDomainBind(m_previousLatchDomain);
|
||||
t_runtime = m_previous;
|
||||
}
|
||||
|
||||
SessionRuntime::SessionRuntime()
|
||||
: m_latchDomain(FatalLatchDomainOpen()) {}
|
||||
|
||||
SessionRuntime::~SessionRuntime() {
|
||||
// P14 S5: this runtime's session is the key every applier it registered was filed
|
||||
// under, so the last act of the session is to drop them. Safe here for the reason the
|
||||
// latch domain is (SessionLoop::Stop has joined the apply thread; the control thread's
|
||||
// scope outlives this object), and idempotent against Accept's own release.
|
||||
MG_Pipe::MGPipeApplierReleaseSession(reinterpret_cast<Uint64>(&m_session));
|
||||
// No thread may still be bound to this domain: the apply thread is joined by
|
||||
// ServerLoop::Stop and the control thread's scope outlives this object.
|
||||
FatalLatchDomainClose(m_latchDomain);
|
||||
m_latchDomain = 0;
|
||||
}
|
||||
|
||||
Uint32 LiveServerSessionCount() { return ServerSessionCount(); }
|
||||
|
||||
} // namespace MobileGL::MG_Remote::Server
|
||||
@@ -0,0 +1,103 @@
|
||||
// MobileGL - MobileGL/MG_Remote/Server/SessionRuntime.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
|
||||
|
||||
// P14 S2 (docs/Disaggregated/design/11-state-ownership.md): ONE SERVED SESSION'S PROCESS-LOCAL
|
||||
// STATE, and the routing that lets the rest of the tree keep spelling the singletons.
|
||||
//
|
||||
// WHAT THE SINGLETONS WERE. ServerSessionInstance()/ServerLoopInstance() were the session, so one
|
||||
// session per process was a property of every file that named them. This slice gives each served
|
||||
// session its own {ServerSession, ServerLoop, PipeInputs} triple, held here, and resolves the two
|
||||
// singleton accessors through the CALLING THREAD's session - which is what makes the ~900 sites
|
||||
// that spell gPipeInputs, MGB_CTX, ServerSession::Active() or ServerLoopInstance() find the right
|
||||
// one without one line of any of them moving.
|
||||
//
|
||||
// WHO IS A SESSION THREAD. Two threads per session, both created by the session itself:
|
||||
// * the CONTROL thread - ServerMain::RunSession's own thread, which reads the Hello, drives the
|
||||
// blocking control pump and ends the session (a std::thread per session in the supervisors, a
|
||||
// forked process in the `--serve` worker shape);
|
||||
// * the APPLY thread - ServerLoop's mgl-srv-apply, which applies the ring and owns the backend.
|
||||
// ThreadSessionScope is installed on both, first thing. A thread with no scope resolves to the
|
||||
// process-wide defaults, which is exactly the old behaviour and is what the CLIENT process, the
|
||||
// inproc one-process client+server shape and every unit case keep getting.
|
||||
//
|
||||
// THE INPROC CLIENT+SERVER SHAPE IS DELIBERATELY UNTOUCHED. ClientSession::Start calls
|
||||
// ServerLoopInstance().Start(ServerSessionInstance()) and never opens a scope, so its applier and
|
||||
// its app thread still share the one process-wide PipeInputs block - the verb barrier's premise
|
||||
// (one block two roles alternate on) is a property of that shape and this file must not break it.
|
||||
// Only ServerMain::RunSession, which serves a session with its own transport, opens a scope.
|
||||
|
||||
#pragma once
|
||||
#include <Includes.h>
|
||||
#include <MG_Backend/MGPipe/PipeInputs.h>
|
||||
|
||||
#include "ServerLoop.h"
|
||||
#include "ServerSession.h"
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
namespace MobileGL::MG_Remote::Server {
|
||||
|
||||
class SessionRuntime {
|
||||
public:
|
||||
SessionRuntime();
|
||||
~SessionRuntime();
|
||||
SessionRuntime(const SessionRuntime&) = delete;
|
||||
SessionRuntime& operator=(const SessionRuntime&) = delete;
|
||||
|
||||
ServerSession& Session() { return m_session; }
|
||||
ServerLoop& Loop() { return m_loop; }
|
||||
MG_Pipe::PipeInputs& Inputs() { return m_inputs; }
|
||||
|
||||
// The latch domain this session owns (FatalFunnel.h). A named fault latched by one session
|
||||
// must not end another, and must not be cleared by another's reap.
|
||||
int LatchDomain() const { return m_latchDomain; }
|
||||
|
||||
private:
|
||||
ServerSession m_session;
|
||||
ServerLoop m_loop;
|
||||
MG_Pipe::PipeInputs m_inputs;
|
||||
int m_latchDomain = 0;
|
||||
};
|
||||
|
||||
namespace Detail {
|
||||
// The session of the CALLING thread, or nullptr when it is not a session's own thread.
|
||||
SessionRuntime* CurrentRuntime();
|
||||
ServerSession* CurrentSession();
|
||||
ServerLoop* CurrentLoop();
|
||||
// What MG_Pipe's per-thread resolver asks for: the calling thread's block, or nullptr for
|
||||
// "use the process-wide one".
|
||||
MG_Pipe::PipeInputs* CurrentInputs();
|
||||
|
||||
// Installs the process-wide hooks the per-session blocks need (the PipeInputs resolver).
|
||||
// Idempotent, and called by ThreadSessionScope itself so no bring-up order can miss it.
|
||||
void InstallSessionRuntimeHooks();
|
||||
|
||||
// THE SCOPE. Makes `runtime` the calling thread's session for as long as it lives: the
|
||||
// session/loop the singleton accessors answer with, the PipeInputs block MGB_CTX reads,
|
||||
// this session's segment resolver and this session's latch domain. Restores what was there
|
||||
// before on the way out (two nested scopes are not a shape anything uses, but a thread that
|
||||
// served one session and is then reused must not keep answering with the dead one).
|
||||
class ThreadSessionScope {
|
||||
public:
|
||||
explicit ThreadSessionScope(SessionRuntime& runtime);
|
||||
~ThreadSessionScope();
|
||||
ThreadSessionScope(const ThreadSessionScope&) = delete;
|
||||
ThreadSessionScope& operator=(const ThreadSessionScope&) = delete;
|
||||
|
||||
private:
|
||||
SessionRuntime* m_previous = nullptr;
|
||||
int m_previousLatchDomain = 0;
|
||||
};
|
||||
} // namespace Detail
|
||||
|
||||
// Sessions accepted and not yet closed in THIS process. 1 is the old shape; more is this
|
||||
// slice's. ServerSession::Close gates the process-wide hooks (the reverse-channel table, the
|
||||
// segment resolver) on it, and ServerMain logs it beside each session it starts.
|
||||
Uint32 LiveServerSessionCount();
|
||||
|
||||
} // namespace MobileGL::MG_Remote::Server
|
||||
@@ -24,6 +24,8 @@ namespace MobileGL::MG_Remote::Server {
|
||||
case SurfaceControlOp::ReleaseResources: return "ReleaseResources";
|
||||
case SurfaceControlOp::SetWindowHandle: return "SetWindowHandle";
|
||||
case SurfaceControlOp::InitCapabilities: return "InitCapabilities";
|
||||
case SurfaceControlOp::CreateContext: return "CreateContext";
|
||||
case SurfaceControlOp::DestroyContext: return "DestroyContext";
|
||||
case SurfaceControlOp::SwapBuffersInprocOnly: return "SwapBuffersInprocOnly";
|
||||
case SurfaceControlOp::InitWindowSurfaceInprocOnly: return "InitWindowSurfaceInprocOnly";
|
||||
case SurfaceControlOp::ProbeForTesting: return "ProbeForTesting";
|
||||
@@ -47,6 +49,11 @@ namespace MobileGL::MG_Remote::Server {
|
||||
// frame, which is why this row was missing; the request still has to
|
||||
// cross, because under spawn the apply thread is in another process.
|
||||
case SurfaceControlOp::InitCapabilities:
|
||||
// P14 S1: the context lifecycle. The client's eglCreateContext/eglDestroyContext have a
|
||||
// live caller under spawn (EGLImpl), so unlike the inproc-only trio beside them these two
|
||||
// MUST cross - the server it is asking is in another process.
|
||||
case SurfaceControlOp::CreateContext:
|
||||
case SurfaceControlOp::DestroyContext:
|
||||
return true;
|
||||
default:
|
||||
return false;
|
||||
@@ -60,7 +67,6 @@ namespace MobileGL::MG_Remote::Server {
|
||||
case SurfaceRefusalCode::NoServerWindow: return "NoServerWindow";
|
||||
case SurfaceRefusalCode::SurfaceModeMismatch: return "SurfaceModeMismatch";
|
||||
case SurfaceRefusalCode::ServerOwnedOnSetWindowHandle: return "ServerOwnedOnSetWindowHandle";
|
||||
case SurfaceRefusalCode::HostFrameOnSetWindowHandle: return "HostFrameOnSetWindowHandle";
|
||||
}
|
||||
return "<unknown SurfaceRefusalCode>";
|
||||
}
|
||||
|
||||
@@ -65,13 +65,25 @@ namespace MobileGL::MG_Remote::Server {
|
||||
// every spawned eglMakeCurrent died at "surface op kind 11 cannot cross
|
||||
// the wire (InprocOnlyOpOnTheWire)", one call after the backend came up.
|
||||
InitCapabilities = 11,
|
||||
// P14 S1 (docs/Disaggregated/design/11-state-ownership.md). The EGL context lifecycle,
|
||||
// appended to the schema and to this enum together so the identity cast below stays the
|
||||
// whole mapping: the client's eglCreateContext/eglDestroyContext reach the server through
|
||||
// THE SAME frame channel the nine surface forwarders use, on the same thread, in the same
|
||||
// order - which is the property this slice needs and a second channel would not give.
|
||||
CreateContext = 12,
|
||||
DestroyContext = 13,
|
||||
// INPROC-ONLY kinds: legal inside this process's frame channel, NEVER encodable onto the
|
||||
// wire (SurfaceOpCodec refuses them by name). f0-egl's census found no production caller
|
||||
// for the two dead forwarders; they ride the same frame channel because the
|
||||
// function-pointer mailbox is GONE, not because they are wire ops.
|
||||
SwapBuffersInprocOnly = 12, // present travels as a record (the class-B Present emitter)
|
||||
InitWindowSurfaceInprocOnly = 13,// a client-side no-op; kept for the inproc test lane
|
||||
ProbeForTesting = 14, // MG_Test's arbitrary-work seam through the same channel
|
||||
//
|
||||
// THEIR VALUES MOVED 12/13/14 -> 14/15/16 when P14 S1 appended the two context ops. That
|
||||
// is safe by construction: these three never cross a process boundary and are named
|
||||
// symbolically everywhere they are used, so nothing outside this build could have pinned
|
||||
// them - where the eleven above and the two below are wire ABI and may never move.
|
||||
SwapBuffersInprocOnly = 14, // present travels as a record (the class-B Present emitter)
|
||||
InitWindowSurfaceInprocOnly = 15,// a client-side no-op; kept for the inproc test lane
|
||||
ProbeForTesting = 16, // MG_Test's arbitrary-work seam through the same channel
|
||||
};
|
||||
|
||||
// P12 (on-screen server window), D2. THE SERVER-OWNED WINDOW, AS A FRAME-LOCAL TAG.
|
||||
@@ -87,14 +99,6 @@ namespace MobileGL::MG_Remote::Server {
|
||||
// substitutes its own window there; no pointer crosses the wire (Rule G/H).
|
||||
inline constexpr Int kServerOwnedWindowBackend = 0x10000;
|
||||
|
||||
// The OTHER on-screen shape, and its mirror image. With MOBILEGL_IPC_SURFACE=server the
|
||||
// client has no window and the SERVER's own goes into the backend call; with =host the
|
||||
// client still has no window, but the frames are the display host's - it allocates them,
|
||||
// offers each one over the host frame bridge, and puts them on the glass itself. Same
|
||||
// kind of frame-local tag as the one above, and for the same reason: it names no
|
||||
// WindowBackend of MG_Backend's enum, which is in the pull build (gate G1).
|
||||
inline constexpr Int kHostFrameWindowBackend = 0x10001;
|
||||
|
||||
// P12. Why the server declined a surface op, carried back in the reply half (`refusal`). The
|
||||
// values ARE the wire's SurfaceRefusal (protocol.fbs); SurfaceOpCodec pins the agreement with
|
||||
// static_asserts, the way it pins SurfaceControlOp against SurfaceOpKind. None of them latches
|
||||
@@ -105,7 +109,6 @@ namespace MobileGL::MG_Remote::Server {
|
||||
NoServerWindow = 2, // a display, but no window within the wait
|
||||
SurfaceModeMismatch = 3, // D4: the session's surface mode is the other one
|
||||
ServerOwnedOnSetWindowHandle = 4, // SetWindowHandle named the server's own window
|
||||
HostFrameOnSetWindowHandle = 5, // SetWindowHandle named the display host's frames
|
||||
};
|
||||
|
||||
const char* SurfaceRefusalCodeName(SurfaceRefusalCode code);
|
||||
@@ -128,6 +131,11 @@ namespace MobileGL::MG_Remote::Server {
|
||||
Int width = 0;
|
||||
Int height = 0;
|
||||
Int swapInterval = 0;
|
||||
// P14 S1. CreateContext's two values beyond `context` (which is the client context token
|
||||
// itself): the share group the context was derived into, and the reserved flags word the
|
||||
// schema carries so a later attribute has a slot. 0 on every other op.
|
||||
Uint64 shareGroupToken = 0;
|
||||
Uint32 contextFlags = 0;
|
||||
// The reply half: written by the dispatch on the apply thread, read by the poster after
|
||||
// the blocking handshake returns. `ok` is the forwarder's Bool answer; eglMajor/eglMinor
|
||||
// are InitializeDisplay's out values.
|
||||
@@ -153,14 +161,16 @@ namespace MobileGL::MG_Remote::Server {
|
||||
// Exhaustive by the language's aggregate decomposition rule: adding ANY member
|
||||
// without extending this binding is a compile error, so new fields cannot evade it.
|
||||
const auto& [kind, seq, display, surface, readSurface, context, windowBackend,
|
||||
nativeToken, width, height, swapInterval, ok, eglMajor, eglMinor, eventHead,
|
||||
refusal] = frame;
|
||||
nativeToken, width, height, swapInterval, shareGroupToken, contextFlags, ok,
|
||||
eglMajor, eglMinor, eventHead, refusal] = frame;
|
||||
return IsSurfaceControlValue<decltype(kind)> && IsSurfaceControlValue<decltype(seq)> &&
|
||||
IsSurfaceControlValue<decltype(display)> && IsSurfaceControlValue<decltype(surface)> &&
|
||||
IsSurfaceControlValue<decltype(readSurface)> && IsSurfaceControlValue<decltype(context)> &&
|
||||
IsSurfaceControlValue<decltype(windowBackend)> && IsSurfaceControlValue<decltype(nativeToken)> &&
|
||||
IsSurfaceControlValue<decltype(width)> && IsSurfaceControlValue<decltype(height)> &&
|
||||
IsSurfaceControlValue<decltype(swapInterval)> && IsSurfaceControlValue<decltype(ok)> &&
|
||||
IsSurfaceControlValue<decltype(swapInterval)> &&
|
||||
IsSurfaceControlValue<decltype(shareGroupToken)> &&
|
||||
IsSurfaceControlValue<decltype(contextFlags)> && IsSurfaceControlValue<decltype(ok)> &&
|
||||
IsSurfaceControlValue<decltype(eglMajor)> && IsSurfaceControlValue<decltype(eglMinor)> &&
|
||||
IsSurfaceControlValue<decltype(eventHead)> && IsSurfaceControlValue<decltype(refusal)>;
|
||||
}
|
||||
|
||||
@@ -46,13 +46,6 @@ namespace MobileGL::MG_Remote::Transport {
|
||||
class ITransport {
|
||||
public:
|
||||
virtual ~ITransport() = default;
|
||||
// THE AUX DESCRIPTOR CHANNEL, IF THIS TRANSPORT HAS ONE. SCM_RIGHTS needs a socket of its own
|
||||
// (SocketTransport.h:77), and a caller that wants to hand a dma-buf to the server has to name it:
|
||||
// the session's transport is held as an ITransport, so the seam has to answer here rather than in a
|
||||
// downcast. -1 means "this transport carries no descriptors", which is a legal state a caller must
|
||||
// degrade on - the texture then simply has no storage rather than the process failing.
|
||||
virtual int AuxFd() const { return -1; }
|
||||
|
||||
|
||||
ITransport(const ITransport&) = delete;
|
||||
ITransport& operator=(const ITransport&) = delete;
|
||||
|
||||
@@ -180,7 +180,7 @@ namespace MobileGL::MG_Remote::Transport {
|
||||
// For `sm`'s process discipline and for the arm-proof gate: the fds this
|
||||
// transport owns, so a test can assert the child inherited exactly these.
|
||||
int StreamFd() const { return m_streamFd; }
|
||||
int AuxFd() const override { return m_auxFd; }
|
||||
int AuxFd() const { return m_auxFd; }
|
||||
bool IsTcp() const { return m_tcp; }
|
||||
// TCP's second connection belongs exclusively to the data plane.
|
||||
// Taking it disables all descriptor passing on this transport.
|
||||
|
||||
@@ -263,7 +263,8 @@ namespace MobileGL::MG_Remote::Wire {
|
||||
X(SetProgramBindings, MGPProgramBindings) \
|
||||
X(DeleteStreamOutput, MGPStreamOutputBind) \
|
||||
X(ReadPixelsToBuffer, MGPReadbackToBuffer) \
|
||||
X(GetTextureImageToBuffer, MGPReadbackToBuffer)
|
||||
X(GetTextureImageToBuffer, MGPReadbackToBuffer) \
|
||||
X(BindContext, MGPBindContext)
|
||||
|
||||
namespace {
|
||||
|
||||
@@ -375,9 +376,19 @@ namespace MobileGL::MG_Remote::Wire {
|
||||
|
||||
// The process resolver is a plain function pointer with no user datum
|
||||
// (MGPipeHostSpan.h:46), so the table it resolves through has to be found here.
|
||||
//
|
||||
// P14 S2: TWO PLACES, IN THIS ORDER. The CALLING THREAD's binding is the authoritative one
|
||||
// - a served session's threads are bound to that session's table (ThreadSessionScope), so
|
||||
// two sessions in one process never resolve each other's segments. The process-wide table
|
||||
// below is the fallback for a thread with no binding, which is every shape that has only
|
||||
// one session (and is what the thread-bound call reduces to there).
|
||||
SegmentTable* g_processResolverTable = nullptr;
|
||||
thread_local SegmentTable* t_threadResolverTable = nullptr;
|
||||
|
||||
const void* ProcessResolverThunk(Uint32 seg, Uint64 offset, Uint64 size) {
|
||||
if (SegmentTable* const bound = t_threadResolverTable) {
|
||||
return bound->Resolve(seg, offset, size);
|
||||
}
|
||||
if (g_processResolverTable == nullptr) {
|
||||
return nullptr;
|
||||
}
|
||||
@@ -484,24 +495,35 @@ namespace MobileGL::MG_Remote::Wire {
|
||||
return static_cast<const Uint8*>(view.Base) + offset;
|
||||
}
|
||||
|
||||
void SegmentTable::BindThreadResolver() { t_threadResolverTable = this; }
|
||||
|
||||
void SegmentTable::UnbindThreadResolver() { t_threadResolverTable = nullptr; }
|
||||
|
||||
void SegmentTable::InstallProcessResolver() {
|
||||
if (MG_Pipe::gMGPipeSegmentResolver != nullptr && g_processResolverTable != this) {
|
||||
// Table 3: there is exactly ONE gMGPipeSegmentResolver per process, the SERVER
|
||||
// role installs it before the apply thread starts, and the client never resolves a
|
||||
// span at all. Two roles racing on one inline variable is loud rather than silent
|
||||
// because of this line.
|
||||
if (t_threadResolverTable != nullptr && t_threadResolverTable != this) {
|
||||
// Table 3, P14 S2: one thread resolves through ONE table. Two tables on one thread is
|
||||
// the shape this line exists to make loud - a session's threads are per session, so a
|
||||
// well-formed process never reaches it, while a second SESSION (its own threads, its
|
||||
// own table) is exactly what the per-thread binding is for and does not.
|
||||
WireProtocolFatal("SegmentTable::InstallProcessResolver",
|
||||
"a process segment resolver is already installed; the server role "
|
||||
"installs it once, before the apply thread starts");
|
||||
"a process segment resolver is already installed ON THIS THREAD for "
|
||||
"another session's table; a served session's threads belong to one "
|
||||
"session");
|
||||
}
|
||||
if (MG_Pipe::gMGPipeSegmentResolver == nullptr) {
|
||||
MG_Pipe::gMGPipeSegmentResolver = &ProcessResolverThunk;
|
||||
}
|
||||
g_processResolverTable = this;
|
||||
MG_Pipe::gMGPipeSegmentResolver = &ProcessResolverThunk;
|
||||
BindThreadResolver();
|
||||
}
|
||||
|
||||
void SegmentTable::UninstallProcessResolver() {
|
||||
// Teardown order (table 3): uninstall AFTER the join, never before - a record still in
|
||||
// flight can still resolve.
|
||||
MG_Pipe::gMGPipeSegmentResolver = nullptr;
|
||||
// flight can still resolve. P14 S2: this unbinds the calling thread and drops the
|
||||
// process-wide fallback only; the hook stays installed because another session of this
|
||||
// process may still be decoding records (ServerSession::Close gates this call on the last
|
||||
// session).
|
||||
UnbindThreadResolver();
|
||||
g_processResolverTable = nullptr;
|
||||
}
|
||||
|
||||
@@ -2533,6 +2555,16 @@ namespace MobileGL::MG_Remote::Wire {
|
||||
return m_verbs != nullptr &&
|
||||
m_verbs->OnObjectDeath(*static_cast<const MGPHandleOnly*>(payload));
|
||||
|
||||
// ---- P14 S1 (docs/Disaggregated/design/11-state-ownership.md): bind_context, opcode 84.
|
||||
//
|
||||
// The third control record, and the applier_reset shape exactly: a fixed-size POD with
|
||||
// no blob, no tail and no reply, so the generated bounds gate is the whole validation
|
||||
// and the arm hands over. What the sink does with the token - "this session's current
|
||||
// context" - is a session fact, not a shape.
|
||||
case MGPWireOp::BindContext:
|
||||
return m_verbs != nullptr &&
|
||||
m_verbs->OnBindContext(*static_cast<const MGPBindContext*>(payload));
|
||||
|
||||
// ---- P5c rv (CONTRACT-P5C.md §5.3): the residual-value record, opcode 79 -------------
|
||||
//
|
||||
// An ordinary set_* row, unlike the two control records beside it: a fixed-width POD
|
||||
|
||||
@@ -95,10 +95,23 @@ namespace MobileGL::MG_Remote::Wire {
|
||||
const void* Resolve(Uint32 seg, Uint64 offset, Uint64 size) const;
|
||||
|
||||
// Points MG_Pipe::gMGPipeSegmentResolver at this table. Server role only; asserts if
|
||||
// a resolver is already installed, because two roles racing on one inline variable is
|
||||
// the failure this function exists to make loud.
|
||||
// a DIFFERENT table is already installed ON THE CALLING THREAD, because one thread
|
||||
// serving two sessions at once is the failure this function exists to make loud.
|
||||
//
|
||||
// P14 S2: THE TABLE IS PER THREAD, THE HOOK IS PER PROCESS. Several sessions in one
|
||||
// process each have their own table and their own threads, so a second session's install
|
||||
// is neither a race nor an error: it installs the one process-wide thunk (idempotent) and
|
||||
// binds the calling thread to ITS table. g_processResolverTable stays as the fallback for
|
||||
// a thread that bound nothing - the inproc one-process client+server shape, whose apply
|
||||
// thread is created after the app thread's Accept and does not bind.
|
||||
void InstallProcessResolver();
|
||||
// Unbinds the CALLING thread and clears the process-wide fallback. The hook itself stays
|
||||
// installed: another session may still be live, and a null answer from a table-less thunk
|
||||
// is exactly what a null hook answered.
|
||||
static void UninstallProcessResolver();
|
||||
// P14 S2: binds the CALLING thread to this table (ThreadSessionScope's two calls).
|
||||
void BindThreadResolver();
|
||||
static void UnbindThreadResolver();
|
||||
|
||||
private:
|
||||
Transport::ILink* m_link = nullptr;
|
||||
@@ -661,6 +674,19 @@ namespace MobileGL::MG_Remote::Wire {
|
||||
(void)death;
|
||||
return false;
|
||||
}
|
||||
|
||||
// ---- P14 S1 (docs/Disaggregated/design/11-state-ownership.md): bind_context, opcode 84.
|
||||
//
|
||||
// The applier_reset hand-over shape, one plane over: a fixed-size POD the bounds gate has
|
||||
// already proved, no blob, no tail, no reply, so the codec validates nothing further and
|
||||
// the SERVER'S sink does the work - the session's current context token becomes the
|
||||
// record's. It is not an assertion like OnApplierReset's serial: the token is minted by
|
||||
// the client's EGL layer and the server has no independent count of it, so an unknown
|
||||
// token is the sink's own refusal to make and not a shape the codec can check.
|
||||
virtual Bool OnBindContext(const MG_Pipe::MGPBindContext& bind) {
|
||||
(void)bind;
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
// Not thread safe: one decoder on the apply thread, by construction.
|
||||
|
||||
@@ -8,15 +8,6 @@
|
||||
|
||||
#include "Core.h"
|
||||
#include <EGL/eglext.h>
|
||||
// An imported buffer is held by descriptors, and the copy an image takes of one is the platform's
|
||||
// own dup()/close(): unistd.h's where the import exists, io.h's on the Windows build that compiles
|
||||
// this file but never sees EGL_LINUX_DMA_BUF_EXT.
|
||||
#if defined(_WIN32)
|
||||
#include <io.h>
|
||||
#else
|
||||
#include <unistd.h>
|
||||
#endif
|
||||
#include <cerrno>
|
||||
|
||||
namespace MobileGL {
|
||||
namespace MG_State {
|
||||
@@ -39,54 +30,6 @@ namespace MobileGL {
|
||||
return Nullopt;
|
||||
}
|
||||
|
||||
// Taking and closing the descriptor an image owns, per platform. Named rather
|
||||
// than spelled inline so the ownership rule reads the same on both.
|
||||
#if defined(_WIN32)
|
||||
Int DuplicateImageDescriptor(Int fd) { return _dup(fd); }
|
||||
void CloseImageDescriptor(Int fd) { _close(fd); }
|
||||
#else
|
||||
Int DuplicateImageDescriptor(Int fd) { return ::dup(fd); }
|
||||
void CloseImageDescriptor(Int fd) { ::close(fd); }
|
||||
#endif
|
||||
|
||||
// ONE PLANE'S ATTRIBUTE SPELLINGS, in plane order. Plane 0's fd/offset/pitch triple
|
||||
// is EGL_EXT_image_dma_buf_import's; plane 3's triple and every MODIFIER_LO/HI pair
|
||||
// belong to EGL_EXT_image_dma_buf_import_modifiers.
|
||||
struct DmaBufPlaneAttributes {
|
||||
EGLint Fd;
|
||||
EGLint Offset;
|
||||
EGLint Pitch;
|
||||
EGLint ModifierLo;
|
||||
EGLint ModifierHi;
|
||||
};
|
||||
|
||||
constexpr DmaBufPlaneAttributes kDmaBufPlaneAttributes[EGLContext::kMaxImagePlanes] = {
|
||||
{EGL_DMA_BUF_PLANE0_FD_EXT, EGL_DMA_BUF_PLANE0_OFFSET_EXT, EGL_DMA_BUF_PLANE0_PITCH_EXT,
|
||||
EGL_DMA_BUF_PLANE0_MODIFIER_LO_EXT, EGL_DMA_BUF_PLANE0_MODIFIER_HI_EXT},
|
||||
{EGL_DMA_BUF_PLANE1_FD_EXT, EGL_DMA_BUF_PLANE1_OFFSET_EXT, EGL_DMA_BUF_PLANE1_PITCH_EXT,
|
||||
EGL_DMA_BUF_PLANE1_MODIFIER_LO_EXT, EGL_DMA_BUF_PLANE1_MODIFIER_HI_EXT},
|
||||
{EGL_DMA_BUF_PLANE2_FD_EXT, EGL_DMA_BUF_PLANE2_OFFSET_EXT, EGL_DMA_BUF_PLANE2_PITCH_EXT,
|
||||
EGL_DMA_BUF_PLANE2_MODIFIER_LO_EXT, EGL_DMA_BUF_PLANE2_MODIFIER_HI_EXT},
|
||||
{EGL_DMA_BUF_PLANE3_FD_EXT, EGL_DMA_BUF_PLANE3_OFFSET_EXT, EGL_DMA_BUF_PLANE3_PITCH_EXT,
|
||||
EGL_DMA_BUF_PLANE3_MODIFIER_LO_EXT, EGL_DMA_BUF_PLANE3_MODIFIER_HI_EXT},
|
||||
};
|
||||
|
||||
// The EGL spelling of one plane attribute, for the single line a refused image gets:
|
||||
// the attribute list is gone by the time the caller reads eglGetError.
|
||||
String DmaBufPlaneAttributeName(Int plane, const char* role) {
|
||||
return std::format("EGL_DMA_BUF_PLANE{}_{}", plane, role);
|
||||
}
|
||||
|
||||
// Whether the caller mentioned this plane at all, so that a description with a hole
|
||||
// in it can be refused by name instead of silently losing the planes past the hole.
|
||||
Bool HasAnyPlaneAttribute(const EGLAttrib* attribList, Int plane) {
|
||||
const DmaBufPlaneAttributes& attributes = kDmaBufPlaneAttributes[plane];
|
||||
return ParseAttribValue(attribList, attributes.Fd) || ParseAttribValue(attribList, attributes.Offset) ||
|
||||
ParseAttribValue(attribList, attributes.Pitch) ||
|
||||
ParseAttribValue(attribList, attributes.ModifierLo) ||
|
||||
ParseAttribValue(attribList, attributes.ModifierHi);
|
||||
}
|
||||
|
||||
EGLint QueryDefaultX11VisualId() {
|
||||
#if defined(__linux__) && !defined(__ANDROID__)
|
||||
const char* displayName = std::getenv("DISPLAY");
|
||||
@@ -290,6 +233,11 @@ namespace MobileGL {
|
||||
m_contextOwners.erase(ownerIt);
|
||||
}
|
||||
}
|
||||
// P14 S3: the thread's GL state goes back to what it was before this EGL
|
||||
// context was made current on it.
|
||||
if (currentIt->second.RestoreThreadGLState) {
|
||||
pGLContext = Move(currentIt->second.RestoreThreadGLState);
|
||||
}
|
||||
m_threadCurrents.erase(currentIt);
|
||||
DestroyPendingSurfaceIfUnused(drawSurface);
|
||||
DestroyPendingSurfaceIfUnused(readSurface);
|
||||
@@ -349,9 +297,6 @@ namespace MobileGL {
|
||||
|
||||
for (auto imageIt = m_images.begin(); imageIt != m_images.end();) {
|
||||
if (imageIt->second.Display == display) {
|
||||
// The display is going away and takes its images with it, so the descriptors
|
||||
// they own go too: an image erased without this leaks an fd per plane.
|
||||
ReleaseImageDescriptors(imageIt->second);
|
||||
imageIt = m_images.erase(imageIt);
|
||||
} else {
|
||||
++imageIt;
|
||||
@@ -366,6 +311,12 @@ namespace MobileGL {
|
||||
m_contextOwners.erase(ownerIt);
|
||||
}
|
||||
}
|
||||
// Only the CALLING thread's TLS is reachable from here - another
|
||||
// thread's current is dropped from the table, and its own next EGL
|
||||
// call re-establishes the binding.
|
||||
if (threadIt->first == CurrentThreadKey() && threadIt->second.RestoreThreadGLState) {
|
||||
pGLContext = Move(threadIt->second.RestoreThreadGLState);
|
||||
}
|
||||
threadIt = m_threadCurrents.erase(threadIt);
|
||||
} else {
|
||||
++threadIt;
|
||||
@@ -487,12 +438,6 @@ namespace MobileGL {
|
||||
for (SizeT i = 0; attribList[i] != EGL_NONE; i += 2) {
|
||||
const EGLint attr = attribList[i];
|
||||
const EGLint requested = attribList[i + 1];
|
||||
// WHAT DIES HERE, exactly: with an attribute list present this loop is where
|
||||
// eglChooseConfig faults (a NULL list survives it and answers two configs),
|
||||
// and the fault is one instruction inside the attribute switch. These two
|
||||
// lines name the attribute and the config before either is dereferenced.
|
||||
MGLOG_I("chooseConfig: attr=0x%04x requested=%d config=%p", attr, requested,
|
||||
static_cast<const void*>(cfg));
|
||||
if (requested == EGL_DONT_CARE) {
|
||||
continue;
|
||||
}
|
||||
@@ -701,13 +646,7 @@ namespace MobileGL {
|
||||
SetError(EGL_NOT_INITIALIZED);
|
||||
return nullptr;
|
||||
}
|
||||
// EGL_KHR_no_config_context: a context with NO config of its own. It is the shape a
|
||||
// compositor asks for - its contexts are used with whatever framebuffer the frame
|
||||
// needs, so pinning one config to the context would be a claim about the future the
|
||||
// caller does not have - and EGL spells the request as this null handle. A context
|
||||
// that does name a config is validated exactly as before.
|
||||
const Bool noConfigContext = (config == nullptr);
|
||||
if (!noConfigContext && !ValidateConfigOnDisplay(display, config)) {
|
||||
if (!ValidateConfigOnDisplay(display, config)) {
|
||||
SetError(EGL_BAD_CONFIG);
|
||||
return nullptr;
|
||||
}
|
||||
@@ -726,6 +665,30 @@ namespace MobileGL {
|
||||
.MinorVersion = 0,
|
||||
};
|
||||
|
||||
// P14 S1: the wire identity, minted where the context is born. A context that
|
||||
// shares with an existing one joins ITS share group; EGL_NO_CONTEXT starts a new
|
||||
// one. Both tokens are 0-free by construction (the counters start at 1), because
|
||||
// 0 is the wire's "no context" on both planes.
|
||||
contextObject.ClientContextToken = m_nextClientContextToken++;
|
||||
SharedPtr<GLState::ShareGroupState> shareGroup;
|
||||
if (shareCtx != nullptr) {
|
||||
const auto* shared = TryGetContext(shareCtx);
|
||||
if (shared != nullptr && shared->GLStateObject) {
|
||||
shareGroup = shared->GLStateObject->GetShareGroup();
|
||||
contextObject.ShareGroupToken = shared->ShareGroupToken;
|
||||
} else {
|
||||
contextObject.ShareGroupToken = m_nextShareGroupToken++;
|
||||
}
|
||||
} else {
|
||||
contextObject.ShareGroupToken = m_nextShareGroupToken++;
|
||||
}
|
||||
if (!shareGroup) {
|
||||
shareGroup = MakeShared<GLState::ShareGroupState>(contextObject.ShareGroupToken);
|
||||
}
|
||||
// P14 S3: the context's own GL state, sharing the objects (and the name spaces)
|
||||
// of the group above, with bindings, errors and the current program of its own.
|
||||
contextObject.GLStateObject = MakeShared<GLState::GLContext>(shareGroup);
|
||||
|
||||
if (auto value = ParseAttribValue(attribList, EGL_CONTEXT_CLIENT_VERSION); value) {
|
||||
contextObject.ClientVersion = *value;
|
||||
contextObject.MajorVersion = *value;
|
||||
@@ -851,6 +814,37 @@ namespace MobileGL {
|
||||
return ctx && ctx->Display == display;
|
||||
}
|
||||
|
||||
// P14 S1. 0 for an unknown handle or a thread with no current context: 0 is the
|
||||
// wire's "no context" on both planes, so an answer that cannot be given is given as
|
||||
// the value that means "nothing is bound" rather than as a handle-shaped guess.
|
||||
Uint64 EGLContext::GetContextClientToken(EGLContextHandle context) const {
|
||||
const std::lock_guard<std::recursive_mutex> lock(m_mutex);
|
||||
const auto* ctx = TryGetContext(context);
|
||||
return ctx != nullptr ? ctx->ClientContextToken : 0;
|
||||
}
|
||||
|
||||
Uint64 EGLContext::GetContextShareGroupToken(EGLContextHandle context) const {
|
||||
const std::lock_guard<std::recursive_mutex> lock(m_mutex);
|
||||
const auto* ctx = TryGetContext(context);
|
||||
return ctx != nullptr ? ctx->ShareGroupToken : 0;
|
||||
}
|
||||
|
||||
SharedPtr<GLState::GLContext> EGLContext::GetContextGLState(EGLContextHandle context) const {
|
||||
const std::lock_guard<std::recursive_mutex> lock(m_mutex);
|
||||
const auto* ctx = TryGetContext(context);
|
||||
return ctx != nullptr ? ctx->GLStateObject : nullptr;
|
||||
}
|
||||
|
||||
Uint64 EGLContext::CurrentContextClientToken() const {
|
||||
const std::lock_guard<std::recursive_mutex> lock(m_mutex);
|
||||
const auto currentIt = m_threadCurrents.find(CurrentThreadKey());
|
||||
if (currentIt == m_threadCurrents.end()) {
|
||||
return 0;
|
||||
}
|
||||
const auto* ctx = TryGetContext(currentIt->second.Context);
|
||||
return ctx != nullptr ? ctx->ClientContextToken : 0;
|
||||
}
|
||||
|
||||
Bool EGLContext::IsCurrentContextOpenGLCoreProfile() const {
|
||||
const std::lock_guard<std::recursive_mutex> lock(m_mutex);
|
||||
auto currentIt = m_threadCurrents.find(CurrentThreadKey());
|
||||
@@ -1173,18 +1167,6 @@ namespace MobileGL {
|
||||
return surface;
|
||||
}
|
||||
|
||||
// MOBILEGL_IPC_SURFACE=host: the registration is the server-owned one verbatim, because
|
||||
// what makes a window surface host-framed is not its EGL state but where its pixels go -
|
||||
// and that is decided one layer down, by the backend the creation calls next.
|
||||
EGLContext::EGLSurfaceHandle EGLContext::CreateHostFrameWindowSurface(EGLDisplayHandle display,
|
||||
EGLConfigHandle config,
|
||||
const void* nativeWindow,
|
||||
EGLint width, EGLint height,
|
||||
Bool platformWindow) {
|
||||
return CreateServerOwnedWindowSurface(display, config, nativeWindow, width, height,
|
||||
platformWindow);
|
||||
}
|
||||
|
||||
Bool EGLContext::SetSurfaceExtent(EGLSurfaceHandle surface, EGLint width, EGLint height) {
|
||||
const std::lock_guard<std::recursive_mutex> lock(m_mutex);
|
||||
auto surfaceIt = m_surfaces.find(surface);
|
||||
@@ -1332,13 +1314,7 @@ namespace MobileGL {
|
||||
SetError(EGL_BAD_CONTEXT);
|
||||
return false;
|
||||
}
|
||||
// EGL_KHR_surfaceless_context: BOTH surfaces absent is a context that draws into
|
||||
// framebuffers it binds itself, which is how a compositor draws the frames the
|
||||
// display host handed it. One absent and one present stays refused - that is a
|
||||
// pair EGL gives no meaning to, and accepting it would record a draw target that
|
||||
// does not exist.
|
||||
const Bool surfaceless = (draw == EGL_NO_SURFACE && read == EGL_NO_SURFACE);
|
||||
if (!surfaceless && (draw == EGL_NO_SURFACE || read == EGL_NO_SURFACE)) {
|
||||
if (draw == EGL_NO_SURFACE || read == EGL_NO_SURFACE) {
|
||||
SetError(EGL_BAD_MATCH);
|
||||
return false;
|
||||
}
|
||||
@@ -1366,6 +1342,16 @@ namespace MobileGL {
|
||||
}
|
||||
}
|
||||
|
||||
// P14 S3: whatever this thread's GL state was before the first EGL context was
|
||||
// bound to it is what a later release goes back to.
|
||||
SharedPtr<GLState::GLContext> restoreThreadGLState;
|
||||
if (const auto currentIt = m_threadCurrents.find(threadKey);
|
||||
currentIt != m_threadCurrents.end()) {
|
||||
restoreThreadGLState = currentIt->second.RestoreThreadGLState;
|
||||
} else {
|
||||
restoreThreadGLState = pGLContext;
|
||||
}
|
||||
|
||||
ReleaseThreadUnlocked(threadKey);
|
||||
|
||||
m_threadCurrents[threadKey] = ThreadCurrentState{
|
||||
@@ -1373,9 +1359,15 @@ namespace MobileGL {
|
||||
.DrawSurface = draw,
|
||||
.ReadSurface = read,
|
||||
.Context = context,
|
||||
.RestoreThreadGLState = Move(restoreThreadGLState),
|
||||
};
|
||||
if (context != nullptr) {
|
||||
m_contextOwners[context] = threadKey;
|
||||
// P14 S3: this thread's GL calls land in this context's GLContext from here
|
||||
// on, and not before the switch above has been committed.
|
||||
if (const auto* contextObject = TryGetContext(context); contextObject != nullptr) {
|
||||
pGLContext = contextObject->GLStateObject;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
@@ -1542,20 +1534,11 @@ namespace MobileGL {
|
||||
return true;
|
||||
}
|
||||
|
||||
void EGLContext::ReleaseImageDescriptors(ImageObject& imageObject) {
|
||||
for (Int plane = 0; plane < imageObject.PlaneCount; ++plane) {
|
||||
if (imageObject.Planes[plane].Fd >= 0) {
|
||||
CloseImageDescriptor(imageObject.Planes[plane].Fd);
|
||||
imageObject.Planes[plane].Fd = -1;
|
||||
}
|
||||
}
|
||||
imageObject.PlaneCount = 0;
|
||||
}
|
||||
|
||||
EGLContext::EGLImageHandle EGLContext::CreateImage(EGLDisplayHandle display, EGLContextHandle context,
|
||||
EGLenum target, EGLClientBuffer buffer,
|
||||
const EGLAttrib* attribList) {
|
||||
const std::lock_guard<std::recursive_mutex> lock(m_mutex);
|
||||
(void)attribList;
|
||||
if (!IsDisplayInitialized(display)) {
|
||||
SetError(EGL_NOT_INITIALIZED);
|
||||
return EGL_NO_IMAGE;
|
||||
@@ -1565,149 +1548,13 @@ namespace MobileGL {
|
||||
return EGL_NO_IMAGE;
|
||||
}
|
||||
|
||||
ImageObject imageObject = {
|
||||
const auto image = EncodeHandle<EGLImageHandle>(m_nextImageHandle++);
|
||||
m_images[image] = ImageObject{
|
||||
.Display = display,
|
||||
.Context = context,
|
||||
.Target = target,
|
||||
.Buffer = buffer,
|
||||
};
|
||||
|
||||
// EGL_LINUX_DMA_BUF_EXT: the caller handed over a DESCRIPTOR and described the
|
||||
// memory behind it, and that description is the whole image - there is no handle to
|
||||
// import later. Every other target still names a buffer this state cannot see, so
|
||||
// it stays what it was: the record of the target it was made for.
|
||||
if (target == EGL_LINUX_DMA_BUF_EXT) {
|
||||
// ONE line per refusal, naming what was missing: a caller that gets
|
||||
// EGL_BAD_PARAMETER for a buffer it believes it described completely has
|
||||
// nowhere else to look - the attribute list is gone by the time eglGetError is
|
||||
// read, and the frame it wanted to draw into is the frame it cannot.
|
||||
const auto refuse = [&](const String& missing) {
|
||||
SetError(EGL_BAD_PARAMETER);
|
||||
MGLOG_E("eglCreateImage(EGL_LINUX_DMA_BUF_EXT): %s is missing; refusing the image "
|
||||
"(EGL_BAD_PARAMETER)",
|
||||
missing.c_str());
|
||||
};
|
||||
|
||||
const auto width = ParseAttribValue(attribList, EGL_WIDTH);
|
||||
const auto height = ParseAttribValue(attribList, EGL_HEIGHT);
|
||||
const auto fourCC = ParseAttribValue(attribList, EGL_LINUX_DRM_FOURCC_EXT);
|
||||
if (!width) {
|
||||
refuse("EGL_WIDTH");
|
||||
return EGL_NO_IMAGE;
|
||||
}
|
||||
if (!height) {
|
||||
refuse("EGL_HEIGHT");
|
||||
return EGL_NO_IMAGE;
|
||||
}
|
||||
if (!fourCC) {
|
||||
refuse("EGL_LINUX_DRM_FOURCC_EXT");
|
||||
return EGL_NO_IMAGE;
|
||||
}
|
||||
|
||||
// The planes, read and checked BEFORE one descriptor is duplicated, so that a
|
||||
// refusal leaves nothing behind to close.
|
||||
EGLint planeFd[EGLContext::kMaxImagePlanes] = {};
|
||||
EGLint planeOffset[EGLContext::kMaxImagePlanes] = {};
|
||||
EGLint planePitch[EGLContext::kMaxImagePlanes] = {};
|
||||
Uint64 planeModifier[EGLContext::kMaxImagePlanes] = {};
|
||||
Bool planeHasModifier[EGLContext::kMaxImagePlanes] = {};
|
||||
EGLint planeCount = 0;
|
||||
for (Int plane = 0; plane < EGLContext::kMaxImagePlanes; ++plane) {
|
||||
const DmaBufPlaneAttributes& attributes = kDmaBufPlaneAttributes[plane];
|
||||
const auto fd = ParseAttribValue(attribList, attributes.Fd);
|
||||
const auto offset = ParseAttribValue(attribList, attributes.Offset);
|
||||
const auto pitch = ParseAttribValue(attribList, attributes.Pitch);
|
||||
const auto modifierLo = ParseAttribValue(attribList, attributes.ModifierLo);
|
||||
const auto modifierHi = ParseAttribValue(attribList, attributes.ModifierHi);
|
||||
if (!fd && !offset && !pitch && !modifierLo && !modifierHi) {
|
||||
// The caller never mentioned this plane. Planes are positional - the
|
||||
// description carries no plane index - so this ends the list, and a
|
||||
// plane past the hole is refused by name rather than dropped.
|
||||
for (Int higher = plane + 1; higher < EGLContext::kMaxImagePlanes; ++higher) {
|
||||
if (HasAnyPlaneAttribute(attribList, higher)) {
|
||||
refuse(DmaBufPlaneAttributeName(plane, "FD_EXT"));
|
||||
return EGL_NO_IMAGE;
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
// All three of fd/offset/pitch or none, and both halves of the modifier or
|
||||
// neither: a partial triple describes memory no importer could read.
|
||||
if (!fd) {
|
||||
refuse(DmaBufPlaneAttributeName(plane, "FD_EXT"));
|
||||
return EGL_NO_IMAGE;
|
||||
}
|
||||
if (!offset) {
|
||||
refuse(DmaBufPlaneAttributeName(plane, "OFFSET_EXT"));
|
||||
return EGL_NO_IMAGE;
|
||||
}
|
||||
if (!pitch) {
|
||||
refuse(DmaBufPlaneAttributeName(plane, "PITCH_EXT"));
|
||||
return EGL_NO_IMAGE;
|
||||
}
|
||||
if (modifierLo.has_value() != modifierHi.has_value()) {
|
||||
refuse(DmaBufPlaneAttributeName(plane, modifierLo ? "MODIFIER_HI_EXT" : "MODIFIER_LO_EXT"));
|
||||
return EGL_NO_IMAGE;
|
||||
}
|
||||
planeFd[plane] = static_cast<EGLint>(*fd);
|
||||
planeOffset[plane] = static_cast<EGLint>(*offset);
|
||||
planePitch[plane] = static_cast<EGLint>(*pitch);
|
||||
if (modifierLo) {
|
||||
// The modifier arrives in two halves and is one number: DRM cuts a
|
||||
// DRM_FORMAT_MOD_* where EGL takes an EGLint.
|
||||
planeModifier[plane] = (static_cast<Uint64>(static_cast<Uint32>(*modifierHi)) << 32) |
|
||||
static_cast<Uint32>(*modifierLo);
|
||||
planeHasModifier[plane] = true;
|
||||
}
|
||||
planeCount = plane + 1;
|
||||
}
|
||||
if (planeCount == 0) {
|
||||
// A dma-buf image with no plane at all: the description starts here, so
|
||||
// this is the attribute that is missing.
|
||||
refuse(DmaBufPlaneAttributeName(0, "FD_EXT"));
|
||||
return EGL_NO_IMAGE;
|
||||
}
|
||||
|
||||
// THE IMAGE TAKES ITS OWN DESCRIPTORS. The caller's fds stay the caller's -
|
||||
// kwin hands over a dup() of its DmaBufAttributes and closes it as soon as
|
||||
// eglCreateImage returns, and an image that had borrowed it would be holding a
|
||||
// number some other part of the process now owns.
|
||||
for (Int plane = 0; plane < planeCount; ++plane) {
|
||||
const Int ownedFd = DuplicateImageDescriptor(planeFd[plane]);
|
||||
if (ownedFd < 0) {
|
||||
SetError(EGL_BAD_ALLOC);
|
||||
MGLOG_E("eglCreateImage(EGL_LINUX_DMA_BUF_EXT): cannot take a copy of %s=%d (%s); "
|
||||
"refusing the image (EGL_BAD_ALLOC)",
|
||||
DmaBufPlaneAttributeName(plane, "FD_EXT").c_str(), planeFd[plane],
|
||||
std::strerror(errno));
|
||||
ReleaseImageDescriptors(imageObject);
|
||||
return EGL_NO_IMAGE;
|
||||
}
|
||||
imageObject.Planes[plane] = ImagePlane{
|
||||
.Fd = ownedFd,
|
||||
.Offset = planeOffset[plane],
|
||||
.Pitch = planePitch[plane],
|
||||
.Modifier = planeModifier[plane],
|
||||
.HasModifier = planeHasModifier[plane],
|
||||
};
|
||||
// Counted as they are stored, so that a failure below releases exactly what
|
||||
// has been taken.
|
||||
imageObject.PlaneCount = plane + 1;
|
||||
}
|
||||
imageObject.Width = static_cast<EGLint>(*width);
|
||||
imageObject.Height = static_cast<EGLint>(*height);
|
||||
imageObject.FourCC = static_cast<EGLint>(*fourCC);
|
||||
|
||||
MGLOG_D("eglCreateImage(EGL_LINUX_DMA_BUF_EXT): %dx%d fourcc=0x%08x planes=%d plane0(fd=%d "
|
||||
"offset=%d pitch=%d %s0x%016llx)",
|
||||
imageObject.Width, imageObject.Height, imageObject.FourCC, imageObject.PlaneCount,
|
||||
imageObject.Planes[0].Fd, imageObject.Planes[0].Offset, imageObject.Planes[0].Pitch,
|
||||
imageObject.Planes[0].HasModifier ? "modifier=" : "no-modifier=",
|
||||
static_cast<unsigned long long>(imageObject.Planes[0].Modifier));
|
||||
}
|
||||
|
||||
const auto image = EncodeHandle<EGLImageHandle>(m_nextImageHandle++);
|
||||
m_images[image] = imageObject;
|
||||
return image;
|
||||
}
|
||||
|
||||
@@ -1722,9 +1569,6 @@ namespace MobileGL {
|
||||
SetError(EGL_BAD_MATCH);
|
||||
return false;
|
||||
}
|
||||
// The descriptors this image owns die with it. Nothing else in this process holds
|
||||
// them: they are copies, and the caller's originals were never touched.
|
||||
ReleaseImageDescriptors(imageIt->second);
|
||||
m_images.erase(imageIt);
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
#pragma once
|
||||
#include <Includes.h>
|
||||
#include <type_traits>
|
||||
#include <MG_State/GLState/Core.h>
|
||||
|
||||
namespace MobileGL {
|
||||
namespace MG_State {
|
||||
@@ -22,12 +23,6 @@ namespace MobileGL {
|
||||
using EGLSyncHandle = ::EGLSync;
|
||||
using EGLImageHandle = ::EGLImage;
|
||||
|
||||
// How many planes EGL describes an imported buffer with: EGL_DMA_BUF_PLANE0_* comes
|
||||
// from EGL_EXT_image_dma_buf_import, EGL_DMA_BUF_PLANE3_* and every MODIFIER pair
|
||||
// from EGL_EXT_image_dma_buf_import_modifiers. The reader in Core.cpp and the image
|
||||
// object below have to agree on the count, so it is named once.
|
||||
static constexpr Int kMaxImagePlanes = 4;
|
||||
|
||||
EGLContext() = default;
|
||||
|
||||
// Error
|
||||
@@ -75,6 +70,20 @@ namespace MobileGL {
|
||||
Bool IsCurrentContextOpenGLCompatibilityProfile() const;
|
||||
EGLint GetCurrentContextFlags() const;
|
||||
|
||||
// P14 S1. The wire identity of a context, and of the context the CALLING THREAD
|
||||
// has current (0 when it has none - the release edge's value, and the value a
|
||||
// session that never crossed a bind_context answers with). Read by MG_Impl's two
|
||||
// producers: EGLImpl's CreateContext/DestroyContext control frames and PipeFill's
|
||||
// bind_context emission at the make-current edge.
|
||||
Uint64 GetContextClientToken(EGLContextHandle context) const;
|
||||
Uint64 GetContextShareGroupToken(EGLContextHandle context) const;
|
||||
Uint64 CurrentContextClientToken() const;
|
||||
|
||||
// P14 S3. The frontend GL state this context owns, so a caller outside MG_State
|
||||
// can reach the other half of a context it just made current. Null for an
|
||||
// unknown handle.
|
||||
SharedPtr<GLState::GLContext> GetContextGLState(EGLContextHandle context) const;
|
||||
|
||||
// Surface
|
||||
EGLSurfaceHandle CreateWindowSurface(EGLDisplayHandle display, EGLConfigHandle config,
|
||||
NativeWindowType window, const EGLint* attribList);
|
||||
@@ -106,13 +115,6 @@ namespace MobileGL {
|
||||
EGLSurfaceHandle CreateServerOwnedWindowSurface(EGLDisplayHandle display, EGLConfigHandle config,
|
||||
const void* nativeWindow, EGLint width,
|
||||
EGLint height, Bool platformWindow);
|
||||
// MOBILEGL_IPC_SURFACE=host: the same registration under the other on-screen name.
|
||||
// The EGL state does not care which side owns the frames - that is the backend's
|
||||
// business - but a trace has to be able to tell the two runs apart, and the two
|
||||
// paths part company in the backend call that follows.
|
||||
EGLSurfaceHandle CreateHostFrameWindowSurface(EGLDisplayHandle display, EGLConfigHandle config,
|
||||
const void* nativeWindow, EGLint width,
|
||||
EGLint height, Bool platformWindow);
|
||||
// P12: the server's REAL extent of a surface - a server-owned window's geometry, from
|
||||
// the CreateWindowSurface reply and from every surface-changed event after it - so
|
||||
// eglQuerySurface(EGL_WIDTH/EGL_HEIGHT) answers what the server renders at. Unlike
|
||||
@@ -127,57 +129,6 @@ namespace MobileGL {
|
||||
EGLContextHandle GetCurrentContext() const;
|
||||
EGLDisplayHandle GetCurrentDisplay() const;
|
||||
EGLSurfaceHandle GetCurrentSurface(EGLint readdraw) const;
|
||||
// WHAT A HANDLE NAMES, for the GL side of GL_OES_EGL_image: the two entry points in
|
||||
// MG_Impl/GLImpl/Exporting/Definitions.cpp are handed a GLeglImageOES and have to
|
||||
// answer whether it is an image this display created, and with what geometry. A
|
||||
// read-only lookup belongs beside the other queries a caller outside this class
|
||||
// makes, and it is the same object eglCreateImageKHR built and eglDestroyImage
|
||||
// removes - the private one stays private for the class's own use.
|
||||
// WHAT A HANDLE NAMES, for the GL side of GL_OES_EGL_image. The two entry points in
|
||||
// MG_Impl/GLImpl/Exporting/Definitions.cpp are handed a GLeglImageOES and have to
|
||||
// answer (a) whether it is an image this display created and (b) what buffer it
|
||||
// describes. The numbers come back rather than the record itself: the image table and
|
||||
// its layout are this class's own business, and a caller outside it has no use for
|
||||
// either - which is also why this is a function and not a friend declaration.
|
||||
Bool DescribeImage(EGLImageHandle image, EGLint* width, EGLint* height, EGLint* fourCc,
|
||||
EGLint* planeCount) const {
|
||||
const ImageObject* imageObject = TryGetImage(image);
|
||||
if (imageObject == nullptr) {
|
||||
return false;
|
||||
}
|
||||
if (width != nullptr) *width = imageObject->Width;
|
||||
if (height != nullptr) *height = imageObject->Height;
|
||||
if (fourCc != nullptr) *fourCc = imageObject->FourCC;
|
||||
if (planeCount != nullptr) *planeCount = imageObject->PlaneCount;
|
||||
return true;
|
||||
}
|
||||
|
||||
// THE PLANE DESCRIPTORS OF AN IMAGE THIS DISPLAY CREATED, for the one caller that has
|
||||
// to hand them to the render server: the dma-buf import (a texture bound to an imported
|
||||
// EGLImage has no storage on the server, so the server is told which buffer backs it -
|
||||
// one descriptor per plane, over the session transport's SCM_RIGHTS channel). The fd
|
||||
// here is THIS side's dup(), owned by the image; the transport dups again for the
|
||||
// sending process, which is why the caller does not close anything.
|
||||
Bool DescribeImagePlanes(EGLImageHandle image, EGLint* planeCount, EGLint* fds, EGLint* offsets,
|
||||
EGLint* pitches, Uint64* modifiers, Bool* hasModifiers, Int maxPlanes) const {
|
||||
const ImageObject* imageObject = TryGetImage(image);
|
||||
if (imageObject == nullptr) {
|
||||
return false;
|
||||
}
|
||||
Int count = imageObject->PlaneCount;
|
||||
if (count > maxPlanes) count = maxPlanes;
|
||||
if (count < 0) count = 0;
|
||||
if (planeCount != nullptr) *planeCount = count;
|
||||
for (Int plane = 0; plane < count; plane++) {
|
||||
const ImagePlane& described = imageObject->Planes[plane];
|
||||
if (fds != nullptr) fds[plane] = described.Fd;
|
||||
if (offsets != nullptr) offsets[plane] = described.Offset;
|
||||
if (pitches != nullptr) pitches[plane] = described.Pitch;
|
||||
if (modifiers != nullptr) modifiers[plane] = described.Modifier;
|
||||
if (hasModifiers != nullptr) hasModifiers[plane] = described.HasModifier;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
Bool IsDoubleBufferedSurface(EGLSurfaceHandle surface) const;
|
||||
|
||||
// Sync
|
||||
@@ -244,6 +195,17 @@ namespace MobileGL {
|
||||
EGLDisplayHandle Display = EGL_NO_DISPLAY;
|
||||
EGLConfigHandle Config = nullptr;
|
||||
EGLContextHandle SharedContext = nullptr;
|
||||
// P14 S1 (docs/Disaggregated/design/11-state-ownership.md). The wire identity of
|
||||
// this context: `ClientContextToken` is what bind_context carries and what the
|
||||
// server's per-session context table is keyed by, `ShareGroupToken` the group
|
||||
// it was derived into (ShareContext's group, or one of its own). Minted here,
|
||||
// in the one place a context is born, so no caller can invent a second one.
|
||||
Uint64 ClientContextToken = 0;
|
||||
Uint64 ShareGroupToken = 0;
|
||||
// P14 S3. The GL state of THIS EGL context. Its object registries live in the
|
||||
// share group's ShareGroupState (shared with every context that shares with
|
||||
// this one); its bindings, errors and current program are its own.
|
||||
SharedPtr<GLState::GLContext> GLStateObject;
|
||||
EGLenum ClientAPI = EGL_OPENGL_API;
|
||||
EGLint ClientVersion = 1;
|
||||
EGLint MajorVersion = 1;
|
||||
@@ -278,39 +240,11 @@ namespace MobileGL {
|
||||
EGLenum Status = EGL_SIGNALED;
|
||||
};
|
||||
|
||||
// ONE PLANE OF AN IMPORTED BUFFER. The fd/offset/pitch triple is the same
|
||||
// description drmModeAddFB2 takes, and the modifier is the DRM_FORMAT_MOD_* the
|
||||
// caller declared; EGL carries up to four of these (EGL_DMA_BUF_PLANE0..3_*).
|
||||
struct ImagePlane {
|
||||
// THIS library's descriptor, dup()ed from the caller's when the image was made
|
||||
// and closed when it dies: an EGLImage outlives the call that created it, and
|
||||
// the caller is free to close its own fd the moment eglCreateImage returns.
|
||||
EGLint Fd = -1;
|
||||
EGLint Offset = 0;
|
||||
EGLint Pitch = 0;
|
||||
// The two EGL_DMA_BUF_PLANEn_MODIFIER_LO/HI_EXT halves joined back into the
|
||||
// DRM_FORMAT_MOD_* they were cut from.
|
||||
Uint64 Modifier = 0;
|
||||
Bool HasModifier = false;
|
||||
};
|
||||
|
||||
struct ImageObject {
|
||||
EGLDisplayHandle Display = EGL_NO_DISPLAY;
|
||||
EGLContextHandle Context = nullptr;
|
||||
EGLenum Target = EGL_NONE;
|
||||
EGLClientBuffer Buffer = nullptr;
|
||||
// WHAT AN EGL_LINUX_DMA_BUF_EXT IMAGE IS HOLDING, and zero for every other
|
||||
// target: the buffer's geometry and the fourcc that says what its samples mean.
|
||||
// It is kept here because the image is the only thing that outlives the call -
|
||||
// a caller that handed over an fd has nothing left to describe it with.
|
||||
EGLint Width = 0;
|
||||
EGLint Height = 0;
|
||||
EGLint FourCC = 0;
|
||||
EGLint PlaneCount = 0;
|
||||
// Planes 0..PlaneCount-1 are described, in order; index 0 is the plane every
|
||||
// import in this tree reads, the rest are carried because EGL describes them and
|
||||
// a consumer that understands a multi-plane format must be able to see them.
|
||||
ImagePlane Planes[kMaxImagePlanes];
|
||||
};
|
||||
|
||||
struct ThreadCurrentState {
|
||||
@@ -318,6 +252,10 @@ namespace MobileGL {
|
||||
EGLSurfaceHandle DrawSurface = EGL_NO_SURFACE;
|
||||
EGLSurfaceHandle ReadSurface = EGL_NO_SURFACE;
|
||||
EGLContextHandle Context = nullptr;
|
||||
// P14 S3. What pGLContext held on this thread BEFORE the first eglMakeCurrent
|
||||
// bound an EGL context to it, so releasing restores exactly the binding the
|
||||
// thread had rather than a guessed default.
|
||||
SharedPtr<GLState::GLContext> RestoreThreadGLState;
|
||||
};
|
||||
|
||||
template <typename HandleType>
|
||||
@@ -346,9 +284,6 @@ namespace MobileGL {
|
||||
const SurfaceObject* TryGetSurface(EGLSurfaceHandle surface) const;
|
||||
const SyncObject* TryGetSync(EGLSyncHandle sync) const;
|
||||
const ImageObject* TryGetImage(EGLImageHandle image) const;
|
||||
// Closes the descriptors an image owns. Both places an image can die call it:
|
||||
// eglDestroyImage, and eglTerminate, which drops a display's images wholesale.
|
||||
static void ReleaseImageDescriptors(ImageObject& imageObject);
|
||||
|
||||
void ReleaseDisplayObjects(EGLDisplayHandle display);
|
||||
void ReleaseThreadUnlocked(const std::thread::id& threadKey);
|
||||
@@ -364,6 +299,9 @@ namespace MobileGL {
|
||||
Uint64 m_nextContextHandle = 1;
|
||||
Uint64 m_nextSyncHandle = 1;
|
||||
Uint64 m_nextImageHandle = 1;
|
||||
// P14 S1. Dense from 1, never reused, never 0: 0 is "no context" on both planes.
|
||||
Uint64 m_nextClientContextToken = 1;
|
||||
Uint64 m_nextShareGroupToken = 1;
|
||||
|
||||
UnorderedMap<DisplayLookupKey, EGLDisplayHandle, DisplayLookupHasher> m_displayLookup;
|
||||
UnorderedMap<EGLDisplayHandle, DisplayObject> m_displays;
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
#include "BufferState.h"
|
||||
|
||||
namespace MobileGL::MG_State::GLState {
|
||||
BufferState::BufferState() : m_indexGenerator(1024, 1) {
|
||||
BufferState::BufferState() {
|
||||
for (SizeT i = 0; i < m_bindingSlots.size(); ++i) {
|
||||
m_bindingSlots[i] = BindingSlot<BufferObject>(GlobalBufferTargets[i]);
|
||||
}
|
||||
@@ -18,28 +18,6 @@ namespace MobileGL::MG_State::GLState {
|
||||
}
|
||||
}
|
||||
|
||||
const SharedPtr<BufferObject>& BufferState::GetBufferObject(Uint index) {
|
||||
auto it = m_bufferObjects.find(index);
|
||||
if (it != m_bufferObjects.end()) {
|
||||
return it->second;
|
||||
}
|
||||
static SharedPtr<BufferObject> nullBufferObject = nullptr;
|
||||
return nullBufferObject;
|
||||
}
|
||||
|
||||
void BufferState::GenerateNames(Uint number, Vector<Uint>& buffers) {
|
||||
buffers.resize(number);
|
||||
m_indexGenerator.Generate(number, buffers.data());
|
||||
}
|
||||
|
||||
const SharedPtr<BufferObject>& BufferState::CreateBufferObject(Uint index) {
|
||||
auto& bufferObj = m_bufferObjects[index];
|
||||
if (!bufferObj) {
|
||||
bufferObj = MakeShared<BufferObject>(index);
|
||||
}
|
||||
return bufferObj;
|
||||
}
|
||||
|
||||
BindingSlot<BufferObject>& BufferState::GetBindingSlot(BufferTarget target) {
|
||||
for (auto& bindingSlot : m_bindingSlots) {
|
||||
if (bindingSlot.GetTarget() == target) {
|
||||
@@ -50,53 +28,33 @@ namespace MobileGL::MG_State::GLState {
|
||||
return m_bindingSlots[0];
|
||||
}
|
||||
|
||||
void BufferState::MarkBufferObjectForDeletion(Uint index) {
|
||||
if (m_indexGenerator.IsValid(index)) {
|
||||
auto it = m_bufferObjects.find(index);
|
||||
if (it != m_bufferObjects.end()) {
|
||||
for (auto& bindingSlot : m_bindingSlots) {
|
||||
if (bindingSlot.GetBoundObject() == it->second) {
|
||||
bindingSlot.Bind(nullptr);
|
||||
}
|
||||
}
|
||||
for (auto& bindingPointArray : m_bufferBindPointTargets) {
|
||||
for (auto& bindingPoint : bindingPointArray) {
|
||||
if (bindingPoint.GetBoundObject() == it->second) {
|
||||
bindingPoint.Bind(nullptr);
|
||||
bindingPoint.ClearRange();
|
||||
void BufferState::UnbindBufferObject(const SharedPtr<BufferObject>& bufferObject) {
|
||||
if (!bufferObject) return;
|
||||
for (auto& bindingSlot : m_bindingSlots) {
|
||||
if (bindingSlot.GetBoundObject() == bufferObject) {
|
||||
bindingSlot.Bind(nullptr);
|
||||
}
|
||||
}
|
||||
for (auto& bindingPointArray : m_bufferBindPointTargets) {
|
||||
for (auto& bindingPoint : bindingPointArray) {
|
||||
if (bindingPoint.GetBoundObject() == bufferObject) {
|
||||
bindingPoint.Bind(nullptr);
|
||||
bindingPoint.ClearRange();
|
||||
#if MOBILEGL_PIPE_PUSH
|
||||
// An UNBIND, and the one writer of an indexed point that is not an
|
||||
// entry point (GL_Buffer.cpp's BindBuffer{Base,Range}_State and
|
||||
// Core.cpp's transform-feedback writers bump their own): without the
|
||||
// bump the target's window is never re-sent, the server goes on naming
|
||||
// this buffer's handle, and once its slot is reused at a newer
|
||||
// generation the next draw or dispatch that walks the window asks the
|
||||
// backend for the dead one - Espryt dies with Fatal{ProtocolCorruption,
|
||||
// "BackendSlotTable.Generation"} (DeletedBoundBufferScenario).
|
||||
NoteBindPointChanged(BufferBindPointTargets[static_cast<SizeT>(
|
||||
&bindingPointArray - m_bufferBindPointTargets.data())]);
|
||||
// An UNBIND, and the one writer of an indexed point that is not an
|
||||
// entry point (GL_Buffer.cpp's BindBuffer{Base,Range}_State and
|
||||
// Core.cpp's transform-feedback writers bump their own): without the
|
||||
// bump the target's window is never re-sent, the server goes on naming
|
||||
// this buffer's handle, and once its slot is reused at a newer
|
||||
// generation the next draw or dispatch that walks the window asks the
|
||||
// backend for the dead one - Espryt dies with Fatal{ProtocolCorruption,
|
||||
// "BackendSlotTable.Generation"} (DeletedBoundBufferScenario).
|
||||
NoteBindPointChanged(BufferBindPointTargets[static_cast<SizeT>(
|
||||
&bindingPointArray - m_bufferBindPointTargets.data())]);
|
||||
#endif
|
||||
}
|
||||
}
|
||||
}
|
||||
// Erase through the iterator already in hand: erase(key) would repeat the
|
||||
// find() above, and the successor scan that once made key-based
|
||||
// erase the cheaper of the two no longer happens here - erase(iterator)
|
||||
// hands back an unconverted proxy, and the scan is what converting it
|
||||
// would cost. The unbind loops above touch only the binding arrays, so
|
||||
// `it` is still live.
|
||||
m_bufferObjects.erase(it);
|
||||
}
|
||||
m_indexGenerator.Delete(index);
|
||||
}
|
||||
}
|
||||
|
||||
Bool BufferState::ValidateName(Uint index) const {
|
||||
return m_indexGenerator.IsValid(index);
|
||||
}
|
||||
|
||||
Bool BufferState::ValidateBufferObject(Uint index) const {
|
||||
return m_bufferObjects.find(index) != m_bufferObjects.end();
|
||||
}
|
||||
|
||||
BindingSlotRange1D<BufferObject>& BufferState::GetBindingPoint(BufferTarget target, Uint index) {
|
||||
@@ -105,20 +63,7 @@ namespace MobileGL::MG_State::GLState {
|
||||
return m_bufferBindPointTargets[i][index];
|
||||
}
|
||||
}
|
||||
// A GLOBAL TARGET ASKED THROUGH THE INDEXED LOOKUP. Only four targets have per-index binding
|
||||
// points (Uniform, TransformFeedback, AtomicCounter, ShaderStorage); the rest - Vertex, Index,
|
||||
// PixelPack/Unpack, Texture, CopyRead/Write, Query, the indirect ones - are global, and a caller
|
||||
// that asks for one here is reading the wrong accessor, not passing a bad enum.
|
||||
//
|
||||
// This used to abort, and the compositor reached it right after its vertex-attrib setup: the
|
||||
// whole session died on Trace/breakpoint trap ("Invalid BufferTarget enum value for binding
|
||||
// point"). Aborting a compositor over an accessor mix-up is the wrong trade, so the answer is
|
||||
// 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 instead of being a
|
||||
// crash. The proper fix is for that caller to use the global accessor.
|
||||
MGLOG_W_ONCE("BufferState::GetBindingPoint: target=%d has no per-index binding points; answering "
|
||||
"index 0 of the indexed array (a global target was asked through the indexed lookup)",
|
||||
static_cast<int>(target));
|
||||
MOBILEGL_ASSERT(false, "Invalid BufferTarget enum value for binding point: %d", static_cast<int>(target));
|
||||
return m_bufferBindPointTargets[0][index];
|
||||
}
|
||||
} // namespace MobileGL::MG_State::GLState
|
||||
|
||||
@@ -28,13 +28,12 @@ namespace MobileGL::MG_State::GLState {
|
||||
// costs the unused tail of three arrays.
|
||||
constexpr SizeT BufferBindingPointCount = 84;
|
||||
|
||||
// The per-context half of the buffer state: which buffer is bound where. The objects
|
||||
// themselves and their names belong to the share group (ShareGroupState).
|
||||
class BufferState {
|
||||
public:
|
||||
BufferState();
|
||||
|
||||
const SharedPtr<BufferObject>& GetBufferObject(Uint index);
|
||||
void GenerateNames(Uint number, Vector<Uint>& buffers);
|
||||
const SharedPtr<BufferObject>& CreateBufferObject(Uint index);
|
||||
BindingSlot<BufferObject>& GetBindingSlot(BufferTarget target);
|
||||
// For glBindBufferBase / glBindBufferRange
|
||||
BindingSlotRange1D<BufferObject>& GetBindingPoint(BufferTarget target, Uint index);
|
||||
@@ -60,9 +59,9 @@ namespace MobileGL::MG_State::GLState {
|
||||
if (it == BufferBindPointTargets.end()) return 0;
|
||||
return m_touchedBindPointCount[std::distance(BufferBindPointTargets.begin(), it)];
|
||||
}
|
||||
void MarkBufferObjectForDeletion(Uint index);
|
||||
Bool ValidateName(Uint index) const;
|
||||
Bool ValidateBufferObject(Uint index) const;
|
||||
// Detaches a deleted buffer from THIS context's bindings only (GL 4.6 core 6.1: a delete
|
||||
// resets the deleting context's bindings, and other contexts keep their own).
|
||||
void UnbindBufferObject(const SharedPtr<BufferObject>& bufferObject);
|
||||
|
||||
#if MOBILEGL_PIPE_PUSH
|
||||
// P2 brief D4: "did the contents of ANY buffer object move". One counter for every
|
||||
@@ -110,8 +109,6 @@ namespace MobileGL::MG_State::GLState {
|
||||
Uint64 m_anyBufferChangeGeneration = 0;
|
||||
Array<Uint64, BufferBindPointTargets.size()> m_bindPointGeneration{};
|
||||
#endif
|
||||
UnorderedMap<Uint, SharedPtr<BufferObject>> m_bufferObjects;
|
||||
IndexGenerator<Uint> m_indexGenerator;
|
||||
Array<BindingSlot<BufferObject>, GlobalBufferTargets.size()> m_bindingSlots;
|
||||
// TODO: query the count somewhere globally?
|
||||
// For glBindBufferBase / glBindBufferRange
|
||||
|
||||
@@ -18,9 +18,52 @@
|
||||
#include <MG_Pipe/PipeMutation.h>
|
||||
|
||||
namespace MobileGL::MG_State {
|
||||
namespace {
|
||||
// Leak-at-exit storage; see GlobalObjects.cpp.
|
||||
SharedPtr<GLState::GLContext>& DefaultGLContextSlot() {
|
||||
static SharedPtr<GLState::GLContext>* slot = new SharedPtr<GLState::GLContext>();
|
||||
return *slot;
|
||||
}
|
||||
|
||||
SharedPtr<GLState::FramebufferObject>& DefaultFramebufferSlot() {
|
||||
static SharedPtr<GLState::FramebufferObject>* slot = new SharedPtr<GLState::FramebufferObject>();
|
||||
return *slot;
|
||||
}
|
||||
}
|
||||
|
||||
const SharedPtr<GLState::GLContext>& ProcessDefaultGLContext() {
|
||||
auto& slot = DefaultGLContextSlot();
|
||||
if (!slot) {
|
||||
slot = MakeShared<GLState::GLContext>();
|
||||
}
|
||||
return slot;
|
||||
}
|
||||
|
||||
void ReleaseProcessDefaultGLContext() {
|
||||
auto& slot = DefaultGLContextSlot();
|
||||
// Only the calling thread's TLS is reachable here, and only when it is still holding the
|
||||
// fallback rather than an EGL context of its own.
|
||||
if (pGLContext == slot) pGLContext.reset();
|
||||
DefaultFramebufferSlot().reset();
|
||||
slot.reset();
|
||||
}
|
||||
|
||||
void SetDefaultFramebuffer(SharedPtr<GLState::FramebufferObject> framebuffer) {
|
||||
DefaultFramebufferSlot() = Move(framebuffer);
|
||||
}
|
||||
|
||||
const SharedPtr<GLState::FramebufferObject>& DefaultFramebuffer() {
|
||||
return DefaultFramebufferSlot();
|
||||
}
|
||||
|
||||
void Init() {
|
||||
MGLOG_D("Initializing MobileGL State...");
|
||||
pGLContext = MakeUnique<GLState::GLContext>();
|
||||
// Rebuilt on every Initialize(): the fallback context starts empty, so a thread that
|
||||
// never crossed an eglMakeCurrent cannot see the previous run's objects. The default
|
||||
// framebuffer is rebuilt too - MG_Impl::Init() installs the new one right after.
|
||||
DefaultFramebufferSlot().reset();
|
||||
DefaultGLContextSlot() = MakeShared<GLState::GLContext>();
|
||||
pGLContext = ProcessDefaultGLContext();
|
||||
pEGLContext = MakeUnique<EGLState::EGLContext>();
|
||||
}
|
||||
|
||||
@@ -89,11 +132,11 @@ namespace MobileGL::MG_State {
|
||||
|
||||
// Buffer
|
||||
void GLContext::GenBufferNames(Uint number, Vector<Uint>& buffers) {
|
||||
m_bufferState.GenerateNames(number, buffers);
|
||||
Group().GenerateBufferNames(number, buffers);
|
||||
}
|
||||
|
||||
const SharedPtr<BufferObject>& GLContext::GetBufferObject(Uint index) {
|
||||
return m_bufferState.GetBufferObject(index);
|
||||
return Group().GetBufferObject(index);
|
||||
}
|
||||
|
||||
BindingSlot<BufferObject>& GLContext::GetBufferBindingSlot(BufferTarget target) {
|
||||
@@ -111,7 +154,7 @@ namespace MobileGL::MG_State {
|
||||
}
|
||||
|
||||
const SharedPtr<BufferObject>& GLContext::CreateBufferObject(Uint index) {
|
||||
return m_bufferState.CreateBufferObject(index);
|
||||
return Group().CreateBufferObject(index);
|
||||
}
|
||||
|
||||
void GLContext::MarkBufferObjectForDeletion(Uint index) {
|
||||
@@ -123,7 +166,7 @@ namespace MobileGL::MG_State {
|
||||
// previous every-VAO scan was wrong per spec and O(VAOs) per delete —
|
||||
// with one VAO per chunk section, vanilla's steady buffer churn made it
|
||||
// dominate the render thread and FPS decay over session time.
|
||||
auto bufferObject = m_bufferState.GetBufferObject(index);
|
||||
const auto bufferObject = Group().GetBufferObject(index);
|
||||
const auto& vao = m_vertexArrayState.GetBoundVertexArray();
|
||||
if (vao != nullptr) {
|
||||
if (vao->GetIndexBufferBindingSlot().GetBoundObject() == bufferObject) {
|
||||
@@ -135,17 +178,18 @@ namespace MobileGL::MG_State {
|
||||
}
|
||||
}
|
||||
}
|
||||
m_bufferState.UnbindBufferObject(bufferObject);
|
||||
}
|
||||
|
||||
m_bufferState.MarkBufferObjectForDeletion(index);
|
||||
Group().MarkBufferObjectForDeletion(index);
|
||||
}
|
||||
|
||||
Bool GLContext::ValidateBufferName(Uint index) const {
|
||||
return m_bufferState.ValidateName(index);
|
||||
return m_shareGroup->ValidateBufferName(index);
|
||||
}
|
||||
|
||||
Bool GLContext::ValidateBufferObject(Uint index) const {
|
||||
return m_bufferState.ValidateBufferObject(index);
|
||||
return m_shareGroup->ValidateBufferObject(index);
|
||||
}
|
||||
|
||||
// VertexArray
|
||||
@@ -269,11 +313,11 @@ namespace MobileGL::MG_State {
|
||||
|
||||
// Texture
|
||||
void GLContext::GenTextureNames(Uint number, Vector<Uint>& textures) {
|
||||
m_textureState.GenerateNames(number, textures);
|
||||
Group().GenerateTextureNames(number, textures);
|
||||
}
|
||||
|
||||
const SharedPtr<ITextureObject>& GLContext::GetTextureObject(Uint index) {
|
||||
return m_textureState.GetTextureObject(index);
|
||||
return Group().GetTextureObject(index);
|
||||
}
|
||||
|
||||
const SharedPtr<ITextureObject>& GLContext::GetDefaultTextureObject(TextureTarget target) const {
|
||||
@@ -281,14 +325,14 @@ namespace MobileGL::MG_State {
|
||||
}
|
||||
|
||||
const SharedPtr<ITextureObject>& GLContext::CreateTextureObject(Uint index, TextureTarget target) {
|
||||
return m_textureState.CreateTextureObject(index, target);
|
||||
return Group().CreateTextureObject(index, target);
|
||||
}
|
||||
|
||||
const SharedPtr<ITextureObject>& GLContext::CreateTextureViewObject(
|
||||
Uint index, TextureTarget target, const SharedPtr<ITextureObject>& storageOwner, Uint minLevel,
|
||||
Uint numLevels, Uint minLayer, Uint numLayers) {
|
||||
return m_textureState.CreateTextureViewObject(index, target, storageOwner, minLevel, numLevels, minLayer,
|
||||
numLayers);
|
||||
return Group().CreateTextureViewObject(index, target, storageOwner, minLevel, numLevels, minLayer,
|
||||
numLayers);
|
||||
}
|
||||
|
||||
void GLContext::MarkTextureObjectForDeletion(Uint index) {
|
||||
@@ -302,7 +346,8 @@ namespace MobileGL::MG_State {
|
||||
// contents rather than those of whatever the application put in its place - the name
|
||||
// it deleted usually comes straight back from the next glGenTextures, so the two are
|
||||
// indistinguishable from the outside (KHR-GL32.packed_pixels read a stale gradient).
|
||||
if (const auto& textureObject = m_textureState.GetTextureObject(index)) {
|
||||
const auto textureObject = Group().GetTextureObject(index);
|
||||
if (textureObject) {
|
||||
for (SizeT targetIndex = 0; targetIndex < SizeT(FramebufferTarget::FramebufferTargetCount);
|
||||
++targetIndex) {
|
||||
const auto& framebuffer =
|
||||
@@ -318,7 +363,10 @@ namespace MobileGL::MG_State {
|
||||
}
|
||||
}
|
||||
}
|
||||
m_textureState.MarkTextureObjectForDeletion(index, IsRelaxedSemanticsActive());
|
||||
// This context's units only: the object is gone for every context in the share
|
||||
// group, but each of them detaches it from its own bindings (GL 4.6 core 8.1).
|
||||
m_textureState.UnbindTextureFromUnits(textureObject);
|
||||
Group().MarkTextureObjectForDeletion(index, IsRelaxedSemanticsActive());
|
||||
}
|
||||
|
||||
TextureUnit& GLContext::GetTextureUnitObject(Int unit) {
|
||||
@@ -334,11 +382,11 @@ namespace MobileGL::MG_State {
|
||||
}
|
||||
|
||||
Bool GLContext::ValidateTextureName(Uint index) const {
|
||||
return m_textureState.ValidateName(index);
|
||||
return m_shareGroup->ValidateTextureName(index);
|
||||
}
|
||||
|
||||
Bool GLContext::ValidateTextureObject(Uint index) const {
|
||||
return m_textureState.ValidateTextureObject(index);
|
||||
return m_shareGroup->ValidateTextureObject(index);
|
||||
}
|
||||
|
||||
Int GLContext::GetActiveTextureUnit() const {
|
||||
@@ -351,51 +399,67 @@ namespace MobileGL::MG_State {
|
||||
|
||||
// Program
|
||||
Uint GLContext::CreateProgram() {
|
||||
return m_programState.CreateProgram();
|
||||
return Group().Programs().CreateProgram();
|
||||
}
|
||||
|
||||
Uint GLContext::CreateShader(const ShaderStage stage) {
|
||||
return m_programState.CreateShader(stage);
|
||||
return Group().Programs().CreateShader(stage);
|
||||
}
|
||||
|
||||
void GLContext::MarkProgramForDeletion(const Uint index) {
|
||||
return m_programState.MarkProgramObjectForDeletion(index);
|
||||
return Group().Programs().MarkProgramObjectForDeletion(index, m_currentProgram);
|
||||
}
|
||||
|
||||
void GLContext::MarkShaderForDeletion(const Uint index) {
|
||||
return m_programState.MarkShaderObjectForDeletion(index);
|
||||
return Group().Programs().MarkShaderObjectForDeletion(index, m_currentProgram);
|
||||
}
|
||||
|
||||
void GLContext::ReleaseShaderNameIfOrphaned(const Uint index) {
|
||||
return m_programState.ReleaseShaderNameIfOrphaned(index);
|
||||
return Group().Programs().ReleaseShaderNameIfOrphaned(index, m_currentProgram);
|
||||
}
|
||||
|
||||
Bool GLContext::ValidateProgramName(const Uint index) const {
|
||||
return m_programState.ValidateProgramObject(index);
|
||||
return m_shareGroup->Programs().ValidateProgramObject(index);
|
||||
}
|
||||
|
||||
Bool GLContext::ValidateShaderName(const Uint index) const {
|
||||
return m_programState.ValidateShaderObject(index);
|
||||
return m_shareGroup->Programs().ValidateShaderObject(index);
|
||||
}
|
||||
|
||||
const SharedPtr<ProgramObject>& GLContext::GetProgramObject(const Uint index) {
|
||||
return m_programState.GetProgramObject(index);
|
||||
return Group().Programs().GetProgramObject(index);
|
||||
}
|
||||
|
||||
const SharedPtr<ShaderObject>& GLContext::GetShaderObject(const Uint index) {
|
||||
return m_programState.GetShaderObject(index);
|
||||
return Group().Programs().GetShaderObject(index);
|
||||
}
|
||||
|
||||
void GLContext::JoinAllPendingShaderWork() {
|
||||
m_programState.JoinAllPendingWork();
|
||||
Group().Programs().JoinAllPendingWork(m_currentProgram);
|
||||
}
|
||||
|
||||
void GLContext::UseProgram(Uint program) {
|
||||
return m_programState.UseProgram(program);
|
||||
const SharedPtr<ProgramObject> previous = m_currentProgram;
|
||||
|
||||
if (program == 0) m_currentProgram.reset();
|
||||
|
||||
auto& programs = Group().Programs();
|
||||
if (programs.HasProgramSlot(program)) {
|
||||
m_currentProgram = programs.GetProgramObject(program);
|
||||
}
|
||||
|
||||
// A deletion flagged while the program was current takes effect the moment it
|
||||
// stops being current.
|
||||
if (previous != nullptr && previous != m_currentProgram && previous->GetDeleteStatus()) {
|
||||
const Uint previousName = previous->GetExternalIndex();
|
||||
if (programs.HasProgramSlot(previousName) && programs.GetProgramObject(previousName) == previous) {
|
||||
programs.MarkProgramObjectForDeletion(previousName, m_currentProgram);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const SharedPtr<ProgramObject>& GLContext::GetCurrentProgram() {
|
||||
return m_programState.GetCurrentProgram();
|
||||
return m_currentProgram;
|
||||
}
|
||||
|
||||
// Copies every default-block uniform value `source` holds into the same-named uniform of
|
||||
@@ -608,7 +672,7 @@ namespace MobileGL::MG_State {
|
||||
|
||||
const SharedPtr<ProgramObject>& GLContext::GetProgramForDraw() {
|
||||
static const SharedPtr<ProgramObject> nullProgram = nullptr;
|
||||
const auto& currentProgram = m_programState.GetCurrentProgram();
|
||||
const auto& currentProgram = GetCurrentProgram();
|
||||
if (currentProgram) {
|
||||
// P1 join site J1, plain glUseProgram half. The backends read a program's
|
||||
// lifetimeId / backendStateVersion / UBO content version to decide whether
|
||||
@@ -762,7 +826,7 @@ namespace MobileGL::MG_State {
|
||||
|
||||
const SharedPtr<ProgramObject>& GLContext::GetProgramForDispatch() {
|
||||
static const SharedPtr<ProgramObject> nullProgram = nullptr;
|
||||
const auto& currentProgram = m_programState.GetCurrentProgram();
|
||||
const auto& currentProgram = GetCurrentProgram();
|
||||
if (currentProgram) {
|
||||
// Same join contract as GetProgramForDraw's glUseProgram half - see the note
|
||||
// there. A dispatch reads the same non-artifact versions a draw does.
|
||||
@@ -784,7 +848,7 @@ namespace MobileGL::MG_State {
|
||||
}
|
||||
|
||||
const SharedPtr<ProgramObject>& GLContext::GetProgramForUniform() {
|
||||
const auto& currentProgram = m_programState.GetCurrentProgram();
|
||||
const auto& currentProgram = GetCurrentProgram();
|
||||
if (currentProgram) return currentProgram;
|
||||
static const SharedPtr<ProgramObject> nullProgram = nullptr;
|
||||
if (m_boundProgramPipeline == 0) return nullProgram;
|
||||
@@ -1220,21 +1284,21 @@ namespace MobileGL::MG_State {
|
||||
|
||||
// Sampler
|
||||
void GLContext::GenSamplerNames(Uint number, Vector<Uint>& samplers) {
|
||||
m_samplerState.GenerateNames(number, samplers);
|
||||
Group().Samplers().GenerateNames(number, samplers);
|
||||
}
|
||||
|
||||
const SharedPtr<SamplerObject>& GLContext::GetSamplerObject(Uint index) {
|
||||
return m_samplerState.GetSamplerObject(index);
|
||||
return Group().Samplers().GetSamplerObject(index);
|
||||
}
|
||||
|
||||
const SharedPtr<SamplerObject>& GLContext::CreateSamplerObject(Uint index) {
|
||||
return m_samplerState.CreateSamplerObject(index);
|
||||
return Group().Samplers().CreateSamplerObject(index);
|
||||
}
|
||||
|
||||
void GLContext::MarkSamplerObjectForDeletion(Uint index) {
|
||||
// Unbind the sampler from all texture units
|
||||
if (ValidateSamplerObject(index)) {
|
||||
auto sampler = m_samplerState.GetSamplerObject(index);
|
||||
auto sampler = Group().Samplers().GetSamplerObject(index);
|
||||
for (Int unit = 0; unit < TextureState::MAX_TEXTURE_IMAGE_UNITS; ++unit) {
|
||||
auto& textureUnit = m_textureState.GetUnitObject(unit);
|
||||
if (textureUnit.GetSamplerObject() == sampler) {
|
||||
@@ -1242,24 +1306,24 @@ namespace MobileGL::MG_State {
|
||||
}
|
||||
}
|
||||
}
|
||||
m_samplerState.MarkSamplerObjectForDeletion(index);
|
||||
Group().Samplers().MarkSamplerObjectForDeletion(index);
|
||||
}
|
||||
|
||||
Bool GLContext::ValidateSamplerName(Uint index) const {
|
||||
return m_samplerState.ValidateName(index);
|
||||
return m_shareGroup->Samplers().ValidateName(index);
|
||||
}
|
||||
|
||||
Bool GLContext::ValidateSamplerObject(Uint index) const {
|
||||
return m_samplerState.ValidateSamplerObject(index);
|
||||
return m_shareGroup->Samplers().ValidateSamplerObject(index);
|
||||
}
|
||||
|
||||
// Renderbuffer
|
||||
void GLContext::GenRenderbufferNames(Uint number, Vector<Uint>& renderbuffers) {
|
||||
m_renderbufferState.GenerateNames(number, renderbuffers);
|
||||
Group().GenerateRenderbufferNames(number, renderbuffers);
|
||||
}
|
||||
|
||||
const SharedPtr<RenderbufferObject>& GLContext::GetRenderbufferObject(Uint index) {
|
||||
return m_renderbufferState.GetRenderbufferObject(index);
|
||||
return Group().GetRenderbufferObject(index);
|
||||
}
|
||||
|
||||
BindingSlot<RenderbufferObject>& GLContext::GetRenderbufferBindingSlot(RenderbufferTarget target) {
|
||||
@@ -1267,19 +1331,21 @@ namespace MobileGL::MG_State {
|
||||
}
|
||||
|
||||
const SharedPtr<RenderbufferObject>& GLContext::CreateRenderbufferObject(Uint index) {
|
||||
return m_renderbufferState.CreateRenderbufferObject(index);
|
||||
return Group().CreateRenderbufferObject(index);
|
||||
}
|
||||
|
||||
void GLContext::MarkRenderbufferObjectForDeletion(Uint index) {
|
||||
m_renderbufferState.MarkRenderbufferObjectForDeletion(index);
|
||||
const auto renderbufferObject = Group().GetRenderbufferObject(index);
|
||||
m_renderbufferState.UnbindRenderbufferObject(renderbufferObject);
|
||||
Group().MarkRenderbufferObjectForDeletion(index);
|
||||
}
|
||||
|
||||
Bool GLContext::ValidateRenderbufferName(Uint index) const {
|
||||
return m_renderbufferState.ValidateName(index);
|
||||
return m_shareGroup->ValidateRenderbufferName(index);
|
||||
}
|
||||
|
||||
Bool GLContext::ValidateRenderbufferObject(Uint index) const {
|
||||
return m_renderbufferState.ValidateRenderbufferObject(index);
|
||||
return m_shareGroup->ValidateRenderbufferObject(index);
|
||||
}
|
||||
|
||||
Uint64 GLContext::AllocateTransformFeedbackLifetimeId() {
|
||||
@@ -1288,12 +1354,23 @@ namespace MobileGL::MG_State {
|
||||
return nextId.fetch_add(1, std::memory_order_relaxed);
|
||||
}
|
||||
|
||||
GLContext::GLContext() {
|
||||
GLContext::GLContext() : GLContext(MakeShared<ShareGroupState>()) {}
|
||||
|
||||
GLContext::GLContext(SharedPtr<ShareGroupState> shareGroup)
|
||||
: m_shareGroup(shareGroup ? Move(shareGroup) : MakeShared<ShareGroupState>()) {
|
||||
// The default transform feedback object (name 0) exists from the start of the context
|
||||
// (GL 4.6 core 13.2.1), but nothing binds it, so nothing else would materialise it.
|
||||
// Materialising it here is what lets GetBoundTransformFeedbackLifetimeId() be a plain
|
||||
// const read instead of an operator[] insert on the draw path.
|
||||
m_boundTransformFeedbackLifetimeId = m_transformFeedbackObjects[0].lifetimeId;
|
||||
InstallDefaultFramebuffer(DefaultFramebuffer());
|
||||
}
|
||||
|
||||
void GLContext::InstallDefaultFramebuffer(const SharedPtr<FramebufferObject>& framebuffer) {
|
||||
if (!framebuffer) return;
|
||||
m_framebufferState.RegisterFramebufferObject(0, framebuffer);
|
||||
m_framebufferState.GetBindingSlot(FramebufferTarget::Draw).Bind(framebuffer);
|
||||
m_framebufferState.GetBindingSlot(FramebufferTarget::Read).Bind(framebuffer);
|
||||
}
|
||||
|
||||
Bool GLContext::HasOpenTransformFeedbackSpan(Uint64 lifetimeId) const {
|
||||
@@ -1562,5 +1639,5 @@ namespace MobileGL::MG_State {
|
||||
} // namespace GLState
|
||||
|
||||
// Leak-at-exit storage; see GlobalObjects.cpp.
|
||||
UniquePtr<GLState::GLContext>& pGLContext = *new UniquePtr<GLState::GLContext>();
|
||||
thread_local SharedPtr<GLState::GLContext> pGLContext;
|
||||
} // namespace MobileGL::MG_State
|
||||
|
||||
@@ -16,6 +16,7 @@
|
||||
#include "ProgramState/ProgramState.h"
|
||||
#include "ProgramState/ProgramPipelineObject.h"
|
||||
#include "SamplerState/SamplerState.h"
|
||||
#include "ShareGroupState.h"
|
||||
#include "TextureState/TextureState.h"
|
||||
#include "FramebufferState/FramebufferState.h"
|
||||
#include "VertexArrayState/VertexArrayState.h"
|
||||
@@ -76,7 +77,19 @@ namespace MobileGL {
|
||||
|
||||
class GLContext {
|
||||
public:
|
||||
// A context with a share group of its own. Created through EGL, a context
|
||||
// either starts a new group or joins the one its share context belongs to;
|
||||
// this constructor is the standalone shape the tests and the process default
|
||||
// context use.
|
||||
GLContext();
|
||||
explicit GLContext(SharedPtr<ShareGroupState> shareGroup);
|
||||
|
||||
// The GL objects this context shares with every context that shares with it.
|
||||
const SharedPtr<ShareGroupState>& GetShareGroup() const { return m_shareGroup; }
|
||||
|
||||
// Installs the process-wide default framebuffer (GL name 0) into this context:
|
||||
// its table entry and the Draw/Read bindings the context starts with.
|
||||
void InstallDefaultFramebuffer(const SharedPtr<FramebufferObject>& framebuffer);
|
||||
|
||||
// Error
|
||||
void RecordError(ErrorCode code, UniquePtr<ErrorInfo> info);
|
||||
@@ -188,7 +201,7 @@ namespace MobileGL {
|
||||
// P1 stage 6: the per-context index of adoptable compile nodes, for its
|
||||
// adoption counter. Diagnostics and tests only - no GL entry point reads it.
|
||||
ShaderCompileAdoptionMap& GetShaderCompileAdoptionMap() {
|
||||
return m_programState.GetShaderCompileAdoptionMap();
|
||||
return Group().Programs().GetShaderCompileAdoptionMap();
|
||||
}
|
||||
void UseProgram(Uint program);
|
||||
const SharedPtr<ProgramObject>& GetCurrentProgram();
|
||||
@@ -606,6 +619,10 @@ namespace MobileGL {
|
||||
void InvalidateCompileEnv();
|
||||
|
||||
private:
|
||||
ShareGroupState& Group() const { return *m_shareGroup; }
|
||||
|
||||
// The GL objects shared with every context that shares with this one.
|
||||
SharedPtr<ShareGroupState> m_shareGroup;
|
||||
// State Components
|
||||
ErrorState m_errorState;
|
||||
BufferState m_bufferState;
|
||||
@@ -685,10 +702,11 @@ namespace MobileGL {
|
||||
IndexGenerator<Uint> m_programPipelineNames;
|
||||
Uint m_boundProgramPipeline = 0;
|
||||
TextureState m_textureState;
|
||||
ProgramState m_programState;
|
||||
// The program this context has in use. Program STATE (the objects) belongs to
|
||||
// the share group; which of them is current does not.
|
||||
SharedPtr<ProgramObject> m_currentProgram;
|
||||
RenderState m_renderState;
|
||||
FramebufferState m_framebufferState;
|
||||
SamplerState m_samplerState;
|
||||
RenderbufferState m_renderbufferState;
|
||||
|
||||
mutable SharedPtr<const MG_Util::ShaderTranspiler::CompileEnv> m_compileEnv;
|
||||
@@ -698,7 +716,32 @@ namespace MobileGL {
|
||||
};
|
||||
} // namespace GLState
|
||||
|
||||
extern UniquePtr<GLState::GLContext>& pGLContext;
|
||||
// P14 S3 (docs/Disaggregated/design/11-state-ownership.md): the GL state the CALLING
|
||||
// THREAD's GL entry points read and write. eglMakeCurrent points it at that EGL
|
||||
// context's GLContext, and the EGL release edge puts it back to whatever it was, so a
|
||||
// thread that never crossed an eglMakeCurrent keeps the process default MG_State::Init()
|
||||
// gave it. NULL on a thread for which neither has happened, the same answer a process
|
||||
// that never reached MG_State::Init() (the spawn server image) has always given.
|
||||
extern thread_local SharedPtr<GLState::GLContext> pGLContext;
|
||||
|
||||
// The fallback pGLContext starts at and an EGL release edge restores to: the process's
|
||||
// one context for every thread that never bound an EGL context to itself, created on
|
||||
// demand and owned here (leak-at-exit, like every other process global).
|
||||
const SharedPtr<GLState::GLContext>& ProcessDefaultGLContext();
|
||||
|
||||
// Drops the process default context and this thread's binding to it, and the default
|
||||
// framebuffer with them. Called on the teardown edge (the last eglTerminate, before
|
||||
// MobileGL::Destroy()) so the objects MG_State::Init() built do not outlive
|
||||
// glslang::FinalizeProcess() through a thread that kept its fallback binding.
|
||||
void ReleaseProcessDefaultGLContext();
|
||||
|
||||
// P14 S3. GL framebuffer 0, built by MG_Impl once the backend is up (it needs texture
|
||||
// objects, which need the backend's resource plumbing) and handed back here so every
|
||||
// GLContext a later eglCreateContext builds starts with the same default framebuffer
|
||||
// bound. Until the backend grows per-context native tuples there is exactly one such
|
||||
// object, which is what the backend's own default-framebuffer identity tests assume.
|
||||
void SetDefaultFramebuffer(SharedPtr<GLState::FramebufferObject> framebuffer);
|
||||
const SharedPtr<GLState::FramebufferObject>& DefaultFramebuffer();
|
||||
|
||||
// True when relaxed GL semantics apply. Strict core rules are enforced only when the
|
||||
// current EGL context explicitly requested a core profile (core bit in
|
||||
|
||||
@@ -13,23 +13,6 @@
|
||||
#include <atomic>
|
||||
#include <MG_Pipe/PipeMutation.h>
|
||||
|
||||
// The display host's frame, as the backend publishes it (MG_Backend/DirectGLES/DirectGLES.h).
|
||||
// DECLARED HERE RATHER THAN INCLUDED, and that is a deliberate compromise with a named end: the
|
||||
// client asks whether its framebuffer is complete BEFORE any backend binding runs, so this judgement
|
||||
// cannot ask the backend - and the frontend knowing a backend fact is exactly what a record is for.
|
||||
// The wire does not carry one yet (MG_Protocol's dispatch has no glEGLImageTargetTexture2DOES), so
|
||||
// the fact is read from where it already is; when that record lands, this block goes with it.
|
||||
// The backend namespace is the one DirectGLES.cpp:67 opens and defines these in - the SAME nesting
|
||||
// as Uint g_hostFrameFramebufferId beside them. Getting this wrong is not a typo with no cost: a
|
||||
// Linux shared library links with undefined symbols allowed, so the container build passed while the
|
||||
// Android server build (ld.lld, --no-undefined) named all three - which is how a latent runtime
|
||||
// failure was caught by the platform that builds the render server.
|
||||
namespace MobileGL::MG_Backend::DirectGLES {
|
||||
extern Uint g_hostFrameRenderbuffer;
|
||||
extern Uint g_hostFrameWidth;
|
||||
extern Uint g_hostFrameHeight;
|
||||
}
|
||||
|
||||
namespace MobileGL::MG_State::GLState {
|
||||
// Starts at 1 so a zero-initialized memo slot can never carry a live object's id.
|
||||
// Atomic for the same reason as the VAO counter: it costs nothing, and a duplicate
|
||||
@@ -191,34 +174,8 @@ namespace MobileGL::MG_State::GLState {
|
||||
|
||||
Int width = -1, height = -1;
|
||||
Int validAttachmentCount = 0;
|
||||
// THE IMPORTED dma-buf, and why it is judged BEFORE the validity test rather than after it.
|
||||
// Measured: with kwin_wayland's framebuffer attached - it imports the display daemon's
|
||||
// dma-buf as an EGLImage ("taking target 0x8d65 over an EGLImage of 1440x2937 fourcc
|
||||
// 0x34324241") and builds an FBO over that texture - the server answered
|
||||
// "GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT". The old early-continue below dropped the
|
||||
// attachment (a texture that arrived this way has no storage, so it reports itself invalid)
|
||||
// and the completeness gate further down was never reached.
|
||||
//
|
||||
// THE GATE IS THE MEASURED SHAPE, and it is deliberately narrow: this process is holding a
|
||||
// display host frame (g_hostFrameRenderbuffer != 0), and the attachment is a texture with no
|
||||
// storage of its own. That buffer IS the frame the host handed this process - same memory -
|
||||
// and the backend binds the frame's renderbuffer in place of the empty texture
|
||||
// (MG_Backend/DirectGLES/Managers.cpp). A size comparison would be the sharper test and is
|
||||
// impossible here: the imported attachment has no size, which is exactly why the wire needs a
|
||||
// record to say so (MG_Protocol's dispatch has no glEGLImageTargetTexture2DOES yet); when it
|
||||
// lands, this gate is replaced by that record and nothing else changes.
|
||||
// AND IT DELIBERATELY DOES NOT ASK WHETHER THE FRAME IS IN HAND YET, which the first version
|
||||
// of this gate did - and that version did not work, measured: kwin imports the dma-buf and
|
||||
// builds its framebuffer BEFORE the host-framed surface exists, so g_hostFrameRenderbuffer is
|
||||
// still zero at the instant the client asks, the gate refused, and kwin printed
|
||||
// "GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT" again. What the attachment IS is the fact
|
||||
// that holds at that instant: a texture with no storage of its own is the imported dma-buf,
|
||||
// and the buffer it names is the display daemon's frame - the one this process is about to be
|
||||
// handed. The backend binds that frame's renderbuffer to the attachment as soon as it has
|
||||
// one (Managers.cpp re-syncs attachments per draw, so the first draw after the frame arrives
|
||||
// lands in it).
|
||||
for (const auto& attachmentObject : m_attachmentObjects) {
|
||||
if (!attachmentObject.IsValid() && !attachmentObject.IsTexture()) continue;
|
||||
if (!attachmentObject.IsValid()) continue;
|
||||
|
||||
++validAttachmentCount;
|
||||
const auto& attachment = attachmentObject;
|
||||
@@ -233,44 +190,7 @@ namespace MobileGL::MG_State::GLState {
|
||||
return false;
|
||||
}
|
||||
|
||||
// AN IMPORTED dma-buf COUNTS AS COMPLETE, in the measured shape and no other: the
|
||||
// attachment has no storage of its own and this process holds a display host frame of the
|
||||
// same size. Measured, and the reason this is here at all: kwin_wayland imports the
|
||||
// display daemon's dma-buf as an EGLImage ("taking target 0x8d65 over an EGLImage of
|
||||
// 1440x2937 fourcc 0x34324241") and then refuses its own framebuffer with "framebuffer for
|
||||
// dmabuf 0 is not complete" - a refusal that is WRONG here, because the buffer it imported
|
||||
// IS the frame the display host handed this process (same memory, same size) and the
|
||||
// backend binds that frame's renderbuffer in place of the empty texture
|
||||
// (MG_Backend/DirectGLES/Managers.cpp, the external-OES arm under the same gate). A size
|
||||
// that differs, or no frame held, keeps the old answer: an ordinary empty attachment is
|
||||
// still incomplete, and nothing is ever rendered into a buffer of the wrong size.
|
||||
// AND IT DOES NOT ASK WHETHER A FRAME IS HELD, OR HOW BIG IT IS - which the first version
|
||||
// of this gate did, and which is why it never worked. This judgement runs on BOTH sides
|
||||
// of a split run: the client answers glCheckFramebufferStatus out of its own state before
|
||||
// any backend binding happens, and the client holds no frame at all. So a gate that
|
||||
// required g_hostFrameRenderbuffer != 0 and a matching size refused on the client every
|
||||
// time, and kwin kept printing "Invalid framebuffer status:
|
||||
// GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT" - measured, twice, after that gate was
|
||||
// deployed. What the attachment IS is the fact that holds on both sides: a texture with
|
||||
// no storage of its own is the imported dma-buf, and the server binds the display host's
|
||||
// frame to it as soon as it has one (Managers.cpp re-syncs the attachments per draw, so
|
||||
// the first draw after the frame arrives lands in it). An attachment that IS valid - an
|
||||
// ordinary texture or renderbuffer with real storage - still has to be complete.
|
||||
// A TEXTURE ATTACHMENT THAT IS NOT COMPLETE IS THE IMPORTED dma-buf, and it counts. The
|
||||
// condition is written on IsTexture() and NOT on IsValid(), which is the mistake two
|
||||
// earlier versions of this gate made - measured both times as
|
||||
// "Invalid framebuffer status: GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT" from a session
|
||||
// that was healthy and had really reached the import:
|
||||
// * requiring a host frame to be in hand refused on the CLIENT, which holds none;
|
||||
// * requiring the attachment to be INVALID refused too, because AttachTexture registers
|
||||
// the attachment (FramebufferObject.cpp:163) whether or not the texture has storage -
|
||||
// so the imported one is perfectly valid and simply incomplete.
|
||||
// What is true on both sides, at that instant, is what this asks: the attachment is a
|
||||
// TEXTURE and it is incomplete, i.e. it has no storage of its own, and the server binds the
|
||||
// display host's frame to it as soon as it holds one (Managers.cpp re-syncs the attachments
|
||||
// per draw). A RENDERBUFFER attachment still has to be complete, so an ordinary empty
|
||||
// attachment of that kind keeps the old refusal.
|
||||
if (!attachment.IsComplete() && !attachment.IsTexture()) {
|
||||
if (!attachment.IsComplete()) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -46,6 +46,14 @@ namespace MobileGL::MG_State::GLState {
|
||||
return framebufferObject;
|
||||
}
|
||||
|
||||
void FramebufferState::RegisterFramebufferObject(Uint index, SharedPtr<FramebufferObject> object) {
|
||||
if (!object) return;
|
||||
if (index == 0 && !m_indexGenerator.IsValid(0)) {
|
||||
m_indexGenerator.Insert(0);
|
||||
}
|
||||
m_framebufferObjects[index] = Move(object);
|
||||
}
|
||||
|
||||
BindingSlot<FramebufferObject>& FramebufferState::GetBindingSlot(FramebufferTarget target) {
|
||||
for (auto& bindingSlot : m_bindingSlots) {
|
||||
if (bindingSlot.GetTarget() == target) {
|
||||
|
||||
@@ -20,6 +20,9 @@ namespace MobileGL::MG_State::GLState {
|
||||
const SharedPtr<FramebufferObject>& GetFramebufferObject(Uint index);
|
||||
void GenerateNames(Uint number, Vector<Uint>& framebuffers);
|
||||
const SharedPtr<FramebufferObject>& CreateFramebufferObject(Uint index);
|
||||
// Puts an already-built object at `index` without the "name 0 is created once" rule,
|
||||
// so a context can adopt the process-wide default framebuffer.
|
||||
void RegisterFramebufferObject(Uint index, SharedPtr<FramebufferObject> object);
|
||||
BindingSlot<FramebufferObject>& GetBindingSlot(FramebufferTarget target);
|
||||
void MarkFramebufferObjectForDeletion(Uint index);
|
||||
Bool ValidateName(Uint index) const;
|
||||
|
||||
@@ -25,19 +25,24 @@ namespace MobileGL::MG_State::GLState {
|
||||
return m_programObjects[id];
|
||||
}
|
||||
|
||||
void ProgramState::MarkProgramObjectForDeletion(const Uint program) {
|
||||
Bool ProgramState::HasProgramSlot(const Uint program) const {
|
||||
return CheckIndexAvail(program, m_programObjects);
|
||||
}
|
||||
|
||||
void ProgramState::MarkProgramObjectForDeletion(const Uint program,
|
||||
const SharedPtr<ProgramObject>& currentProgram) {
|
||||
if (!CheckIndexAvail(program, m_programObjects)) return; // FIXME: add error reporting here
|
||||
auto& programObject = m_programObjects[program];
|
||||
if (programObject != nullptr) {
|
||||
programObject->MarkAsDeleted();
|
||||
// A program in use is only FLAGGED: its name (and every program query) stays
|
||||
// valid until it stops being current, at which point UseProgram finishes the job.
|
||||
if (programObject == m_currentProgram) return;
|
||||
DestroyProgramSlot(program);
|
||||
if (programObject == currentProgram) return;
|
||||
DestroyProgramSlot(program, currentProgram);
|
||||
}
|
||||
}
|
||||
|
||||
void ProgramState::DestroyProgramSlot(const Uint program) {
|
||||
void ProgramState::DestroyProgramSlot(const Uint program, const SharedPtr<ProgramObject>& currentProgram) {
|
||||
auto& programObject = m_programObjects[program];
|
||||
// P1 join site J4/J5 (glDeleteProgram, and the deferred destroy UseProgram performs
|
||||
// when a deletion-flagged program stops being current). The program's name is about
|
||||
@@ -55,7 +60,7 @@ namespace MobileGL::MG_State::GLState {
|
||||
for (const auto& shader : attachedShaders) {
|
||||
const Uint shaderName = shader->GetExternalIndex();
|
||||
if (CheckIndexAvail(shaderName, m_shaderObjects) && m_shaderObjects[shaderName] == shader) {
|
||||
ReleaseShaderNameIfOrphaned(shaderName);
|
||||
ReleaseShaderNameIfOrphaned(shaderName, currentProgram);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -64,25 +69,6 @@ namespace MobileGL::MG_State::GLState {
|
||||
return CheckIndexAvail(program, m_programObjects) && m_programObjects[program] != nullptr;
|
||||
}
|
||||
|
||||
void ProgramState::UseProgram(Uint program) {
|
||||
const SharedPtr<ProgramObject> previous = m_currentProgram;
|
||||
|
||||
if (program == 0) m_currentProgram.reset();
|
||||
|
||||
if (CheckIndexAvail(program, m_programObjects)) {
|
||||
m_currentProgram = m_programObjects[program];
|
||||
}
|
||||
|
||||
// A deletion flagged while the program was current takes effect the moment it
|
||||
// stops being current.
|
||||
if (previous != nullptr && previous != m_currentProgram && previous->GetDeleteStatus()) {
|
||||
const Uint previousName = previous->GetExternalIndex();
|
||||
if (CheckIndexAvail(previousName, m_programObjects) && m_programObjects[previousName] == previous) {
|
||||
DestroyProgramSlot(previousName);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Uint ProgramState::CreateShader(ShaderStage stage) {
|
||||
Uint shaderId = 0;
|
||||
m_programShaderNameGenerator.Generate(1, &shaderId);
|
||||
@@ -100,7 +86,7 @@ namespace MobileGL::MG_State::GLState {
|
||||
return m_shaderObjects[shader];
|
||||
}
|
||||
|
||||
void ProgramState::JoinAllPendingWork() {
|
||||
void ProgramState::JoinAllPendingWork(const SharedPtr<ProgramObject>& currentProgram) {
|
||||
// Programs first: a link joins the compiles it depends on, so the shader pass that
|
||||
// follows finds most of them already settled. The reverse order would be correct but
|
||||
// would wait on each compile twice - once here, once inside the link's own prologue.
|
||||
@@ -126,10 +112,10 @@ namespace MobileGL::MG_State::GLState {
|
||||
// The currently-used program is reachable through m_programObjects unless
|
||||
// glDeleteProgram already freed its slot while it stayed current. Nothing else holds
|
||||
// a GL-visible name for it, but a draw would still join it, so settle it here too.
|
||||
if (m_currentProgram) m_currentProgram->JoinLinkAndSpirv();
|
||||
if (currentProgram) currentProgram->JoinLinkAndSpirv();
|
||||
}
|
||||
|
||||
void ProgramState::MarkShaderObjectForDeletion(Uint shader) {
|
||||
void ProgramState::MarkShaderObjectForDeletion(Uint shader, const SharedPtr<ProgramObject>& currentProgram) {
|
||||
if (!CheckIndexAvail(shader, m_shaderObjects)) return;
|
||||
auto& shaderObject = m_shaderObjects[shader];
|
||||
if (shaderObject != nullptr) {
|
||||
@@ -138,11 +124,12 @@ namespace MobileGL::MG_State::GLState {
|
||||
// from every program. The GL CTS compiles shaders through exactly this
|
||||
// create-attach-delete-source-compile sequence (uniform_block.common.name_matching).
|
||||
shaderObject->MarkAsDeleted();
|
||||
ReleaseShaderNameIfOrphaned(shader);
|
||||
ReleaseShaderNameIfOrphaned(shader, currentProgram);
|
||||
}
|
||||
}
|
||||
|
||||
Bool ProgramState::ShaderHasGLVisibleAttachment(const SharedPtr<ShaderObject>& shaderObject) const {
|
||||
Bool ProgramState::ShaderHasGLVisibleAttachment(const SharedPtr<ShaderObject>& shaderObject,
|
||||
const SharedPtr<ProgramObject>& currentProgram) const {
|
||||
for (const auto& programObject : m_programObjects) {
|
||||
if (programObject != nullptr && programObject->ShaderIsAttachedGLVisible(shaderObject)) {
|
||||
return true;
|
||||
@@ -150,14 +137,14 @@ namespace MobileGL::MG_State::GLState {
|
||||
}
|
||||
// A program deleted while current vacates its table slot but stays alive as the
|
||||
// current program; its attachments still count.
|
||||
return m_currentProgram != nullptr && m_currentProgram->ShaderIsAttachedGLVisible(shaderObject);
|
||||
return currentProgram != nullptr && currentProgram->ShaderIsAttachedGLVisible(shaderObject);
|
||||
}
|
||||
|
||||
void ProgramState::ReleaseShaderNameIfOrphaned(Uint shader) {
|
||||
void ProgramState::ReleaseShaderNameIfOrphaned(Uint shader, const SharedPtr<ProgramObject>& currentProgram) {
|
||||
if (!CheckIndexAvail(shader, m_shaderObjects)) return;
|
||||
auto& shaderObject = m_shaderObjects[shader];
|
||||
if (shaderObject == nullptr || !shaderObject->GetDeleteStatus()) return;
|
||||
if (ShaderHasGLVisibleAttachment(shaderObject)) return;
|
||||
if (ShaderHasGLVisibleAttachment(shaderObject, currentProgram)) return;
|
||||
// The name is about to go, so nothing can observe this shader's compile through THIS
|
||||
// object any more and a job still in flight for it is pure waste - unless another
|
||||
// shader object adopted the same node (stage 6) or a pending link pinned it, which is
|
||||
|
||||
@@ -14,28 +14,31 @@
|
||||
#include "ShaderPreprocessCache.h"
|
||||
|
||||
namespace MobileGL::MG_State::GLState {
|
||||
// The program and shader objects of one share group, and the name space they share. The
|
||||
// program a context has in use is context state and lives on GLContext - the operations
|
||||
// that need it (a delete of the current program, the deferred destroy UseProgram
|
||||
// performs, the orphan test) take it as a parameter.
|
||||
class ProgramState {
|
||||
public:
|
||||
// This function WILL actually create the program object.
|
||||
// To retrieve created program object, use GetProgramObject()
|
||||
Uint CreateProgram();
|
||||
const SharedPtr<ProgramObject>& GetProgramObject(Uint id);
|
||||
void MarkProgramObjectForDeletion(Uint program);
|
||||
void MarkProgramObjectForDeletion(Uint program, const SharedPtr<ProgramObject>& currentProgram);
|
||||
Bool ValidateProgramObject(Uint program) const;
|
||||
|
||||
void UseProgram(Uint program);
|
||||
// Whether `program` names a slot in the table at all, i.e. in range - not whether that
|
||||
// slot currently holds an object.
|
||||
Bool HasProgramSlot(Uint program) const;
|
||||
|
||||
Uint CreateShader(ShaderStage stage);
|
||||
const SharedPtr<ShaderObject>& GetShaderObject(Uint shader);
|
||||
void MarkShaderObjectForDeletion(Uint shader);
|
||||
void MarkShaderObjectForDeletion(Uint shader, const SharedPtr<ProgramObject>& currentProgram);
|
||||
// Frees a deletion-flagged shader's name once no program holds a GL-visible
|
||||
// attachment to it (the deferred half of glDeleteShader-while-attached).
|
||||
void ReleaseShaderNameIfOrphaned(Uint shader);
|
||||
void ReleaseShaderNameIfOrphaned(Uint shader, const SharedPtr<ProgramObject>& currentProgram);
|
||||
Bool ValidateShaderObject(Uint shader) const;
|
||||
|
||||
const SharedPtr<ProgramObject>& GetCurrentProgram() const { return m_currentProgram; }
|
||||
|
||||
// Joins every outstanding compile and link this context still owns, publishing each
|
||||
// Joins every outstanding compile and link this share group still owns, publishing each
|
||||
// one's artifacts through the ordinary gates. The single caller is
|
||||
// glMaxShaderCompilerThreadsKHR(0): GL_KHR_parallel_shader_compile requires a zero
|
||||
// count to leave nothing in flight, so that every subsequent
|
||||
@@ -46,7 +49,7 @@ namespace MobileGL::MG_State::GLState {
|
||||
// compilation straight back. Nodes belonging to objects this context has already
|
||||
// dropped are not joined - nothing can observe them, and waiting on them would make
|
||||
// a GL call's cost depend on garbage.
|
||||
void JoinAllPendingWork();
|
||||
void JoinAllPendingWork(const SharedPtr<ProgramObject>& currentProgram);
|
||||
|
||||
// P0b layer 2. Exposed for tests and diagnostics; the GL frontend never touches it
|
||||
// directly - shader objects reach it through the pointer they are handed at
|
||||
@@ -59,10 +62,11 @@ namespace MobileGL::MG_State::GLState {
|
||||
ShaderCompileAdoptionMap& GetShaderCompileAdoptionMap() { return *m_shaderCompileAdoptionMap; }
|
||||
|
||||
private:
|
||||
Bool ShaderHasGLVisibleAttachment(const SharedPtr<ShaderObject>& shaderObject) const;
|
||||
Bool ShaderHasGLVisibleAttachment(const SharedPtr<ShaderObject>& shaderObject,
|
||||
const SharedPtr<ProgramObject>& currentProgram) const;
|
||||
// Frees the name slot and releases orphaned attached shaders; the immediate half
|
||||
// of glDeleteProgram (deferred while the program is current).
|
||||
void DestroyProgramSlot(Uint program);
|
||||
void DestroyProgramSlot(Uint program, const SharedPtr<ProgramObject>& currentProgram);
|
||||
|
||||
template <typename T>
|
||||
static Bool CheckIndexAvail(const SizeT idx, const Vector<T>& vec) {
|
||||
@@ -96,7 +100,5 @@ namespace MobileGL::MG_State::GLState {
|
||||
|
||||
Vector<SharedPtr<ProgramObject>> m_programObjects;
|
||||
Vector<SharedPtr<ShaderObject>> m_shaderObjects;
|
||||
|
||||
SharedPtr<ProgramObject> m_currentProgram;
|
||||
};
|
||||
} // namespace MobileGL::MG_State::GLState
|
||||
|
||||
@@ -10,34 +10,12 @@
|
||||
#include "MG_Util/Types.h"
|
||||
|
||||
namespace MobileGL::MG_State::GLState {
|
||||
RenderbufferState::RenderbufferState() : m_indexGenerator(1024, 1) {
|
||||
RenderbufferState::RenderbufferState() {
|
||||
for (SizeT i = 0; i < m_bindingSlots.size(); ++i) {
|
||||
m_bindingSlots[i] = BindingSlot<RenderbufferObject>(static_cast<RenderbufferTarget>(i));
|
||||
}
|
||||
}
|
||||
|
||||
const SharedPtr<RenderbufferObject>& RenderbufferState::GetRenderbufferObject(Uint index) {
|
||||
auto it = m_renderbufferObjects.find(index);
|
||||
if (it != m_renderbufferObjects.end()) {
|
||||
return it->second;
|
||||
}
|
||||
static SharedPtr<RenderbufferObject> nullRenderbufferObject = nullptr;
|
||||
return nullRenderbufferObject;
|
||||
}
|
||||
|
||||
void RenderbufferState::GenerateNames(Uint number, Vector<Uint>& renderbuffers) {
|
||||
renderbuffers.resize(number);
|
||||
m_indexGenerator.Generate(number, renderbuffers.data());
|
||||
}
|
||||
|
||||
const SharedPtr<RenderbufferObject>& RenderbufferState::CreateRenderbufferObject(Uint index) {
|
||||
auto& bufferObject = m_renderbufferObjects[index];
|
||||
if (!bufferObject) {
|
||||
bufferObject = MakeShared<RenderbufferObject>(index);
|
||||
}
|
||||
return bufferObject;
|
||||
}
|
||||
|
||||
BindingSlot<RenderbufferObject>& RenderbufferState::GetBindingSlot(RenderbufferTarget target) {
|
||||
for (auto& bindingSlot : m_bindingSlots) {
|
||||
if (bindingSlot.GetTarget() == target) {
|
||||
@@ -48,26 +26,12 @@ namespace MobileGL::MG_State::GLState {
|
||||
return m_bindingSlots[0];
|
||||
}
|
||||
|
||||
void RenderbufferState::MarkRenderbufferObjectForDeletion(Uint index) {
|
||||
if (m_indexGenerator.IsValid(index)) {
|
||||
auto it = m_renderbufferObjects.find(index);
|
||||
if (it != m_renderbufferObjects.end()) {
|
||||
for (auto& bindingSlot : m_bindingSlots) {
|
||||
if (bindingSlot.GetBoundObject() == it->second) {
|
||||
bindingSlot.Bind(nullptr);
|
||||
}
|
||||
}
|
||||
m_renderbufferObjects.erase(index);
|
||||
void RenderbufferState::UnbindRenderbufferObject(const SharedPtr<RenderbufferObject>& renderbufferObject) {
|
||||
if (!renderbufferObject) return;
|
||||
for (auto& bindingSlot : m_bindingSlots) {
|
||||
if (bindingSlot.GetBoundObject() == renderbufferObject) {
|
||||
bindingSlot.Bind(nullptr);
|
||||
}
|
||||
m_indexGenerator.Delete(index);
|
||||
}
|
||||
}
|
||||
|
||||
Bool RenderbufferState::ValidateName(Uint index) const {
|
||||
return m_indexGenerator.IsValid(index);
|
||||
}
|
||||
|
||||
Bool RenderbufferState::ValidateRenderbufferObject(Uint index) const {
|
||||
return m_renderbufferObjects.find(index) != m_renderbufferObjects.end();
|
||||
}
|
||||
} // namespace MobileGL::MG_State::GLState
|
||||
|
||||
@@ -12,21 +12,16 @@
|
||||
#include "RenderbufferObject.h"
|
||||
|
||||
namespace MobileGL::MG_State::GLState {
|
||||
// The per-context half of the renderbuffer state: which renderbuffer is bound. The
|
||||
// objects and their names belong to the share group (ShareGroupState).
|
||||
class RenderbufferState {
|
||||
public:
|
||||
RenderbufferState();
|
||||
|
||||
const SharedPtr<RenderbufferObject>& GetRenderbufferObject(Uint index);
|
||||
void GenerateNames(Uint number, Vector<Uint>& renderbuffers);
|
||||
const SharedPtr<RenderbufferObject>& CreateRenderbufferObject(Uint index);
|
||||
BindingSlot<RenderbufferObject>& GetBindingSlot(RenderbufferTarget target);
|
||||
void MarkRenderbufferObjectForDeletion(Uint index);
|
||||
Bool ValidateName(Uint index) const;
|
||||
Bool ValidateRenderbufferObject(Uint index) const;
|
||||
void UnbindRenderbufferObject(const SharedPtr<RenderbufferObject>& renderbufferObject);
|
||||
|
||||
private:
|
||||
UnorderedMap<Uint, SharedPtr<RenderbufferObject>> m_renderbufferObjects;
|
||||
IndexGenerator<Uint> m_indexGenerator;
|
||||
Array<BindingSlot<RenderbufferObject>, static_cast<SizeT>(RenderbufferTarget::RenderbufferTargetCount)>
|
||||
m_bindingSlots;
|
||||
};
|
||||
|
||||
@@ -0,0 +1,188 @@
|
||||
// MobileGL - MobileGL/MG_State/GLState/ShareGroupState.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 "ShareGroupState.h"
|
||||
|
||||
#include "TextureState/TextureObject1D.h"
|
||||
#include "TextureState/TextureObject2D.h"
|
||||
#include "TextureState/TextureObject3D.h"
|
||||
#include "TextureState/TextureObject2DCube.h"
|
||||
#include "TextureState/TextureObjectBuffer.h"
|
||||
#include "TextureState/TextureObjectStubs.h"
|
||||
#include "TextureState/TextureObjectView.h"
|
||||
|
||||
namespace MobileGL::MG_State::GLState {
|
||||
SharedPtr<ITextureObject> MakeTextureObjectForTarget(Uint index, TextureTarget target) {
|
||||
switch (target) {
|
||||
case TextureTarget::Texture1D:
|
||||
return MakeShared<TextureObject1D>(index);
|
||||
case TextureTarget::TextureCubeMap:
|
||||
return MakeShared<TextureObject2DCube>(index);
|
||||
case TextureTarget::Texture2D:
|
||||
return MakeShared<TextureObject2D>(index);
|
||||
case TextureTarget::Texture3D:
|
||||
return MakeShared<TextureObject3D>(index);
|
||||
case TextureTarget::TextureBuffer:
|
||||
return MakeShared<TextureObjectBuffer>(index);
|
||||
|
||||
// These texture types are still stubbed:
|
||||
case TextureTarget::TextureRectangle:
|
||||
return MakeShared<TextureObjectRectangle>(index);
|
||||
case TextureTarget::Texture2DMultisample:
|
||||
return MakeShared<TextureObject2DMultisample>(index);
|
||||
case TextureTarget::Texture1DArray:
|
||||
return MakeShared<TextureObject1DArray>(index);
|
||||
case TextureTarget::Texture2DArray:
|
||||
return MakeShared<TextureObject2DArray>(index);
|
||||
case TextureTarget::TextureCubeMapArray:
|
||||
return MakeShared<TextureObjectCubeMapArray>(index);
|
||||
case TextureTarget::Texture2DMultisampleArray:
|
||||
return MakeShared<TextureObject2DMultisampleArray>(index);
|
||||
default:
|
||||
MOBILEGL_ASSERT(false, "Unimplemented texture type when creating texture object!: %d", (int)target);
|
||||
return nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
// Buffer
|
||||
const SharedPtr<BufferObject>& ShareGroupState::GetBufferObject(Uint index) {
|
||||
auto it = m_bufferObjects.find(index);
|
||||
if (it != m_bufferObjects.end()) {
|
||||
return it->second;
|
||||
}
|
||||
static SharedPtr<BufferObject> nullBufferObject = nullptr;
|
||||
return nullBufferObject;
|
||||
}
|
||||
|
||||
void ShareGroupState::GenerateBufferNames(Uint number, Vector<Uint>& buffers) {
|
||||
buffers.resize(number);
|
||||
m_bufferNames.Generate(number, buffers.data());
|
||||
}
|
||||
|
||||
const SharedPtr<BufferObject>& ShareGroupState::CreateBufferObject(Uint index) {
|
||||
auto& bufferObj = m_bufferObjects[index];
|
||||
if (!bufferObj) {
|
||||
bufferObj = MakeShared<BufferObject>(index);
|
||||
}
|
||||
return bufferObj;
|
||||
}
|
||||
|
||||
void ShareGroupState::MarkBufferObjectForDeletion(Uint index) {
|
||||
if (m_bufferNames.IsValid(index)) {
|
||||
m_bufferObjects.erase(index);
|
||||
m_bufferNames.Delete(index);
|
||||
}
|
||||
}
|
||||
|
||||
Bool ShareGroupState::ValidateBufferName(Uint index) const {
|
||||
return m_bufferNames.IsValid(index);
|
||||
}
|
||||
|
||||
Bool ShareGroupState::ValidateBufferObject(Uint index) const {
|
||||
return m_bufferObjects.find(index) != m_bufferObjects.end();
|
||||
}
|
||||
|
||||
// Texture
|
||||
void ShareGroupState::GenerateTextureNames(Uint number, Vector<Uint>& textures) {
|
||||
textures.resize(number);
|
||||
m_textureNames.Generate(number, textures.data());
|
||||
}
|
||||
|
||||
const SharedPtr<ITextureObject>& ShareGroupState::GetTextureObject(Uint index) {
|
||||
auto it = m_textureObjects.find(index);
|
||||
if (it != m_textureObjects.end()) {
|
||||
return it->second;
|
||||
}
|
||||
static SharedPtr<ITextureObject> nullTextureObject = nullptr;
|
||||
return nullTextureObject;
|
||||
}
|
||||
|
||||
const SharedPtr<ITextureObject>& ShareGroupState::CreateTextureObject(Uint index, TextureTarget target) {
|
||||
auto& textureObject = m_textureObjects[index];
|
||||
textureObject = MakeTextureObjectForTarget(index, target);
|
||||
if (!textureObject) {
|
||||
static SharedPtr<ITextureObject> nullTextureObject = nullptr;
|
||||
return nullTextureObject;
|
||||
}
|
||||
return textureObject;
|
||||
}
|
||||
|
||||
const SharedPtr<ITextureObject>& ShareGroupState::CreateTextureViewObject(
|
||||
Uint index, TextureTarget target, const SharedPtr<ITextureObject>& storageOwner, Uint minLevel,
|
||||
Uint numLevels, Uint minLayer, Uint numLayers) {
|
||||
MOBILEGL_ASSERT(storageOwner != nullptr, "CreateTextureViewObject: storage owner is null");
|
||||
auto& textureObject = m_textureObjects[index];
|
||||
textureObject = MakeShared<TextureObjectView>(index, target, storageOwner, minLevel, numLevels, minLayer,
|
||||
numLayers);
|
||||
return textureObject;
|
||||
}
|
||||
|
||||
void ShareGroupState::MarkTextureObjectForDeletion(Uint index, Bool keepUnboundReservation) {
|
||||
if (m_textureNames.IsValid(index)) {
|
||||
auto it = m_textureObjects.find(index);
|
||||
if (it != m_textureObjects.end()) {
|
||||
m_textureObjects.erase(it);
|
||||
m_textureNames.Delete(index);
|
||||
} else if (!keepUnboundReservation) {
|
||||
// GL 3.3 core 3.8.1 makes a deleted name unused again even when GenTextures only
|
||||
// reserved it and no bind ever instantiated an object (so a later bind of it must
|
||||
// fail), and the reservation has to return to the free list.
|
||||
m_textureNames.Delete(index);
|
||||
}
|
||||
// Relaxed semantics: legacy apps may delete a generated name before its first
|
||||
// bind, then bind and populate that same name. Keep such a reservation alive there;
|
||||
// a real texture object reaching deletion still releases its index above.
|
||||
}
|
||||
}
|
||||
|
||||
Bool ShareGroupState::ValidateTextureName(Uint index) const {
|
||||
return m_textureNames.IsValid(index);
|
||||
}
|
||||
|
||||
Bool ShareGroupState::ValidateTextureObject(Uint index) const {
|
||||
return m_textureObjects.find(index) != m_textureObjects.end();
|
||||
}
|
||||
|
||||
// Renderbuffer
|
||||
const SharedPtr<RenderbufferObject>& ShareGroupState::GetRenderbufferObject(Uint index) {
|
||||
auto it = m_renderbufferObjects.find(index);
|
||||
if (it != m_renderbufferObjects.end()) {
|
||||
return it->second;
|
||||
}
|
||||
static SharedPtr<RenderbufferObject> nullRenderbufferObject = nullptr;
|
||||
return nullRenderbufferObject;
|
||||
}
|
||||
|
||||
void ShareGroupState::GenerateRenderbufferNames(Uint number, Vector<Uint>& renderbuffers) {
|
||||
renderbuffers.resize(number);
|
||||
m_renderbufferNames.Generate(number, renderbuffers.data());
|
||||
}
|
||||
|
||||
const SharedPtr<RenderbufferObject>& ShareGroupState::CreateRenderbufferObject(Uint index) {
|
||||
auto& bufferObject = m_renderbufferObjects[index];
|
||||
if (!bufferObject) {
|
||||
bufferObject = MakeShared<RenderbufferObject>(index);
|
||||
}
|
||||
return bufferObject;
|
||||
}
|
||||
|
||||
void ShareGroupState::MarkRenderbufferObjectForDeletion(Uint index) {
|
||||
if (m_renderbufferNames.IsValid(index)) {
|
||||
m_renderbufferObjects.erase(index);
|
||||
m_renderbufferNames.Delete(index);
|
||||
}
|
||||
}
|
||||
|
||||
Bool ShareGroupState::ValidateRenderbufferName(Uint index) const {
|
||||
return m_renderbufferNames.IsValid(index);
|
||||
}
|
||||
|
||||
Bool ShareGroupState::ValidateRenderbufferObject(Uint index) const {
|
||||
return m_renderbufferObjects.find(index) != m_renderbufferObjects.end();
|
||||
}
|
||||
} // namespace MobileGL::MG_State::GLState
|
||||
@@ -0,0 +1,81 @@
|
||||
// MobileGL - MobileGL/MG_State/GLState/ShareGroupState.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 <MG_Util/Miscellany/IndexGenerator.h>
|
||||
#include "BufferState/BufferObject.h"
|
||||
#include "ProgramState/ProgramState.h"
|
||||
#include "RenderbufferState/RenderbufferObject.h"
|
||||
#include "SamplerState/SamplerState.h"
|
||||
#include "TextureState/TextureObject.h"
|
||||
|
||||
namespace MobileGL::MG_State::GLState {
|
||||
// The GL object registries and name spaces a set of sharing contexts share, i.e. one EGL
|
||||
// share group (GL 4.6 core 5.1). Buffers, textures, renderbuffers, samplers, programs and
|
||||
// shaders live here; glGen* names are drawn from this object's generators.
|
||||
//
|
||||
// What is NOT here is what GL scopes to a single context - bindings, texture units, the
|
||||
// current program, errors, and the container objects (VAO/FBO/query/pipeline/transform
|
||||
// feedback) - so two contexts sharing a group see the same objects and their own bindings.
|
||||
class ShareGroupState {
|
||||
public:
|
||||
ShareGroupState() = default;
|
||||
explicit ShareGroupState(Uint64 token) : m_token(token) {}
|
||||
|
||||
// P14 S1's shareGroupToken: the identity the wire uses, 0 for a group no EGL context
|
||||
// was made for.
|
||||
Uint64 GetToken() const { return m_token; }
|
||||
|
||||
// Buffer
|
||||
const SharedPtr<BufferObject>& GetBufferObject(Uint index);
|
||||
void GenerateBufferNames(Uint number, Vector<Uint>& buffers);
|
||||
const SharedPtr<BufferObject>& CreateBufferObject(Uint index);
|
||||
void MarkBufferObjectForDeletion(Uint index);
|
||||
Bool ValidateBufferName(Uint index) const;
|
||||
Bool ValidateBufferObject(Uint index) const;
|
||||
|
||||
// Texture
|
||||
void GenerateTextureNames(Uint number, Vector<Uint>& textures);
|
||||
const SharedPtr<ITextureObject>& GetTextureObject(Uint index);
|
||||
const SharedPtr<ITextureObject>& CreateTextureObject(Uint index, TextureTarget target);
|
||||
const SharedPtr<ITextureObject>& CreateTextureViewObject(Uint index, TextureTarget target,
|
||||
const SharedPtr<ITextureObject>& storageOwner,
|
||||
Uint minLevel, Uint numLevels, Uint minLayer,
|
||||
Uint numLayers);
|
||||
void MarkTextureObjectForDeletion(Uint index, Bool keepUnboundReservation);
|
||||
Bool ValidateTextureName(Uint index) const;
|
||||
Bool ValidateTextureObject(Uint index) const;
|
||||
|
||||
// Renderbuffer
|
||||
const SharedPtr<RenderbufferObject>& GetRenderbufferObject(Uint index);
|
||||
void GenerateRenderbufferNames(Uint number, Vector<Uint>& renderbuffers);
|
||||
const SharedPtr<RenderbufferObject>& CreateRenderbufferObject(Uint index);
|
||||
void MarkRenderbufferObjectForDeletion(Uint index);
|
||||
Bool ValidateRenderbufferName(Uint index) const;
|
||||
Bool ValidateRenderbufferObject(Uint index) const;
|
||||
|
||||
// Sampler objects carry no per-context state, so the whole table lives here.
|
||||
SamplerState& Samplers() { return m_samplerState; }
|
||||
|
||||
// Program and shader objects, one name space for both (GL 3.3 core 2.11).
|
||||
ProgramState& Programs() { return m_programState; }
|
||||
const ProgramState& Programs() const { return m_programState; }
|
||||
|
||||
private:
|
||||
Uint64 m_token = 0;
|
||||
UnorderedMap<Uint, SharedPtr<BufferObject>> m_bufferObjects;
|
||||
IndexGenerator<Uint> m_bufferNames{1024, 1};
|
||||
UnorderedMap<GLuint, SharedPtr<ITextureObject>> m_textureObjects;
|
||||
IndexGenerator<Uint> m_textureNames{1024, 1};
|
||||
UnorderedMap<Uint, SharedPtr<RenderbufferObject>> m_renderbufferObjects;
|
||||
IndexGenerator<Uint> m_renderbufferNames{1024, 1};
|
||||
SamplerState m_samplerState;
|
||||
ProgramState m_programState;
|
||||
};
|
||||
} // namespace MobileGL::MG_State::GLState
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user