Compare commits

...
31 Commits
Author SHA1 Message Date
swung0x48 4f6f4125ac [Fix] (EGL, SharedImage): real EGL native fences publish a dma-buf producer's writes, so Chrome's GPU process frames reach the compositor. 2026-10-03 10:59:02 -04:00
swung0x48 2a1889b817 Discover gtest cases at ctest start so parallel links stop sharing one discovery JSON file. 2026-10-03 09:38:51 -04:00
swung0x48 07e7730085 [Docs] (Anland): kwin-recover.sh reads the latch from the server log file, not the too-small logcat buffer. 2026-10-03 09:05:55 -04:00
swung0x48 03648c2783 [Docs] (Anland): add a device test that loses KWin's own session and checks the desktop keeps compositing. 2026-10-03 09:05:54 -04:00
swung0x48 f22ae625cb [Fix] (Server): a lost session's window lease is waited for by the fresh session, and a window wait holds no backend turn. 2026-10-03 09:05:54 -04:00
swung0x48 f52a546707 [Fix] (EGL, Remote): a server-owned surface is re-created at the size it asked for, and a lost session's image reference is never released on the fresh one. 2026-10-03 09:05:53 -04:00
swung0x48 77c604061e [Docs] (Anland): glxgears is fixed-function, so it measures presentation only 2026-10-03 07:53:11 -04:00
swung0x48 36190b7cc0 [Fix] (EGL, Wayland): a swap that runs into a device loss reports it and still commits the window, instead of showing an empty frame. 2026-10-03 07:17:08 -04:00
swung0x48 cf763b4081 [Fix] (EGL, Remote): a thread that released a lost context keeps reporting the reset until it binds another. 2026-10-03 07:17:07 -04:00
swung0x48 2acc6c41bb [Fix] (Pipe): an evicted sampler CSO is deleted from every share group of its session. 2026-10-03 05:37:53 -04:00
swung0x48 a84104a40f [Fix] (Pipe): the default framebuffer's record names no placeholder surface that only one share group holds. 2026-10-03 05:37:53 -04:00
swung0x48 1dd888cb21 [Fix] (EGL, DirectGLES): keep a lost context's release off the fresh session, bind no surfaceless context natively, and keep the display while surfaces remain. 2026-10-03 05:37:52 -04:00
swung0x48 393002a46e [Fix] (Pipe): give each context's applier its own serial range so backend memos never match another context. 2026-10-03 05:37:51 -04:00
swung0x48 25a76c1b20 [Fix] (Pipe): drain a texture's pending texels only under a context of the share group that wrote them. 2026-10-03 05:37:51 -04:00
swung0x48 a9f22ebb63 [Fix] (EGL): create and end a context's objects under its own binding and the stream lock, and defer destroying a current context. 2026-10-03 05:37:50 -04:00
swung0x48 2fe011adf6 [Test] (Wire): enable the concurrent-context repro and add release, sibling, deferred-destroy and read-back-race shapes. 2026-10-03 05:37:49 -04:00
swung0x48 11668b02f2 [Docs] (Anland): Chrome runs its GPU in its own process by default and recovers from a device loss. 2026-10-03 05:21:53 -04:00
swung0x48 30977c181f [Feature] (EGL+GL): an opt-in OpenGL ES identity for ES contexts with BGRA textures, and contexts take the dispatcher's API, so Chrome's GPU process runs on ANGLE. 2026-10-03 05:21:52 -04:00
swung0x48 e5f097f9e1 [Docs] (Anland): add a Chrome device-loss recovery test and the GPU-process launch mode. 2026-10-03 04:37:34 -04:00
swung0x48 90e63c9e2a [Feature] (EGL+GL): advertise EGL_EXT_create_context_robustness and GL robustness, with per-context reset notification and a pid-targeted device-loss knob. 2026-10-03 04:37:33 -04:00
swung0x48 af2b9f4c1c [Docs] (Anland): root cause of the X11 stale-region issue 2026-10-03 04:36:24 -04:00
swung0x48 cd58f048b6 [Fix] (Shader): an inactive fragment output no longer takes location 0 from the active one 2026-10-03 04:16:41 -04:00
swung0x48 b0dad54cf1 [Docs] (Anland): device numbers and the open stale-region issue for X11 on the GPU 2026-10-03 03:20:12 -04:00
swung0x48 95aa618d22 [Docs] (Anland): x11-verify measures 1280x720 glxgears and runs Qt apps on xcb 2026-10-03 02:58:03 -04:00
swung0x48 5de6ecd4e1 [Fix] (SharedImage): uploads into a texture bound to a shared image are written into the image, and a producer's flush sends them first 2026-10-03 02:58:02 -04:00
swung0x48 7fd965ceda [Fix] (SharedImage): a session that writes images publishes every frame boundary as a write 2026-10-03 01:51:25 -04:00
swung0x48 9e7305b885 [Docs] (Anland): plan and device scripts for X11 apps on the GPU 2026-10-03 01:51:24 -04:00
swung0x48 bd4c5b5770 [Test] (Gbm): drive mobilegl_gbm through the system loader the way Xwayland's glamor does 2026-10-03 01:51:23 -04:00
swung0x48 198d6feaf3 [Feature] (GLX): present windows as shared images through DRI3 and Present, with MIT-SHM readback as the fallback 2026-10-03 01:51:22 -04:00
swung0x48 08f23543aa [Feature] (SharedImage): a glFlush publishes an image producer's accesses, so Xwayland's glamor gets implicit sync 2026-10-03 01:51:20 -04:00
swung0x48 316ffe02d0 [Fix] (X11): never open an X connection to a display this process serves 2026-10-03 01:50:58 -04:00
96 changed files with 7874 additions and 277 deletions
@@ -26,7 +26,7 @@ nobody else is mid-test. Use your own `ct.sh` channel names (others use c, c2,
7. KWin 6.7.4 with anland's `anland` backend renders straight into the anland Android Surface through the server. While the window is not on screen (consumer disconnected) the backend powers its output down (DPMS Off + RenderLoop inhibited: no compositing, no frame callbacks) and back up when the window returns. Every other GL process is `MOBILEGL_IPC_SURFACE=offscreen` and presents through KWin.
8. Client = `/opt/mobilegl/lib/libMobileGL.so` (glibc aarch64), the container's **system-wide** GL vendor (section below): glvnd EGL vendor `/usr/share/glvnd/egl_vendor.d/10_mobilegl.json` (sorts before the distribution's `50_*.json`, which serves whenever MobileGL declines), GLX vendor `/usr/lib/libGLX_mobilegl.so.0`, settings from `/etc/mobilegl/client.conf` (`MOBILEGL_TRANSPORT=spawn MOBILEGL_IPC_DATA=shm MOBILEGL_IPC_CONTROL=unix:@anland-mobilegl`) + `/etc/mobilegl/backend`. No per-process environment is needed.
9. Zero-copy windows: client `wl_egl_window` frames are server-allocated AHardwareBuffer "shared images" exported as dma-buf fds over `zwp_linux_dmabuf_v1`; KWin imports them with EGL and the server recognises its own buffer by inode. KWin gets a DRM device via `GBM_BACKEND=mobilegl` -> `/usr/lib/gbm/mobilegl_gbm.so` (node is only an identity, never ioctl'd). Without linux-dmabuf the client falls back to wl_shm readback.
10. X11 apps (Xwayland) use the MobileGL GLX vendor with per-frame readback + `xcb_put_image`. Chrome runs ANGLE-GLES over MobileGL EGL with the GPU in-process (`mobilegl-startup.sh chrome`).
10. X11 (`docs/Disaggregated/notes/anland/plan-x11-gpu.md`): Xwayland draws with **glamor on MobileGL** (an offscreen session; `GBM_BACKEND=mobilegl` on KWin's render node; window pixmaps are shared images handed to KWin as linux-dmabuf buffers; its `glFlush` publishes them through the server, `/tmp/mgl-xwayland.client.log`); `ANLAND_XWAYLAND_GLAMOR=0` in KWin's drop-in brings back the software `-shm` Xwayland. GLX windows present their frames as shared images through **DRI3 + Present** (log `presented through DRI3+Present shared images`), falling back to readback + MIT-SHM / `xcb_put_image` when the X server has no DRI3 (`MOBILEGL_GLX_PRESENT=readback` forces it per app). Chrome runs ANGLE-GLES over MobileGL EGL with the GPU in its own process (`mobilegl-startup.sh chrome`; `MOBILEGL_CHROME_GPU=in-process` opts out), presenting GBM dma-bufs over linux-dmabuf; after a device loss Chrome restarts that process and repaints.
## First-time prerequisites (Windows host)
@@ -108,7 +108,7 @@ Installed by `xdeploy.sh` (and anland's `anland-build-client.sh`), so any proces
Precedence is environment > `/etc/mobilegl/backend` (backend only) > client.conf > built-in; `MOBILEGL_CONFIG_FILE` / `MOBILEGL_BACKEND_FILE` name other files (empty = off); a server process never reads them.
**Fallback.** Before bringing anything up the client probes the configured endpoint (one non-blocking connect, `MOBILEGL_IPC_PROBE_TIMEOUT_MS`, default 250, 0 = off; a refused abstract socket answers in ~0.2 ms). With no server: the EGL vendor returns `EGL_NO_DISPLAY` and no devices (glvnd moves on to the other vendor), the GLX vendor fails `__glx_Main` (libGLX falls back to the vendor Xwayland names), and `mobilegl_gbm` fails `create_device` (libgbm falls back to the device's own backend). Client queries (`eglQueryString(EGL_NO_DISPLAY)`, `eglGetProcAddress`) never bring a session up. MobileGL also steps aside for a GBM device another backend created and for `LIBGL_ALWAYS_SOFTWARE=1` - that is how Xwayland (KWin's patch sets it) keeps the software stack. Show it without stopping the real server:
**Fallback.** Before bringing anything up the client probes the configured endpoint (one non-blocking connect, `MOBILEGL_IPC_PROBE_TIMEOUT_MS`, default 250, 0 = off; a refused abstract socket answers in ~0.2 ms). With no server: the EGL vendor returns `EGL_NO_DISPLAY` and no devices (glvnd moves on to the other vendor), the GLX vendor fails `__glx_Main` (libGLX falls back to the vendor Xwayland names), and `mobilegl_gbm` fails `create_device` (libgbm falls back to the device's own backend). Client queries (`eglQueryString(EGL_NO_DISPLAY)`, `eglGetProcAddress`) never bring a session up. MobileGL also steps aside for a GBM device another backend created and for `LIBGL_ALWAYS_SOFTWARE=1` - that is how a software Xwayland (`ANLAND_XWAYLAND_GLAMOR=0`, KWin's patch sets it then) keeps the software stack. MobileGL never opens an X connection to a display its own process serves (`MG_Util/X11/DisplayGuard.h`; `MOBILEGL_X11_DIAL=0` forbids all), which is what made a glamor Xwayland deadlock on itself before. Show it without stopping the real server:
```sh
sed 's|^MOBILEGL_IPC_CONTROL=.*|MOBILEGL_IPC_CONTROL=unix:@nobody|' /etc/mobilegl/client.conf > /tmp/down.conf
sudo -u swung0x48 env -i HOME=/home/swung0x48 PATH=/usr/bin XDG_RUNTIME_DIR=/run/user/1000 WAYLAND_DISPLAY=wayland-0 \
@@ -117,13 +117,16 @@ sudo -u swung0x48 env -i HOME=/home/swung0x48 PATH=/usr/bin XDG_RUNTIME_DIR=/run
## Test clients and how to verify
X11 on the GPU has its own driver, `scripts/x11-verify.sh` (preflight, measure before/after with glxgears at `vblank_mode=0` on both GLX paths (presentation throughput only: glxgears is fixed-function GL, which MobileGL does not implement, so its window is black by design), deploy-client/-kwin/-server, check, apps, stop); `scripts/device/x11-measure.sh` refuses to load the phone below 40% battery.
Inside the container as root (`printf '...' | bash scripts/ct.sh <chan>`), `mgrun offscreen <cmd>` runs a client as swung0x48 in the live session through a login shell, with nothing but the surface mode and the log path set (log `/tmp/mgl-run.client.log`, override base with `MGLOG=/tmp/x.log`); a plain `env -i ... bash -l -c '<cmd>'` as swung0x48 gets MobileGL the same way:
```sh
mgrun offscreen eglinfo -B ; mgrun offscreen glxinfo -B
timeout 25 mgrun offscreen glmark2-es2-wayland -s 1280x720 --run-forever > /tmp/gm.out 2>&1 &
sleep 8; grep -a "presented through" /tmp/mgl-run.client.log
```
Chrome: `bash scripts/chrome-launch.sh <tag> [flags]` (log `/tmp/mgl-chrome-<tag>.client.log`, screenshot `ch-<tag>.png`).
Chrome: `bash scripts/chrome-launch.sh <tag> [flags]` (log `/tmp/mgl-chrome-<tag>.client.log`, screenshot `ch-<tag>.png`; `CHROME_GPU=in-process` puts the GPU back in the browser, which cannot recover from a device loss).
Device loss: `setprop debug.mobilegl.inject_device_lost_pid <pid>` (as root) loses the server session of the client whose pid - as it sees itself in the container - is `<pid>`, once per value, on any backend and whether or not it presents; `debug.mobilegl.inject_device_lost_at N` instead loses whichever session makes the N-th device check (Espryt presents and read-backs only). `bash scripts/chrome-recover.sh <in-process|process> [rounds]` checks that Chrome repaints after such a loss without a restart (battery-guarded, stops below 40%). `bash scripts/kwin-recover.sh [rounds]` loses KWin's own session (default twice) and checks that KWin restarts compositing on a fresh session - same KWin, plasmashell and client processes, the screen still animating (glmark2 on Wayland, glxgears on X11, `CHROME=1` adds Chrome) - which needs the anland backend + kwin.patch reset handling deployed (`kwin-stage.sh build`).
Probes: `scripts/probes/texfmt.c` (texture formats keep alpha?), `dmahash.c` (hash a process's dma-bufs); build in the container, e.g. `gcc -O1 /root/texfmt.c -o /usr/local/bin/mgl-texfmt -lEGL`, run with `mgrun offscreen`.
A result counts only if ALL hold:
@@ -1,10 +1,14 @@
#!/usr/bin/env bash
# chrome-launch.sh <tag> [extra chrome flags...] - (re)start Chrome inside the running Plasma session
# through mobilegl-startup.sh's `chrome` mode (ANGLE GLES over MobileGL EGL, in-process GPU), client
# log /tmp/mgl-chrome-<tag>.client.log, then print its "presented through" line and save a screenshot
# through mobilegl-startup.sh's `chrome` mode (ANGLE GLES over MobileGL EGL), client log
# /tmp/mgl-chrome-<tag>.client.log, then print its "presented through" line and save a screenshot
# to $ANL_DIR/ch-<tag>.png. Kills the running chrome first (pkill -x, never -f). MobileGL is the
# container's system-wide vendor (10_mobilegl.json + /etc/mobilegl/client.conf), so only the log is set here.
# Env: WAIT (s before checking, default 20), CHANNEL (ct.sh channel, default chrome).
# Env: WAIT (s before checking, default 20), CHANNEL (ct.sh channel, default chrome),
# CHROME_GPU (process, the default: the GPU in its own process, which presents
# through GBM dma-bufs and is restarted by Chrome after a device loss; in-process opts out -
# needs the anland startup script that knows MOBILEGL_CHROME_GPU; in process mode the GPU process and the browser
# write the one client log, the GPU process last); CHROME_GPU_SANDBOX=on keeps its GPU sandbox.
set -euo pipefail
here=$(cd "$(dirname "$0")" && pwd)
. "$here/env.sh"
@@ -12,7 +16,8 @@ TAG=${1:?usage: chrome-launch.sh <tag> [chrome flags...]}; shift
bash "$here/ct.sh" "${CHANNEL:-chrome}" <<IN
pkill -x chrome; sleep 2
U=\$(id -u $MGL_DESKTOP_USER)
sudo -u $MGL_DESKTOP_USER env XDG_RUNTIME_DIR=/run/user/\$U WAYLAND_DISPLAY=wayland-0 DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/\$U/bus MOBILEGL_LOG_FILE_PATH=/tmp/mgl-chrome-$TAG.log bash -c 'nohup /opt/mobilegl/bin/mobilegl-startup.sh chrome --restore-last-session $* > /tmp/chrome-$TAG-out.log 2>&1 &'
rm -f /tmp/mgl-chrome-$TAG.client.log /tmp/chrome-$TAG-out.log
sudo -u $MGL_DESKTOP_USER env XDG_RUNTIME_DIR=/run/user/\$U WAYLAND_DISPLAY=wayland-0 DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/\$U/bus MOBILEGL_LOG_FILE_PATH=/tmp/mgl-chrome-$TAG.log MOBILEGL_CHROME_GPU=${CHROME_GPU:-process} MOBILEGL_CHROME_GPU_SANDBOX=${CHROME_GPU_SANDBOX:-off} bash -c 'nohup /opt/mobilegl/bin/mobilegl-startup.sh chrome --restore-last-session $* > /tmp/chrome-$TAG-out.log 2>&1 &'
sleep ${WAIT:-20}
grep -ah 'presented through' /tmp/mgl-chrome-$TAG.client.log | head -3
IN
@@ -0,0 +1,146 @@
#!/usr/bin/env bash
# chrome-recover.sh <in-process|process> [rounds] - does Chrome repaint after a GPU device loss,
# without a restart? Starts Chrome (chrome-launch.sh, CHROME_GPU=<mode>) on an animated WebGL page,
# then per round: screenshots (the page must animate), loses the session of Chrome's GPU client with
# the server's pid-targeted debug knob (debug.mobilegl.inject_device_lost_pid; the pid as Chrome sees
# itself in the container), waits, and screenshots again. A round PASSES when the server latched
# that pid's session, the browser process is the same one (no restart), a GPU client is drawing on a
# NEW server session, and the screen still animates. Stops early below MIN_BATTERY percent.
#
# in-process the GPU in the browser process (the startup script's default today): the target is
# the browser itself; recovery needs ANGLE to make a new native context.
# process the GPU in its own process (MOBILEGL_CHROME_GPU=process): the target is the GPU
# process; Chrome restarts it after the loss, so the next round's target is a new pid.
#
# Deploy first (same MobileGL commit on both sides; see SKILL.md):
# bash scripts/build-android.sh && bash scripts/cyc.sh pre # server -> APK, restarts the session
# bash scripts/xbuild.sh && bash scripts/xdeploy.sh # client -> container
# STARTUP=<anland worktree>/producers/kde/Arch_v5/mobilegl-startup.sh bash scripts/chrome-recover.sh deploy-startup
# Env: ROUNDS (default 2), SETTLE (s after the loss, default 8), MIN_BATTERY (default 40),
# CHANNEL (ct.sh channel, default crec), TAG (log tag, default crec-<mode>).
set -euo pipefail
here=$(cd "$(dirname "$0")" && pwd)
. "$here/env.sh"
MODE=${1:?usage: chrome-recover.sh <in-process|process|deploy-startup> [rounds]}
ROUNDS=${2:-${ROUNDS:-2}}
SETTLE=${SETTLE:-8}
MIN_BATTERY=${MIN_BATTERY:-40}
CH=${CHANNEL:-crec}
TAG=${TAG:-crec-$MODE}
PAGE=/tmp/mgl-spin.html
ct() { bash "$here/ct.sh" "$CH"; }
battery() { adb_ shell dumpsys battery | tr -d '\r' | awk '/ level:/ {print $2}'; }
check_battery() {
local level; level=$(battery)
echo "battery: $level%"
if [ -n "$level" ] && [ "$level" -lt "$MIN_BATTERY" ]; then
echo "STOP: battery below $MIN_BATTERY%"; cleanup; exit 3
fi
}
cleanup() { adb_ shell "su -c 'setprop debug.mobilegl.inject_device_lost_pid 0'" || true; }
if [ "$MODE" = deploy-startup ]; then
# The anland startup script that knows MOBILEGL_CHROME_GPU, installed by rename (a running
# session keeps its open copy).
src=${STARTUP:?STARTUP=<path to the anland mobilegl-startup.sh>}
tr -d '\r' < "$src" > "$ANL_DIR/mobilegl-startup.sh"
adb_ push "$ANL_DIR/mobilegl-startup.sh" "$DEV_SHARE/mobilegl-startup.sh.new" >/dev/null
ct <<'IN'
install -m 755 /run/anland-mobilegl/mobilegl-startup.sh.new /opt/mobilegl/bin/mobilegl-startup.sh.new
mv -f /opt/mobilegl/bin/mobilegl-startup.sh.new /opt/mobilegl/bin/mobilegl-startup.sh
grep -c MOBILEGL_CHROME_GPU /opt/mobilegl/bin/mobilegl-startup.sh
IN
exit 0
fi
case "$MODE" in in-process|process) ;; *) echo "mode must be in-process or process" >&2; exit 2;; esac
trap cleanup EXIT
check_battery
adb_ shell "su -c 'sh $DEV_TOOLS/status.sh'" || true
cleanup
# The page: WebGL clears that change colour every frame plus a moving block, so a frame that
# reaches the screen changes the screenshot.
ct <<IN
cat > $PAGE <<'HTML'
<!doctype html><html><body style="margin:0;background:#000">
<canvas id=c width=640 height=360 style="width:100vw;height:100vh"></canvas>
<script>
const gl = document.getElementById('c').getContext('webgl');
let t = 0, lost = 0;
document.getElementById('c').addEventListener('webglcontextlost', e => { e.preventDefault(); lost++; });
function frame() {
t++;
if (gl && !gl.isContextLost()) {
gl.clearColor((t % 60) / 60, ((t + 20) % 60) / 60, ((t + 40) % 60) / 60, 1);
gl.clear(gl.COLOR_BUFFER_BIT);
gl.enable(gl.SCISSOR_TEST); gl.scissor((t * 7) % 600, 100, 40, 160);
gl.clearColor(1, 1, 1, 1); gl.clear(gl.COLOR_BUFFER_BIT); gl.disable(gl.SCISSOR_TEST);
}
document.title = 'spin ' + t + ' lost ' + lost;
requestAnimationFrame(frame);
}
frame();
</script></body></html>
HTML
chmod 644 $PAGE
IN
WAIT=${WAIT:-20} CHROME_GPU=$MODE CHANNEL=$CH bash "$here/chrome-launch.sh" "$TAG" --new-window "file://$PAGE"
# The target pid inside the container: the browser (in-process) or the GPU process.
target_pid() {
ct <<'IN' | tr -d '\r' | tail -1
for p in $(pgrep -x chrome); do
args=$(tr '\0' ' ' < /proc/$p/cmdline)
case "$args" in
*--type=gpu-process*) echo "gpu $p" ;;
*--type=*) ;;
*) echo "browser $p" ;;
esac
done | sort > /tmp/mgl-crec-pids
cat /tmp/mgl-crec-pids >&2
echo "$(awk '/^browser/ {print $2; exit}' /tmp/mgl-crec-pids) $(awk '/^gpu/ {print $2; exit}' /tmp/mgl-crec-pids)"
IN
}
pass=0
for round in $(seq 1 "$ROUNDS"); do
echo "=== round $round/$ROUNDS ($MODE)"
check_battery
read -r browser gpu < <(target_pid)
if [ "$MODE" = process ]; then target=$gpu; else target=$browser; fi
echo "browser=$browser gpu=${gpu:-none} target=$target"
if [ -z "$target" ]; then echo "FAIL: no target process"; break; fi
bash "$here/shot.sh" "$TAG-r$round-pre" 2 1
adb_ logcat -c
adb_ shell "su -c 'setprop debug.mobilegl.inject_device_lost_pid $target'"
sleep "$SETTLE"
adb_ shell "su -c 'setprop debug.mobilegl.inject_device_lost_pid 0'"
bash "$here/shot.sh" "$TAG-r$round-post" 3 1 | tee "$ANL_DIR/$TAG-r$round-post.md5"
latched=$(adb_ logcat -d | grep -c "injected:pid=$target" || true)
started=$(adb_ logcat -d | grep -c "session #[0-9]* started" || true)
adb_ logcat -d | grep -E "inject_device_lost_pid|SessionLatch|session #[0-9]+ (started|pid)" | cut -c1-220 | head -12 || true
read -r browser2 gpu2 < <(target_pid)
echo "after: browser=$browser2 gpu=${gpu2:-none}"
ct <<IN || true
echo "--- client log ($TAG):"; grep -aE "DEVICE LOST|RECOVERED|GL_UNKNOWN_CONTEXT_RESET|failed to make|session #" /tmp/mgl-chrome-$TAG.client.log | tail -8
echo "--- chrome stderr:"; grep -aiE "context lost|GPU process|make.*current|lost" /tmp/chrome-$TAG-out.log | tail -8
IN
adb_ logcat -b crash -d | tail -5
hashes=$(awk '{print $1}' "$ANL_DIR/$TAG-r$round-post.md5" | sort -u | wc -l)
verdict=PASS
[ "$latched" -ge 1 ] || { echo " - the server never latched pid $target"; verdict=FAIL; }
[ "$browser2" = "$browser" ] || { echo " - the browser process changed ($browser -> $browser2): Chrome restarted"; verdict=FAIL; }
[ "$started" -ge 1 ] || { echo " - no new server session started after the loss"; verdict=FAIL; }
if [ "$MODE" = process ]; then
[ -n "$gpu2" ] && [ "$gpu2" != "$gpu" ] || { echo " - no new GPU process"; verdict=FAIL; }
fi
[ "$hashes" -ge 2 ] || { echo " - the screen does not change after the loss (frozen)"; verdict=FAIL; }
echo "round $round: $verdict"
[ "$verdict" = PASS ] && pass=$((pass + 1))
[ "$verdict" = PASS ] || break
done
echo "=== $pass/$ROUNDS rounds passed ($MODE); screenshots in $ANL_DIR/$TAG-r*-*.png"
@@ -0,0 +1,47 @@
# x11-measure.sh <label> <app-process-name> [seconds] - (Android root shell) CPU of the X11 path while
# an X11 app runs: % of ONE core (800 = all 8 cores) for the whole phone, the app, Xwayland,
# kwin_wayland, the app's :mobilegl server; mean kgsl gpu_busy_percentage; and the number of dma-buf
# descriptors Xwayland and KWin hold (window pixmaps / client buffers as dma-bufs). Refuses to run
# below 40% battery: the phone drains faster under load than USB charges it.
# Run: su -c "sh /data/local/tmp/anl/x11-measure.sh glamor glxgears 10" Env: PKG, MIN_BATTERY.
L=${1:-sample}
APP=${2:-glxgears}
N=${3:-10}
P=${PKG:-com.anland.consumer.mobilegl}
GPU=/sys/class/kgsl/kgsl-3d0/gpu_busy_percentage
level=$(dumpsys battery | sed -n 's/^ *level: *//p')
if [ "${level:-0}" -lt "${MIN_BATTERY:-40}" ]; then
echo "battery ${level}% < ${MIN_BATTERY:-40}%: not loading the phone; charge first" >&2
exit 3
fi
ticks() {
t=0
for p in "$@"; do
[ -r /proc/$p/stat ] || continue
v=$(sed 's/^.*) //' /proc/$p/stat | awk '{print $12 + $13}')
t=$((t + v))
done
echo $t
}
total() { awk '/^cpu /{print $2+$3+$4+$6+$7+$8}' /proc/stat; }
dmabufs() { # dma-buf descriptors held by the pids (Android kernels link them to /dmabuf:...)
n=0
for p in "$@"; do n=$((n + $(ls -l /proc/$p/fd 2>/dev/null | grep -c dmabuf))); done
echo $n
}
AP="$(pidof $APP)"
XW="$(pidof Xwayland)"
KW="$(pidof kwin_wayland)"
SV="$(pidof $P:mobilegl)"
[ -n "$AP" ] || { echo "no running process named $APP" >&2; exit 2; }
a0=$(total); p0=$(ticks $AP); x0=$(ticks $XW); k0=$(ticks $KW); v0=$(ticks $SV)
g=0; i=0
while [ $i -lt $N ]; do
sleep 1
b=$(cat $GPU 2>/dev/null | tr -dc '0-9'); g=$((g + ${b:-0})); i=$((i + 1))
done
a1=$(total); p1=$(ticks $AP); x1=$(ticks $XW); k1=$(ticks $KW); v1=$(ticks $SV)
pct() { echo $(( ($2 - $1) / N )); }
printf '%-12s %3ss phone %4s%% %s %3s%% Xwayland %3s%% kwin %3s%% server %3s%% gpu %3s%% dmabufs Xwayland %s kwin %s battery %s%%\n' \
"$L" "$N" "$(pct $a0 $a1)" "$APP" "$(pct $p0 $p1)" "$(pct $x0 $x1)" "$(pct $k0 $k1)" "$(pct $v0 $v1)" "$((g / N))" \
"$(dmabufs $XW)" "$(dmabufs $KW)" "$level"
@@ -0,0 +1,146 @@
#!/usr/bin/env bash
# kwin-recover.sh [rounds] - does the desktop keep working when KWin's OWN MobileGL session is lost?
# Starts animated clients (glmark2-es2-wayland: Wayland, zero-copy shared images; glxgears: X11 through
# Xwayland's GLX; with CHROME=1 also Chrome on an animated WebGL page), then per round loses the server
# session of KWin with the pid-targeted debug knob (debug.mobilegl.inject_device_lost_pid, KWin's pid as
# it sees itself in the container), waits, and checks. A round PASSES when:
# - the server latched KWin's session (the server log file: "injected:pid=<kwin>"; logcat is too small);
# - KWin, plasmashell and every test client are the SAME processes (nothing restarted);
# - KWin restarted compositing on a fresh session (its journal: "compositing restarted on a fresh
# MobileGL session"; its client log: one more "RECOVERED");
# - the screen still animates (shot.sh hashes differ) and the clients keep presenting;
# - no native crash (logcat -b crash).
# Between rounds the knob is reset to 0 while the clients run, which re-arms it for the same pid.
# Stops early below MIN_BATTERY percent (the phone drains faster under load than USB charges it).
#
# Deploy first (same MobileGL commit on both sides; see SKILL.md):
# bash scripts/build-android.sh && bash scripts/cyc.sh pre # server -> APK, restarts the session
# bash scripts/xbuild.sh && bash scripts/xdeploy.sh # client -> container
# ANLAND_WORKTREE=<anland worktree> bash scripts/kwin-stage.sh build # kwin.patch + anland backend
# (wait for "== ALL DONE ==" in /root/kwin-build.log), then: adb shell 'su -c "sh /data/local/tmp/anl/run-plasma.sh"'
# Env: ROUNDS (default 2), SETTLE (s after the loss, default 10), REARM (s with the knob at 0 between
# rounds, default 4), MIN_BATTERY (default 40), CHROME (1: add Chrome), CHANNEL (ct.sh channel,
# default krec), TAG (screenshot/log tag, default krec).
set -euo pipefail
here=$(cd "$(dirname "$0")" && pwd)
. "$here/env.sh"
ROUNDS=${1:-${ROUNDS:-2}}
SETTLE=${SETTLE:-10}
REARM=${REARM:-4}
MIN_BATTERY=${MIN_BATTERY:-40}
CH=${CHANNEL:-krec}
TAG=${TAG:-krec}
COMPOSITOR_LOG=/tmp/mobilegl-compositor.client.log
SERVER_LOG=/data/data/$MGL_PKG/files/mobilegl-server.server.log
ct() { bash "$here/ct.sh" "$CH"; }
battery() { adb_ shell dumpsys battery | tr -d '\r' | awk '/ level:/ {print $2}'; }
stop_clients() {
ct <<'IN' || true
pkill -x glmark2-es2-way 2>/dev/null; pkill -x glmark2-es2-wayland 2>/dev/null; pkill -x glxgears 2>/dev/null
true
IN
}
cleanup() {
adb_ shell "su -c 'setprop debug.mobilegl.inject_device_lost_pid 0'" || true
stop_clients
}
check_battery() {
local level; level=$(battery)
echo "battery: $level%"
if [ -n "$level" ] && [ "$level" -lt "$MIN_BATTERY" ]; then
echo "STOP: battery below $MIN_BATTERY%"; exit 3
fi
}
trap cleanup EXIT
check_battery
adb_ shell "su -c 'sh $DEV_TOOLS/status.sh'" || true
adb_ shell "su -c 'setprop debug.mobilegl.inject_device_lost_pid 0'"
# The clients, each with its own log (mgrun's MGLOG), in the background for the whole run.
ct <<'IN'
rm -f /tmp/mgl-krec-gm.client.log /tmp/mgl-krec-gx.client.log /tmp/krec-gm.out /tmp/krec-gx.out
MGLOG=/tmp/mgl-krec-gm.log nohup timeout 900 mgrun offscreen glmark2-es2-wayland -s 960x540 --run-forever \
> /tmp/krec-gm.out 2>&1 < /dev/null &
MGLOG=/tmp/mgl-krec-gx.log nohup timeout 900 mgrun offscreen glxgears -info > /tmp/krec-gx.out 2>&1 < /dev/null &
sleep 8
echo "glmark2: $(pgrep -x glmark2-es2-way || pgrep -x glmark2-es2-wayland) glxgears: $(pgrep -x glxgears)"
grep -aE "presented through|could not be presented" /tmp/mgl-krec-gm.client.log | head -2
grep -aE "presented through|readback" /tmp/mgl-krec-gx.client.log | head -2
IN
if [ "${CHROME:-0}" = 1 ]; then
ct <<'IN'
cat > /tmp/mgl-krec-spin.html <<'HTML'
<!doctype html><html><body style="margin:0;background:#000">
<canvas id=c width=640 height=360 style="width:100vw;height:100vh"></canvas>
<script>
const gl = document.getElementById('c').getContext('webgl'); let t = 0;
function frame() { t++; if (gl && !gl.isContextLost()) { gl.clearColor((t % 60) / 60, 0.2, 0.6, 1); gl.clear(gl.COLOR_BUFFER_BIT); }
requestAnimationFrame(frame); }
frame();
</script></body></html>
HTML
chmod 644 /tmp/mgl-krec-spin.html
IN
WAIT=${WAIT:-20} CHANNEL=$CH bash "$here/chrome-launch.sh" "$TAG" --new-window "file:///tmp/mgl-krec-spin.html"
fi
# KWin, plasmashell and the clients, as pids inside the container; how often KWin recovered so far.
snapshot() {
ct <<IN | tr -d '\r' | tail -1
k=\$(pgrep -x kwin_wayland | head -1); p=\$(pgrep -x plasmashell | head -1)
g=\$(pgrep -x glmark2-es2-way || pgrep -x glmark2-es2-wayland); x=\$(pgrep -x glxgears | head -1)
c=\$(pgrep -x chrome | head -1)
r=\$(grep -ac "RECOVERED" $COMPOSITOR_LOG 2>/dev/null || true)
f=\$(grep -ac "FPS" /tmp/krec-gm.out 2>/dev/null || true)
echo "\${k:-none} \${p:-none} \${g:-none} \${x:-none} \${c:-none} \${r:-0} \${f:-0}"
IN
}
pass=0
for round in $(seq 1 "$ROUNDS"); do
echo "=== round $round/$ROUNDS"
check_battery
read -r kwin plasma gm gx chrome recovered fps < <(snapshot)
echo "kwin=$kwin plasmashell=$plasma glmark2=$gm glxgears=$gx chrome=$chrome recoveries=$recovered fps-lines=$fps"
if [ "$kwin" = none ]; then echo "FAIL: KWin is not running"; break; fi
bash "$here/shot.sh" "$TAG-r$round-pre" 2 1
srvlines=$(adb_ shell "su -c 'wc -l < $SERVER_LOG'" | tr -dc '0-9')
adb_ logcat -b crash -c || true
adb_ shell "su -c 'setprop debug.mobilegl.inject_device_lost_pid $kwin'"
sleep "$SETTLE"
adb_ shell "su -c 'setprop debug.mobilegl.inject_device_lost_pid 0'"
bash "$here/shot.sh" "$TAG-r$round-post" 3 1 | tee "$ANL_DIR/$TAG-r$round-post.md5"
read -r kwin2 plasma2 gm2 gx2 chrome2 recovered2 fps2 < <(snapshot)
echo "after: kwin=$kwin2 plasmashell=$plasma2 glmark2=$gm2 glxgears=$gx2 chrome=$chrome2 recoveries=$recovered2 fps-lines=$fps2"
adb_ shell "su -c 'tail -n +$((srvlines + 1)) $SERVER_LOG'" > "$ANL_DIR/$TAG-r$round-server.log"
latched=$(grep -c "injected:pid=$kwin" "$ANL_DIR/$TAG-r$round-server.log" || true)
grep -aE "inject_device_lost_pid|SessionLatch|session #[0-9]+ (started|pid)|owner=server|lease" \
"$ANL_DIR/$TAG-r$round-server.log" | cut -c1-220 | head -14 || true
ct <<IN || true
echo "--- KWin's MobileGL client log:"; grep -aE "DEVICE LOST|RECOVERED|GL_UNKNOWN_CONTEXT_RESET|re-created on the fresh|Refuse" $COMPOSITOR_LOG | tail -6
echo "--- KWin journal:"; journalctl --no-pager --since -40s 2>/dev/null | grep -aE "kwin_wayland" | grep -aiE "reset|restarted|MobileGL swap|context|fatal|abort" | tail -10
echo "--- clients:"; grep -aE "DEVICE LOST|lost|Fatal" /tmp/mgl-krec-gm.client.log /tmp/mgl-krec-gx.client.log | tail -4
IN
crashes=$(adb_ logcat -b crash -d | grep -c "Fatal signal\|Abort message" || true)
hashes=$(awk '{print $1}' "$ANL_DIR/$TAG-r$round-post.md5" | sort -u | wc -l)
verdict=PASS
[ "$latched" -ge 1 ] || { echo " - the server never latched KWin's session (pid $kwin)"; verdict=FAIL; }
[ "$kwin2" = "$kwin" ] || { echo " - KWin is a different process ($kwin -> $kwin2): it restarted"; verdict=FAIL; }
[ "$plasma2" = "$plasma" ] || { echo " - plasmashell restarted ($plasma -> $plasma2)"; verdict=FAIL; }
[ "$gm2" = "$gm" ] && [ "$gx2" = "$gx" ] || { echo " - a test client restarted or died"; verdict=FAIL; }
[ "${CHROME:-0}" != 1 ] || [ "$chrome2" = "$chrome" ] || { echo " - Chrome restarted"; verdict=FAIL; }
[ "$recovered2" -gt "$recovered" ] || { echo " - KWin's client log shows no new RECOVERED session"; verdict=FAIL; }
[ "$fps2" -gt "$fps" ] || { echo " - glmark2 stopped reporting frames"; verdict=FAIL; }
[ "$hashes" -ge 2 ] || { echo " - the screen does not change after the loss (frozen)"; verdict=FAIL; }
[ "$crashes" -eq 0 ] || { echo " - native crash(es):"; adb_ logcat -b crash -d | tail -8; verdict=FAIL; }
echo "round $round: $verdict"
[ "$verdict" = PASS ] && pass=$((pass + 1))
[ "$verdict" = PASS ] || break
# Re-arm the knob for the same pid: a session must observe 0 before the next value counts.
sleep "$REARM"
done
echo "=== $pass/$ROUNDS rounds passed; screenshots in $ANL_DIR/$TAG-r*-*.png"
[ "$pass" = "$ROUNDS" ]
@@ -0,0 +1,135 @@
#!/usr/bin/env bash
# x11-verify.sh <step> [...] - device verification of X11 on the GPU (docs/Disaggregated/notes/anland/
# plan-x11-gpu.md): Xwayland drawing with glamor on MobileGL, and GLX windows presented through
# DRI3 + Present from shared images. Steps, in the order a full run takes them:
#
# preflight read-only: battery, stack status, Xwayland package, render node, xcb libs,
# test apps, Xwayland's extensions and its GLX vendor
# measure <label> [s] glxgears 1280x720 (GEARS_ARGS; vblank_mode=0) for s seconds (10): its fps, then CPU/GPU/dma-buf
# counts (device/x11-measure.sh); also with MOBILEGL_GLX_PRESENT=readback
# deploy-client xbuild.sh + xdeploy.sh of this worktree's client (MGL_XBUILD_DIR)
# deploy-kwin kwin-stage.sh build from ANLAND_WORKTREE; waits for "== ALL DONE =="
# deploy-server build-android.sh + cyc.sh x11-server (swaps the APK lib, RESTARTS the session)
# check the evidence: Xwayland took glamor (journal), its MobileGL log, GLX's path
# line, dma-buf counts in Xwayland/KWin, the server's import lines
# apps X11 clients on screen: konsole and kate on Qt's xcb platform (glamor-drawn
# core X), glxgears (GLX), xterm/xeyes when installed; two screenshots
# stop kill the test apps
#
# Typical run: preflight; measure before; deploy-client; deploy-kwin; deploy-server; check; measure
# after; apps; stop. Battery: every load step refuses below MIN_BATTERY (40) %.
# Env: CHANNEL (ct.sh channel, default x11), ANLAND_WORKTREE (anland x11-gpu worktree, Windows
# form), MGL_XBUILD_DIR (default /home/swung/mgl-xbuild-x11), MIN_BATTERY.
set -euo pipefail
here=$(cd "$(dirname "$0")" && pwd)
. "$here/env.sh"
CH=${CHANNEL:-x11}
: "${MGL_XBUILD_DIR:=/home/swung/mgl-xbuild-x11}"
: "${ANLAND_WORKTREE:=$(cygpath -m "$USERPROFILE" 2>/dev/null)/AndroidStudioProjects/anland/.claude/worktrees/x11-gpu}"
export MGL_XBUILD_DIR ANLAND_WORKTREE
battery_ok() {
local level
level=$(adb_ shell "dumpsys battery" | sed -n 's/^ *level: *//p' | tr -d '\r')
echo "battery: ${level}%"
if [ "${level:-0}" -lt "${MIN_BATTERY:-40}" ]; then
echo "below ${MIN_BATTERY:-40}%: stopping GPU-heavy work; charge the phone first" >&2
return 1
fi
}
push_measure() {
tr -d '\r' < "$here/device/x11-measure.sh" > "$ANL_DIR/x11-measure.sh"
adb_ push "$ANL_DIR/x11-measure.sh" "$DEV_TOOLS/x11-measure.sh" >/dev/null
}
step=${1:?usage: x11-verify.sh <preflight|measure|deploy-client|deploy-kwin|deploy-server|check|apps|stop>}
shift
case "$step" in
preflight)
battery_ok || true
adb_ shell "su -c 'sh $DEV_TOOLS/status.sh'" || true
bash "$here/ct.sh" "$CH" <<'IN'
echo "== packages"; pacman -Q xorg-xwayland libxcb mesa-utils xorg-xdpyinfo qt6-base 2>&1 | sed 's/^/ /'
echo "== render nodes"; ls -l /dev/dri/ 2>&1 | sed 's/^/ /'
U=swung0x48; for n in /dev/dri/renderD*; do sudo -u $U test -r "$n" -a -w "$n" && echo " $U can open $n"; done
echo "== KWin's thin node"; tr '\0' '\n' < /proc/$(pgrep -x kwin_wayland)/environ 2>/dev/null | grep -E "MOBILEGL_GBM_NODE|ANLAND_XWAYLAND_GLAMOR|GBM_BACKEND" | sed 's/^/ /'
echo "== xcb libraries"; for l in libxcb-dri3.so.0 libxcb-present.so.0 libxcb-xfixes.so.0 libxcb-shm.so.0; do ls /usr/lib/$l >/dev/null 2>&1 && echo " $l ok" || echo " $l MISSING"; done
echo "== Xwayland"; pgrep -a -x Xwayland | sed 's/^/ /'
mgrun offscreen xdpyinfo 2>/dev/null | grep -E "^ +(DRI3|Present|MIT-SHM|XFIXES|GLX)$" | sed 's/^/ ext/'
mgrun offscreen glxinfo -B 2>&1 | grep -E "vendor|renderer|direct rendering" | sed 's/^/ /'
IN
;;
measure)
label=${1:?usage: x11-verify.sh measure <label> [seconds]}
secs=${2:-10}
battery_ok
push_measure
for mode in auto readback; do
printf '%s\n' \
"pkill -x glxgears; rm -f /tmp/mgl-x11-gears.client.log /tmp/x11-gears.out" \
"MGLOG=/tmp/mgl-x11-gears.log timeout $((secs + 8)) mgrun offscreen env vblank_mode=${VBLANK_MODE:-0} MOBILEGL_GLX_PRESENT=$mode glxgears ${GEARS_ARGS:--geometry 1280x720} > /tmp/x11-gears.out 2>&1 &" \
"sleep 3" | bash "$here/ct.sh" "$CH" >/dev/null
adb_ shell "su -c 'sh $DEV_TOOLS/x11-measure.sh $label-$mode glxgears $secs'" || true
sleep 6
printf '%s\n' "grep -a 'frames in' /tmp/x11-gears.out | tail -3; grep -a 'presented through' /tmp/mgl-x11-gears.client.log | head -1; pkill -x glxgears; true" \
| bash "$here/ct.sh" "$CH"
done
;;
deploy-client)
bash "$here/xbuild.sh"
CHANNEL=$CH bash "$here/xdeploy.sh"
;;
deploy-kwin)
CHANNEL=$CH bash "$here/kwin-stage.sh" build
for _ in $(seq 1 120); do
out=$(printf 'tail -3 /root/kwin-build.log\n' | bash "$here/ct.sh" "$CH" 2>/dev/null || true)
echo "$out" | tail -1
echo "$out" | grep -q "== ALL DONE ==" && exit 0
echo "$out" | grep -qiE "error|failed" && { echo "KWin build failed" >&2; exit 1; }
sleep 30
done
echo "KWin build did not finish in an hour" >&2; exit 1
;;
deploy-server)
battery_ok
bash "$here/build-android.sh"
CHANNEL=$CH bash "$here/cyc.sh" x11-server
;;
check)
bash "$here/ct.sh" "$CH" <<'IN'
echo "== Xwayland's command line (no -shm with glamor)"; pgrep -a -x Xwayland | sed 's/^/ /'
echo "== Xwayland's glamor (journal)"
journalctl --no-pager --since -30min 2>/dev/null | grep -aiE "glamor|Xwayland.*(EGL|gbm|dri3|falling back)" | tail -10 | sed 's/^/ /'
echo "== Xwayland's MobileGL client log"; grep -aE "presented|shared image|declin|Fatal|ERROR" /tmp/mgl-xwayland.client.log /tmp/mgl-xwayland.client 2>/dev/null | tail -8 | sed 's/^/ /' || echo " (none)"
X=$(pgrep -x Xwayland); K=$(pgrep -x kwin_wayland)
echo "== dma-bufs held: Xwayland $(ls -l /proc/$X/fd 2>/dev/null | grep -c dmabuf), kwin $(ls -l /proc/$K/fd 2>/dev/null | grep -c dmabuf)"
echo "== Xwayland's GLX vendor and extensions"
mgrun offscreen xdpyinfo 2>/dev/null | grep -E "^ +(DRI3|Present|MIT-SHM)$" | sed 's/^/ ext/'
echo "== a GLX window's path"
rm -f /tmp/mgl-x11-check.client.log
MGLOG=/tmp/mgl-x11-check.log timeout 6 mgrun offscreen glxgears >/dev/null 2>&1
grep -a "presented through\|leaves DRI3" /tmp/mgl-x11-check.client.log | sed 's/^/ /'
IN
adb_ logcat -d | grep -aE "MobileGL.*(shared image|dma-buf import|refused)" | tail -8 || true
adb_ logcat -b crash -d | tail -5 || true
;;
apps)
battery_ok
printf '%s\n' \
"pkill -x xterm; pkill -x xeyes; pkill -x glxgears; pkill -x konsole; pkill -x kate" \
"MGLOG=/tmp/mgl-x11-konsole.log mgrun offscreen env QT_QPA_PLATFORM=xcb konsole >/dev/null 2>&1 &" \
"MGLOG=/tmp/mgl-x11-kate.log mgrun offscreen env QT_QPA_PLATFORM=xcb kate >/dev/null 2>&1 &" \
"command -v xterm >/dev/null && MGLOG=/tmp/mgl-x11-xterm.log mgrun offscreen xterm >/dev/null 2>&1 &" \
"command -v xeyes >/dev/null && MGLOG=/tmp/mgl-x11-xeyes.log mgrun offscreen xeyes >/dev/null 2>&1 &" \
"MGLOG=/tmp/mgl-x11-gears.log mgrun offscreen glxgears >/dev/null 2>&1 &" \
"sleep 6; pgrep -a -x konsole; pgrep -a -x kate; pgrep -a -x xterm; pgrep -a -x xeyes; pgrep -a -x glxgears; true" | bash "$here/ct.sh" "$CH"
bash "$here/shot.sh" x11-apps 2 1
;;
stop)
printf '%s\n' "pkill -x xterm; pkill -x xeyes; pkill -x glxgears; pkill -x konsole; pkill -x kate; true" | bash "$here/ct.sh" "$CH"
;;
*)
echo "unknown step $step" >&2; exit 2
;;
esac
+14
View File
@@ -304,6 +304,7 @@ set(SOURCE_FILES
MobileGL/ConfigLoader.cpp
MobileGL/MG_Util/Debug/Log.cpp
MobileGL/MG_Util/X11/DisplayGuard.cpp
MobileGL/MG_Util/Async/JobNode.cpp
MobileGL/MG_Util/Async/ShaderCompilePool.cpp
@@ -401,6 +402,8 @@ set(SOURCE_FILES
MobileGL/MG_Impl/GLXImpl/Exporting/Definitions.cpp
MobileGL/MG_Impl/GLXImpl/Exporting/GlvndVendor.cpp
MobileGL/MG_Impl/GLXImpl/GLXImpl.cpp
MobileGL/MG_Impl/GLXImpl/X11Present.cpp
MobileGL/MG_Impl/GLXImpl/X11PresentXcb.cpp
MobileGL/MG_Impl/GLXImpl/LookUp/LookUp.cpp
MobileGL/MG_Impl/EGLImpl/Exporting/Definitions.cpp
@@ -1004,6 +1007,17 @@ if (NOT ANDROID AND NOT MOBILEGL_IOS)
endif ()
endif ()
# Discover gtest cases when ctest starts, one binary after another, instead of in a post-build
# step. The post-build discovery of the CMake releases that never pass the target name down
# writes every binary's `--gtest_output=json` result to ONE per-directory file
# (cmake_test_discovery_<hash of an empty name>.json), so binaries linked in parallel in the same
# directory overwrite and delete each other's list: the registered count then differs between
# runs of the same tree and a binary ends up with none or only some of its cases. The pre-test
# mode reads the list from stdout, serially, and also works when the binary is cross-built.
if (NOT DEFINED CMAKE_GTEST_DISCOVER_TESTS_DISCOVERY_MODE)
set(CMAKE_GTEST_DISCOVER_TESTS_DISCOVERY_MODE PRE_TEST)
endif()
if (NOT ANDROID)
# Enable testing in the top-level scope so a CTestTestfile.cmake is emitted
# at the build-tree root. This lets `ctest` be invoked from the top-level
+28
View File
@@ -666,6 +666,23 @@ namespace MobileGL {
(void)region;
return true;
}
// IMPLICIT SYNC BY FLUSH (docs/Disaggregated/notes/anland/plan-x11-gpu.md): the session
// on this (the apply) thread ends a frame at a glFlush. Every shared image it used since
// its last boundary is published as written and read by one fence of everything it
// submitted (SharedImages::ReadTracker::PublishFrameAsWrite), and from now on its first
// use of an image in a frame waits for that image's pending reads (it may be about to
// overwrite what another session still samples). A backend without shared images has
// nothing to publish.
virtual Bool PublishSharedImageAccesses() { return true; }
// EGL_ANDROID_native_fence_sync's fence command, on the server: in `*fence`, a sync_file
// (the caller's to close) that signals once everything the session submitted so far has
// completed - and, for a session that writes images, what PublishSharedImageAccesses
// does. -1 when there is none to give: the backend cannot export one, or the work has
// already completed - in both cases it HAS completed when this returns.
virtual Bool ExportNativeFence(int* fence) {
*fence = -1;
return PublishSharedImageAccesses();
}
// ---- shared images, CLIENT side (BackendObject_Remote implements these) ----------
//
@@ -711,6 +728,17 @@ namespace MobileGL {
(void)textureLifetimeId, (void)id;
return false;
}
// In the GL stream, from glFlush/glFinish: PublishSharedImageAccesses on the server,
// returning once the fence is published. Skipped (true) when nothing reached the stream
// since the last one.
virtual Bool FlushSharedImageAccesses() { return false; }
// In the GL stream, from eglCreateSync(EGL_SYNC_NATIVE_FENCE_ANDROID) with no descriptor:
// ExportNativeFence on the server. `*fence` is the sync_file it handed back (the
// caller's to close), or -1 when it had none - the fenced work has then completed.
virtual Bool CreateNativeFence(int* fence) {
*fence = -1;
return false;
}
virtual void Initialize() = 0;
virtual Bool InitCapabilities() = 0;
@@ -1230,6 +1230,23 @@ namespace MobileGL::MG_Backend::DirectGLES {
return DirectGLES::SetCurrentDrawDamageRegion(region);
}
Bool BackendObject_DirectGLES::PublishSharedImageAccesses() {
#if MOBILEGL_BUILD_DISAGGREGATED
return DirectGLES::SharedImageImpl::PublishPendingAccesses();
#else
return true;
#endif
}
Bool BackendObject_DirectGLES::ExportNativeFence(int* fence) {
*fence = -1;
#if MOBILEGL_BUILD_DISAGGREGATED
return DirectGLES::SharedImageImpl::ExportNativeFence(fence);
#else
return true;
#endif
}
Bool BackendObject_DirectGLES::SwapEGLBuffers(EGLDisplay dpy, EGLSurface draw) {
return BackendObject::SwapEGLBuffers(dpy, draw);
}
@@ -51,6 +51,10 @@ namespace MobileGL::MG_Backend::DirectGLES {
Int32 QueryCurrentBufferAge(Bool damageRegionFollows) override;
// eglSetDamageRegionKHR on a window surface whose driver has EGL_KHR_partial_update.
Bool SetCurrentDamageRegion(const MG_Util::Damage::Region& region) override;
// A glFlush that ends a shared-image producer's frame (SharedImageImpl::PublishPendingAccesses).
Bool PublishSharedImageAccesses() override;
// An EGL native fence of the session's work (SharedImageImpl::ExportNativeFence).
Bool ExportNativeFence(int* fence) override;
void ReleaseEGLSurface(EGLSurface surface) override;
void ReleaseEGLResources() override;
// The server window going and coming back: each window surface on it swaps its native EGL
+74 -4
View File
@@ -8,6 +8,7 @@
#include "DirectGLES.h"
#include "ContextEpoch.h"
#include "MG_Util/X11/DisplayGuard.h"
#include "EGL/egl.h"
#include "MG_Util/Types.h"
#include "Utils.h"
@@ -16769,7 +16770,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
static EGLint QueryDefaultX11VisualId() {
#if defined(__linux__) && !defined(__ANDROID__)
const char* displayName = std::getenv("DISPLAY");
if (!displayName) {
if (!displayName || !MG_Util::X11::MayDialX11Display(displayName)) {
return 0;
}
@@ -16816,7 +16817,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
return 0;
}
const char* displayName = std::getenv("DISPLAY");
if (!displayName) {
if (!displayName || !MG_Util::X11::MayDialX11Display(displayName)) {
return 0;
}
@@ -17109,7 +17110,14 @@ namespace MobileGL::MG_Backend::DirectGLES {
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) {
// NOT WHILE A SESSION STILL HOLDS SURFACES. eglTerminate destroys them with the display, and
// the session keeps naming them: the next context made current on one (an application that
// destroys its only context and creates another on the same surface, as eglinfo does with
// its surfaceless stand-in) bound a surface the driver no longer had. The session's own
// teardown terminates the display once its surfaces are gone (DestroyNativeStateOfSession).
Bool surfacesRemain = false;
for (const auto* session : NativeSessions()) surfacesRemain = surfacesRemain || !session->Surfaces.empty();
if (g_displayUsers == 0 && !surfacesRemain && g_Display != EGL_NO_DISPLAY && g_EGLFuncs.eglTerminate) {
g_EGLFuncs.eglTerminate(g_Display);
NoteDisplayTerminated();
g_Display = EGL_NO_DISPLAY;
@@ -17137,6 +17145,12 @@ namespace MobileGL::MG_Backend::DirectGLES {
// own thread with its own context, and binding a context back onto another window's
// surface drew one window's frame into the other.
NativeSessionState& session = ActiveNativeSession();
// Nothing to make it current on yet: a context bound for the records of its own creation
// (EGLImpl's CreateContext), which no make-current has given a surface (or whose surface
// is gone). Binding it to whichever surface the session holds would hand it another
// context's surface - one the driver may not even have any more. Its first make-current
// binds it natively.
if (tuple.Draw == EGL_NO_SURFACE) return true;
if (tuple.Draw != session.Draw && SessionOwnsSurface(session, tuple.Draw)) {
session.Draw = tuple.Draw;
session.Read = SessionOwnsSurface(session, tuple.Read) ? tuple.Read : tuple.Draw;
@@ -18812,6 +18826,9 @@ namespace MobileGL::MG_Backend::DirectGLES {
struct ReadFrame {
Uint64 Id = 0;
SI::ReadTracker Tracker;
// The session ends frames at publishing flushes (PublishPendingAccesses): it writes
// images, so its first use of one in a frame waits for that image's pending reads.
Bool ImplicitSync = false;
};
std::atomic<Uint64> g_readFrameIds{0};
@@ -18839,11 +18856,54 @@ namespace MobileGL::MG_Backend::DirectGLES {
CloseFd(fence);
ReadFrame& frame = CurrentReadFrame();
if (state.NotedFrame != frame.Id) {
// A session that renders into images (it ends frames with a publishing flush) may be
// about to overwrite this one: what other sessions still sample goes first.
if (frame.ImplicitSync) {
for (const int read : SI::DupPendingReadFences(*state.Image)) WaitForFenceBeforeLaterCommands(read);
}
frame.Tracker.NoteRead(state.Image);
state.NotedFrame = frame.Id;
}
}
Bool PublishPendingAccesses() {
ReadFrame& frame = CurrentReadFrame();
frame.ImplicitSync = true;
// Sub-data waiting for a sync that nothing of this session would otherwise trigger.
if (t_boundNativeContext != EGL_NO_CONTEXT) TextureImpl::WritePendingSharedImageUploads();
if (frame.Tracker.Pending() == 0) return true;
int fence = -1;
if (t_boundNativeContext != EGL_NO_CONTEXT && !ExportFence(&fence)) {
// No fence to publish: the work is waited out here, and published as completed.
(void)WaitForCompletion();
}
frame.Tracker.PublishFrameAsWrite(fence);
frame.Id = g_readFrameIds.fetch_add(1, std::memory_order_relaxed) + 1;
return true;
}
Bool ExportNativeFence(int* fence) {
*fence = -1;
ReadFrame& frame = CurrentReadFrame();
// No context current: nothing of this session is in flight to fence.
if (t_boundNativeContext == EGL_NO_CONTEXT) return true;
TextureImpl::WritePendingSharedImageUploads();
int exported = -1;
if (!ExportFence(&exported)) {
// No descriptor to give: the work is waited out, so the caller may report it done.
exported = -1;
(void)WaitForCompletion();
}
// A session that writes images (one that ends frames at flushes) ends one here too; a
// compositor's reads stay for its swap, which comes after the fence's work anyway.
if (frame.ImplicitSync && frame.Tracker.Pending() != 0) {
frame.Tracker.PublishFrameAsWrite(exported >= 0 ? ::dup(exported) : -1);
frame.Id = g_readFrameIds.fetch_add(1, std::memory_order_relaxed) + 1;
}
*fence = exported;
return true;
}
void PublishPendingReads() {
ReadFrame& frame = CurrentReadFrame();
if (frame.Tracker.Pending() == 0) return;
@@ -18856,7 +18916,12 @@ namespace MobileGL::MG_Backend::DirectGLES {
// producer), nothing it submitted still samples the image.
(void)WaitForCompletion();
}
frame.Tracker.PublishFrame(fence);
// A session that writes images publishes every boundary as a write: an image it rendered
// into must not leave the frame without its generation moving.
if (frame.ImplicitSync)
frame.Tracker.PublishFrameAsWrite(fence);
else
frame.Tracker.PublishFrame(fence);
frame.Id = g_readFrameIds.fetch_add(1, std::memory_order_relaxed) + 1;
}
@@ -19034,6 +19099,11 @@ namespace MobileGL::MG_Backend::DirectGLES {
}
void AcquireForSampling(const EglImageRef& image) { (void)image; }
void PublishPendingReads() {}
Bool PublishPendingAccesses() { return true; }
Bool ExportNativeFence(int* fence) {
*fence = -1;
return true;
}
void ForgetPresentTargetsAfterTerminate() {}
#endif
} // namespace SharedImageImpl
@@ -546,6 +546,16 @@ namespace MobileGL::MG_Backend::DirectGLES {
// at Present and wherever the current native context stops being current (its reads can
// only be fenced from it). Nothing noted = nothing done.
void PublishPendingReads();
// IMPLICIT SYNC BY FLUSH (BackendObject::PublishSharedImageAccesses): everything the
// calling session used since its last boundary is published as written and read by one
// fence, and the session's first use of an image in each frame from now on also waits for
// the image's pending reads.
Bool PublishPendingAccesses();
// EGL_ANDROID_native_fence_sync's fence command (BackendObject::ExportNativeFence): a
// sync_file of everything the current context submitted in `*fence` (-1: none, and the work
// is waited out here), and - for a session that writes images - the boundary
// PublishPendingAccesses makes.
Bool ExportNativeFence(int* fence);
} // namespace SharedImageImpl
#endif
+95 -18
View File
@@ -8858,27 +8858,12 @@ namespace MobileGL::MG_Backend::DirectGLES {
return false;
}
// Sub-data aimed at the image is not replayed into it - the image is written by the
// producer's present - but it must still leave the pending set, or the per-draw clean
// gate (IsDrawSyncCleanByRecord) would never close.
const auto dropPendingUploads = [&record] {
if (record.PendingUploads.empty()) return;
MGLOG_W_ONCE("Shared image texture %u: sub-data on an attached shared image is dropped",
record.Desc.GlNameForDiag);
Vector<std::pair<Uint16, Uint16>> keys;
keys.reserve(record.PendingUploads.size());
for (const auto& pending : record.PendingUploads) {
keys.emplace_back(MG_Pipe::MGPipeSubDataUploadTargetOf(pending.UploadTarget), pending.Level);
}
for (const auto& key : keys) ConsumePipeTextureUpload(record.Desc.Resource, key.first, key.second);
};
// Steady state: bound to this image already (the serial moves with sub-data and with a
// metadata respecify, neither of which changes what the name samples). A failed bind is
// retried only once the record moves.
// retried only once the record moves. Pending sub-data is the caller's
// (ReplaySharedImageUploads), after the image's sync state has been acquired.
if (m_sharedImageId == imageId && m_isInitialized &&
(m_sharedImage != nullptr || m_syncedResourceSerial == record.Serial)) {
dropPendingUploads();
m_syncedResourceSerial = record.Serial;
return true;
}
@@ -8893,7 +8878,6 @@ namespace MobileGL::MG_Backend::DirectGLES {
// Whatever comes next redefines storage through a re-mint (see the imageId == 0 arm).
m_backendStorageImmutable = true;
m_syncedResourceSerial = record.Serial;
dropPendingUploads();
const TextureTarget target = BufferImpl::StagedTextureTargetForPipeTarget(record.Desc.Target);
if (ConvertTextureTargetToBackendGLEnum(target) != GL_TEXTURE_2D) {
@@ -8915,6 +8899,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
return true;
}
m_sharedImage = std::move(image);
m_sharedImageUploadsRgb = false;
// The shape the name now has: the descriptor's level 0, and that one level only.
m_prevTextureInfo = {static_cast<TextureInternalFormat>(record.Desc.InternalFormat),
record.Desc.Width,
@@ -8926,6 +8911,83 @@ namespace MobileGL::MG_Backend::DirectGLES {
record.Desc.FixedSampleLocations != 0};
return true;
}
// SUB-DATA ON A SHARED IMAGE IS WRITTEN INTO IT. An X server drawing with glamor uploads
// its clients' pixels (MIT-SHM / PutImage) into window pixmaps whose level 0 is a shared
// image, with glTexSubImage2D: the texels are in the staged store (the client defined the
// level without data, so only the uploaded boxes are covered), and they go into the
// EGLImage-backed name box by box. Every pending entry leaves the set either way, or the
// per-draw clean gate would never close. Called after AcquireForSampling, so the upload is
// ordered after the image's pending reads and writes like any other use.
void BackendTextureObject::ReplaySharedImageUploads(const MG_Pipe::MGPipeResourceRecord& record) {
if (record.PendingUploads.empty()) return;
Vector<std::pair<Uint16, Uint16>> keys;
Vector<std::pair<Uint16, MG_Pipe::MGPBox>> boxes;
keys.reserve(record.PendingUploads.size());
for (const auto& pending : record.PendingUploads) {
const Uint16 uploadHalf = MG_Pipe::MGPipeSubDataUploadTargetOf(pending.UploadTarget);
keys.emplace_back(uploadHalf, pending.Level);
if (pending.Level != 0) continue; // an image has one level
if (pending.Regions.empty()) {
boxes.emplace_back(uploadHalf, pending.UnionBox);
} else {
for (const auto& region : pending.Regions)
boxes.emplace_back(uploadHalf, MG_Pipe::MGPBox{region.X, region.Y, region.Z, region.W, region.H,
region.D});
}
}
if (m_sharedImage != nullptr && !boxes.empty()) {
auto& store = MG_Remote::Server::ServerStagedTexture();
const Uint64 key = MG_Remote::Server::StagedTextureStore::KeyForHandle(record.Desc.Resource);
Bind(GL_TEXTURE_2D);
ScopedDefaultUnpackState unpackState;
BufferImpl::BindPixelUnpackBufferId(0);
for (const auto& [uploadHalf, box] : boxes) {
Int rowTexels = 0;
// A shared image is RGBA8 to every client that names it (the level the client
// defined over it): four bytes a texel.
const Uint8* bytes =
store.CoveredBoxBytes(key, uploadHalf, 0, box.X, box.Y, box.W, box.H, 4, &rowTexels);
if (bytes == nullptr) {
MGLOG_E_ONCE("Shared image texture %u: an upload of %ux%u at (%d,%d) has no staged texels; "
"not written",
record.Desc.GlNameForDiag, box.W, box.H, box.X, box.Y);
continue;
}
const Uint8* origin =
bytes + (static_cast<SizeT>(box.Y) * static_cast<SizeT>(rowTexels) + static_cast<SizeT>(box.X)) * 4;
if (!m_sharedImageUploadsRgb) {
while (g_GLESFuncs.glGetError() != GL_NO_ERROR) {
}
g_GLESFuncs.glPixelStorei(GL_UNPACK_ROW_LENGTH, rowTexels);
g_GLESFuncs.glTexSubImage2D(GL_TEXTURE_2D, 0, box.X, box.Y, static_cast<GLsizei>(box.W),
static_cast<GLsizei>(box.H), GL_RGBA, GL_UNSIGNED_BYTE, origin);
g_GLESFuncs.glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
// An image of an X format (no alpha) is an RGB8 texture to the driver, which
// takes only RGB texels: this image's uploads are converted from now on.
if (g_GLESFuncs.glGetError() != GL_INVALID_OPERATION) continue;
m_sharedImageUploadsRgb = true;
}
Vector<Uint8> rgb(static_cast<SizeT>(box.W) * box.H * 3);
for (Uint32 row = 0; row < box.H; ++row) {
const Uint8* src = origin + static_cast<SizeT>(row) * static_cast<SizeT>(rowTexels) * 4;
Uint8* dst = rgb.data() + static_cast<SizeT>(row) * box.W * 3;
for (Uint32 x = 0; x < box.W; ++x) {
dst[x * 3 + 0] = src[x * 4 + 0];
dst[x * 3 + 1] = src[x * 4 + 1];
dst[x * 3 + 2] = src[x * 4 + 2];
}
}
g_GLESFuncs.glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
g_GLESFuncs.glTexSubImage2D(GL_TEXTURE_2D, 0, box.X, box.Y, static_cast<GLsizei>(box.W),
static_cast<GLsizei>(box.H), GL_RGB, GL_UNSIGNED_BYTE, rgb.data());
g_GLESFuncs.glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
}
MGLOG_I_ONCE("Shared image texture %u: sub-data written into its image (%s texels)",
record.Desc.GlNameForDiag, m_sharedImageUploadsRgb ? "RGB" : "RGBA");
}
for (const auto& [uploadHalf, level] : keys) ConsumePipeTextureUpload(record.Desc.Resource, uploadHalf, level);
}
#endif
void BackendTextureObject::SyncMipmapsToBackend(
@@ -8979,6 +9041,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
// a write that landed since the last one is waited for on this context's GPU
// before the command this sync is for, and the session's frame notes the read.
if (m_sharedImage != nullptr) SharedImageImpl::AcquireForSampling(m_sharedImage);
ReplaySharedImageUploads(*pushedStorage);
return;
}
// P5e (tx2), CONTRACT-P5E §5.2 (scout G-S2-2): THE VIEW TEST MOVES BEHIND THE
@@ -11248,6 +11311,20 @@ namespace MobileGL::MG_Backend::DirectGLES {
g_boundTexturesCache;
TwinRegistry<MG_State::GLState::ITextureObject, BackendTextureObject, MG_Pipe::MGPipeKind::Texture> g_backendTextureObjects;
#if MOBILEGL_BUILD_DISAGGREGATED
void WritePendingSharedImageUploads() {
auto& applier = MG_Pipe::MGPipeApplier();
for (SizeT slot = 0; slot < applier.TextureResources.size(); ++slot) {
const auto& record = applier.TextureResources[slot];
if (!record.Live || record.SharedImageId == 0 || record.PendingUploads.empty()) continue;
const MG_Pipe::MGPipeHandle handle{static_cast<Uint32>(slot), record.Gen};
auto* twin = g_backendTextureObjects.FindByHandle(handle);
if (twin == nullptr || !*twin) continue;
(*twin)->SyncMipmapsToBackendByHandle(handle);
}
}
#endif
void NoteDriverSideTextureWrite(const SharedPtr<MG_State::GLState::ITextureObject>& textureObject) {
SharedPtr<MG_State::GLState::ITextureObject> storage = textureObject;
// Bounded: GL resolves a view of a view to the original storage, so this takes one step.
+10
View File
@@ -2111,6 +2111,10 @@ namespace MobileGL::MG_Backend::DirectGLES {
// not go on to allocate or upload. False when the record names no image: a twin that
// was bound to one has been told to re-mint, and the normal storage path takes over.
Bool SyncSharedImageStorage(const MG_Pipe::MGPipeResourceRecord& record);
// Pending sub-data written into the attached shared image (Managers.cpp).
void ReplaySharedImageUploads(const MG_Pipe::MGPipeResourceRecord& record);
// The attached image takes RGB texels only (an X format): uploads are converted.
Bool m_sharedImageUploadsRgb = false;
#endif
// Whether this texture's ES storage was minted in an image carrier rather than in the
// frontend format's own layout - the readback has to ask, because for a NORMALIZED
@@ -2483,6 +2487,12 @@ namespace MobileGL::MG_Backend::DirectGLES {
// FBO's texture attachments - onto the backend, through the two borrowed-pair memos
// documented at their definitions. Declared here so tests can drive those memos directly.
void SyncNeccessaryTextures();
#if MOBILEGL_BUILD_DISAGGREGATED
// Every texture of this session bound to a shared image with sub-data still pending is
// synced now, so the uploads are in the images before a flush publishes them (an X
// server's PutImage into a window pixmap no later draw of its own samples).
void WritePendingSharedImageUploads();
#endif
extern Array<Array<BackendTextureObject*, (SizeT)TextureTarget::TextureTargetCount>,
MG_State::GLState::TextureState::MAX_TEXTURE_IMAGE_UNITS>
g_boundTexturesCache;
+4 -1
View File
@@ -572,7 +572,10 @@ namespace MobileGL::MG_Backend::DirectGLES {
ZoneScopedC(TRACY_ZONECOLOR_BACKEND);
#endif
// The name is the marker: ShaderSourceProcessor only emits it when the source
// wrote gl_FragColor, and such a shader can have no other output.
// names gl_FragColor, and a shader that writes it can have no other output. One that
// names it only in an inactive preprocessor arm keeps the declaration unwritten, and
// the IO resolver moves that inactive output off location 0, so the match below
// (which wants location 0) does not take it.
static const char* const kLoweredName = "mg_FragColor";
if (shaderType != GL_FRAGMENT_SHADER || drawBufferCount <= 1) {
return glslCode;
@@ -585,6 +585,25 @@ namespace MobileGL::MG_Backend::DirectVulkan {
#endif
}
Bool BackendObject_DirectVulkan::PublishSharedImageAccesses() {
#if MOBILEGL_BUILD_DISAGGREGATED
const std::lock_guard<std::recursive_mutex> lock(m_eglStateMutex);
return pVulkanRenderer ? pVulkanRenderer->PublishSharedImageAccesses() : true;
#else
return true;
#endif
}
Bool BackendObject_DirectVulkan::ExportNativeFence(int* fence) {
*fence = -1;
#if MOBILEGL_BUILD_DISAGGREGATED
const std::lock_guard<std::recursive_mutex> lock(m_eglStateMutex);
return pVulkanRenderer ? pVulkanRenderer->ExportNativeFence(fence) : true;
#else
return true;
#endif
}
// A swapchain image keeps its content through a present whatever region is drawn next: the
// damage region the client may declare is not needed here.
Int32 BackendObject_DirectVulkan::QueryCurrentBufferAge(Bool damageRegionFollows) {
@@ -42,6 +42,10 @@ namespace MobileGL::MG_Backend::DirectVulkan {
const MG_Util::Damage::Region& region) override;
// The active surface target's swapchain image ages (VulkanRenderer::CurrentDrawBufferAge).
Int32 QueryCurrentBufferAge(Bool damageRegionFollows) override;
// A glFlush that ends a shared-image producer's frame (VulkanRenderer::PublishSharedImageAccesses).
Bool PublishSharedImageAccesses() override;
// An EGL native fence of the session's work (VulkanRenderer::ExportNativeFence).
Bool ExportNativeFence(int* fence) override;
void ReleaseEGLSurface(EGLSurface surface) override;
void ReleaseEGLResources() override;
// The server window going and coming back: the window surface's target (VkSurfaceKHR,
@@ -8,6 +8,7 @@
#include "VulkanRenderer.h"
#include "SubmitFencePrefix.h"
#include "MG_Util/X11/DisplayGuard.h"
#include "OffscreenSurfaceRoute.h"
#include "MG_Backend/DirectVulkan/SubgroupSupportPolicy.h"
@@ -16720,7 +16721,10 @@ void main() {
}
const char* displayName = std::getenv("DISPLAY");
auto* display = xOpenDisplay(displayName);
// Never the display this process serves (MG_Util/X11/DisplayGuard.h).
auto* display = displayName != nullptr && MG_Util::X11::MayDialX11Display(displayName)
? xOpenDisplay(displayName)
: nullptr;
if (display == nullptr) {
MGLOG_F("XOpenDisplay(%s) failed while creating a Vulkan Xlib window surface; there is no usable X "
"display for the requested window surface",
@@ -191,6 +191,15 @@ namespace MobileGL::MG_Backend::DirectVulkan {
// renderer has written before - the rest of it is left as it is; a first write, a scaled
// or turned copy copies all of it.
Bool BlitDefaultFramebufferToSharedImage(const SharedImageView& image, const MG_Util::Damage::Region& region);
// IMPLICIT SYNC BY FLUSH (BackendObject::PublishSharedImageAccesses): every image acquired
// since the last boundary goes back to the foreign family, the recording is submitted with
// the exportable semaphore, and its sync_file is published to each as a write and a read.
// From then on an image's first acquire per frame also waits for its pending reads.
Bool PublishSharedImageAccesses();
// EGL_ANDROID_native_fence_sync's fence command (BackendObject::ExportNativeFence): the
// submission's sync_file in `*fence` (-1: none, and the work is waited out here), and - for
// a session that writes images - the boundary PublishSharedImageAccesses makes.
Bool ExportNativeFence(int* fence);
// EGL_BUFFER_AGE_EXT of the active target's default framebuffer for the next frame: the age
// of the swapchain image acquired for it (SwapchainObject::BufferAgeOf). Asking makes the
// target keep its presented images' content from then on.
@@ -721,6 +730,11 @@ namespace MobileGL::MG_Backend::DirectVulkan {
// m_sharedImageSyncFd: the device imports and exports SYNC_FD binary semaphores; without
// it the waits happen on the CPU and nothing is exported (see WireSharedImage.inc).
Bool m_sharedImageSyncFd = false;
// The session writes images - it ends frames at publishing flushes
// (PublishSharedImageAccesses), or it reached one through a framebuffer (ResolveWireImage):
// a first acquire waits for the image's pending reads as well, and its boundaries publish
// what it used as written.
Bool m_sharedImageImplicitSync = false;
PFN_vkImportSemaphoreFdKHR m_importSemaphoreFd = nullptr;
PFN_vkGetSemaphoreFdKHR m_getSemaphoreFd = nullptr;
struct SharedImageWait {
@@ -161,7 +161,12 @@
auto* resource = m_textureManager->SyncTextureResourceByHandle(out.storage, renderbuffer);
if (!resource) MagmaWireFatal("framebuffer-resource");
// Another session writes it: acquired (WireSharedImage.inc) before the layout is read below.
if (resource->sharedImageId != 0) AcquireSharedImage(*resource);
// An image reached through a framebuffer is one this session renders into (or copies
// through), which makes it a writer of images from now on.
if (resource->sharedImageId != 0) {
m_sharedImageImplicitSync = true;
AcquireSharedImage(*resource);
}
out.image = resource->image;
out.format = viewFormat != VK_FORMAT_UNDEFINED ? viewFormat : resource->format;
out.extent = {std::max(resource->extent.width >> level, 1u),
@@ -517,6 +517,11 @@
// The write's fence gates the submission carrying the acquire: this recording's, or an
// earlier one if a flush takes it first - either way ahead of every later command.
StageSharedImageWait(fence, kSharedImageUseStages);
// A session that writes images (implicit sync by flush) may be about to overwrite what
// another session still samples: those reads go first.
if (m_sharedImageImplicitSync && !resource.sharedImageHeld) {
for (const int read : SI::DupPendingReadFences(*image)) StageSharedImageWait(read, kSharedImageUseStages);
}
const Uint32 family = static_cast<Uint32>(m_physicalDevice.queueFamilies.graphicsFamily);
VkImageMemoryBarrier barrier{VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER};
@@ -595,6 +600,72 @@
static_cast<Uint32>(releases.size()), releases.data());
}
Bool VulkanRenderer::PublishSharedImageAccesses() {
m_sharedImageImplicitSync = true;
if (m_sharedImageReads.Pending() == 0 && m_sharedImagesHeld.empty()) return true;
ReleaseHeldSharedImages();
if (m_sharedImageSyncFd && m_sharedImageSignal == VK_NULL_HANDLE)
m_sharedImageSignal = TakeSharedImageSemaphore(/*exportable=*/true);
m_sharedImageSignalSubmitted = VK_NULL_HANDLE;
if (!FlushPendingCommands()) {
MGLOG_E_ONCE("Magma: a flush's shared-image accesses could not be submitted");
m_sharedImageReads.PublishFrame(-1); // drops the references; nothing to order against
return false;
}
const VkSemaphore signal = std::exchange(m_sharedImageSignalSubmitted, VK_NULL_HANDLE);
int fence = -1;
if (signal == VK_NULL_HANDLE || !ExportSharedImageSignal(signal, fence)) {
// No fence came out of it: the submission is waited for and published as completed.
fence = -1;
if (!WaitForSubmitsUpTo(m_submitCounter, UINT64_MAX)) {
MGLOG_E_ONCE("Magma: a flush's shared-image accesses could not be waited for");
}
}
m_sharedImageReads.PublishFrameAsWrite(fence);
return true;
}
// THE NATIVE FENCE. A sync_file of everything the session submitted so far, for the client's
// EGL_ANDROID_native_fence_sync: the application hands the descriptor on (Chrome's GPU process,
// to the browser that commits the buffer), so it has to signal no earlier than the last of that
// work. With nothing recorded, an empty
// recording is submitted to carry the signal: the in-order queue runs it after every earlier
// submission, and it is tracked like any other (the semaphore's reuse waits for it).
Bool VulkanRenderer::ExportNativeFence(int* fence) {
*fence = -1;
if (m_device == VK_NULL_HANDLE || m_graphicsQueue == VK_NULL_HANDLE || m_frameContext.GetFrameCount() == 0)
return true; // nothing was ever submitted: nothing to fence
// A session that writes images ends its frame here, as at a flush; a compositor that only
// samples them keeps its reads for its present, which follows the fence's work anyway.
const Bool boundary = m_sharedImageImplicitSync;
if (boundary) ReleaseHeldSharedImages();
if (m_sharedImageSyncFd && m_sharedImageSignal == VK_NULL_HANDLE)
m_sharedImageSignal = TakeSharedImageSemaphore(/*exportable=*/true);
m_sharedImageSignalSubmitted = VK_NULL_HANDLE;
if (!HasPendingRecordedWork() && m_sharedImageSignal != VK_NULL_HANDLE)
m_frameContext.BeginCommandRecording();
const Bool submitted = HasPendingRecordedWork() && FlushPendingCommands();
if (HasPendingRecordedWork()) MGLOG_E_ONCE("Magma: a native fence's commands could not be submitted");
const VkSemaphore signal =
submitted ? std::exchange(m_sharedImageSignalSubmitted, VK_NULL_HANDLE) : VK_NULL_HANDLE;
int exported = -1;
if (signal == VK_NULL_HANDLE || !ExportSharedImageSignal(signal, exported)) exported = -1;
if (exported < 0) {
// No descriptor: the work is waited out, so the caller may report it completed.
if (!WaitForSubmitsUpTo(m_submitCounter, UINT64_MAX))
MGLOG_E_ONCE("Magma: a native fence's work could not be waited for");
}
if (boundary && m_sharedImageReads.Pending() != 0) {
int published = -1;
#if !defined(_WIN32)
if (exported >= 0) published = ::dup(exported);
#endif
m_sharedImageReads.PublishFrameAsWrite(published);
}
*fence = exported;
return true;
}
void VulkanRenderer::PublishSharedImageReads() {
const VkSemaphore signal = std::exchange(m_sharedImageSignalSubmitted, VK_NULL_HANDLE);
int fence = -1;
@@ -607,7 +678,11 @@
}
// No fence (no export on this device): the frame's reads go unpublished - the file
// comment says why that is the choice.
m_sharedImageReads.PublishFrame(fence);
// A session that writes images publishes every boundary as a write (PublishSharedImageAccesses).
if (m_sharedImageImplicitSync)
m_sharedImageReads.PublishFrameAsWrite(fence);
else
m_sharedImageReads.PublishFrame(fence);
}
void VulkanRenderer::AbandonSharedImageReads() {
+270 -35
View File
@@ -8,6 +8,7 @@
#include "EGLImpl.h"
#include "EGLPlatformExtensions.h"
#include "SharedImageFlushPolicy.h"
#include "WaylandWindow.h"
#include "../GetProcAddress.h"
#include <Init.h>
@@ -32,6 +33,8 @@
#include <MG_State/GLState/Core.h>
#include <optional>
#endif
#include <atomic>
#include <cstdlib>
#include <cstring>
#include <mutex>
#include <sstream>
@@ -45,6 +48,8 @@
namespace MobileGL::MG_Impl::EGLImpl {
namespace {
// SetDispatcherCurrentApiHook.
std::atomic<EGLenum (*)()> g_dispatcherCurrentApi{nullptr};
using EGLStateContext = MG_State::EGLState::EGLContext;
EGLStateContext* GetState() {
@@ -83,6 +88,8 @@ namespace MobileGL::MG_Impl::EGLImpl {
}
#if MOBILEGL_BUILD_DISAGGREGATED
using MG_Remote::Client::ClientSession;
// P14 S1 (docs/Disaggregated/design/11-state-ownership.md). THE CONTEXT BINDING, AND
// THE ONE PLACE IT IS EMITTED.
//
@@ -154,6 +161,82 @@ namespace MobileGL::MG_Impl::EGLImpl {
}
namespace {
// RECORDS WRITTEN FOR A CONTEXT THAT IS NOT THE CALLING THREAD'S. eglCreateContext builds
// the new context's GL state (its default objects are created there) and eglDestroyContext
// ends a context's objects, on whatever thread calls them - one with another context
// current, or none. Those records belong to the context being created or destroyed, so the
// stream is bound to it first; the next GL entry point binds the stream back to its own
// thread's context (GLStreamScope). The caller holds StreamMutex().
void StreamBindContextLocked(Uint64 token, Uint64 shareGroupToken) {
if (token == g_boundContextToken) return;
if (MG_Remote::Client::EmitBindContextRecord(token)) {
g_boundContextToken = token;
g_boundShareGroupToken = shareGroupToken;
}
}
// THE ONE WAY A CONTEXT ENDS on a split client, whether eglDestroyContext ended it at once
// or its deferred destroy completed when the last thread released it. `glState` is the
// context's GL state, whose last owner this is: dropping it ends the context's own objects
// (and its share group's, when it is the group's last context). They end under the
// context's own binding, the residual fill's object pins included (a pinned vertex array
// or program of this context would otherwise end inside some later thread's draw), and
// only then does the server drop the context - the order the records need, because the
// server files nothing under a context it no longer has. A context lost with an ended
// session goes in silence, as before.
void FinishContextDestroy(Uint64 token, Uint64 shareGroupToken, SharedPtr<MG_State::GLState::GLContext> glState,
Bool lost) {
if (token == 0 || lost || !StreamGateActive()) {
std::optional<ClientSession::ScopedWireMute> silence;
if (lost) silence.emplace();
glState.reset();
return;
}
StreamBindContextLocked(token, shareGroupToken);
// The pins live in the client's own residual block - its own memory only when the
// server is another process; in the one-process shape the apply thread reads that block
// too, and only a barriered apply's return may touch it (ClientSession::ReleaseFillPins).
if (ClientSession* session = ClientSession::Active();
session != nullptr && session->Started() && MG_Config::Transport != MG_Config::TransportMode::InProcess) {
session->WaitForApplyToCatchUp("eglDestroyContext");
session->ReleaseFillPins();
}
glState.reset();
// The server drops its binding to 0 when the bound context is destroyed
// (ServerSession::DestroyContext's compare-and-swap); the gate mirrors it so the next
// write re-binds.
if (g_boundContextToken == token) {
g_boundContextToken = 0;
g_boundShareGroupToken = 0;
}
const auto emitted = MG_Remote::Client::SendDestroyContextFrame(token);
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>(token));
}
}
} // namespace
void FinishReapedContexts(MG_State::EGLState::EGLContext* state) {
if (state == nullptr) return;
if (!StreamGateActive()) {
(void)state->TakeReapedContexts(); // dropping them ends their GL state
return;
}
for (auto& reaped : state->TakeReapedContexts()) {
const Bool lost = reaped.GLStateObject != nullptr &&
(reaped.GLStateObject->IsFromEndedWireSession() || ClientSession::SessionLatchedLost());
FinishContextDestroy(reaped.ClientContextToken, reaped.ShareGroupToken, Move(reaped.GLStateObject), lost);
}
}
namespace {
#else
// A monolith has no stream to bind: a context whose deferred destroy completed simply ends.
void FinishReapedContexts(MG_State::EGLState::EGLContext* state) {
if (state != nullptr) (void)state->TakeReapedContexts();
}
#endif
String CurrentThreadIdString() {
std::ostringstream stream;
@@ -609,7 +692,14 @@ namespace MobileGL::MG_Impl::EGLImpl {
}
#if MOBILEGL_BUILD_DISAGGREGATED
// A swap of a lost context's frame: EGL_CONTEXT_LOST (EGL 1.5 3.2), and nothing presented.
// A Wayland window is still committed, with no new buffer (WindowSurface::CommitPendingState):
// Qt asks for a frame callback before every swap and draws the window again only once it
// has fired, so a swap that never committed froze the window for good - a Plasma panel
// that hit the loss in its own swap never redrew, not even to rebuild its context.
if (ContextIsLost(state, state->GetCurrentContext())) {
#if MOBILEGL_WAYLAND_WINDOWS
if (auto it = WaylandSurfaces().find(draw); it != WaylandSurfaces().end()) it->second->CommitPendingState();
#endif
state->SetError(EGL_CONTEXT_LOST);
return EGL_FALSE;
}
@@ -637,10 +727,28 @@ 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() && !it->second->Present(damage, state->GetSwapInterval(dpy))) {
state->SetError(EGL_BAD_SURFACE);
return EGL_FALSE;
if (auto it = WaylandSurfaces().find(draw); it != WaylandSurfaces().end()) {
#if MOBILEGL_BUILD_DISAGGREGATED
// A loss that this very present runs into is reported here, as the one above: a
// frame of the lost device shown as if it were the window's would leave the toolkit
// with a transparent window it learns only afterwards it has to redraw.
const auto sessionLost = +[]() -> Bool {
auto* current = GetState();
return current != nullptr && ContextIsLost(current, current->GetCurrentContext());
};
#else
Bool (*const sessionLost)() = nullptr;
#endif
switch (it->second->Present(damage, state->GetSwapInterval(dpy), sessionLost)) {
case Wayland::WindowSurface::PresentResult::kPresented: break;
case Wayland::WindowSurface::PresentResult::kLost:
it->second->CommitPendingState();
state->SetError(EGL_CONTEXT_LOST);
return EGL_FALSE;
case Wayland::WindowSurface::PresentResult::kNotShown:
state->SetError(EGL_BAD_SURFACE);
return EGL_FALSE;
}
}
#endif
const Bool swapped = damage.IsFull() ? backendObject->SwapEGLBuffers(dpy, draw)
@@ -671,6 +779,12 @@ namespace MobileGL::MG_Impl::EGLImpl {
if (!state) {
return EGL_NO_CONTEXT;
}
// The API the context is for, as the dispatcher reports it (SetDispatcherCurrentApiHook):
// an ES context made without an eglBindAPI - or with one of the default - is an ES context.
if (const auto currentApi = g_dispatcherCurrentApi.load()) {
const EGLenum api = currentApi();
if (api == EGL_OPENGL_API || api == EGL_OPENGL_ES_API) state->SetBoundAPI(api);
}
#if MOBILEGL_BUILD_DISAGGREGATED
// AFTER A DEVICE LOSS THIS IS WHERE AN APPLICATION REBUILDS, so this is where a fresh
// session comes up (RecoverLostSession) - before the context's GL state is built, because
@@ -702,8 +816,13 @@ namespace MobileGL::MG_Impl::EGLImpl {
// The calling thread may still have a lost context current: what is built here is the
// fresh session's all the same.
const ClientSession::ScopedCurrentSessionWork currentSession;
// A split client builds the context's GL state only once the server has its token (below).
const Bool splitClient = MG_Config::Transport != MG_Config::TransportMode::Monolith &&
!MG_Remote::Client::RunsAsTheServerRole();
#else
constexpr Bool splitClient = false;
#endif
EGLContext context = state->CreateContext(dpy, config, shareCtx, attrib_list);
EGLContext context = state->CreateContext(dpy, config, shareCtx, attrib_list, splitClient);
if (context == EGL_NO_CONTEXT) {
return EGL_NO_CONTEXT;
}
@@ -743,7 +862,7 @@ namespace MobileGL::MG_Impl::EGLImpl {
replacedGroup = state->GetContextShareGroupToken(shareCtx);
shareCtx = ReplacementShareContext(state, dpy, replacedGroup);
}
context = state->CreateContext(dpy, config, shareCtx, attrib_list);
context = state->CreateContext(dpy, config, shareCtx, attrib_list, splitClient);
}
if (context == EGL_NO_CONTEXT) {
state->SetError(EGL_BAD_ALLOC);
@@ -758,6 +877,16 @@ namespace MobileGL::MG_Impl::EGLImpl {
state->SetError(EGL_BAD_ACCESS);
return EGL_NO_CONTEXT;
}
// NOW THE CONTEXT'S GL STATE, under its own binding. Building it creates the context's
// default objects (a texture per target, ...), and the records that create them belong
// to THIS context's share group on the server - not to whichever context the stream
// was last bound to by some other thread, which is where they landed when the state was
// built before the token crossed: a context in a share group of its own then drew with
// default objects its group never had.
if (emitted == MG_Remote::Client::ContextFrameEmit::Sent) {
StreamBindContextLocked(state->GetContextClientToken(context), state->GetContextShareGroupToken(context));
}
(void)state->BuildContextGLState(context);
}
#endif
return context;
@@ -817,6 +946,13 @@ namespace MobileGL::MG_Impl::EGLImpl {
if (!state) {
return EGL_FALSE;
}
// A release (explicit, or the implicit one of binding another context) may complete the
// deferred destroy of the context it releases; that destroy is finished on the way out,
// under the lock, whichever way this call returns.
struct FinishReapedOnExit {
EGLStateContext* State;
~FinishReapedOnExit() { FinishReapedContexts(State); }
} finishReaped{state};
const auto oldDisplay = state->GetCurrentDisplay();
const auto oldDraw = state->GetCurrentSurface(EGL_DRAW);
@@ -827,6 +963,9 @@ namespace MobileGL::MG_Impl::EGLImpl {
// 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);
// Read before the release too: a thread letting go of a context lost with an ended session
// says nothing to the fresh one (its binding never named that context).
const Bool oldContextLost = ContextIsLost(state, oldContext);
#endif
const String threadId = CurrentThreadIdString();
@@ -870,7 +1009,11 @@ 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);
{
std::optional<ClientSession::ScopedWireMute> silence;
if (oldContextLost) silence.emplace();
EmitContextBinding(state, EGL_NO_CONTEXT, oldContextToken);
}
#endif
return EGL_TRUE;
}
@@ -917,41 +1060,34 @@ namespace MobileGL::MG_Impl::EGLImpl {
return EGL_FALSE;
}
#if MOBILEGL_BUILD_DISAGGREGATED
// Under the operation lock, like every GL call: what ends here writes records.
const std::lock_guard<std::recursive_mutex> destroyLock(EGLOperationMutex());
// 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.
// AFTER the client's state machine has accepted the destroy, so one EGL refused 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);
const Uint64 shareGroupToken = state->GetContextShareGroupToken(ctx);
// A LOST CONTEXT IS DESTROYED IN SILENCE. Its objects die here, and a death that reached
// the wire would land on whichever session is current now - a fresh one after a recovery,
// which never created them. Under the operation lock, like every GL call.
const std::lock_guard<std::recursive_mutex> destroyLock(EGLOperationMutex());
// which never created them.
const Bool lost = ContextIsLost(state, ctx);
std::optional<ClientSession::ScopedWireMute> silence;
if (lost) silence.emplace();
#endif
if (!state->DestroyContext(dpy, ctx)) {
// The context's GL state, held across the book's drop so that its objects end in
// FinishContextDestroy, under the context's own binding, rather than inside EGLState.
SharedPtr<MG_State::GLState::GLContext> glState = state->GetContextGLState(ctx);
Bool deferred = false;
if (!state->DestroyContext(dpy, ctx, &deferred)) {
return EGL_FALSE;
}
#if MOBILEGL_BUILD_DISAGGREGATED
ForgetReplacementShareContext(ctx);
if (contextToken != 0 && !lost && MG_Config::Transport != MG_Config::TransportMode::Monolith &&
!MG_Remote::Client::RunsAsTheServerRole()) {
const std::lock_guard<std::recursive_mutex> streamLock(EGLOperationMutex());
// The server drops its binding to 0 when the current context is destroyed
// (ServerSession::DestroyContext's compare-and-swap); the gate mirrors it so the next
// write re-binds.
if (g_boundContextToken == contextToken) {
g_boundContextToken = 0;
g_boundShareGroupToken = 0;
}
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));
}
// CURRENT TO A THREAD (this one or another): EGL destroys it once it is released, and that
// release finishes it (FinishReapedContexts). Until then its thread keeps drawing in it.
if (deferred) return EGL_TRUE;
FinishContextDestroy(contextToken, shareGroupToken, Move(glState), lost);
#else
if (!state->DestroyContext(dpy, ctx)) {
return EGL_FALSE;
}
#endif
return EGL_TRUE;
@@ -1016,11 +1152,18 @@ namespace MobileGL::MG_Impl::EGLImpl {
// Always succeeds (EGL 1.4 §3.11): after the last eglTerminate tore MobileGL down there is
// simply nothing of this thread's left to release.
if (!MG_State::pEGLContext) return EGL_TRUE;
const std::lock_guard<std::recursive_mutex> operationLock(EGLOperationMutex());
auto* state = GetState();
if (auto* backendObject = MG_Backend::pActiveBackendObject.get()) {
(void)backendObject->MakeEGLCurrent(EGL_NO_DISPLAY, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
}
state->ReleaseThread();
#if MOBILEGL_BUILD_DISAGGREGATED
// The release edge, as eglMakeCurrent's release sends it: this thread has no context now,
// and the binding must not keep naming the one it had.
EmitContextBinding(state, EGL_NO_CONTEXT, 0);
#endif
FinishReapedContexts(state);
return EGL_TRUE;
}
@@ -1386,9 +1529,49 @@ namespace MobileGL::MG_Impl::EGLImpl {
if (!state) {
return EGL_NO_SYNC;
}
#if MOBILEGL_BUILD_DISAGGREGATED
// EGL_ANDROID_native_fence_sync's fence command: a native fence with no descriptor of the
// application's. The server publishes the current context's shared-image accesses - its
// writes into dma-bufs become visible to the compositor's session, as at a glFlush - and
// hands back a sync_file of the work, which the application passes on with the buffer
// (Chrome's GPU process creates one per frame instead of flushing, when the compositor's
// kernel takes dma-buf fences). Answered through the round trip, so it is flushed too.
if (type == EGL_SYNC_NATIVE_FENCE_ANDROID && SharedImagesAvailable()) {
Bool hasFd = false;
for (const EGLAttrib* at = attrib_list; at != nullptr && at[0] != EGL_NONE; at += 2) {
if (at[0] == EGL_SYNC_NATIVE_FENCE_FD_ANDROID && at[1] != EGL_NO_NATIVE_FENCE_FD_ANDROID) hasFd = true;
}
if (!hasFd) {
if (GetCurrentContext() == EGL_NO_CONTEXT) {
state->SetError(EGL_BAD_MATCH);
return EGL_NO_SYNC;
}
int fence = -1;
{
const GLStreamScope stream;
MG_Pipe::MGPipeClientDrainTextureUploads();
auto* backendObject = MG_Backend::pActiveBackendObject.get();
if (backendObject == nullptr || !backendObject->CreateNativeFence(&fence)) {
MGLOG_E_ONCE("eglCreateSync: the server did not answer a native fence; none is created");
state->SetError(EGL_BAD_ALLOC);
return EGL_NO_SYNC;
}
}
return state->CreateNativeFenceSync(dpy, fence, EGL_SYNC_PRIOR_COMMANDS_COMPLETE);
}
}
#endif
return state->CreateSync(dpy, type, attrib_list);
}
EGLint DupNativeFenceFD(EGLDisplay dpy, EGLSync sync) {
auto* state = GetState();
if (!state) {
return EGL_NO_NATIVE_FENCE_FD_ANDROID;
}
return state->DupNativeFenceFD(dpy, sync);
}
EGLBoolean DestroySync(EGLDisplay dpy, EGLSync sync) {
auto* state = GetState();
if (!state) {
@@ -1413,6 +1596,8 @@ namespace MobileGL::MG_Impl::EGLImpl {
return state->GetSyncAttrib(dpy, sync, attribute, value) ? EGL_TRUE : EGL_FALSE;
}
void SetDispatcherCurrentApiHook(EGLenum (*hook)()) { g_dispatcherCurrentApi.store(hook); }
Bool SharedImagesAvailable() {
#if MOBILEGL_BUILD_DISAGGREGATED
// A split client's backend is the remote one, which forwards the shared-image verbs to
@@ -1433,6 +1618,38 @@ namespace MobileGL::MG_Impl::EGLImpl {
return true;
}
namespace {
std::atomic<Bool>& SharedImageBoundToTexture() {
static std::atomic<Bool> bound{false};
return bound;
}
} // namespace
void NoteSharedImageBoundToTexture() { SharedImageBoundToTexture().store(true, std::memory_order_relaxed); }
void FlushSharedImageAccesses() {
if (!SharedImageBoundToTexture().load(std::memory_order_relaxed) &&
std::getenv("MOBILEGL_SHARED_IMAGE_FLUSH_SYNC") == nullptr)
return;
#if MOBILEGL_BUILD_DISAGGREGATED
static const Bool ownsServerWindow = MG_Config::ServerOwnedWindowSurfaces();
#else
constexpr Bool ownsServerWindow = false;
#endif
if (!FlushPublishesSharedImageAccesses(SharedImagesAvailable(), SharedImageBoundToTexture().load(),
ownsServerWindow, std::getenv("MOBILEGL_SHARED_IMAGE_FLUSH_SYNC")))
return;
auto* backendObject = MG_Backend::pActiveBackendObject.get();
#if MOBILEGL_BUILD_DISAGGREGATED
// Uploads still waiting for a validate point go first: they are part of what is published.
MG_Pipe::MGPipeClientDrainTextureUploads();
#endif
if (backendObject != nullptr && !backendObject->FlushSharedImageAccesses()) {
MGLOG_E_ONCE("glFlush: this session's shared-image accesses could not be published; another session may "
"read them early");
}
}
EGLImage CreateImage(EGLDisplay dpy, EGLContext ctx, EGLenum target, EGLClientBuffer buffer,
const EGLAttrib* attrib_list) {
auto* state = GetState();
@@ -1466,8 +1683,16 @@ namespace MobileGL::MG_Impl::EGLImpl {
state->SetError(EGL_BAD_MATCH);
return EGL_NO_IMAGE;
}
const EGLImage image = state->CreateSharedImage(
dpy, {.Id = sharedImageId, .Width = request.Width, .Height = request.Height, .Fourcc = request.Fourcc});
#if MOBILEGL_BUILD_DISAGGREGATED
const Uint64 wireEpoch = MG_State::CurrentWireEpoch();
#else
const Uint64 wireEpoch = 0;
#endif
const EGLImage image = state->CreateSharedImage(dpy, {.Id = sharedImageId,
.Width = request.Width,
.Height = request.Height,
.Fourcc = request.Fourcc,
.WireEpoch = wireEpoch});
if (image == EGL_NO_IMAGE) (void)backendObject->ReleaseSharedImage(sharedImageId);
return image;
}
@@ -1477,10 +1702,20 @@ namespace MobileGL::MG_Impl::EGLImpl {
if (!state) {
return EGL_FALSE;
}
// The session the image's reference was taken on: a reference of a session that has ended
// died with it, and the same image imported again on the fresh session has the same id - a
// release of the old one sent there would drop the new one's reference.
MG_State::EGLState::EGLContext::SharedImageInfo shared;
const Bool sharedImage = state->GetSharedImage(image, &shared);
Uint64 sharedImageId = 0;
if (!state->DestroyImage(dpy, image, &sharedImageId)) {
return EGL_FALSE;
}
#if MOBILEGL_BUILD_DISAGGREGATED
if (sharedImage && shared.WireEpoch != MG_State::CurrentWireEpoch()) sharedImageId = 0;
#else
(void)sharedImage;
#endif
// A texture the image was bound to keeps its own reference on the server (EGLImage
// siblings outlive the image), so only this handle's goes.
if (sharedImageId != 0) {
+13
View File
@@ -56,6 +56,8 @@ namespace MobileGL::MG_Impl::EGLImpl {
EGLBoolean DestroySync(EGLDisplay dpy, EGLSync sync);
EGLint ClientWaitSync(EGLDisplay dpy, EGLSync sync, EGLint flags, EGLTime timeout);
EGLBoolean GetSyncAttrib(EGLDisplay dpy, EGLSync sync, EGLint attribute, EGLAttrib* value);
// EGL_ANDROID_native_fence_sync: a copy of a native fence sync's sync_file.
EGLint DupNativeFenceFD(EGLDisplay dpy, EGLSync sync);
EGLImage CreateImage(EGLDisplay dpy, EGLContext ctx, EGLenum target, EGLClientBuffer buffer,
const EGLAttrib* attrib_list);
EGLBoolean DestroyImage(EGLDisplay dpy, EGLImage image);
@@ -66,8 +68,19 @@ namespace MobileGL::MG_Impl::EGLImpl {
// a split client's does, a monolith's does not. Decides the dma-buf EGL extensions, the
// Wayland linux-dmabuf presentation and GL_OES_EGL_image.
Bool SharedImagesAvailable();
// Under a dispatching libEGL the dispatcher, not this library, owns eglBindAPI's state: it does
// not forward a bind of the API it already reports (EGL_OPENGL_ES_API, EGL's default), so a
// context would otherwise be created for whatever this library assumed. The glvnd vendor
// installs the dispatcher's own answer here; eglCreateContext asks it.
void SetDispatcherCurrentApiHook(EGLenum (*hook)());
// The shared image an EGLImage names (EGL_LINUX_DMA_BUF_EXT), for glEGLImageTargetTexture2DOES.
Bool LookupSharedImage(EGLImage image, Uint64* id, EGLint* width, EGLint* height);
// glEGLImageTargetTexture2DOES bound a shared image to a texture: from now on glFlush/glFinish
// may be shared-image boundaries (SharedImageFlushPolicy.h).
void NoteSharedImageBoundToTexture();
// From glFlush/glFinish, under the stream lock: publish this session's shared-image accesses
// when the policy says a flush is a boundary in this process. Cheap when it is not.
void FlushSharedImageAccesses();
EGLDisplay GetPlatformDisplay(EGLenum platform, void* native_display, const EGLAttrib* attrib_list);
EGLSurface CreatePlatformWindowSurface(EGLDisplay dpy, EGLConfig config, void* native_window,
const EGLAttrib* attrib_list);
@@ -18,9 +18,14 @@ namespace MobileGL::MG_Impl::EGLImpl {
inline constexpr const char* kPlatformExtensionString =
"EGL_EXT_client_extensions EGL_EXT_platform_base EGL_KHR_platform_base "
"EGL_MESA_platform_surfaceless" MOBILEGL_PLATFORM_WAYLAND_EXTENSIONS;
// EGL_EXT_create_context_robustness: a context may ask for EGL_LOSE_CONTEXT_ON_RESET, and a
// split client's contexts are lost exactly when their server session is (a device loss on the
// server ends that session). An application learns of it through glGetGraphicsResetStatus only
// if it could ask for it here: ANGLE's GL-on-EGL backend mirrors this extension onto its own
// display, and Chrome checks that display for it before it ever queries the reset status.
inline constexpr const char* kDisplayExtensionString =
"EGL_KHR_create_context EGL_KHR_surfaceless_context EGL_KHR_no_config_context EGL_EXT_platform_base "
"EGL_KHR_platform_base "
"EGL_EXT_create_context_robustness EGL_KHR_platform_base "
"EGL_MESA_platform_surfaceless" MOBILEGL_PLATFORM_WAYLAND_EXTENSIONS;
// The display list again, with the dma-buf import a backend with shared images has (a split
// client: the server allocates the images and names the descriptors that come back). A
@@ -28,11 +33,15 @@ namespace MobileGL::MG_Impl::EGLImpl {
// same server answers the buffer age of its surfaces and takes swap damage to its presents.
inline constexpr const char* kDisplayExtensionStringWithSharedImages =
"EGL_KHR_create_context EGL_KHR_surfaceless_context EGL_KHR_no_config_context EGL_EXT_platform_base "
"EGL_KHR_platform_base "
"EGL_EXT_create_context_robustness EGL_KHR_platform_base "
"EGL_MESA_platform_surfaceless" MOBILEGL_PLATFORM_WAYLAND_EXTENSIONS
" EGL_KHR_image_base EGL_EXT_image_dma_buf_import EGL_EXT_image_dma_buf_import_modifiers"
" EGL_EXT_buffer_age EGL_KHR_partial_update EGL_KHR_swap_buffers_with_damage"
" EGL_EXT_swap_buffers_with_damage";
" EGL_EXT_swap_buffers_with_damage"
// Native fences come from the server's sessions (a sync_file of a session's submitted work),
// which is also what publishes a context's writes into dma-bufs to the compositor without a
// swap: Chrome's GPU process ends each frame with one rather than a flush.
" EGL_KHR_fence_sync EGL_KHR_wait_sync EGL_ANDROID_native_fence_sync";
inline constexpr const char* kClientExtensionString =
"EGL_EXT_client_extensions EGL_KHR_create_context EGL_EXT_platform_base "
"EGL_KHR_platform_base EGL_MESA_platform_surfaceless" MOBILEGL_PLATFORM_WAYLAND_EXTENSIONS;
@@ -287,8 +287,10 @@ MOBILEGL_EGL_API EGLBoolean eglDestroySync(EGLDisplay dpy, EGLSync sync) {
return MobileGL::MG_Impl::EGLImpl::DestroySync(dpy, sync);
}
// The waits take no stream lock: they read EGL state only (its own lock), never the stream, and a
// native fence's wait blocks for as long as the fenced work runs - with the lock held, every other
// thread's GL call would wait with it.
MOBILEGL_EGL_API EGLint eglClientWaitSync(EGLDisplay dpy, EGLSync sync, EGLint flags, EGLTime timeout) {
const MobileGL::MG_Impl::EGLImpl::StreamLockScope mglStreamLock;
MGLOG_D("eglClientWaitSync(dpy=%p, sync=%p, flags=%d, timeout=%llu)", dpy, sync, flags,
static_cast<unsigned long long>(timeout));
return MobileGL::MG_Impl::EGLImpl::ClientWaitSync(dpy, sync, flags, timeout);
@@ -300,6 +302,65 @@ MOBILEGL_EGL_API EGLBoolean eglGetSyncAttrib(EGLDisplay dpy, EGLSync sync, EGLin
return MobileGL::MG_Impl::EGLImpl::GetSyncAttrib(dpy, sync, attribute, value);
}
// EGL_KHR_fence_sync / EGL_KHR_wait_sync / EGL_ANDROID_native_fence_sync's spellings, which
// ANGLE's GLES-on-EGL backend loads by name (and only through them offers fences to Chrome): the
// same objects as EGL 1.5's, with EGLint attribute lists.
namespace {
// EGL_KHR_fence_sync's attribute list widened to EGL 1.5's; at most 16 pairs, as no sync type
// takes more than two attributes.
bool WidenSyncAttribs(const EGLint* in, EGLAttrib* out, int capacity) {
int n = 0;
for (const EGLint* at = in; at != nullptr && at[0] != EGL_NONE; at += 2) {
if (n + 3 > capacity) return false;
out[n++] = static_cast<EGLAttrib>(at[0]);
out[n++] = static_cast<EGLAttrib>(at[1]);
}
out[n] = EGL_NONE;
return true;
}
} // namespace
MOBILEGL_EGL_API EGLSyncKHR eglCreateSyncKHR(EGLDisplay dpy, EGLenum type, const EGLint* attrib_list) {
const MobileGL::MG_Impl::EGLImpl::StreamLockScope mglStreamLock;
MGLOG_D("eglCreateSyncKHR(dpy=%p, type=%u, attrib_list=%p)", dpy, type, attrib_list);
EGLAttrib attribs[33];
if (!WidenSyncAttribs(attrib_list, attribs, 33)) return EGL_NO_SYNC_KHR;
return MobileGL::MG_Impl::EGLImpl::CreateSync(dpy, type, attribs);
}
MOBILEGL_EGL_API EGLBoolean eglDestroySyncKHR(EGLDisplay dpy, EGLSyncKHR sync) {
const MobileGL::MG_Impl::EGLImpl::StreamLockScope mglStreamLock;
MGLOG_D("eglDestroySyncKHR(dpy=%p, sync=%p)", dpy, sync);
return MobileGL::MG_Impl::EGLImpl::DestroySync(dpy, sync);
}
MOBILEGL_EGL_API EGLint eglClientWaitSyncKHR(EGLDisplay dpy, EGLSyncKHR sync, EGLint flags, EGLTimeKHR timeout) {
MGLOG_D("eglClientWaitSyncKHR(dpy=%p, sync=%p, flags=%d, timeout=%llu)", dpy, sync, flags,
static_cast<unsigned long long>(timeout));
return MobileGL::MG_Impl::EGLImpl::ClientWaitSync(dpy, sync, flags, timeout);
}
MOBILEGL_EGL_API EGLBoolean eglGetSyncAttribKHR(EGLDisplay dpy, EGLSyncKHR sync, EGLint attribute, EGLint* value) {
const MobileGL::MG_Impl::EGLImpl::StreamLockScope mglStreamLock;
MGLOG_D("eglGetSyncAttribKHR(dpy=%p, sync=%p, attribute=%d, value=%p)", dpy, sync, attribute, value);
if (value == nullptr) return MobileGL::MG_Impl::EGLImpl::GetSyncAttrib(dpy, sync, attribute, nullptr);
EGLAttrib wide = 0;
const EGLBoolean ok = MobileGL::MG_Impl::EGLImpl::GetSyncAttrib(dpy, sync, attribute, &wide);
if (ok == EGL_TRUE) *value = static_cast<EGLint>(wide);
return ok;
}
MOBILEGL_EGL_API EGLint eglWaitSyncKHR(EGLDisplay dpy, EGLSyncKHR sync, EGLint flags) {
MGLOG_D("eglWaitSyncKHR(dpy=%p, sync=%p, flags=%d)", dpy, sync, flags);
return MobileGL::MG_Impl::EGLImpl::WaitSync(dpy, sync, flags) == EGL_TRUE ? EGL_TRUE : EGL_FALSE;
}
MOBILEGL_EGL_API EGLint eglDupNativeFenceFDANDROID(EGLDisplay dpy, EGLSyncKHR sync) {
const MobileGL::MG_Impl::EGLImpl::StreamLockScope mglStreamLock;
MGLOG_D("eglDupNativeFenceFDANDROID(dpy=%p, sync=%p)", dpy, sync);
return MobileGL::MG_Impl::EGLImpl::DupNativeFenceFD(dpy, sync);
}
MOBILEGL_EGL_API EGLImage eglCreateImage(EGLDisplay dpy, EGLContext ctx, EGLenum target, EGLClientBuffer buffer,
const EGLAttrib* attrib_list) {
const MobileGL::MG_Impl::EGLImpl::StreamLockScope mglStreamLock;
@@ -384,8 +445,8 @@ MOBILEGL_EGL_API EGLSurface eglCreatePlatformPixmapSurface(EGLDisplay dpy, EGLCo
return MobileGL::MG_Impl::EGLImpl::CreatePlatformPixmapSurface(dpy, config, native_pixmap, attrib_list);
}
// No stream lock, like eglClientWaitSync's: a native fence's server wait blocks the calling thread.
MOBILEGL_EGL_API EGLBoolean eglWaitSync(EGLDisplay dpy, EGLSync sync, EGLint flags) {
const MobileGL::MG_Impl::EGLImpl::StreamLockScope mglStreamLock;
MGLOG_D("eglWaitSync(dpy=%p, sync=%p, flags=%d)", dpy, sync, flags);
return MobileGL::MG_Impl::EGLImpl::WaitSync(dpy, sync, flags);
}
@@ -44,6 +44,12 @@ extern "C" EGLBoolean eglSwapBuffersWithDamageKHR(EGLDisplay dpy, EGLSurface dra
extern "C" EGLBoolean eglSwapBuffersWithDamageEXT(EGLDisplay dpy, EGLSurface draw, const EGLint* rects,
EGLint n_rects);
extern "C" EGLBoolean eglSetDamageRegionKHR(EGLDisplay dpy, EGLSurface surface, 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 eglGetSyncAttribKHR(EGLDisplay dpy, EGLSyncKHR sync, EGLint attribute, EGLint* value);
extern "C" EGLint eglWaitSyncKHR(EGLDisplay dpy, EGLSyncKHR sync, EGLint flags);
extern "C" EGLint eglDupNativeFenceFDANDROID(EGLDisplay dpy, EGLSyncKHR sync);
extern "C" EGLBoolean eglQueryDmaBufFormatsEXT(EGLDisplay dpy, EGLint max_formats, EGLint* formats,
EGLint* num_formats);
extern "C" EGLBoolean eglQueryDmaBufModifiersEXT(EGLDisplay dpy, EGLint format, EGLint max_modifiers,
@@ -264,6 +270,12 @@ namespace {
{"eglClientWaitSync", reinterpret_cast<void*>(eglClientWaitSync)},
{"eglGetSyncAttrib", reinterpret_cast<void*>(eglGetSyncAttrib)},
{"eglWaitSync", reinterpret_cast<void*>(eglWaitSync)},
{"eglCreateSyncKHR", reinterpret_cast<void*>(eglCreateSyncKHR)},
{"eglDestroySyncKHR", reinterpret_cast<void*>(eglDestroySyncKHR)},
{"eglClientWaitSyncKHR", reinterpret_cast<void*>(eglClientWaitSyncKHR)},
{"eglGetSyncAttribKHR", reinterpret_cast<void*>(eglGetSyncAttribKHR)},
{"eglWaitSyncKHR", reinterpret_cast<void*>(eglWaitSyncKHR)},
{"eglDupNativeFenceFDANDROID", reinterpret_cast<void*>(eglDupNativeFenceFDANDROID)},
{"eglCreateImage", reinterpret_cast<void*>(eglCreateImage)},
{"eglDestroyImage", reinterpret_cast<void*>(eglDestroyImage)},
{"eglCreateImageKHR", reinterpret_cast<void*>(eglCreateImageKHR)},
@@ -352,6 +364,12 @@ extern "C" MOBILEGL_EGL_API EGLBoolean __egl_Main(uint32_t version, const __EGLa
return EGL_FALSE;
}
g_eglExports = exports;
if (exports->getCurrentApi != nullptr) {
MobileGL::MG_Impl::EGLImpl::SetDispatcherCurrentApiHook([]() -> EGLenum {
return g_eglExports != nullptr && g_eglExports->getCurrentApi != nullptr ? g_eglExports->getCurrentApi()
: EGL_NONE;
});
}
imports->getPlatformDisplay = VendorGetPlatformDisplay;
imports->getSupportsAPI = VendorGetSupportsAPI;
@@ -0,0 +1,42 @@
// MobileGL - MobileGL/MG_Impl/EGLImpl/SharedImageFlushPolicy.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
// WHEN glFlush IS A SHARED-IMAGE BOUNDARY (docs/Disaggregated/notes/anland/plan-x11-gpu.md).
//
// A dma-buf producer that renders into its buffers and hands them on after a glFlush (an X
// server's glamor committing a window pixmap) relies on implicit sync: whoever samples the buffer
// next is ordered after the flushed work by the kernel. MobileGL's images are ordered by its server
// instead, and the server learns of a write at a boundary - a swap, a present, or this flush. So a
// flush becomes a round trip that publishes the session's accesses, but only in a process for which
// that can matter: it has bound a shared image to a texture, it does not own the server's window
// (the compositor samples client buffers and ends its frames at its swaps), and nobody turned it
// off. MOBILEGL_SHARED_IMAGE_FLUSH_SYNC=1 forces it on (still only with shared images), =0 off.
//
// Header-only and pure: a host test pins the table.
#include <Includes.h>
#include <cstring>
namespace MobileGL::MG_Impl::EGLImpl {
inline Bool FlushPublishesSharedImageAccesses(Bool sharedImagesAvailable, Bool boundSharedImageToTexture,
Bool ownsServerWindow, const char* overrideValue) {
if (!sharedImagesAvailable) return false;
if (overrideValue != nullptr && overrideValue[0] != '\0') {
if (std::strcmp(overrideValue, "0") == 0 || std::strcmp(overrideValue, "off") == 0 ||
std::strcmp(overrideValue, "false") == 0)
return false;
if (std::strcmp(overrideValue, "1") == 0 || std::strcmp(overrideValue, "on") == 0 ||
std::strcmp(overrideValue, "true") == 0)
return true;
}
return boundSharedImageToTexture && !ownsServerWindow;
}
} // namespace MobileGL::MG_Impl::EGLImpl
+20 -5
View File
@@ -822,9 +822,19 @@ namespace MobileGL::MG_Impl::EGLImpl::Wayland {
impl.useDmabuf = impl.dmabufWanted && impl.dmabuf != nullptr;
}
Bool WindowSurface::Present(const MG_Util::Damage::Region& damage, Int swapInterval) {
void WindowSurface::CommitPendingState() {
Impl& impl = *m_impl;
if (impl.window == nullptr) return false;
if (impl.window == nullptr || impl.window->surface == nullptr) return;
const Api& api = WaylandApi();
wl_proxy* surface = impl.window->surface;
api.marshalFlags(surface, kSurfaceCommit, nullptr, api.getVersion(surface), 0);
api.flush(impl.display);
}
WindowSurface::PresentResult WindowSurface::Present(const MG_Util::Damage::Region& damage, Int swapInterval,
Bool (*sessionLost)()) {
Impl& impl = *m_impl;
if (impl.window == nullptr) return PresentResult::kNotShown;
if (swapInterval != impl.loggedInterval) {
MGLOG_I("Wayland: window surface %dx%d swaps with interval %d (%s)", impl.width, impl.height,
static_cast<int>(swapInterval),
@@ -846,9 +856,12 @@ namespace MobileGL::MG_Impl::EGLImpl::Wayland {
if (backendObject->PresentToSharedImage(buffer->imageId, copy)) {
impl.Commit(buffer->buffer, damage);
buffer->busy = true;
return true;
return PresentResult::kPresented;
}
}
// The image went with a lost server: the window keeps its shared images (a fresh
// session replaces them, OnSessionReplaced) and shows no frame of the lost device.
if (sessionLost != nullptr && sessionLost()) return PresentResult::kLost;
MGLOG_E_ONCE("Wayland: a frame could not be presented through a linux-dmabuf shared image; the window "
"falls back to wl_shm");
impl.FallBackToShm();
@@ -857,15 +870,17 @@ namespace MobileGL::MG_Impl::EGLImpl::Wayland {
ShmBuffer* buffer = impl.NextFree();
if (buffer == nullptr) {
MGLOG_E_ONCE("Wayland: no wl_shm buffer could be taken for the frame; it is not shown");
return false;
return PresentResult::kNotShown;
}
// GL's rows run bottom-up and RGBA; a wl_shm buffer's run top-down and B, G, R, A.
ReadBackFrameBGRA(impl.width, impl.height, impl.scratch, static_cast<Uint8*>(buffer->map),
static_cast<SizeT>(buffer->stride));
// A read-back the device was lost under answered zeros: the buffer stays free.
if (sessionLost != nullptr && sessionLost()) return PresentResult::kLost;
impl.Commit(buffer->buffer, MG_Util::Damage::Region::Full());
buffer->busy = true;
return true;
return PresentResult::kPresented;
}
} // namespace MobileGL::MG_Impl::EGLImpl::Wayland
+15 -3
View File
@@ -75,8 +75,8 @@ namespace MobileGL::MG_Impl::EGLImpl::Wayland {
// Puts the current context's default-framebuffer frame on the window: copied into a
// shared image (or read back into a wl_shm buffer, the application's read-framebuffer and
// pack state put back exactly as they were), then attach, damage, commit. A shared-image
// present that fails moves the window to wl_shm for good. False (logged) when the frame
// did not reach the window; the swap itself goes on regardless.
// present that fails moves the window to wl_shm for good. kNotShown (logged) when the
// frame did not reach the window; the swap itself goes on regardless.
//
// `damage` (GL window coordinates, clipped to the window; Full = all of it) is what the
// frame changed. A shared image is copied only where it differs from the frame - the
@@ -85,13 +85,25 @@ namespace MobileGL::MG_Impl::EGLImpl::Wayland {
//
// `swapInterval` above 0 paces the swaps by the compositor's frame callbacks: this waits
// for the previous frame's before taking a buffer (FrameThrottle.h).
Bool Present(const MG_Util::Damage::Region& damage, Int swapInterval);
//
// `sessionLost` (may be null) says whether the device was lost under the frame. A frame
// that failed - or was read back - on a lost device is nothing but zeros: kLost, with no
// buffer attached and the window left where it was, so the caller reports the loss at
// this swap instead of showing a transparent window that the toolkit never redraws.
enum class PresentResult { kPresented, kNotShown, kLost };
PresentResult Present(const MG_Util::Damage::Region& damage, Int swapInterval, Bool (*sessionLost)());
// wl_egl_window_resize's effect, taken: true (with the new size) when the application gave
// its wl_egl_window a size this presentation is not at yet. The presentation adopts it -
// its next buffer is that size - and the caller resizes the drawable behind it.
Bool TakeResize(EGLint* width, EGLint* height);
// A swap that presents nothing (its context was lost) still commits the application's
// wl_surface, with no new buffer: the frame callback a toolkit asked for just before the
// swap is surface state that only a commit applies, and a toolkit that waits for it before
// drawing again would never draw again - not even to find out that it has to rebuild.
void CommitPendingState();
// The server session that allocated this window's shared images was lost and a fresh one
// replaced it: the images went with their server. Their wl_buffers are destroyed here,
// nothing is released (the fresh server never issued those ids), and the window goes
@@ -123,6 +123,8 @@ MOBILEGL_GL_API void glFinish() {
MGLOG_D("Implementing function: %s(...)", __FUNCTION__);
const MobileGL::MG_Impl::EGLImpl::GLStreamScope mglStreamScope;
#if MOBILEGL_BUILD_DISAGGREGATED
// A shared-image producer's boundary first (implicit sync; EGLImpl/SharedImageFlushPolicy.h).
MobileGL::MG_Impl::EGLImpl::FlushSharedImageAccesses();
MobileGL::MG_Pipe::MGPipeClientFinish();
#endif
}
@@ -130,6 +132,7 @@ MOBILEGL_GL_API void glFlush() {
MGLOG_D("Implementing function: %s(...)", __FUNCTION__);
const MobileGL::MG_Impl::EGLImpl::GLStreamScope mglStreamScope;
#if MOBILEGL_BUILD_DISAGGREGATED
MobileGL::MG_Impl::EGLImpl::FlushSharedImageAccesses();
MobileGL::MG_Pipe::MGPipeClientFlush();
#endif
}
@@ -432,9 +435,9 @@ DECLARE_GL_FUNCTION_HEAD(void, FramebufferTexture, GLenum target, GLenum attachm
DECLARE_GL_FUNCTION_STUB_HEAD(void, PrimitiveBoundingBox, GLfloat minX, GLfloat minY, GLfloat minZ, GLfloat minW, GLfloat maxX, GLfloat maxY, GLfloat maxZ, GLfloat maxW) DECLARE_GL_FUNCTION_STUB_END_NO_RETURN(void, PrimitiveBoundingBox, minX, minY, minZ, minW, maxX, maxY, maxZ, maxW)
DECLARE_GL_FUNCTION_HEAD(GLenum, GetGraphicsResetStatus) DECLARE_GL_FUNCTION_END(GLenum, GetGraphicsResetStatus)
DECLARE_GL_FUNCTION_HEAD(void, ReadnPixels, GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLsizei bufSize, void* data) DECLARE_GL_FUNCTION_END_NO_RETURN(void, ReadnPixels, x, y, width, height, format, type, bufSize, data)
DECLARE_GL_FUNCTION_STUB_HEAD(void, GetnUniformfv, GLuint program, GLint location, GLsizei bufSize, GLfloat* params) DECLARE_GL_FUNCTION_STUB_END_NO_RETURN(void, GetnUniformfv, program, location, bufSize, params)
DECLARE_GL_FUNCTION_STUB_HEAD(void, GetnUniformiv, GLuint program, GLint location, GLsizei bufSize, GLint* params) DECLARE_GL_FUNCTION_STUB_END_NO_RETURN(void, GetnUniformiv, program, location, bufSize, params)
DECLARE_GL_FUNCTION_STUB_HEAD(void, GetnUniformuiv, GLuint program, GLint location, GLsizei bufSize, GLuint* params) DECLARE_GL_FUNCTION_STUB_END_NO_RETURN(void, GetnUniformuiv, program, location, bufSize, params)
DECLARE_GL_FUNCTION_HEAD(void, GetnUniformfv, GLuint program, GLint location, GLsizei bufSize, GLfloat* params) DECLARE_GL_FUNCTION_END_NO_RETURN(void, GetnUniformfv, program, location, bufSize, params)
DECLARE_GL_FUNCTION_HEAD(void, GetnUniformiv, GLuint program, GLint location, GLsizei bufSize, GLint* params) DECLARE_GL_FUNCTION_END_NO_RETURN(void, GetnUniformiv, program, location, bufSize, params)
DECLARE_GL_FUNCTION_HEAD(void, GetnUniformuiv, GLuint program, GLint location, GLsizei bufSize, GLuint* params) DECLARE_GL_FUNCTION_END_NO_RETURN(void, GetnUniformuiv, program, location, bufSize, params)
DECLARE_GL_FUNCTION_HEAD(void, MinSampleShading, GLfloat value) DECLARE_GL_FUNCTION_END_NO_RETURN(void, MinSampleShading, value)
DECLARE_GL_FUNCTION_HEAD(void, PatchParameteri, GLenum pname, GLint value) DECLARE_GL_FUNCTION_END_NO_RETURN(void, PatchParameteri, pname, value)
DECLARE_GL_FUNCTION_HEAD(void, TexParameterIiv, GLenum target, GLenum pname, const GLint* params) DECLARE_GL_FUNCTION_END_NO_RETURN(void, TexParameterIiv, target, pname, params)
@@ -1118,7 +1121,7 @@ DECLARE_GL_FUNCTION_HEAD(void, GetTextureSubImage, GLuint texture, GLint level,
DECLARE_GL_FUNCTION_STUB_HEAD(void, GetCompressedTextureSubImage, GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLsizei bufSize, void* pixels) DECLARE_GL_FUNCTION_STUB_END_NO_RETURN(void, GetCompressedTextureSubImage, texture, level, xoffset, yoffset, zoffset, width, height, depth, bufSize, pixels)
DECLARE_GL_FUNCTION_STUB_HEAD(void, GetnCompressedTexImage, GLenum target, GLint lod, GLsizei bufSize, void* pixels) DECLARE_GL_FUNCTION_STUB_END_NO_RETURN(void, GetnCompressedTexImage, target, lod, bufSize, pixels)
DECLARE_GL_FUNCTION_STUB_HEAD(void, GetnTexImage, GLenum target, GLint level, GLenum format, GLenum type, GLsizei bufSize, void* pixels) DECLARE_GL_FUNCTION_STUB_END_NO_RETURN(void, GetnTexImage, target, level, format, type, bufSize, pixels)
DECLARE_GL_FUNCTION_STUB_HEAD(void, GetnUniformdv, GLuint program, GLint location, GLsizei bufSize, GLdouble* params) DECLARE_GL_FUNCTION_STUB_END_NO_RETURN(void, GetnUniformdv, program, location, bufSize, params)
DECLARE_GL_FUNCTION_HEAD(void, GetnUniformdv, GLuint program, GLint location, GLsizei bufSize, GLdouble* params) DECLARE_GL_FUNCTION_END_NO_RETURN(void, GetnUniformdv, program, location, bufSize, params)
DECLARE_GL_FUNCTION_STUB_HEAD(void, GetnMapdv, GLenum target, GLenum query, GLsizei bufSize, GLdouble* v) DECLARE_GL_FUNCTION_STUB_END_NO_RETURN(void, GetnMapdv, target, query, bufSize, v)
DECLARE_GL_FUNCTION_STUB_HEAD(void, GetnMapfv, GLenum target, GLenum query, GLsizei bufSize, GLfloat* v) DECLARE_GL_FUNCTION_STUB_END_NO_RETURN(void, GetnMapfv, target, query, bufSize, v)
DECLARE_GL_FUNCTION_STUB_HEAD(void, GetnMapiv, GLenum target, GLenum query, GLsizei bufSize, GLint* v) DECLARE_GL_FUNCTION_STUB_END_NO_RETURN(void, GetnMapiv, target, query, bufSize, v)
@@ -1289,7 +1292,6 @@ DECLARE_GL_FUNCTION_STUB_HEAD(void, PointParameterfARB, GLenum pname, GLfloat pa
DECLARE_GL_FUNCTION_STUB_HEAD(void, PointParameterfvARB, GLenum pname, const GLfloat* params) DECLARE_GL_FUNCTION_STUB_END_NO_RETURN(void, PointParameterfvARB, pname, params)
DECLARE_GL_FUNCTION_STUB_HEAD(void, GetnTexImageARB, GLenum target, GLint level, GLenum format, GLenum type, GLsizei bufSize, void* img) DECLARE_GL_FUNCTION_STUB_END_NO_RETURN(void, GetnTexImageARB, target, level, format, type, bufSize, img)
DECLARE_GL_FUNCTION_STUB_HEAD(void, GetnCompressedTexImageARB, GLenum target, GLint lod, GLsizei bufSize, void* img) DECLARE_GL_FUNCTION_STUB_END_NO_RETURN(void, GetnCompressedTexImageARB, target, lod, bufSize, img)
DECLARE_GL_FUNCTION_STUB_HEAD(void, GetnUniformdvARB, GLuint program, GLint location, GLsizei bufSize, GLdouble* params) DECLARE_GL_FUNCTION_STUB_END_NO_RETURN(void, GetnUniformdvARB, program, location, bufSize, params)
DECLARE_GL_FUNCTION_STUB_HEAD(void, GetnMapdvARB, GLenum target, GLenum query, GLsizei bufSize, GLdouble* v) DECLARE_GL_FUNCTION_STUB_END_NO_RETURN(void, GetnMapdvARB, target, query, bufSize, v)
DECLARE_GL_FUNCTION_STUB_HEAD(void, GetnMapfvARB, GLenum target, GLenum query, GLsizei bufSize, GLfloat* v) DECLARE_GL_FUNCTION_STUB_END_NO_RETURN(void, GetnMapfvARB, target, query, bufSize, v)
DECLARE_GL_FUNCTION_STUB_HEAD(void, GetnMapivARB, GLenum target, GLenum query, GLsizei bufSize, GLint* v) DECLARE_GL_FUNCTION_STUB_END_NO_RETURN(void, GetnMapivARB, target, query, bufSize, v)
@@ -2990,6 +2992,50 @@ MOBILEGL_GL_API void glGetnUniformuivARB(GLuint program, GLint location, GLsizei
glGetnUniformuiv(program, location, bufSize, params);
}
MOBILEGL_GL_API void glGetnUniformdvARB(GLuint program, GLint location, GLsizei bufSize, GLdouble* params) {
glGetnUniformdv(program, location, bufSize, params);
}
// KHR_robustness and EXT_robustness name the same entry points with their own suffixes (an ES
// application, ANGLE's GL backend among them, looks them up by those names).
MOBILEGL_GL_API GLenum glGetGraphicsResetStatusKHR(void) {
return glGetGraphicsResetStatus();
}
MOBILEGL_GL_API GLenum glGetGraphicsResetStatusEXT(void) {
return glGetGraphicsResetStatus();
}
MOBILEGL_GL_API void glReadnPixelsKHR(GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type,
GLsizei bufSize, void* data) {
glReadnPixels(x, y, width, height, format, type, bufSize, data);
}
MOBILEGL_GL_API void glReadnPixelsEXT(GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type,
GLsizei bufSize, void* data) {
glReadnPixels(x, y, width, height, format, type, bufSize, data);
}
MOBILEGL_GL_API void glGetnUniformfvKHR(GLuint program, GLint location, GLsizei bufSize, GLfloat* params) {
glGetnUniformfv(program, location, bufSize, params);
}
MOBILEGL_GL_API void glGetnUniformfvEXT(GLuint program, GLint location, GLsizei bufSize, GLfloat* params) {
glGetnUniformfv(program, location, bufSize, params);
}
MOBILEGL_GL_API void glGetnUniformivKHR(GLuint program, GLint location, GLsizei bufSize, GLint* params) {
glGetnUniformiv(program, location, bufSize, params);
}
MOBILEGL_GL_API void glGetnUniformivEXT(GLuint program, GLint location, GLsizei bufSize, GLint* params) {
glGetnUniformiv(program, location, bufSize, params);
}
MOBILEGL_GL_API void glGetnUniformuivKHR(GLuint program, GLint location, GLsizei bufSize, GLuint* params) {
glGetnUniformuiv(program, location, bufSize, params);
}
MOBILEGL_GL_API void glGetObjectLabelEXT(GLenum identifier, GLuint name, GLsizei bufSize, GLsizei* length,
GLchar* label) {
glGetObjectLabel(identifier, name, bufSize, length, label);
+137 -16
View File
@@ -592,12 +592,90 @@ namespace MobileGL::MG_Impl::GLImpl {
}
namespace {
// GL_OES_EGL_image binds the EGL side's dma-buf images, which only a backend with shared
// images has (EGLImpl::SharedImagesAvailable). The backend's own list - the server's,
// under split - cannot know that, so the extension is appended after it.
const char* ClientSideExtension() {
return MG_Impl::EGLImpl::SharedImagesAvailable() ? "GL_OES_EGL_image" : nullptr;
// Extensions this library implements itself, appended after the backend's own list (the
// server's, under split), which cannot know about them:
// * GL_OES_EGL_image binds the EGL side's dma-buf images, which only a backend with
// shared images has (EGLImpl::SharedImagesAvailable);
// * the robustness family - reset notification (glGetGraphicsResetStatus, the contexts'
// EGL reset strategy, GL_CONTEXT_LOST) and the bounded queries (glReadnPixels,
// glGetnUniform*) are this frontend's, whatever the backend. KHR for GL and ES, ARB for
// GL applications that ask for that name, EXT for ES applications that ask for that one.
// Robust buffer ACCESS is a separate promise (GL_CONTEXT_ROBUST_ACCESS) and is not
// implied by any of them.
// One list for glGetString and glGetStringi, so the two forms always agree.
Bool EsIdentityActive();
const Vector<const char*>& ClientSideExtensions() {
static const Vector<const char*> withImages = {"GL_OES_EGL_image", "GL_KHR_robustness",
"GL_ARB_robustness", "GL_EXT_robustness"};
static const Vector<const char*> withoutImages = {"GL_KHR_robustness", "GL_ARB_robustness",
"GL_EXT_robustness"};
// Under the ES identity (EsIdentityActive) the ES names of what desktop GL has in core:
// BGRA textures, render targets and read-backs. GL_BGRA_EXT / GL_BGRA8_EXT as internal
// formats are taken as RGBA storage (TextureEnumConverter), the byte order being the
// pixel transfer format's, as on desktop GL.
static const Vector<const char*> esWithImages = {
"GL_OES_EGL_image", "GL_KHR_robustness", "GL_ARB_robustness",
"GL_EXT_robustness", "GL_EXT_texture_format_BGRA8888", "GL_EXT_read_format_bgra"};
static const Vector<const char*> esWithoutImages = {"GL_KHR_robustness", "GL_ARB_robustness",
"GL_EXT_robustness", "GL_EXT_texture_format_BGRA8888",
"GL_EXT_read_format_bgra"};
const Bool images = MG_Impl::EGLImpl::SharedImagesAvailable();
if (EsIdentityActive()) return images ? esWithImages : esWithoutImages;
return images ? withImages : withoutImages;
}
// Robust buffer access as GL 4.5 / KHR_robust_buffer_access_behavior define it: the backend
// promises it by listing one of the behavior extensions. Neither backend does today, so a
// context that asked for robust access gets it reported as absent rather than claimed.
Bool BackendProvidesRobustBufferAccess() {
const auto& backend = MG_Backend::pActiveBackendObject;
if (!backend) return false;
const auto& extensions = backend->GetRendererInfo().RendererGLInfo.Extensions;
return std::find(extensions.begin(), extensions.end(), E_GL_KHR_robust_buffer_access_behavior) !=
extensions.end() ||
std::find(extensions.begin(), extensions.end(), E_GL_ARB_robust_buffer_access_behavior) !=
extensions.end();
}
// MOBILEGL_ES_CONTEXT_IDENTITY=1: a context created for the OpenGL ES API names itself OpenGL
// ES 3.2 (GL_VERSION, GL_SHADING_LANGUAGE_VERSION, GL_MAJOR/MINOR_VERSION) instead of the
// desktop version every context reports by default. Opt-in, for an application that
// decides what it may use from that identity: ANGLE's GL-on-EGL backend offers
// GL_OES_EGL_image - which Chrome's GPU process presents through - only over a native
// driver that calls itself OpenGL ES, and reads the desktop identity's extension names
// otherwise.
Bool EsIdentityActive() {
static const Bool requested = [] {
const char* value = std::getenv("MOBILEGL_ES_CONTEXT_IDENTITY");
return value != nullptr && value[0] == '1';
}();
return requested && MG_State::pEGLContext &&
MG_State::pEGLContext->GetCurrentContextClientAPI() == EGL_OPENGL_ES_API;
}
Bool CurrentContextHasRobustAccess() {
return MG_State::pEGLContext && MG_State::pEGLContext->IsCurrentContextRobustAccessRequested() &&
BackendProvidesRobustBufferAccess();
}
#if MOBILEGL_BUILD_DISAGGREGATED
// KHR_robustness 2.6.1: a context whose reset notification behavior is
// NO_RESET_NOTIFICATION is never told of a reset - glGetGraphicsResetStatus answers
// GL_NO_ERROR and no command raises GL_CONTEXT_LOST. That is what an explicit core-profile
// context gets. Everywhere else (MG_State::IsRelaxedSemanticsActive) the loss is reported
// to every context, as before the strategy existed: an application that queries the reset
// status without having asked for notification still learns that its context is gone,
// which on a split client it is - there is nothing to recover in place. A context created
// with EGL_LOSE_CONTEXT_ON_RESET is always told.
Bool ResetIsNotified() {
if (MG_State::pEGLContext &&
MG_State::pEGLContext->GetCurrentContextResetNotificationStrategy() == EGL_LOSE_CONTEXT_ON_RESET) {
return true;
}
return MG_State::IsRelaxedSemanticsActive();
}
#endif
} // namespace
/* @INSERTION_POINT:FUNCTION_IMPLEMENTATION@ */
@@ -635,6 +713,12 @@ namespace MobileGL::MG_Impl::GLImpl {
if (const auto at = backendName.find("OpenGL ES"); at != String::npos) {
backendName.replace(at, sizeof("OpenGL ES") - 1, "GLES");
}
if (EsIdentityActive()) {
versionStr = std::format("OpenGL ES 3.2 {} {}, {} Backend, GIT@" GIT_COMMIT_HASH_SHORT, MG_Config::ProjectName,
MG_Config::CoreVersion.toFormattedString(MG_Config::DefaultVersionStringFormatAttrib),
backendName);
return (const GLubyte*)versionStr.c_str();
}
versionStr =
std::format("{} {} {}, {} Backend, GIT@" GIT_COMMIT_HASH_SHORT,
rendererInfo.RendererGLInfo.TargetGLVersion.toString(), MG_Config::ProjectName,
@@ -651,6 +735,7 @@ namespace MobileGL::MG_Impl::GLImpl {
return (const GLubyte*)rendererString.c_str();
}
case GL_SHADING_LANGUAGE_VERSION:
if (EsIdentityActive()) return (const GLubyte*)"OpenGL ES GLSL ES 3.20";
shadingLanguageVersion =
std::format("{} {}", rendererInfo.RendererGLInfo.TargetGLSLVersion.toString({true, false}),
MG_Config::ProjectName);
@@ -664,7 +749,7 @@ namespace MobileGL::MG_Impl::GLImpl {
}
extensionsString += MG_Util::ConvertGLExtToString(ext);
}
if (const char* extra = ClientSideExtension()) {
for (const char* extra : ClientSideExtensions()) {
if (!extensionsString.empty()) extensionsString += " ";
extensionsString += extra;
}
@@ -688,8 +773,9 @@ namespace MobileGL::MG_Impl::GLImpl {
const auto& rendererInfo = activeBackendObject->GetRendererInfo();
const auto& exts = rendererInfo.RendererGLInfo.Extensions;
if (index == exts.size()) {
if (const char* extra = ClientSideExtension()) return (const GLubyte*)extra;
if (index >= exts.size()) {
const auto& extras = ClientSideExtensions();
if (index - exts.size() < extras.size()) return (const GLubyte*)extras[index - exts.size()];
}
if (index >= exts.size()) {
return nullptr;
@@ -1675,8 +1761,20 @@ namespace MobileGL::MG_Impl::GLImpl {
return;
case GL_CONTEXT_FLAGS: {
*params = MG_State::pEGLContext ? MG_State::pEGLContext->GetCurrentContextFlags() : 0;
if (CurrentContextHasRobustAccess()) *params |= GL_CONTEXT_FLAG_ROBUST_ACCESS_BIT;
return;
}
case GL_CONTEXT_ROBUST_ACCESS:
// GL ES 3.2 / KHR_robustness: true only where it was asked for AND is provided.
*params = CurrentContextHasRobustAccess() ? GL_TRUE : GL_FALSE;
return;
case GL_RESET_NOTIFICATION_STRATEGY:
// The EGL reset notification behavior the context was created with.
*params = MG_State::pEGLContext && MG_State::pEGLContext->GetCurrentContextResetNotificationStrategy() ==
EGL_LOSE_CONTEXT_ON_RESET
? GL_LOSE_CONTEXT_ON_RESET
: GL_NO_RESET_NOTIFICATION;
return;
case GL_CULL_FACE:
*params = MG_State::pGLContext->IsCapabilityEnabled(CapabilityInput::CullFace) ? GL_TRUE : GL_FALSE;
return;
@@ -2522,7 +2620,7 @@ namespace MobileGL::MG_Impl::GLImpl {
GetIntegeri_v(GL_MAX_COMPUTE_WORK_GROUP_SIZE, 2, &params[2]);
break;
case GL_MAJOR_VERSION:
*params = rendererInfo.RendererGLInfo.TargetGLVersion.Major;
*params = EsIdentityActive() ? 3 : rendererInfo.RendererGLInfo.TargetGLVersion.Major;
break;
case GL_MAX_3D_TEXTURE_SIZE:
*params = dynamicParameters.Max3DTextureSize;
@@ -2809,11 +2907,10 @@ namespace MobileGL::MG_Impl::GLImpl {
*params = static_cast<GLint>(RenderStateParameters::MAX_VIEWPORTS);
break;
case GL_MINOR_VERSION:
*params = rendererInfo.RendererGLInfo.TargetGLVersion.Minor;
*params = EsIdentityActive() ? 2 : rendererInfo.RendererGLInfo.TargetGLVersion.Minor;
break;
case GL_NUM_EXTENSIONS:
*params = static_cast<Int>(rendererInfo.RendererGLInfo.Extensions.size()) +
(ClientSideExtension() != nullptr ? 1 : 0);
*params = static_cast<Int>(rendererInfo.RendererGLInfo.Extensions.size() + ClientSideExtensions().size());
break;
case GL_POINT_SIZE_GRANULARITY:
*params = static_cast<GLint>(dynamicParameters.PointSizeGranularity);
@@ -2883,7 +2980,9 @@ namespace MobileGL::MG_Impl::GLImpl {
// context and ahead of whatever else is queued, so an application that learns of the loss
// from glGetError (Chromium's decoder does) learns of it, and one that drains errors in a
// loop until GL_NO_ERROR still terminates.
if (MG_Remote::Client::ClientSession::DeviceLost() && MG_State::pGLContext &&
// Only where the reset is notified at all (ResetIsNotified: not on a NO_RESET_NOTIFICATION
// explicit core-profile context).
if (MG_Remote::Client::ClientSession::DeviceLost() && MG_State::pGLContext && ResetIsNotified() &&
MG_State::pGLContext->TakeContextLostReport()) {
return GL_CONTEXT_LOST;
}
@@ -2907,13 +3006,35 @@ namespace MobileGL::MG_Impl::GLImpl {
//
// GL_UNKNOWN_CONTEXT_RESET, not GUILTY or INNOCENT. Those two assign BLAME - guilty
// means this context's commands caused the reset, innocent means another context's did -
// and neither is knowable here: the server died for a reason that never crossed the
// wire, and it could as easily have been a driver fault as this client's draw. UNKNOWN is
// the spec's answer for exactly that, and it is the one that does not lie.
// and neither is knowable here:
// * a session ends for a fault the server names by FAMILY only (BackendDeviceLost, a
// protocol fault, ...) or by hanging up; nothing it sends attributes the fault to a
// context, and a hangup is a server death, not a GPU reset at all;
// * a GPU device loss is not attributable either: Vulkan's device loss carries no
// culprit, and the host GL driver's own GUILTY/INNOCENT (which Espryt reads when it
// latches) is about whichever backend context the server had current, while the
// session ends as a whole - every context of it is lost with that one;
// * INNOCENT would mean another context's fault reset this one, but a loss ends exactly
// the session that faulted (every other session keeps running), so the contexts that
// see it are all in the faulting session.
// UNKNOWN is the spec's answer for exactly that, and it is the one that does not lie. The
// cause - the latch's words, with the fault family where the server named one - is
// logged once per context, the first time its reset is reported.
//
// The status does not go back to GL_NO_ERROR: the context stays lost (KHR_robustness
// allows a reset status to be returned repeatedly while the reset "is in progress", and
// this one never completes - the context has to be recreated, which puts it on a fresh
// session).
//
// WHOLLY INSIDE THE GUARD, including the include above. In a pull build this function is
// byte-for-byte what it was, which is what G1 measures.
if (MG_Remote::Client::ClientSession::DeviceLost()) {
if (!ResetIsNotified()) return GL_NO_ERROR;
if (MG_State::pGLContext && MG_State::pGLContext->TakeResetStatusReport()) {
const String reason = MG_Remote::Client::ClientSession::LastLossReason();
MGLOG_W("glGetGraphicsResetStatus: GL_UNKNOWN_CONTEXT_RESET for a context of a lost session (%s)",
reason.empty() ? "the session was lost" : reason.c_str());
}
return GL_UNKNOWN_CONTEXT_RESET;
}
#endif
@@ -1380,6 +1380,36 @@ namespace MobileGL::MG_Impl::GLImpl {
GetUniformScalar_State(program, location, params);
}
// glGetnUniform* (GL 4.5 core, KHR_robustness): glGetUniform* bounded by bufSize. The query
// writes one value per component of the uniform at `location` (an opaque uniform's unit is
// one), so the bound is that count times the element size; a destination smaller than that -
// a negative bufSize included - is GL_INVALID_OPERATION and nothing is written. Every other
// error is the unbounded query's, raised by it.
template <typename T>
void GetnUniform_State(GLuint program, GLint location, GLsizei bufSize, T* params) {
auto& programObject = TryToGetProgramObject(program);
if (!programObject) return;
if (programObject->GetLinkStatus() && programObject->IsValidUniformLocation(location)) {
SizeT components = 1;
if (!programObject->IsUniformOpaqueAtLocation(location)) {
const auto& type = programObject->GetUniformTypeFacts(location);
components = type.isMatrix ? static_cast<SizeT>(type.matrixCols) * static_cast<SizeT>(type.matrixRows)
: type.isVector ? static_cast<SizeT>(type.vectorSize)
: 1;
}
if (bufSize < 0 || components * sizeof(T) > static_cast<SizeT>(bufSize)) {
MG_State::pGLContext->RecordError(
ErrorCode::InvalidOperation,
MakeUnique<GenericErrorInfo>("MG_Impl/GLImpl", __func__,
"the uniform's " + std::to_string(components) +
" component(s) do not fit in bufSize " + std::to_string(bufSize) +
"."));
return;
}
}
GetUniformScalar_State(program, location, params);
}
GLboolean IsProgram_State(GLuint program) {
// Deletion-flagged names stay valid while the object is still GL-visible (program in
// use, shader attached), so name validity is exactly the Is* answer.
@@ -2553,6 +2583,22 @@ namespace MobileGL::MG_Impl::GLImpl {
GetUniformuiv_State(program, location, params);
}
void GetnUniformfv(GLuint program, GLint location, GLsizei bufSize, GLfloat* params) {
GetnUniform_State(program, location, bufSize, params);
}
void GetnUniformiv(GLuint program, GLint location, GLsizei bufSize, GLint* params) {
GetnUniform_State(program, location, bufSize, params);
}
void GetnUniformuiv(GLuint program, GLint location, GLsizei bufSize, GLuint* params) {
GetnUniform_State(program, location, bufSize, params);
}
void GetnUniformdv(GLuint program, GLint location, GLsizei bufSize, GLdouble* params) {
GetnUniform_State(program, location, bufSize, params);
}
GLboolean IsProgram(GLuint program) {
return IsProgram_State(program);
}
@@ -46,6 +46,11 @@ namespace MobileGL::MG_Impl::GLImpl {
void GetUniformfv(GLuint program, GLint location, GLfloat* params);
void GetUniformiv(GLuint program, GLint location, GLint* params);
void GetUniformuiv(GLuint program, GLint location, GLuint* params);
// GL 4.5 / KHR_robustness: the queries above, bounded by bufSize.
void GetnUniformfv(GLuint program, GLint location, GLsizei bufSize, GLfloat* params);
void GetnUniformiv(GLuint program, GLint location, GLsizei bufSize, GLint* params);
void GetnUniformuiv(GLuint program, GLint location, GLsizei bufSize, GLuint* params);
void GetnUniformdv(GLuint program, GLint location, GLsizei bufSize, GLdouble* params);
GLboolean IsProgram(GLuint program);
GLboolean IsShader(GLuint shader);
void LinkProgram(GLuint program);
@@ -7178,7 +7178,9 @@ namespace MobileGL::MG_Impl::GLImpl {
MG_State::pGLContext->RecordError(
ErrorCode::InvalidOperation,
MakeUnique<GenericErrorInfo>("MG_Impl/GLImpl", __func__, "the image could not be bound."));
return;
}
MG_Impl::EGLImpl::NoteSharedImageBoundToTexture();
}
void TexImage1D(GLenum target, GLint level, GLint internalFormat, GLsizei width, GLint border, GLenum format,
+169 -9
View File
@@ -12,8 +12,11 @@
#include "../EGLImpl/EGLImpl.h"
#include "../EGLImpl/WaylandWindow.h"
#include "../GetProcAddress.h"
#include "X11Present.h"
#include "X11PresentXcb.h"
#include <Init.h>
#include <Config.h>
#include <MG_Backend/BackendObjects.h>
namespace MobileGL::MG_Impl::GLXImpl {
namespace {
@@ -72,6 +75,8 @@ namespace MobileGL::MG_Impl::GLXImpl {
// GLX_EXT_swap_control
constexpr int GLX_SWAP_INTERVAL_EXT = 0x20F1;
constexpr int GLX_MAX_SWAP_INTERVAL_EXT = 0x20F2;
// GLX_EXT_buffer_age
constexpr int GLX_BACK_BUFFER_AGE_EXT = 0x20F4;
// GLX_ARB_create_context / _profile / _no_error
constexpr int GLX_CONTEXT_MAJOR_VERSION_ARB = 0x2091;
constexpr int GLX_CONTEXT_MINOR_VERSION_ARB = 0x2092;
@@ -86,6 +91,15 @@ namespace MobileGL::MG_Impl::GLXImpl {
constexpr const char* kGLXExtensions =
"GLX_ARB_create_context GLX_ARB_create_context_no_error GLX_ARB_create_context_profile "
"GLX_ARB_get_proc_address GLX_EXT_swap_control GLX_MESA_swap_control GLX_SGI_swap_control";
// The server answers its surfaces' buffer age (EGL_EXT_buffer_age) when it has shared images.
constexpr const char* kGLXExtensionsWithBufferAge =
"GLX_ARB_create_context GLX_ARB_create_context_no_error GLX_ARB_create_context_profile "
"GLX_ARB_get_proc_address GLX_EXT_swap_control GLX_MESA_swap_control GLX_SGI_swap_control "
"GLX_EXT_buffer_age";
const char* GLXExtensions() {
return EGLImpl::SharedImagesAvailable() ? kGLXExtensionsWithBufferAge : kGLXExtensions;
}
// ---- Xlib access (dlopen'd at runtime, same convention as the backends;
// libX11 is never a link-time dependency of libMobileGL) ----
@@ -230,6 +244,33 @@ namespace MobileGL::MG_Impl::GLXImpl {
const FBConfigInfo* FBConfig = nullptr;
};
// The server's shared images, as X11Present's chain uses them (the GL stream's verbs: the
// caller holds the stream lock, as every GLX entry point does).
class BackendImageSource final : public X11Present::ImageSource {
public:
Bool Allocate(Uint32 width, Uint32 height, Uint32 fourcc, X11Present::Image* out) override {
auto* backend = MG_Backend::pActiveBackendObject.get();
MG_Backend::SharedImageExport image;
if (backend == nullptr || !backend->AllocateSharedImage(width, height, fourcc, &image)) return false;
out->Id = image.Id;
out->Fd = image.Fd;
out->Width = image.Width;
out->Height = image.Height;
out->Stride = image.Stride;
out->Offset = image.Offset;
out->Fourcc = image.Fourcc;
out->Modifier = image.Modifier;
return true;
}
void Release(Uint64 id) override {
if (auto* backend = MG_Backend::pActiveBackendObject.get()) (void)backend->ReleaseSharedImage(id);
}
Bool CopyFrame(Uint64 id, const MG_Util::Damage::Region& region) override {
auto* backend = MG_Backend::pActiveBackendObject.get();
return backend != nullptr && backend->PresentToSharedImage(id, region);
}
};
struct DrawableSurface {
EGLDisplay Display = EGL_NO_DISPLAY;
EGLSurface Surface = EGL_NO_SURFACE;
@@ -244,6 +285,14 @@ namespace MobileGL::MG_Impl::GLXImpl {
Uint32 Gc = 0;
Vector<Uint8> Scratch;
Vector<Uint8> Image;
// How its frames reach the window (chosen at the first swap, X11Present::SelectPath):
// DRI3+Present shared images, or the readback put with MIT-SHM or plain PutImage.
Bool PathChosen = false;
X11Present::Path Path = X11Present::Path::PutImage;
UniquePtr<X11Present::Connection> PresentConnection;
UniquePtr<BackendImageSource> Images;
UniquePtr<X11Present::Chain> Chain;
UniquePtr<X11Present::ShmPresenter> Shm;
};
std::recursive_mutex& RegistryMutex() {
@@ -279,8 +328,18 @@ namespace MobileGL::MG_Impl::GLXImpl {
};
thread_local ThreadCurrent t_current;
// vblank_mode=0 (the benchmark convention X11 GL drivers honour) never waits for the
// display, whatever the application asks; anything else leaves the interval to it.
Bool VblankForcedOff() {
static const Bool off = [] {
const char* mode = std::getenv("vblank_mode");
return mode != nullptr && std::strcmp(mode, "0") == 0;
}();
return off;
}
Int& SwapIntervalShadow() {
static auto* interval = new Int(1);
static auto* interval = new Int(VblankForcedOff() ? 0 : 1);
return *interval;
}
@@ -334,10 +393,62 @@ namespace MobileGL::MG_Impl::GLXImpl {
return true;
}
Int& SwapIntervalShadow();
Int64 SteadyNowMs() {
return std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now().time_since_epoch())
.count();
}
// Which way this drawable's frames go, decided once (X11Present::SelectPath), with the
// DRI3 chain set up when that is the way. A chain that cannot be set up falls through to
// the readback paths.
void ChoosePresentPath(GLXDrawableHandle drawable, DrawableSurface& surface, void* connection) {
surface.PathChosen = true;
X11Present::ConnectionCaps caps = X11Present::QueryConnectionCaps(connection);
caps.SharedImages = EGLImpl::SharedImagesAvailable();
const char* override = std::getenv("MOBILEGL_GLX_PRESENT");
surface.Path = X11Present::SelectPath(caps, surface.Depth, override);
if (surface.Path == X11Present::Path::Dri3Present) {
surface.PresentConnection =
X11Present::CreateXcbConnection(connection, static_cast<Uint32>(drawable), caps);
if (surface.PresentConnection) {
surface.Images = MakeUnique<BackendImageSource>();
surface.Chain = MakeUnique<X11Present::Chain>(
*surface.PresentConnection, *surface.Images, surface.Depth, static_cast<Int32>(surface.Width),
static_cast<Int32>(surface.Height), &SteadyNowMs);
} else {
caps.Dri3Major = 0;
surface.Path = X11Present::SelectPath(caps, surface.Depth, override);
}
}
if (surface.Path == X11Present::Path::ShmPutImage) {
surface.Shm = X11Present::CreateShmPresenter(connection);
if (!surface.Shm) surface.Path = X11Present::Path::PutImage;
}
MGLOG_I("glx: window 0x%lx (%ux%u, depth %u) presented through %s (DRI3 %u.%u, Present %u.%u, MIT-SHM "
"%u.%u, %s connection, shared images %s)",
drawable, surface.Width, surface.Height, surface.Depth, X11Present::PathName(surface.Path),
caps.Dri3Major, caps.Dri3Minor, caps.PresentMajor, caps.PresentMinor, caps.ShmMajor, caps.ShmMinor,
caps.LocalConnection ? "local" : "remote", caps.SharedImages ? "yes" : "no");
}
// The chain's resources go (pixmaps freed, images released); the drawable keeps whatever
// readback path is left.
void DropChain(DrawableSurface& surface) {
surface.Chain.reset();
surface.PresentConnection.reset();
surface.Images.reset();
}
// A REMOTE DRAWABLE IS A PBUFFER, AND NOTHING OF IT REACHES THE X WINDOW BY ITSELF: the
// backend draws in another process (another OS), where an XID means nothing. So at every
// swap the frame is read back and put on the window with PutImage - the same contract as
// the Wayland windows' wl_shm presentation. Called with the drawable current.
// swap the frame goes to the window one of three ways (X11Present.h): copied GPU-side into
// a shared image the X server has as a DRI3 pixmap and presented with PresentPixmap - no
// CPU copy at all; or read back and put with MIT-SHM; or read back and put with PutImage,
// the same contract as the Wayland windows' wl_shm presentation. Called with the drawable
// current.
void PresentRemoteDrawable(GLXDrawableHandle drawable, DrawableSurface& surface) {
const EGLImpl::GLStreamScope stream; // the readback is GL records of this thread's context
const auto& xcb = Xcb();
@@ -348,6 +459,20 @@ namespace MobileGL::MG_Impl::GLXImpl {
}
void* connection = xcb.GetXCBConnection(surface.XDisplay);
if (!connection) return;
if (!surface.PathChosen) ChoosePresentPath(drawable, surface, connection);
if (surface.Chain) {
if (surface.Chain->Present(MG_Util::Damage::Region::Full(), SwapIntervalShadow())) return;
if (!surface.Chain->Broken()) return; // the frame is dropped; the chain goes on
MGLOG_I("glx: window 0x%lx leaves DRI3+Present: %s; its frames are read back from now on", drawable,
surface.Chain->BrokenReason());
DropChain(surface);
X11Present::ConnectionCaps caps = X11Present::QueryConnectionCaps(connection);
surface.Path = X11Present::SelectPath(caps, surface.Depth, "readback");
if (surface.Path == X11Present::Path::ShmPutImage) {
surface.Shm = X11Present::CreateShmPresenter(connection);
if (!surface.Shm) surface.Path = X11Present::Path::PutImage;
}
}
if (surface.Gc == 0) {
surface.Gc = xcb.GenerateId(connection);
(void)xcb.CreateGC(connection, surface.Gc, static_cast<Uint32>(drawable), 0, nullptr);
@@ -355,6 +480,15 @@ namespace MobileGL::MG_Impl::GLXImpl {
const EGLint width = static_cast<EGLint>(surface.Width);
const EGLint height = static_cast<EGLint>(surface.Height);
const SizeT rowBytes = static_cast<SizeT>(width) * 4;
if (surface.Shm) {
const Bool put = surface.Shm->Put(
static_cast<Uint32>(drawable), surface.Gc, surface.Depth, width, height,
[&](Uint8* rows, SizeT stride) { EGLImpl::ReadBackFrameBGRA(width, height, surface.Scratch, rows, stride); });
if (put) return;
MGLOG_I("glx: window 0x%lx: MIT-SHM put failed; PutImage from now on", drawable);
surface.Shm.reset();
surface.Path = X11Present::Path::PutImage;
}
surface.Image.resize(rowBytes * static_cast<SizeT>(height));
EGLImpl::ReadBackFrameBGRA(width, height, surface.Scratch, surface.Image.data(), rowBytes);
@@ -374,6 +508,8 @@ namespace MobileGL::MG_Impl::GLXImpl {
}
void ReleaseDrawableSurface(DrawableSurface& surface) {
DropChain(surface);
surface.Shm.reset();
if (surface.Gc != 0 && surface.XDisplay) {
const auto& xcb = Xcb();
if (void* connection = xcb.Valid() ? xcb.GetXCBConnection(surface.XDisplay) : nullptr) {
@@ -408,6 +544,8 @@ namespace MobileGL::MG_Impl::GLXImpl {
static_cast<EGLint>(height))) {
surface.Width = width;
surface.Height = height;
// The shared images follow: the next frame goes into ones of the new size.
if (surface.Chain) surface.Chain->Resize(static_cast<Int32>(width), static_cast<Int32>(height));
}
}
@@ -456,7 +594,7 @@ namespace MobileGL::MG_Impl::GLXImpl {
record.XDisplay = dpy;
record.Depth = depth;
record.LastSizePoll = std::chrono::steady_clock::now();
auto [inserted, _] = surfaces.emplace(drawable, record);
auto [inserted, _] = surfaces.emplace(drawable, std::move(record));
return &inserted->second;
}
@@ -670,7 +808,7 @@ namespace MobileGL::MG_Impl::GLXImpl {
}
const char* QueryExtensionsString(Display*, int) {
return kGLXExtensions;
return GLXExtensions();
}
const char* GetClientString(Display*, int name) {
@@ -680,7 +818,7 @@ namespace MobileGL::MG_Impl::GLXImpl {
case GLX_VERSION:
return "1.4";
case GLX_EXTENSIONS:
return kGLXExtensions;
return GLXExtensions();
default:
return nullptr;
}
@@ -1086,8 +1224,15 @@ namespace MobileGL::MG_Impl::GLXImpl {
PresentRemoteDrawable(drawable, it->second);
}
EGLImpl::SwapBuffers(it->second.Display, it->second.Surface);
// A resize takes effect for the next frame.
SyncSurfaceSize(dpy, drawable, it->second);
// A resize takes effect for the next frame: at once when Present reported one, else at the
// next throttled geometry poll.
Int32 configuredWidth = 0;
Int32 configuredHeight = 0;
const Bool configured =
it->second.Chain && it->second.Chain->TakeConfiguredSize(&configuredWidth, &configuredHeight) &&
(static_cast<Uint32>(configuredWidth) != it->second.Width ||
static_cast<Uint32>(configuredHeight) != it->second.Height);
SyncSurfaceSize(dpy, drawable, it->second, configured);
}
GLXDrawableHandle CreateWindow(Display*, GLXFBConfigHandle config, GLXDrawableHandle window,
@@ -1187,6 +1332,21 @@ namespace MobileGL::MG_Impl::GLXImpl {
case GLX_SWAP_INTERVAL_EXT:
*value = static_cast<unsigned int>(SwapIntervalShadow());
return;
case GLX_BACK_BUFFER_AGE_EXT: {
// GLX_EXT_buffer_age: the age of the buffer the drawable's next frame draws into - the
// server's pbuffer, which keeps its content - asked of the EGL surface behind it, which
// answers only while it is the calling thread's draw surface.
*value = 0;
const std::lock_guard<std::recursive_mutex> lock(RegistryMutex());
auto& surfaces = DrawableSurfaces();
auto it = surfaces.find(drawable);
if (it == surfaces.end() || t_current.Draw != drawable) return;
EGLint age = 0;
if (EGLImpl::QuerySurface(it->second.Display, it->second.Surface, EGL_BUFFER_AGE_EXT, &age) && age > 0) {
*value = static_cast<unsigned int>(age);
}
return;
}
case GLX_MAX_SWAP_INTERVAL_EXT:
*value = 4;
return;
@@ -1210,7 +1370,7 @@ namespace MobileGL::MG_Impl::GLXImpl {
return;
}
// MobileGL validates 0..4; adaptive vsync (negative) clamps to regular.
interval = std::clamp(interval, 0, 4);
interval = VblankForcedOff() ? 0 : std::clamp(interval, 0, 4);
EGLImpl::SwapInterval(display, interval);
SwapIntervalShadow() = interval;
}
+284
View File
@@ -0,0 +1,284 @@
// MobileGL - MobileGL/MG_Impl/GLXImpl/X11Present.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 "X11Present.h"
#include <cstring>
#if !defined(_WIN32)
#include <unistd.h>
#endif
namespace MobileGL::MG_Impl::GLXImpl::X11Present {
namespace {
void CloseDescriptor(int fd) {
#if !defined(_WIN32)
if (fd >= 0) ::close(fd);
#else
(void)fd;
#endif
}
} // namespace
const char* PathName(Path path) {
switch (path) {
case Path::Dri3Present:
return "DRI3+Present shared images";
case Path::ShmPutImage:
return "readback + MIT-SHM PutImage";
case Path::PutImage:
return "readback + PutImage";
}
return "?";
}
Uint32 FourccForDepth(Uint32 depth) {
switch (depth) {
case 24:
return kFourccXrgb8888;
case 32:
return kFourccArgb8888;
default:
return 0;
}
}
Path SelectPath(const ConnectionCaps& caps, Uint32 depth, const char* overrideValue) {
const Bool putImageOnly = overrideValue != nullptr && std::strcmp(overrideValue, "putimage") == 0;
const Bool noDri3 = putImageOnly || (overrideValue != nullptr && (std::strcmp(overrideValue, "readback") == 0 ||
std::strcmp(overrideValue, "shm") == 0));
if (!noDri3 && caps.SharedImages && caps.LocalConnection && FourccForDepth(depth) != 0 &&
caps.Dri3Major >= 1 && caps.PresentMajor >= 1) {
return Path::Dri3Present;
}
// MIT-SHM 1.2 is the first with a client-made segment passed as a descriptor (no SysV
// shared memory, which a container need not share with the X server).
const Bool shmFd = caps.ShmMajor > 1 || (caps.ShmMajor == 1 && caps.ShmMinor >= 2);
if (!putImageOnly && caps.LocalConnection && shmFd) return Path::ShmPutImage;
return Path::PutImage;
}
Chain::Chain(Connection& connection, ImageSource& images, Uint32 depth, Int32 width, Int32 height,
std::function<Int64()> nowMs)
: m_connection(connection), m_images(images), m_depth(depth), m_fourcc(FourccForDepth(depth)),
m_width(width > 0 ? width : 1), m_height(height > 0 ? height : 1), m_nowMs(std::move(nowMs)) {
if (m_fourcc == 0) Break("the window's depth has no shared-image format");
}
Chain::~Chain() {
for (Buffer& buffer : m_buffers) Drop(buffer);
m_connection.Flush();
}
void Chain::Break(const char* reason) {
if (m_broken) return;
m_broken = true;
m_brokenReason = reason;
}
SizeT Chain::AllocatedBuffers() const {
SizeT count = 0;
for (const Buffer& buffer : m_buffers) count += buffer.Pixmap != 0 ? 1 : 0;
return count;
}
SizeT Chain::BusyBuffers() const {
SizeT count = 0;
for (const Buffer& buffer : m_buffers) count += buffer.Pixmap != 0 && buffer.Busy ? 1 : 0;
return count;
}
void Chain::Drop(Buffer& buffer) {
// The X server keeps a pixmap a pending present still names alive past FreePixmap, and the
// X server's own import of the image holds the image on the MobileGL server: both may go.
if (buffer.Pixmap != 0) m_connection.FreePixmap(buffer.Pixmap);
if (buffer.Storage.Id != 0) m_images.Release(buffer.Storage.Id);
CloseDescriptor(buffer.Storage.Fd);
m_damage.Invalidate(static_cast<SizeT>(&buffer - m_buffers));
buffer = Buffer{};
}
Bool Chain::Allocate(Buffer& buffer) {
Drop(buffer);
Image image;
if (!m_images.Allocate(static_cast<Uint32>(m_width), static_cast<Uint32>(m_height), m_fourcc, &image) ||
image.Id == 0) {
CloseDescriptor(image.Fd);
Break("the server allocated no shared image for the window");
return false;
}
if (image.Fd < 0 || image.Width != static_cast<Uint32>(m_width) || image.Height != static_cast<Uint32>(m_height)) {
CloseDescriptor(image.Fd);
m_images.Release(image.Id);
Break("a shared image came back without a descriptor or at another size");
return false;
}
const Uint32 pixmap = m_connection.ImportPixmap(image, m_depth);
// The pixmap holds the memory now (and the X server's own import, the image).
CloseDescriptor(image.Fd);
image.Fd = -1;
if (pixmap == 0) {
m_images.Release(image.Id);
Break("the X server refused the shared image as a DRI3 pixmap");
return false;
}
buffer.Storage = image;
buffer.Pixmap = pixmap;
buffer.Busy = false;
buffer.Serial = 0;
m_damage.Invalidate(static_cast<SizeT>(&buffer - m_buffers));
return true;
}
void Chain::Handle(const Event& event) {
switch (event.Type) {
case Event::Kind::Idle:
for (Buffer& buffer : m_buffers) {
if (buffer.Pixmap != 0 && buffer.Pixmap == event.Pixmap) buffer.Busy = false;
}
break;
case Event::Kind::Complete:
if (event.Msc != 0) m_lastMsc = event.Msc;
if (m_throttle.Outstanding() && event.Serial == m_awaitedSerial) m_throttle.Done();
break;
case Event::Kind::Configure:
if (event.WindowDestroyed) {
Break("the window was destroyed");
break;
}
if (event.Width > 0 && event.Height > 0) {
m_configured = true;
m_configuredWidth = event.Width;
m_configuredHeight = event.Height;
}
break;
case Event::Kind::None:
break;
}
}
void Chain::DrainEvents() {
Event event;
while (m_connection.PollEvent(&event)) Handle(event);
}
void Chain::WaitForPacing(Int swapInterval) {
const Int64 budget = m_throttle.WaitBudgetMs(swapInterval, m_nowMs());
if (budget == 0) return;
const Int64 limit = budget == EGLImpl::Wayland::FrameThrottle::kForever ? kCompleteGiveUpMs : budget;
const Int64 deadline = m_nowMs() + limit;
Event event;
while (m_throttle.Outstanding() && !m_broken) {
const Int64 remaining = deadline - m_nowMs();
if (remaining <= 0) {
// Interval 0's bounded wait simply ends; a paced wait gives the completion up so a
// server that lost it does not stall the application forever.
if (budget == EGLImpl::Wayland::FrameThrottle::kForever) m_throttle.Done();
return;
}
if (m_connection.WaitEvent(&event, remaining)) Handle(event);
}
}
Chain::Buffer* Chain::NextFree() {
const Int64 deadline = m_nowMs() + kIdleWaitMs;
for (;;) {
if (m_broken) return nullptr;
// The free buffer presented longest ago, so the images take turns.
Buffer* best = nullptr;
for (Buffer& buffer : m_buffers) {
if (buffer.Pixmap == 0 || buffer.Busy) continue;
if (best == nullptr || buffer.Serial < best->Serial) best = &buffer;
}
if (best != nullptr) {
const Bool sized = best->Storage.Width == static_cast<Uint32>(m_width) &&
best->Storage.Height == static_cast<Uint32>(m_height);
if (sized || Allocate(*best)) return best;
return nullptr;
}
SizeT allocated = AllocatedBuffers();
if (allocated < kBuffers) {
for (Buffer& buffer : m_buffers) {
if (buffer.Pixmap == 0) return Allocate(buffer) ? &buffer : nullptr;
}
}
// Every buffer is with the X server: wait for one to come back.
const Int64 remaining = deadline - m_nowMs();
Event event;
if (remaining > 0 && m_connection.WaitEvent(&event, remaining)) {
Handle(event);
continue;
}
// None came back in time: one more buffer, up to the limit; past it the frame is
// dropped (the chain is not broken: the server may just be slow).
if (allocated < kMaxBuffers) {
for (Buffer& buffer : m_buffers) {
if (buffer.Pixmap == 0) return Allocate(buffer) ? &buffer : nullptr;
}
}
return nullptr;
}
}
Bool Chain::Present(const MG_Util::Damage::Region& damage, Int swapInterval) {
if (m_broken) return false;
DrainEvents();
if (m_connection.PresentFailed()) Break("the X server refused a PresentPixmap");
if (m_broken) return false;
WaitForPacing(swapInterval);
if (m_broken) return false;
Buffer* buffer = NextFree();
if (buffer == nullptr) return false;
const SizeT index = static_cast<SizeT>(buffer - m_buffers);
const MG_Util::Damage::Region copy = m_damage.TakeForWrite(index, damage, m_width, m_height);
if (!m_images.CopyFrame(buffer->Storage.Id, copy)) {
Break("the frame could not be copied into a shared image");
return false;
}
const Uint32 serial = ++m_serial;
const Uint32 options = swapInterval > 0 ? 0u : kPresentOptionAsync;
const Uint64 targetMsc = swapInterval > 0 && m_lastMsc != 0 ? m_lastMsc + static_cast<Uint64>(swapInterval) : 0;
MG_Util::Damage::Region update = MG_Util::Damage::Region::Full();
if (!damage.IsFull()) update = damage.FlippedY(m_height);
if (!m_connection.PresentPixmap(buffer->Pixmap, serial, options, targetMsc, update)) {
Break("PresentPixmap could not be sent");
return false;
}
buffer->Busy = true;
buffer->Serial = serial;
if (m_throttle.WantsFrameRequest()) {
m_throttle.Requested(m_nowMs());
m_awaitedSerial = serial;
}
m_connection.Flush();
++m_framesPresented;
return true;
}
void Chain::Resize(Int32 width, Int32 height) {
if (width <= 0 || height <= 0 || (width == m_width && height == m_height)) return;
m_width = width;
m_height = height;
// Old-size buffers the X server is not holding go now; the rest as they come back
// (NextFree reallocates a free buffer of the wrong size).
for (Buffer& buffer : m_buffers) {
if (buffer.Pixmap != 0 && !buffer.Busy) Drop(buffer);
}
m_damage.InvalidateAll();
}
Bool Chain::TakeConfiguredSize(Int32* width, Int32* height) {
if (!m_configured) return false;
m_configured = false;
*width = m_configuredWidth;
*height = m_configuredHeight;
return true;
}
} // namespace MobileGL::MG_Impl::GLXImpl::X11Present
+199
View File
@@ -0,0 +1,199 @@
// MobileGL - MobileGL/MG_Impl/GLXImpl/X11Present.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
// GLX WINDOWS PRESENTED THROUGH DRI3 + PRESENT (docs/Disaggregated/notes/anland/plan-x11-gpu.md).
//
// A GLX window's frames are drawn by the server into a pbuffer. Instead of reading each frame back
// and putting it on the window, the frame is copied GPU-side into one of a few server-allocated
// shared images, each imported into the X server once as a pixmap (DRI3 PixmapFromBuffer(s), the
// image's dma-buf), and presented with Present PresentPixmap. An X server drawing with MobileGL
// (Xwayland's glamor) then shows the very same image - attached to its window as a linux-dmabuf
// buffer, or copied on its GPU - and no frame crosses the CPU.
//
// The logic is here, behind two narrow interfaces: Connection (the X side of one window: the DRI3
// import, PresentPixmap, the Present events of a special-event queue) and ImageSource (the server's
// shared images and the GPU copy). X11PresentXcb.cpp implements Connection over libxcb; the host
// tests drive Chain with fakes of both.
//
// Buffers. Up to kBuffers images of the window's size (kMaxBuffers when the X server has held
// every one past kIdleWaitMs); a buffer is busy from its PresentPixmap to its IdleNotify. A
// resize drops each old-size buffer as it comes back idle.
// Pacing. FrameThrottle's rules (EGLImpl/FrameThrottle.h) on CompleteNotify: interval >= 1 waits
// for the previous frame's completion and targets last_msc + interval; interval 0 presents
// PresentOptionAsync, unpaced while completions come, slowed to about one frame a second once
// one is overdue (the X server shows nothing of the window).
// Errors. A refused import, a failed PresentPixmap, a failed copy or the window's destruction
// break the chain for good; its owner falls back to the readback path.
#include <Includes.h>
#include <MG_Util/Damage/Damage.h>
#include "../EGLImpl/FrameThrottle.h"
#include <functional>
namespace MobileGL::MG_Impl::GLXImpl::X11Present {
inline constexpr Uint64 kModifierInvalid = 0x00ffffffffffffffull;
// DRM fourccs: what an X server drawing through GBM imports a depth-24/32 pixmap as.
inline constexpr Uint32 kFourccXrgb8888 = 0x34325258u; // 'XR24'
inline constexpr Uint32 kFourccArgb8888 = 0x34325241u; // 'AR24'
// Present option bits (presentproto).
inline constexpr Uint32 kPresentOptionAsync = 1u;
// ---- which path a window's frames take -------------------------------------------------------
enum class Path { Dri3Present, ShmPutImage, PutImage };
const char* PathName(Path path);
struct ConnectionCaps {
Bool SharedImages = false; // the backend allocates shared images (a split client)
Bool LocalConnection = false; // a unix socket: descriptors can be passed
Uint32 Dri3Major = 0, Dri3Minor = 0;
Uint32 PresentMajor = 0, PresentMinor = 0;
Uint32 ShmMajor = 0, ShmMinor = 0;
};
// The fourcc a window of `depth` is presented in; 0 for a depth this cannot present.
Uint32 FourccForDepth(Uint32 depth);
// DRI3+Present when the connection has both, descriptors can travel, the backend has shared
// images and the depth is 24/32; otherwise MIT-SHM >= 1.2 (fd attach) when local; otherwise
// PutImage. `overrideValue` (MOBILEGL_GLX_PRESENT): "readback" never takes DRI3, "putimage"
// takes neither DRI3 nor MIT-SHM; anything else is automatic.
Path SelectPath(const ConnectionCaps& caps, Uint32 depth, const char* overrideValue);
// ---- the two sides -------------------------------------------------------------------------
struct Image {
Uint64 Id = 0;
int Fd = -1;
Uint32 Width = 0;
Uint32 Height = 0;
Uint32 Stride = 0;
Uint32 Offset = 0;
Uint32 Fourcc = 0;
Uint64 Modifier = kModifierInvalid;
};
class ImageSource {
public:
virtual ~ImageSource() = default;
// A new image; `out->Fd` is the caller's.
virtual Bool Allocate(Uint32 width, Uint32 height, Uint32 fourcc, Image* out) = 0;
virtual void Release(Uint64 id) = 0;
// The current frame into the image, top row first; `region` in GL window coordinates (Full
// = all). True once the copy is submitted and its fence published.
virtual Bool CopyFrame(Uint64 id, const MG_Util::Damage::Region& region) = 0;
};
struct Event {
enum class Kind { None, Idle, Complete, Configure };
Kind Type = Kind::None;
Uint32 Serial = 0;
Uint32 Pixmap = 0;
Uint64 Msc = 0;
Uint8 Mode = 0;
Int32 Width = 0;
Int32 Height = 0;
Bool WindowDestroyed = false;
};
class Connection {
public:
virtual ~Connection() = default;
// A pixmap of `depth` whose storage is the image (its descriptor is duplicated for the
// request; the caller keeps its own). 0 = the X server refused it.
virtual Uint32 ImportPixmap(const Image& image, Uint32 depth) = 0;
virtual void FreePixmap(Uint32 pixmap) = 0;
// Queues a PresentPixmap. `update` is in X coordinates (top-left origin); Full = all of it.
// False when it could not even be sent.
virtual Bool PresentPixmap(Uint32 pixmap, Uint32 serial, Uint32 options, Uint64 targetMsc,
const MG_Util::Damage::Region& update) = 0;
// Whether a PresentPixmap sent earlier is now known to have failed (an X error).
virtual Bool PresentFailed() = 0;
virtual Bool PollEvent(Event* out) = 0;
// Waits up to `timeoutMs` for an event. False: none came (or the connection broke).
virtual Bool WaitEvent(Event* out, Int64 timeoutMs) = 0;
virtual void Flush() = 0;
};
// ---- one window's swap chain ----------------------------------------------------------------
class Chain {
public:
static constexpr SizeT kBuffers = 3;
static constexpr SizeT kMaxBuffers = 4;
static constexpr Int64 kIdleWaitMs = 1000;
// Longest a swap waits for a completion before it stops pacing on it (a server that lost it).
static constexpr Int64 kCompleteGiveUpMs = 5000;
// `nowMs`: a monotonic clock in milliseconds (injected for the tests).
Chain(Connection& connection, ImageSource& images, Uint32 depth, Int32 width, Int32 height,
std::function<Int64()> nowMs);
~Chain();
Chain(const Chain&) = delete;
Chain& operator=(const Chain&) = delete;
// Presents the current frame. `damage` is what it changed (GL window coordinates; Full = all).
// False: the frame was not shown this way - Broken() says whether that is for good.
Bool Present(const MG_Util::Damage::Region& damage, Int swapInterval);
// The window has a new size: the next frame goes into images of that size.
void Resize(Int32 width, Int32 height);
// A size the X server reported (ConfigureNotify) that the owner has not taken yet.
Bool TakeConfiguredSize(Int32* width, Int32* height);
Bool Broken() const { return m_broken; }
const char* BrokenReason() const { return m_brokenReason; }
// For the tests and the log.
SizeT AllocatedBuffers() const;
SizeT BusyBuffers() const;
Uint64 FramesPresented() const { return m_framesPresented; }
Int32 Width() const { return m_width; }
Int32 Height() const { return m_height; }
private:
struct Buffer {
Image Storage;
Uint32 Pixmap = 0;
Bool Busy = false;
Uint32 Serial = 0;
};
void Break(const char* reason);
void Handle(const Event& event);
void DrainEvents();
void WaitForPacing(Int swapInterval);
Buffer* NextFree();
Bool Allocate(Buffer& buffer);
void Drop(Buffer& buffer);
Connection& m_connection;
ImageSource& m_images;
Uint32 m_depth = 24;
Uint32 m_fourcc = kFourccXrgb8888;
Int32 m_width = 0;
Int32 m_height = 0;
std::function<Int64()> m_nowMs;
Buffer m_buffers[kMaxBuffers];
MG_Util::Damage::BufferDamageTracker m_damage{kMaxBuffers};
EGLImpl::Wayland::FrameThrottle m_throttle;
Uint32 m_awaitedSerial = 0;
Uint32 m_serial = 0;
Uint64 m_lastMsc = 0;
Uint64 m_framesPresented = 0;
Bool m_configured = false;
Int32 m_configuredWidth = 0;
Int32 m_configuredHeight = 0;
Bool m_broken = false;
const char* m_brokenReason = "";
};
} // namespace MobileGL::MG_Impl::GLXImpl::X11Present
+522
View File
@@ -0,0 +1,522 @@
// MobileGL - MobileGL/MG_Impl/GLXImpl/X11PresentXcb.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 "X11PresentXcb.h"
#if MOBILEGL_GLX_XCB_PRESENT
#include <MG_Util/Debug/Log.h>
#include <xcb/dri3.h>
#include <xcb/present.h>
#include <xcb/shm.h>
#include <xcb/xcb.h>
#include <xcb/xcbext.h>
#include <xcb/xfixes.h>
#include <cerrno>
#include <chrono>
#include <cstdlib>
#include <cstring>
#include <mutex>
#include <dlfcn.h>
#include <fcntl.h>
#include <poll.h>
#include <sys/mman.h>
#include <sys/socket.h>
#include <unistd.h>
namespace MobileGL::MG_Impl::GLXImpl::X11Present {
namespace {
// presentproto: ConfigureNotify's pixmap_flags when the window is gone (Present 1.2+).
constexpr uint32_t kPresentWindowDestroyed = 1u << 0;
#define MGL_XCB_FN(name) decltype(&::name) name = nullptr
struct XcbApi {
Bool core = false, dri3 = false, present = false, xfixes = false, shm = false;
// libxcb
MGL_XCB_FN(xcb_generate_id);
MGL_XCB_FN(xcb_flush);
MGL_XCB_FN(xcb_get_extension_data);
MGL_XCB_FN(xcb_request_check);
MGL_XCB_FN(xcb_poll_for_reply);
MGL_XCB_FN(xcb_discard_reply);
MGL_XCB_FN(xcb_get_file_descriptor);
MGL_XCB_FN(xcb_connection_has_error);
MGL_XCB_FN(xcb_register_for_special_xge);
MGL_XCB_FN(xcb_unregister_for_special_event);
MGL_XCB_FN(xcb_poll_for_special_event);
MGL_XCB_FN(xcb_free_pixmap_checked);
MGL_XCB_FN(xcb_get_input_focus);
MGL_XCB_FN(xcb_get_input_focus_reply);
// libxcb-dri3
xcb_extension_t* dri3Id = nullptr;
MGL_XCB_FN(xcb_dri3_query_version);
MGL_XCB_FN(xcb_dri3_query_version_reply);
MGL_XCB_FN(xcb_dri3_pixmap_from_buffer_checked);
MGL_XCB_FN(xcb_dri3_pixmap_from_buffers_checked);
// libxcb-present
xcb_extension_t* presentId = nullptr;
MGL_XCB_FN(xcb_present_query_version);
MGL_XCB_FN(xcb_present_query_version_reply);
MGL_XCB_FN(xcb_present_select_input_checked);
MGL_XCB_FN(xcb_present_pixmap_checked);
// libxcb-xfixes
xcb_extension_t* xfixesId = nullptr;
MGL_XCB_FN(xcb_xfixes_query_version);
MGL_XCB_FN(xcb_xfixes_query_version_reply);
MGL_XCB_FN(xcb_xfixes_create_region);
MGL_XCB_FN(xcb_xfixes_destroy_region);
// libxcb-shm
xcb_extension_t* shmId = nullptr;
MGL_XCB_FN(xcb_shm_query_version);
MGL_XCB_FN(xcb_shm_query_version_reply);
MGL_XCB_FN(xcb_shm_attach_fd_checked);
MGL_XCB_FN(xcb_shm_detach);
MGL_XCB_FN(xcb_shm_put_image);
};
#undef MGL_XCB_FN
void* OpenLibrary(const char* name) {
void* lib = dlopen(name, RTLD_NOW | RTLD_NOLOAD);
return lib != nullptr ? lib : dlopen(name, RTLD_NOW | RTLD_LOCAL);
}
template <typename Fn>
Bool Resolve(void* lib, const char* name, Fn& out) {
out = lib != nullptr ? reinterpret_cast<Fn>(dlsym(lib, name)) : nullptr;
return out != nullptr;
}
const XcbApi& Api() {
static const XcbApi* api = [] {
auto* a = new XcbApi();
void* xcb = OpenLibrary("libxcb.so.1");
#define R(lib, fn) Resolve(lib, #fn, a->fn)
a->core = R(xcb, xcb_generate_id) & R(xcb, xcb_flush) & R(xcb, xcb_get_extension_data) &
R(xcb, xcb_request_check) & R(xcb, xcb_poll_for_reply) & R(xcb, xcb_discard_reply) &
R(xcb, xcb_get_file_descriptor) & R(xcb, xcb_connection_has_error) &
R(xcb, xcb_register_for_special_xge) & R(xcb, xcb_unregister_for_special_event) &
R(xcb, xcb_poll_for_special_event) & R(xcb, xcb_free_pixmap_checked) &
R(xcb, xcb_get_input_focus) & R(xcb, xcb_get_input_focus_reply);
if (a->core) {
void* dri3 = OpenLibrary("libxcb-dri3.so.0");
a->dri3Id = dri3 != nullptr ? static_cast<xcb_extension_t*>(dlsym(dri3, "xcb_dri3_id")) : nullptr;
a->dri3 = a->dri3Id != nullptr && R(dri3, xcb_dri3_query_version) &
R(dri3, xcb_dri3_query_version_reply) &
R(dri3, xcb_dri3_pixmap_from_buffer_checked);
// 1.2's multi-plane request is optional: an older libxcb-dri3 has only 1.0's.
(void)R(dri3, xcb_dri3_pixmap_from_buffers_checked);
void* present = OpenLibrary("libxcb-present.so.0");
a->presentId =
present != nullptr ? static_cast<xcb_extension_t*>(dlsym(present, "xcb_present_id")) : nullptr;
a->present = a->presentId != nullptr && R(present, xcb_present_query_version) &
R(present, xcb_present_query_version_reply) &
R(present, xcb_present_select_input_checked) &
R(present, xcb_present_pixmap_checked);
void* xfixes = OpenLibrary("libxcb-xfixes.so.0");
a->xfixesId =
xfixes != nullptr ? static_cast<xcb_extension_t*>(dlsym(xfixes, "xcb_xfixes_id")) : nullptr;
a->xfixes = a->xfixesId != nullptr && R(xfixes, xcb_xfixes_query_version) &
R(xfixes, xcb_xfixes_query_version_reply) &
R(xfixes, xcb_xfixes_create_region) &
R(xfixes, xcb_xfixes_destroy_region);
void* shm = OpenLibrary("libxcb-shm.so.0");
a->shmId = shm != nullptr ? static_cast<xcb_extension_t*>(dlsym(shm, "xcb_shm_id")) : nullptr;
a->shm = a->shmId != nullptr && R(shm, xcb_shm_query_version) &
R(shm, xcb_shm_query_version_reply) &
R(shm, xcb_shm_attach_fd_checked) & R(shm, xcb_shm_detach) &
R(shm, xcb_shm_put_image);
}
#undef R
return a;
}();
return *api;
}
xcb_connection_t* Xcb(void* connection) { return static_cast<xcb_connection_t*>(connection); }
Bool ExtensionPresent(xcb_connection_t* c, xcb_extension_t* id) {
const XcbApi& api = Api();
if (id == nullptr) return false;
const xcb_query_extension_reply_t* data = api.xcb_get_extension_data(c, id);
return data != nullptr && data->present != 0;
}
struct CachedCaps {
void* Connection = nullptr;
ConnectionCaps Caps;
Bool XFixes = false;
};
std::mutex& CapsMutex() {
static auto* mutex = new std::mutex();
return *mutex;
}
Vector<CachedCaps>& CapsCache() {
static auto* cache = new Vector<CachedCaps>();
return *cache;
}
CachedCaps Query(void* connection) {
const std::lock_guard<std::mutex> lock(CapsMutex());
for (const CachedCaps& cached : CapsCache()) {
if (cached.Connection == connection) return cached;
}
CachedCaps result;
result.Connection = connection;
const XcbApi& api = Api();
xcb_connection_t* c = Xcb(connection);
if (!api.core || c == nullptr || api.xcb_connection_has_error(c)) return result;
sockaddr_storage address{};
socklen_t length = sizeof(address);
if (::getsockname(api.xcb_get_file_descriptor(c), reinterpret_cast<sockaddr*>(&address), &length) == 0)
result.Caps.LocalConnection = address.ss_family == AF_UNIX;
if (api.dri3 && ExtensionPresent(c, api.dri3Id)) {
if (auto* reply = api.xcb_dri3_query_version_reply(c, api.xcb_dri3_query_version(c, 1, 2), nullptr)) {
result.Caps.Dri3Major = reply->major_version;
result.Caps.Dri3Minor = reply->minor_version;
std::free(reply);
}
}
if (api.present && ExtensionPresent(c, api.presentId)) {
if (auto* reply =
api.xcb_present_query_version_reply(c, api.xcb_present_query_version(c, 1, 2), nullptr)) {
result.Caps.PresentMajor = reply->major_version;
result.Caps.PresentMinor = reply->minor_version;
std::free(reply);
}
}
// XFixes demands its version be asked before any other request of it.
if (api.xfixes && ExtensionPresent(c, api.xfixesId)) {
if (auto* reply = api.xcb_xfixes_query_version_reply(c, api.xcb_xfixes_query_version(c, 5, 0), nullptr)) {
result.XFixes = reply->major_version >= 2;
std::free(reply);
}
}
if (api.shm && ExtensionPresent(c, api.shmId)) {
if (auto* reply = api.xcb_shm_query_version_reply(c, api.xcb_shm_query_version(c), nullptr)) {
result.Caps.ShmMajor = reply->major_version;
result.Caps.ShmMinor = reply->minor_version;
std::free(reply);
}
}
CapsCache().push_back(result);
return result;
}
Int64 NowMs() {
return std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now().time_since_epoch())
.count();
}
Bool Translate(const xcb_generic_event_t* raw, Event* out) {
const auto* generic = reinterpret_cast<const xcb_present_generic_event_t*>(raw);
*out = Event{};
switch (generic->evtype) {
case XCB_PRESENT_EVENT_IDLE_NOTIFY: {
const auto* idle = reinterpret_cast<const xcb_present_idle_notify_event_t*>(raw);
out->Type = Event::Kind::Idle;
out->Serial = idle->serial;
out->Pixmap = idle->pixmap;
return true;
}
case XCB_PRESENT_EVENT_COMPLETE_NOTIFY: {
const auto* complete = reinterpret_cast<const xcb_present_complete_notify_event_t*>(raw);
if (complete->kind != XCB_PRESENT_COMPLETE_KIND_PIXMAP) return false;
out->Type = Event::Kind::Complete;
out->Serial = complete->serial;
out->Msc = complete->msc;
out->Mode = complete->mode;
return true;
}
case XCB_PRESENT_EVENT_CONFIGURE_NOTIFY: {
const auto* configure = reinterpret_cast<const xcb_present_configure_notify_event_t*>(raw);
out->Type = Event::Kind::Configure;
out->Width = configure->width;
out->Height = configure->height;
out->WindowDestroyed = (configure->pixmap_flags & kPresentWindowDestroyed) != 0;
return true;
}
default:
return false;
}
}
class XcbConnection final : public Connection {
public:
XcbConnection(xcb_connection_t* c, Uint32 window, Bool buffers12, Bool xfixes)
: m_c(c), m_window(window), m_buffers12(buffers12), m_xfixes(xfixes) {}
Bool Init() {
const XcbApi& api = Api();
m_eid = api.xcb_generate_id(m_c);
m_special = api.xcb_register_for_special_xge(m_c, Api().presentId, m_eid, &m_stamp);
if (m_special == nullptr) return false;
const xcb_void_cookie_t cookie = api.xcb_present_select_input_checked(
m_c, m_eid, m_window,
XCB_PRESENT_EVENT_MASK_CONFIGURE_NOTIFY | XCB_PRESENT_EVENT_MASK_COMPLETE_NOTIFY |
XCB_PRESENT_EVENT_MASK_IDLE_NOTIFY);
if (xcb_generic_error_t* error = api.xcb_request_check(m_c, cookie)) {
std::free(error);
return false;
}
return true;
}
~XcbConnection() override {
const XcbApi& api = Api();
if (m_hasPendingPresent) api.xcb_discard_reply(m_c, m_pendingPresent);
if (m_special != nullptr) {
const xcb_void_cookie_t cookie =
api.xcb_present_select_input_checked(m_c, m_eid, m_window, XCB_PRESENT_EVENT_MASK_NO_EVENT);
// The window may be gone already: an error here is expected and dropped.
api.xcb_discard_reply(m_c, cookie.sequence);
api.xcb_unregister_for_special_event(m_c, m_special);
}
api.xcb_flush(m_c);
}
Uint32 ImportPixmap(const Image& image, Uint32 depth) override {
const XcbApi& api = Api();
// libxcb closes the descriptor it sends.
const int fd = ::fcntl(image.Fd, F_DUPFD_CLOEXEC, 0);
if (fd < 0) return 0;
const Uint32 pixmap = api.xcb_generate_id(m_c);
xcb_void_cookie_t cookie{};
if (m_buffers12 && api.xcb_dri3_pixmap_from_buffers_checked != nullptr) {
int32_t fds[1] = {fd};
cookie = api.xcb_dri3_pixmap_from_buffers_checked(
m_c, pixmap, m_window, 1, static_cast<uint16_t>(image.Width), static_cast<uint16_t>(image.Height),
image.Stride, image.Offset, 0, 0, 0, 0, 0, 0, static_cast<uint8_t>(depth), 32, image.Modifier, fds);
} else {
if (image.Offset != 0 || image.Stride > 0xffffu) {
::close(fd);
return 0;
}
cookie = api.xcb_dri3_pixmap_from_buffer_checked(
m_c, pixmap, m_window, image.Stride * image.Height, static_cast<uint16_t>(image.Width),
static_cast<uint16_t>(image.Height), static_cast<uint16_t>(image.Stride),
static_cast<uint8_t>(depth), 32, fd);
}
if (xcb_generic_error_t* error = api.xcb_request_check(m_c, cookie)) {
MGLOG_I("glx: the X server refused a %ux%u shared image as a pixmap (X error %u, major %u minor %u)",
image.Width, image.Height, error->error_code, error->major_code, error->minor_code);
std::free(error);
return 0;
}
return pixmap;
}
void FreePixmap(Uint32 pixmap) override {
const XcbApi& api = Api();
api.xcb_discard_reply(m_c, api.xcb_free_pixmap_checked(m_c, pixmap).sequence);
}
Bool PresentPixmap(Uint32 pixmap, Uint32 serial, Uint32 options, Uint64 targetMsc,
const MG_Util::Damage::Region& update) override {
const XcbApi& api = Api();
if (api.xcb_connection_has_error(m_c)) return false;
Uint32 region = 0;
if (!update.IsFull() && m_xfixes) {
Vector<xcb_rectangle_t> rects;
for (const MG_Util::Damage::Rect& rect : update.Rects()) {
rects.push_back({static_cast<int16_t>(rect.X), static_cast<int16_t>(rect.Y),
static_cast<uint16_t>(rect.Width), static_cast<uint16_t>(rect.Height)});
}
if (!rects.empty()) {
region = api.xcb_generate_id(m_c);
api.xcb_xfixes_create_region(m_c, region, static_cast<uint32_t>(rects.size()), rects.data());
}
}
// An earlier present whose answer never came is given up on, not left queued.
if (m_hasPendingPresent) api.xcb_discard_reply(m_c, m_pendingPresent);
const xcb_void_cookie_t cookie =
api.xcb_present_pixmap_checked(m_c, m_window, pixmap, serial, 0, region, 0, 0, 0, 0, 0, options,
targetMsc, 0, 0, 0, nullptr);
m_pendingPresent = cookie.sequence;
m_hasPendingPresent = true;
if (region != 0) api.xcb_xfixes_destroy_region(m_c, region);
return true;
}
Bool PresentFailed() override {
const XcbApi& api = Api();
if (m_failed || !m_hasPendingPresent) return m_failed;
void* reply = nullptr;
xcb_generic_error_t* error = nullptr;
// Known once anything later has come back (an event carries the sequence): no round trip.
if (api.xcb_poll_for_reply(m_c, m_pendingPresent, &reply, &error) != 0) {
m_hasPendingPresent = false;
if (error != nullptr) {
MGLOG_I("glx: PresentPixmap failed (X error %u)", error->error_code);
m_failed = true;
}
std::free(reply);
std::free(error);
}
return m_failed;
}
Bool PollEvent(Event* out) override {
const XcbApi& api = Api();
for (;;) {
xcb_generic_event_t* raw = api.xcb_poll_for_special_event(m_c, m_special);
if (raw == nullptr) return false;
const Bool known = Translate(raw, out);
std::free(raw);
if (known) return true;
}
}
// Short poll slices: another thread (the application's event loop) may be the one
// reading the socket, and its read moves our events into the special queue.
Bool WaitEvent(Event* out, Int64 timeoutMs) override {
const XcbApi& api = Api();
api.xcb_flush(m_c);
const Int64 deadline = NowMs() + timeoutMs;
for (;;) {
if (PollEvent(out)) return true;
if (api.xcb_connection_has_error(m_c)) return false;
const Int64 remaining = deadline - NowMs();
if (remaining <= 0) return false;
pollfd p{api.xcb_get_file_descriptor(m_c), POLLIN, 0};
(void)::poll(&p, 1, static_cast<int>(std::min<Int64>(remaining, 4)));
}
}
void Flush() override { Api().xcb_flush(m_c); }
private:
xcb_connection_t* m_c = nullptr;
Uint32 m_window = 0;
Bool m_buffers12 = false;
Bool m_xfixes = false;
Uint32 m_eid = 0;
uint32_t m_stamp = 0;
xcb_special_event_t* m_special = nullptr;
unsigned int m_pendingPresent = 0;
Bool m_hasPendingPresent = false;
Bool m_failed = false;
};
class XcbShmPresenter final : public ShmPresenter {
public:
explicit XcbShmPresenter(xcb_connection_t* c) : m_c(c) {}
~XcbShmPresenter() override {
for (Segment& segment : m_segments) Release(segment);
Api().xcb_flush(m_c);
}
Bool Put(Uint32 drawable, Uint32 gc, Uint32 depth, Int32 width, Int32 height,
const std::function<void(Uint8*, SizeT)>& fill) override {
const XcbApi& api = Api();
if (width <= 0 || height <= 0 || width > 0xffff || height > 0xffff) return false;
Segment& segment = m_segments[m_next];
m_next = (m_next + 1) % 2;
// The X server may still be reading this segment's last frame: the round trip queued
// behind that put coming back says it is done with it.
if (segment.HasSync) {
std::free(api.xcb_get_input_focus_reply(m_c, segment.Sync, nullptr));
segment.HasSync = false;
}
const SizeT stride = static_cast<SizeT>(width) * 4;
const SizeT size = stride * static_cast<SizeT>(height);
if (segment.Size < size && !Make(segment, size)) return false;
fill(static_cast<Uint8*>(segment.Map), stride);
api.xcb_shm_put_image(m_c, drawable, gc, static_cast<uint16_t>(width), static_cast<uint16_t>(height), 0,
0, static_cast<uint16_t>(width), static_cast<uint16_t>(height), 0, 0,
static_cast<uint8_t>(depth), XCB_IMAGE_FORMAT_Z_PIXMAP, 0, segment.Seg, 0);
segment.Sync = api.xcb_get_input_focus(m_c);
segment.HasSync = true;
api.xcb_flush(m_c);
return true;
}
private:
struct Segment {
Uint32 Seg = 0;
void* Map = nullptr;
SizeT Size = 0;
xcb_get_input_focus_cookie_t Sync{};
Bool HasSync = false;
};
void Release(Segment& segment) {
const XcbApi& api = Api();
if (segment.HasSync) std::free(api.xcb_get_input_focus_reply(m_c, segment.Sync, nullptr));
if (segment.Seg != 0) api.xcb_shm_detach(m_c, segment.Seg);
if (segment.Map != nullptr) ::munmap(segment.Map, segment.Size);
segment = Segment{};
}
Bool Make(Segment& segment, SizeT size) {
const XcbApi& api = Api();
Release(segment);
const int fd = ::memfd_create("mobilegl-glx-shm", MFD_CLOEXEC);
if (fd < 0) return false;
if (::ftruncate(fd, static_cast<off_t>(size)) != 0) {
::close(fd);
return false;
}
void* map = ::mmap(nullptr, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if (map == MAP_FAILED) {
::close(fd);
return false;
}
const Uint32 seg = api.xcb_generate_id(m_c);
// libxcb sends, then closes, the descriptor; the mapping stays.
const xcb_void_cookie_t cookie = api.xcb_shm_attach_fd_checked(m_c, seg, fd, 1);
if (xcb_generic_error_t* error = api.xcb_request_check(m_c, cookie)) {
std::free(error);
::munmap(map, size);
return false;
}
segment.Seg = seg;
segment.Map = map;
segment.Size = size;
return true;
}
xcb_connection_t* m_c = nullptr;
Segment m_segments[2];
SizeT m_next = 0;
};
} // namespace
ConnectionCaps QueryConnectionCaps(void* xcbConnection) { return Query(xcbConnection).Caps; }
UniquePtr<Connection> CreateXcbConnection(void* xcbConnection, Uint32 window, const ConnectionCaps& caps) {
const XcbApi& api = Api();
if (!api.core || !api.dri3 || !api.present || caps.Dri3Major < 1 || caps.PresentMajor < 1) return nullptr;
const CachedCaps cached = Query(xcbConnection);
const Bool buffers12 = caps.Dri3Major > 1 || (caps.Dri3Major == 1 && caps.Dri3Minor >= 2);
auto connection = MakeUnique<XcbConnection>(Xcb(xcbConnection), window, buffers12, cached.XFixes);
if (!connection->Init()) return nullptr;
return connection;
}
UniquePtr<ShmPresenter> CreateShmPresenter(void* xcbConnection) {
const XcbApi& api = Api();
if (!api.core || !api.shm || xcbConnection == nullptr) return nullptr;
return MakeUnique<XcbShmPresenter>(Xcb(xcbConnection));
}
} // namespace MobileGL::MG_Impl::GLXImpl::X11Present
#else // !MOBILEGL_GLX_XCB_PRESENT
namespace MobileGL::MG_Impl::GLXImpl::X11Present {
ConnectionCaps QueryConnectionCaps(void*) { return {}; }
UniquePtr<Connection> CreateXcbConnection(void*, Uint32, const ConnectionCaps&) { return nullptr; }
UniquePtr<ShmPresenter> CreateShmPresenter(void*) { return nullptr; }
} // namespace MobileGL::MG_Impl::GLXImpl::X11Present
#endif
+48
View File
@@ -0,0 +1,48 @@
// MobileGL - MobileGL/MG_Impl/GLXImpl/X11PresentXcb.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
// The X side of X11Present over libxcb: DRI3, Present, XFixes and MIT-SHM on the application's own
// connection (XGetXCBConnection of its Display - this library never opens one). Every libxcb entry
// point is resolved at run time, like the rest of the GLX layer, so nothing links libxcb; the
// protocol headers are only needed at build time, and a build without them has no DRI3 path
// (MOBILEGL_GLX_XCB_PRESENT is 0 and every window takes the readback path).
#include "X11Present.h"
#if defined(__linux__) && !defined(__ANDROID__) && __has_include(<xcb/dri3.h>) && __has_include(<xcb/present.h>) && \
__has_include(<xcb/xfixes.h>) && __has_include(<xcb/shm.h>)
#define MOBILEGL_GLX_XCB_PRESENT 1
#else
#define MOBILEGL_GLX_XCB_PRESENT 0
#endif
namespace MobileGL::MG_Impl::GLXImpl::X11Present {
// What the connection offers (queried once per connection). SharedImages is left false: that
// one is the backend's to answer.
ConnectionCaps QueryConnectionCaps(void* xcbConnection);
// A window's Present events on a special-event queue of their own, its DRI3 imports and its
// PresentPixmaps. Null when the connection lacks DRI3/Present or the queue cannot be set up.
UniquePtr<Connection> CreateXcbConnection(void* xcbConnection, Uint32 window, const ConnectionCaps& caps);
// THE MIT-SHM FALLBACK: frames read back into a shared segment (a memfd passed with
// ShmAttachFd, so no SysV memory has to be shared with the X server) and put with ShmPutImage -
// the pixels reach the X server without travelling down its socket. Two segments, alternating;
// a segment is written again only after a round trip queued behind its last put has come back.
class ShmPresenter {
public:
virtual ~ShmPresenter() = default;
// `fill(rows, stride)` writes a width x height top-down 32bpp frame; then it is put on
// `drawable` with `gc` at (0,0). False: not shown (the segment could not be made).
virtual Bool Put(Uint32 drawable, Uint32 gc, Uint32 depth, Int32 width, Int32 height,
const std::function<void(Uint8*, SizeT)>& fill) = 0;
};
UniquePtr<ShmPresenter> CreateShmPresenter(void* xcbConnection);
} // namespace MobileGL::MG_Impl::GLXImpl::X11Present
+35
View File
@@ -29,6 +29,26 @@ extern "C" EGLBoolean eglQueryDmaBufModifiersEXT(EGLDisplay dpy, EGLint format,
khronos_uint64_t* modifiers, EGLBoolean* external_only,
EGLint* num_modifiers);
extern "C" void glEGLImageTargetTexture2DOES(GLenum target, GLeglImageOES image);
// EGL_KHR_fence_sync / EGL_KHR_wait_sync / EGL_ANDROID_native_fence_sync (Definitions.cpp).
extern "C" EGLSync eglCreateSyncKHR(EGLDisplay dpy, EGLenum type, const EGLint* attrib_list);
extern "C" EGLBoolean eglDestroySyncKHR(EGLDisplay dpy, EGLSync sync);
extern "C" EGLint eglClientWaitSyncKHR(EGLDisplay dpy, EGLSync sync, EGLint flags, EGLTime timeout);
extern "C" EGLBoolean eglGetSyncAttribKHR(EGLDisplay dpy, EGLSync sync, EGLint attribute, EGLint* value);
extern "C" EGLint eglWaitSyncKHR(EGLDisplay dpy, EGLSync sync, EGLint flags);
extern "C" EGLint eglDupNativeFenceFDANDROID(EGLDisplay dpy, EGLSync sync);
// KHR_robustness / EXT_robustness suffixed names (Definitions.cpp); the desktop headers declare
// only the unsuffixed and ARB ones.
extern "C" GLenum glGetGraphicsResetStatusKHR(void);
extern "C" GLenum glGetGraphicsResetStatusEXT(void);
extern "C" void glReadnPixelsKHR(GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type,
GLsizei bufSize, void* data);
extern "C" void glReadnPixelsEXT(GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type,
GLsizei bufSize, void* data);
extern "C" void glGetnUniformfvKHR(GLuint program, GLint location, GLsizei bufSize, GLfloat* params);
extern "C" void glGetnUniformfvEXT(GLuint program, GLint location, GLsizei bufSize, GLfloat* params);
extern "C" void glGetnUniformivKHR(GLuint program, GLint location, GLsizei bufSize, GLint* params);
extern "C" void glGetnUniformivEXT(GLuint program, GLint location, GLsizei bufSize, GLint* params);
extern "C" void glGetnUniformuivKHR(GLuint program, GLint location, GLsizei bufSize, GLuint* params);
#define GETPROC(name, var) \
if (strcmp(#name, var) == 0) { \
@@ -76,6 +96,12 @@ namespace MobileGL::MG_Impl {
GETPROC(eglDestroySync, name);
GETPROC(eglClientWaitSync, name);
GETPROC(eglGetSyncAttrib, name);
GETPROC(eglCreateSyncKHR, name);
GETPROC(eglDestroySyncKHR, name);
GETPROC(eglClientWaitSyncKHR, name);
GETPROC(eglGetSyncAttribKHR, name);
GETPROC(eglWaitSyncKHR, name);
GETPROC(eglDupNativeFenceFDANDROID, name);
GETPROC(eglCreateImage, name);
GETPROC(eglDestroyImage, name);
GETPROC(eglCreateImageKHR, name);
@@ -876,6 +902,15 @@ namespace MobileGL::MG_Impl {
GETPROC(glGetnUniformivARB, name);
GETPROC(glGetnUniformuivARB, name);
GETPROC(glGetnUniformdvARB, name);
GETPROC(glGetGraphicsResetStatusKHR, name);
GETPROC(glGetGraphicsResetStatusEXT, name);
GETPROC(glReadnPixelsKHR, name);
GETPROC(glReadnPixelsEXT, name);
GETPROC(glGetnUniformfvKHR, name);
GETPROC(glGetnUniformfvEXT, name);
GETPROC(glGetnUniformivKHR, name);
GETPROC(glGetnUniformivEXT, name);
GETPROC(glGetnUniformuivKHR, name);
GETPROC(glFramebufferSampleLocationsfvARB, name);
GETPROC(glNamedFramebufferSampleLocationsfvARB, name);
GETPROC(glEvaluateDepthValuesARB, name);
+16 -10
View File
@@ -524,22 +524,28 @@ namespace MobileGL::MG_Pipe {
out.Target = static_cast<Uint8>(target);
out.IsDefault = fbo.IsDefaultFramebuffer() ? 1 : 0;
// THE COLOUR POINTS. A default framebuffer keeps its one colour surface under
// BackLeft rather than under Color0, and the record has exactly one place to put
// it: Color[0], which is also the index MGPipeDrawBufferIndex maps that token to,
// so the array and the draw-buffer indices agree by construction.
if (out.IsDefault != 0) {
out.Color[0] = SurfaceOf(fbo, FramebufferAttachmentType::BackLeft);
} else {
// THE SURFACES - and a DEFAULT framebuffer's record names none. Its storage on the
// server is the surface the context is current on (the native window or pbuffer,
// Magma's swapchain); both servers answer every default-framebuffer question from
// IsDefault and never resolve a surface of this record. The frontend's attachments
// are placeholders: one process-wide set of textures every context's framebuffer 0
// shares, created once, so their records live in the ONE share group that was
// bound when they were born. Naming them here sent every other group a handle it
// holds no record for ("texture {12, 0} has no applier resource record" on each of
// its draws) and marked bind bits on them under whichever context drew next.
// Publishing them into every group instead would build a driver texture per group
// for storage nothing reads. The extent still comes from them (FillGeometry), and
// the draw-buffer indices below still map BackLeft to slot 0.
if (out.IsDefault == 0) {
for (SizeT i = 0; i < kMGPipeMaxColorAttachments; ++i) {
out.Color[i] = SurfaceOf(fbo, static_cast<FramebufferAttachmentType>(
static_cast<Int>(FramebufferAttachmentType::Color0) +
static_cast<Int>(i)));
}
out.Depth = SurfaceOf(fbo, FramebufferAttachmentType::Depth);
out.Stencil = SurfaceOf(fbo, FramebufferAttachmentType::Stencil);
out.ReadSurface = SurfaceOf(fbo, fbo.GetReadBuffer());
}
out.Depth = SurfaceOf(fbo, FramebufferAttachmentType::Depth);
out.Stencil = SurfaceOf(fbo, FramebufferAttachmentType::Stencil);
out.ReadSurface = SurfaceOf(fbo, fbo.GetReadBuffer());
const auto& drawBuffers = fbo.GetDrawBuffers();
for (SizeT i = 0; i < kMGPipeMaxColorAttachments; ++i) {
+14
View File
@@ -3987,6 +3987,20 @@ namespace MobileGL::MG_Pipe {
#endif
}
void MGPipeClientDrainTextureUploads() {
if (MG_Config::Transport == MG_Config::TransportMode::Monolith) return;
if (MG_Remote::Client::RunsAsTheServerRole()) return;
auto* ctx = LiveContext();
if (ctx == nullptr) return;
const Uint64 pushMask = MG_Config::Features.PipePush;
if ((pushMask & kMGPipeSubsystemTextureResources) != 0 &&
(kMGPipeWiredSubsystems & kMGPipeSubsystemTextureResources) != 0 &&
P4aFamilyHasItsConsumer(kMGPipeSubsystemTextureResources) &&
P4aFamilyDependenciesAreSet(kMGPipeSubsystemTextureResources, pushMask)) {
(void)MGPipeTextureEmitterInstance().DrainTextureSubData(*ctx);
}
}
#if MOBILEGL_BUILD_DISAGGREGATED
// Declared in PipeMutation.h, where the list is argued. THE ORDER: the latch goes first, so
// everything after it - a pin's last owner dying, a deferred destroy replayed, an evicted
+6 -6
View File
@@ -576,12 +576,12 @@ namespace MobileGL::MG_Pipe {
// here - a content-addressed CSO has no frontend object whose death is being
// announced, which is precisely why this eviction is the only death path it has.
//
// THE DELETE REACHES THE BOUND SHARE GROUP ONLY, so it is sent only when that group
// holds the record; a group that was never sent the create would count
// it as a refused object call. Other groups keep an unreferenced record at this slot
// (nothing may name it: the count is 0) until a create for the slot's next
// generation is published there and starts it over, or the group is torn down.
if (IsPublishedIn(m_entries[index], MGPipeCurrentShareGroupToken())) {
// THE DELETE ENDS THE HANDLE IN EVERY SHARE GROUP IT WAS PUBLISHED TO, not only the
// bound one: the applier drops a sampler CSO from every group of its session
// (MGPipeApplyDeleteSamplerState), because the handle this frees is one identity for
// the whole session. So it is sent whenever ANY group was sent the create - and not
// at all for an entry no group holds, which the applier would count as a refusal.
if (m_entries[index].PublishedGroupCount != 0) {
MGPipeRouteDeleteSamplerState(handle);
}
// AND THE LATCH GOES WITH THE DELETE. This is the "an emitter that drops a record
+17 -1
View File
@@ -1166,7 +1166,10 @@ namespace MobileGL::MG_Pipe {
if (present == key) return;
}
entry.DrainKeys.push_back(key);
m_drain.push_back(DrainEntry{handle, key});
// The share group the texels are owed to: the one the stream is bound to while the
// GL call that wrote them runs (GLStreamScope binds it to the writing thread's
// context, whose group the texture is in). See DrainTextureSubData.
m_drain.push_back(DrainEntry{handle, key, MGPipeCurrentShareGroupToken()});
}
// The DRAIN, at the validate point: one resource_subdata per dirty (storage owner,
@@ -1189,7 +1192,19 @@ namespace MobileGL::MG_Pipe {
m_draining = true;
Uint64 bytes = 0;
Vector<DrainEntry> retry;
// ONLY THE BOUND SHARE GROUP'S TEXELS. The list is the process's, and the validate
// point that drains it belongs to whichever thread draws next - in a client whose
// threads draw with contexts of different share groups, often not the group that
// wrote the texels. Its records would land in the drawing context's group, where the
// texture has no record, and the level's dirty flag would be cleared all the same:
// the texture's own context then sampled a texture that never got its texels. A
// level owed to another group waits for a verb of that group.
const Uint64 group = MGPipeCurrentShareGroupToken();
for (const DrainEntry& pending : m_drain) {
if (pending.Group != group) {
retry.push_back(pending);
continue;
}
if (EmitOneLevel(pending, bytes)) continue;
retry.push_back(pending);
}
@@ -1319,6 +1334,7 @@ namespace MobileGL::MG_Pipe {
struct DrainEntry {
MGPipeHandle Handle;
Uint32 Key;
Uint64 Group; // MGPipeCurrentShareGroupToken() when the level went dirty
};
static constexpr Uint32 PackLevelKey(MobileGL::TextureUploadTarget uploadTarget, Uint level) {
+13
View File
@@ -2013,6 +2013,16 @@ namespace MobileGL::MG_Pipe {
// (EGL_KHR_partial_update) before it draws.
// SetDamageRegion eglSetDamageRegionKHR for the current draw surface: Damage is the region
// the frame is about to draw (GL window coordinates; 0 rectangles = all of it).
// Flush glFlush/glFinish of a session that renders INTO images (an X server's glamor):
// every image the session used since its last boundary is published as written
// and read by the flush's fence (implicit sync); answered once published.
// NativeFence EGL_ANDROID_native_fence_sync's fence command: a sync_file that signals
// once everything the session submitted so far has completed (and, in a session
// that writes images, what Flush does)
// reaches the client on the aux socket BEFORE the reply is posted, with the reply's
// Format = kMGPNativeFenceFdFollows. Format = 0: the server has no descriptor to give
// (it cannot export fences, and none it gave before can stand in), and the work has
// completed by the time the reply is posted.
//
// A Present carries the region of the frame to copy (DamageCount rectangles of Damage, GL
// window coordinates, origin bottom-left; 0 = all of it): the client keeps per image what the
@@ -2028,8 +2038,11 @@ namespace MobileGL::MG_Pipe {
kMGPSharedImageAttach = 5,
kMGPSharedImageQueryBufferAge = 6,
kMGPSharedImageSetDamageRegion = 7,
kMGPSharedImageFlush = 8,
kMGPSharedImageNativeFence = 9,
};
inline constexpr Uint32 kMGPBufferAgeDamageRegionFollows = 1u;
inline constexpr Uint32 kMGPNativeFenceFdFollows = 1u;
struct MGPSharedImageOp {
Uint32 Op;
+94 -1
View File
@@ -54,6 +54,7 @@
#include <algorithm>
#include <atomic>
#include <chrono>
#include <cmath>
#include <cstdarg>
#include <cstdio>
@@ -209,6 +210,47 @@ namespace MobileGL::MG_Pipe {
return true;
}
bool MGPipeDebugSessionLossDue(unsigned clientPid) {
if (clientPid == 0) return false;
// The first call on a thread only starts the clock, so a session is first asked 100 ms
// after it started rendering - never in the middle of its first make-current.
thread_local auto lastAsked = std::chrono::steady_clock::time_point{};
const auto now = std::chrono::steady_clock::now();
if (lastAsked == std::chrono::steady_clock::time_point{}) {
lastAsked = now;
return false;
}
if (now - lastAsked < std::chrono::milliseconds(100)) return false;
lastAsked = now;
long target = 0;
if (const char* value = std::getenv("MOBILEGL_DEBUG_INJECT_DEVICE_LOST_PID")) {
target = std::strtol(value, nullptr, 10);
}
#if defined(__ANDROID__)
else {
char property[PROP_VALUE_MAX] = {};
if (__system_property_get("debug.mobilegl.inject_device_lost_pid", property) > 0) {
target = std::strtol(property, nullptr, 10);
}
}
#endif
// Once per value: the session it hit is over, and a later session of the same process (the
// recovery's) must not be lost again by the same setting. Another pid - or unset/0 and
// then the same one - re-arms it.
static std::atomic<long> firedFor{0};
if (target <= 0) {
if (firedFor.load(std::memory_order_relaxed) != 0) firedFor.store(0, std::memory_order_relaxed);
return false;
}
if (static_cast<unsigned long>(target) != clientPid) return false;
long previous = firedFor.load(std::memory_order_acquire);
if (previous == target || !firedFor.compare_exchange_strong(previous, target, std::memory_order_acq_rel)) {
return false;
}
MGLOG_E("MGPipe: debug knob inject_device_lost_pid=%ld - this session's device is reported LOST", target);
return true;
}
bool MGPipeSessionLatch(MGPipeFatalFamily family, const char* fmt, ...) {
char line[512];
va_list args;
@@ -621,12 +663,37 @@ namespace MobileGL::MG_Pipe {
return raw;
}
// Every share group's object records in the session the calling thread's records are
// applied for, or nothing on a thread that serves no session (the process-wide applier is
// then the only one). The pointers stay valid after the lock is dropped: a group's records
// are held by UniquePtr, and only this session's own apply thread adds or drops its groups.
Vector<MGPipeObjectRecords*> BoundSessionGroups() {
Vector<MGPipeObjectRecords*> groups;
const MGPipeApplierKeyResolver resolve = g_applierKeyResolver;
MGPipeApplierKey key;
if (resolve == nullptr || !resolve(&key)) return groups;
std::lock_guard<std::mutex> guard(g_applierSessionsMutex);
const auto session = g_applierSessions.find(key.SessionKey);
if (session == g_applierSessions.end()) return groups;
for (auto& [groupKey, records] : session->second.Groups) {
(void)groupKey;
if (records) groups.push_back(records.get());
}
return groups;
}
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
Uint64 MGPipeNextApplierSerialBase() {
// Constant-initialized, so the default applier's static construction may already use it.
static std::atomic<Uint64> appliers{0};
return (appliers.fetch_add(1, std::memory_order_relaxed) + 1) << 40;
}
MGPipeApplierState& MGPipeApplier() {
const MGPipeApplierKeyResolver resolve = g_applierKeyResolver;
if (resolve == nullptr) return g_defaultApplier;
@@ -2371,7 +2438,12 @@ namespace MobileGL::MG_Pipe {
// the mask arrives - and by construction only the non-storage fields differ.
record->Desc = desc;
// A shared image is the storage this call replaces - unless the call replaces none.
if (level != nullptr || !metadataOnly) record->SharedImageId = 0;
if ((level != nullptr || !metadataOnly) && record->SharedImageId != 0) {
MGLOG_D("MGPipe: texture %u leaves shared image %llu: a respecify (%s) redefined its storage",
desc.GlNameForDiag, static_cast<unsigned long long>(record->SharedImageId),
level != nullptr ? "one level" : "whole resource");
record->SharedImageId = 0;
}
#if MOBILEGL_BUILD_DISAGGREGATED
if (level != nullptr && desc.Target != static_cast<Uint8>(MGPipeResourceTarget::TexBuffer)) {
// Scope and BufOffset/BufSize are transient respecify carriers, not resource state.
@@ -3233,6 +3305,27 @@ namespace MobileGL::MG_Pipe {
void MGPipeApplyDeleteSamplerState(const MGPHandleOnly& handle) {
MOBILEGL_ASSERT(handle.Kind == static_cast<Uint32>(MGPipeKind::SamplerCso),
"delete_sampler_state on kind %u", handle.Kind);
// A SAMPLER CSO IS ONE VALUE FOR THE WHOLE SESSION, and its delete drops it from every
// share group that holds it. The client's cache is content-addressed and process-wide:
// one handle names one canonical value, published into each group that uses it (a
// record per group, all of them copies), and the cache's eviction frees the handle -
// which ends it in every group at once, whichever context happens to be bound. Dropping
// only the bound group's copy left every other group a record at a slot the client hands
// out again. The handle space is the client's, so no other object can hold this slot at
// this generation in any of the session's groups.
if (const Vector<MGPipeObjectRecords*> groups = BoundSessionGroups(); !groups.empty()) {
Bool dropped = false;
for (MGPipeObjectRecords* group : groups) {
MGPipeSamplerCsoRecord* held = FindIn(group->SamplerCsos, handle.Handle);
if (held == nullptr) continue;
const Uint32 gen = held->Gen;
*held = MGPipeSamplerCsoRecord{};
held->Gen = gen;
dropped = true;
}
if (!dropped) (void)ResolveObject(MGPipeApplier().SamplerCsos, "delete_sampler_state", handle.Handle);
return;
}
MGPipeSamplerCsoRecord* record =
ResolveObject(MGPipeApplier().SamplerCsos, "delete_sampler_state", handle.Handle);
if (record == nullptr) return;
+15 -1
View File
@@ -938,6 +938,15 @@ namespace MobileGL::MG_Pipe {
};
// P14: where a new applier's working-state serials start. Each applier (one per served context)
// gets a range of its own, 2^40 values wide, so no two appliers ever answer with the same serial:
// the backends key process-wide memos on these serials (a texture sync list on ContextSerial and
// SamplerViewsSerial, the synced framebuffer binding on FramebufferSerial, ...), and one apply
// thread serves every context of its session. With every applier counting from 0, two contexts
// at the same point of their lives answered the same keys, and a draw in one replayed the memo
// the other had built - its own textures went unsynced and it sampled them empty.
Uint64 MGPipeNextApplierSerialBase();
// =====================================================================================
// P14 S5: ONE CONTEXT'S APPLIER = ITS OWN WORKING STATE + ITS SHARE GROUP'S RECORDS.
// =====================================================================================
@@ -981,7 +990,12 @@ namespace MobileGL::MG_Pipe {
TextureResources(objects.TextureResources), RenderbufferResources(objects.RenderbufferResources),
SamplerCsos(objects.SamplerCsos), SamplerViewCsos(objects.SamplerViewCsos),
ShaderCsos(objects.ShaderCsos), CompositeShaderCsos(objects.CompositeShaderCsos),
FramebufferRecords(objects.FramebufferRecords) {}
FramebufferRecords(objects.FramebufferRecords) {
const Uint64 base = MGPipeNextApplierSerialBase();
VertexBuffersSerial = IndexBufferSerial = FramebufferSerial = SamplerViewsSerial = base;
SamplerStatesSerial = ShaderImagesSerial = ProgramBindingSerial = ShaderBuffersSerial = base;
TextureShutterSerial = ContextSerial = base;
}
// ---- 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
+5
View File
@@ -266,6 +266,11 @@ namespace MobileGL::MG_Pipe {
void MGPipeClientFinish();
// Submit a stream link's published prefix; never wait for appliedSeq.
void MGPipeClientFlush();
// The texture sub-data drain of a validate point, outside one: a shared-image producer's
// glFlush (an X server's PutImage into a window pixmap is followed by no draw of its own)
// has to get its uploads to the server before the flush publishes the images. Gated as the
// validate point's drain is; a no-op on a monolith and on the server role.
void MGPipeClientDrainTextureUploads();
// A FRESH SESSION REPLACES AN ENDED ONE (a device loss recovered, or an eglTerminate /
// eglInitialize): every client-side answer to "what does the server hold" describes the
+9
View File
@@ -124,6 +124,15 @@ namespace MobileGL::MG_Pipe {
// several sessions in turn. The backends ask at their frame boundaries and readbacks; unset
// (the default) it is one getenv.
bool MGPipeDebugDeviceLossDue();
// THE SAME KNOB, AIMED AT ONE CLIENT. MOBILEGL_DEBUG_INJECT_DEVICE_LOST_PID=P (Android: the
// property debug.mobilegl.inject_device_lost_pid) loses the session whose client named pid P in
// its Hello (its own pid, as it sees it - a container's own pid namespace included), once per
// value, whatever the backend and whether or not that client ever presents or reads back: the
// server's apply thread asks after every drain. It is how one application among several is
// made to lose its device - a browser's GPU process, which renders into dma-bufs and never
// presents, included. Asked only for a session with a context bound; asks the environment /
// property at most every 100 ms per thread.
bool MGPipeDebugSessionLossDue(unsigned clientPid);
#endif
} // namespace MobileGL::MG_Pipe
@@ -238,8 +238,12 @@ namespace MobileGL::MG_Remote::Client {
// into its registration only; it is re-created at that size when it is next used.
{
const std::lock_guard<std::recursive_mutex> lock(m_eglStateMutex);
if (GetRegisteredEGLSurface(surface) != nullptr && m_homedSurfaces.count(surface) == 0)
if (GetRegisteredEGLSurface(surface) != nullptr && m_homedSurfaces.count(surface) == 0) {
// A server-owned one asks the fresh session's window for this size, as a resize would.
if (ClientSession::IsServerOwnedWindowSurface(surface))
m_serverOwnedRequests[surface] = {width, height};
return MG_Backend::BackendObject::ResizeEGLWindowSurface(surface, width, height);
}
}
// P12 review fix: a surface on the SERVER's window is resized by resizing that window. The
// server asks its display for the size and answers with the extent the window really took,
@@ -254,6 +258,7 @@ namespace MobileGL::MG_Remote::Client {
width, height, static_cast<int>(reply.transport), Server::SurfaceRefusalCodeName(reply.refusal));
return false;
}
NoteServerOwnedRequest(surface, width, height);
const Uint32 realWidth = reply.width != 0 ? reply.width : width;
const Uint32 realHeight = reply.height != 0 ? reply.height : height;
if (MG_State::pEGLContext) {
@@ -392,6 +397,7 @@ namespace MobileGL::MG_Remote::Client {
local.Width = reply.width;
local.Height = reply.height;
if (!MG_Backend::BackendObject::CreateEGLWindowSurface(surface, local)) return false;
NoteServerOwnedRequest(surface, handle.Width, handle.Height);
NoteHomed(surface);
return true;
}
@@ -481,6 +487,7 @@ namespace MobileGL::MG_Remote::Client {
const std::lock_guard<std::recursive_mutex> lock(m_eglStateMutex);
homed = m_homedSurfaces.erase(surface) != 0;
m_standInSurfaces.erase(surface);
m_serverOwnedRequests.erase(surface);
}
if (homed && !ClientSession::SessionLatchedLost()) Server::ServerReleaseEGLSurface(surface);
MG_Backend::BackendObject::ReleaseEGLSurface(surface);
@@ -534,8 +541,13 @@ namespace MobileGL::MG_Remote::Client {
recreated = Server::ServerCreateEGLPbufferSurface(surface, state.Width, state.Height, nullptr, flags);
} else if (ClientSession::IsServerOwnedWindowSurface(surface)) {
kind = "server-owned window";
// The window is asked for what the application asked for (its own size for a surface
// created without one), not for the extent it had: that would fix its size for good.
const auto requested = m_serverOwnedRequests.find(surface);
const Uint32 wantWidth = requested != m_serverOwnedRequests.end() ? requested->second.first : 0u;
const Uint32 wantHeight = requested != m_serverOwnedRequests.end() ? requested->second.second : 0u;
const Server::ServerOwnedWindowReply reply =
Server::ServerCreateServerOwnedWindowSurface(surface, state.Window.Width, state.Window.Height);
Server::ServerCreateServerOwnedWindowSurface(surface, wantWidth, wantHeight);
recreated = reply.ok;
if (recreated && reply.width != 0 && reply.height != 0) {
if (MG_State::pEGLContext) {
@@ -684,6 +696,30 @@ namespace MobileGL::MG_Remote::Client {
return session->EmitSharedImage(op, -1, nullptr, nullptr);
}
Bool BackendObject_Remote::FlushSharedImageAccesses() {
ClientSession* session = ClientSession::Active();
if (session == nullptr || !session->Started()) return false;
if (m_sharedImageFlushedAt != 0 && session->LastPublishedSeq() == m_sharedImageFlushedAt) return true;
MG_Pipe::MGPSharedImageOp op{};
op.Op = MG_Pipe::kMGPSharedImageFlush;
const Bool published = session->EmitSharedImage(op, -1, nullptr, nullptr);
m_sharedImageFlushedAt = session->LastPublishedSeq();
return published;
}
Bool BackendObject_Remote::CreateNativeFence(int* fence) {
*fence = -1;
ClientSession* session = ClientSession::Active();
if (session == nullptr || !session->Started()) return false;
MG_Pipe::MGPSharedImageOp op{};
op.Op = MG_Pipe::kMGPSharedImageNativeFence;
MG_Pipe::MGPSharedImageReply reply{};
if (!session->EmitSharedImage(op, -1, &reply, fence)) return false;
// It published what a flush would: a flush right after it has nothing new to say.
m_sharedImageFlushedAt = session->LastPublishedSeq();
return true;
}
// NO strong CreateRemoteBackendObject() lives here, and the reason is a link fact, not an
// oversight. v1's Init.cpp calls MG_Remote::Client::CreateRemoteBackendObject() and ships a
// __attribute__((weak)) placeholder for it beside ServerLoop that aborts by name; its comment
@@ -53,6 +53,7 @@
#include <unordered_map>
#include <unordered_set>
#include <utility>
namespace MobileGL::MG_Remote::Client {
@@ -94,6 +95,8 @@ namespace MobileGL::MG_Remote::Client {
Bool QueryBufferAge(Bool damageRegionFollows, EGLint* age) override;
Bool SetDamageRegion(const MG_Util::Damage::Region& region) override;
Bool AttachSharedImageToTexture(Uint64 textureLifetimeId, Uint64 id) override;
Bool FlushSharedImageAccesses() override;
Bool CreateNativeFence(int* fence) override;
// Copies the caps mirror's FormatCapabilityCache into the base class's
// m_formatCapabilities. Public because CapsMirror's adoption hook is a free function
@@ -122,6 +125,10 @@ namespace MobileGL::MG_Remote::Client {
// geometry adopted before it returns, and every refusal named in this process's log.
Bool CreateServerOwnedWindowSurface(EGLSurface surface, const MG_Backend::WindowHandle& handle);
// The stream position right after the last shared-image Flush record: a flush with nothing
// published since has nothing new to fence and costs no round trip.
Uint64 m_sharedImageFlushedAt = 0;
// 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
// is exactly the shape trap 2 exists to prevent.
@@ -151,6 +158,15 @@ namespace MobileGL::MG_Remote::Client {
std::unordered_map<Uint64, Uint32> m_sessionSharedImages; // id -> references taken
// The ids a replaced session held: releasing one is a success with nothing sent.
std::unordered_set<Uint64> m_lostSessionSharedImages;
// The size each server-owned window surface ASKED for (0x0: the window's own), which is what a
// fresh session is asked for again when the surface is re-created there - not the extent the
// window happened to have, which would fix the window's size for good. Guarded by
// m_eglStateMutex.
std::unordered_map<EGLSurface, std::pair<Uint32, Uint32>> m_serverOwnedRequests;
void NoteServerOwnedRequest(EGLSurface surface, Uint32 width, Uint32 height) {
const std::lock_guard<std::recursive_mutex> lock(m_eglStateMutex);
m_serverOwnedRequests[surface] = {width, height};
}
};
} // namespace MobileGL::MG_Remote::Client
+37 -2
View File
@@ -103,6 +103,27 @@ namespace MobileGL::MG_Remote::Client {
thread_local Uint32 tl_wireMute = 0;
thread_local Uint32 tl_currentSessionWork = 0;
std::atomic<Uint64> g_remoteSessionsStarted{0};
// ClientSession::LastLossReason(). Leaked on purpose: read from GL entry points that may
// run during process exit.
std::mutex& LossReasonMutex() {
static auto* mutex = new std::mutex();
return *mutex;
}
String& LossReason() {
static auto* reason = new String();
return *reason;
}
// The latch's words for a session the server ended on a named fault: what happened, and
// the fault family the server named (BackendDeviceLost for a GPU device loss).
String FaultReason(const ::MobileGL::Wire::CtrlEnvelope* envelope, const char* what) {
String reason = what;
if (const auto* fatal = envelope->msg_as_Fatal(); fatal != nullptr && fatal->family() != nullptr) {
reason += " (Fatal family ";
reason += fatal->family()->c_str();
reason += ")";
}
return reason;
}
// The same bounded handshake deadline the server uses. Bounded, not kWaitForever: a
// bring-up that never answers has to be a red lane rather than a wedged CI job.
@@ -608,12 +629,19 @@ namespace MobileGL::MG_Remote::Client {
if (session == nullptr) return false;
if (session->m_deviceLost.load(std::memory_order_acquire)) return true;
if (tl_currentSessionWork != 0) return false;
// A thread that released a lost context and has bound none since (MG_State's marker).
if (MG_State::tThreadReleasedLostContext) return true;
// A thread still on a context from before a recovered loss: lost for good, whatever the
// session it would now be writing into.
const SharedPtr<MG_State::GLState::GLContext>& context = MG_State::pGLContext;
return context != nullptr && context->IsFromEndedWireSession();
}
String ClientSession::LastLossReason() {
const std::lock_guard<std::mutex> lock(LossReasonMutex());
return LossReason();
}
Bool ClientSession::SessionLatchedLost() {
const ClientSession* session = Active();
return session != nullptr && session->m_deviceLost.load(std::memory_order_acquire);
@@ -633,6 +661,10 @@ namespace MobileGL::MG_Remote::Client {
if (m_deviceLost.exchange(true, std::memory_order_acq_rel)) {
return;
}
{
const std::lock_guard<std::mutex> lock(LossReasonMutex());
LossReason() = why == nullptr ? "the peer hung up" : why;
}
MGLOG_E("MGPipe: DEVICE LOST - %s. This session's server side is gone; every verb from here "
"is DECLINED and glGetGraphicsResetStatus reports GL_UNKNOWN_CONTEXT_RESET. This is "
"latched from the peer's HANGUP (or its named SessionFault) and not from any "
@@ -1645,7 +1677,7 @@ namespace MobileGL::MG_Remote::Client {
MGLOG_E("MG_Remote client: the server published a SessionFault before dying - "
"Fatal family %s: %s", fam, msg);
}
LatchDeviceLost("the server published a SessionFault and then aborted");
LatchDeviceLost(FaultReason(envelope, "the server published a SessionFault and then aborted").c_str());
frame.ok = false;
return MOBILEGL_ERR_TRANSPORT_CLOSED;
}
@@ -2742,7 +2774,7 @@ namespace MobileGL::MG_Remote::Client {
fatal->family() ? fatal->family()->c_str() : "<none>",
fatal->message() ? fatal->message()->c_str() : "");
}
LatchDeviceLost("the server published a SessionFault for this session");
LatchDeviceLost(FaultReason(envelope, "the server published a SessionFault for this session").c_str());
continue;
}
if (envelope->msg_type() != ::MobileGL::Wire::CtrlMsg::CapsSnapshot) {
@@ -3035,6 +3067,9 @@ namespace MobileGL::MG_Remote::Client {
if (status != Wire::ReplySink::kStatusOk || returned != sizeof(answer)) return false;
if (reply != nullptr) *reply = answer;
if (receivedFd == nullptr) return true;
// A native fence's answer says whether a descriptor follows (none: the work completed).
if (op.Op == MG_Pipe::kMGPSharedImageNativeFence && answer.Format != MG_Pipe::kMGPNativeFenceFdFollows)
return true;
#if defined(_WIN32)
return false;
#else
@@ -100,6 +100,10 @@ namespace MobileGL::MG_Remote::Client {
// Arms the latch and says why, once. Safe to call repeatedly and from any thread; only
// the first call logs.
void LatchDeviceLost(const char* why);
// Why the most recent session of this process was lost, in the latch's words (empty
// before any loss). Kept past the recovery, because the contexts of the lost session
// outlive it: glGetGraphicsResetStatus names it when it first reports a context's reset.
static String LastLossReason();
// A reply-owning record came back DECLINED where only a latched server declines (a
// readback). The server publishes its SessionFault on the control plane BEFORE it declines,
+10
View File
@@ -30,12 +30,18 @@ namespace MobileGL::MG_Remote {
// that forks a child and reads it back sees the increment even though the child is gone -
// it reads its OWN process's counter for the funnel it drove, not the child's.
std::atomic<std::uint64_t> g_sessionFaultCount{0};
// SetSessionLatchObserver's; read once per latched session.
std::atomic<SessionLatchObserver> g_sessionLatchObserver{nullptr};
} // namespace
std::uint64_t SessionFaultCount() {
return g_sessionFaultCount.load(std::memory_order_relaxed);
}
void SetSessionLatchObserver(SessionLatchObserver observer) {
g_sessionLatchObserver.store(observer, std::memory_order_release);
}
namespace {
// THE PROJECTION FROM MG_Pipe's TWO-WORD BOUNDARY ENUM ONTO THE .def's VOCABULARY, as a
// switch with a named default rather than a cast. MGPipeFatalFamily is deliberately not
@@ -241,6 +247,10 @@ namespace MobileGL::MG_Remote {
"closes (exit %d) for the supervisor to serve the next connection (PH-1, "
"ID-P7-1)",
FatalFamilyName(family), kSessionLatchedExitCode);
// Before the peer hears of it: what the observer records must already hold when the client
// reacts (a lost compositor re-creates its window surface on a fresh session at once).
if (const SessionLatchObserver observer = g_sessionLatchObserver.load(std::memory_order_acquire))
observer();
PublishSessionFault(family, line);
return false;
}
+8
View File
@@ -140,6 +140,14 @@ namespace MobileGL::MG_Remote {
#endif
SessionLatch(MGFatalFamily family, const char* fmt, ...);
// THE FIRST LATCHED FAULT OF A SESSION, OBSERVED. Called on the latching thread (its latch
// domain bound) once the latch is raised and BEFORE the SessionFault frame goes to the peer, so
// what it records about the session is in place before the client can act on the loss. One
// process-wide observer, replaced by the next install; it must not block. ServerLoop's marks the
// session's lease on the server window as ending (ServerDisplay::MarkLeaseEnding).
using SessionLatchObserver = void (*)();
void SetSessionLatchObserver(SessionLatchObserver observer);
// P7 wave 0. Points MG_Pipe's MGPipeSessionFail seam (MG_Pipe/PipeSessionFail.h) at
// SessionFail, which is what makes the three Magma wire funnels in MG_Backend's renderer
// publish a SessionFault, bump SessionFaultCount() and appear in the census like every other
+53
View File
@@ -1480,6 +1480,20 @@ namespace MobileGL::MG_Remote::Server {
return true;
}
ServerVerbSink::OwnedFd& ServerVerbSink::OwnedFd::operator=(OwnedFd&& other) noexcept {
if (this != &other) Reset(std::exchange(other.fd, -1));
return *this;
}
ServerVerbSink::OwnedFd::~OwnedFd() { Reset(-1); }
void ServerVerbSink::OwnedFd::Reset(int next) {
#if !defined(_WIN32)
if (fd >= 0) ::close(fd);
#endif
fd = next;
}
// 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
@@ -1586,6 +1600,45 @@ namespace MobileGL::MG_Remote::Server {
if (backend == nullptr) return false;
return backend->SetCurrentDamageRegion(DamageOfRecord(op.DamageCount, op.Damage));
}
case MG_Pipe::kMGPSharedImageFlush: {
// The answer is posted after the fence is published: the client commits the buffer to
// its compositor only after this returns, so the compositor's session finds the write.
MG_Backend::BackendObject* backend = ServerLoopInstance().Backend();
if (backend == nullptr) return false;
return backend->PublishSharedImageAccesses();
}
case MG_Pipe::kMGPSharedImageNativeFence: {
// A descriptor of the session's work, and an image writer's flush (MGPipeTypes.h). Like
// an Allocate's, the descriptor goes out BEFORE the reply is posted.
MG_Backend::BackendObject* backend = ServerLoopInstance().Backend();
if (backend == nullptr) return false;
int fence = -1;
if (!backend->ExportNativeFence(&fence)) return false;
#if !defined(_WIN32)
if (fence >= 0) {
m_lastNativeFence.Reset(::dup(fence));
} else if (m_lastNativeFence.fd >= 0) {
fence = ::dup(m_lastNativeFence.fd);
}
#endif
reply.Format = 0;
if (fence < 0) return true;
Transport::ITransport* transport = session->ControlTransport();
MG_Pipe::MGPSharedImageFdOffer offer{MG_Pipe::kMGPSharedImageFdMagic, 1, seq, 0, 0};
const MobileGLResult shared = transport != nullptr
? transport->ShareFd(fence, MobileGLByteSpan{&offer, sizeof(offer)})
: MOBILEGL_ERR_NOT_INITIALIZED;
#if !defined(_WIN32)
::close(fence);
#endif
if (shared != MOBILEGL_OK) {
MGLOG_E_ONCE("MG_Remote server: a native fence could not be sent on the aux socket (rc=%d)",
static_cast<int>(shared));
return false;
}
reply.Format = MG_Pipe::kMGPNativeFenceFdFollows;
return true;
}
case MG_Pipe::kMGPSharedImageAttach: {
SI::ImageRef image = holder.Get(op.ImageId);
if (image == nullptr) return false;
+15
View File
@@ -47,6 +47,7 @@
#include "../Wire/PipeWireCodec.h"
#include <deque>
#include <utility>
namespace MobileGL::MG_Remote::Server {
@@ -413,6 +414,20 @@ namespace MobileGL::MG_Remote::Server {
Vector<GLint> m_multiBaseVertices;
LastDrawRecord m_lastDraw{};
Uint64 m_drawRecords = 0;
// The newest native fence (shared_image NativeFence) this session handed out, kept so a
// later fence with nothing left to export still answers with a descriptor: by then this
// one has signaled (the backend waited the work out), and a signaled sync_file stays so.
struct OwnedFd {
int fd = -1;
OwnedFd() = default;
OwnedFd(const OwnedFd&) = delete;
OwnedFd& operator=(const OwnedFd&) = delete;
OwnedFd(OwnedFd&& other) noexcept : fd(std::exchange(other.fd, -1)) {}
OwnedFd& operator=(OwnedFd&& other) noexcept;
~OwnedFd();
void Reset(int next);
};
OwnedFd m_lastNativeFence;
};
class PipeApplier {
+40 -4
View File
@@ -204,7 +204,8 @@ namespace MobileGL::MG_Remote::Server {
{
const std::lock_guard<std::mutex> lock(m_mutex);
if (!m_installed) return ServerWindowAcquire::NoDisplay;
if (m_leaseHolder != nullptr && m_leaseHolder != holder) return ServerWindowAcquire::LeasedElsewhere;
if (m_leaseHolder != nullptr && m_leaseHolder != holder && !m_leaseEnding)
return ServerWindowAcquire::LeasedElsewhere;
hooks = m_hooks;
interrupts = m_interrupts;
previousWidth = m_requestedWidth;
@@ -231,14 +232,27 @@ namespace MobileGL::MG_Remote::Server {
std::unique_lock<std::mutex> lock(m_mutex);
const auto deadline = Clock::now() + std::chrono::milliseconds(timeoutMs);
Bool attachedSeen = false;
Bool waitedForEndingHolder = false;
auto geometryDeadline = deadline;
for (;;) {
if (!m_installed) return ServerWindowAcquire::NoDisplay;
if (m_interrupts != interrupts) return ServerWindowAcquire::Interrupted;
if (cancel != nullptr && cancel(cancelUser)) return ServerWindowAcquire::Cancelled;
if (m_leaseHolder != nullptr && m_leaseHolder != holder) return ServerWindowAcquire::LeasedElsewhere;
// ANOTHER HOLDER: refused at once while its session goes on, waited for while it ends
// (its EndLease wakes this). The window is judged only once the lease is free.
const Bool heldElsewhere = m_leaseHolder != nullptr && m_leaseHolder != holder;
if (heldElsewhere && !m_leaseEnding) return ServerWindowAcquire::LeasedElsewhere;
if (heldElsewhere && !waitedForEndingHolder) {
waitedForEndingHolder = true;
MGLOG_I("MG_Remote server: the server window is still leased by a session that is ending; this "
"session waits for that lease to end (at most %u ms)",
timeoutMs);
}
const auto now = Clock::now();
if (m_window != nullptr) {
if (heldElsewhere) {
attachedSeen = false;
geometryDeadline = deadline;
} else if (m_window != nullptr) {
if (!attachedSeen) {
attachedSeen = true;
geometryDeadline = std::min(deadline, now + std::chrono::milliseconds(kGeometryGraceMs));
@@ -249,6 +263,7 @@ namespace MobileGL::MG_Remote::Server {
m_onLost = onLost;
m_onResized = onResized;
m_lostRequested = false;
m_leaseEnding = false;
// A suspended holder that leased a window again waits for no other.
m_suspended.erase(std::remove_if(m_suspended.begin(), m_suspended.end(),
[holder](const SuspendedHolder& entry) {
@@ -273,13 +288,18 @@ namespace MobileGL::MG_Remote::Server {
"at that size and the client is told so",
m_width, m_height, kGeometryGraceMs);
}
if (waitedForEndingHolder) {
MGLOG_I("MG_Remote server: the ending session's lease ended; the server window is leased to "
"this session");
}
return ServerWindowAcquire::Acquired;
}
} else {
attachedSeen = false;
geometryDeadline = deadline;
}
if (now >= deadline) return ServerWindowAcquire::NoWindow;
if (now >= deadline)
return heldElsewhere ? ServerWindowAcquire::LeasedElsewhere : ServerWindowAcquire::NoWindow;
const auto wake = std::min({deadline, geometryDeadline, now + kCancelPollInterval});
m_cv.wait_until(lock, wake);
}
@@ -291,6 +311,7 @@ namespace MobileGL::MG_Remote::Server {
m_onLost = nullptr;
m_onResized = nullptr;
m_lostRequested = false;
m_leaseEnding = false;
releases->swap(m_releaseAfterLease);
*hooks = m_hooks;
// An Uninstall that ran while this lease still owed releases kept the hooks for them.
@@ -317,6 +338,16 @@ namespace MobileGL::MG_Remote::Server {
ReleaseAfterLease(hooks, releases);
}
void ServerDisplay::MarkLeaseEnding(void* holder) {
{
const std::lock_guard<std::mutex> lock(m_mutex);
if (holder == nullptr || m_leaseHolder != holder || m_leaseEnding) return;
m_leaseEnding = true;
}
// A request already refused is not waiting; one made from here on waits for the EndLease.
m_cv.notify_all();
}
void ServerDisplay::SuspendLease(void* holder, ServerWindowAttachedHook onAttached) {
if (holder == nullptr) return;
std::vector<void*> releases;
@@ -379,6 +410,11 @@ namespace MobileGL::MG_Remote::Server {
return m_leaseHolder != nullptr;
}
Bool ServerDisplay::LeaseEnding() const {
const std::lock_guard<std::mutex> lock(m_mutex);
return m_leaseHolder != nullptr && m_leaseEnding;
}
Uint64 ServerDisplay::Generation() const {
const std::lock_guard<std::mutex> lock(m_mutex);
return m_generation;
+20 -1
View File
@@ -35,6 +35,14 @@
// reference is kept and released when the lease finally ends - and Detach returns TimedOut, by
// name, so the UI thread is never held longer than its bound.
//
// A LEASE THAT IS ENDING IS WAITED FOR, NOT REFUSED. A holder whose session is over - it latched a
// fault (a device loss among them) or is stopping - says so (MarkLeaseEnding) before its client can
// learn of it; its lease still lasts until its backend has let go of the window. A client that loses
// its session re-creates its window surface on a fresh session at once, typically while the old
// session's apply thread is still tearing its backend down: that request waits for the old lease
// to end, bounded by its own timeout, instead of being refused as LeasedElsewhere. A holder whose
// session goes on keeps the window exclusively, as before.
//
// SUSPEND, NOT END (screen off / lock). A holder whose backend can let go of the window and keep
// everything else - its contexts, objects and device - ends its lease with SuspendLease instead of
// EndLease and names a second hook: the next Attach of a NEW window calls it, so the holder can
@@ -96,7 +104,9 @@ namespace MobileGL::MG_Remote::Server {
Interrupted, // Interrupt() (the in-process server is stopping)
// 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.
// (ServerLoop logs the holder); offscreen sessions take no lease and are unaffected. A holder
// whose session is ending (MarkLeaseEnding) is waited for instead, and this is the answer
// only when its lease outlasted the wait.
LeasedElsewhere, // another session in this process holds the window: see the note above
};
@@ -156,6 +166,11 @@ namespace MobileGL::MG_Remote::Server {
// whole backend). Wakes a waiting Detach; releases a reference Detach left behind on timeout.
// A holder that holds no lease is a no-op.
void EndLease(void* holder);
// `holder`'s session is ending (it latched, or it is stopping): its lease ends once its
// backend has let go of the window, and another holder's AcquireFor waits for that rather
// than being refused (see the header block). A no-op for a holder that holds no lease; the
// mark ends with the lease.
void MarkLeaseEnding(void* holder);
// EndLease for a holder that only SUSPENDED its use of the window (its backend let go of the
// window and kept everything else). Also registers `onAttached`, which the next Attach of a
// new window calls - at once when a window is already attached. The registration ends when
@@ -169,6 +184,8 @@ namespace MobileGL::MG_Remote::Server {
// Diagnostics, for logs and tests.
Bool Attached() const;
Bool Leased() const;
// The lease is held by a holder whose session is ending (MarkLeaseEnding).
Bool LeaseEnding() const;
Uint64 Generation() const;
// How many holders wait for a window to resume on (SuspendLease).
Uint32 SuspendedHolders() const;
@@ -207,6 +224,8 @@ namespace MobileGL::MG_Remote::Server {
ServerWindowLostHook m_onLost = nullptr;
ServerWindowResizedHook m_onResized = nullptr;
Bool m_lostRequested = false;
// The holder's session is ending (MarkLeaseEnding); cleared with the lease.
Bool m_leaseEnding = false;
// References a timed-out Detach could not release yet; EndLease releases them.
std::vector<void*> m_releaseAfterLease;
// SuspendLease's registrations, told about the next new window.
+88 -8
View File
@@ -12,6 +12,7 @@
#include "ApplyThreadPolicy.h"
#include "SessionRuntime.h"
#include <MG_Remote/FatalFunnel.h>
#include <MG_Pipe/PipeSessionFail.h>
#include <MG_Remote/Transport/LinkMetrics.h>
#include <MG_Backend/MGPipe/PipeInputs.h>
@@ -78,6 +79,24 @@ namespace MobileGL::MG_Remote::Server {
++m_serving;
m_turn.notify_all();
}
// Gives the turn up however deep the calling thread holds it, for a wait that does no
// backend work; answers the depth Resume restores (0: the thread did not hold it).
Uint32 YieldIfHeld() {
const std::lock_guard<std::mutex> lock(m_mutex);
if (m_owner != std::this_thread::get_id()) return 0;
const Uint32 depth = m_depth;
m_depth = 0;
m_owner = std::thread::id{};
++m_serving;
m_turn.notify_all();
return depth;
}
void Resume(Uint32 depth) {
if (depth == 0) return;
Lock();
const std::lock_guard<std::mutex> lock(m_mutex);
m_depth = depth;
}
private:
std::mutex m_mutex;
@@ -102,6 +121,31 @@ namespace MobileGL::MG_Remote::Server {
ScopedBackendTurn& operator=(const ScopedBackendTurn&) = delete;
};
// A WAIT FOR THE SERVER WINDOW HOLDS NO TURN. It can last seconds - a window that is not up
// yet, or the lease of a session that is ending - and the other sessions' apply threads need
// the turn meanwhile: the ending one to tear its backend down, which is what ends its lease.
// Nothing of the backend is touched while it is given up; it is taken back (a handoff, when
// another thread had it) before the waiter goes on.
class ScopedBackendTurnYield {
public:
ScopedBackendTurnYield() : m_depth(BackendTurn().YieldIfHeld()) {}
~ScopedBackendTurnYield() { BackendTurn().Resume(m_depth); }
ScopedBackendTurnYield(const ScopedBackendTurnYield&) = delete;
ScopedBackendTurnYield& operator=(const ScopedBackendTurnYield&) = delete;
private:
const Uint32 m_depth;
};
// The process-wide test seam (ServerLoop.h).
std::atomic<ServerLoop::ServerOwnedSurfaceHook> g_serverOwnedSurfaceHook{nullptr};
// FatalFunnel's latch observer. The latching thread is one of the session's own (its scope
// resolves ServerLoopInstance to that session's loop): a session that latched is over, and
// its lease on the server window, if it holds one, ends once its apply thread has torn the
// backend down - which a fresh session of the same client waits for (MarkLeaseEnding).
void MarkLatchedSessionsLeaseEnding() { ServerDisplayInstance().MarkLeaseEnding(&ServerLoopInstance()); }
// The bounded join. InProcessTransportTest.cpp:344 uses five seconds for the same
// reason: a lost wakeup must be a RED TEST and not a hung CI job.
constexpr Uint32 kJoinTimeoutMs = 5000;
@@ -332,6 +376,10 @@ namespace MobileGL::MG_Remote::Server {
return MOBILEGL_OK;
}
void ServerLoop::SetServerOwnedSurfaceHookForTesting(ServerOwnedSurfaceHook hook) {
g_serverOwnedSurfaceHook.store(hook, std::memory_order_release);
}
// ---------------------------------------------------------------------------------
// Start / the loop / Stop
// ---------------------------------------------------------------------------------
@@ -346,6 +394,8 @@ namespace MobileGL::MG_Remote::Server {
return MOBILEGL_ERR_NOT_INITIALIZED;
}
m_session = &session;
// A session that latches marks its window lease as ending before its client hears of it.
SetSessionLatchObserver(&MarkLatchedSessionsLeaseEnding);
m_stopRequested.store(false, std::memory_order_release);
m_abandonQueue.store(false, std::memory_order_release);
// PH-6 fix round: the session's copy of the request, for ReserveEventOrBlock's wait. Lowered
@@ -633,6 +683,18 @@ namespace MobileGL::MG_Remote::Server {
if (stopOrForfeit()) break;
if (eventRingHasRoom()) DrainRing();
if (stopOrForfeit()) break;
// The session-targeted device-loss debug knob (PipeSessionFail.h): asked here, after a
// drain, so it reaches a client that never presents or reads back, once the session
// has a context bound (it renders); latched as the backends latch a real loss. Unset
// it is one clock read per iteration.
if (!SessionLatched() && session.CurrentContextToken() != 0 &&
MG_Pipe::MGPipeDebugSessionLossDue(session.ClientPid())) {
(void)MG_Pipe::MGPipeSessionLatch(MG_Pipe::MGPipeFatalFamily::DeviceLost,
"MGPipe: Fatal{BackendDeviceLost, \"injected:pid=%u\"} - the debug "
"knob lost this session's device; the session ends and its client "
"reads a lost context, every other session keeps running",
session.ClientPid());
}
if (eventRingHasRoom() && !SessionLatched()) verbs.ReportSignaledFences(/*flush=*/false);
// PH-1 (3): a latched session applies nothing more, so this thread leaves the loop
// (and does not spin on a ring whose head is still ahead of a tail DrainRing will no
@@ -722,6 +784,11 @@ namespace MobileGL::MG_Remote::Server {
// AND AFTER AbandonQueuedRecords (P12 review fix), for the forfeit's reason: the server is
// stopping under a client that may still be streaming, and draining what it keeps queuing
// is the unbounded hold Stop()'s bounded join turns into an abort.
//
// THE SESSION IS ENDING, whatever ended it: its lease on the server window (if it holds one)
// ends below, once the backend is gone, and a fresh session of the same client that asks for
// the window meanwhile waits for that instead of being refused.
ServerDisplayInstance().MarkLeaseEnding(this);
std::optional<ScopedBackendTurn> exitTurn(std::in_place);
const Bool forfeited = session.ReverseChannelForfeited();
const Bool abandoned = m_abandonQueue.load(std::memory_order_acquire);
@@ -1280,6 +1347,9 @@ namespace MobileGL::MG_Remote::Server {
m_running.store(false, std::memory_order_release);
return;
}
// As on the apply thread's own way out: the window lease ends once the thread has torn the
// backend down, and a fresh session waits for it meanwhile.
ServerDisplayInstance().MarkLeaseEnding(this);
m_stopRequested.store(true, std::memory_order_release);
if (m_session != nullptr) {
// PH-6 fix round: the apply thread may be parked in ReserveEventOrBlock rather than in
@@ -1807,9 +1877,12 @@ namespace MobileGL::MG_Remote::Server {
ServerDisplay& display = ServerDisplayInstance();
ServerWindowLease local;
ServerWindowLease* const lease = out != nullptr ? out : &local;
const ServerWindowAcquire acquired = display.AcquireFor(width, height, timeoutMs, this, &ServerWindowLostThunk,
&ServerWindowWaitCancelled, this, lease,
&ServerWindowResizedThunk);
ServerWindowAcquire acquired = ServerWindowAcquire::NoDisplay;
{
const ScopedBackendTurnYield yield;
acquired = display.AcquireFor(width, height, timeoutMs, this, &ServerWindowLostThunk,
&ServerWindowWaitCancelled, this, lease, &ServerWindowResizedThunk);
}
switch (acquired) {
case ServerWindowAcquire::Acquired:
m_holdsWindowLease = true;
@@ -1889,7 +1962,10 @@ namespace MobileGL::MG_Remote::Server {
// Review fix: the backend is told which window is the server's own, so its surface init
// reports the extent for this window and for no window a client named (MGPipeServerOwnedWindow).
NoteServerWindowExtent(lease.window, lease.width, lease.height);
frame.ok = backend->CreateEGLWindowSurface(HandleFromToken<EGLSurface>(frame.surface), window);
const ServerOwnedSurfaceHook surfaceHook = g_serverOwnedSurfaceHook.load(std::memory_order_acquire);
const EGLSurface ownedSurface = HandleFromToken<EGLSurface>(frame.surface);
frame.ok = surfaceHook != nullptr ? surfaceHook(backend, ownedSurface, window)
: backend->CreateEGLWindowSurface(ownedSurface, window);
if (!frame.ok) {
MGLOG_E("MG_Remote server: the backend could not create a window surface on the server window %p "
"(%ux%u) for ServerOwned seq %llu",
@@ -2071,10 +2147,14 @@ namespace MobileGL::MG_Remote::Server {
// have survived it). Bounded by the geometry grace: the window IS attached - that is what woke
// this - so only its size is waited for.
ServerWindowLease lease;
const ServerWindowAcquire acquired =
ServerDisplayInstance().AcquireFor(m_serverWindowWantWidth, m_serverWindowWantHeight,
ServerDisplay::kGeometryGraceMs, this, &ServerWindowLostThunk,
&ServerWindowWaitCancelled, this, &lease, &ServerWindowResizedThunk);
ServerWindowAcquire acquired = ServerWindowAcquire::NoDisplay;
{
const ScopedBackendTurnYield yield;
acquired = ServerDisplayInstance().AcquireFor(m_serverWindowWantWidth, m_serverWindowWantHeight,
ServerDisplay::kGeometryGraceMs, this, &ServerWindowLostThunk,
&ServerWindowWaitCancelled, this, &lease,
&ServerWindowResizedThunk);
}
if (acquired != ServerWindowAcquire::Acquired) {
// Still registered: the next new window wakes this again.
MGLOG_I("MG_Remote server: a suspended on-screen session did not get the new server window (%s); it "
+9
View File
@@ -449,6 +449,15 @@ namespace MobileGL::MG_Remote::Server {
// suspend, for the window-loss cases). Before Start(); fails when one is already installed.
MobileGLResult InstallBackendForTesting(UniquePtr<MG_Backend::BackendObject> backend);
// PROCESS-WIDE TEST SEAM for a server forked from a test (every session's loop reads it; null -
// the default - is the production path): the backend surface behind a ServerOwned window
// surface. A host has no window a backend can draw into, so a case that serves a stand-in
// window gives the backend a surface of the window's extent another way (a pbuffer). Called on
// the apply thread with the lease held, in place of CreateEGLWindowSurface.
using ServerOwnedSurfaceHook = Bool (*)(MG_Backend::BackendObject* backend, EGLSurface surface,
const MG_Backend::WindowHandle& window);
static void SetServerOwnedSurfaceHookForTesting(ServerOwnedSurfaceHook hook);
private:
RemoteControlSink m_remoteSink = nullptr;
void* m_remoteSinkUser = nullptr;
@@ -687,6 +687,7 @@ namespace MobileGL::MG_Remote::Server {
m_peer = hello->dialMode() == ::MobileGL::Wire::DialMode::Connect ? ApplyPeer::Connected
: hello->dialMode() == ::MobileGL::Wire::DialMode::Fork ? ApplyPeer::Forked
: ApplyPeer::InProcess;
m_clientPid = hello->pid();
const MobileGLResult compatible = ValidatePeerHandshake(transport, hello->abiMajor(),
hello->abiMinor(), hello->wireFingerprint(), theirStamp, hello->dialMode());
if (compatible != MOBILEGL_OK) return compatible;
@@ -370,6 +370,9 @@ namespace MobileGL::MG_Remote::Server {
// 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); }
// The pid the client's Hello names (its own, in its own pid namespace; 0 before Accept).
// What the session-targeted device-loss debug knob matches.
Uint32 ClientPid() const { return m_clientPid; }
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; }
@@ -418,6 +421,7 @@ namespace MobileGL::MG_Remote::Server {
// P11 B2 (T0). Set by Accept from the Hello, by SettleAdoptT0AtBind on the apply thread;
// the inbox and the counters are the apply thread's.
Bool m_adoptT0Asked = false;
Uint32 m_clientPid = 0;
Bool m_adoptT0Quiet = false;
Uint8 m_adoptAsk = 2;
Bool m_adoptT0Settled = false;
@@ -394,6 +394,15 @@ namespace MobileGL::MG_Remote::Server::SharedImages {
m_images.clear();
}
void ReadTracker::PublishFrameAsWrite(int fence) {
for (const auto& [id, image] : m_images) {
PublishWrite(*image, Dup(fence));
PublishRead(*image, Dup(fence));
}
CloseFd(fence);
m_images.clear();
}
void SessionHolder::Hold(const ImageRef& image) {
if (image == nullptr) return;
const std::lock_guard<std::mutex> lock(m_mutex);
@@ -134,6 +134,12 @@ namespace MobileGL::MG_Remote::Server::SharedImages {
void NoteRead(const ImageRef& image);
// Takes ownership of `fence` (a sync_file for the frame, -1 if it has completed).
void PublishFrame(int fence);
// IMPLICIT SYNC BY FLUSH: a session that renders into images as well as sampling them, with
// no swap and no explicit write (an X server's glamor) ends its frame at glFlush. Every image
// it used since its last boundary gets `fence` both as a write - the generation moves, so the
// next reader waits for it - and as a read, so the next writer waits for it too. Takes
// ownership of `fence` (-1: the work has completed; the generation still moves).
void PublishFrameAsWrite(int fence);
SizeT Pending() const { return m_images.size(); }
private:
@@ -668,6 +668,29 @@ namespace MobileGL::MG_Remote::Server {
site, static_cast<Uint32>(uploadTarget), static_cast<Uint32>(level));
}
// A box of a level for a replay into storage that is not this store's - a shared image,
// whose level was defined with no data and is written in pieces (an X server uploading a
// client's pixels into a window pixmap). The level image and its row length in texels when
// every row of the box is covered; null otherwise. Unlike RequireLevelBytes a partially
// covered level answers, and nothing is fatal: an uncovered box is the caller's to skip.
const Uint8* CoveredBoxBytes(Uint64 key, Uint16 uploadTarget, Uint16 level, Int x, Int y, Uint32 w, Uint32 h,
SizeT texel, Int* rowTexels) const {
if (!m_copies) return nullptr;
const std::lock_guard<std::mutex> lock(m_mutex);
const LevelShadow* shadow = FindLevel(key, uploadTarget, level);
if (shadow == nullptr || !shadow->Defined || x < 0 || y < 0 || w == 0 || h == 0 ||
x + static_cast<Int>(w) > shadow->Extent.x() || y + static_cast<Int>(h) > shadow->Extent.y())
return nullptr;
for (Uint32 row = 0; row < h; ++row) {
const SizeT begin = TexelOffset(shadow->Extent, x, y + static_cast<Int>(row), 0, texel);
const SizeT end = begin + static_cast<SizeT>(w) * texel;
if (end > shadow->Bytes.size() || !StagedShadowStore::CoverageHas(shadow->Covered, begin, end))
return nullptr;
}
*rowTexels = shadow->Extent.x();
return shadow->Bytes.data();
}
// Diagnostics the sync path and the unit cases read, so that a check can assert WHAT
// HAPPENED rather than that nothing blew up.
Bool IsCovered(Uint64 key, Uint16 uploadTarget, Uint16 level) const {
+303 -40
View File
@@ -8,6 +8,14 @@
#include "Core.h"
#include <EGL/eglext.h>
#include <MG_Util/X11/DisplayGuard.h>
#include <cerrno>
#include <climits>
#if !defined(_WIN32)
#include <poll.h>
#include <unistd.h>
#endif
namespace MobileGL {
namespace MG_State {
@@ -33,7 +41,9 @@ namespace MobileGL {
EGLint QueryDefaultX11VisualId() {
#if defined(__linux__) && !defined(__ANDROID__)
const char* displayName = std::getenv("DISPLAY");
if (!displayName) {
// Never the display this process serves: an X server drawing with MobileGL
// (Xwayland's glamor) would wait on its own socket (MG_Util/X11/DisplayGuard.h).
if (!displayName || !MG_Util::X11::MayDialX11Display(displayName)) {
return 0;
}
@@ -220,6 +230,55 @@ namespace MobileGL {
return it == m_surfaces.end() ? nullptr : &it->second;
}
namespace {
void CloseNativeFd(int fd) {
#if !defined(_WIN32)
if (fd >= 0) ::close(fd);
#else
(void)fd;
#endif
}
// Waits up to `timeoutMs` (negative: for ever) for a sync_file to signal; an absent
// descriptor has. False on timeout.
Bool WaitNativeFd(int fd, int timeoutMs) {
#if !defined(_WIN32)
if (fd < 0) return true;
pollfd entry{fd, POLLIN, 0};
for (;;) {
const int ready = ::poll(&entry, 1, timeoutMs);
if (ready > 0) return true;
if (ready == 0) return false;
if (errno != EINTR && errno != EAGAIN) return true; // not a fence that can block
}
#else
(void)fd, (void)timeoutMs;
return true;
#endif
}
int DupNativeFd(int fd) {
#if !defined(_WIN32)
return fd >= 0 ? ::dup(fd) : -1;
#else
(void)fd;
return -1;
#endif
}
// EGLTimeKHR nanoseconds as a poll timeout, rounded up; EGL_FOREVER waits for ever.
int NativeWaitTimeoutMs(EGLTime timeout) {
if (timeout == EGL_FOREVER) return -1;
const EGLTime ms = timeout / 1000000u + (timeout % 1000000u != 0 ? 1u : 0u);
return ms > static_cast<EGLTime>(INT_MAX) ? INT_MAX : static_cast<int>(ms);
}
// A server wait on a native fence is a wait of the calling thread: nothing it issues
// later reaches the server before the fence signals. Bounded, so a fence that never
// signals costs a stall rather than the application.
constexpr int kNativeServerWaitMs = 2000;
} // namespace
const EGLContext::SyncObject* EGLContext::TryGetSync(EGLSyncHandle sync) const {
auto it = m_syncs.find(sync);
return it == m_syncs.end() ? nullptr : &it->second;
@@ -247,17 +306,42 @@ namespace MobileGL {
}
// 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);
//
// A THREAD THAT HAD NONE (one that never had GL state before its first bind) GOES
// TO THE PROCESS DEFAULT, never keeps the released context's. Keeping it made the
// thread's TLS the last owner of a context destroyed after the release, so the
// context's objects ended in the thread-exit destructor of that TLS: outside every
// entry point and its lock, writing their records into the middle of another
// thread's - torn records, a reply read from the wrong slot, a lost session.
#if MOBILEGL_BUILD_DISAGGREGATED
// A fallback built against a server session that has since ended (a device
// loss, recovered) is lost with it: the thread falls back to today's default.
if (pGLContext->IsFromEndedWireSession()) pGLContext = ProcessDefaultGLContext();
#endif
{
const auto released = context != nullptr ? m_contexts.find(context) : m_contexts.end();
tThreadReleasedLostContext = !currentIt->second.RestoreThreadGLState && released != m_contexts.end() &&
released->second.GLStateObject &&
released->second.GLStateObject->IsFromEndedWireSession();
}
#endif
pGLContext = currentIt->second.RestoreThreadGLState ? Move(currentIt->second.RestoreThreadGLState)
: ProcessDefaultGLContext();
#if MOBILEGL_BUILD_DISAGGREGATED
// A fallback built against a server session that has since ended (a device loss,
// recovered) is lost with it: the thread falls back to today's default.
if (pGLContext->IsFromEndedWireSession()) pGLContext = ProcessDefaultGLContext();
#endif
m_threadCurrents.erase(currentIt);
DestroyPendingSurfaceIfUnused(drawSurface);
DestroyPendingSurfaceIfUnused(readSurface);
// A context destroyed while it was current is destroyed now that nothing has it
// current; the caller finishes it (TakeReapedContexts).
if (context != nullptr && m_contextOwners.find(context) == m_contextOwners.end()) {
const auto contextIt = m_contexts.find(context);
if (contextIt != m_contexts.end() && contextIt->second.DestroyPending) {
m_reapedContexts.push_back(ReapedContext{context, contextIt->second.ClientContextToken,
contextIt->second.ShareGroupToken,
Move(contextIt->second.GLStateObject)});
m_contexts.erase(contextIt);
}
}
}
Bool EGLContext::IsSurfaceCurrentUnlocked(EGLSurfaceHandle surface) const {
@@ -306,6 +390,7 @@ namespace MobileGL {
for (auto syncIt = m_syncs.begin(); syncIt != m_syncs.end();) {
if (syncIt->second.Display == display) {
CloseNativeFd(syncIt->second.NativeFd);
syncIt = m_syncs.erase(syncIt);
} else {
++syncIt;
@@ -314,7 +399,14 @@ namespace MobileGL {
for (auto imageIt = m_images.begin(); imageIt != m_images.end();) {
if (imageIt->second.Display == display) {
if (imageIt->second.Shared.Id != 0) m_orphanedSharedImages.push_back(imageIt->second.Shared.Id);
// Only a reference the current session holds is owed a release there.
#if MOBILEGL_BUILD_DISAGGREGATED
const Bool currentSession = imageIt->second.Shared.WireEpoch == CurrentWireEpoch();
#else
constexpr Bool currentSession = true;
#endif
if (imageIt->second.Shared.Id != 0 && currentSession)
m_orphanedSharedImages.push_back(imageIt->second.Shared.Id);
imageIt = m_images.erase(imageIt);
} else {
++imageIt;
@@ -653,7 +745,8 @@ namespace MobileGL {
EGLContext::EGLContextHandle EGLContext::CreateContext(EGLDisplayHandle display, EGLConfigHandle config,
EGLContextHandle shareCtx,
const EGLint* attribList) {
const EGLint* attribList,
Bool deferGLState) {
const std::lock_guard<std::recursive_mutex> lock(m_mutex);
const auto* displayObject = TryGetDisplay(display);
if (!displayObject) {
@@ -676,6 +769,31 @@ namespace MobileGL {
return nullptr;
}
// RESET NOTIFICATION (EGL_EXT_create_context_robustness, EGL 1.5): validated before
// anything of the context is built, since building its GL state already makes
// objects. Both names of the attribute are taken - the extension's (what Chrome,
// KWin and Qt pass) and EGL 1.5's (what ANGLE's GL-on-EGL backend passes for its
// own native context) - with the two values they share. Contexts that share
// objects must agree on it (EGL_BAD_MATCH otherwise).
EGLint resetStrategy = EGL_NO_RESET_NOTIFICATION;
for (const EGLint name :
{EGL_CONTEXT_OPENGL_RESET_NOTIFICATION_STRATEGY_EXT, EGL_CONTEXT_OPENGL_RESET_NOTIFICATION_STRATEGY}) {
if (auto value = ParseAttribValue(attribList, name); value) {
if (*value != EGL_NO_RESET_NOTIFICATION && *value != EGL_LOSE_CONTEXT_ON_RESET) {
SetError(EGL_BAD_ATTRIBUTE);
return nullptr;
}
resetStrategy = *value;
}
}
if (shareCtx != nullptr) {
const auto* shared = TryGetContext(shareCtx);
if (shared != nullptr && shared->ResetNotificationStrategy != resetStrategy) {
SetError(EGL_BAD_MATCH);
return nullptr;
}
}
ContextObject contextObject = {
.Display = display,
.Config = config,
@@ -685,6 +803,7 @@ namespace MobileGL {
.MajorVersion = 1,
.MinorVersion = 0,
};
contextObject.ResetNotificationStrategy = resetStrategy;
// 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
@@ -708,7 +827,11 @@ namespace MobileGL {
}
// 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 (deferGLState) {
contextObject.PendingShareGroup = Move(shareGroup);
} else {
contextObject.GLStateObject = MakeShared<GLState::GLContext>(shareGroup);
}
if (auto value = ParseAttribValue(attribList, EGL_CONTEXT_CLIENT_VERSION); value) {
contextObject.ClientVersion = *value;
@@ -732,7 +855,7 @@ namespace MobileGL {
contextObject.OpenGLContextFlags |= GL_CONTEXT_FLAG_DEBUG_BIT;
}
if (*value & EGL_CONTEXT_OPENGL_ROBUST_ACCESS_BIT_KHR) {
contextObject.OpenGLContextFlags |= GL_CONTEXT_FLAG_ROBUST_ACCESS_BIT;
contextObject.RobustAccessRequested = true;
}
}
if (auto value = ParseAttribValue(attribList, EGL_CONTEXT_OPENGL_FORWARD_COMPATIBLE);
@@ -744,10 +867,17 @@ namespace MobileGL {
contextObject.EGLContextFlags |= EGL_CONTEXT_OPENGL_DEBUG_BIT_KHR;
contextObject.OpenGLContextFlags |= GL_CONTEXT_FLAG_DEBUG_BIT;
}
if (auto value = ParseAttribValue(attribList, EGL_CONTEXT_OPENGL_ROBUST_ACCESS);
value && *value == EGL_TRUE) {
contextObject.EGLContextFlags |= EGL_CONTEXT_OPENGL_ROBUST_ACCESS_BIT_KHR;
contextObject.OpenGLContextFlags |= GL_CONTEXT_FLAG_ROBUST_ACCESS_BIT;
// ROBUST BUFFER ACCESS is recorded as asked for and reported only where it is
// provided (GL_CONTEXT_ROBUST_ACCESS, GL_CONTEXT_FLAG_ROBUST_ACCESS_BIT; the GL
// layer decides). The request is not refused where it is not: compositors and
// browsers ask for robust access and reset notification in the same attempt, and
// refusing the first would cost them the second, which is the one that matters to
// a split client - its contexts are lost exactly when the server session is.
for (const EGLint name : {EGL_CONTEXT_OPENGL_ROBUST_ACCESS, EGL_CONTEXT_OPENGL_ROBUST_ACCESS_EXT}) {
if (auto value = ParseAttribValue(attribList, name); value && *value == EGL_TRUE) {
contextObject.EGLContextFlags |= EGL_CONTEXT_OPENGL_ROBUST_ACCESS_BIT_KHR;
contextObject.RobustAccessRequested = true;
}
}
const auto context = EncodeHandle<EGLContextHandle>(m_nextContextHandle++);
@@ -755,10 +885,23 @@ namespace MobileGL {
return context;
}
Bool EGLContext::DestroyContext(EGLDisplayHandle display, EGLContextHandle context) {
Bool EGLContext::BuildContextGLState(EGLContextHandle context) {
const std::lock_guard<std::recursive_mutex> lock(m_mutex);
const auto contextIt = m_contexts.find(context);
if (contextIt == m_contexts.end()) return false;
ContextObject& object = contextIt->second;
if (!object.GLStateObject) {
object.GLStateObject = MakeShared<GLState::GLContext>(Move(object.PendingShareGroup));
object.PendingShareGroup = nullptr;
}
return true;
}
Bool EGLContext::DestroyContext(EGLDisplayHandle display, EGLContextHandle context, Bool* deferred) {
const std::lock_guard<std::recursive_mutex> lock(m_mutex);
if (deferred != nullptr) *deferred = false;
auto contextIt = m_contexts.find(context);
if (contextIt == m_contexts.end()) {
if (contextIt == m_contexts.end() || contextIt->second.DestroyPending) {
SetError(EGL_BAD_CONTEXT);
return false;
}
@@ -767,15 +910,23 @@ namespace MobileGL {
return false;
}
auto ownerIt = m_contextOwners.find(context);
if (ownerIt != m_contextOwners.end()) {
SetError(EGL_BAD_ACCESS);
return false;
if (m_contextOwners.find(context) != m_contextOwners.end()) {
// EGL 1.5 3.7.2: current to a thread, so destroyed once it no longer is.
contextIt->second.DestroyPending = true;
if (deferred != nullptr) *deferred = true;
return true;
}
m_contexts.erase(contextIt);
return true;
}
Vector<EGLContext::ReapedContext> EGLContext::TakeReapedContexts() {
const std::lock_guard<std::recursive_mutex> lock(m_mutex);
Vector<ReapedContext> reaped;
reaped.swap(m_reapedContexts);
return reaped;
}
Bool EGLContext::QueryContext(EGLDisplayHandle display, EGLContextHandle context, EGLint attribute,
EGLint* value) const {
const std::lock_guard<std::recursive_mutex> lock(m_mutex);
@@ -784,7 +935,7 @@ namespace MobileGL {
return false;
}
const auto* contextObject = TryGetContext(context);
if (!contextObject) {
if (!contextObject || contextObject->DestroyPending) {
const_cast<EGLContext*>(this)->SetError(EGL_BAD_CONTEXT);
return false;
}
@@ -831,13 +982,15 @@ namespace MobileGL {
Bool EGLContext::ValidateContext(EGLContextHandle context) const {
const std::lock_guard<std::recursive_mutex> lock(m_mutex);
return m_contexts.find(context) != m_contexts.end();
const auto* ctx = TryGetContext(context);
return ctx != nullptr && !ctx->DestroyPending;
}
// A context whose destroy is pending is no context for any new use of its handle.
Bool EGLContext::ValidateContextOnDisplay(EGLDisplayHandle display, EGLContextHandle context) const {
const std::lock_guard<std::recursive_mutex> lock(m_mutex);
const auto* ctx = TryGetContext(context);
return ctx && ctx->Display == display;
return ctx && !ctx->DestroyPending && ctx->Display == display;
}
// P14 S1. 0 for an unknown handle or a thread with no current context: 0 is the
@@ -910,6 +1063,36 @@ namespace MobileGL {
return ctx ? ctx->OpenGLContextFlags : 0;
}
EGLint EGLContext::GetCurrentContextResetNotificationStrategy() const {
const std::lock_guard<std::recursive_mutex> lock(m_mutex);
auto currentIt = m_threadCurrents.find(CurrentThreadKey());
if (currentIt == m_threadCurrents.end()) {
return EGL_NO_RESET_NOTIFICATION;
}
const auto* ctx = TryGetContext(currentIt->second.Context);
return ctx ? ctx->ResetNotificationStrategy : EGL_NO_RESET_NOTIFICATION;
}
EGLenum EGLContext::GetCurrentContextClientAPI() const {
const std::lock_guard<std::recursive_mutex> lock(m_mutex);
auto currentIt = m_threadCurrents.find(CurrentThreadKey());
if (currentIt == m_threadCurrents.end()) {
return EGL_OPENGL_API;
}
const auto* ctx = TryGetContext(currentIt->second.Context);
return ctx ? ctx->ClientAPI : EGL_OPENGL_API;
}
Bool EGLContext::IsCurrentContextRobustAccessRequested() const {
const std::lock_guard<std::recursive_mutex> lock(m_mutex);
auto currentIt = m_threadCurrents.find(CurrentThreadKey());
if (currentIt == m_threadCurrents.end()) {
return false;
}
const auto* ctx = TryGetContext(currentIt->second.Context);
return ctx && ctx->RobustAccessRequested;
}
EGLContext::EGLSurfaceHandle EGLContext::CreateWindowSurface(EGLDisplayHandle display,
EGLConfigHandle config,
NativeWindowType window,
@@ -1402,6 +1585,9 @@ namespace MobileGL {
if (const auto* contextObject = TryGetContext(context); contextObject != nullptr) {
pGLContext = contextObject->GLStateObject;
}
#if MOBILEGL_BUILD_DISAGGREGATED
tThreadReleasedLostContext = false;
#endif
}
return true;
}
@@ -1466,6 +1652,19 @@ namespace MobileGL {
SetError(EGL_NOT_INITIALIZED);
return EGL_NO_SYNC;
}
if (type == EGL_SYNC_NATIVE_FENCE_ANDROID) {
// An application's descriptor to wait on. A fence command (no descriptor) needs
// the backend, which EGLImpl asks before it gets here (CreateNativeFenceSync).
const auto fd = ParseAttribValue(attribList, EGL_SYNC_NATIVE_FENCE_FD_ANDROID);
#if !defined(_WIN32)
if (fd && *fd != EGL_NO_NATIVE_FENCE_FD_ANDROID) {
return CreateNativeFenceSync(display, static_cast<int>(*fd),
EGL_SYNC_NATIVE_FENCE_SIGNALED_ANDROID);
}
#endif
SetError(EGL_BAD_ATTRIBUTE);
return EGL_NO_SYNC;
}
if (type != EGL_SYNC_FENCE) {
SetError(EGL_BAD_ATTRIBUTE);
return EGL_NO_SYNC;
@@ -1497,27 +1696,80 @@ namespace MobileGL {
SetError(EGL_BAD_MATCH);
return false;
}
CloseNativeFd(syncIt->second.NativeFd);
m_syncs.erase(syncIt);
return true;
}
EGLint EGLContext::ClientWaitSync(EGLDisplayHandle display, EGLSyncHandle sync, EGLint flags,
EGLTime timeout) {
EGLContext::EGLSyncHandle EGLContext::CreateNativeFenceSync(EGLDisplayHandle display, int fd,
EGLenum condition) {
const std::lock_guard<std::recursive_mutex> lock(m_mutex);
(void)flags;
(void)timeout;
#if defined(_WIN32)
(void)display, (void)fd, (void)condition;
SetError(EGL_BAD_ATTRIBUTE);
return EGL_NO_SYNC;
#else
if (!IsDisplayInitialized(display)) {
CloseNativeFd(fd);
SetError(EGL_NOT_INITIALIZED);
return EGL_NO_SYNC;
}
SyncObject sync = {
.Display = display,
.Type = EGL_SYNC_NATIVE_FENCE_ANDROID,
.Condition = condition,
.Status = EGL_UNSIGNALED,
.NativeFd = fd,
};
const auto syncHandle = EncodeHandle<EGLSyncHandle>(m_nextSyncHandle++);
m_syncs[syncHandle] = sync;
return syncHandle;
#endif
}
EGLint EGLContext::DupNativeFenceFD(EGLDisplayHandle display, EGLSyncHandle sync) {
const std::lock_guard<std::recursive_mutex> lock(m_mutex);
const auto* syncObject = TryGetSync(sync);
if (!syncObject) {
SetError(EGL_BAD_PARAMETER);
return EGL_FALSE;
return EGL_NO_NATIVE_FENCE_FD_ANDROID;
}
if (syncObject->Display != display) {
SetError(EGL_BAD_MATCH);
return EGL_FALSE;
return EGL_NO_NATIVE_FENCE_FD_ANDROID;
}
const int fd =
syncObject->Type == EGL_SYNC_NATIVE_FENCE_ANDROID ? DupNativeFd(syncObject->NativeFd) : -1;
if (fd < 0) {
SetError(EGL_BAD_PARAMETER);
return EGL_NO_NATIVE_FENCE_FD_ANDROID;
}
return fd;
}
return EGL_CONDITION_SATISFIED;
EGLint EGLContext::ClientWaitSync(EGLDisplayHandle display, EGLSyncHandle sync, EGLint flags,
EGLTime timeout) {
(void)flags;
int fd = -1;
{
const std::lock_guard<std::recursive_mutex> lock(m_mutex);
const auto* syncObject = TryGetSync(sync);
if (!syncObject) {
SetError(EGL_BAD_PARAMETER);
return EGL_FALSE;
}
if (syncObject->Display != display) {
SetError(EGL_BAD_MATCH);
return EGL_FALSE;
}
if (syncObject->Type != EGL_SYNC_NATIVE_FENCE_ANDROID) return EGL_CONDITION_SATISFIED;
// A copy, waited on outside the lock: other threads keep using EGL meanwhile,
// and one may destroy the sync while this waits.
fd = DupNativeFd(syncObject->NativeFd);
}
const Bool signaled = WaitNativeFd(fd, NativeWaitTimeoutMs(timeout));
CloseNativeFd(fd);
return signaled ? EGL_CONDITION_SATISFIED : EGL_TIMEOUT_EXPIRED;
}
Bool EGLContext::GetSyncAttrib(EGLDisplayHandle display, EGLSyncHandle sync, EGLint attribute,
@@ -1542,6 +1794,10 @@ namespace MobileGL {
*value = static_cast<EGLAttrib>(syncObject->Type);
return true;
case EGL_SYNC_STATUS:
if (syncObject->Type == EGL_SYNC_NATIVE_FENCE_ANDROID) {
*value = WaitNativeFd(syncObject->NativeFd, 0) ? EGL_SIGNALED : EGL_UNSIGNALED;
return true;
}
*value = static_cast<EGLAttrib>(syncObject->Status);
return true;
case EGL_SYNC_CONDITION:
@@ -1554,17 +1810,24 @@ namespace MobileGL {
}
Bool EGLContext::WaitSync(EGLDisplayHandle display, EGLSyncHandle sync, EGLint flags) const {
const std::lock_guard<std::recursive_mutex> lock(m_mutex);
(void)flags;
const auto* syncObject = TryGetSync(sync);
if (!syncObject) {
const_cast<EGLContext*>(this)->SetError(EGL_BAD_PARAMETER);
return false;
}
if (syncObject->Display != display) {
const_cast<EGLContext*>(this)->SetError(EGL_BAD_MATCH);
return false;
int fd = -1;
{
const std::lock_guard<std::recursive_mutex> lock(m_mutex);
const auto* syncObject = TryGetSync(sync);
if (!syncObject) {
const_cast<EGLContext*>(this)->SetError(EGL_BAD_PARAMETER);
return false;
}
if (syncObject->Display != display) {
const_cast<EGLContext*>(this)->SetError(EGL_BAD_MATCH);
return false;
}
if (syncObject->Type != EGL_SYNC_NATIVE_FENCE_ANDROID) return true;
fd = DupNativeFd(syncObject->NativeFd);
}
(void)WaitNativeFd(fd, kNativeServerWaitMs);
CloseNativeFd(fd);
return true;
}
+58 -2
View File
@@ -59,9 +59,28 @@ namespace MobileGL {
EGLint* value) const;
// Context
// `deferGLState`: the context is created without its GL state, which
// BuildContextGLState builds later. Building it creates the context's default
// objects, and a split client has to tell its server which context they belong to
// first (the server must know the context before anything is filed under it).
EGLContextHandle CreateContext(EGLDisplayHandle display, EGLConfigHandle config,
EGLContextHandle shareCtx, const EGLint* attribList);
Bool DestroyContext(EGLDisplayHandle display, EGLContextHandle context);
EGLContextHandle shareCtx, const EGLint* attribList,
Bool deferGLState = false);
Bool BuildContextGLState(EGLContextHandle context);
// EGL 1.5 3.7.2: a context current to some thread is not destroyed until it is no
// longer current. Such a destroy answers true with `*deferred` set: the handle is
// invalid for any new use from here on, and the release that ends its last binding
// moves it to the reaped list (TakeReapedContexts), where the caller finishes it.
Bool DestroyContext(EGLDisplayHandle display, EGLContextHandle context, Bool* deferred = nullptr);
struct ReapedContext {
EGLContextHandle Handle = nullptr;
Uint64 ClientContextToken = 0;
Uint64 ShareGroupToken = 0;
SharedPtr<GLState::GLContext> GLStateObject;
};
// The contexts whose deferred destroy a release has just completed, oldest first.
// The caller owns them now: dropping a GLStateObject destroys the context's objects.
Vector<ReapedContext> TakeReapedContexts();
Bool QueryContext(EGLDisplayHandle display, EGLContextHandle context, EGLint attribute,
EGLint* value) const;
Bool ValidateContext(EGLContextHandle context) const;
@@ -69,6 +88,14 @@ namespace MobileGL {
Bool IsCurrentContextOpenGLCoreProfile() const;
Bool IsCurrentContextOpenGLCompatibilityProfile() const;
EGLint GetCurrentContextFlags() const;
// The calling thread's current context's reset notification behavior
// (EGL_NO_RESET_NOTIFICATION with no context current) and whether it asked for
// robust buffer access.
EGLint GetCurrentContextResetNotificationStrategy() const;
Bool IsCurrentContextRobustAccessRequested() const;
// The client API the calling thread's current context was created for
// (EGL_OPENGL_API with no context current).
EGLenum GetCurrentContextClientAPI() 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
@@ -141,6 +168,15 @@ namespace MobileGL {
Bool GetSyncAttrib(EGLDisplayHandle display, EGLSyncHandle sync, EGLint attribute,
EGLAttrib* value) const;
Bool WaitSync(EGLDisplayHandle display, EGLSyncHandle sync, EGLint flags) const;
// EGL_ANDROID_native_fence_sync. A native fence sync owns a sync_file descriptor and
// its status is that descriptor's: CreateSync takes one an application imports
// (EGL_SYNC_NATIVE_FENCE_FD_ANDROID), and CreateNativeFenceSync takes the one a fence
// command produced (`condition` EGL_SYNC_PRIOR_COMMANDS_COMPLETE; fd -1 = the fenced
// work has completed and no descriptor came with it). Both take ownership of `fd`,
// also on failure. DupNativeFenceFD hands out a copy, or EGL_NO_NATIVE_FENCE_FD_ANDROID
// (EGL_BAD_PARAMETER) when the sync has none. Not on Windows, which has no sync_file.
EGLSyncHandle CreateNativeFenceSync(EGLDisplayHandle display, int fd, EGLenum condition);
EGLint DupNativeFenceFD(EGLDisplayHandle display, EGLSyncHandle sync);
// Image
EGLImageHandle CreateImage(EGLDisplayHandle display, EGLContextHandle context, EGLenum target,
@@ -170,6 +206,10 @@ namespace MobileGL {
EGLint Width = 0;
EGLint Height = 0;
Uint32 Fourcc = 0;
// The server session the reference was taken on (MG_State::CurrentWireEpoch() at the
// import). A reference of an ended session died with it and is never released on
// another: the same image imported again on the fresh session has the same Id.
Uint64 WireEpoch = 0;
};
static constexpr Uint32 kDrmFourccAbgr8888 = 0x34324241u; // 'AB24'
static constexpr Uint32 kDrmFourccXbgr8888 = 0x34324258u; // 'XB24'
@@ -259,13 +299,26 @@ namespace MobileGL {
// 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;
// The group GLStateObject joins when it is built later (CreateContext's
// deferGLState); null once it is built.
SharedPtr<GLState::ShareGroupState> PendingShareGroup;
// eglDestroyContext was called while the context was current to a thread.
Bool DestroyPending = false;
EGLenum ClientAPI = EGL_OPENGL_API;
EGLint ClientVersion = 1;
EGLint MajorVersion = 1;
EGLint MinorVersion = 0;
EGLint OpenGLProfileMask = 0;
EGLint EGLContextFlags = 0;
// GL_CONTEXT_FLAGS as requested, without GL_CONTEXT_FLAG_ROBUST_ACCESS_BIT: that
// one is reported only where robust buffer access is actually provided, which
// the GL layer decides (RobustAccessRequested below is the request).
EGLint OpenGLContextFlags = 0;
// EGL_EXT_create_context_robustness / EGL 1.5. EGL_NO_RESET_NOTIFICATION or
// EGL_LOSE_CONTEXT_ON_RESET; contexts that share must agree on it.
EGLint ResetNotificationStrategy = EGL_NO_RESET_NOTIFICATION;
// EGL_CONTEXT_OPENGL_ROBUST_ACCESS(_EXT) or the KHR flag bit was given as true.
Bool RobustAccessRequested = false;
};
struct SurfaceObject {
@@ -291,6 +344,8 @@ namespace MobileGL {
EGLenum Type = EGL_SYNC_FENCE;
EGLenum Condition = EGL_SYNC_PRIOR_COMMANDS_COMPLETE;
EGLenum Status = EGL_SIGNALED;
// EGL_SYNC_NATIVE_FENCE_ANDROID only: the owned sync_file, -1 = none (signaled).
int NativeFd = -1;
};
struct ImageObject {
@@ -363,6 +418,7 @@ namespace MobileGL {
UnorderedMap<EGLConfigHandle, ConfigObject> m_configs;
UnorderedMap<EGLSurfaceHandle, SurfaceObject> m_surfaces;
UnorderedMap<EGLContextHandle, ContextObject> m_contexts;
Vector<ReapedContext> m_reapedContexts;
UnorderedMap<EGLSyncHandle, SyncObject> m_syncs;
UnorderedMap<EGLImageHandle, ImageObject> m_images;
Vector<Uint64> m_orphanedSharedImages;
+3
View File
@@ -1665,4 +1665,7 @@ namespace MobileGL::MG_State {
// Leak-at-exit storage; see GlobalObjects.cpp.
thread_local SharedPtr<GLState::GLContext> pGLContext;
#if MOBILEGL_BUILD_DISAGGREGATED
thread_local Bool tThreadReleasedLostContext = false;
#endif
} // namespace MobileGL::MG_State
+17
View File
@@ -115,6 +115,13 @@ namespace MobileGL {
m_contextLostReported = true;
return true;
}
// True the first time glGetGraphicsResetStatus reports this context's reset (the
// one time it names the cause in the log).
Bool TakeResetStatusReport() {
if (m_resetStatusReported) return false;
m_resetStatusReported = true;
return true;
}
#endif
// Error
@@ -743,6 +750,7 @@ namespace MobileGL {
// See WireEpoch(); taken when the context is constructed.
Uint64 m_wireEpoch = CurrentWireEpoch();
Bool m_contextLostReported = false;
Bool m_resetStatusReported = false;
#endif
};
} // namespace GLState
@@ -754,6 +762,15 @@ namespace MobileGL {
// 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;
#if MOBILEGL_BUILD_DISAGGREGATED
// True on a thread whose last EGL release let go of a context lost with an ended server
// session, until it makes a context current again. The release hands such a thread the
// process default rather than the lost context's GL state (which would make the thread's
// TLS that state's last owner), so this is what keeps the thread answering as lost: an
// application that releases its context before asking glGetGraphicsResetStatus - Qt's
// render threads do - still learns that the context is gone and rebuilds it.
extern thread_local Bool tThreadReleasedLostContext;
#endif
// 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
+2
View File
@@ -105,4 +105,6 @@ endif()
# is only registered there. Nothing under MG_Remote is compiled otherwise.
if (MOBILEGL_BUILD_DISAGGREGATED)
add_subdirectory(Wire)
# The GBM backend glamor uses (Xwayland on MobileGL), through the system's loader.
add_subdirectory(Gbm)
endif()
+259
View File
@@ -1,5 +1,6 @@
#include <gtest/gtest.h>
#include <MG_State/EGLState/Core.h>
#include <MG_State/GLState/Core.h>
#include <EGL/eglext.h>
#include <future>
#include <memory>
@@ -149,6 +150,99 @@ TEST(EGLStateMakeCurrent, SurfacelessBindIsAcceptedAndRecordsNoSurface) {
EXPECT_TRUE(fixture->State.MakeCurrent(EGL_NO_DISPLAY, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT));
}
// EGL 1.5 3.7.2: a context current to a thread is destroyed once it is no longer current. The
// destroy answers EGL_TRUE (it used to be EGL_BAD_ACCESS), the handle is dead for any new use at
// once, the thread keeps it current until it releases it, and that release hands the context -
// with its GL state, whose last owner the caller now is - to whoever finishes the destroy.
TEST(EGLStateDestroyContext, DestroyingAContextCurrentOnAThreadIsDeferredUntilItsRelease) {
auto fixture = CreateFixture();
auto& state = fixture->State;
const MobileGL::Uint64 token = state.GetContextClientToken(fixture->Context);
std::weak_ptr<MobileGL::MG_State::GLState::GLContext> glState = state.GetContextGLState(fixture->Context);
ASSERT_FALSE(glState.expired());
std::promise<void> current;
std::promise<void> destroyed;
auto currentFuture = current.get_future();
auto destroyedFuture = destroyed.get_future();
bool stillCurrentAfterDestroy = false;
bool rebindRefused = false;
EGLint rebindError = EGL_SUCCESS;
size_t reapedWhileCurrent = 0;
std::thread owner([&] {
EXPECT_TRUE(state.MakeCurrent(fixture->Display, fixture->Surface, fixture->Surface, fixture->Context));
current.set_value();
destroyedFuture.wait();
stillCurrentAfterDestroy = state.GetCurrentContext() == fixture->Context;
rebindRefused = !state.MakeCurrent(fixture->Display, fixture->Surface, fixture->Surface, fixture->Context);
rebindError = state.ConsumeError();
reapedWhileCurrent = state.TakeReapedContexts().size();
EXPECT_TRUE(state.MakeCurrent(EGL_NO_DISPLAY, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT));
});
currentFuture.wait();
bool deferred = false;
EXPECT_TRUE(state.DestroyContext(fixture->Display, fixture->Context, &deferred));
EXPECT_TRUE(deferred);
EXPECT_FALSE(state.ValidateContext(fixture->Context));
EXPECT_FALSE(state.DestroyContext(fixture->Display, fixture->Context));
EXPECT_EQ(state.ConsumeError(), EGL_BAD_CONTEXT);
destroyed.set_value();
owner.join();
EXPECT_TRUE(stillCurrentAfterDestroy);
EXPECT_TRUE(rebindRefused);
EXPECT_EQ(rebindError, EGL_BAD_CONTEXT);
EXPECT_EQ(reapedWhileCurrent, 0u);
auto reaped = state.TakeReapedContexts();
ASSERT_EQ(reaped.size(), 1u);
EXPECT_EQ(reaped[0].Handle, fixture->Context);
EXPECT_EQ(reaped[0].ClientContextToken, token);
ASSERT_NE(reaped[0].GLStateObject, nullptr);
// Nothing else holds the GL state - neither the book nor the thread that released it.
reaped.clear();
EXPECT_TRUE(glState.expired());
}
// A thread that had no GL state before its first bind does not keep the context's after releasing
// it. Keeping it made the thread's TLS the last owner of a context destroyed after the release, and
// the context's objects then died in the thread-exit destructor of that TLS, outside every entry
// point and its lock.
TEST(EGLStateDestroyContext, ReleasingThreadDoesNotKeepTheContextsGLState) {
auto fixture = CreateFixture();
auto& state = fixture->State;
std::weak_ptr<MobileGL::MG_State::GLState::GLContext> glState = state.GetContextGLState(fixture->Context);
std::thread worker([&] {
EXPECT_TRUE(state.MakeCurrent(fixture->Display, fixture->Surface, fixture->Surface, fixture->Context));
EXPECT_EQ(MobileGL::MG_State::pGLContext.get(), glState.lock().get());
EXPECT_TRUE(state.MakeCurrent(EGL_NO_DISPLAY, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT));
EXPECT_NE(MobileGL::MG_State::pGLContext.get(), glState.lock().get());
bool deferred = true;
EXPECT_TRUE(state.DestroyContext(fixture->Display, fixture->Context, &deferred));
EXPECT_FALSE(deferred);
// Ended here, by the destroy - not later, when this thread exits.
EXPECT_TRUE(glState.expired());
});
worker.join();
}
// A context created with its GL state deferred has none until BuildContextGLState builds it (a
// split client tells its server about the context first, then builds the state under it).
TEST(EGLStateCreateContext, DeferredGLStateIsBuiltOnRequestInTheShareGroup) {
auto fixture = CreateFixture();
auto& state = fixture->State;
const auto shared = state.CreateContext(fixture->Display, fixture->Config, fixture->Context, nullptr,
/*deferGLState=*/true);
ASSERT_NE(shared, EGL_NO_CONTEXT);
EXPECT_EQ(state.GetContextGLState(shared), nullptr);
EXPECT_EQ(state.GetContextShareGroupToken(shared), state.GetContextShareGroupToken(fixture->Context));
ASSERT_TRUE(state.BuildContextGLState(shared));
const auto built = state.GetContextGLState(shared);
ASSERT_NE(built, nullptr);
EXPECT_EQ(built->GetShareGroup(), state.GetContextGLState(fixture->Context)->GetShareGroup());
ASSERT_TRUE(state.BuildContextGLState(shared)); // idempotent
EXPECT_EQ(state.GetContextGLState(shared), built);
}
// The extension relaxes only the both-absent case: one surface without the other stays a mismatch.
TEST(EGLStateMakeCurrent, OneSidedSurfaceIsStillAMismatch) {
auto fixture = CreateFixture();
@@ -344,3 +438,168 @@ TEST(EGLStateDmaBufImport, FormatAndModifierQueries) {
EXPECT_FALSE(fixture->State.QueryDmaBufFormats(fixture->Display, true, 0, nullptr, &count));
EXPECT_EQ(fixture->State.ConsumeError(), EGL_NOT_INITIALIZED);
}
// EGL_EXT_create_context_robustness / EGL 1.5: the reset notification behavior a context is
// created with, under both names of the attribute (the extension's, which Chrome, KWin and Qt
// pass, and EGL 1.5's, which ANGLE's GL-on-EGL backend passes for its own native context), the
// errors the extension defines, and robust buffer access recorded as a request only.
TEST(EGLStateRobustness, ResetNotificationStrategyIsRecordedValidatedAndMatchedAcrossShares) {
auto fixture = CreateFixture();
auto& state = fixture->State;
auto strategyOf = [&](StateContext::EGLContextHandle context) {
EXPECT_TRUE(state.MakeCurrent(fixture->Display, fixture->Surface, fixture->Surface, context));
const EGLint strategy = state.GetCurrentContextResetNotificationStrategy();
EXPECT_TRUE(state.MakeCurrent(fixture->Display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT));
return strategy;
};
// The default, and no context current at all.
EXPECT_EQ(state.GetCurrentContextResetNotificationStrategy(), EGL_NO_RESET_NOTIFICATION);
EXPECT_EQ(strategyOf(fixture->Context), EGL_NO_RESET_NOTIFICATION);
const EGLint loseExt[] = {EGL_CONTEXT_OPENGL_RESET_NOTIFICATION_STRATEGY_EXT, EGL_LOSE_CONTEXT_ON_RESET_EXT,
EGL_NONE};
const auto robustExt = state.CreateContext(fixture->Display, fixture->Config, EGL_NO_CONTEXT, loseExt);
ASSERT_NE(robustExt, EGL_NO_CONTEXT);
EXPECT_EQ(strategyOf(robustExt), EGL_LOSE_CONTEXT_ON_RESET);
// ANGLE's shape: an ES 3.2 request with the EGL 1.5 name.
const EGLint loseCore[] = {EGL_CONTEXT_MAJOR_VERSION, 3, EGL_CONTEXT_MINOR_VERSION, 2,
EGL_CONTEXT_OPENGL_RESET_NOTIFICATION_STRATEGY, EGL_LOSE_CONTEXT_ON_RESET, EGL_NONE};
const auto robustCore = state.CreateContext(fixture->Display, fixture->Config, EGL_NO_CONTEXT, loseCore);
ASSERT_NE(robustCore, EGL_NO_CONTEXT);
EXPECT_EQ(strategyOf(robustCore), EGL_LOSE_CONTEXT_ON_RESET);
const EGLint noReset[] = {EGL_CONTEXT_OPENGL_RESET_NOTIFICATION_STRATEGY_EXT, EGL_NO_RESET_NOTIFICATION_EXT,
EGL_NONE};
const auto plain = state.CreateContext(fixture->Display, fixture->Config, EGL_NO_CONTEXT, noReset);
ASSERT_NE(plain, EGL_NO_CONTEXT);
EXPECT_EQ(strategyOf(plain), EGL_NO_RESET_NOTIFICATION);
// A value that is neither: EGL_BAD_ATTRIBUTE, for both names.
const EGLint badExt[] = {EGL_CONTEXT_OPENGL_RESET_NOTIFICATION_STRATEGY_EXT, EGL_TRUE, EGL_NONE};
EXPECT_EQ(state.CreateContext(fixture->Display, fixture->Config, EGL_NO_CONTEXT, badExt), EGL_NO_CONTEXT);
EXPECT_EQ(state.ConsumeError(), EGL_BAD_ATTRIBUTE);
const EGLint badCore[] = {EGL_CONTEXT_OPENGL_RESET_NOTIFICATION_STRATEGY, 0, EGL_NONE};
EXPECT_EQ(state.CreateContext(fixture->Display, fixture->Config, EGL_NO_CONTEXT, badCore), EGL_NO_CONTEXT);
EXPECT_EQ(state.ConsumeError(), EGL_BAD_ATTRIBUTE);
// Sharing: the two must agree (EGL_BAD_MATCH), in both directions; agreeing shares are made.
EXPECT_EQ(state.CreateContext(fixture->Display, fixture->Config, robustExt, nullptr), EGL_NO_CONTEXT);
EXPECT_EQ(state.ConsumeError(), EGL_BAD_MATCH);
EXPECT_EQ(state.CreateContext(fixture->Display, fixture->Config, fixture->Context, loseExt), EGL_NO_CONTEXT);
EXPECT_EQ(state.ConsumeError(), EGL_BAD_MATCH);
const auto sharedRobust = state.CreateContext(fixture->Display, fixture->Config, robustExt, loseCore);
ASSERT_NE(sharedRobust, EGL_NO_CONTEXT);
EXPECT_EQ(state.GetContextShareGroupToken(sharedRobust), state.GetContextShareGroupToken(robustExt));
EXPECT_EQ(strategyOf(sharedRobust), EGL_LOSE_CONTEXT_ON_RESET);
const auto sharedPlain = state.CreateContext(fixture->Display, fixture->Config, fixture->Context, noReset);
EXPECT_NE(sharedPlain, EGL_NO_CONTEXT);
}
TEST(EGLStateRobustness, RobustAccessIsARequestAndNeverAGLContextFlagByItself) {
auto fixture = CreateFixture();
auto& state = fixture->State;
auto requestOf = [&](const EGLint* attribs, EGLint* flags) {
const auto context = state.CreateContext(fixture->Display, fixture->Config, EGL_NO_CONTEXT, attribs);
EXPECT_NE(context, EGL_NO_CONTEXT);
EXPECT_TRUE(state.MakeCurrent(fixture->Display, fixture->Surface, fixture->Surface, context));
const bool requested = state.IsCurrentContextRobustAccessRequested();
*flags = state.GetCurrentContextFlags();
EXPECT_TRUE(state.MakeCurrent(fixture->Display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT));
return requested;
};
EGLint flags = 0;
const EGLint none[] = {EGL_NONE};
EXPECT_FALSE(requestOf(none, &flags));
const EGLint ext[] = {EGL_CONTEXT_OPENGL_ROBUST_ACCESS_EXT, EGL_TRUE, EGL_NONE};
EXPECT_TRUE(requestOf(ext, &flags));
EXPECT_EQ(flags & GL_CONTEXT_FLAG_ROBUST_ACCESS_BIT, 0) << "GL_CONTEXT_FLAGS claims robust access";
const EGLint core[] = {EGL_CONTEXT_OPENGL_ROBUST_ACCESS, EGL_TRUE, EGL_NONE};
EXPECT_TRUE(requestOf(core, &flags));
EXPECT_EQ(flags & GL_CONTEXT_FLAG_ROBUST_ACCESS_BIT, 0);
// KWin's desktop candidate: the KHR flag bit, next to the debug bit that IS a GL flag.
const EGLint khr[] = {EGL_CONTEXT_FLAGS_KHR, EGL_CONTEXT_OPENGL_ROBUST_ACCESS_BIT_KHR | EGL_CONTEXT_OPENGL_DEBUG_BIT_KHR,
EGL_NONE};
EXPECT_TRUE(requestOf(khr, &flags));
EXPECT_EQ(flags & GL_CONTEXT_FLAG_ROBUST_ACCESS_BIT, 0);
EXPECT_NE(flags & GL_CONTEXT_FLAG_DEBUG_BIT, 0);
const EGLint off[] = {EGL_CONTEXT_OPENGL_ROBUST_ACCESS_EXT, EGL_FALSE, EGL_NONE};
EXPECT_FALSE(requestOf(off, &flags));
}
#if !defined(_WIN32)
#include <fcntl.h>
#include <poll.h>
#include <unistd.h>
// EGL_ANDROID_native_fence_sync, the half that is pure state: a native fence sync owns a sync_file
// and answers its status, waits and copies from it. A pipe's read end stands in for the sync_file -
// it polls readable once something is written, as a fence does once it signals.
TEST(EGLStateNativeFence, AnImportedDescriptorDecidesStatusWaitsAndCopies) {
auto fixture = CreateFixture();
int fence[2] = {-1, -1};
ASSERT_EQ(::pipe(fence), 0);
const EGLAttrib attribs[] = {EGL_SYNC_NATIVE_FENCE_FD_ANDROID, fence[0], EGL_NONE};
const EGLSync sync = fixture->State.CreateSync(fixture->Display, EGL_SYNC_NATIVE_FENCE_ANDROID, attribs);
ASSERT_NE(sync, EGL_NO_SYNC) << "error 0x" << std::hex << fixture->State.ConsumeError();
EGLAttrib value = 0;
ASSERT_TRUE(fixture->State.GetSyncAttrib(fixture->Display, sync, EGL_SYNC_TYPE, &value));
EXPECT_EQ(value, static_cast<EGLAttrib>(EGL_SYNC_NATIVE_FENCE_ANDROID));
ASSERT_TRUE(fixture->State.GetSyncAttrib(fixture->Display, sync, EGL_SYNC_CONDITION, &value));
EXPECT_EQ(value, static_cast<EGLAttrib>(EGL_SYNC_NATIVE_FENCE_SIGNALED_ANDROID));
ASSERT_TRUE(fixture->State.GetSyncAttrib(fixture->Display, sync, EGL_SYNC_STATUS, &value));
EXPECT_EQ(value, static_cast<EGLAttrib>(EGL_UNSIGNALED));
EXPECT_EQ(fixture->State.ClientWaitSync(fixture->Display, sync, 0, 0), EGL_TIMEOUT_EXPIRED);
EXPECT_EQ(fixture->State.ClientWaitSync(fixture->Display, sync, 0, 5u * 1000 * 1000), EGL_TIMEOUT_EXPIRED);
// A copy is a descriptor of the same fence: it signals with it.
const EGLint copy = fixture->State.DupNativeFenceFD(fixture->Display, sync);
ASSERT_GE(copy, 0);
EXPECT_NE(copy, fence[0]);
ASSERT_EQ(::write(fence[1], "s", 1), 1);
ASSERT_TRUE(fixture->State.GetSyncAttrib(fixture->Display, sync, EGL_SYNC_STATUS, &value));
EXPECT_EQ(value, static_cast<EGLAttrib>(EGL_SIGNALED));
EXPECT_EQ(fixture->State.ClientWaitSync(fixture->Display, sync, 0, EGL_FOREVER), EGL_CONDITION_SATISFIED);
EXPECT_TRUE(fixture->State.WaitSync(fixture->Display, sync, 0));
pollfd entry{copy, POLLIN, 0};
EXPECT_EQ(::poll(&entry, 1, 0), 1);
// The sync owned its descriptor: destroying it closes that, and the copy stays the caller's.
EXPECT_TRUE(fixture->State.DestroySync(fixture->Display, sync));
EXPECT_EQ(::fcntl(fence[0], F_GETFD), -1);
EXPECT_NE(::fcntl(copy, F_GETFD), -1);
::close(copy);
::close(fence[1]);
}
// A fence command whose work completed with no descriptor to show for it is signaled, and has no
// descriptor to copy; a native fence without one is no import either, and an ordinary fence has
// none to copy.
TEST(EGLStateNativeFence, AFenceCommandWithoutADescriptorIsSignaledAndHasNoneToCopy) {
auto fixture = CreateFixture();
const EGLSync done = fixture->State.CreateNativeFenceSync(fixture->Display, -1, EGL_SYNC_PRIOR_COMMANDS_COMPLETE);
ASSERT_NE(done, EGL_NO_SYNC);
EGLAttrib value = 0;
ASSERT_TRUE(fixture->State.GetSyncAttrib(fixture->Display, done, EGL_SYNC_STATUS, &value));
EXPECT_EQ(value, static_cast<EGLAttrib>(EGL_SIGNALED));
ASSERT_TRUE(fixture->State.GetSyncAttrib(fixture->Display, done, EGL_SYNC_CONDITION, &value));
EXPECT_EQ(value, static_cast<EGLAttrib>(EGL_SYNC_PRIOR_COMMANDS_COMPLETE));
EXPECT_EQ(fixture->State.ClientWaitSync(fixture->Display, done, 0, 0), EGL_CONDITION_SATISFIED);
EXPECT_EQ(fixture->State.DupNativeFenceFD(fixture->Display, done), EGL_NO_NATIVE_FENCE_FD_ANDROID);
EXPECT_EQ(fixture->State.ConsumeError(), EGL_BAD_PARAMETER);
EXPECT_TRUE(fixture->State.DestroySync(fixture->Display, done));
const EGLAttrib none[] = {EGL_NONE};
EXPECT_EQ(fixture->State.CreateSync(fixture->Display, EGL_SYNC_NATIVE_FENCE_ANDROID, none), EGL_NO_SYNC);
EXPECT_EQ(fixture->State.ConsumeError(), EGL_BAD_ATTRIBUTE);
const EGLSync plain = fixture->State.CreateSync(fixture->Display, EGL_SYNC_FENCE, none);
ASSERT_NE(plain, EGL_NO_SYNC);
EXPECT_EQ(fixture->State.DupNativeFenceFD(fixture->Display, plain), EGL_NO_NATIVE_FENCE_FD_ANDROID);
EXPECT_EQ(fixture->State.ConsumeError(), EGL_BAD_PARAMETER);
EXPECT_TRUE(fixture->State.DestroySync(fixture->Display, plain));
}
#endif
+25
View File
@@ -0,0 +1,25 @@
cmake_minimum_required(VERSION 3.14)
# mobilegl_gbm.so through the system's GBM loader, the calls Xwayland's glamor makes, over a fake of
# libMobileGL's shared-image C ABI. Only where the GBM backend itself is built (gbm headers found).
find_library(MOBILEGL_TEST_GBM_LIBRARY gbm)
if (NOT TARGET mobilegl_gbm OR NOT MOBILEGL_TEST_GBM_LIBRARY)
message(STATUS "MobileGL: GbmGlamorTest not built (no mobilegl_gbm target or no libgbm)")
return()
endif()
add_library(mobilegl_fake_shared_images MODULE FakeSharedImageLibrary.cpp)
set_target_properties(mobilegl_fake_shared_images PROPERTIES PREFIX "" CXX_VISIBILITY_PRESET hidden)
target_include_directories(mobilegl_fake_shared_images PRIVATE ${MGL_ROOT}/MobileGL/MG_Impl)
add_executable(GbmGlamorTest GbmGlamorTest.cpp)
add_dependencies(GbmGlamorTest mobilegl_gbm mobilegl_fake_shared_images)
target_include_directories(GbmGlamorTest PRIVATE ${MOBILEGL_GBM_INCLUDE_DIR})
target_compile_definitions(GbmGlamorTest PRIVATE
MOBILEGL_TEST_GBM_BACKEND_DIR="$<TARGET_FILE_DIR:mobilegl_gbm>"
MOBILEGL_TEST_FAKE_SHARED_IMAGE_LIBRARY="$<TARGET_FILE:mobilegl_fake_shared_images>"
)
target_link_libraries(GbmGlamorTest PRIVATE GTest::gtest_main ${MOBILEGL_TEST_GBM_LIBRARY} ${CMAKE_DL_LIBS})
include(GoogleTest)
gtest_discover_tests(GbmGlamorTest DISCOVERY_TIMEOUT 30 PROPERTIES LABELS unit)
@@ -0,0 +1,105 @@
// MobileGL - MobileGL/MG_Test/Gbm/FakeSharedImageLibrary.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
// A stand-in for libMobileGL.so's shared-image C ABI (MG_Impl/SharedImageApi.h), loaded by
// mobilegl_gbm.so through MOBILEGL_GBM_LIBRARY in GbmGlamorTest: images are memfds, identified on
// import by inode as the server identifies its dma-bufs. fake_shared_image_* let the test look in.
#include "SharedImageApi.h"
#include <cerrno>
#include <map>
#include <mutex>
#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>
#define FAKE_EXPORT extern "C" __attribute__((visibility("default")))
namespace {
struct FakeImage {
int fd = -1;
ino_t inode = 0;
uint32_t width = 0, height = 0, fourcc = 0;
int references = 0;
};
std::mutex g_mutex;
std::map<uint64_t, FakeImage> g_images;
uint64_t g_nextId = 1;
int g_imports = 0;
bool Supported(uint32_t fourcc) {
return fourcc == MOBILEGL_SHARED_IMAGE_FOURCC_ABGR8888 || fourcc == MOBILEGL_SHARED_IMAGE_FOURCC_XBGR8888 ||
fourcc == MOBILEGL_SHARED_IMAGE_FOURCC_ARGB8888 || fourcc == MOBILEGL_SHARED_IMAGE_FOURCC_XRGB8888;
}
} // namespace
FAKE_EXPORT uint32_t mobilegl_shared_image_abi_version(void) { return MOBILEGL_SHARED_IMAGE_ABI_VERSION; }
FAKE_EXPORT int mobilegl_server_available(void) { return 1; }
FAKE_EXPORT int mobilegl_shared_image_formats(uint32_t*, uint32_t) { return 4; }
FAKE_EXPORT int mobilegl_shared_image_allocate(uint32_t width, uint32_t height, uint32_t fourcc,
struct mobilegl_shared_image* out) {
if (width == 0 || height == 0 || !Supported(fourcc) || out == nullptr) return -EINVAL;
const int fd = ::memfd_create("fake-shared-image", MFD_CLOEXEC);
if (fd < 0 || ::ftruncate(fd, static_cast<off_t>(width) * height * 4) != 0) return -EIO;
struct stat st {};
::fstat(fd, &st);
const std::lock_guard<std::mutex> lock(g_mutex);
const uint64_t id = g_nextId++;
g_images[id] = FakeImage{fd, st.st_ino, width, height, fourcc, 1};
out->width = width;
out->height = height;
out->fourcc = fourcc;
out->id = id;
out->fd = ::dup(fd);
out->stride = width * 4;
out->offset = 0;
out->modifier = 0x00ffffffffffffffull;
return 0;
}
FAKE_EXPORT int mobilegl_shared_image_import(int fd, uint32_t width, uint32_t height, uint32_t fourcc,
uint64_t* out_id) {
struct stat st {};
if (fd < 0 || ::fstat(fd, &st) != 0 || !Supported(fourcc)) return -EINVAL;
const std::lock_guard<std::mutex> lock(g_mutex);
for (auto& [id, image] : g_images) {
if (image.inode != st.st_ino) continue;
if (image.width != width || image.height != height) return -EIO;
++image.references;
++g_imports;
if (out_id != nullptr) *out_id = id;
return 0;
}
return -EIO; // not one of "the server's" images
}
FAKE_EXPORT int mobilegl_shared_image_release(uint64_t id) {
const std::lock_guard<std::mutex> lock(g_mutex);
auto it = g_images.find(id);
if (it == g_images.end()) return -EINVAL;
if (--it->second.references == 0) {
::close(it->second.fd);
g_images.erase(it);
}
return 0;
}
FAKE_EXPORT int fake_shared_image_live(void) {
const std::lock_guard<std::mutex> lock(g_mutex);
return static_cast<int>(g_images.size());
}
FAKE_EXPORT int fake_shared_image_imports(void) {
const std::lock_guard<std::mutex> lock(g_mutex);
return g_imports;
}
+182
View File
@@ -0,0 +1,182 @@
// MobileGL - MobileGL/MG_Test/Gbm/GbmGlamorTest.cpp
// Copyright (c) 2025-2026 MobileGL-Dev
// Licensed under the GNU Lesser General Public License v3.0:
// https://www.gnu.org/licenses/gpl-3.0.txt
// https://www.gnu.org/licenses/lgpl-3.0.txt
// SPDX-License-Identifier: LGPL-3.0-only
// End of Source File Header
// mobilegl_gbm.so THROUGH THE SYSTEM'S GBM LOADER, the way Xwayland's glamor drives it
// (hw/xwayland/xwayland-glamor-gbm.c, 24.1): gbm_create_device on a character device with
// GBM_BACKEND=mobilegl, window pixmaps from gbm_bo_create_with_modifiers2 with the compositor's
// {INVALID, LINEAR} (else gbm_bo_create), their planes exported for EGL and linux-dmabuf, and a
// DRI3 client's buffer imported back with GBM_BO_IMPORT_FD / _FD_MODIFIER. The shared images come
// from a fake of libMobileGL's C ABI (FakeSharedImageLibrary.cpp).
#include <gbm.h>
#include <gtest/gtest.h>
#include <cstdlib>
#include <cstring>
#include <dlfcn.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>
#ifndef DRM_FORMAT_MOD_INVALID
#define DRM_FORMAT_MOD_INVALID 0x00ffffffffffffffULL
#endif
#ifndef DRM_FORMAT_MOD_LINEAR
#define DRM_FORMAT_MOD_LINEAR 0ULL
#endif
namespace {
using CountFn = int (*)();
class GbmGlamor : public ::testing::Test {
protected:
void SetUp() override {
::setenv("GBM_BACKEND", "mobilegl", 1);
::setenv("GBM_BACKENDS_PATH", MOBILEGL_TEST_GBM_BACKEND_DIR, 1);
::setenv("MOBILEGL_GBM_LIBRARY", MOBILEGL_TEST_FAKE_SHARED_IMAGE_LIBRARY, 1);
m_fd = ::open("/dev/null", O_RDWR | O_CLOEXEC);
ASSERT_GE(m_fd, 0);
m_gbm = gbm_create_device(m_fd);
ASSERT_NE(m_gbm, nullptr) << "libgbm did not take the mobilegl backend";
void* fake = dlopen(MOBILEGL_TEST_FAKE_SHARED_IMAGE_LIBRARY, RTLD_NOW | RTLD_NOLOAD);
ASSERT_NE(fake, nullptr) << "the backend did not load the shared-image library";
m_live = reinterpret_cast<CountFn>(dlsym(fake, "fake_shared_image_live"));
m_imports = reinterpret_cast<CountFn>(dlsym(fake, "fake_shared_image_imports"));
ASSERT_TRUE(m_live && m_imports);
m_liveAtStart = m_live();
}
void TearDown() override {
if (m_gbm != nullptr) gbm_device_destroy(m_gbm);
if (m_fd >= 0) ::close(m_fd);
}
int m_fd = -1;
gbm_device* m_gbm = nullptr;
CountFn m_live = nullptr;
CountFn m_imports = nullptr;
int m_liveAtStart = 0;
};
} // namespace
TEST_F(GbmGlamor, TheDeviceIsMobileGLsAndTakesTheFormatsGlamorAsksFor) {
// Xwayland names the screen's GLX vendor after the backend (anything but "drm").
EXPECT_STREQ(gbm_device_get_backend_name(m_gbm), "mobilegl");
// gbm_format_for_depth: 24 -> XRGB8888 (ARGB8888 under GLES glamor), 32 -> ARGB8888.
EXPECT_TRUE(gbm_device_is_format_supported(m_gbm, GBM_FORMAT_XRGB8888, GBM_BO_USE_RENDERING));
EXPECT_TRUE(gbm_device_is_format_supported(m_gbm, GBM_FORMAT_ARGB8888, GBM_BO_USE_RENDERING | GBM_BO_USE_SCANOUT));
EXPECT_FALSE(gbm_device_is_format_supported(m_gbm, GBM_FORMAT_RGB565, GBM_BO_USE_RENDERING));
}
TEST_F(GbmGlamor, AWindowPixmapIsASharedImageWithOneExportablePlane) {
// The compositor's tranche for a MobileGL EGL lists INVALID and LINEAR (implicit modifiers).
const uint64_t modifiers[] = {DRM_FORMAT_MOD_INVALID, DRM_FORMAT_MOD_LINEAR};
gbm_bo* bo = gbm_bo_create_with_modifiers2(m_gbm, 640, 480, GBM_FORMAT_XRGB8888, modifiers, 2,
GBM_BO_USE_RENDERING | GBM_BO_USE_SCANOUT);
ASSERT_NE(bo, nullptr) << std::strerror(errno);
EXPECT_EQ(m_live(), m_liveAtStart + 1);
EXPECT_EQ(gbm_bo_get_width(bo), 640u);
EXPECT_EQ(gbm_bo_get_height(bo), 480u);
EXPECT_EQ(gbm_bo_get_format(bo), GBM_FORMAT_XRGB8888);
EXPECT_EQ(gbm_bo_get_modifier(bo), DRM_FORMAT_MOD_INVALID) << "the layout is the allocator's";
// xwl_glamor_gbm_create_pixmap_for_bo / init_buffer_params_with_modifiers:
ASSERT_EQ(gbm_bo_get_plane_count(bo), 1);
const int fd = gbm_bo_get_fd_for_plane(bo, 0);
ASSERT_GE(fd, 0);
EXPECT_NE(gbm_bo_get_handle_for_plane(bo, 0).u32, 0u);
EXPECT_GE(gbm_bo_get_stride_for_plane(bo, 0), 640u * 4u);
EXPECT_EQ(gbm_bo_get_offset(bo, 0), 0u);
// Exports are duplicates of one dma-buf: the same inode every time.
const int again = gbm_bo_get_fd(bo);
struct stat a {}, b {};
ASSERT_EQ(::fstat(fd, &a), 0);
ASSERT_EQ(::fstat(again, &b), 0);
EXPECT_EQ(a.st_ino, b.st_ino);
::close(fd);
::close(again);
gbm_bo_destroy(bo);
EXPECT_EQ(m_live(), m_liveAtStart) << "destroying the bo released the image";
}
TEST_F(GbmGlamor, AModifierListWithoutInvalidIsRefusedAndGlamorsFallbackWorks) {
const uint64_t linearOnly[] = {DRM_FORMAT_MOD_LINEAR};
EXPECT_EQ(gbm_bo_create_with_modifiers2(m_gbm, 64, 64, GBM_FORMAT_XRGB8888, linearOnly, 1, GBM_BO_USE_RENDERING),
nullptr);
// glamor's implicit-modifier fallback.
gbm_bo* bo = gbm_bo_create(m_gbm, 64, 64, GBM_FORMAT_XRGB8888, GBM_BO_USE_RENDERING);
ASSERT_NE(bo, nullptr);
EXPECT_EQ(gbm_bo_get_modifier(bo), DRM_FORMAT_MOD_INVALID);
gbm_bo_destroy(bo);
// ...which with a LINEAR-only tranche asks for a linear layout, and that no shared image promises.
EXPECT_EQ(gbm_bo_create(m_gbm, 64, 64, GBM_FORMAT_XRGB8888, GBM_BO_USE_RENDERING | GBM_BO_USE_LINEAR), nullptr);
}
TEST_F(GbmGlamor, ADri3ClientsBufferImportsBackAsTheSameImage) {
// The GLX client's side: an image it allocated (here through the same ABI) handed over as a
// dma-buf with PixmapFromBuffer(s), modifier INVALID.
gbm_bo* clientBo = gbm_bo_create(m_gbm, 320, 200, GBM_FORMAT_XRGB8888, GBM_BO_USE_RENDERING);
ASSERT_NE(clientBo, nullptr);
const int fd = gbm_bo_get_fd(clientBo);
const int importsBefore = m_imports();
// glamor_pixmap_from_fds, modifier INVALID: GBM_BO_IMPORT_FD with the depth's format.
gbm_import_fd_data plain{};
plain.fd = fd;
plain.width = 320;
plain.height = 200;
plain.stride = gbm_bo_get_stride(clientBo);
plain.format = GBM_FORMAT_XRGB8888;
gbm_bo* imported = gbm_bo_import(m_gbm, GBM_BO_IMPORT_FD, &plain, GBM_BO_USE_RENDERING);
ASSERT_NE(imported, nullptr);
EXPECT_EQ(m_imports(), importsBefore + 1);
// ...and re-exported for EGL_LINUX_DMA_BUF_EXT: still that image.
const int reexport = gbm_bo_get_fd_for_plane(imported, 0);
struct stat a {}, b {};
::fstat(fd, &a);
::fstat(reexport, &b);
EXPECT_EQ(a.st_ino, b.st_ino);
::close(reexport);
// A client that sent an explicit modifier list: GBM_BO_IMPORT_FD_MODIFIER.
gbm_import_fd_modifier_data withModifier{};
withModifier.width = 320;
withModifier.height = 200;
withModifier.format = GBM_FORMAT_XRGB8888;
withModifier.num_fds = 1;
withModifier.fds[0] = fd;
withModifier.strides[0] = static_cast<int>(gbm_bo_get_stride(clientBo));
withModifier.modifier = DRM_FORMAT_MOD_INVALID;
gbm_bo* importedModifier = gbm_bo_import(m_gbm, GBM_BO_IMPORT_FD_MODIFIER, &withModifier, GBM_BO_USE_RENDERING);
ASSERT_NE(importedModifier, nullptr);
// A size that disagrees with the image is refused.
plain.width = 321;
EXPECT_EQ(gbm_bo_import(m_gbm, GBM_BO_IMPORT_FD, &plain, GBM_BO_USE_RENDERING), nullptr);
gbm_bo_destroy(importedModifier);
gbm_bo_destroy(imported);
gbm_bo_destroy(clientBo);
::close(fd);
EXPECT_EQ(m_live(), m_liveAtStart) << "every reference was dropped";
}
TEST_F(GbmGlamor, AForeignDmaBufIsRefused) {
// A buffer the MobileGL server never allocated (another driver's client) cannot become a pixmap.
const int foreign = ::memfd_create("foreign", MFD_CLOEXEC);
ASSERT_GE(foreign, 0);
ASSERT_EQ(::ftruncate(foreign, 64 * 64 * 4), 0);
gbm_import_fd_data data{};
data.fd = foreign;
data.width = 64;
data.height = 64;
data.stride = 256;
data.format = GBM_FORMAT_XRGB8888;
EXPECT_EQ(gbm_bo_import(m_gbm, GBM_BO_IMPORT_FD, &data, GBM_BO_USE_RENDERING), nullptr);
::close(foreign);
}
+41 -1
View File
@@ -245,7 +245,7 @@ TEST(FramebufferEmit, TheEmitterIsOneNeverDestroyedProcessSingleton) {
X(FramebufferEmit, EveryNonTexturePointCarriesTheUnknownSentinelsRatherThanZero) \
X(FramebufferEmit, ADeadFramebuffersNamedRecordLatchIsRetired) \
X(FramebufferEmit, TheRecordsElevenSurfacesAreTheWholePointSetTheServerReads) \
X(FramebufferEmit, ADefaultFramebufferResizeReEmitsTheRecordWithItsNewExtent)
X(FramebufferEmit, ADefaultFramebufferResizeReEmitsTheRecordWithItsNewExtent) X(FramebufferEmit, TheDefaultFramebuffersRecordNamesNoSurfaceAShareGroupWouldHaveToHold)
#define MGL_DECLARE_PULL_SKIP(Suite, Name) \
TEST(Suite, Name) { GTEST_SKIP() << "compiled only under MOBILEGL_PIPE_PUSH"; }
@@ -706,6 +706,46 @@ TEST(FramebufferEmit, ADefaultFramebufferResizeReEmitsTheRecordWithItsNewExtent)
EXPECT_EQ(applied->Height, 96u);
}
// THE DEFAULT FRAMEBUFFER'S RECORD NAMES NO SURFACE. Its attachments are the frontend's
// placeholders - one process-wide set every context's framebuffer 0 shares, whose records live in
// the one share group that was bound when they were born - and the server's default framebuffer
// is the surface the context is current on. Red while the record named them: every other share
// group was sent texture handles it held no record for, and logged the miss on each draw.
TEST(FramebufferEmit, TheDefaultFramebuffersRecordNamesNoSurfaceAShareGroupWouldHaveToHold) {
FramebufferScope scope;
const auto color = MakeColorTexture(96, 64);
const auto depthStencil = MakeShared<TextureObject2D>(97);
depthStencil->SetInternalFormat(TextureInternalFormat::Depth32FStencil8);
depthStencil->AllocateStorage(TextureUploadTarget::Texture2D, 0,
MipmapInput{IntVec3{64, 64, 1}, static_cast<SizeT>(64 * 64 * 8)});
const auto fbo0 = MakeShared<FramebufferObject>(0); // what MG_Impl::BuildDefaultFramebuffer builds
ASSERT_TRUE(fbo0->IsDefaultFramebuffer());
for (const auto point : {FramebufferAttachmentType::Color0, FramebufferAttachmentType::FrontLeft,
FramebufferAttachmentType::FrontRight, FramebufferAttachmentType::BackLeft,
FramebufferAttachmentType::BackRight}) {
fbo0->AttachTexture(point, color, TextureUploadTarget::Texture2D);
}
fbo0->AttachTexture(FramebufferAttachmentType::Depth, depthStencil, TextureUploadTarget::Texture2D);
fbo0->AttachTexture(FramebufferAttachmentType::Stencil, depthStencil, TextureUploadTarget::Texture2D);
BindDrawAndRead(fbo0, fbo0);
Framebuffers().EmitFramebufferState(Ctx());
const MGPFramebufferState* const applied = MGPipeApplier().DrawFramebuffer();
ASSERT_NE(applied, nullptr) << "the default framebuffer's record did not reach the applier";
EXPECT_EQ(applied->IsDefault, 1) << "MGPFramebufferState::IsDefault";
for (Uint i = 0; i < kMGPipeMaxColorAttachments; ++i) {
EXPECT_EQ(applied->Color[i].Kind, kMGPipeSurfaceKindNone) << "MGPSurface::Kind at colour point " << i;
EXPECT_TRUE(MGPipeHandleIsNull(applied->Color[i].Res)) << "MGPSurface::Res at colour point " << i;
}
EXPECT_EQ(applied->Depth.Kind, kMGPipeSurfaceKindNone) << "MGPSurface::Kind on the depth point";
EXPECT_EQ(applied->Stencil.Kind, kMGPipeSurfaceKindNone) << "MGPSurface::Kind on the stencil point";
EXPECT_EQ(applied->ReadSurface.Kind, kMGPipeSurfaceKindNone) << "MGPFramebufferState::ReadSurface";
// What the record still carries: the extent, and slot 0 as the back buffer's draw buffer.
EXPECT_EQ(applied->Width, 64u) << "MGPFramebufferState::Width";
EXPECT_EQ(applied->Height, 64u) << "MGPFramebufferState::Height";
EXPECT_EQ(applied->DrawBuffers[0], 0) << "MGPFramebufferState::DrawBuffers[0]";
}
// ============================ D-D2 ============================
//
// RED BEFORE THIS PACKAGE LANDED. RenderbufferObject's three storage setters bump no version
+34
View File
@@ -908,6 +908,40 @@ namespace {
Cache().Release(second);
}
// AN EVICTION ENDS THE VALUE IN EVERY SHARE GROUP IT WAS PUBLISHED TO. The cache frees the
// handle, which is one identity for the whole session, whichever context is bound when the LRU
// runs. Red while the delete reached the bound group only: the other group kept a record at a
// slot the cache hands out again.
TEST(SamplerEmit, AnEvictionDropsTheValueFromEveryShareGroupItWasPublishedTo) {
EmitterScope scope;
ShareGroupPair groups(/*shared=*/false);
Uint64 payload = 0;
const SamplerParameters params = DistinctParameters();
groups.MakeCurrent(0);
const MGPipeHandle victim = Cache().Acquire(params, payload);
groups.MakeCurrent(1);
ASSERT_EQ(Cache().Acquire(params, payload), victim);
ASSERT_NE(BoundGroupSamplerRecord(victim), nullptr) << "the second group was not sent the create";
Cache().Release(victim);
Cache().Release(victim);
// The first group fills the cache with values nothing keeps naming: the victim is the
// least recently used entry, and the LRU takes it while the FIRST group is bound.
groups.MakeCurrent(0);
SamplerParameters filler = DistinctParameters();
for (SizeT i = 0; i < kMGPipeSamplerCsoCacheCapacity; ++i) {
filler.minLod = static_cast<float>(i) + 0.5f;
Cache().Release(Cache().Acquire(filler, payload));
}
ASSERT_FALSE(Cache().RecordIsPublished(victim)) << "the LRU did not take the victim";
EXPECT_EQ(BoundGroupSamplerRecord(victim), nullptr) << "the bound group still holds the evicted value";
groups.MakeCurrent(1);
EXPECT_EQ(BoundGroupSamplerRecord(victim), nullptr)
<< "the other share group still holds a sampler CSO the cache has freed";
EXPECT_EQ(MGPipeApplier().RefusedObjectCalls, 0u);
}
// ============================ D-F2: the sampler view ============================
TEST(SamplerEmit, AnUnchangedTextureReIssuesNothing) {
+101
View File
@@ -661,6 +661,30 @@ TEST_F(ProgramTest, CompileAndLink) {
GetUniformiv(program, locInt, &intVal);
EXPECT_EQ(intVal, 114514);
// glGetnUniform* (GL 4.5 / KHR_robustness): the same answers, bounded by bufSize. A
// destination too small for the uniform's components is GL_INVALID_OPERATION and untouched.
while (GetError() != GL_NO_ERROR) {
}
float boundedRed[4] = {-1.0f, -1.0f, -1.0f, -1.0f};
GetnUniformfv(program, locRed, static_cast<GLsizei>(3 * sizeof(float)), boundedRed);
EXPECT_EQ(GetError(), static_cast<GLenum>(GL_NO_ERROR));
EXPECT_EQ(boundedRed[0], 1.0f);
EXPECT_EQ(boundedRed[2], 5.0f);
EXPECT_EQ(boundedRed[3], -1.0f) << "glGetnUniformfv wrote past the uniform";
float tooSmall[3] = {-1.0f, -1.0f, -1.0f};
GetnUniformfv(program, locRed, static_cast<GLsizei>(2 * sizeof(float)), tooSmall);
EXPECT_EQ(GetError(), static_cast<GLenum>(GL_INVALID_OPERATION));
EXPECT_EQ(tooSmall[0], -1.0f) << "a refused glGetnUniformfv wrote anyway";
int boundedInt = 0;
GetnUniformiv(program, locInt, static_cast<GLsizei>(sizeof(int)), &boundedInt);
EXPECT_EQ(GetError(), static_cast<GLenum>(GL_NO_ERROR));
EXPECT_EQ(boundedInt, 114514);
GetnUniformiv(program, locInt, -1, &boundedInt);
EXPECT_EQ(GetError(), static_cast<GLenum>(GL_INVALID_OPERATION));
// Every other error is the unbounded query's: a location the program does not have.
GetnUniformfv(program, 4096, static_cast<GLsizei>(sizeof(boundedRed)), boundedRed);
EXPECT_EQ(GetError(), static_cast<GLenum>(GL_INVALID_OPERATION));
auto programObj = MG_State::pGLContext->GetProgramObject(program);
auto& shaderSpirvs = programObj->GetGeneratedSpirv();
for (int index = 0; index < shaderSpirvs.size(); ++index) {
@@ -1613,6 +1637,83 @@ void main() {
EXPECT_EQ(locationMask, 0x1u);
}
// An X server's 2D shaders name gl_FragColor only in the arm of a version guard that a 1.30
// compile does not take, and write their own output instead. The legacy lowering still declares
// mg_FragColor (it cannot see the guard), ahead of the shader's output: that declaration is
// inactive and must not take location 0, or every copy and fill writes to a draw buffer nobody
// enabled and the window keeps whatever it held before.
TEST_F(ProgramTest, InactiveLoweredFragColorDoesNotDisplaceTheActiveOutput) {
const char* vertexSource = R"(#version 130
in vec2 primitive;
out vec2 fill_pos;
uniform vec4 v_matrix;
void main() {
gl_Position = vec4(primitive * v_matrix.xz + v_matrix.yw, 0.0, 1.0);
fill_pos = primitive;
}
)";
const char* fragmentSource = R"(#version 130
#if __VERSION__ >= 130
out vec4 frag_color;
#else
#define frag_color gl_FragColor
#endif
in vec2 fill_pos;
uniform sampler2D sampler;
void main() {
frag_color = texture(sampler, fill_pos);
}
)";
const auto compile = [](GLenum stage, const char* source) {
const GLuint shader = CreateShader(stage);
ShaderSource(shader, 1, &source, nullptr);
CompileShader(shader);
GLint status = GL_FALSE;
GetShaderiv(shader, GL_COMPILE_STATUS, &status);
char log[1024] = "";
GetShaderInfoLog(shader, sizeof log, nullptr, log);
EXPECT_EQ(status, GL_TRUE) << log;
return shader;
};
const GLuint program = CreateProgram();
AttachShader(program, compile(GL_VERTEX_SHADER, vertexSource));
AttachShader(program, compile(GL_FRAGMENT_SHADER, fragmentSource));
BindAttribLocation(program, 0, "primitive");
LinkProgram(program);
GLint linkStatus = GL_FALSE;
GetProgramiv(program, GL_LINK_STATUS, &linkStatus);
ASSERT_EQ(linkStatus, GL_TRUE);
EXPECT_EQ(GetFragDataLocation(program, "frag_color"), 0);
auto programObject = MG_State::pGLContext->GetProgramObject(program);
ASSERT_NE(programObject, nullptr);
const Int fragmentIndex = programObject->GetShaderIndexByStage(ShaderStage::Fragment);
ASSERT_GE(fragmentIndex, 0);
const auto& spirvs = programObject->GetGeneratedSpirv();
ASSERT_LT(static_cast<SizeT>(fragmentIndex), spirvs.size());
const auto& fragmentSpirv = spirvs[fragmentIndex];
spv_reflect::ShaderModule reflection(fragmentSpirv.size() * sizeof(Uint), fragmentSpirv.data());
ASSERT_EQ(reflection.GetResult(), SPV_REFLECT_RESULT_SUCCESS);
uint32_t outputCount = 0;
ASSERT_EQ(reflection.EnumerateOutputVariables(&outputCount, nullptr), SPV_REFLECT_RESULT_SUCCESS);
Vector<SpvReflectInterfaceVariable*> outputs(outputCount);
ASSERT_EQ(reflection.EnumerateOutputVariables(&outputCount, outputs.data()), SPV_REFLECT_RESULT_SUCCESS);
Bool sawActive = false;
for (const auto* output : outputs) {
if (output == nullptr || output->name == nullptr) continue;
const String name = output->name;
if (name == "frag_color") {
sawActive = true;
EXPECT_EQ(output->location, 0u);
} else {
// The lowered declaration, if it survives at all, sits clear of the active output.
EXPECT_NE(output->location, 0u) << name;
}
}
EXPECT_TRUE(sawActive);
}
TEST_F(ProgramTest, CompileAndLinkWithExplicitFragmentOut) {
char infoLog[1024] = "";
+39
View File
@@ -89,7 +89,46 @@ target_link_libraries(
${LINK_LIBRARIES}
)
# The X-connection safety rule: MobileGL never dials an X display its own process serves (the
# Xwayland-on-glamor deadlock), with the /proc facts injected and once for real in a child.
add_executable(
X11DisplayGuardTest
X11DisplayGuardTest.cpp
)
target_include_directories(X11DisplayGuardTest PRIVATE
${MGL_ROOT}/include
${MGL_ROOT}/MobileGL
)
target_link_libraries(
X11DisplayGuardTest PRIVATE
GTest::gtest_main
${LINK_LIBRARIES}
)
# GLX presentation through DRI3 + Present against a fake X server and fake shared images, and the
# glFlush-as-shared-image-boundary policy (docs/Disaggregated/notes/anland/plan-x11-gpu.md).
add_executable(
X11PresentTest
X11PresentTest.cpp
SharedImageFlushPolicyTest.cpp
)
target_include_directories(X11PresentTest PRIVATE
${MGL_ROOT}/include
${MGL_ROOT}/MobileGL
)
target_link_libraries(
X11PresentTest PRIVATE
GTest::gtest_main
${LINK_LIBRARIES}
)
include(GoogleTest)
gtest_discover_tests(X11DisplayGuardTest DISCOVERY_TIMEOUT 30 PROPERTIES LABELS unit)
gtest_discover_tests(X11PresentTest DISCOVERY_TIMEOUT 30 PROPERTIES LABELS unit)
gtest_discover_tests(JobNodeTest DISCOVERY_TIMEOUT 30 PROPERTIES LABELS unit)
gtest_discover_tests(LogLevelTest DISCOVERY_TIMEOUT 30 PROPERTIES LABELS unit)
gtest_discover_tests(PipeStatsTest DISCOVERY_TIMEOUT 30 PROPERTIES LABELS unit)
@@ -0,0 +1,38 @@
// MobileGL - MobileGL/MG_Test/Util/SharedImageFlushPolicyTest.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
// When a glFlush publishes the session's shared-image accesses (implicit sync for a producer that
// renders into its dma-bufs, Xwayland's glamor): MG_Impl/EGLImpl/SharedImageFlushPolicy.h.
#include <MG_Impl/EGLImpl/SharedImageFlushPolicy.h>
#include <gtest/gtest.h>
using MobileGL::MG_Impl::EGLImpl::FlushPublishesSharedImageAccesses;
TEST(SharedImageFlushPolicy, AnXServerThatBoundImagesToTexturesFlushesAsABoundary) {
// Xwayland: offscreen session, glamor bound its window pixmaps' images to textures.
EXPECT_TRUE(FlushPublishesSharedImageAccesses(true, true, false, nullptr));
// An ordinary GL client never bound one: its flushes stay free.
EXPECT_FALSE(FlushPublishesSharedImageAccesses(true, false, false, nullptr));
// The compositor (owns the server window) samples client buffers and ends frames at its swaps.
EXPECT_FALSE(FlushPublishesSharedImageAccesses(true, true, true, nullptr));
// Without shared images (a monolith) there is nothing to publish, whatever is asked.
EXPECT_FALSE(FlushPublishesSharedImageAccesses(false, true, false, nullptr));
EXPECT_FALSE(FlushPublishesSharedImageAccesses(false, true, false, "1"));
}
TEST(SharedImageFlushPolicy, TheOverrideForcesEitherWay) {
EXPECT_FALSE(FlushPublishesSharedImageAccesses(true, true, false, "0"));
EXPECT_FALSE(FlushPublishesSharedImageAccesses(true, true, false, "off"));
EXPECT_TRUE(FlushPublishesSharedImageAccesses(true, false, true, "1"));
EXPECT_TRUE(FlushPublishesSharedImageAccesses(true, true, true, "on"));
// Anything else is the automatic answer.
EXPECT_TRUE(FlushPublishesSharedImageAccesses(true, true, false, ""));
EXPECT_FALSE(FlushPublishesSharedImageAccesses(true, true, true, "auto"));
}
@@ -0,0 +1,165 @@
// MobileGL - MobileGL/MG_Test/Util/X11DisplayGuardTest.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
// The X-connection safety rule (MG_Util/X11/DisplayGuard.h): MobileGL never opens a connection to a
// display its own process serves. The last case is the deadlock itself: a process that listens on
// an X display's socket, as Xwayland does, creates an EGL display with DISPLAY naming that socket.
// Before the guard EGLState dialed it to pick a visual and waited forever for a setup reply only
// the blocked process could send.
#include <MG_State/EGLState/Core.h>
#include <MG_Util/X11/DisplayGuard.h>
#include <gtest/gtest.h>
#include <cstdlib>
#include <cstring>
#include <string>
#include <poll.h>
#include <signal.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/un.h>
#include <sys/wait.h>
#include <unistd.h>
using namespace MobileGL;
namespace X = MobileGL::MG_Util::X11;
namespace {
// /proc/net/unix as Xwayland's process sees it under KWin: the two listening sockets KWin bound
// and handed over with -listenfd, plus connected ones.
const char* kProcNetUnix =
"Num RefCount Protocol Flags Type St Inode Path\n"
"0000000000000000: 00000002 00000000 00010000 0001 01 41001 @/tmp/.X11-unix/X0\n"
"0000000000000000: 00000002 00000000 00010000 0001 01 41002 /tmp/.X11-unix/X0\n"
"0000000000000000: 00000003 00000000 00000000 0001 03 41003 /tmp/.X11-unix/X0\n"
"0000000000000000: 00000002 00000000 00010000 0001 01 41004 /run/user/1000/wayland-0\n"
"0000000000000000: 00000003 00000000 00000000 0001 03 41005\n"
"0000000000000000: 00000002 00000000 00010000 0001 01 41006 @/tmp/.X11-unix/X1\n";
} // namespace
TEST(X11DisplayGuard, DisplayNamesYieldTheirNumber) {
EXPECT_EQ(X::ParseDisplayNumber(":0"), 0);
EXPECT_EQ(X::ParseDisplayNumber(":1.0"), 1);
EXPECT_EQ(X::ParseDisplayNumber("unix:2"), 2);
EXPECT_EQ(X::ParseDisplayNumber("localhost:10.2"), 10);
EXPECT_EQ(X::ParseDisplayNumber("[::1]:3"), 3);
EXPECT_EQ(X::ParseDisplayNumber("/tmp/.X11-unix/X4"), 4);
EXPECT_EQ(X::ParseDisplayNumber("@/tmp/.X11-unix/X5"), 5);
EXPECT_EQ(X::ParseDisplayNumber(""), -1);
EXPECT_EQ(X::ParseDisplayNumber(nullptr), -1);
EXPECT_EQ(X::ParseDisplayNumber("wayland-0"), -1);
EXPECT_EQ(X::ParseDisplayNumber(":x"), -1);
}
TEST(X11DisplayGuard, OnlyListeningSocketsOfThatDisplayCount) {
const Vector<Uint64> zero = X::ListeningDisplaySocketInodes(kProcNetUnix, 0);
ASSERT_EQ(zero.size(), 2u);
EXPECT_EQ(zero[0], 41001u); // abstract
EXPECT_EQ(zero[1], 41002u); // path; 41003 is a connection to it, not a listener
EXPECT_EQ(X::ListeningDisplaySocketInodes(kProcNetUnix, 1), Vector<Uint64>{41006u});
EXPECT_TRUE(X::ListeningDisplaySocketInodes(kProcNetUnix, 7).empty());
}
TEST(X11DisplayGuard, AnXServerNeverDialsItsOwnDisplay) {
// Xwayland holding display 0's listening socket.
X::ProcessFacts xwayland{"Xwayland", kProcNetUnix, {7, 41002, 9}};
EXPECT_FALSE(X::MayDial(":0", xwayland, nullptr));
// By executable alone (a socket held through a path /proc does not show): still refused.
X::ProcessFacts xwaylandNoSocket{"Xwayland", kProcNetUnix, {}};
EXPECT_FALSE(X::MayDial(":0", xwaylandNoSocket, nullptr));
// A process that is not named like an X server but holds the listener serves it too.
X::ProcessFacts renamed{"my-x-server", kProcNetUnix, {41001}};
EXPECT_FALSE(X::MayDial(":0", renamed, nullptr));
EXPECT_TRUE(X::MayDial(":1", renamed, nullptr)) << "display 1 is someone else's";
}
TEST(X11DisplayGuard, AnOrdinaryClientDialsUnlessForbidden) {
X::ProcessFacts client{"glxgears", kProcNetUnix, {41003, 41005}}; // connected, not listening
EXPECT_TRUE(X::MayDial(":0", client, nullptr));
EXPECT_TRUE(X::MayDial(":0", client, "1"));
EXPECT_FALSE(X::MayDial(":0", client, "0"));
EXPECT_FALSE(X::MayDial(":0", client, "off"));
EXPECT_FALSE(X::MayDial(nullptr, client, nullptr));
EXPECT_FALSE(X::MayDial("", client, nullptr));
EXPECT_TRUE(X::MayDial("weird-name", client, nullptr)) << "no number: only an X server refuses";
EXPECT_TRUE(X::IsXServerProgram("Xorg"));
EXPECT_TRUE(X::IsXServerProgram("Xvfb"));
EXPECT_FALSE(X::IsXServerProgram("Xclock"));
}
namespace {
// A listening abstract socket named like display `number`'s, as an X server (or KWin, for
// Xwayland's -listenfd) binds it.
int ListenAsDisplay(int number) {
const int fd = ::socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0);
if (fd < 0) return -1;
sockaddr_un addr{};
addr.sun_family = AF_UNIX;
const std::string name = "/tmp/.X11-unix/X" + std::to_string(number);
std::memcpy(addr.sun_path + 1, name.data(), name.size()); // abstract: leading NUL
const socklen_t length = static_cast<socklen_t>(offsetof(sockaddr_un, sun_path) + 1 + name.size());
if (::bind(fd, reinterpret_cast<sockaddr*>(&addr), length) != 0 || ::listen(fd, 4) != 0) {
::close(fd);
return -1;
}
return fd;
}
int UnusedDisplayNumber() { return 3000 + static_cast<int>(::getpid() % 2000); }
} // namespace
TEST(X11DisplayGuard, ThisProcessServesADisplayWhileItListensOnItsSocket) {
const int number = UnusedDisplayNumber();
const std::string name = ":" + std::to_string(number);
EXPECT_TRUE(X::MayDialX11Display(name.c_str()));
const int listener = ListenAsDisplay(number);
ASSERT_GE(listener, 0) << std::strerror(errno);
EXPECT_FALSE(X::MayDialX11Display(name.c_str()));
::close(listener);
EXPECT_TRUE(X::MayDialX11Display(name.c_str()));
}
// THE DEADLOCK. In a child (a hang must not take the suite with it): listen like an X server,
// point DISPLAY at ourselves, and create the default EGL display - which used to XOpenDisplay
// DISPLAY for the configs' native visual and block in the connection setup forever.
TEST(X11DisplayGuard, AnEglDisplayInAnXServerDoesNotDialItself) {
const int number = UnusedDisplayNumber() + 1;
int fds[2];
ASSERT_EQ(::pipe(fds), 0);
const pid_t pid = ::fork();
ASSERT_GE(pid, 0);
if (pid == 0) {
::close(fds[0]);
const int listener = ListenAsDisplay(number);
if (listener < 0) ::_exit(3);
const std::string name = ":" + std::to_string(number);
::setenv("DISPLAY", name.c_str(), 1);
::unsetenv("MOBILEGL_X11_DIAL");
{
MG_State::EGLState::EGLContext state;
const EGLDisplay display = state.GetDisplay(EGL_DEFAULT_DISPLAY);
const char ok = display != EGL_NO_DISPLAY ? 'y' : 'n';
(void)!::write(fds[1], &ok, 1);
}
::_exit(0);
}
::close(fds[1]);
pollfd p{fds[0], POLLIN, 0};
const int ready = ::poll(&p, 1, 15000);
char got = 0;
if (ready > 0) (void)!::read(fds[0], &got, 1);
if (ready <= 0) ::kill(pid, SIGKILL);
int status = 0;
::waitpid(pid, &status, 0);
::close(fds[0]);
ASSERT_GT(ready, 0) << "eglGetDisplay blocked: MobileGL dialed the X display its own process serves";
EXPECT_EQ(got, 'y');
}
+387
View File
@@ -0,0 +1,387 @@
// MobileGL - MobileGL/MG_Test/Util/X11PresentTest.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
// GLX presentation through DRI3 + Present (MG_Impl/GLXImpl/X11Present.h), driven with a fake X
// server and fake shared images: which path a window takes, how the images rotate through the X
// server's hands (PresentPixmap -> IdleNotify), how swaps are paced on CompleteNotify, what a resize
// does, and which failures send the window back to the readback path.
#include <MG_Impl/GLXImpl/X11Present.h>
#include <gtest/gtest.h>
#include <deque>
#include <functional>
#include <map>
#include <unistd.h>
using namespace MobileGL;
namespace XP = MobileGL::MG_Impl::GLXImpl::X11Present;
using MobileGL::MG_Util::Damage::Rect;
using MobileGL::MG_Util::Damage::Region;
namespace {
struct Clock {
Int64 now = 1000;
};
struct FakeImages final : XP::ImageSource {
Uint64 nextId = 1;
std::map<Uint64, std::pair<Uint32, Uint32>> live; // id -> size
Vector<Uint64> released;
Vector<std::pair<Uint64, Region>> copies;
Bool failAllocate = false;
Bool failCopy = false;
Bool Allocate(Uint32 width, Uint32 height, Uint32 fourcc, XP::Image* out) override {
if (failAllocate) return false;
out->Id = nextId++;
out->Fd = ::dup(0); // any descriptor: the chain closes it once the pixmap holds the memory
out->Width = width;
out->Height = height;
out->Stride = width * 4;
out->Fourcc = fourcc;
live[out->Id] = {width, height};
return true;
}
void Release(Uint64 id) override {
live.erase(id);
released.push_back(id);
}
Bool CopyFrame(Uint64 id, const Region& region) override {
copies.emplace_back(id, region);
return !failCopy;
}
};
struct Presented {
Uint32 pixmap = 0;
Uint32 serial = 0;
Uint32 options = 0;
Uint64 targetMsc = 0;
Region update;
};
struct FakeX final : XP::Connection {
Clock& clock;
std::deque<XP::Event> events;
Uint32 nextPixmap = 0x400000;
std::map<Uint32, Uint64> pixmaps; // pixmap -> image id
Vector<Uint32> freed;
Vector<Presented> presents;
Bool refuseImport = false;
Bool presentFailed = false;
Uint32 lastImportDepth = 0;
// Called whenever the chain waits with nothing queued: the X server's turn to answer.
std::function<void(FakeX&)> serverTurn;
explicit FakeX(Clock& c) : clock(c) {}
Uint32 ImportPixmap(const XP::Image& image, Uint32 depth) override {
EXPECT_GE(image.Fd, 0);
lastImportDepth = depth;
if (refuseImport) return 0;
pixmaps[++nextPixmap] = image.Id;
return nextPixmap;
}
void FreePixmap(Uint32 pixmap) override {
freed.push_back(pixmap);
pixmaps.erase(pixmap);
}
Bool PresentPixmap(Uint32 pixmap, Uint32 serial, Uint32 options, Uint64 targetMsc, const Region& update) override {
presents.push_back({pixmap, serial, options, targetMsc, update});
return true;
}
Bool PresentFailed() override { return presentFailed; }
Bool PollEvent(XP::Event* out) override {
if (events.empty()) return false;
*out = events.front();
events.pop_front();
return true;
}
Bool WaitEvent(XP::Event* out, Int64 timeoutMs) override {
if (events.empty() && serverTurn) serverTurn(*this);
if (events.empty()) {
clock.now += timeoutMs;
return false;
}
clock.now += 1;
return PollEvent(out);
}
void Flush() override {}
void Idle(Uint32 pixmap) {
XP::Event e;
e.Type = XP::Event::Kind::Idle;
e.Pixmap = pixmap;
events.push_back(e);
}
void Complete(Uint32 serial, Uint64 msc) {
XP::Event e;
e.Type = XP::Event::Kind::Complete;
e.Serial = serial;
e.Msc = msc;
events.push_back(e);
}
void Configure(Int32 w, Int32 h, Bool destroyed = false) {
XP::Event e;
e.Type = XP::Event::Kind::Configure;
e.Width = w;
e.Height = h;
e.WindowDestroyed = destroyed;
events.push_back(e);
}
};
struct Rig {
Clock clock;
FakeImages images;
FakeX x{clock};
std::unique_ptr<XP::Chain> chain;
explicit Rig(Uint32 depth = 24, Int32 w = 64, Int32 h = 48) {
chain = std::make_unique<XP::Chain>(x, images, depth, w, h, [this] { return clock.now; });
}
};
} // namespace
TEST(X11PresentPath, Dri3WhenTheConnectionAndTheBackendHaveEverything) {
XP::ConnectionCaps all;
all.SharedImages = true;
all.LocalConnection = true;
all.Dri3Major = 1;
all.Dri3Minor = 2;
all.PresentMajor = 1;
all.PresentMinor = 2;
all.ShmMajor = 1;
all.ShmMinor = 2;
EXPECT_EQ(XP::SelectPath(all, 24, nullptr), XP::Path::Dri3Present);
EXPECT_EQ(XP::SelectPath(all, 32, nullptr), XP::Path::Dri3Present);
EXPECT_EQ(XP::SelectPath(all, 16, nullptr), XP::Path::ShmPutImage) << "no shared-image format for depth 16";
EXPECT_EQ(XP::SelectPath(all, 24, "readback"), XP::Path::ShmPutImage);
EXPECT_EQ(XP::SelectPath(all, 24, "putimage"), XP::Path::PutImage);
XP::ConnectionCaps shmOnly = all; // Xwayland -shm: no glamor, so no DRI3
shmOnly.Dri3Major = shmOnly.Dri3Minor = 0;
EXPECT_EQ(XP::SelectPath(shmOnly, 24, nullptr), XP::Path::ShmPutImage);
XP::ConnectionCaps monolith = all; // a backend without shared images
monolith.SharedImages = false;
EXPECT_EQ(XP::SelectPath(monolith, 24, nullptr), XP::Path::ShmPutImage);
XP::ConnectionCaps oldShm = shmOnly; // MIT-SHM 1.1: SysV only
oldShm.ShmMinor = 1;
EXPECT_EQ(XP::SelectPath(oldShm, 24, nullptr), XP::Path::PutImage);
XP::ConnectionCaps remote = all; // TCP: no descriptor travels
remote.LocalConnection = false;
EXPECT_EQ(XP::SelectPath(remote, 24, nullptr), XP::Path::PutImage);
XP::ConnectionCaps noPresent = all;
noPresent.PresentMajor = 0;
EXPECT_EQ(XP::SelectPath(noPresent, 24, nullptr), XP::Path::ShmPutImage);
EXPECT_EQ(XP::FourccForDepth(24), XP::kFourccXrgb8888);
EXPECT_EQ(XP::FourccForDepth(32), XP::kFourccArgb8888);
EXPECT_EQ(XP::FourccForDepth(30), 0u);
}
TEST(X11PresentChain, AFrameIsCopiedIntoAnImportedImageAndPresented) {
Rig rig(32, 64, 48);
ASSERT_TRUE(rig.chain->Present(Region::Full(), 0));
ASSERT_EQ(rig.images.live.size(), 1u);
const auto& [id, size] = *rig.images.live.begin();
EXPECT_EQ(size, std::make_pair(64u, 48u));
EXPECT_EQ(rig.x.lastImportDepth, 32u);
ASSERT_EQ(rig.images.copies.size(), 1u);
EXPECT_EQ(rig.images.copies[0].first, id);
EXPECT_TRUE(rig.images.copies[0].second.IsFull());
ASSERT_EQ(rig.x.presents.size(), 1u);
EXPECT_EQ(rig.x.pixmaps.at(rig.x.presents[0].pixmap), id);
EXPECT_EQ(rig.x.presents[0].options, XP::kPresentOptionAsync);
EXPECT_EQ(rig.x.presents[0].serial, 1u);
EXPECT_EQ(rig.chain->BusyBuffers(), 1u);
}
TEST(X11PresentChain, AnImageComesBackWithIdleNotifyAndIsReused) {
Rig rig;
ASSERT_TRUE(rig.chain->Present(Region::Full(), 0));
const Uint32 first = rig.x.presents[0].pixmap;
rig.x.Idle(first);
ASSERT_TRUE(rig.chain->Present(Region::Full(), 0));
EXPECT_EQ(rig.x.presents[1].pixmap, first) << "the idle image is taken before a new one is made";
EXPECT_EQ(rig.chain->AllocatedBuffers(), 1u);
// Held by the server: the next frame takes a second image, and a third.
ASSERT_TRUE(rig.chain->Present(Region::Full(), 0));
ASSERT_TRUE(rig.chain->Present(Region::Full(), 0));
EXPECT_EQ(rig.chain->AllocatedBuffers(), 3u);
EXPECT_EQ(rig.chain->BusyBuffers(), 3u);
// Idle for an unknown pixmap is ignored.
rig.x.Idle(0x1234);
rig.x.Idle(rig.x.presents[2].pixmap);
ASSERT_TRUE(rig.chain->Present(Region::Full(), 0));
EXPECT_EQ(rig.x.presents[4].pixmap, rig.x.presents[2].pixmap);
EXPECT_EQ(rig.chain->AllocatedBuffers(), 3u);
}
TEST(X11PresentChain, AllImagesHeldWaitsThenGrowsToFourThenDropsTheFrame) {
Rig rig;
for (int i = 0; i < 3; ++i) ASSERT_TRUE(rig.chain->Present(Region::Full(), 0));
const Int64 before = rig.clock.now;
ASSERT_TRUE(rig.chain->Present(Region::Full(), 0)) << "a fourth image after the idle wait";
EXPECT_GE(rig.clock.now - before, XP::Chain::kIdleWaitMs);
EXPECT_EQ(rig.chain->AllocatedBuffers(), XP::Chain::kMaxBuffers);
EXPECT_FALSE(rig.chain->Present(Region::Full(), 0)) << "past the limit the frame is dropped";
EXPECT_FALSE(rig.chain->Broken()) << "a slow server does not end the chain";
EXPECT_EQ(rig.x.presents.size(), 4u);
// The server answers while the chain waits: no fifth image, no dropped frame.
rig.x.serverTurn = [](FakeX& x) { x.Idle(x.presents.front().pixmap); };
ASSERT_TRUE(rig.chain->Present(Region::Full(), 0));
EXPECT_EQ(rig.x.presents.back().pixmap, rig.x.presents.front().pixmap);
EXPECT_EQ(rig.chain->AllocatedBuffers(), XP::Chain::kMaxBuffers);
}
TEST(X11PresentChain, IntervalOneWaitsForThePreviousCompletionAndTargetsTheNextMsc) {
Rig rig;
ASSERT_TRUE(rig.chain->Present(Region::Full(), 1));
EXPECT_EQ(rig.x.presents[0].options, 0u);
EXPECT_EQ(rig.x.presents[0].targetMsc, 0u) << "no MSC known yet";
rig.x.serverTurn = [](FakeX& x) { x.Complete(1, 500); };
ASSERT_TRUE(rig.chain->Present(Region::Full(), 1));
EXPECT_EQ(rig.x.presents[1].targetMsc, 501u);
EXPECT_TRUE(rig.x.events.empty());
// Interval 2 targets two frames on.
rig.x.serverTurn = [](FakeX& x) { x.Complete(2, 501); };
ASSERT_TRUE(rig.chain->Present(Region::Full(), 2));
EXPECT_EQ(rig.x.presents[2].targetMsc, 503u);
// A server that never completes stalls a paced swap only so long.
rig.x.serverTurn = nullptr;
const Int64 before = rig.clock.now;
rig.x.Idle(rig.x.presents[0].pixmap);
ASSERT_TRUE(rig.chain->Present(Region::Full(), 1));
EXPECT_GE(rig.clock.now - before, XP::Chain::kCompleteGiveUpMs);
EXPECT_LT(rig.clock.now - before, XP::Chain::kCompleteGiveUpMs + XP::Chain::kIdleWaitMs);
}
TEST(X11PresentChain, IntervalZeroIsUnpacedUntilACompletionIsOverdue) {
Rig rig;
ASSERT_TRUE(rig.chain->Present(Region::Full(), 0));
rig.x.Idle(rig.x.presents[0].pixmap);
Int64 before = rig.clock.now;
ASSERT_TRUE(rig.chain->Present(Region::Full(), 0));
EXPECT_EQ(rig.clock.now, before) << "the completion is outstanding but not overdue";
// Nothing of the window is shown: no completion for 250 ms.
rig.clock.now += 250;
rig.x.Idle(rig.x.presents[1].pixmap);
before = rig.clock.now;
ASSERT_TRUE(rig.chain->Present(Region::Full(), 0));
EXPECT_GE(rig.clock.now - before, 1000) << "about one frame a second while nothing is shown";
EXPECT_LE(rig.clock.now - before, 1001);
// Completions come back: unpaced again.
rig.x.Complete(1, 10);
rig.x.Idle(rig.x.presents[2].pixmap);
before = rig.clock.now;
ASSERT_TRUE(rig.chain->Present(Region::Full(), 0));
EXPECT_EQ(rig.clock.now, before);
}
TEST(X11PresentChain, AResizeRetiresOldImagesAsTheyComeBack) {
Rig rig(24, 64, 48);
const auto newSize = std::make_pair(128u, 96u);
ASSERT_TRUE(rig.chain->Present(Region::Full(), 0));
ASSERT_TRUE(rig.chain->Present(Region::Full(), 0));
const Uint32 a = rig.x.presents[0].pixmap;
const Uint32 b = rig.x.presents[1].pixmap;
// Both with the server; a comes back, b does not.
rig.x.Idle(a);
rig.chain->Resize(128, 96);
EXPECT_EQ(rig.chain->Width(), 128);
EXPECT_TRUE(rig.x.freed.empty()) << "both were still with the server at the resize";
ASSERT_TRUE(rig.chain->Present(Region::Full(), 0));
const Uint32 c = rig.x.presents.back().pixmap;
EXPECT_NE(c, a);
EXPECT_NE(c, b);
EXPECT_EQ(rig.images.live.at(rig.x.pixmaps.at(c)), newSize);
EXPECT_EQ(rig.x.freed, Vector<Uint32>{a}) << "a came back at the old size and was replaced";
EXPECT_EQ(rig.x.pixmaps.count(b), 1u) << "b is still with the server";
// b comes back: the next frame that would take it gets a new-size image instead.
rig.x.Idle(b);
rig.x.Idle(c);
ASSERT_TRUE(rig.chain->Present(Region::Full(), 0));
EXPECT_EQ(rig.x.pixmaps.count(b), 0u);
for (const auto& [id, size] : rig.images.live) EXPECT_EQ(size, newSize);
}
TEST(X11PresentChain, ConfigureNotifyReportsTheNewSizeOnce) {
Rig rig;
rig.x.Configure(300, 200);
ASSERT_TRUE(rig.chain->Present(Region::Full(), 0));
Int32 w = 0, h = 0;
ASSERT_TRUE(rig.chain->TakeConfiguredSize(&w, &h));
EXPECT_EQ(w, 300);
EXPECT_EQ(h, 200);
EXPECT_FALSE(rig.chain->TakeConfiguredSize(&w, &h));
}
TEST(X11PresentChain, PartialDamageIsFlippedIntoTheUpdateRegion) {
Rig rig(24, 100, 100);
const Rect gl{10, 0, 20, 5}; // bottom-left origin: the bottom rows
ASSERT_TRUE(rig.chain->Present(Region::FromRects(&gl, 1), 0));
ASSERT_FALSE(rig.x.presents[0].update.IsFull());
ASSERT_EQ(rig.x.presents[0].update.Rects().size(), 1u);
EXPECT_EQ(rig.x.presents[0].update.Rects()[0], (Rect{10, 95, 20, 5}));
EXPECT_TRUE(rig.images.copies[0].second.IsFull()) << "a new image holds no frame yet: copied whole";
}
TEST(X11PresentChain, FailuresSendTheWindowBackToReadback) {
{
Rig rig;
rig.x.refuseImport = true;
EXPECT_FALSE(rig.chain->Present(Region::Full(), 0));
EXPECT_TRUE(rig.chain->Broken());
EXPECT_TRUE(rig.images.live.empty()) << "the refused image is released";
EXPECT_FALSE(rig.chain->Present(Region::Full(), 0));
}
{
Rig rig;
rig.images.failAllocate = true;
EXPECT_FALSE(rig.chain->Present(Region::Full(), 0));
EXPECT_TRUE(rig.chain->Broken());
}
{
Rig rig;
rig.images.failCopy = true;
EXPECT_FALSE(rig.chain->Present(Region::Full(), 0));
EXPECT_TRUE(rig.chain->Broken());
EXPECT_TRUE(rig.x.presents.empty()) << "nothing is presented that was not copied";
}
{
Rig rig;
ASSERT_TRUE(rig.chain->Present(Region::Full(), 0));
rig.x.presentFailed = true;
EXPECT_FALSE(rig.chain->Present(Region::Full(), 0));
EXPECT_TRUE(rig.chain->Broken());
}
{
Rig rig;
ASSERT_TRUE(rig.chain->Present(Region::Full(), 0));
rig.x.Configure(64, 48, /*destroyed=*/true);
EXPECT_FALSE(rig.chain->Present(Region::Full(), 0));
EXPECT_TRUE(rig.chain->Broken());
}
{
Rig rig(16);
EXPECT_TRUE(rig.chain->Broken()) << "depth 16 has no shared-image format";
}
}
TEST(X11PresentChain, TheChainFreesEveryPixmapAndReleasesEveryImage) {
Rig rig;
for (int i = 0; i < 3; ++i) ASSERT_TRUE(rig.chain->Present(Region::Full(), 0));
EXPECT_EQ(rig.images.live.size(), 3u);
rig.chain.reset();
EXPECT_TRUE(rig.images.live.empty());
EXPECT_TRUE(rig.x.pixmaps.empty());
EXPECT_EQ(rig.x.freed.size(), 3u);
}
+12 -3
View File
@@ -70,6 +70,9 @@ if (NOT WIN32)
# `eglinfo -B`'s per-API sequence (surfaceless make-current, the ES probe's NULL config) through
# a real MobileGL client against a real `--serve` supervisor, as ServerOwnedSurfaceTest does.
list(APPEND MOBILEGL_WIRE_TESTS EglInfoSequenceTest)
# Xwayland's glamor against MobileGL's EGL (GBM platform, config-less core context, surfaceless,
# dma-buf import) and the shared_image Flush verb its glFlush sends; a real supervisor again.
list(APPEND MOBILEGL_WIRE_TESTS GlamorEglSequenceTest)
# P14 S2 (docs/Disaggregated/design/11-state-ownership.md): several sessions in ONE process.
# The in-process unix supervisor serves each session on its own control thread with its own
# ServerSession/ServerLoop/PipeInputs block/latch domain/segment resolver; two SHM clients are
@@ -80,6 +83,11 @@ if (NOT WIN32)
# the loss reported, creates new contexts on a FRESH session and renders. Forks the in-process
# display server and its client, like MultiSessionTest, so it needs no server image either.
list(APPEND MOBILEGL_WIRE_TESTS ClientRecoveryTest)
# A compositor outlives its lost session: a client on the server's own window (ServerOwned) that
# samples another client's shared image loses its session, re-creates its surface on a fresh one -
# waiting for the lost session's window lease - and imports the image again; the image's owner
# is untouched. Forks the in-process display server (with a stand-in window) and its clients.
list(APPEND MOBILEGL_WIRE_TESTS CompositorRecoveryTest)
# Several contexts on several threads of one client, in one share group or one each, drawing at
# once against the in-process display server (Qt Quick's shape, and its shape after a loss).
list(APPEND MOBILEGL_WIRE_TESTS ConcurrentContextsTest)
@@ -109,9 +117,10 @@ foreach (test IN LISTS MOBILEGL_WIRE_TESTS)
${MGL_ROOT}/3rdparty/flatbuffers/include
)
if (test STREQUAL "PeerLatchTest" OR test STREQUAL "InProcessServerTest" OR test STREQUAL "ServerOwnedSurfaceTest" OR
test STREQUAL "EglInfoSequenceTest" OR
test STREQUAL "EglInfoSequenceTest" OR test STREQUAL "GlamorEglSequenceTest" OR
test STREQUAL "AdoptTierStreamTest" OR test STREQUAL "MultiSessionTest" OR test STREQUAL "ServerProbeTest" OR
test STREQUAL "ClientRecoveryTest" OR test STREQUAL "ConcurrentContextsTest")
test STREQUAL "ClientRecoveryTest" OR test STREQUAL "ConcurrentContextsTest" OR
test STREQUAL "CompositorRecoveryTest")
# It builds records and a program archive by hand, so it reaches MG_Pipe and MG_State
# the way the codec suites do. (P12's two server suites share PeerLatchTest's healthy
# session, P12ServerRig.h, and so its include paths.)
@@ -141,7 +150,7 @@ foreach (test IN LISTS MOBILEGL_WIRE_TESTS)
if (test STREQUAL "ServerSpawnTest" OR test STREQUAL "PeerLatchTest" OR test STREQUAL "InProcessServerTest" OR
test STREQUAL "ServerOwnedSurfaceTest" OR test STREQUAL "EglInfoSequenceTest" OR test STREQUAL "AdoptTierStreamTest" OR
test STREQUAL "ServerProbeTest")
test STREQUAL "ServerProbeTest" OR test STREQUAL "GlamorEglSequenceTest")
# It execs the real image, so it must be built first and must be told
# where it is. MOBILEGL_TEST_SERVER_PATH is read by the test's
# ServerImage() helper; without it the test would depend on the working
+585 -12
View File
@@ -14,8 +14,11 @@
//
// What an application that handles context loss (Chrome through ANGLE) needs, each case asserting
// it from the application's side:
// * the loss is REPORTED: glGetGraphicsResetStatus answers a reset, glGetError GL_CONTEXT_LOST
// (once), eglSwapBuffers and eglMakeCurrent on the old context fail with EGL_CONTEXT_LOST;
// * the loss is REPORTED to a context that asked to be told (EGL_EXT_create_context_robustness,
// EGL_LOSE_CONTEXT_ON_RESET - advertised, and what ANGLE asks for): glGetGraphicsResetStatus
// answers a reset and keeps answering it, glGetError GL_CONTEXT_LOST (once), eglSwapBuffers
// and eglMakeCurrent on the old context fail with EGL_CONTEXT_LOST; a context that did not ask
// is told through GL only where semantics are relaxed, and through EGL everywhere;
// * the old context is SAFE TO USE AND TO DESTROY: a draw and a texture upload on it after the
// loss do nothing, and destroying it puts nothing on the new session's wire;
// * a context created after the loss gets a FRESH session (the server starts session #2, nothing
@@ -41,6 +44,12 @@
#include <mutex>
extern "C" {
void glTexStorage2D(GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height);
const GLubyte* glGetString(GLenum name);
const GLubyte* glGetStringi(GLenum name, GLuint index);
void glGetIntegerv(GLenum pname, GLint* data);
void glGetnUniformfv(GLuint program, GLint location, GLsizei bufSize, GLfloat* params);
void glUniform4f(GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3);
void glClearColor(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha);
void glClear(GLbitfield mask);
void glReadPixels(GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, void* pixels);
@@ -130,9 +139,25 @@ namespace {
Uint32 resetStatusEnd = 0xFFFFFFFFu;
Uint32 serverPidBefore = 0;
Uint32 serverPidAfter = 0;
// Robustness, as the application sees it: the extensions it checks before asking, the
// strategy its contexts report, the status again (it stays) and through the KHR name.
Int32 eglRobustnessAdvertised = -1;
Int32 glRobustnessAdvertised = -1;
Int32 glRobustnessIndexed = -1;
Int32 strategyBefore = 0;
Int32 robustAccess = -1;
Uint32 resetStatusRepeat = 0;
Uint32 resetStatusKhr = 0;
Int32 strategyNew = 0;
char note[256] = {};
};
Bool HasToken(const char* list, const char* token) {
if (list == nullptr) return false;
const std::string all = std::string(" ") + list + " ";
return all.find(std::string(" ") + token + " ") != std::string::npos;
}
void Note(RecoveryReport& r, const char* text) {
if (r.note[0] == '\0') std::snprintf(r.note, sizeof(r.note), "%s", text);
}
@@ -233,10 +258,32 @@ namespace {
return session != nullptr ? session->LastPublishedSeq() : 0;
}
// The contexts an application that handles loss creates: a 3.3 context that asks to be told of
// a reset (EGL_EXT_create_context_robustness - what Chrome, KWin and Qt pass when the display
// has the extension). Contexts that share must agree on it.
const EGLint kRobustAttribs[] = {EGL_CONTEXT_MAJOR_VERSION,
3,
EGL_CONTEXT_MINOR_VERSION,
3,
EGL_CONTEXT_OPENGL_RESET_NOTIFICATION_STRATEGY_EXT,
EGL_LOSE_CONTEXT_ON_RESET_EXT,
EGL_NONE};
// ANGLE's GL-on-EGL backend's own native context: the ES API, the highest ES version it tries
// first, and EGL 1.5's name of the attribute.
const EGLint kAngleNativeAttribs[] = {EGL_CONTEXT_MAJOR_VERSION,
3,
EGL_CONTEXT_MINOR_VERSION,
2,
EGL_CONTEXT_OPENGL_RESET_NOTIFICATION_STRATEGY,
EGL_LOSE_CONTEXT_ON_RESET,
EGL_NONE};
struct Egl {
EGLDisplay dpy = EGL_NO_DISPLAY;
EGLConfig config = nullptr;
EGLSurface surface = EGL_NO_SURFACE;
EGLenum api = EGL_OPENGL_API;
const EGLint* contextAttribs = kRobustAttribs;
Bool Bring(RecoveryReport& r) {
dpy = EGL::GetDisplay(EGL_DEFAULT_DISPLAY);
@@ -244,7 +291,7 @@ namespace {
EGLint minor = 0;
if (dpy == EGL_NO_DISPLAY || EGL::Initialize(dpy, &major, &minor) != EGL_TRUE)
return Note(r, "eglInitialize failed (no spawn session?)"), false;
(void)EGL::BindAPI(EGL_OPENGL_API);
(void)EGL::BindAPI(api);
const EGLint configAttribs[] = {EGL_SURFACE_TYPE, EGL_PBUFFER_BIT, EGL_NONE};
EGLint count = 0;
if (EGL::ChooseConfig(dpy, configAttribs, &config, 1, &count) != EGL_TRUE || count < 1)
@@ -255,21 +302,42 @@ namespace {
return true;
}
EGLContext Context() const {
const EGLint attribs[] = {EGL_CONTEXT_MAJOR_VERSION, 3, EGL_CONTEXT_MINOR_VERSION, 3, EGL_NONE};
return EGL::CreateContext(dpy, config, EGL_NO_CONTEXT, attribs);
}
EGLContext Context() const { return EGL::CreateContext(dpy, config, EGL_NO_CONTEXT, contextAttribs); }
};
// The robustness answers of the current context, before the loss.
void NoteRobustness(Egl& egl, RecoveryReport& r) {
r.eglRobustnessAdvertised =
HasToken(EGL::QueryString(egl.dpy, EGL_EXTENSIONS), "EGL_EXT_create_context_robustness") ? 1 : 0;
r.glRobustnessAdvertised =
HasToken(reinterpret_cast<const char*>(glGetString(GL_EXTENSIONS)), "GL_KHR_robustness") ? 1 : 0;
GLint count = 0;
glGetIntegerv(GL_NUM_EXTENSIONS, &count);
r.glRobustnessIndexed = 0;
for (GLint i = 0; i < count; ++i) {
const auto* name = reinterpret_cast<const char*>(glGetStringi(GL_EXTENSIONS, static_cast<GLuint>(i)));
if (name != nullptr && std::string(name) == "GL_KHR_robustness") r.glRobustnessIndexed = 1;
}
glGetIntegerv(GL_RESET_NOTIFICATION_STRATEGY, &r.strategyBefore);
GLint robust = -1;
glGetIntegerv(GL_CONTEXT_ROBUST_ACCESS, &robust);
r.robustAccess = robust;
}
// The client, in a fork: everything an application does around a loss, through the entry points.
void RunRecoveringClient(Route route, RecoveryReport& r) {
// `api` and `attribs` are the contexts' shape (the first and every replacement).
void RunRecoveringClient(Route route, RecoveryReport& r, EGLenum api = EGL_OPENGL_API,
const EGLint* attribs = kRobustAttribs) {
Egl egl;
egl.api = api;
egl.contextAttribs = attribs;
if (!egl.Bring(r)) return;
const EGLContext lost = egl.Context();
if (lost == EGL_NO_CONTEXT || EGL::MakeCurrent(egl.dpy, egl.surface, egl.surface, lost) != EGL_TRUE)
return Note(r, "the first context did not go current");
r.initialized = 1;
r.serverPidBefore = ServerPid();
NoteRobustness(egl, r);
// The objects of the context that is about to be lost, and device check #1 in the server
// process: a textured draw, read back.
@@ -285,6 +353,10 @@ namespace {
r.resetStatusLost = glGetGraphicsResetStatus();
r.errorLost = glGetError();
r.errorAfterLost = glGetError();
r.resetStatusRepeat = glGetGraphicsResetStatus();
using ResetStatusFn = GLenum (*)(void);
if (auto khr = reinterpret_cast<ResetStatusFn>(EGL::GetProcAddress("glGetGraphicsResetStatusKHR")))
r.resetStatusKhr = khr();
// What an application does before it has looked: more work on the lost context - a draw,
// and then an upload that no later verb of the lost context will ever carry (it is owed to
// a server that is gone). None of it may surface on the fresh session.
@@ -318,6 +390,8 @@ namespace {
(void)EGL::DestroySurface(egl.dpy, egl.surface);
(void)EGL::Terminate(egl.dpy);
Egl again;
again.api = egl.api;
again.contextAttribs = egl.contextAttribs;
if (!again.Bring(r)) return;
egl = again;
NoteTextureBooks(oldHandle, &r.oldTexturePublishedAfter, &r.oldTextureOwedAfter);
@@ -331,6 +405,7 @@ namespace {
if (!r.newCurrentOk) return Note(r, "the new context did not go current");
r.serverPidAfter = ServerPid();
r.resetStatusNew = glGetGraphicsResetStatus();
glGetIntegerv(GL_RESET_NOTIFICATION_STRATEGY, &r.strategyNew);
r.oldNameIsTexture = glIsTexture(old.texture) == GL_TRUE ? 1 : 0;
// THE NEW CONTEXT RENDERS: the same textured draw with a new program and texture, a clear of
@@ -384,7 +459,7 @@ namespace {
Egl egl;
RecoveryReport bring{};
if (!egl.Bring(bring)) return Note(r, bring.note);
const EGLint attribs[] = {EGL_CONTEXT_MAJOR_VERSION, 3, EGL_CONTEXT_MINOR_VERSION, 3, EGL_NONE};
const EGLint* attribs = kRobustAttribs;
const EGLContext share = egl.Context();
const EGLContext working = EGL::CreateContext(egl.dpy, egl.config, share, attribs);
if (working == EGL_NO_CONTEXT || EGL::MakeCurrent(egl.dpy, egl.surface, egl.surface, working) != EGL_TRUE)
@@ -492,6 +567,7 @@ namespace {
Int32 staleSwap = -1;
Int32 staleSwapError = 0;
Int32 staleRelease = 0;
Uint32 resetStatusAfterRelease = 0;
Int64 recordsByStaleThread = -1;
Uint32 pixelAfterStale = 0;
Uint32 resetStatusAfterStale = 0xFFFFFFFFu;
@@ -546,6 +622,9 @@ namespace {
r.staleSwap = EGL::SwapBuffers(egl.dpy, egl.surface);
r.staleSwapError = EGL::GetError();
r.staleRelease = EGL::MakeCurrent(egl.dpy, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT) == EGL_TRUE;
// Released, the thread still answers as lost until it binds a context again: Qt's
// render threads release before they ask, and rebuild only when told.
r.resetStatusAfterRelease = glGetGraphicsResetStatus();
});
r.recordsByStaleThread = static_cast<Int64>(PublishedSeq()) - static_cast<Int64>(before);
r.destroyOldOk = EGL::DestroyContext(egl.dpy, lost) == EGL_TRUE;
@@ -562,6 +641,95 @@ namespace {
(void)EGL::Terminate(egl.dpy);
}
// NO RESET NOTIFICATION. Two contexts of one session that did not ask to be told of a reset,
// each current on its own thread when the session is lost: an explicit core-profile one, which
// gets KHR_robustness' NO_RESET_NOTIFICATION behavior exactly (no reset status, no
// GL_CONTEXT_LOST), and a compatibility-profile one, which is told all the same (the relaxed
// default). Both still learn it from EGL - a swap and a make-current fail with EGL_CONTEXT_LOST -
// and a context created afterwards renders on a fresh session.
const EGLint kCoreNoResetAttribs[] = {EGL_CONTEXT_MAJOR_VERSION, 3, EGL_CONTEXT_MINOR_VERSION, 3, EGL_NONE};
const EGLint kCompatNoResetAttribs[] = {EGL_CONTEXT_MAJOR_VERSION,
3,
EGL_CONTEXT_MINOR_VERSION,
3,
EGL_CONTEXT_OPENGL_PROFILE_MASK,
EGL_CONTEXT_OPENGL_COMPATIBILITY_PROFILE_BIT,
EGL_NONE};
struct UntoldReport {
Int32 initialized = 0;
Uint32 firstPixel = 0;
Int32 lossSeen = 0;
Int32 coreStrategy = 0;
Uint32 coreStatus = 0xFFFFFFFFu;
Uint32 coreError = 0xFFFFFFFFu;
Int32 coreSwap = -1;
Int32 coreSwapError = 0;
Uint32 compatStatus = 0;
Uint32 compatError = 0;
Int32 coreAgain = -1;
Int32 coreAgainError = 0;
Int32 freshCurrent = 0;
Uint32 freshStatus = 0xFFFFFFFFu;
Uint32 freshPixel = 0;
char note[256] = {};
};
void Note(UntoldReport& r, const char* text) {
if (r.note[0] == '\0') std::snprintf(r.note, sizeof(r.note), "%s", text);
}
void RunUntoldClient(UntoldReport& r) {
Egl egl;
egl.contextAttribs = kCoreNoResetAttribs;
RecoveryReport bring{};
if (!egl.Bring(bring)) return Note(r, bring.note);
const EGLint pbufferAttribs[] = {EGL_WIDTH, 8, EGL_HEIGHT, 8, EGL_NONE};
const EGLSurface other = EGL::CreatePbufferSurface(egl.dpy, egl.config, pbufferAttribs);
const EGLContext core = egl.Context();
const EGLContext compat = EGL::CreateContext(egl.dpy, egl.config, EGL_NO_CONTEXT, kCompatNoResetAttribs);
if (core == EGL_NO_CONTEXT || compat == EGL_NO_CONTEXT || other == EGL_NO_SURFACE)
return Note(r, "the contexts or the second surface were not created");
Worker second;
Bool compatCurrent = false;
second.Run([&] { compatCurrent = EGL::MakeCurrent(egl.dpy, other, other, compat) == EGL_TRUE; });
if (!compatCurrent || EGL::MakeCurrent(egl.dpy, egl.surface, egl.surface, core) != EGL_TRUE)
return Note(r, "the contexts did not go current");
r.initialized = 1;
glGetIntegerv(GL_RESET_NOTIFICATION_STRATEGY, &r.coreStrategy);
r.firstPixel = ClearAndRead(0.0f, 1.0f, 0.0f); // device check #1
(void)ClearAndRead(0.0f, 0.0f, 1.0f); // device check #2: lost
r.lossSeen = WaitFor([] { return Remote::Client::ClientSession::SessionLatchedLost(); }, 5000) ? 1 : 0;
r.coreStatus = glGetGraphicsResetStatus();
r.coreError = glGetError();
second.Run([&] {
r.compatStatus = glGetGraphicsResetStatus();
r.compatError = glGetError();
(void)EGL::MakeCurrent(egl.dpy, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
});
r.coreSwap = EGL::SwapBuffers(egl.dpy, egl.surface);
r.coreSwapError = EGL::GetError();
(void)EGL::MakeCurrent(egl.dpy, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
r.coreAgain = EGL::MakeCurrent(egl.dpy, egl.surface, egl.surface, core);
r.coreAgainError = EGL::GetError();
if (r.coreAgain == EGL_TRUE) (void)EGL::MakeCurrent(egl.dpy, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
const EGLContext fresh = egl.Context();
r.freshCurrent = fresh != EGL_NO_CONTEXT && EGL::MakeCurrent(egl.dpy, egl.surface, egl.surface, fresh) == EGL_TRUE;
if (!r.freshCurrent) return Note(r, "no fresh context went current");
r.freshStatus = glGetGraphicsResetStatus();
r.freshPixel = ClearAndRead(0.0f, 0.0f, 1.0f);
(void)EGL::MakeCurrent(egl.dpy, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
(void)EGL::DestroyContext(egl.dpy, fresh);
(void)EGL::DestroyContext(egl.dpy, compat);
(void)EGL::DestroyContext(egl.dpy, core);
(void)EGL::DestroySurface(egl.dpy, other);
(void)EGL::DestroySurface(egl.dpy, egl.surface);
(void)EGL::Terminate(egl.dpy);
}
// Runs `body` in a forked client (the environment a deployment sets, then the entry points)
// and hands back the report it filled.
template <class Report, class Body>
@@ -607,9 +775,259 @@ namespace {
return report;
}
RecoveryReport RunClient(const ServerProcess& server, Route route, const std::string& clientLogBase) {
return RunInClient<RecoveryReport>(server, clientLogBase,
[route](RecoveryReport& r) { RunRecoveringClient(route, r); });
// THE SESSION-TARGETED KNOB (MOBILEGL_DEBUG_INJECT_DEVICE_LOST_PID): one client of several is
// lost, whenever its session drains, whether or not it ever presents or reads back. Its pid
// has to be known before the server starts (the knob is the server's environment), so it is
// forked first and held until the server listens; the endpoint is handed to it then.
struct TargetedReport {
Int32 initialized = 0;
Int32 lossSeen = 0;
Uint32 resetStatus = 0;
Int32 freshCurrent = 0;
Uint32 freshPixel = 0;
Int32 freshFrames = 0;
Uint32 freshStatusEnd = 0xFFFFFFFFu;
char note[256] = {};
};
void Note(TargetedReport& r, const char* text) {
if (r.note[0] == '\0') std::snprintf(r.note, sizeof(r.note), "%s", text);
}
// Draws until its context reports the reset, recovers on a new context, then keeps drawing
// for half a second - long enough for the knob to be asked again - and must not be lost again.
void RunTargetedClient(TargetedReport& r) {
Egl egl;
RecoveryReport bring{};
if (!egl.Bring(bring)) return Note(r, bring.note);
const EGLContext lost = egl.Context();
if (lost == EGL_NO_CONTEXT || EGL::MakeCurrent(egl.dpy, egl.surface, egl.surface, lost) != EGL_TRUE)
return Note(r, "the first context did not go current");
r.initialized = 1;
r.lossSeen = WaitFor(
[] {
(void)ClearAndRead(0.0f, 1.0f, 0.0f);
return glGetGraphicsResetStatus() != GL_NO_ERROR;
},
10000)
? 1
: 0;
r.resetStatus = glGetGraphicsResetStatus();
(void)EGL::MakeCurrent(egl.dpy, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
const EGLContext fresh = egl.Context();
(void)EGL::DestroyContext(egl.dpy, lost);
r.freshCurrent = fresh != EGL_NO_CONTEXT && EGL::MakeCurrent(egl.dpy, egl.surface, egl.surface, fresh) == EGL_TRUE;
if (!r.freshCurrent) return Note(r, "no fresh context went current");
const auto until = std::chrono::steady_clock::now() + std::chrono::milliseconds(500);
while (std::chrono::steady_clock::now() < until) {
r.freshPixel = ClearAndRead(0.0f, 0.0f, 1.0f);
++r.freshFrames;
std::this_thread::sleep_for(std::chrono::milliseconds(20));
}
r.freshStatusEnd = glGetGraphicsResetStatus();
(void)EGL::MakeCurrent(egl.dpy, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
(void)EGL::DestroyContext(egl.dpy, fresh);
(void)EGL::DestroySurface(egl.dpy, egl.surface);
(void)EGL::Terminate(egl.dpy);
}
// A client of the same server that is not the target: half a second of read-backs, untouched.
struct BystanderReport {
Int32 initialized = 0;
Int32 frames = 0;
Uint32 lastPixel = 0;
Uint32 resetStatus = 0xFFFFFFFFu;
char note[256] = {};
};
void Note(BystanderReport& r, const char* text) {
if (r.note[0] == '\0') std::snprintf(r.note, sizeof(r.note), "%s", text);
}
void RunBystanderClient(BystanderReport& r) {
Egl egl;
RecoveryReport bring{};
if (!egl.Bring(bring)) return Note(r, bring.note);
const EGLContext context = egl.Context();
if (context == EGL_NO_CONTEXT || EGL::MakeCurrent(egl.dpy, egl.surface, egl.surface, context) != EGL_TRUE)
return Note(r, "the context did not go current");
r.initialized = 1;
const auto until = std::chrono::steady_clock::now() + std::chrono::milliseconds(500);
while (std::chrono::steady_clock::now() < until) {
r.lastPixel = ClearAndRead(1.0f, 0.0f, 0.0f);
++r.frames;
std::this_thread::sleep_for(std::chrono::milliseconds(20));
}
r.resetStatus = glGetGraphicsResetStatus();
(void)EGL::MakeCurrent(egl.dpy, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
(void)EGL::DestroyContext(egl.dpy, context);
(void)EGL::DestroySurface(egl.dpy, egl.surface);
(void)EGL::Terminate(egl.dpy);
}
// A forked client that waits for the endpoint before it does anything.
template <class Report, class Body>
struct HeldClient {
pid_t pid = -1;
int go = -1;
int report = -1;
Bool Fork(const std::string& clientLogBase, Body body) {
int goFds[2] = {-1, -1};
int reportFds[2] = {-1, -1};
if (::pipe(goFds) != 0 || ::pipe(reportFds) != 0) return false;
std::fflush(nullptr);
pid = ::fork();
if (pid == 0) {
::close(goFds[1]);
::close(reportFds[0]);
char endpoint[512] = {};
const ssize_t got = ::read(goFds[0], endpoint, sizeof(endpoint) - 1);
if (got <= 0) ::_exit(0);
::setenv("MOBILEGL_LOG_FILE_PATH", clientLogBase.c_str(), 1);
::setenv("MOBILEGL_TRANSPORT", "spawn", 1);
::setenv("MOBILEGL_IPC_CONTROL", endpoint, 1);
::unsetenv("MOBILEGL_IPC_SURFACE");
::unsetenv("MOBILEGL_BACKEND_TYPE");
::unsetenv("MOBILEGL_DEBUG_INJECT_DEVICE_LOST_AT");
::unsetenv("MOBILEGL_DEBUG_INJECT_DEVICE_LOST_PID");
Report r{};
body(r);
const ssize_t wrote = ::write(reportFds[1], &r, sizeof(r));
(void)wrote;
std::fflush(nullptr);
::_exit(0);
}
::close(goFds[0]);
::close(reportFds[1]);
go = goFds[1];
report = reportFds[0];
return pid > 0;
}
Report Release(const std::string& endpoint) {
Report r{};
const ssize_t wrote = ::write(go, endpoint.c_str(), endpoint.size());
(void)wrote;
::close(go);
pollfd pfd{report, POLLIN, 0};
if (::poll(&pfd, 1, 90000) > 0) {
if (::read(report, &r, sizeof(r)) != static_cast<ssize_t>(sizeof(r))) {
r = Report{};
Note(r, "the client died before reporting");
}
} else {
Note(r, "the client timed out");
::kill(pid, SIGKILL);
}
::close(report);
int status = 0;
::waitpid(pid, &status, 0);
return r;
}
};
// THE ES IDENTITY (MOBILEGL_ES_CONTEXT_IDENTITY=1), what Chrome's GPU process runs with: ANGLE
// offers GL_OES_EGL_image - the GPU process's dma-buf images - only over a native driver that
// calls itself OpenGL ES, and then creates BGRA textures with the ES spelling. And the API a
// dispatching libEGL reports wins over the one this library was told (glvnd never forwards a
// bind of the API it already reports, EGL's default ES).
struct EsIdentityReport {
Int32 initialized = 0;
Int32 dispatcherApiWins = -1;
char esVersion[96] = {};
char esGlsl[64] = {};
Int32 esMajor = 0;
Int32 esMinor = 0;
Int32 bgraAdvertised = -1;
Int32 bgraIndexed = -1;
Uint32 bgraImageError = 0xFFFFFFFFu;
Uint32 bgraStorageError = 0xFFFFFFFFu;
Uint32 bgraFboStatus = 0;
Uint32 bgraPixel = 0;
char desktopVersion[96] = {};
char note[256] = {};
};
void Note(EsIdentityReport& r, const char* text) {
if (r.note[0] == '\0') std::snprintf(r.note, sizeof(r.note), "%s", text);
}
EGLenum g_dispatcherApi = EGL_OPENGL_ES_API;
void RunEsIdentityClient(EsIdentityReport& r) {
::setenv("MOBILEGL_ES_CONTEXT_IDENTITY", "1", 1);
Egl egl;
RecoveryReport bring{};
if (!egl.Bring(bring)) return Note(r, bring.note);
// The dispatcher says ES although this library was told GL last (Bring binds the GL API).
EGL::SetDispatcherCurrentApiHook([]() -> EGLenum { return g_dispatcherApi; });
const EGLContext es = EGL::CreateContext(egl.dpy, egl.config, EGL_NO_CONTEXT, kAngleNativeAttribs);
g_dispatcherApi = EGL_OPENGL_API;
const EGLContext desktop = EGL::CreateContext(egl.dpy, egl.config, EGL_NO_CONTEXT, kRobustAttribs);
EGL::SetDispatcherCurrentApiHook(nullptr);
if (es == EGL_NO_CONTEXT || desktop == EGL_NO_CONTEXT) return Note(r, "the contexts were not created");
EGLint type = 0;
(void)EGL::QueryContext(egl.dpy, es, EGL_CONTEXT_CLIENT_TYPE, &type);
r.dispatcherApiWins = type == EGL_OPENGL_ES_API ? 1 : 0;
if (EGL::MakeCurrent(egl.dpy, egl.surface, egl.surface, es) != EGL_TRUE)
return Note(r, "the ES context did not go current");
r.initialized = 1;
std::snprintf(r.esVersion, sizeof(r.esVersion), "%s", reinterpret_cast<const char*>(glGetString(GL_VERSION)));
std::snprintf(r.esGlsl, sizeof(r.esGlsl), "%s",
reinterpret_cast<const char*>(glGetString(GL_SHADING_LANGUAGE_VERSION)));
glGetIntegerv(GL_MAJOR_VERSION, &r.esMajor);
glGetIntegerv(GL_MINOR_VERSION, &r.esMinor);
r.bgraAdvertised = HasToken(reinterpret_cast<const char*>(glGetString(GL_EXTENSIONS)),
"GL_EXT_texture_format_BGRA8888")
? 1
: 0;
GLint count = 0;
glGetIntegerv(GL_NUM_EXTENSIONS, &count);
r.bgraIndexed = 0;
for (GLint i = 0; i < count; ++i) {
const auto* name = reinterpret_cast<const char*>(glGetStringi(GL_EXTENSIONS, static_cast<GLuint>(i)));
if (name != nullptr && std::string(name) == "GL_EXT_texture_format_BGRA8888") r.bgraIndexed = 1;
}
while (glGetError() != GL_NO_ERROR) {
}
// BGRA as EXT_texture_format_BGRA8888 spells it: GL_BGRA_EXT as the internal format, and
// GL_BGRA8_EXT through glTexStorage2D; a BGRA texel reads back in RGBA order.
const Uint8 bgra[4] = {0x10, 0x20, 0x30, 0xFF}; // B, G, R, A
GLuint textures[2] = {};
glGenTextures(2, textures);
glBindTexture(GL_TEXTURE_2D, textures[0]);
glTexImage2D(GL_TEXTURE_2D, 0, GL_BGRA, 1, 1, 0, GL_BGRA, GL_UNSIGNED_BYTE, bgra);
r.bgraImageError = glGetError();
glBindTexture(GL_TEXTURE_2D, textures[1]);
glTexStorage2D(GL_TEXTURE_2D, 1, 0x93A1 /* GL_BGRA8_EXT */, 1, 1);
r.bgraStorageError = glGetError();
GLuint framebuffer = 0;
glGenFramebuffers(1, &framebuffer);
glBindFramebuffer(GL_FRAMEBUFFER, framebuffer);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, textures[0], 0);
r.bgraFboStatus = glCheckFramebufferStatus(GL_FRAMEBUFFER);
r.bgraPixel = ReadPixel();
glBindFramebuffer(GL_FRAMEBUFFER, 0);
(void)EGL::MakeCurrent(egl.dpy, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
if (EGL::MakeCurrent(egl.dpy, egl.surface, egl.surface, desktop) == EGL_TRUE) {
std::snprintf(r.desktopVersion, sizeof(r.desktopVersion), "%s",
reinterpret_cast<const char*>(glGetString(GL_VERSION)));
(void)EGL::MakeCurrent(egl.dpy, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
}
(void)EGL::DestroyContext(egl.dpy, es);
(void)EGL::DestroyContext(egl.dpy, desktop);
(void)EGL::DestroySurface(egl.dpy, egl.surface);
(void)EGL::Terminate(egl.dpy);
}
RecoveryReport RunClient(const ServerProcess& server, Route route, const std::string& clientLogBase,
EGLenum api = EGL_OPENGL_API, const EGLint* attribs = kRobustAttribs) {
return RunInClient<RecoveryReport>(server, clientLogBase, [route, api, attribs](RecoveryReport& r) {
RunRecoveringClient(route, r, api, attribs);
});
}
struct ClientLog {
@@ -646,6 +1064,15 @@ namespace {
ASSERT_EQ(r.firstPixel, kGreen) << "the first draw (device check #1) did not read back: " << std::hex
<< r.firstPixel << "\n" << r.note << "\n" << diagnostics;
EXPECT_NE(r.lostPixel, kBlue) << "a read-back on the lost device returned a frame";
// What the application checked before it asked to be told (ANGLE mirrors the EGL
// extension onto its own display; Chrome checks that and GL_*_robustness), and what
// its context then reports. Robust buffer ACCESS was not asked for and is not claimed.
EXPECT_EQ(r.eglRobustnessAdvertised, 1) << "EGL_EXT_create_context_robustness is not advertised";
EXPECT_EQ(r.glRobustnessAdvertised, 1) << "GL_KHR_robustness is not in glGetString(GL_EXTENSIONS)";
EXPECT_EQ(r.glRobustnessIndexed, 1) << "GL_KHR_robustness is not in glGetStringi(GL_EXTENSIONS, i)";
EXPECT_EQ(r.strategyBefore, GL_LOSE_CONTEXT_ON_RESET) << "GL_RESET_NOTIFICATION_STRATEGY: 0x" << std::hex
<< r.strategyBefore;
EXPECT_EQ(r.robustAccess, GL_FALSE);
// The loss is reported.
EXPECT_TRUE(r.resetStatusLost == GL_UNKNOWN_CONTEXT_RESET || r.resetStatusLost == GL_GUILTY_CONTEXT_RESET)
<< "glGetGraphicsResetStatus after the loss: 0x" << std::hex << r.resetStatusLost;
@@ -653,6 +1080,13 @@ namespace {
<< "glGetError after the loss: 0x" << std::hex << r.errorLost;
EXPECT_EQ(r.errorAfterLost, static_cast<Uint32>(GL_NO_ERROR))
<< "GL_CONTEXT_LOST must be reported once, not forever (a drain loop must end)";
// LOSE_CONTEXT_ON_RESET: the context stays lost, so the status does not go back to
// GL_NO_ERROR (that would read as a reset that completed in place), and the KHR name
// an ES application looks up answers the same.
EXPECT_EQ(r.resetStatusRepeat, r.resetStatusLost) << "the reset status of a lost context went back to 0x"
<< std::hex << r.resetStatusRepeat;
EXPECT_EQ(r.resetStatusKhr, r.resetStatusLost) << "glGetGraphicsResetStatusKHR: 0x" << std::hex
<< r.resetStatusKhr;
EXPECT_EQ(r.swapLost, EGL_FALSE) << "eglSwapBuffers on the lost context succeeded";
EXPECT_EQ(r.swapLostError, EGL_CONTEXT_LOST) << "eglSwapBuffers on the lost context: 0x" << std::hex
<< r.swapLostError;
@@ -668,6 +1102,7 @@ namespace {
<< r.newCurrentError << ")\n" << r.note << "\n" << diagnostics;
EXPECT_EQ(r.serverPidAfter, r.serverPidBefore) << "the new session is not on the same server process";
EXPECT_EQ(r.resetStatusNew, static_cast<Uint32>(GL_NO_ERROR)) << "the new context reports a reset";
EXPECT_EQ(r.strategyNew, GL_LOSE_CONTEXT_ON_RESET) << "the replacement is not told of resets";
EXPECT_EQ(r.oldNameIsTexture, 0) << "the old context's texture name resolves in the new context";
// The client's books on the lost texture: before the recovery the lost session had its
// record (the arm proof that there was something to forget), and the upload made on the
@@ -724,6 +1159,51 @@ TEST_F(ClientRecovery, ANewContextAfterADeviceLossRendersOnAFreshSession) {
const std::string diagnostics = "server:\n" + server.Log() + "\nclient:\n" + client.Text();
ExpectLossReportedAndRecovered(r, diagnostics);
EXPECT_EQ(r.recordsByOldDestroy, 0) << "destroying the lost context published records on the new session";
// The status is UNKNOWN for a reason, and the client log names it once.
EXPECT_EQ(Count(client.Text(), "GL_UNKNOWN_CONTEXT_RESET for a context of a lost session"), 1u) << client.Text();
ExpectOneLossAndACleanSecondSession(server);
server.Stop();
}
// ANGLE'S OWN NATIVE CONTEXT. ANGLE's GL-on-EGL backend (Chrome's --use-angle=gles) creates one ES
// context per display with EGL 1.5's name of the reset attribute, and learns of a reset ONLY through
// that context's reset status - which it then hands to Chrome. The same recovery, in its shape.
TEST_F(ClientRecovery, AnglesNativeContextShapeIsToldOfTheLossAndRecovers) {
ServerProcess server;
ASSERT_TRUE(Launch(&server, "angle")) << server.Log();
ClientLog client("angle");
const RecoveryReport r = RunClient(server, Route::NewContext, client.base, EGL_OPENGL_ES_API, kAngleNativeAttribs);
const std::string diagnostics = "server:\n" + server.Log() + "\nclient:\n" + client.Text();
ExpectLossReportedAndRecovered(r, diagnostics);
ExpectOneLossAndACleanSecondSession(server);
server.Stop();
}
// NO RESET NOTIFICATION (RunUntoldClient): the explicit core-profile context is not told through
// GL, the compatibility-profile one is; both learn it from EGL, and the application recovers.
TEST_F(ClientRecovery, ContextsThatDidNotAskAreToldOnlyWhereRelaxedAndStillRecoverThroughEgl) {
ServerProcess server;
ASSERT_TRUE(Launch(&server, "untold")) << server.Log();
ClientLog client("untold");
const UntoldReport r = RunInClient<UntoldReport>(server, client.base, &RunUntoldClient);
const std::string diagnostics = "server:\n" + server.Log() + "\nclient:\n" + client.Text();
ASSERT_EQ(r.initialized, 1) << r.note << "\n" << diagnostics;
ASSERT_EQ(r.firstPixel, kGreen) << std::hex << r.firstPixel << "\n" << diagnostics;
ASSERT_EQ(r.lossSeen, 1) << "the injected loss never latched\n" << diagnostics;
EXPECT_EQ(r.coreStrategy, GL_NO_RESET_NOTIFICATION);
EXPECT_EQ(r.coreStatus, static_cast<Uint32>(GL_NO_ERROR))
<< "a NO_RESET_NOTIFICATION core-profile context was told of the reset: 0x" << std::hex << r.coreStatus;
EXPECT_NE(r.coreError, static_cast<Uint32>(GL_CONTEXT_LOST));
EXPECT_EQ(r.compatStatus, static_cast<Uint32>(GL_UNKNOWN_CONTEXT_RESET))
<< "the compatibility-profile context was not told: 0x" << std::hex << r.compatStatus;
EXPECT_EQ(r.compatError, static_cast<Uint32>(GL_CONTEXT_LOST));
EXPECT_EQ(r.coreSwap, EGL_FALSE);
EXPECT_EQ(r.coreSwapError, EGL_CONTEXT_LOST) << std::hex << r.coreSwapError;
EXPECT_EQ(r.coreAgain, EGL_FALSE);
EXPECT_EQ(r.coreAgainError, EGL_CONTEXT_LOST) << std::hex << r.coreAgainError;
ASSERT_EQ(r.freshCurrent, 1) << r.note << "\n" << diagnostics;
EXPECT_EQ(r.freshStatus, static_cast<Uint32>(GL_NO_ERROR));
EXPECT_EQ(r.freshPixel, kBlue) << std::hex << r.freshPixel << "\n" << diagnostics;
ExpectOneLossAndACleanSecondSession(server);
server.Stop();
}
@@ -760,6 +1240,8 @@ TEST_F(ClientRecovery, AThreadStillOnTheLostContextReachesNothingOfTheFreshSessi
EXPECT_EQ(r.staleSwap, EGL_FALSE);
EXPECT_EQ(r.staleSwapError, EGL_CONTEXT_LOST) << std::hex << r.staleSwapError;
EXPECT_EQ(r.staleRelease, 1) << "the second thread could not release the lost context";
EXPECT_NE(r.resetStatusAfterRelease, static_cast<Uint32>(GL_NO_ERROR))
<< "the thread that released the lost context no longer reports the reset";
EXPECT_EQ(r.recordsByStaleThread, 0) << "the thread on the lost context published records on the fresh session";
EXPECT_EQ(r.destroyOldOk, 1);
EXPECT_EQ(r.pixelAfterStale, kRed) << "the fresh context stopped rendering: " << std::hex << r.pixelAfterStale
@@ -791,3 +1273,94 @@ TEST_F(ClientRecovery, ContextsNamingALostShareContextShareOneNewGroup) {
ExpectOneLossAndACleanSecondSession(server);
server.Stop();
}
// THE SESSION-TARGETED KNOB (what the device test sets on a running desktop): a bystander client
// of the same server draws on untouched; the target is lost although it only clears and reads
// back - no present - recovers on a fresh session, and is not lost again by the same setting.
TEST_F(ClientRecovery, ThePidTargetedKnobLosesOnlyThatClientAndOnlyOnce) {
auto targetBody = [](TargetedReport& r) { RunTargetedClient(r); };
HeldClient<TargetedReport, decltype(targetBody)> target;
ClientLog targetLog("pid-target");
ASSERT_TRUE(target.Fork(targetLog.base, targetBody));
ServerProcess server;
::setenv("MOBILEGL_DEBUG_INJECT_DEVICE_LOST_PID", std::to_string(target.pid).c_str(), 1);
const bool launched = LaunchUnixInProcessServer(&server, "pid");
::unsetenv("MOBILEGL_DEBUG_INJECT_DEVICE_LOST_PID");
if (!launched) {
(void)target.Release("");
FAIL() << server.Log();
}
ClientLog bystanderLog("pid-bystander");
const BystanderReport bystander =
RunInClient<BystanderReport>(server, bystanderLog.base, &RunBystanderClient);
const TargetedReport r = target.Release(server.endpoint);
const std::string diagnostics = "server:\n" + server.Log() + "\ntarget:\n" + targetLog.Text() +
"\nbystander:\n" + bystanderLog.Text();
ASSERT_EQ(bystander.initialized, 1) << bystander.note << "\n" << diagnostics;
EXPECT_GT(bystander.frames, 5);
EXPECT_EQ(bystander.lastPixel, kRed) << std::hex << bystander.lastPixel;
EXPECT_EQ(bystander.resetStatus, static_cast<Uint32>(GL_NO_ERROR)) << "the bystander was lost";
ASSERT_EQ(r.initialized, 1) << r.note << "\n" << diagnostics;
ASSERT_EQ(r.lossSeen, 1) << "the targeted client was never lost\n" << diagnostics;
EXPECT_EQ(r.resetStatus, static_cast<Uint32>(GL_UNKNOWN_CONTEXT_RESET)) << std::hex << r.resetStatus;
ASSERT_EQ(r.freshCurrent, 1) << r.note << "\n" << diagnostics;
EXPECT_GT(r.freshFrames, 5);
EXPECT_EQ(r.freshPixel, kBlue) << std::hex << r.freshPixel << "\n" << diagnostics;
EXPECT_EQ(r.freshStatusEnd, static_cast<Uint32>(GL_NO_ERROR)) << "the recovered session was lost again";
// Three sessions: the bystander's and the recovered one end cleanly, the target's latched on
// the knob, naming the pid.
ASSERT_TRUE(WaitFor([&] { return Count(server.Log(), "reaped exit=") == 3; }, 10000)) << server.Log();
const std::string log = server.Log();
EXPECT_EQ(Count(log, "SessionLatch{"), 1u) << log;
EXPECT_NE(log.find("injected:pid=" + std::to_string(target.pid)), std::string::npos) << log;
EXPECT_EQ(Count(log, "reaped exit=75"), 1u) << log;
EXPECT_EQ(Count(log, "reaped exit=0"), 2u) << log;
server.Stop();
}
// THE ES IDENTITY (RunEsIdentityClient): an ES context names itself OpenGL ES 3.2 and offers BGRA
// the ES way, a desktop context of the same process does not change, and the dispatcher's API wins.
TEST_F(ClientRecovery, AnEsContextUnderTheEsIdentityIsOpenGlEs32WithBgraTextures) {
ServerProcess server;
ASSERT_TRUE(LaunchUnixInProcessServer(&server, "esid")) << server.Log();
ClientLog client("esid");
const EsIdentityReport r = RunInClient<EsIdentityReport>(server, client.base, &RunEsIdentityClient);
const std::string diagnostics = "server:\n" + server.Log() + "\nclient:\n" + client.Text();
EXPECT_EQ(r.dispatcherApiWins, 1) << "the context was not created for the API the dispatcher reports";
ASSERT_EQ(r.initialized, 1) << r.note << "\n" << diagnostics;
EXPECT_EQ(std::string(r.esVersion).rfind("OpenGL ES 3.2 ", 0), 0u) << r.esVersion;
EXPECT_STREQ(r.esGlsl, "OpenGL ES GLSL ES 3.20");
EXPECT_EQ(r.esMajor, 3);
EXPECT_EQ(r.esMinor, 2);
EXPECT_EQ(r.bgraAdvertised, 1);
EXPECT_EQ(r.bgraIndexed, 1);
EXPECT_EQ(r.bgraImageError, static_cast<Uint32>(GL_NO_ERROR)) << std::hex << r.bgraImageError;
EXPECT_EQ(r.bgraStorageError, static_cast<Uint32>(GL_NO_ERROR)) << std::hex << r.bgraStorageError;
EXPECT_EQ(r.bgraFboStatus, static_cast<Uint32>(GL_FRAMEBUFFER_COMPLETE)) << std::hex << r.bgraFboStatus;
EXPECT_EQ(r.bgraPixel, 0xFF102030u) << "a BGRA texel did not read back in RGBA order: " << std::hex << r.bgraPixel;
EXPECT_EQ(std::string(r.desktopVersion).find("OpenGL ES"), std::string::npos)
<< "a desktop context took the ES identity: " << r.desktopVersion;
EXPECT_NE(std::string(r.desktopVersion), "") << diagnostics;
server.Stop();
}
// Chrome's GPU process's own shape: ANGLE's native ES context, under the ES identity, told of the
// loss and recovering like any other.
TEST_F(ClientRecovery, AnglesNativeContextUnderTheEsIdentityRecovers) {
ServerProcess server;
ASSERT_TRUE(Launch(&server, "angle-es")) << server.Log();
ClientLog client("angle-es");
const RecoveryReport r = RunInClient<RecoveryReport>(server, client.base, [](RecoveryReport& report) {
::setenv("MOBILEGL_ES_CONTEXT_IDENTITY", "1", 1);
RunRecoveringClient(Route::NewContext, report, EGL_OPENGL_ES_API, kAngleNativeAttribs);
});
const std::string diagnostics = "server:\n" + server.Log() + "\nclient:\n" + client.Text();
ExpectLossReportedAndRecovered(r, diagnostics);
ExpectOneLossAndACleanSecondSession(server);
server.Stop();
}
@@ -0,0 +1,686 @@
// MobileGL - MobileGL/MG_Test/Wire/CompositorRecoveryTest.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
// A COMPOSITOR OUTLIVES ITS LOST SESSION. The compositor of the anland desktop renders into the
// SERVER's window (MOBILEGL_IPC_SURFACE=server: a ServerOwned window surface, which its session holds
// the display's window lease for) and samples its clients' frames as shared images it imports from
// their dma-bufs. ClientRecoveryTest is an application's recovery; this is the compositor's, against
// the in-process display server with a stand-in window (a host has no window a backend can draw into,
// so the server gives the ServerOwned surface a pbuffer of the window's extent - the seam is
// ServerLoop's). The hand-over of the window lease from a lost session that is still tearing down is
// ServerDisplayTest's and ServerLoopTest's: the client hears of a loss it is blocked in only when the
// lost session hangs up, which is after that session ended its lease.
//
// What it asserts, from each side:
// * the compositor's session is lost (the pid-targeted knob) and the compositor, recovering the
// way KWin does - its contexts recreated, naming the lost share context, and the surface it kept
// made current again - gets the server's window again on a FRESH session, asked for at the size
// the compositor asked for (none: the window's own), not fixed at the extent it had;
// * the surface renders on the fresh session (a clear, read back) and swaps;
// * the other client's shared image survives the loss and is imported again; the lost session's
// EGLImage of it can no longer be bound, and destroying it - after the same image was imported
// again under the same id - puts nothing on the fresh session's wire (it must not drop the new
// reference);
// * the image's owner is untouched: its session is not lost, it renders, and the server still
// identifies its image.
#include "P12ServerRig.h"
#include <MG_Backend/BackendObjects.h>
#include <MG_Impl/EGLImpl/EGLImpl.h>
#include <MG_Remote/Server/ServerDisplay.h>
#include <fcntl.h>
#include <sys/uio.h>
extern "C" {
void glClearColor(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha);
void glClear(GLbitfield mask);
void glReadPixels(GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, void* pixels);
GLenum glGetError(void);
GLenum glGetGraphicsResetStatus(void);
void glGenTextures(GLsizei n, GLuint* textures);
void glBindTexture(GLenum target, GLuint texture);
void glFlush(void);
}
using namespace MobileGL;
using namespace P12;
namespace {
namespace EGL = MobileGL::MG_Impl::EGLImpl;
namespace Server = MobileGL::MG_Remote::Server;
constexpr Uint32 kGreen = 0xFF00FF00u;
constexpr Uint32 kBlue = 0xFFFF0000u;
constexpr Uint32 kRed = 0xFF0000FFu;
constexpr Uint32 kUntouched = 0x5A5A5A5Au;
constexpr Uint32 kXrgb8888 = 0x34325258u;
constexpr Uint32 kWindowWidth = 64;
constexpr Uint32 kWindowHeight = 48;
constexpr Uint32 kImageWidth = 32;
constexpr Uint32 kImageHeight = 16;
// KWin's context shape: desktop GL 3.1 that asks to be told of a reset.
const EGLint kRobustAttribs[] = {EGL_CONTEXT_MAJOR_VERSION,
3,
EGL_CONTEXT_MINOR_VERSION,
1,
EGL_CONTEXT_OPENGL_RESET_NOTIFICATION_STRATEGY,
EGL_LOSE_CONTEXT_ON_RESET,
EGL_NONE};
Uint32 ReadPixel() {
Uint32 pixel = kUntouched;
glReadPixels(0, 0, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, &pixel);
return pixel;
}
Uint32 ClearAndRead(GLfloat red, GLfloat green, GLfloat blue) {
glClearColor(red, green, blue, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
return ReadPixel();
}
Uint64 PublishedSeq() {
auto* session = Remote::Client::ClientSession::Active();
return session != nullptr ? session->LastPublishedSeq() : 0;
}
// ---- the server process -----------------------------------------------------------------
int g_window = 0;
std::string g_geometryPath;
void NoWindowReference(void*, void*) {}
// Every geometry the display is asked for, one "W H" line each, for the parent to read.
void RecordGeometry(void*, Uint32 width, Uint32 height) {
const int fd = ::open(g_geometryPath.c_str(), O_WRONLY | O_CREAT | O_APPEND | O_CLOEXEC, 0644);
if (fd < 0) return;
const std::string line = std::to_string(width) + " " + std::to_string(height) + "\n";
const ssize_t wrote = ::write(fd, line.data(), line.size());
(void)wrote;
::close(fd);
}
Bool PbufferForTheServerWindow(MG_Backend::BackendObject* backend, EGLSurface surface,
const MG_Backend::WindowHandle& window) {
return backend->CreateEGLPbufferSurface(surface, static_cast<EGLint>(window.Width),
static_cast<EGLint>(window.Height));
}
// RunUnixInProcessServerProcess (P12ServerRig.h), with a display and its stand-in window.
[[noreturn]] void RunDisplayServerProcess(const std::string& endpoint, const std::string& logBase) {
::setenv("MOBILEGL_LOG_FILE_PATH", logBase.c_str(), 1);
::setenv("MOBILEGL_IPC_ROLE", "server", 1);
::setenv("MOBILEGL_IPC_DIAL", "no", 1);
for (const char* name : {"MOBILEGL_TRANSPORT", "MOBILEGL_IPC_SERVER_PATH", "MOBILEGL_IPC_RING_MB",
"MOBILEGL_IPC_STAGE_MB", "MOBILEGL_IPC_CONTROL", "MOBILEGL_IPC_SURFACE",
"MOBILEGL_IPC_INPROC_MAX_SESSIONS", "MOBILEGL_BACKEND_TYPE"})
::unsetenv(name);
g_geometryPath = logBase + ".geometry";
Server::ServerDisplayHooks hooks;
hooks.acquire = &NoWindowReference;
hooks.release = &NoWindowReference;
hooks.requestGeometry = &RecordGeometry;
Server::ServerDisplayInstance().Install(hooks);
Server::ServerDisplayInstance().Attach(&g_window, kWindowWidth, kWindowHeight);
Server::ServerLoop::SetServerOwnedSurfaceHookForTesting(&PbufferForTheServerWindow);
sigset_t stop;
sigemptyset(&stop);
sigaddset(&stop, SIGTERM);
pthread_sigmask(SIG_BLOCK, &stop, nullptr);
std::atomic<bool> returned{false};
std::atomic<int> served{-1};
std::thread server([&] {
served.store(mobilegl_server_serve_inprocess(endpoint.c_str()));
returned.store(true);
});
bool stopping = false;
while (!returned.load()) {
timespec slice{0, 100 * 1000 * 1000};
if (sigtimedwait(&stop, nullptr, &slice) == SIGTERM && !stopping) {
stopping = true;
mobilegl_server_stop_inprocess();
}
}
server.join();
std::fflush(nullptr);
::_exit(stopping && served.load() == 0 ? 0 : 100 + (served.load() & 0x7f));
}
bool LaunchDisplayServer(ServerProcess* server, const std::string& label) {
server->endpoint = "@mgl-comprec-" + label + "-" + std::to_string(::getpid());
server->logBase = "/tmp/mgl-comprec-" + label + "-" + std::to_string(::getpid()) + ".log";
::setenv("MOBILEGL_LOG_FILE_PATH", server->logBase.c_str(), 1);
PinHeadlessEgl();
Debug::TruncateRoleLogs(server->logBase.c_str());
std::error_code ec;
std::filesystem::remove(server->logBase + ".geometry", ec);
std::fflush(nullptr);
const pid_t pid = ::fork();
if (pid < 0) return false;
if (pid == 0) RunDisplayServerProcess(server->endpoint, server->logBase);
server->pid = pid;
bool listening = false;
(void)WaitFor(
[&] {
if (server->Log().find("listening on") != std::string::npos) return listening = true;
return server->WaitExit(0) && server->pid <= 0;
},
10000);
if (listening) server->endpoint = "unix:" + server->endpoint;
return listening;
}
// ---- the descriptor between the two clients ---------------------------------------------
struct SharedImageMessage {
Uint32 width = 0;
Uint32 height = 0;
Uint32 fourcc = 0;
Uint32 stride = 0;
Uint32 offset = 0;
Uint64 id = 0;
};
bool SendFd(int sock, int fd, const SharedImageMessage& message) {
iovec iov{const_cast<SharedImageMessage*>(&message), sizeof(message)};
alignas(cmsghdr) char control[CMSG_SPACE(sizeof(int))] = {};
msghdr msg{};
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
msg.msg_control = control;
msg.msg_controllen = sizeof(control);
cmsghdr* cmsg = CMSG_FIRSTHDR(&msg);
cmsg->cmsg_level = SOL_SOCKET;
cmsg->cmsg_type = SCM_RIGHTS;
cmsg->cmsg_len = CMSG_LEN(sizeof(int));
std::memcpy(CMSG_DATA(cmsg), &fd, sizeof(int));
return ::sendmsg(sock, &msg, 0) == static_cast<ssize_t>(sizeof(message));
}
bool ReceiveFd(int sock, int* fd, SharedImageMessage* message, int timeoutMs) {
pollfd pfd{sock, POLLIN, 0};
if (::poll(&pfd, 1, timeoutMs) <= 0) return false;
iovec iov{message, sizeof(*message)};
alignas(cmsghdr) char control[CMSG_SPACE(sizeof(int))] = {};
msghdr msg{};
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
msg.msg_control = control;
msg.msg_controllen = sizeof(control);
if (::recvmsg(sock, &msg, 0) != static_cast<ssize_t>(sizeof(*message))) return false;
cmsghdr* cmsg = CMSG_FIRSTHDR(&msg);
if (cmsg == nullptr || cmsg->cmsg_type != SCM_RIGHTS) return false;
std::memcpy(fd, CMSG_DATA(cmsg), sizeof(int));
return true;
}
bool WaitForByte(int sock, int timeoutMs) {
pollfd pfd{sock, POLLIN, 0};
char byte = 0;
return ::poll(&pfd, 1, timeoutMs) > 0 && ::read(sock, &byte, 1) == 1;
}
// ---- the clients --------------------------------------------------------------------------
void SetClientEnvironment(const std::string& endpoint, const std::string& logBase, bool serverWindow) {
::setenv("MOBILEGL_LOG_FILE_PATH", logBase.c_str(), 1);
::setenv("MOBILEGL_TRANSPORT", "spawn", 1);
::setenv("MOBILEGL_IPC_CONTROL", endpoint.c_str(), 1);
if (serverWindow) ::setenv("MOBILEGL_IPC_SURFACE", "server", 1);
else ::unsetenv("MOBILEGL_IPC_SURFACE");
::unsetenv("MOBILEGL_BACKEND_TYPE");
::unsetenv("MOBILEGL_DEBUG_INJECT_DEVICE_LOST_AT");
::unsetenv("MOBILEGL_DEBUG_INJECT_DEVICE_LOST_PID");
}
EGLImage ImportImage(EGLDisplay dpy, int fd, const SharedImageMessage& image) {
const EGLAttrib attribs[] = {EGL_WIDTH,
static_cast<EGLAttrib>(image.width),
EGL_HEIGHT,
static_cast<EGLAttrib>(image.height),
EGL_LINUX_DRM_FOURCC_EXT,
static_cast<EGLAttrib>(image.fourcc),
EGL_DMA_BUF_PLANE0_FD_EXT,
fd,
EGL_DMA_BUF_PLANE0_OFFSET_EXT,
static_cast<EGLAttrib>(image.offset),
EGL_DMA_BUF_PLANE0_PITCH_EXT,
static_cast<EGLAttrib>(image.stride),
EGL_NONE};
return EGL::CreateImage(dpy, EGL_NO_CONTEXT, EGL_LINUX_DMA_BUF_EXT, nullptr, attribs);
}
// A new texture with `image` as its level 0 (glEGLImageTargetTexture2DOES); the GL error it raised.
Uint32 BindImageToNewTexture(EGLImage image) {
using TargetFn = void (*)(GLenum, void*);
const auto target = reinterpret_cast<TargetFn>(EGL::GetProcAddress("glEGLImageTargetTexture2DOES"));
if (target == nullptr) return 0xFFFFFFFFu;
while (glGetError() != GL_NO_ERROR) {
}
GLuint texture = 0;
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);
target(GL_TEXTURE_2D, image);
return glGetError();
}
// THE IMAGE'S OWNER (a Wayland client of the compositor): an offscreen session that allocates a
// shared image and hands its descriptor over, then - once the compositor has recovered - checks
// that nothing of the compositor's loss reached it.
struct OwnerReport {
Int32 initialized = 0;
Int32 allocated = 0;
Int32 sent = 0;
Int32 sawDone = 0;
Uint32 statusAfter = 0xFFFFFFFFu;
Uint32 pixelAfter = 0;
Int32 stillIdentified = -1;
Uint64 imageId = 0;
char note[256] = {};
};
void Note(OwnerReport& r, const char* text) {
if (r.note[0] == '\0') std::snprintf(r.note, sizeof(r.note), "%s", text);
}
void RunOwner(int sock, OwnerReport& r) {
const EGLDisplay dpy = EGL::GetDisplay(EGL_DEFAULT_DISPLAY);
EGLint major = 0;
EGLint minor = 0;
if (dpy == EGL_NO_DISPLAY || EGL::Initialize(dpy, &major, &minor) != EGL_TRUE) return Note(r, "no display");
(void)EGL::BindAPI(EGL_OPENGL_API);
const EGLint configAttribs[] = {EGL_SURFACE_TYPE, EGL_PBUFFER_BIT, EGL_NONE};
EGLConfig config = nullptr;
EGLint count = 0;
if (EGL::ChooseConfig(dpy, configAttribs, &config, 1, &count) != EGL_TRUE || count < 1)
return Note(r, "no config");
const EGLint pbufferAttribs[] = {EGL_WIDTH, 8, EGL_HEIGHT, 8, EGL_NONE};
const EGLSurface surface = EGL::CreatePbufferSurface(dpy, config, pbufferAttribs);
const EGLContext context = EGL::CreateContext(dpy, config, EGL_NO_CONTEXT, kRobustAttribs);
if (surface == EGL_NO_SURFACE || context == EGL_NO_CONTEXT ||
EGL::MakeCurrent(dpy, surface, surface, context) != EGL_TRUE)
return Note(r, "the owner's context did not go current");
r.initialized = 1;
auto* backend = MG_Backend::pActiveBackendObject.get();
MG_Backend::SharedImageExport image;
if (backend == nullptr || !backend->AllocateSharedImage(kImageWidth, kImageHeight, kXrgb8888, &image) ||
image.Fd < 0)
return Note(r, "no shared image was allocated");
r.allocated = 1;
r.imageId = image.Id;
// A frame of the client's own first (its session is as busy as a client's is).
(void)ClearAndRead(0.0f, 1.0f, 0.0f);
glFlush();
SharedImageMessage message;
message.width = image.Width;
message.height = image.Height;
message.fourcc = image.Fourcc;
message.stride = image.Stride;
message.offset = image.Offset;
message.id = image.Id;
r.sent = SendFd(sock, image.Fd, message) ? 1 : 0;
if (!r.sent) return Note(r, "the descriptor could not be sent");
r.sawDone = WaitForByte(sock, 60000) ? 1 : 0;
r.statusAfter = glGetGraphicsResetStatus();
r.pixelAfter = ClearAndRead(1.0f, 0.0f, 0.0f);
Uint64 again = 0;
r.stillIdentified =
backend->ImportSharedImage(image.Fd, image.Width, image.Height, image.Fourcc, &again) && again == image.Id
? 1
: 0;
if (again != 0) (void)backend->ReleaseSharedImage(again);
::close(image.Fd);
(void)backend->ReleaseSharedImage(image.Id);
(void)EGL::MakeCurrent(dpy, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
(void)EGL::DestroyContext(dpy, context);
(void)EGL::DestroySurface(dpy, surface);
(void)EGL::Terminate(dpy);
}
// THE COMPOSITOR: KWin's EGL shape on the server's window, its loss and its restart.
struct CompositorReport {
Int32 received = 0;
Int32 surfaceOk = 0;
Int32 width = 0;
Int32 height = 0;
Int32 firstCurrent = 0;
Int32 imported = 0;
Uint64 importedId = 0;
Uint32 firstBindError = 0xFFFFFFFFu;
Uint32 firstPixel = 0;
Int32 firstSwap = -1;
Int32 lossSeen = 0;
Uint32 resetStatus = 0;
Int32 lostSwap = -1;
Int32 lostSwapError = 0;
Int32 newContextOk = 0;
Int32 newCurrentOk = 0;
Int32 newCurrentError = 0;
Int64 rehomeMs = -1;
Uint32 resetStatusNew = 0xFFFFFFFFu;
Int32 widthAfter = 0;
Int32 heightAfter = 0;
Uint32 staleBindError = 0;
Int32 reimported = 0;
Uint64 reimportedId = 0;
Int64 recordsByStaleDestroy = -1;
Uint32 freshBindError = 0xFFFFFFFFu;
Uint32 freshPixel = 0;
Int32 freshSwap = -1;
Uint32 resetStatusEnd = 0xFFFFFFFFu;
char note[256] = {};
};
void Note(CompositorReport& r, const char* text) {
if (r.note[0] == '\0') std::snprintf(r.note, sizeof(r.note), "%s", text);
}
void RunCompositor(int sock, CompositorReport& r) {
int fd = -1;
SharedImageMessage image;
r.received = ReceiveFd(sock, &fd, &image, 30000) ? 1 : 0;
if (!r.received) return Note(r, "no descriptor from the owner");
// AnlandBackend::initialize: the display, an RGBA window config, the server's window.
const EGLDisplay dpy = EGL::GetDisplay(EGL_DEFAULT_DISPLAY);
EGLint major = 0;
EGLint minor = 0;
if (dpy == EGL_NO_DISPLAY || EGL::Initialize(dpy, &major, &minor) != EGL_TRUE) return Note(r, "no display");
const EGLint configAttribs[] = {EGL_SURFACE_TYPE, EGL_WINDOW_BIT, EGL_RENDERABLE_TYPE, EGL_OPENGL_BIT,
EGL_RED_SIZE, 8, EGL_GREEN_SIZE, 8,
EGL_BLUE_SIZE, 8, EGL_ALPHA_SIZE, 8,
EGL_NONE};
EGLConfig config = nullptr;
EGLint count = 0;
if (EGL::ChooseConfig(dpy, configAttribs, &config, 1, &count) != EGL_TRUE || count < 1)
return Note(r, "no window config");
const EGLSurface surface = EGL::CreateWindowSurface(dpy, config, NativeWindowType{}, nullptr);
r.surfaceOk = surface != EGL_NO_SURFACE ? 1 : 0;
if (!r.surfaceOk) return Note(r, "the server's window surface was not created");
(void)EGL::QuerySurface(dpy, surface, EGL_WIDTH, &r.width);
(void)EGL::QuerySurface(dpy, surface, EGL_HEIGHT, &r.height);
// EglBackend::createContext: a global share context, and the compositor's sharing with it.
(void)EGL::BindAPI(EGL_OPENGL_API);
const EGLContext share = EGL::CreateContext(dpy, config, EGL_NO_CONTEXT, kRobustAttribs);
const EGLContext lost = EGL::CreateContext(dpy, config, share, kRobustAttribs);
r.firstCurrent = share != EGL_NO_CONTEXT && lost != EGL_NO_CONTEXT &&
EGL::MakeCurrent(dpy, surface, surface, lost) == EGL_TRUE
? 1
: 0;
if (!r.firstCurrent) return Note(r, "the compositor's context did not go current");
// A client's buffer, imported and bound (the scene's surface texture), and a frame.
const EGLImage stale = ImportImage(dpy, fd, image);
r.imported = stale != EGL_NO_IMAGE ? 1 : 0;
if (!r.imported) return Note(r, "the client's image was not imported");
EGLint ignored = 0;
(void)EGL::LookupSharedImage(stale, &r.importedId, &ignored, &ignored);
r.firstBindError = BindImageToNewTexture(stale);
r.firstPixel = ClearAndRead(0.0f, 1.0f, 0.0f);
r.firstSwap = EGL::SwapBuffers(dpy, surface);
// Compositing until the session is lost (the knob targets this pid).
const auto until = std::chrono::steady_clock::now() + std::chrono::seconds(10);
while (std::chrono::steady_clock::now() < until) {
(void)ClearAndRead(0.0f, 1.0f, 0.0f);
r.lostSwap = EGL::SwapBuffers(dpy, surface);
r.lostSwapError = EGL::GetError();
if (glGetGraphicsResetStatus() != GL_NO_ERROR) {
r.lossSeen = 1;
break;
}
std::this_thread::sleep_for(std::chrono::milliseconds(20));
}
if (!r.lossSeen) return Note(r, "the compositor's session was never lost");
r.resetStatus = glGetGraphicsResetStatus();
// The swap that ran into the loss, if this frame's did not: one more, which must say so.
r.lostSwap = EGL::SwapBuffers(dpy, surface);
r.lostSwapError = EGL::GetError();
// Compositor::reinitialize: the scene and the context go, a new context is created (still
// naming the lost share context) and made current on the surface the compositor kept.
(void)EGL::MakeCurrent(dpy, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
(void)EGL::DestroyContext(dpy, lost);
const auto restart = std::chrono::steady_clock::now();
const EGLContext fresh = EGL::CreateContext(dpy, config, share, kRobustAttribs);
r.newContextOk = fresh != EGL_NO_CONTEXT ? 1 : 0;
if (!r.newContextOk) return Note(r, "no context after the loss");
r.newCurrentOk = EGL::MakeCurrent(dpy, surface, surface, fresh) == EGL_TRUE ? 1 : 0;
r.newCurrentError = EGL::GetError();
r.rehomeMs =
std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - restart).count();
if (!r.newCurrentOk) return Note(r, "the kept surface did not go current on the fresh session");
r.resetStatusNew = glGetGraphicsResetStatus();
(void)EGL::QuerySurface(dpy, surface, EGL_WIDTH, &r.widthAfter);
(void)EGL::QuerySurface(dpy, surface, EGL_HEIGHT, &r.heightAfter);
// The lost session's image names nothing the fresh one holds; the buffer is imported again
// (the same server image, so the same id) - and only then is the stale one destroyed.
r.staleBindError = BindImageToNewTexture(stale);
const EGLImage again = ImportImage(dpy, fd, image);
r.reimported = again != EGL_NO_IMAGE ? 1 : 0;
if (!r.reimported) return Note(r, "the client's image was not imported again");
(void)EGL::LookupSharedImage(again, &r.reimportedId, &ignored, &ignored);
const Uint64 before = PublishedSeq();
(void)EGL::DestroyImage(dpy, stale);
r.recordsByStaleDestroy = static_cast<Int64>(PublishedSeq()) - static_cast<Int64>(before);
r.freshBindError = BindImageToNewTexture(again);
r.freshPixel = ClearAndRead(0.0f, 0.0f, 1.0f);
r.freshSwap = EGL::SwapBuffers(dpy, surface);
r.resetStatusEnd = glGetGraphicsResetStatus();
// The owner looks at its own session now.
const char done = 1;
const ssize_t wrote = ::write(sock, &done, 1);
(void)wrote;
(void)EGL::DestroyImage(dpy, again);
::close(fd);
(void)EGL::MakeCurrent(dpy, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
(void)EGL::DestroyContext(dpy, fresh);
(void)EGL::DestroyContext(dpy, share);
(void)EGL::DestroySurface(dpy, surface);
(void)EGL::Terminate(dpy);
}
// A forked client that waits for the server's endpoint before it does anything (the knob names
// the compositor's pid, so the clients exist before the server starts).
template <class Report>
struct HeldChild {
pid_t pid = -1;
int go = -1;
int report = -1;
template <class Body>
bool Fork(Body body) {
int goFds[2] = {-1, -1};
int reportFds[2] = {-1, -1};
if (::pipe(goFds) != 0 || ::pipe(reportFds) != 0) return false;
std::fflush(nullptr);
pid = ::fork();
if (pid == 0) {
::close(goFds[1]);
::close(reportFds[0]);
char endpoint[512] = {};
const ssize_t got = ::read(goFds[0], endpoint, sizeof(endpoint) - 1);
if (got <= 0) ::_exit(0);
Report r{};
body(std::string(endpoint), r);
const ssize_t wrote = ::write(reportFds[1], &r, sizeof(r));
(void)wrote;
std::fflush(nullptr);
::_exit(0);
}
::close(goFds[0]);
::close(reportFds[1]);
go = goFds[1];
report = reportFds[0];
return pid > 0;
}
void Go(const std::string& endpoint) {
const ssize_t wrote = ::write(go, endpoint.c_str(), endpoint.size());
(void)wrote;
::close(go);
go = -1;
}
Report Wait() {
Report r{};
pollfd pfd{report, POLLIN, 0};
if (::poll(&pfd, 1, 90000) > 0) {
if (::read(report, &r, sizeof(r)) != static_cast<ssize_t>(sizeof(r))) {
r = Report{};
Note(r, "the client died before reporting");
}
} else {
Note(r, "the client timed out");
::kill(pid, SIGKILL);
}
::close(report);
int status = 0;
::waitpid(pid, &status, 0);
return r;
}
~HeldChild() {
if (go >= 0) ::close(go); // a child never released ends itself
}
};
struct ClientLog {
std::string base;
explicit ClientLog(const std::string& label)
: base("/tmp/mgl-comprec-client-" + label + "-" + std::to_string(::getpid()) + ".log") {
Debug::TruncateRoleLogs(base.c_str());
}
std::string Text() const { return ReadFile(Debug::RoleLogPath(base.c_str(), Debug::LogRole::Client)); }
~ClientLog() {
if (::testing::Test::HasFailure() || std::getenv("MOBILEGL_TEST_KEEP_LOGS") != nullptr) return;
std::error_code ec;
std::filesystem::remove(Debug::RoleLogPath(base.c_str(), Debug::LogRole::Client), ec);
std::filesystem::remove(Debug::RoleLogPath(base.c_str(), Debug::LogRole::Server), ec);
std::filesystem::remove(base, ec);
}
};
} // namespace
TEST(CompositorRecovery, ACompositorOnTheServerWindowRecoversOnAFreshSessionAndReimportsItsClientsImages) {
::signal(SIGPIPE, SIG_IGN);
int pair[2] = {-1, -1};
ASSERT_EQ(::socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0, pair), 0);
ClientLog ownerLog("owner");
ClientLog compositorLog("compositor");
HeldChild<OwnerReport> owner;
ASSERT_TRUE(owner.Fork([&](const std::string& endpoint, OwnerReport& r) {
::close(pair[1]);
SetClientEnvironment(endpoint, ownerLog.base, /*serverWindow=*/false);
RunOwner(pair[0], r);
}));
HeldChild<CompositorReport> compositor;
ASSERT_TRUE(compositor.Fork([&](const std::string& endpoint, CompositorReport& r) {
::close(pair[0]);
SetClientEnvironment(endpoint, compositorLog.base, /*serverWindow=*/true);
RunCompositor(pair[1], r);
}));
::close(pair[0]);
::close(pair[1]);
ServerProcess server;
::setenv("MOBILEGL_DEBUG_INJECT_DEVICE_LOST_PID", std::to_string(compositor.pid).c_str(), 1);
const bool launched = LaunchDisplayServer(&server, "kwin");
::unsetenv("MOBILEGL_DEBUG_INJECT_DEVICE_LOST_PID");
ASSERT_TRUE(launched) << server.Log();
owner.Go(server.endpoint);
compositor.Go(server.endpoint);
const CompositorReport c = compositor.Wait();
const OwnerReport o = owner.Wait();
const std::string diagnostics = "server:\n" + server.Log() + "\ncompositor:\n" + compositorLog.Text() +
"\nowner:\n" + ownerLog.Text();
// The compositor, before the loss: the server's window, an imported client image, a frame.
ASSERT_EQ(c.received, 1) << c.note << "\n" << o.note << "\n" << diagnostics;
ASSERT_EQ(c.surfaceOk, 1) << c.note << "\n" << diagnostics;
EXPECT_EQ(c.width, static_cast<Int32>(kWindowWidth));
EXPECT_EQ(c.height, static_cast<Int32>(kWindowHeight));
ASSERT_EQ(c.firstCurrent, 1) << c.note << "\n" << diagnostics;
ASSERT_EQ(c.imported, 1) << c.note << "\n" << diagnostics;
EXPECT_EQ(c.importedId, o.imageId) << "the compositor imported some other image";
EXPECT_EQ(c.firstBindError, static_cast<Uint32>(GL_NO_ERROR)) << std::hex << c.firstBindError;
EXPECT_EQ(c.firstPixel, kGreen) << std::hex << c.firstPixel << "\n" << diagnostics;
EXPECT_EQ(c.firstSwap, EGL_TRUE);
// The loss, reported.
ASSERT_EQ(c.lossSeen, 1) << c.note << "\n" << diagnostics;
EXPECT_EQ(c.resetStatus, static_cast<Uint32>(GL_UNKNOWN_CONTEXT_RESET)) << std::hex << c.resetStatus;
EXPECT_EQ(c.lostSwap, EGL_FALSE);
EXPECT_EQ(c.lostSwapError, EGL_CONTEXT_LOST) << std::hex << c.lostSwapError;
// The restart: a fresh session, the server's window again - after the lost session let go of it.
ASSERT_EQ(c.newContextOk, 1) << c.note << "\n" << diagnostics;
ASSERT_EQ(c.newCurrentOk, 1) << "the kept server-window surface did not go current on the fresh session (EGL "
"error 0x"
<< std::hex << c.newCurrentError << ")\n"
<< c.note << "\n"
<< diagnostics;
EXPECT_EQ(c.resetStatusNew, static_cast<Uint32>(GL_NO_ERROR));
EXPECT_EQ(c.widthAfter, static_cast<Int32>(kWindowWidth));
EXPECT_EQ(c.heightAfter, static_cast<Int32>(kWindowHeight));
// The client's image: the lost session's EGLImage binds nothing any more, the buffer imports
// again as the same image, and destroying the stale EGLImage after that is silent.
EXPECT_EQ(c.staleBindError, static_cast<Uint32>(GL_INVALID_OPERATION))
<< "an EGLImage of the lost session was bound on the fresh one: 0x" << std::hex << c.staleBindError;
ASSERT_EQ(c.reimported, 1) << c.note << "\n" << diagnostics;
EXPECT_EQ(c.reimportedId, o.imageId);
EXPECT_EQ(c.recordsByStaleDestroy, 0) << "destroying the lost session's EGLImage released the fresh import's "
"reference on the new session";
EXPECT_EQ(c.freshBindError, static_cast<Uint32>(GL_NO_ERROR))
<< "the image imported again could not be bound: 0x" << std::hex << c.freshBindError;
EXPECT_EQ(c.freshPixel, kBlue) << std::hex << c.freshPixel << "\n" << diagnostics;
EXPECT_EQ(c.freshSwap, EGL_TRUE);
EXPECT_EQ(c.resetStatusEnd, static_cast<Uint32>(GL_NO_ERROR)) << "the fresh session was lost too";
// The owner: untouched.
ASSERT_EQ(o.initialized, 1) << o.note << "\n" << diagnostics;
ASSERT_EQ(o.allocated, 1) << o.note;
EXPECT_EQ(o.sent, 1);
EXPECT_EQ(o.sawDone, 1) << "the compositor never finished";
EXPECT_EQ(o.statusAfter, static_cast<Uint32>(GL_NO_ERROR)) << "the owner's session was lost with the compositor's";
EXPECT_EQ(o.pixelAfter, kRed) << std::hex << o.pixelAfter;
EXPECT_EQ(o.stillIdentified, 1) << "the owner's image is gone from the server";
// The server's side: the window went to the compositor twice, and only ever at the size the
// compositor asked for (the window's own).
ASSERT_TRUE(WaitFor([&] { return Count(server.Log(), "reaped exit=") == 3; }, 10000)) << server.Log();
const std::string log = server.Log();
EXPECT_EQ(Count(log, "owner=server (ServerOwned"), 2u) << log;
EXPECT_EQ(Count(log, "SessionLatch{"), 1u) << log;
EXPECT_NE(log.find("injected:pid=" + std::to_string(compositor.pid)), std::string::npos) << log;
EXPECT_EQ(log.find("Fatal{ProtocolCorruption"), std::string::npos) << log;
EXPECT_EQ(Count(log, "reaped exit=75"), 1u) << log;
EXPECT_EQ(Count(log, "reaped exit=0"), 2u) << log;
const std::string geometry = ReadFile(server.logBase + ".geometry");
EXPECT_EQ(Count(geometry, "\n"), 2u) << "geometry requests:\n" << geometry;
EXPECT_EQ(Count(geometry, "0 0\n"), Count(geometry, "\n"))
<< "the window was asked for a fixed size - re-creating the surface pinned the window's extent:\n"
<< geometry;
server.Stop();
std::error_code ec;
if (!::testing::Test::HasFailure()) std::filesystem::remove(server.logBase + ".geometry", ec);
}
+342 -72
View File
@@ -13,10 +13,17 @@
// a context and a textured draw of its own colour, and reads it back over and over - through the
// exported EGL and GL entry points, which is where the client serialises its threads.
//
// DISABLED: KNOWN TO FAIL. With six threads, a thread's read-backs come back untouched once another
// thread has released and destroyed its context (both shapes, most runs), and a run sometimes hangs
// until the client is killed. On the phone an unshared thread can also read back nothing from its
// first frame. Run it with --gtest_also_run_disabled_tests while working on that.
// Every shape below has one rule in common: a thread's records apply under ITS context, whatever the
// other threads bind, release or destroy meanwhile. The shapes differ in what the other threads do:
// - each thread destroys its context when it is done (shared root, and one group per thread);
// - threads release and re-bind in the middle of their run and release without destroying at
// the end (the destroy comes after every thread has joined);
// - siblings of one share group with no root: the group's first context is destroyed while the
// others still draw with objects of the group;
// - a context destroyed by ANOTHER thread while it is current (EGL defers the destroy until it
// is released: the thread keeps drawing, and the context is gone once released);
// - one thread reading back without pause while others create, draw in, release and destroy
// contexts as fast as they can.
#include "P12ServerRig.h"
@@ -29,6 +36,7 @@ void glClearColor(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha);
void glClear(GLbitfield mask);
void glReadPixels(GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, void* pixels);
void glGenTextures(GLsizei n, GLuint* textures);
void glDeleteTextures(GLsizei n, const GLuint* textures);
void glBindTexture(GLenum target, GLuint texture);
void glActiveTexture(GLenum texture);
void glTexImage2D(GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border,
@@ -59,6 +67,18 @@ namespace {
constexpr int kThreads = 6;
constexpr int kFrames = 40;
// The reader of the read-back race, and the frames it reads.
constexpr int kRaceChurners = 3;
constexpr int kRaceReaderFrames = 300;
enum class Shape : Int32 {
SharedRoot, // every thread shares with one root context, destroys its own when done
Unshared, // one share group per thread, each destroys its own when done
ReleaseOnly, // one group per thread; release + re-bind mid-run, release (no destroy) at the end
Siblings, // one group, no root: the group's first context is destroyed while the rest draw
DestroyWhileCurrent, // another thread destroys a context while it is current (deferred by EGL)
ReadbackRace, // one reader without pause, the rest churn create/draw/release/destroy
};
struct ThreadReport {
Int32 current = 0;
@@ -66,29 +86,73 @@ namespace {
Int32 good = 0;
Int32 bad = 0;
Uint32 firstBad = 0;
Uint32 firstExpected = 0;
Int32 firstBadFrame = -1;
Int32 vertexCompiled = -1;
Int32 fragmentCompiled = -1;
Int32 rebinds = 0; // ReleaseOnly: mid-run release + make-current that succeeded
Int32 cycles = 0; // ReadbackRace churners: contexts created, used and destroyed
Int32 cycleFailures = 0;
// DestroyWhileCurrent: what eglDestroyContext answered on the OTHER thread, and what
// binding the destroyed context again after this thread released it answered.
Int32 destroyAnswer = -1;
Int32 destroyError = 0;
Int32 rebindAnswer = -1;
Int32 rebindError = 0;
Int32 destroyWaited = 0; // the destroy happened while this thread was current
char linkLog[200] = {};
};
struct Report {
Int32 initialized = 0;
Int32 finished = 0;
ThreadReport threads[kThreads];
};
// A<<24|B<<16|G<<8|R of the texel each thread draws.
Uint32 ColourOf(int index) { return 0xFF000000u | (0x40u + 0x50u * static_cast<Uint32>(index)) << 8 | 0x20u; }
Uint32 ColourOf(int index) { return 0xFF000000u | (0x40u + 0x50u * static_cast<Uint32>(index % 3)) << 8 |
(0x20u + 0x30u * static_cast<Uint32>(index / 3)); }
// The clear colour of a churn cycle (ReadbackRace): a different one per thread and cycle.
Uint32 ChurnColourOf(int index, int cycle) {
return 0xFF000000u | (0x10u * static_cast<Uint32>(index)) << 16 | (static_cast<Uint32>(cycle * 7) & 0xFFu) << 8 |
0x80u;
}
void RenderOnThread(EGLDisplay dpy, EGLConfig config, EGLContext share, int index, ThreadReport* out) {
const EGLint pbufferAttribs[] = {EGL_WIDTH, 8, EGL_HEIGHT, 8, EGL_NONE};
const EGLSurface surface = eglCreatePbufferSurface(dpy, config, pbufferAttribs);
const EGLint attribs[] = {EGL_CONTEXT_MAJOR_VERSION, 3, EGL_CONTEXT_MINOR_VERSION, 3, EGL_NONE};
const EGLContext context = eglCreateContext(dpy, config, share, attribs);
if (surface == EGL_NO_SURFACE || context == EGL_NO_CONTEXT ||
eglMakeCurrent(dpy, surface, surface, context) != EGL_TRUE)
return;
out->current = 1;
struct Rig {
EGLDisplay dpy = EGL_NO_DISPLAY;
EGLConfig config = nullptr;
Shape shape = Shape::Unshared;
Report* report = nullptr;
EGLContext share = EGL_NO_CONTEXT; // SharedRoot's root
EGLContext given[kThreads] = {}; // contexts made on the main thread (Siblings)
std::atomic<EGLContext> published[kThreads] = {}; // DestroyWhileCurrent: each thread's own
std::atomic<Int32> halfway[kThreads] = {};
std::atomic<Int32> destroyed[kThreads] = {};
std::atomic<Int32> readerDone{0};
};
const EGLint kContextAttribs[] = {EGL_CONTEXT_MAJOR_VERSION, 3, EGL_CONTEXT_MINOR_VERSION, 3, EGL_NONE};
const EGLint kPbufferAttribs[] = {EGL_WIDTH, 8, EGL_HEIGHT, 8, EGL_NONE};
template <typename Predicate>
bool WaitUntil(Predicate predicate, int timeoutMs) {
const auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(timeoutMs);
while (!predicate()) {
if (std::chrono::steady_clock::now() >= deadline) return false;
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
return true;
}
struct Drawing {
GLuint program = 0;
GLuint vertexArray = 0;
GLuint texture = 0;
Uint32 colour = 0;
};
// The thread's program, vertex array and one-texel texture of its own colour.
Drawing BuildDrawing(int index, ThreadReport* out) {
static const char* kVertex = "#version 330 core\n"
"const vec2 corners[3] = vec2[3](vec2(-1.0, -1.0), vec2(3.0, -1.0), vec2(-1.0, 3.0));\n"
"void main() { gl_Position = vec4(corners[gl_VertexID], 0.0, 1.0); }\n";
@@ -96,60 +160,225 @@ namespace {
"uniform sampler2D image;\n"
"out vec4 color;\n"
"void main() { color = texture(image, vec2(0.5)); }\n";
Drawing drawing;
const GLuint vertex = glCreateShader(GL_VERTEX_SHADER);
const GLuint fragment = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(vertex, 1, &kVertex, nullptr);
glShaderSource(fragment, 1, &kFragment, nullptr);
glCompileShader(vertex);
glCompileShader(fragment);
const GLuint program = glCreateProgram();
glAttachShader(program, vertex);
glAttachShader(program, fragment);
glLinkProgram(program);
drawing.program = glCreateProgram();
glAttachShader(drawing.program, vertex);
glAttachShader(drawing.program, fragment);
glLinkProgram(drawing.program);
GLint linked = 0;
glGetProgramiv(program, GL_LINK_STATUS, &linked);
glGetProgramiv(drawing.program, GL_LINK_STATUS, &linked);
out->linked = linked;
glGetShaderiv(vertex, GL_COMPILE_STATUS, &out->vertexCompiled);
glGetShaderiv(fragment, GL_COMPILE_STATUS, &out->fragmentCompiled);
if (!linked) glGetProgramInfoLog(program, sizeof(out->linkLog) - 1, nullptr, out->linkLog);
GLuint vertexArray = 0;
glGenVertexArrays(1, &vertexArray);
GLuint texture = 0;
glGenTextures(1, &texture);
const Uint32 colour = ColourOf(index);
if (!linked) glGetProgramInfoLog(drawing.program, sizeof(out->linkLog) - 1, nullptr, out->linkLog);
glGenVertexArrays(1, &drawing.vertexArray);
glGenTextures(1, &drawing.texture);
drawing.colour = ColourOf(index);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, texture);
glBindTexture(GL_TEXTURE_2D, drawing.texture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, 1, 1, 0, GL_RGBA, GL_UNSIGNED_BYTE, &colour);
for (int frame = 0; frame < kFrames; ++frame) {
glViewport(0, 0, 8, 8);
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
glClear(GL_COLOR_BUFFER_BIT);
glUseProgram(program);
glUniform1i(glGetUniformLocation(program, "image"), 0);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, texture);
glBindVertexArray(vertexArray);
glDrawArrays(GL_TRIANGLES, 0, 3);
Uint32 pixel = 0x5A5A5A5Au;
glReadPixels(0, 0, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, &pixel);
if (pixel == colour) {
++out->good;
} else {
if (out->bad++ == 0) {
out->firstBad = pixel;
out->firstBadFrame = frame;
}
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, 1, 1, 0, GL_RGBA, GL_UNSIGNED_BYTE, &drawing.colour);
return drawing;
}
void Tally(ThreadReport* out, int frame, Uint32 pixel, Uint32 expected) {
if (pixel == expected) {
++out->good;
return;
}
if (out->bad++ == 0) {
out->firstBad = pixel;
out->firstExpected = expected;
out->firstBadFrame = frame;
}
}
// One frame: clear to transparent black, draw the thread's texel over the whole surface, read
// one pixel back.
void DrawFrame(const Drawing& drawing, int frame, ThreadReport* out) {
glViewport(0, 0, 8, 8);
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
glClear(GL_COLOR_BUFFER_BIT);
glUseProgram(drawing.program);
glUniform1i(glGetUniformLocation(drawing.program, "image"), 0);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, drawing.texture);
glBindVertexArray(drawing.vertexArray);
glDrawArrays(GL_TRIANGLES, 0, 3);
Uint32 pixel = 0x5A5A5A5Au;
glReadPixels(0, 0, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, &pixel);
Tally(out, frame, pixel, drawing.colour);
}
// The frames a thread draws: staggered, so the threads finish (and tear down) one after another
// while the rest are still drawing.
int FramesOf(const Rig& rig, int index) {
if (rig.shape == Shape::Siblings) return index == 0 ? kFrames / 4 : kFrames + 4 * index;
return kFrames + 6 * index;
}
void RenderOnThread(Rig* rig, int index) {
ThreadReport* out = &rig->report->threads[index];
const EGLDisplay dpy = rig->dpy;
const EGLSurface surface = eglCreatePbufferSurface(dpy, rig->config, kPbufferAttribs);
EGLContext context = EGL_NO_CONTEXT;
switch (rig->shape) {
case Shape::SharedRoot: context = eglCreateContext(dpy, rig->config, rig->share, kContextAttribs); break;
case Shape::Siblings: context = rig->given[index]; break;
default: context = eglCreateContext(dpy, rig->config, EGL_NO_CONTEXT, kContextAttribs); break;
}
if (surface == EGL_NO_SURFACE || context == EGL_NO_CONTEXT ||
eglMakeCurrent(dpy, surface, surface, context) != EGL_TRUE) {
if (rig->shape == Shape::DestroyWhileCurrent) rig->published[index].store(EGL_NO_CONTEXT);
rig->halfway[index].store(1);
return;
}
out->current = 1;
rig->published[index].store(context);
const Drawing drawing = BuildDrawing(index, out);
const int frames = FramesOf(*rig, index);
for (int frame = 0; frame < frames; ++frame) {
if (rig->shape == Shape::DestroyWhileCurrent && frame == frames / 2) {
// Halfway: let the main thread destroy this context while it is current here, and
// draw the second half in it all the same.
rig->halfway[index].store(1);
out->destroyWaited = WaitUntil([&] { return rig->destroyed[index].load() != 0; }, 20000) ? 1 : 0;
}
if (rig->shape == Shape::ReleaseOnly && frame > 0 && frame % 8 == 0) {
// Release and bind again in the middle of the run: nothing is destroyed, and this
// thread's state must be just as it was.
if (eglMakeCurrent(dpy, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT) == EGL_TRUE &&
eglMakeCurrent(dpy, surface, surface, context) == EGL_TRUE)
++out->rebinds;
}
DrawFrame(drawing, frame, out);
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
(void)eglMakeCurrent(dpy, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
(void)eglDestroyContext(dpy, context);
switch (rig->shape) {
case Shape::ReleaseOnly:
break; // destroyed by the main thread once every thread has joined
case Shape::DestroyWhileCurrent:
// Released, so the destroy the main thread asked for has happened: the handle is gone.
out->rebindAnswer = eglMakeCurrent(dpy, surface, surface, context);
out->rebindError = eglGetError();
if (out->rebindAnswer == EGL_TRUE) (void)eglMakeCurrent(dpy, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
break;
default:
(void)eglDestroyContext(dpy, context);
break;
}
(void)eglDestroySurface(dpy, surface);
}
Report RunClient(const ServerProcess& server, const std::string& logBase, bool shareRoot) {
// ReadbackRace's reader: one context, no pause between frames, until it has read them all.
void ReadWithoutPause(Rig* rig, int index) {
ThreadReport* out = &rig->report->threads[index];
const EGLSurface surface = eglCreatePbufferSurface(rig->dpy, rig->config, kPbufferAttribs);
const EGLContext context = eglCreateContext(rig->dpy, rig->config, EGL_NO_CONTEXT, kContextAttribs);
if (surface != EGL_NO_SURFACE && context != EGL_NO_CONTEXT &&
eglMakeCurrent(rig->dpy, surface, surface, context) == EGL_TRUE) {
out->current = 1;
const Drawing drawing = BuildDrawing(index, out);
for (int frame = 0; frame < kRaceReaderFrames; ++frame) DrawFrame(drawing, frame, out);
(void)eglMakeCurrent(rig->dpy, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
(void)eglDestroyContext(rig->dpy, context);
}
if (surface != EGL_NO_SURFACE) (void)eglDestroySurface(rig->dpy, surface);
rig->readerDone.store(1);
}
// ReadbackRace's churners: create a context of its own, make it current, give it objects (a
// texture, deleted every other cycle and otherwise left to die with the context, and a vertex
// array), clear and read back, release and destroy it. Until the reader is done.
void ChurnContexts(Rig* rig, int index) {
ThreadReport* out = &rig->report->threads[index];
const EGLSurface surface = eglCreatePbufferSurface(rig->dpy, rig->config, kPbufferAttribs);
if (surface == EGL_NO_SURFACE) return;
out->current = 1;
out->linked = 1;
for (int cycle = 0; rig->readerDone.load() == 0 && cycle < 400; ++cycle) {
const EGLContext context = eglCreateContext(rig->dpy, rig->config, EGL_NO_CONTEXT, kContextAttribs);
if (context == EGL_NO_CONTEXT || eglMakeCurrent(rig->dpy, surface, surface, context) != EGL_TRUE) {
++out->cycleFailures;
if (context != EGL_NO_CONTEXT) (void)eglDestroyContext(rig->dpy, context);
continue;
}
GLuint texture = 0;
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);
const Uint32 texel = ChurnColourOf(index, cycle);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, 1, 1, 0, GL_RGBA, GL_UNSIGNED_BYTE, &texel);
GLuint vertexArray = 0;
glGenVertexArrays(1, &vertexArray);
glBindVertexArray(vertexArray);
const Uint32 colour = ChurnColourOf(index, cycle);
glViewport(0, 0, 8, 8);
glClearColor(static_cast<float>(colour & 0xFFu) / 255.0f, static_cast<float>((colour >> 8) & 0xFFu) / 255.0f,
static_cast<float>((colour >> 16) & 0xFFu) / 255.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
Uint32 pixel = 0x5A5A5A5Au;
glReadPixels(0, 0, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, &pixel);
Tally(out, cycle, pixel, colour);
if (cycle % 2 == 0) glDeleteTextures(1, &texture); // the odd ones die with the context
(void)eglMakeCurrent(rig->dpy, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
(void)eglDestroyContext(rig->dpy, context);
++out->cycles;
}
(void)eglDestroySurface(rig->dpy, surface);
}
void RunShape(Rig& rig) {
std::thread threads[kThreads];
if (rig.shape == Shape::ReadbackRace) {
threads[0] = std::thread(ReadWithoutPause, &rig, 0);
for (int i = 1; i <= kRaceChurners; ++i) threads[i] = std::thread(ChurnContexts, &rig, i);
for (int i = 0; i <= kRaceChurners; ++i) threads[i].join();
return;
}
if (rig.shape == Shape::SharedRoot) {
rig.share = eglCreateContext(rig.dpy, rig.config, EGL_NO_CONTEXT, kContextAttribs);
}
if (rig.shape == Shape::Siblings) {
// The group's first context, and the rest sharing with it; nothing else holds the group.
rig.given[0] = eglCreateContext(rig.dpy, rig.config, EGL_NO_CONTEXT, kContextAttribs);
for (int i = 1; i < kThreads; ++i)
rig.given[i] = eglCreateContext(rig.dpy, rig.config, rig.given[0], kContextAttribs);
}
for (int i = 0; i < kThreads; ++i) threads[i] = std::thread(RenderOnThread, &rig, i);
if (rig.shape == Shape::DestroyWhileCurrent) {
// Each context is destroyed from HERE while its own thread still has it current. EGL
// answers EGL_TRUE and destroys it once that thread releases it.
for (int i = 0; i < kThreads; ++i) {
ThreadReport& t = rig.report->threads[i];
if (WaitUntil([&] { return rig.halfway[i].load() != 0; }, 30000)) {
const EGLContext context = rig.published[i].load();
if (context != EGL_NO_CONTEXT) {
t.destroyAnswer = eglDestroyContext(rig.dpy, context);
t.destroyError = eglGetError();
}
}
rig.destroyed[i].store(1);
}
}
for (auto& thread : threads) thread.join();
if (rig.shape == Shape::ReleaseOnly) {
for (int i = 0; i < kThreads; ++i) {
const EGLContext context = rig.published[i].load();
if (context != EGL_NO_CONTEXT) (void)eglDestroyContext(rig.dpy, context);
}
}
if (rig.share != EGL_NO_CONTEXT) (void)eglDestroyContext(rig.dpy, rig.share);
}
Report RunClient(const ServerProcess& server, const std::string& logBase, Shape shape) {
Report report{};
int fds[2] = {-1, -1};
if (::pipe(fds) != 0) return report;
@@ -162,27 +391,23 @@ namespace {
::setenv("MOBILEGL_IPC_CONTROL", server.endpoint.c_str(), 1);
::unsetenv("MOBILEGL_IPC_SURFACE");
::unsetenv("MOBILEGL_BACKEND_TYPE");
Report r{};
const EGLDisplay dpy = eglGetDisplay(EGL_DEFAULT_DISPLAY);
static Report r{};
static Rig rig;
rig.shape = shape;
rig.report = &r;
rig.dpy = eglGetDisplay(EGL_DEFAULT_DISPLAY);
EGLint major = 0;
EGLint minor = 0;
if (dpy != EGL_NO_DISPLAY && eglInitialize(dpy, &major, &minor) == EGL_TRUE) {
if (rig.dpy != EGL_NO_DISPLAY && eglInitialize(rig.dpy, &major, &minor) == EGL_TRUE) {
(void)eglBindAPI(EGL_OPENGL_API);
const EGLint configAttribs[] = {EGL_SURFACE_TYPE, EGL_PBUFFER_BIT, EGL_NONE};
EGLConfig config = nullptr;
EGLint count = 0;
if (eglChooseConfig(dpy, configAttribs, &config, 1, &count) == EGL_TRUE && count > 0) {
if (eglChooseConfig(rig.dpy, configAttribs, &rig.config, 1, &count) == EGL_TRUE && count > 0) {
r.initialized = 1;
const EGLint attribs[] = {EGL_CONTEXT_MAJOR_VERSION, 3, EGL_CONTEXT_MINOR_VERSION, 3, EGL_NONE};
const EGLContext share =
shareRoot ? eglCreateContext(dpy, config, EGL_NO_CONTEXT, attribs) : EGL_NO_CONTEXT;
std::thread threads[kThreads];
for (int i = 0; i < kThreads; ++i)
threads[i] = std::thread(RenderOnThread, dpy, config, share, i, &r.threads[i]);
for (auto& thread : threads) thread.join();
if (share != EGL_NO_CONTEXT) (void)eglDestroyContext(dpy, share);
RunShape(rig);
r.finished = 1;
}
(void)eglTerminate(dpy);
(void)eglTerminate(rig.dpy);
}
const ssize_t wrote = ::write(fds[1], &r, sizeof(r));
(void)wrote;
@@ -195,10 +420,10 @@ namespace {
return report;
}
pollfd pfd{fds[0], POLLIN, 0};
if (::poll(&pfd, 1, 90000) > 0) {
if (::poll(&pfd, 1, 60000) > 0) {
if (::read(fds[0], &report, sizeof(report)) != static_cast<ssize_t>(sizeof(report))) report = Report{};
} else {
::kill(pid, SIGKILL);
::kill(pid, SIGKILL); // a hang: report.initialized stays 0 and the case says so
}
::close(fds[0]);
int status = 0;
@@ -206,28 +431,73 @@ namespace {
return report;
}
void Check(bool shareRoot) {
const char* NameOf(Shape shape) {
switch (shape) {
case Shape::SharedRoot: return "concurrent-shared";
case Shape::Unshared: return "concurrent-unshared";
case Shape::ReleaseOnly: return "concurrent-release";
case Shape::Siblings: return "concurrent-siblings";
case Shape::DestroyWhileCurrent: return "concurrent-destroy-current";
case Shape::ReadbackRace: return "concurrent-race";
}
return "concurrent";
}
void Check(Shape shape) {
::signal(SIGPIPE, SIG_IGN);
ServerProcess server;
const std::string label = shareRoot ? "concurrent-shared" : "concurrent-unshared";
const std::string label = NameOf(shape);
ASSERT_TRUE(LaunchUnixInProcessServer(&server, label)) << server.Log();
const std::string logBase = "/tmp/mgl-" + label + "-client-" + std::to_string(::getpid()) + ".log";
Debug::TruncateRoleLogs(logBase.c_str());
const Report r = RunClient(server, logBase, shareRoot);
ASSERT_EQ(r.initialized, 1) << server.Log();
for (int i = 0; i < kThreads; ++i) {
const Report r = RunClient(server, logBase, shape);
ASSERT_EQ(r.initialized, 1) << "the client hung or did not come up; client log " << logBase << "\n"
<< server.Log();
ASSERT_EQ(r.finished, 1) << "the client did not finish";
// Every record named something its own context's share group holds. The default
// framebuffer's placeholder textures were the standing exception: one process-wide set,
// recorded in the group bound when they were born and named by every context's draw.
const std::string serverLog = server.Log();
EXPECT_EQ(serverLog.find("has no applier resource record"), std::string::npos)
<< "a record named a texture its share group holds no record for";
const int threads = shape == Shape::ReadbackRace ? 1 + kRaceChurners : kThreads;
for (int i = 0; i < threads; ++i) {
const ThreadReport& t = r.threads[i];
if (t.current == 0) GTEST_SKIP() << "a context did not go current (no headless EGL here?)";
EXPECT_EQ(t.linked, 1) << "thread " << i << " (compiled " << t.vertexCompiled << "/" << t.fragmentCompiled
<< "): " << t.linkLog;
EXPECT_EQ(t.bad, 0) << "thread " << i << " read back 0x" << std::hex << t.firstBad << " for 0x"
<< ColourOf(i) << std::dec << " first at frame " << t.firstBadFrame << " ("
<< t.firstExpected << std::dec << " first at frame " << t.firstBadFrame << " ("
<< t.good << " frames right)";
EXPECT_GT(t.good, 0) << "thread " << i;
if (shape == Shape::ReleaseOnly) EXPECT_GT(t.rebinds, 0) << "thread " << i;
if (shape == Shape::DestroyWhileCurrent) {
EXPECT_EQ(t.destroyWaited, 1) << "thread " << i;
EXPECT_EQ(t.destroyAnswer, EGL_TRUE)
<< "thread " << i << ": eglDestroyContext of a context current on another thread is deferred, "
<< "not refused (error 0x" << std::hex << t.destroyError << ")";
EXPECT_EQ(t.rebindAnswer, EGL_FALSE) << "thread " << i << ": the context outlived its release";
EXPECT_EQ(t.rebindError, EGL_BAD_CONTEXT) << "thread " << i;
}
if (shape == Shape::ReadbackRace && i > 0) {
EXPECT_GT(t.cycles, 3) << "churner " << i;
EXPECT_EQ(t.cycleFailures, 0) << "churner " << i;
}
}
}
} // namespace
TEST(ConcurrentContexts, DISABLED_ThreadsSharingOneRootContextEachDrawTheirOwnTexture) { Check(true); }
TEST(ConcurrentContexts, ThreadsSharingOneRootContextEachDrawTheirOwnTexture) { Check(Shape::SharedRoot); }
TEST(ConcurrentContexts, DISABLED_ThreadsInSeparateShareGroupsEachDrawTheirOwnTexture) { Check(false); }
TEST(ConcurrentContexts, ThreadsInSeparateShareGroupsEachDrawTheirOwnTexture) { Check(Shape::Unshared); }
TEST(ConcurrentContexts, ReleasingWithoutDestroyingLeavesTheOtherThreadsDrawing) { Check(Shape::ReleaseOnly); }
TEST(ConcurrentContexts, ShareGroupSiblingsOutliveTheGroupsFirstContext) { Check(Shape::Siblings); }
TEST(ConcurrentContexts, DestroyingAContextCurrentOnAnotherThreadIsDeferredUntilItsRelease) {
Check(Shape::DestroyWhileCurrent);
}
TEST(ConcurrentContexts, AReadBackRacingOtherThreadsContextTeardownsIsNotLost) { Check(Shape::ReadbackRace); }
@@ -0,0 +1,465 @@
// MobileGL - MobileGL/MG_Test/Wire/GlamorEglSequenceTest.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
// XWAYLAND'S GLAMOR AGAINST MOBILEGL'S EGL, END TO END ON THE HOST: a real MobileGL client against
// a real `--serve` supervisor, through what xwl_glamor_gbm_init_egl and glamor_init (Xwayland
// 24.1) require before they take the GPU path:
//
// client extension EGL_MESA_platform_gbm (or _KHR_), eglGetPlatformDisplay(GBM, gbm_device),
// eglInitialize, eglBindAPI(EGL_OPENGL_API), eglCreateContext(EGL_NO_CONFIG_KHR, core 3.1),
// surfaceless eglMakeCurrent, GL_RENDERER not llvmpipe/softpipe, desktop GL >= 2.1, no
// GL_ARB_compatibility (core), GL_ARB_vertex_array_object, GL_OES_EGL_image,
// EGL_EXT_image_dma_buf_import + _modifiers (dmabuf_capable), XRGB8888/ARGB8888 importable,
// eglCreateImageKHR(EGL_LINUX_DMA_BUF_EXT) of a shared image's descriptor.
//
// And the implicit-sync flush (docs/Disaggregated/notes/anland/plan-x11-gpu.md): the shared_image
// Flush verb the client sends from glFlush is answered by the server.
//
// Chrome's GPU process on the same kind of display (a GBM one) is the other dma-buf producer, and it
// never flushes: when the compositor's kernel takes dma-buf fences it ends each frame by creating an
// EGL_ANDROID_native_fence_sync fence (through ANGLE, which offers fences only when the native EGL
// has EGL_KHR_fence_sync and the extension, and loads the KHR entry points by name) and hands its
// descriptor to the browser with the buffer. That fence is the only point at which the frame's
// writes into the buffer can reach the compositor's session, so it must be a real one.
#include "P12ServerRig.h"
#include <MG_Backend/BackendObjects.h>
#include <MG_Impl/EGLImpl/EGLImpl.h>
using namespace MobileGL;
using namespace P12;
namespace {
namespace EGL = MobileGL::MG_Impl::EGLImpl;
constexpr EGLenum kPlatformGbm = 0x31D7;
constexpr unsigned kGlRenderer = 0x1F01;
constexpr unsigned kGlVersion = 0x1F02;
constexpr unsigned kGlExtensions = 0x1F03;
constexpr unsigned kGlNumExtensions = 0x821D;
constexpr Uint32 kXrgb8888 = 0x34325258u;
constexpr Uint32 kArgb8888 = 0x34325241u;
struct GlamorReport {
Int32 platformGbmExtension = 0;
Int32 display = 0;
Int32 initialized = 0;
Int32 noConfigCoreContext = 0;
Int32 surfacelessCurrent = 0;
Int32 dmabufCapable = 0;
Int32 desktopGl = 0;
Int32 glVersion = 0; // epoxy_gl_version(): major * 10 + minor
Int32 rendererNotSoftware = 0;
Int32 coreProfile = 0; // no GL_ARB_compatibility
Int32 vertexArrayObject = 0;
Int32 oesEglImage = 0;
Int32 xrgbImportable = 0;
Int32 argbImportable = 0;
Int32 imageCreated = 0;
Int32 flushAnswered = 0;
Int32 flushAgainAnswered = 0;
Int32 eglError = 0;
char renderer[128] = {};
char note[128] = {};
};
bool HasToken(const char* list, const char* token) {
if (list == nullptr) return false;
const std::string all = std::string(" ") + list + " ";
return all.find(std::string(" ") + token + " ") != std::string::npos;
}
// epoxy_has_gl_extension on a core context: glGetStringi.
bool HasGlExtension(const char* name) {
using GetIntegervFn = void (*)(unsigned, int*);
using GetStringiFn = const unsigned char* (*)(unsigned, unsigned);
const auto getIntegerv = reinterpret_cast<GetIntegervFn>(EGL::GetProcAddress("glGetIntegerv"));
const auto getStringi = reinterpret_cast<GetStringiFn>(EGL::GetProcAddress("glGetStringi"));
if (getIntegerv == nullptr || getStringi == nullptr) return false;
int count = 0;
getIntegerv(kGlNumExtensions, &count);
for (int i = 0; i < count; ++i) {
const unsigned char* ext = getStringi(kGlExtensions, static_cast<unsigned>(i));
if (ext != nullptr && std::strcmp(reinterpret_cast<const char*>(ext), name) == 0) return true;
}
return false;
}
void RunGlamor(GlamorReport& r) {
r.platformGbmExtension = HasToken(EGL::QueryString(EGL_NO_DISPLAY, EGL_EXTENSIONS), "EGL_MESA_platform_gbm") ||
HasToken(EGL::QueryString(EGL_NO_DISPLAY, EGL_EXTENSIONS), "EGL_KHR_platform_gbm")
? 1
: 0;
// Any gbm_device* will do: this process has no GBM loader to ask its backend's name, and the
// display's frames come from the server, never from the device.
static int fakeGbmDevice[16] = {};
const EGLDisplay dpy = EGL::GetPlatformDisplay(kPlatformGbm, fakeGbmDevice, nullptr);
r.display = dpy != EGL_NO_DISPLAY ? 1 : 0;
if (!r.display) return;
EGLint major = 0, minor = 0;
r.initialized = EGL::Initialize(dpy, &major, &minor) == EGL_TRUE ? 1 : 0;
if (!r.initialized) return;
const char* exts = EGL::QueryString(dpy, EGL_EXTENSIONS);
r.dmabufCapable =
HasToken(exts, "EGL_EXT_image_dma_buf_import") && HasToken(exts, "EGL_EXT_image_dma_buf_import_modifiers");
(void)EGL::BindAPI(EGL_OPENGL_API);
const EGLint core31[] = {EGL_CONTEXT_OPENGL_PROFILE_MASK, EGL_CONTEXT_OPENGL_CORE_PROFILE_BIT,
EGL_CONTEXT_MAJOR_VERSION, 3, EGL_CONTEXT_MINOR_VERSION, 1, EGL_NONE};
const EGLContext ctx = EGL::CreateContext(dpy, EGL_NO_CONFIG_KHR, EGL_NO_CONTEXT, core31);
r.noConfigCoreContext = ctx != EGL_NO_CONTEXT ? 1 : 0;
if (!r.noConfigCoreContext) {
r.eglError = EGL::GetError();
return;
}
r.surfacelessCurrent = EGL::MakeCurrent(dpy, EGL_NO_SURFACE, EGL_NO_SURFACE, ctx) == EGL_TRUE ? 1 : 0;
if (!r.surfacelessCurrent) {
r.eglError = EGL::GetError();
return;
}
using GetStringFn = const unsigned char* (*)(unsigned);
const auto getString = reinterpret_cast<GetStringFn>(EGL::GetProcAddress("glGetString"));
const char* renderer = getString ? reinterpret_cast<const char*>(getString(kGlRenderer)) : nullptr;
const char* version = getString ? reinterpret_cast<const char*>(getString(kGlVersion)) : nullptr;
std::snprintf(r.renderer, sizeof(r.renderer), "%s", renderer ? renderer : "");
// xwl_glamor_gbm_init_egl's refusals.
r.rendererNotSoftware = renderer != nullptr && std::strncmp(renderer, "llvmpipe", 8) != 0 &&
std::strstr(renderer, "softpipe") == nullptr;
// epoxy_is_desktop_gl / epoxy_gl_version.
if (version != nullptr) {
r.desktopGl = std::strncmp(version, "OpenGL ES", 9) != 0;
int vmaj = 0, vmin = 0;
if (std::sscanf(version, "%d.%d", &vmaj, &vmin) == 2) r.glVersion = vmaj * 10 + vmin;
}
r.coreProfile = !HasGlExtension("GL_ARB_compatibility");
r.vertexArrayObject = HasGlExtension("GL_ARB_vertex_array_object") || HasGlExtension("GL_OES_vertex_array_object");
r.oesEglImage = HasGlExtension("GL_OES_EGL_image");
EGLint formats[16] = {};
EGLint count = 0;
if (EGL::QueryDmaBufFormats(dpy, 16, formats, &count)) {
for (EGLint i = 0; i < count; ++i) {
r.xrgbImportable |= static_cast<Uint32>(formats[i]) == kXrgb8888;
r.argbImportable |= static_cast<Uint32>(formats[i]) == kArgb8888;
}
}
// A window pixmap: a shared image (what gbm_bo_create gives glamor), bound through
// EGL_LINUX_DMA_BUF_EXT the way xwl_glamor_gbm_create_pixmap_for_bo does.
auto* backend = MG_Backend::pActiveBackendObject.get();
MG_Backend::SharedImageExport image;
if (backend != nullptr && backend->AllocateSharedImage(64, 32, kXrgb8888, &image) && image.Fd >= 0) {
const EGLAttrib attribs[] = {EGL_WIDTH, 64, EGL_HEIGHT, 32, EGL_LINUX_DRM_FOURCC_EXT, kXrgb8888,
EGL_DMA_BUF_PLANE0_FD_EXT, image.Fd, EGL_DMA_BUF_PLANE0_OFFSET_EXT,
static_cast<EGLAttrib>(image.Offset), EGL_DMA_BUF_PLANE0_PITCH_EXT,
static_cast<EGLAttrib>(image.Stride), EGL_NONE};
const EGLImage eglImage = EGL::CreateImage(dpy, EGL_NO_CONTEXT, EGL_LINUX_DMA_BUF_EXT, nullptr, attribs);
r.imageCreated = eglImage != EGL_NO_IMAGE ? 1 : 0;
if (eglImage != EGL_NO_IMAGE) (void)EGL::DestroyImage(dpy, eglImage);
::close(image.Fd);
(void)backend->ReleaseSharedImage(image.Id);
}
// glamor's block handler: glFlush, which in an X server is where its renders become visible
// to the compositor. The verb must be answered (an unknown verb is refused).
using ClearFn = void (*)(unsigned);
if (const auto clear = reinterpret_cast<ClearFn>(EGL::GetProcAddress("glClear"))) clear(0x4000);
r.flushAnswered = backend != nullptr && backend->FlushSharedImageAccesses() ? 1 : 0;
// Nothing reached the stream since: no round trip, still a success.
r.flushAgainAnswered = backend != nullptr && backend->FlushSharedImageAccesses() ? 1 : 0;
(void)EGL::MakeCurrent(dpy, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
(void)EGL::DestroyContext(dpy, ctx);
(void)EGL::Terminate(dpy);
}
struct ChromeFenceReport {
Int32 initialized = 0;
Int32 fenceSyncExtension = 0;
Int32 waitSyncExtension = 0;
Int32 nativeFenceExtension = 0;
Int32 entryPoints = 0;
Int32 current = 0;
Int32 imageBound = 0;
Int32 framebufferComplete = 0;
Int32 noContextRefused = 0;
Int32 fenceCreated = 0;
Int32 fenceType = 0;
Int32 fenceWaited = 0;
Int32 fenceSignaled = 0;
Int32 dupFd = -2;
Int32 dupError = 0;
Int32 dupSignaled = 0;
Int32 importCreated = 0;
Int32 importWaited = 0;
Int32 eglError = 0;
char note[128] = {};
};
// ANGLE's FunctionsEGL and Chrome's GLFenceAndroidNativeFenceSync / GbmSurfacelessWayland,
// reduced to the calls they make on the native EGL.
void RunChromeGpuFence(ChromeFenceReport& r) {
using CreateSyncFn = EGLSyncKHR (*)(EGLDisplay, EGLenum, const EGLint*);
using DestroySyncFn = EGLBoolean (*)(EGLDisplay, EGLSyncKHR);
using ClientWaitFn = EGLint (*)(EGLDisplay, EGLSyncKHR, EGLint, EGLTimeKHR);
using GetSyncAttribFn = EGLBoolean (*)(EGLDisplay, EGLSyncKHR, EGLint, EGLint*);
using WaitSyncFn = EGLint (*)(EGLDisplay, EGLSyncKHR, EGLint);
using DupFn = EGLint (*)(EGLDisplay, EGLSyncKHR);
static int fakeGbmDevice[16] = {};
const EGLDisplay dpy = EGL::GetPlatformDisplay(kPlatformGbm, fakeGbmDevice, nullptr);
if (dpy == EGL_NO_DISPLAY) return;
EGLint major = 0, minor = 0;
r.initialized = EGL::Initialize(dpy, &major, &minor) == EGL_TRUE ? 1 : 0;
if (!r.initialized) return;
const char* exts = EGL::QueryString(dpy, EGL_EXTENSIONS);
r.fenceSyncExtension = HasToken(exts, "EGL_KHR_fence_sync") ? 1 : 0;
r.waitSyncExtension = HasToken(exts, "EGL_KHR_wait_sync") ? 1 : 0;
r.nativeFenceExtension = HasToken(exts, "EGL_ANDROID_native_fence_sync") ? 1 : 0;
const auto createSync = reinterpret_cast<CreateSyncFn>(EGL::GetProcAddress("eglCreateSyncKHR"));
const auto destroySync = reinterpret_cast<DestroySyncFn>(EGL::GetProcAddress("eglDestroySyncKHR"));
const auto clientWait = reinterpret_cast<ClientWaitFn>(EGL::GetProcAddress("eglClientWaitSyncKHR"));
const auto getSyncAttrib = reinterpret_cast<GetSyncAttribFn>(EGL::GetProcAddress("eglGetSyncAttribKHR"));
const auto waitSync = reinterpret_cast<WaitSyncFn>(EGL::GetProcAddress("eglWaitSyncKHR"));
const auto dupFence = reinterpret_cast<DupFn>(EGL::GetProcAddress("eglDupNativeFenceFDANDROID"));
r.entryPoints = createSync && destroySync && clientWait && getSyncAttrib && waitSync && dupFence ? 1 : 0;
if (!r.entryPoints) return;
// A fence command needs a current context.
r.noContextRefused = createSync(dpy, EGL_SYNC_NATIVE_FENCE_ANDROID, nullptr) == EGL_NO_SYNC_KHR &&
EGL::GetError() == EGL_BAD_MATCH
? 1
: 0;
// Chrome's GPU process: ES through ANGLE's identity, surfaceless, no config.
(void)EGL::BindAPI(EGL_OPENGL_ES_API);
const EGLint es3[] = {EGL_CONTEXT_MAJOR_VERSION, 3, EGL_NONE};
const EGLContext ctx = EGL::CreateContext(dpy, EGL_NO_CONFIG_KHR, EGL_NO_CONTEXT, es3);
if (ctx == EGL_NO_CONTEXT) {
r.eglError = EGL::GetError();
return;
}
r.current = EGL::MakeCurrent(dpy, EGL_NO_SURFACE, EGL_NO_SURFACE, ctx) == EGL_TRUE ? 1 : 0;
if (!r.current) {
r.eglError = EGL::GetError();
return;
}
// A GBM scanout buffer (a shared image), bound as a texture and rendered into through a
// framebuffer - and then no glFlush, as Chrome does when it has native fences.
auto* backend = MG_Backend::pActiveBackendObject.get();
MG_Backend::SharedImageExport image;
EGLImage eglImage = EGL_NO_IMAGE;
using GenFn = void (*)(int, unsigned*);
using BindFn = void (*)(unsigned, unsigned);
using ImageTargetFn = void (*)(unsigned, void*);
using FbTexFn = void (*)(unsigned, unsigned, unsigned, unsigned, int);
using StatusFn = unsigned (*)(unsigned);
using ClearColorFn = void (*)(float, float, float, float);
using ClearFn = void (*)(unsigned);
const auto genTextures = reinterpret_cast<GenFn>(EGL::GetProcAddress("glGenTextures"));
const auto bindTexture = reinterpret_cast<BindFn>(EGL::GetProcAddress("glBindTexture"));
const auto imageTarget = reinterpret_cast<ImageTargetFn>(EGL::GetProcAddress("glEGLImageTargetTexture2DOES"));
const auto genFramebuffers = reinterpret_cast<GenFn>(EGL::GetProcAddress("glGenFramebuffers"));
const auto bindFramebuffer = reinterpret_cast<BindFn>(EGL::GetProcAddress("glBindFramebuffer"));
const auto framebufferTexture = reinterpret_cast<FbTexFn>(EGL::GetProcAddress("glFramebufferTexture2D"));
const auto checkStatus = reinterpret_cast<StatusFn>(EGL::GetProcAddress("glCheckFramebufferStatus"));
const auto clearColor = reinterpret_cast<ClearColorFn>(EGL::GetProcAddress("glClearColor"));
const auto clear = reinterpret_cast<ClearFn>(EGL::GetProcAddress("glClear"));
if (backend != nullptr && backend->AllocateSharedImage(64, 32, kArgb8888, &image) && image.Fd >= 0) {
const EGLAttrib attribs[] = {EGL_WIDTH, 64, EGL_HEIGHT, 32, EGL_LINUX_DRM_FOURCC_EXT, kArgb8888,
EGL_DMA_BUF_PLANE0_FD_EXT, image.Fd, EGL_DMA_BUF_PLANE0_OFFSET_EXT,
static_cast<EGLAttrib>(image.Offset), EGL_DMA_BUF_PLANE0_PITCH_EXT,
static_cast<EGLAttrib>(image.Stride), EGL_NONE};
eglImage = EGL::CreateImage(dpy, EGL_NO_CONTEXT, EGL_LINUX_DMA_BUF_EXT, nullptr, attribs);
}
if (eglImage != EGL_NO_IMAGE && genTextures && bindTexture && imageTarget && genFramebuffers &&
bindFramebuffer && framebufferTexture && checkStatus && clearColor && clear) {
unsigned texture = 0, framebuffer = 0;
genTextures(1, &texture);
bindTexture(0x0DE1 /* GL_TEXTURE_2D */, texture);
imageTarget(0x0DE1, eglImage);
r.imageBound = 1;
genFramebuffers(1, &framebuffer);
bindFramebuffer(0x8D40 /* GL_FRAMEBUFFER */, framebuffer);
framebufferTexture(0x8D40, 0x8CE0 /* GL_COLOR_ATTACHMENT0 */, 0x0DE1, texture, 0);
r.framebufferComplete = checkStatus(0x8D40) == 0x8CD5 /* GL_FRAMEBUFFER_COMPLETE */ ? 1 : 0;
clearColor(0.0f, 1.0f, 1.0f, 1.0f);
clear(0x4000);
}
// GLFenceAndroidNativeFenceSync::CreateForGpuFence, then GetGpuFenceHandle.
const EGLSyncKHR fence = createSync(dpy, EGL_SYNC_NATIVE_FENCE_ANDROID, nullptr);
r.fenceCreated = fence != EGL_NO_SYNC_KHR ? 1 : 0;
if (!r.fenceCreated) {
r.eglError = EGL::GetError();
} else {
EGLint value = 0;
if (getSyncAttrib(dpy, fence, EGL_SYNC_TYPE_KHR, &value)) r.fenceType = value;
r.fenceWaited = clientWait(dpy, fence, 0, EGL_FOREVER_KHR) == EGL_CONDITION_SATISFIED_KHR ? 1 : 0;
if (getSyncAttrib(dpy, fence, EGL_SYNC_STATUS_KHR, &value)) r.fenceSignaled = value == EGL_SIGNALED_KHR;
r.dupFd = dupFence(dpy, fence);
r.dupError = r.dupFd < 0 ? EGL::GetError() : EGL_SUCCESS;
if (r.dupFd >= 0) {
pollfd entry{r.dupFd, POLLIN, 0};
r.dupSignaled = ::poll(&entry, 1, 5000) == 1 ? 1 : 0;
// GLFenceAndroidNativeFenceSync::CreateFromGpuFenceHandle + ServerWait: the
// descriptor imported back (the sync takes it) and waited on.
const EGLint importAttribs[] = {EGL_SYNC_NATIVE_FENCE_FD_ANDROID, r.dupFd, EGL_NONE};
const EGLSyncKHR imported = createSync(dpy, EGL_SYNC_NATIVE_FENCE_ANDROID, importAttribs);
r.importCreated = imported != EGL_NO_SYNC_KHR ? 1 : 0;
if (imported != EGL_NO_SYNC_KHR) {
r.importWaited = waitSync(dpy, imported, 0) == EGL_TRUE ? 1 : 0;
(void)destroySync(dpy, imported);
} else {
::close(r.dupFd);
}
}
(void)destroySync(dpy, fence);
}
if (eglImage != EGL_NO_IMAGE) (void)EGL::DestroyImage(dpy, eglImage);
if (image.Fd >= 0) ::close(image.Fd);
if (backend != nullptr && image.Id != 0) (void)backend->ReleaseSharedImage(image.Id);
(void)EGL::MakeCurrent(dpy, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
(void)EGL::DestroyContext(dpy, ctx);
(void)EGL::Terminate(dpy);
}
// The supervisor on an abstract unix socket, as the device's is: shared images travel as
// descriptors on its aux socket, which a TCP endpoint does not have.
bool LaunchUnixSupervisor(ServerProcess* server) {
server->logBase = "/tmp/mgl-p12-glamor-" + std::to_string(::getpid()) + ".log";
::setenv("MOBILEGL_LOG_FILE_PATH", server->logBase.c_str(), 1);
PinHeadlessEgl();
// The listener takes the native address; the client's selector carries the transport prefix.
const std::string address = "@mgl-glamor-test-" + std::to_string(::getpid());
server->endpoint = "unix:" + address;
Debug::TruncateRoleLogs(server->logBase.c_str());
Remote::Server::LaunchedServer launched;
if (Remote::Server::LaunchServerWithArgs(ServerImage(), address, {"--serve"}, &launched) != MOBILEGL_OK)
return false;
server->pid = launched.pid;
return WaitFor([&] { return server->Log().find("listening on") != std::string::npos; }, 10000);
}
// One forked client running `run` against the server, its report back through a pipe.
template <class Report>
Report RunPeer(const ServerProcess& server, const std::string& clientLogBase, void (*run)(Report&)) {
Report report{};
int fds[2] = {-1, -1};
if (::pipe(fds) != 0) return report;
std::fflush(nullptr);
const pid_t pid = ::fork();
if (pid == 0) {
::close(fds[0]);
::setenv("MOBILEGL_LOG_FILE_PATH", clientLogBase.c_str(), 1);
::setenv("MOBILEGL_TRANSPORT", "spawn", 1);
::setenv("MOBILEGL_IPC_CONTROL", server.endpoint.c_str(), 1);
::setenv("MOBILEGL_BACKEND_TYPE", "DirectGLES", 1);
::setenv("MOBILEGL_IPC_SURFACE", "offscreen", 1);
Report r{};
run(r);
const ssize_t wrote = ::write(fds[1], &r, sizeof(r));
(void)wrote;
std::fflush(nullptr);
::_exit(0);
}
::close(fds[1]);
if (pid < 0) {
::close(fds[0]);
return report;
}
pollfd pfd{fds[0], POLLIN, 0};
if (::poll(&pfd, 1, 90000) > 0) {
if (::read(fds[0], &report, sizeof(report)) != static_cast<ssize_t>(sizeof(report))) {
report = Report{};
std::snprintf(report.note, sizeof(report.note), "peer died before reporting");
}
} else {
std::snprintf(report.note, sizeof(report.note), "peer timed out");
::kill(pid, SIGKILL);
}
::close(fds[0]);
int status = 0;
::waitpid(pid, &status, 0);
return report;
}
} // namespace
TEST(GlamorEglSequence, XwaylandFindsEverythingGlamorNeeds) {
ServerProcess server;
ASSERT_TRUE(LaunchUnixSupervisor(&server)) << server.Log();
const std::string clientLog = "/tmp/mgl-glamor-client-" + std::to_string(::getpid()) + ".log";
Debug::TruncateRoleLogs(clientLog.c_str());
const GlamorReport r = RunPeer<GlamorReport>(server, clientLog, RunGlamor);
ASSERT_EQ(r.display, 1) << r.note;
EXPECT_EQ(r.platformGbmExtension, 1);
ASSERT_EQ(r.initialized, 1);
EXPECT_EQ(r.dmabufCapable, 1) << "glamor would not be dmabuf_capable: no linux-dmabuf window buffers";
ASSERT_EQ(r.noConfigCoreContext, 1) << "eglCreateContext(EGL_NO_CONFIG_KHR) error 0x" << std::hex << r.eglError;
ASSERT_EQ(r.surfacelessCurrent, 1) << "surfaceless eglMakeCurrent error 0x" << std::hex << r.eglError;
std::printf("[ glamor ] renderer='%s' GL %d.%d\n", r.renderer, r.glVersion / 10, r.glVersion % 10);
EXPECT_EQ(r.rendererNotSoftware, 1) << r.renderer;
EXPECT_EQ(r.desktopGl, 1);
EXPECT_GE(r.glVersion, 21);
EXPECT_EQ(r.coreProfile, 1);
EXPECT_EQ(r.vertexArrayObject, 1);
EXPECT_EQ(r.oesEglImage, 1);
EXPECT_EQ(r.xrgbImportable, 1);
EXPECT_EQ(r.argbImportable, 1);
EXPECT_EQ(r.imageCreated, 1) << "a shared image's descriptor did not import as an EGLImage";
EXPECT_EQ(r.flushAnswered, 1) << "the shared_image Flush verb was not answered";
EXPECT_EQ(r.flushAgainAnswered, 1);
std::error_code ec;
if (!::testing::Test::HasFailure()) {
std::filesystem::remove(Debug::RoleLogPath(clientLog.c_str(), Debug::LogRole::Client), ec);
std::filesystem::remove(Debug::RoleLogPath(clientLog.c_str(), Debug::LogRole::Server), ec);
std::filesystem::remove(clientLog, ec);
}
}
TEST(GlamorEglSequence, ChromesGpuProcessGetsANativeFenceOfItsDmaBufWrites) {
ServerProcess server;
ASSERT_TRUE(LaunchUnixSupervisor(&server)) << server.Log();
const std::string clientLog = "/tmp/mgl-chrome-fence-client-" + std::to_string(::getpid()) + ".log";
Debug::TruncateRoleLogs(clientLog.c_str());
const ChromeFenceReport r = RunPeer<ChromeFenceReport>(server, clientLog, RunChromeGpuFence);
ASSERT_EQ(r.initialized, 1) << r.note;
// ANGLE offers Chrome fences only with all three, and loads the KHR names.
EXPECT_EQ(r.fenceSyncExtension, 1);
EXPECT_EQ(r.waitSyncExtension, 1);
EXPECT_EQ(r.nativeFenceExtension, 1);
ASSERT_EQ(r.entryPoints, 1) << "eglCreateSyncKHR & co. or eglDupNativeFenceFDANDROID did not resolve";
EXPECT_EQ(r.noContextRefused, 1);
ASSERT_EQ(r.current, 1) << "error 0x" << std::hex << r.eglError;
std::printf("[ chrome ] image bound %d, framebuffer complete %d, fence descriptor %d (error 0x%x)\n",
r.imageBound, r.framebufferComplete, r.dupFd, r.dupError);
// The fence command reaches the server, which publishes the context's image writes and answers.
ASSERT_EQ(r.fenceCreated, 1) << "the native fence was refused, error 0x" << std::hex << r.eglError;
EXPECT_EQ(r.fenceType, EGL_SYNC_NATIVE_FENCE_ANDROID);
EXPECT_EQ(r.fenceWaited, 1);
EXPECT_EQ(r.fenceSignaled, 1);
if (r.dupFd >= 0) {
// A sync_file of the work, which signals; imported back it is waited on.
EXPECT_EQ(r.dupSignaled, 1);
EXPECT_EQ(r.importCreated, 1);
EXPECT_EQ(r.importWaited, 1);
} else {
// A server that cannot export fences (a host driver without them) waits the work out and
// has no descriptor: the copy is refused by name, not answered with garbage.
EXPECT_EQ(r.dupError, EGL_BAD_PARAMETER);
}
std::error_code ec;
if (!::testing::Test::HasFailure()) {
std::filesystem::remove(Debug::RoleLogPath(clientLog.c_str(), Debug::LogRole::Client), ec);
std::filesystem::remove(Debug::RoleLogPath(clientLog.c_str(), Debug::LogRole::Server), ec);
std::filesystem::remove(clientLog, ec);
}
}
@@ -395,6 +395,90 @@ TEST(ServerDisplayTest, AWindowLeasedToOneHolderIsNotLeasedToAnother) {
display.EndLease(&first);
}
// A LEASE WHOSE SESSION IS ENDING IS WAITED FOR. A compositor whose session was lost re-creates its
// window surface on a fresh session at once, while the lost session's apply thread is still tearing
// its backend down: the fresh session's request waits for that lease to end and then gets the window,
// where it used to be refused (LeasedElsewhere) - and the compositor could never draw again. Red with
// AcquireFor ignoring the mark: the second holder is refused at once.
TEST(ServerDisplayTest, ALeaseWhoseSessionIsEndingIsWaitedForAndThenHandedOver) {
FakePlatform platform;
ServerDisplay display;
display.Install(HooksFor(platform));
display.Attach(FakeWindow(0), 64, 48);
int lost = 0;
int fresh = 0;
ServerWindowLease lease;
ASSERT_EQ(display.AcquireFor(0, 0, 1000, &lost, nullptr, nullptr, nullptr, &lease), ServerWindowAcquire::Acquired);
display.MarkLeaseEnding(&lost);
EXPECT_TRUE(display.LeaseEnding());
std::thread teardown([&] {
// The lost session's backend lets go of the window, then its lease ends.
std::this_thread::sleep_for(std::chrono::milliseconds(300));
display.EndLease(&lost);
});
const auto started = std::chrono::steady_clock::now();
ServerWindowLease freshLease;
EXPECT_EQ(display.AcquireFor(0, 0, 5000, &fresh, nullptr, nullptr, nullptr, &freshLease),
ServerWindowAcquire::Acquired);
const auto waited =
std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - started).count();
teardown.join();
EXPECT_GE(waited, 250) << "the window was handed over before the ending lease ended";
EXPECT_EQ(freshLease.window, FakeWindow(0));
EXPECT_EQ(freshLease.width, 64u);
EXPECT_EQ(freshLease.height, 48u);
EXPECT_TRUE(display.Leased());
EXPECT_FALSE(display.LeaseEnding()) << "the new holder's lease inherited the old one's mark";
// The new lease is exclusive again: a third holder is refused at once.
int third = 0;
const auto refusedAt = std::chrono::steady_clock::now();
EXPECT_EQ(display.AcquireFor(0, 0, 2000, &third, nullptr, nullptr, nullptr, &lease),
ServerWindowAcquire::LeasedElsewhere);
EXPECT_LT(std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - refusedAt)
.count(),
500);
display.EndLease(&fresh);
EXPECT_EQ(platform.releases.load(), 0) << "a lease that changed hands released the window";
}
// The wait for an ending lease is bounded by the request's own timeout and then refused by name; a
// mark from a holder that holds no lease changes nothing; the mark goes with the lease it was on.
TEST(ServerDisplayTest, AnEndingLeaseIsWaitedForOnlyAsLongAsTheRequestWaitsAndTheMarkGoesWithIt) {
FakePlatform platform;
ServerDisplay display;
display.Install(HooksFor(platform));
display.Attach(FakeWindow(0), 10, 10);
int first = 0;
int second = 0;
ServerWindowLease lease;
ASSERT_EQ(display.AcquireFor(0, 0, 1000, &first, nullptr, nullptr, nullptr, &lease), ServerWindowAcquire::Acquired);
display.MarkLeaseEnding(&second);
EXPECT_FALSE(display.LeaseEnding()) << "a holder without the lease marked it ending";
display.MarkLeaseEnding(&first);
const auto started = std::chrono::steady_clock::now();
EXPECT_EQ(display.AcquireFor(0, 0, 200, &second, nullptr, nullptr, nullptr, &lease),
ServerWindowAcquire::LeasedElsewhere);
EXPECT_GE(std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - started)
.count(),
150)
<< "the ending lease was not waited for";
display.EndLease(&first);
EXPECT_FALSE(display.Leased());
EXPECT_FALSE(display.LeaseEnding());
ASSERT_EQ(display.AcquireFor(0, 0, 1000, &first, nullptr, nullptr, nullptr, &lease), ServerWindowAcquire::Acquired);
EXPECT_FALSE(display.LeaseEnding()) << "the mark outlived the lease it was on";
const auto refusedAt = std::chrono::steady_clock::now();
EXPECT_EQ(display.AcquireFor(0, 0, 2000, &second, nullptr, nullptr, nullptr, &lease),
ServerWindowAcquire::LeasedElsewhere);
EXPECT_LT(std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - refusedAt)
.count(),
500);
display.EndLease(&first);
}
// The two ways a wait ends early, by name: the in-process server stopping (Interrupt), and the
// caller's own cancel predicate (ServerLoop's: the loop stopping, the session latched).
TEST(ServerDisplayTest, InterruptAndTheCancelPredicateEndAWaitByName) {
+66
View File
@@ -3335,6 +3335,72 @@ TEST(ServerLoopLatchTest, ALostServerWindowIsReleasedOnTheApplyThreadBeforeDetac
"latch; 16 = ServerWindowsLost() != 1; 32 = the apply thread stayed (64+ = setup)";
}
namespace {
// A SESSION THAT LATCHES WHILE IT HOLDS THE SERVER WINDOW (a compositor's device loss). Its client
// hears of the loss at once and re-creates its window surface on a fresh session, which asks the
// display for the window while the lost session still holds it - its apply thread has the
// backend to tear down first. The latch itself marks the lease ending (before the peer is told),
// so the fresh session's request waits for the lease and gets the window when the session ends.
enum : int {
kEndingNotLeased = 1, // the probe could not take the lease
kEndingNotMarked = 2, // the latch did not mark the lease ending
kEndingRefused = 4, // the fresh holder was refused instead of waiting
kEndingNotHandedOver = 8, // the fresh holder did not get the window once the session ended
kEndingReleased = 16, // the window's reference was released in the hand-over
};
int g_freshServerWindowHolder = 0;
[[noreturn]] void LatchWhileHoldingTheServerWindowAndExit() {
Remote::ArmSessionLatch();
ServerFixture fixture;
if (!fixture.Handshake() || !fixture.StartLoop()) ::_exit(64);
if (!fixture.WaitUntilTrulyParked()) ::_exit(65);
Server::ServerLoop& loop = Server::ServerLoopInstance();
Server::ServerDisplay& display = Server::ServerDisplayInstance();
display.Install(CountingWindowHooks::Hooks());
display.Attach(&g_fakeServerWindow, 64, 48);
ServerWindowProbe probe;
probe.width = 64;
probe.height = 48;
if (loop.RunProbeOnApplyThreadForTesting(&AcquireServerWindowOnTheApplyThread, &probe) != MOBILEGL_OK) ::_exit(66);
int failed = 0;
if (probe.rc != MOBILEGL_OK || probe.lease.window != &g_fakeServerWindow) failed |= kEndingNotLeased;
if (!fixture.WaitUntilTrulyParked()) ::_exit(67);
// The loss, latched by a thread of the session while its apply thread is parked.
(void)Remote::SessionLatch(Remote::MGFatalFamily::BackendDeviceLost,
"MGPipe: Fatal{BackendDeviceLost, \"test\"} - the session's device is lost while it "
"holds the server window");
if (!display.LeaseEnding()) failed |= kEndingNotMarked;
std::atomic<int> fresh{-1};
std::thread freshSession([&] {
Server::ServerWindowLease lease;
fresh.store(static_cast<int>(display.AcquireFor(0, 0, 5000, &g_freshServerWindowHolder, nullptr, nullptr,
nullptr, &lease)));
});
std::this_thread::sleep_for(std::chrono::milliseconds(200));
if (fresh.load() == static_cast<int>(Server::ServerWindowAcquire::LeasedElsewhere)) failed |= kEndingRefused;
// The session ends: its backend goes, then its lease.
fixture.Stop();
freshSession.join();
if (fresh.load() != static_cast<int>(Server::ServerWindowAcquire::Acquired)) failed |= kEndingNotHandedOver;
if (CountingWindowHooks::releases.load() != 0) failed |= kEndingReleased;
display.EndLease(&g_freshServerWindowHolder);
::_exit(failed);
}
} // namespace
// Red with the latch observer not installed (bits 2|4: the fresh session is refused at once, and a
// compositor whose session was lost could never draw again).
TEST(ServerLoopLatchTest, ALatchedSessionsWindowLeaseIsWaitedForAndHandedToAFreshSession) {
EXPECT_EXIT(LatchWhileHoldingTheServerWindowAndExit(), ::testing::ExitedWithCode(0), ".*")
<< "bits: 1 = the lease was not taken; 2 = the latch did not mark it ending; 4 = the fresh session was "
"refused; 8 = it did not get the window after the session ended; 16 = the window was released "
"(64+ = setup)";
}
namespace {
// P12 review fix (major): THE LOST WINDOW IS ANSWERED IN THE MIDDLE OF A BATCH. A client streaming
// frames keeps the command ring from emptying, and the first version answered a window-lost request
+40
View File
@@ -255,3 +255,43 @@ TEST(SharedImageSync, AReadTrackerPublishesOneFrameToEveryImageItRead) {
EXPECT_TRUE(SI::WaitForReads(*a, 10));
EXPECT_TRUE(SI::WaitForReads(*b, 10));
}
// Implicit sync by flush (glamor): what a session used since its last boundary is published as a
// write AND a read - a compositor sampling an X window's pixmap waits for the flush's fence, and the
// next writer of that pixmap (or of a client buffer the X server copied from) waits for it too.
TEST(SharedImageSync, AFlushPublishesEveryUsedImageAsAWriteAndARead) {
std::string why;
SI::ImageRef windowPixmap = SI::Allocate(8, 8, SI::kFourccXrgb8888, why);
SI::ImageRef clientBuffer = SI::Allocate(8, 8, SI::kFourccXrgb8888, why);
SI::ImageRef untouched = SI::Allocate(8, 8, SI::kFourccXrgb8888, why);
ASSERT_TRUE(windowPixmap && clientBuffer && untouched) << why;
SI::ReadTracker frame;
frame.NoteRead(windowPixmap);
frame.NoteRead(clientBuffer);
FakeFence flush;
frame.PublishFrameAsWrite(flush.Dup());
EXPECT_EQ(frame.Pending(), 0u);
Uint64 generation = 0;
for (const SI::ImageRef& image : {windowPixmap, clientBuffer}) {
const int write = SI::DupWriteFence(*image, &generation);
EXPECT_EQ(generation, 1u) << "a reader must see the flush as a new write";
ASSERT_GE(write, 0);
EXPECT_FALSE(SI::SyncFile::Signaled(write));
::close(write);
EXPECT_FALSE(SI::WaitForReads(*image, 10)) << "a writer must wait for the flush";
}
EXPECT_EQ(SI::DupWriteFence(*untouched, &generation), -1);
EXPECT_EQ(generation, 0u);
flush.Signal();
EXPECT_EQ(SI::DupWriteFence(*windowPixmap, &generation), -1);
EXPECT_TRUE(SI::WaitForReads(*windowPixmap, 10));
EXPECT_TRUE(SI::WaitForReads(*clientBuffer, 10));
// A completed flush (no fence) still moves the generation.
frame.NoteRead(windowPixmap);
frame.PublishFrameAsWrite(-1);
EXPECT_EQ(SI::DupWriteFence(*windowPixmap, &generation), -1);
EXPECT_EQ(generation, 2u);
}
@@ -153,6 +153,9 @@ namespace MobileGL {
return TextureInternalFormat::RGBA4;
case GL_RGB5_A1:
return TextureInternalFormat::RGB5A1;
// GL_BGRA8_EXT (EXT_texture_storage with EXT_texture_format_BGRA8888): stored as RGBA8;
// the BGRA byte order is the pixel transfer format's business, as on desktop GL.
case 0x93A1:
case GL_RGBA8:
return TextureInternalFormat::RGBA8;
case GL_RGBA8_SNORM:
@@ -330,6 +333,9 @@ namespace MobileGL {
return TextureInternalFormat::RG;
case GL_RGB:
return TextureInternalFormat::RGB;
// GL_BGRA_EXT as an unsized internal format (EXT_texture_format_BGRA8888, an ES
// application's spelling): the same storage as GL_RGBA.
case GL_BGRA:
case GL_RGBA:
return TextureInternalFormat::RGBA;
default:
@@ -152,6 +152,29 @@ namespace MobileGL {
--m_nextInactiveVertexInLocation;
}
}
// INACTIVE FRAGMENT OUTPUTS go to the top of the draw-buffer range for the same reason:
// GL gives locations to active outputs only, and resolution runs in declaration order, so
// a dead output declared first would take location 0 and push the real one to 1, where no
// draw buffer reads it. The legacy lowering is where that happens: a source whose
// gl_FragColor sits in an inactive preprocessor arm (`#if __VERSION__ >= 130 / out vec4
// frag_color; / #else / #define frag_color gl_FragColor`) still gets the injected
// mg_FragColor declaration ahead of its own output. The slot is reserved, so no active
// output auto-assigned later can land on it.
if (!ent.live && stage == EShLangFragment && type.getQualifier().isPipeOutput() &&
!type.getQualifier().hasLocation() && !type.isBuiltIn()) {
const int size = std::max(1, glslang::TIntermediate::computeTypeLocationSize(type, stage));
const int drawBuffers = referenceIntermediate.getLimits().maxDrawBuffers;
const int top = (drawBuffers > 0 ? drawBuffers : kMinimumDrawBuffers) - size;
const int key = buildStorageKey(EShLangFragment, glslang::EvqInOut);
for (int location = top; location >= 0; --location) {
bool free = true;
for (int i = 0; i < size && free; ++i) free = checkEmpty(key, location + i);
if (!free) continue;
reserveSlot(key, location, size);
ent.symbol->getWritableType().getQualifier().layoutLocation = location;
break;
}
}
return TDefaultGlslIoResolver::resolveInOutLocation(stage, ent);
}
@@ -95,5 +95,8 @@ namespace MobileGL {
// driver (caught by the super-duper-vanilla and chocapic retrace fixtures).
static constexpr int kInactiveVertexInLocationTop = 15;
int m_nextInactiveVertexInLocation = kInactiveVertexInLocationTop;
// The draw-buffer count every GL/ES implementation has, for an inactive fragment output
// when the compile carried no limit.
static constexpr int kMinimumDrawBuffers = 4;
};
} // namespace MobileGL
+180
View File
@@ -0,0 +1,180 @@
// MobileGL - MobileGL/MG_Util/X11/DisplayGuard.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 "DisplayGuard.h"
#include <MG_Util/Debug/Log.h>
#include <atomic>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <sstream>
#if defined(__linux__)
#include <dirent.h>
#include <unistd.h>
#endif
namespace MobileGL::MG_Util::X11 {
namespace {
constexpr const char* kSocketDirectory = "/tmp/.X11-unix/X";
// __SO_ACCEPTCON in /proc/net/unix's Flags column: the socket listens.
constexpr unsigned long kAcceptConnectionsFlag = 0x00010000ul;
Bool AllDigits(const char* begin, const char* end) {
if (begin == end) return false;
for (const char* p = begin; p != end; ++p) {
if (*p < '0' || *p > '9') return false;
}
return true;
}
Int32 ToNumber(const char* begin, const char* end) {
if (!AllDigits(begin, end) || end - begin > 6) return -1;
Int32 value = 0;
for (const char* p = begin; p != end; ++p) value = value * 10 + (*p - '0');
return value;
}
String ReadWhole(const char* path) {
std::ifstream in(path, std::ios::binary);
if (!in) return {};
std::stringstream all;
all << in.rdbuf();
return all.str();
}
Bool Forbidden(const char* value) {
if (value == nullptr) return false;
return std::strcmp(value, "0") == 0 || std::strcmp(value, "false") == 0 || std::strcmp(value, "off") == 0 ||
std::strcmp(value, "no") == 0;
}
} // namespace
Int32 ParseDisplayNumber(const char* name) {
if (name == nullptr || name[0] == '\0') return -1;
const SizeT length = std::strlen(name);
// A socket path (launchd-style names, and how some tools spell a local display).
const SizeT dirLength = std::strlen(kSocketDirectory);
const char* path = name[0] == '@' ? name + 1 : name;
if (std::strncmp(path, kSocketDirectory, dirLength) == 0) {
const char* digits = path + dirLength;
const char* end = digits;
while (*end >= '0' && *end <= '9') ++end;
return ToNumber(digits, end);
}
// [protocol/][host]:display[.screen]: the LAST colon (an IPv6 host has colons of its own).
const char* colon = std::strrchr(name, ':');
if (colon == nullptr) return -1;
const char* digits = colon + 1;
const char* end = digits;
while (*end >= '0' && *end <= '9') ++end;
if (*end != '\0' && *end != '.') return -1;
(void)length;
return ToNumber(digits, end);
}
Bool IsXServerProgram(const String& basename) {
static const char* const kServers[] = {"Xwayland", "Xorg", "Xorg.bin", "X", "Xvfb", "Xephyr",
"Xnest", "Xvnc", "Xwin", "XWin", "Xquartz", "Xfake"};
for (const char* server : kServers) {
if (basename == server) return true;
}
return false;
}
Vector<Uint64> ListeningDisplaySocketInodes(const String& procNetUnix, Int32 number) {
Vector<Uint64> inodes;
if (number < 0) return inodes;
const String wanted = String(kSocketDirectory) + std::to_string(number);
std::istringstream lines(procNetUnix);
String line;
Bool header = true;
while (std::getline(lines, line)) {
if (header) { // "Num RefCount Protocol Flags Type St Inode Path"
header = false;
if (line.find("Inode") != String::npos) continue;
}
std::istringstream fields(line);
String num, refCount, protocol, flags, type, state, inode, path;
if (!(fields >> num >> refCount >> protocol >> flags >> type >> state >> inode)) continue;
if (!(fields >> path)) continue; // unbound
const unsigned long flagBits = std::strtoul(flags.c_str(), nullptr, 16);
if ((flagBits & kAcceptConnectionsFlag) == 0) continue;
const String bare = !path.empty() && path[0] == '@' ? path.substr(1) : path;
if (bare != wanted) continue;
inodes.push_back(std::strtoull(inode.c_str(), nullptr, 10));
}
return inodes;
}
Bool ServesDisplay(const ProcessFacts& facts, Int32 number) {
if (number < 0) return false;
for (const Uint64 listening : ListeningDisplaySocketInodes(facts.ProcNetUnix, number)) {
for (const Uint64 own : facts.OwnSocketInodes) {
if (own == listening) return true;
}
}
return false;
}
Bool MayDial(const char* displayName, const ProcessFacts& facts, const char* overrideValue) {
if (Forbidden(overrideValue)) return false;
if (displayName == nullptr || displayName[0] == '\0') return false;
// An X server never dials a display: the one it would reach first is likely its own, and
// nothing it draws needs another one.
if (IsXServerProgram(facts.ExeBasename)) return false;
const Int32 number = ParseDisplayNumber(displayName);
return number < 0 || !ServesDisplay(facts, number);
}
ProcessFacts ReadProcessFacts() {
ProcessFacts facts;
#if defined(__linux__)
char exe[4096] = {};
const ssize_t length = ::readlink("/proc/self/exe", exe, sizeof(exe) - 1);
if (length > 0) {
exe[length] = '\0';
const char* slash = std::strrchr(exe, '/');
facts.ExeBasename = slash != nullptr ? slash + 1 : exe;
}
facts.ProcNetUnix = ReadWhole("/proc/self/net/unix");
if (DIR* fds = ::opendir("/proc/self/fd")) {
while (const dirent* entry = ::readdir(fds)) {
if (entry->d_name[0] == '.') continue;
const String link = String("/proc/self/fd/") + entry->d_name;
char target[128] = {};
const ssize_t n = ::readlink(link.c_str(), target, sizeof(target) - 1);
if (n <= 0) continue;
target[n] = '\0';
// "socket:[12345]"
if (std::strncmp(target, "socket:[", 8) != 0) continue;
facts.OwnSocketInodes.push_back(std::strtoull(target + 8, nullptr, 10));
}
::closedir(fds);
}
#endif
return facts;
}
Bool MayDialX11Display(const char* displayName) {
const char* overrideValue = std::getenv("MOBILEGL_X11_DIAL");
if (displayName == nullptr || displayName[0] == '\0') return false;
const Bool allowed = MayDial(displayName, ReadProcessFacts(), overrideValue);
if (!allowed) {
static std::atomic<Bool> logged{false};
if (!logged.exchange(true)) {
MGLOG_I("X11: not opening a connection to display '%s' - this process serves it (an X server), or "
"MOBILEGL_X11_DIAL forbids it",
displayName);
}
}
return allowed;
}
} // namespace MobileGL::MG_Util::X11
+59
View File
@@ -0,0 +1,59 @@
// MobileGL - MobileGL/MG_Util/X11/DisplayGuard.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
// MOBILEGL NEVER DIALS AN X DISPLAY ITS OWN PROCESS SERVES.
//
// A rootless X server that draws with MobileGL (Xwayland's glamor) loads this library into the X
// server itself. Anything here that opens a connection to $DISPLAY then connects to the very
// process that is blocked inside the call - which can never answer: the X server deadlocks on its
// own socket. So every place that would open an X connection asks MayDialX11Display first.
//
// "Serves" is decided by facts about the process, not by who called: it holds a LISTENING unix
// socket bound to that display's name (/tmp/.X11-unix/X<n>, as a path or in the abstract
// namespace - an X server started with -listenfd holds the ones its compositor bound), or its
// executable is an X server's. MOBILEGL_X11_DIAL=0 forbids every dial.
//
// The pure pieces take their inputs (the /proc/net/unix text, the process's socket inodes, the
// executable name) so a host test pins them without being an X server.
#include <Includes.h>
namespace MobileGL::MG_Util::X11 {
// The display number of an X display name - ":0", ":1.0", "unix:2", "host:3.1",
// "/tmp/.X11-unix/X4" - or -1 when the name has none.
Int32 ParseDisplayNumber(const char* name);
// Whether an executable's base name is an X server's (Xwayland, Xorg, Xvfb, ...).
Bool IsXServerProgram(const String& basename);
// The inodes of the LISTENING sockets in a /proc/net/unix table bound to display `number`'s
// socket name, as a path or abstract (leading '@').
Vector<Uint64> ListeningDisplaySocketInodes(const String& procNetUnix, Int32 number);
struct ProcessFacts {
String ExeBasename;
String ProcNetUnix;
Vector<Uint64> OwnSocketInodes; // inodes of the sockets in the process's descriptor table
};
// Whether the process the facts describe serves display `number`.
Bool ServesDisplay(const ProcessFacts& facts, Int32 number);
// The decision: false for no name, a forbidding override ("0"/"false"/"off"), or a display this
// process serves; a name with no number is dialed only by a process that is not an X server.
Bool MayDial(const char* displayName, const ProcessFacts& facts, const char* overrideValue);
// The real process's facts, read from /proc.
ProcessFacts ReadProcessFacts();
// MayDial for this process (facts read on each call: rare - a display creation, a window
// surface - and a process may start serving later). Logs a refusal once.
Bool MayDialX11Display(const char* displayName);
} // namespace MobileGL::MG_Util::X11
@@ -0,0 +1,174 @@
# Plan: X11 apps on the GPU, zero-copy (Xwayland glamor + GLX DRI3/Present) (2026-10-03)
> Follows [`plan-ahb-dmabuf.md`](plan-ahb-dmabuf.md) (the Wayland half: server-allocated AHB
> "shared images" exported as dma-bufs). Same hard rules: vendor-neutral (AHB, dma-buf, sync_file,
> the libgbm backend ABI, linux-dmabuf, DRI3/Present), no layout assumptions (modifier INVALID).
## Today
```
GLX app --glXSwapBuffers--> ReadPixels (server->client CPU) --xcb_put_image--> Xwayland (-shm, llvmpipe)
Xwayland --wl_shm--> KWin --glTexSubImage2D upload--> server
```
Two full-frame CPU trips per frame for every X11 GL app, and every ordinary X11 app is drawn by
pixman/llvmpipe and uploaded again by KWin.
## Target
```
GLX app --render--> pbuffer --GPU copy (PresentToSharedImage)--> [AHB image]
--DRI3 PixmapFromBuffer(s)(dma-buf, once per buffer)--> Xwayland pixmap (glamor: gbm_bo_import -> EGLImage)
--Present PresentPixmap--> Xwayland flips it (attaches the pixmap's dma-buf wl_buffer) or GPU-copies it
Xwayland (glamor on MobileGL EGL/GBM) --linux-dmabuf wl_buffer (window pixmaps are shared images)--> KWin
```
Every hop is a session of the same MobileGL server sampling or writing the same AHardwareBuffer.
CPU copies: zero.
## Stage 1 - Xwayland on MobileGL (glamor)
What Xwayland 24.1.13 (`hw/xwayland/xwayland-glamor-gbm.c`, `glamor/glamor.c`) needs, and where it is:
| Need | Status |
|---|---|
| render node from linux-dmabuf v4 feedback `main_device` (drmGetDeviceFromDevId) | KWin's thin node: must be a real DRM render node (`MOBILEGL_GBM_NODE`=/dev/dri/renderD128). `/dev/null` makes glamor fail -> shm fallback |
| `gbm_create_device(fd)` with `GBM_BACKEND=mobilegl` | `mobilegl_gbm.so` (exists) |
| EGL client ext `EGL_KHR/MESA_platform_gbm`, `eglGetPlatformDisplay(GBM, gbm)` | exists; the foreign-device decline keys on the backend name `mobilegl` |
| `eglCreateContext(EGL_NO_CONFIG_KHR, core 3.1)` + surfaceless `eglMakeCurrent` | cherry-picked from the surfaceless branch (6125f941), to be dropped on rebase |
| GL >= 2.1 desktop, `GL_ARB_vertex_array_object`, `GL_OES_EGL_image`; renderer not llvmpipe | exists on a split client |
| `EGL_EXT_image_dma_buf_import(_modifiers)` -> dmabuf_capable | exists (shared images) |
| `gbm_bo_create_with_modifiers2(XRGB8888/ARGB8888, {INVALID, LINEAR})`, `gbm_bo_get_fd_for_plane`, `_handle_for_plane`, `_stride_for_plane`, `_offset`, `_modifier`, `gbm_bo_import(FD / FD_MODIFIER)` | exists; now covered by a host test through the real libgbm loader |
| `eglCreateImageKHR(EGL_LINUX_DMA_BUF_EXT)` of its own bos, `glEGLImageTargetTexture2DOES` | exists (server identifies its image by inode) |
| KWin's tranche lists XRGB8888/ARGB8888 with modifier INVALID | KWin adds INVALID+LINEAR when the EGL reports no modifiers (ours) |
| **implicit sync**: glamor renders into window pixmaps and commits after `glFlush`, assuming the kernel orders KWin's read after it | **new**: see below |
| **Xwayland must never dial its own display** | **new**: see below |
### Implicit sync by flush (new shared_image op `Flush`)
The server already orders an image between sessions: a writer publishes a sync_file per write
(`PublishWrite`), a reader waits on it at its first use and publishes its frame's read fence at
its frame boundary (swap). glamor has neither a swap nor an explicit write: it renders into the
image through an FBO and calls `glFlush` before committing.
- Client: `glFlush`/`glFinish` in a process that has bound a shared image to a texture
(`glEGLImageTargetTexture2DOES`) and does not own the server window (not KWin) send the new
in-stream `shared_image Flush` op and wait for its reply. Policy is a pure function
(`SharedImageFlushPolicy`), overridable with `MOBILEGL_SHARED_IMAGE_FLUSH_SYNC=0/1`.
- Server: `BackendObject::PublishSharedImageAccesses()` - every image the session used since its
last boundary gets the flush's fence as a write (generation moves) and as a read.
Espryt: `ExportFence` (EGL_ANDROID_native_fence_sync), Magma: release held images, submit with
the exportable semaphore, export it. A session that has flushed this way also waits (GPU) for
the pending read fences of an image before its first use in a frame (write-after-read).
- The reply comes after the fence is published, so KWin (which samples after Xwayland's commit,
which follows the reply) always finds the new generation.
### X-connection safety (`MG_Util/X11/DisplayGuard`)
One rule, one function: `MayDialX11Display(name)` is false when this process **serves** that
display: it holds a listening unix socket named `/tmp/.X11-unix/X<n>` (path or abstract) per
`/proc/net/unix` + `/proc/self/fd`, or its executable is an X server (Xwayland, Xorg, Xvfb, ...).
`MOBILEGL_X11_DIAL=0` turns all dialing off. Every place MobileGL opens an X connection asks it
first: EGLState's default-visual query (eglGetDisplay of a non-X native display has platform NONE,
so the old "only on X displays" test still dialed for `eglGetDisplay(gbm_device)`), DirectGLES's
visual query and window-surface display, Magma's Xlib surface. GLX never opens a connection (it
uses the application's). KWin's launcher also drops `DISPLAY` from Xwayland's environment.
### KWin (anland `kwin.patch`, `mobilegl-startup.sh`)
`ANLAND_MOBILEGL=1` and `ANLAND_XWAYLAND_GLAMOR != 0`: Xwayland starts **without** `-shm`, with
`MOBILEGL_IPC_SURFACE=offscreen`, its own `MOBILEGL_LOG_FILE_PATH=/tmp/mgl-xwayland`, `GBM_BACKEND`
kept, no `LIBGL_ALWAYS_SOFTWARE`/`GALLIUM_DRIVER`, no `DISPLAY`. Otherwise the old `-shm` +
software environment. If glamor cannot initialise, Xwayland itself falls back to shm rendering.
## Stage 2 - GLX presentation through DRI3 + Present
Per GLX window drawable (`GLXImpl/X11Present.{h,cpp}`, logic behind two small interfaces so the
host tests drive it with fakes):
- **Path selection** (`SelectPresentPath`): DRI3 >= 1.0 and Present >= 1.0 on the connection,
shared images available, depth 24/32, `MOBILEGL_GLX_PRESENT` not `readback` -> `Dri3Present`;
else MIT-SHM >= 1.2 with fd passing -> `ShmPutImage`; else `PutImage` (today's bands).
- **Buffers**: up to 3 (4 when Xwayland holds all three past a 1 s wait) shared images of the
window's format (depth 24 -> XRGB8888, 32 -> ARGB8888: exactly what glamor imports them as), each
imported once as a pixmap (`PixmapFromBuffers` with modifier INVALID on DRI3 >= 1.2, else
`PixmapFromBuffer`, checked). A buffer is busy from its PresentPixmap until its `IdleNotify`.
- **Present**: `PresentToSharedImage` (GPU copy, rows top first, returns once submitted with the
write fence published), then `PresentPixmap` with an XFixes update region from the swap's
damage (flipped to X's top-left origin; none = whole), serial per frame. Events arrive on a
special-event queue (`xcb_register_for_special_xge`), never in the application's queue.
- **Pacing**: `FrameThrottle` (the Wayland rules) on `CompleteNotify`: interval >= 1 waits for the
previous frame's completion, `target_msc = last_msc + interval`; interval 0 uses
`PresentOptionAsync`, unpaced while completions come, ~1 fps once one is 200 ms overdue.
- **Errors**: a refused `PixmapFromBuffer`, a `PresentPixmap` error (checked lazily, no round
trip), or the window's destruction (`ConfigureNotify` with `PresentWindowDestroyed`) latch the
drawable onto the readback path for good, logged once.
- **Resize**: `ConfigureNotify` (and the existing throttled `XGetGeometry`) resize the pbuffer;
buffers of the old size are dropped as they come back idle.
- **Fallback** (no DRI3/Present: Xwayland `-shm`, a remote X server): readback into a MIT-SHM
segment (memfd, `xcb_shm_attach_fd`) + `xcb_shm_put_image`; without MIT-SHM, today's bands.
- `GLX_EXT_buffer_age` (`GLX_BACK_BUFFER_AGE_EXT`) answers the EGL buffer age of the drawable.
## Tests (host, WSL)
`X11DisplayGuardTest` (display names, /proc parsing, the Xwayland case), `X11PresentTest` (path
selection, rotation, idle/complete/configure handling, pacing, resize, error latching, fake xcb
and fake images), `SharedImageSync` additions (accesses publish as write + read),
`SharedImageFlushPolicyTest`, `GbmGlamorTest` (the real libgbm loader with `GBM_BACKEND=mobilegl`
over a fake shared-image library: glamor's create/export/import calls).
## Device verification (phase B)
`scripts/x11/` in the skill: deploy, check Xwayland's glamor log lines and its dma-buf wl_buffers in
KWin (`WAYLAND_DEBUG`-free: `/proc/<kwin>/fdinfo` dma-buf count and the server log's import lines),
glxgears/glxinfo/an X11 GL app before/after (fps, `top` CPU of app/Xwayland/KWin/server), and
ordinary X apps (xterm, xeyes) for glamor rendering.
## Risks
- `drmGetDeviceFromDevId` on the borrowed render node inside the container (sysfs visibility).
- Adreno: cross-context ordering relies on the Flush op's fence; a missed flush shows as tearing,
not corruption of other windows.
- The extra round trip per Xwayland `glFlush` (glamor flushes once per main-loop wakeup).
- DRI3 clients that are not MobileGL (Mesa Vulkan WSI) hand Xwayland dma-bufs the server never
allocated: `PixmapFromBuffers` fails with BadAlloc for them, as on any driver mismatch.
## Device results (2026-10-03, TB321FU / Adreno 750, x11-gpu 95aa618d server + client)
glxgears 1280x720, % of one core, `x11-verify.sh measure`; "before" = the old stack (`-shm`
llvmpipe Xwayland, GLX readback + PutImage).
> glxgears is fixed-function GL (glBegin/glEnd display lists, glLight), which MobileGL does not
> implement (Core Profile only), so its window stays black. These numbers measure presentation
> throughput of empty frames through each path, not rendering. Check X11 rendering with a
> core-profile or shader-based GLX client, and verify it from pixels (mgl-xgrab / XGetImage).
| run | fps | phone | glxgears | Xwayland | kwin | server | GPU |
|---|---|---|---|---|---|---|---|
| before, unpaced | 160 | 229% | 28% | 42% | 71% | 37% | 15% |
| Espryt DRI3+Present, interval 1 | 98-101 | 210% | 12% | 5% | 28% | 32% | 12% |
| Espryt DRI3+Present, vblank_mode=0 | 1440-1780 | 296% | 29% | 29% | 36% | 62% | 72% |
| Espryt readback + MIT-SHM on glamor | 46 | 168-188% | 5% | 78% | 11% | 35% | 5% |
| Magma DRI3+Present, interval 1 | 105-112 | 210% | 12% | 5% | 24% | 43% | 16% |
| Magma DRI3+Present, vblank_mode=0 | 940-970 | 282% | 24% | 18% | 33% | 60% | 77% |
| Magma readback + MIT-SHM on glamor | 27 | 161% | 2% | 50% | 7% | 70% | 5% |
- Glamor engages on both backends: Xwayland runs without `-shm`, offers DRI3 1.2 + Present 1.2,
its windows are linux-dmabuf shared images; GLX windows log `presented through DRI3+Present`.
- Found on the device and fixed: uploads into a texture bound to a shared image were dropped
(Espryt) - an X server's PutImage into a window pixmap showed black windows. They are now
drained at the producer's flush and written into the image (RGB-converted for X formats, which
the driver holds as RGB8).
- The forced readback path is slower on a glamor Xwayland than on the old llvmpipe one (glamor
uploads every frame through the server); it is only the fallback now.
- Fixed (cd58f048): after a hide/show or lock/unlock round, X11 Qt windows kept stale or black
regions in their window pixmap. Root cause: every glamor copy and fill drew nothing. glamor's
fragment shaders name gl_FragColor only in the inactive arm of a version guard and write their
own `frag_color`; the legacy lowering still declared `mg_FragColor` ahead of it, and the IO
resolver gave that dead output location 0 and `frag_color` location 1, which no draw buffer
reads. Uploads (PutImage) still landed, so windows looked right until Xwayland copied between
window buffers (it swaps the window pixmap on every commit and reallocates buffers after a
hide), and then showed old content or zeros. Inactive fragment outputs now take the top of the
draw-buffer range. Host test: ProgramTest.InactiveLoweredFragColorDoesNotDisplaceTheActiveOutput.
On the device, an X client checking its own XGetImage against a CPU model (PutImage, CopyArea
and FillRectangle; MIT-SHM and plain; depth 24 and 32) sees 0 bad pixels through hide/show/lock
on both backends. One run in about 20 on Magma (no SHM, depth 24) left a 2751-pixel rect
mismatched; it did not come back in the repeats.