Compare commits

..
Author SHA1 Message Date
BZLZHH 8302dd30bf [Docs] (Anland): the lock screen behind the black desktop, and where the Magma text gap is not 2026-10-03 16:34:25 +08:00
BZLZHH a6d788191f [Docs] (Anland): record the Magma verification and its missing glyphs 2026-10-03 16:07:53 +08:00
BZLZHH 0d89db36dd [Docs] (Anland): the D1100 + Mali changes and why each one was needed 2026-10-03 15:57:11 +08:00
BZLZHH b7a6e6c538 [Docs] (Anland): the D1100 + Mali, kernel 4.14 bring-up and its three fixes 2026-10-03 15:55:53 +08:00
BZLZHH f44888ca01 [Fix] (Espryt): present through eglSwapBuffers when the driver refuses the damage entry point
A vendor EGL can export eglSwapBuffersWithDamageEXT and then answer EGL_FALSE on
a window surface without setting an error (measured on an Android 4.14 vendor
kernel with a Mali driver; the surface is current, the context is current, the
ANativeWindow reports its full extent, and the plain entry point presents the
same surface happily). Trusting that pointer kept the frame: the window's buffer
queue never saw a buffer, the compositor's own window stayed a solid colour on
screen, and every client of the session fell back to wl_shm because the
compositor could not sample what it could not present.

A refused damage swap now falls back to eglSwapBuffers and says so once. A
driver without the extension presents through the plain call as before.
2026-10-03 15:54:55 +08:00
BZLZHH 8245221755 [Fix] (Remote): name a shared image by extent and format when the kernel gives descriptors one identity
(st_dev, st_ino) is how an incoming dma-buf descriptor names the image it was
exported from, and it is the only identity the registry had. Some kernels do not
keep those apart: on a 4.14 vendor kernel every descriptor of every image reports
dev 12 ino 10658 with st_size 0, and /proc/self/fdinfo carries nothing else, so
the registry correctly detected the ambiguity and then refused every import -
which is every zero-copy window a compositor ever tries to sample, leaving the
whole stack on the wl_shm fallback.

The identity stays the kernel's to give. When it is ambiguous, the import's own
extent and format select among the live images exported under that identity, in
allocation order and each claimed once, which is the order a producer allocates
and hands them over in. Identify() takes the extent and the fourcc the import
record already carries; nothing else changes.
2026-10-03 15:54:55 +08:00
248 changed files with 1290 additions and 19335 deletions
+25 -32
View File
@@ -18,15 +18,15 @@ nobody else is mid-test. Use your own `ct.sh` channel names (others use c, c2,
## Architecture (10 lines)
1. Phone: Lenovo TB321FU (Y700, Adreno 750, Android 15, kernel 6.1), rooted with **KernelSU** (`/data/adb/ksu`, `ksud`; `su -c` works). USB serial `HA27Q3LQ`, or wireless adb `ip:port`.
2. anland APK `com.anland.consumer.mobilegl` (debuggable build of anland branch `legacy-mobilegl-unified`): UI process + private service process `:mobilegl` (`MobileGLWorker`), which loads the **server** `libMobileGL.so` (NDK, from MobileGL `feat/disaggregated`) and listens on abstract socket `@anland-mobilegl` from the first attached window on. One process serves every client (KWin, plasmashell, ksplash, Chrome...), one backend per process. `MobileGLWorker` is a **foreground service** (notification "Linux desktop is running" / action "Stop desktop"), so the server and the session outlive a hidden, locked or swiped-away window.
3. Backend = the app setting "Renderer backend" (Settings > Connection > MobileGL desktop; file `/data/data/<pkg>/files/mobilegl-backend`, default DirectGLES; also `am start ... --es mobilegl_backend X`). Espryt = DirectGLES, Magma = DirectVulkan. The server reads it when its process starts; the app publishes it as `/data/local/tmp/anland-mobilegl/backend` and the session copies that into the container's `/etc/mobilegl/backend` (what every client reports; mismatch = "Hello.backendType disagrees with pinned backend"). `debug.mobilegl.backend`, if someone sets it, still overrides the setting until the next reboot.
4. Experiment display daemon `/data/adb/modules/anland-daemon/display_daemon /data/local/tmp/anland-mobilegl/display.sock` (display/input broker), started by the app (below). The module only starts the original one on `/data/local/tmp/display_daemon.sock` at boot; leave that alone.
2. anland APK `com.anland.consumer.mobilegl` (debuggable build of anland branch `legacy-mobilegl-unified`): UI process + private service process `:mobilegl` (`MobileGLWorker`), which loads the **server** `libMobileGL.so` (NDK, from MobileGL `feat/disaggregated`) and listens on abstract socket `@anland-mobilegl`. One process serves every client (KWin, plasmashell, ksplash, Chrome...), one backend per process.
3. Backend = `setprop debug.mobilegl.backend DirectGLES|DirectVulkan` (Espryt = DirectGLES, Magma = DirectVulkan; prop lost on reboot) and must equal the container's `/etc/mobilegl/backend` (what every client reports; mismatch = "Hello.backendType disagrees with pinned backend").
4. Experiment display daemon `/data/adb/modules/anland-daemon/display_daemon /data/local/tmp/anland-mobilegl/display.sock` (display/input broker; NOT started at boot - the module only starts the original one on `/data/local/tmp/display_daemon.sock`, leave that alone).
5. Container `arch-kde-mgl` (Droidspaces 6.4.5, Arch Linux ARM aarch64 glibc, host net, `rootfs.img` mounted at `/mnt/Droidspaces/arch-kde-mgl` on the Android side). Bind mounts: `/data/local/tmp/anland-mobilegl` -> `/run/anland-mobilegl`, `/data/local/tmp/display_daemon.sock` -> `/run/display.sock`.
6. `desktop-session.service` (User=swung0x48, **enabled**: the container boots straight into it, as the original image does) has drop-in `/etc/systemd/system/desktop-session.service.d/mobilegl.conf` (anland `producers/kde/Arch_v5/desktop-session-mobilegl.conf`, installed + enabled by `sync-build-kwin.sh`): `ExecStartPre=mobilegl-startup.sh wait` (until `@anland-mobilegl` listens in `/proc/net/unix` and the daemon socket exists), `ExecStartPre=+... sync-backend`, `Restart=always`, then `ExecStart=/opt/mobilegl/bin/mobilegl-startup.sh plasma`, which deletes the sticky software-renderer key, sets `MOBILEGL_IPC_PROBE_TIMEOUT_MS=0` session-wide (MobileGL never declines, so glvnd never falls through to another GL stack), writes a user drop-in for `plasma-kwin_wayland.service` (kwin_wayland_wrapper -> `/opt/mobilegl/kwin/bin/kwin_wayland` + `/opt/mobilegl/kwin/lib/libkwin.so.6.7.4`, `ANLAND_MOBILEGL=1`, `MOBILEGL_IPC_SURFACE=server`) and runs `startplasma-wayland`.
7. KWin 6.7.4 with anland's `anland` backend renders straight into the anland Android Surface through the server. 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.
6. `desktop-session.service` (User=swung0x48) has drop-in `ExecStart=/opt/mobilegl/bin/mobilegl-startup.sh plasma`, which writes a user drop-in for `plasma-kwin_wayland.service` (kwin_wayland_wrapper -> `/opt/mobilegl/kwin/bin/kwin_wayland` + `/opt/mobilegl/kwin/lib/libkwin.so.6.7.4`, `ANLAND_MOBILEGL=1`, `MOBILEGL_IPC_SURFACE=server`) and runs `startplasma-wayland`.
7. KWin 6.7.4 with anland's `anland` backend renders straight into the anland Android Surface through the server. Every other GL process is `MOBILEGL_IPC_SURFACE=offscreen` and presents through KWin.
8. Client = `/opt/mobilegl/lib/libMobileGL.so` (glibc aarch64), the container's **system-wide** GL vendor (section below): glvnd EGL vendor `/usr/share/glvnd/egl_vendor.d/10_mobilegl.json` (sorts before the distribution's `50_*.json`, which serves whenever MobileGL declines), GLX vendor `/usr/lib/libGLX_mobilegl.so.0`, settings from `/etc/mobilegl/client.conf` (`MOBILEGL_TRANSPORT=spawn MOBILEGL_IPC_DATA=shm MOBILEGL_IPC_CONTROL=unix:@anland-mobilegl`) + `/etc/mobilegl/backend`. No per-process environment is needed.
9. Zero-copy windows: client `wl_egl_window` frames are server-allocated AHardwareBuffer "shared images" exported as dma-buf fds over `zwp_linux_dmabuf_v1`; KWin imports them with EGL and the server recognises its own buffer by inode. KWin gets a DRM device via `GBM_BACKEND=mobilegl` -> `/usr/lib/gbm/mobilegl_gbm.so` (node is only an identity, never ioctl'd). Without linux-dmabuf the client falls back to wl_shm readback.
10. X11 (`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.
10. X11 apps (Xwayland) use the MobileGL GLX vendor with per-frame readback + `xcb_put_image`. Chrome runs ANGLE-GLES over MobileGL EGL with the GPU in-process (`mobilegl-startup.sh chrome`).
## First-time prerequisites (Windows host)
@@ -35,28 +35,28 @@ nobody else is mid-test. Use your own `ct.sh` channel names (others use c, c2,
- WSL distro **archlinux** with clang, lld, llvm, cmake, ninja. **lld's major version must equal clang/llvm-libs'** (lld 23 on llvm 22 broke `ld.lld`; working set: all 22.1.6). Then export the sysroot once: `bash scripts/xsysroot/refresh-sysroot.sh` (-> `~/sysroots/arch-kde-mgl` + `~/sysroots/aarch64-arch.cmake`; re-run after container package upgrades, then `xbuild.sh --reconfigure`).
- MobileGL worktree (never build in the shared main checkout): `GIT_LFS_SKIP_SMUDGE=1 git worktree add ...`, `git submodule update --init --recursive`, and copy `3rdparty/glslang/External/spirv-tools` from the main checkout (the submodule leaves it empty).
- anland worktree on `legacy-mobilegl-unified` (KWin patch/backend, startup script, `mobilegl-tools/`).
- Phone side that already exists and is NOT recreated by this skill: the APK (build: anland `consumers/anland_v5/android_consumer/MOBILEGL.md`, gradle `:app:assemblePlainDebug` with `MOBILEGL_DIST`, `-PmobileglApplicationId=com.anland.consumer.mobilegl -PanlandDefaultSocket=/data/local/tmp/anland-mobilegl/display.sock`, from Git Bash with `MSYS_NO_PATHCONV=1`; signed with this machine's `~/.android/debug.keystore`, so `adb install -r` works; reinstalling with another key changes the UID and needs the KernelSU grant again - `mobilegl-tools/ksu_grant.c`), the anland KernelSU modules (`anland-daemon`, `anland-awl`), the container with KWin's configured build tree `/root/mobilegl-build/kwin-6.7.4/build` and pristine `/root/gbm-dev/kwin-a/src`.
- Phone side that already exists and is NOT recreated by this skill: the APK (build: anland `consumers/anland_v5/android_consumer/MOBILEGL.md`, gradle `:app:assemblePlainDebug` with `MOBILEGL_DIST`, `-PmobileglApplicationId=com.anland.consumer.mobilegl`; reinstalling with another key changes the UID and needs the KernelSU grant again - `mobilegl-tools/ksu_grant.c`), the anland KernelSU modules (`anland-daemon`, `anland-awl`), the container with KWin's configured build tree `/root/mobilegl-build/kwin-6.7.4/build` and pristine `/root/gbm-dev/kwin-a/src`.
- Install the helpers once (container must be running): `bash scripts/push-tools.sh` (device/*.sh -> `/data/local/tmp/anl`, `mgrun` -> container `/usr/local/bin`, `kwprep.sh` -> container `/root`).
Run host scripts from Git Bash as `bash scripts/<x>.sh`. Raw adb with device paths needs `MSYS_NO_PATHCONV=1` and the whole root command in one quoted string: `adb shell 'su -c "..."'`. A device script can also be run without pushing: `MSYS_NO_PATHCONV=1 adb shell 'su -c sh' < scripts/device/status.sh`.
## Starting, idling, stopping - no manual steps
## Bring-up after a phone reboot
Nothing starts at phone boot (container `run_at_boot=0`). **Opening the app** (launcher icon = `am start -n com.anland.consumer.mobilegl/com.anland.consumer.MainActivity`, no extras; the APK's default socket is the experiment's, `-PanlandDefaultSocket`) calls `MobileGLDesktop.ensureStarted()` - the single trigger - which starts the foreground service and runs the APK's `assets/mobilegl-desktop.sh up` as root (`su`): display daemon if absent (the script leaves the app's cgroup first, so it survives the app) -> backend published -> container started if stopped -> `systemctl start --no-block desktop-session`. The window waits for the daemon socket; the server listens once the Surface is attached; the session's `wait` step then lets Plasma start. A reopen with everything up only reattaches the window. Log: `/data/local/tmp/anland-mobilegl/desktop.log`, logcat `AnlandMobileGL` ("MobileGL desktop up done in N ms").
Hidden window, screen off, lock screen or swiped-away task: server and session stay (foreground service); KWin turns the workspace's DPMS off (logs "viewer gone: output powered down"; windows get xdg_toplevel `suspended`, no frame callbacks) and back on ("viewer back"). Client swaps are paced by frame callbacks (`MG_Impl/EGLImpl/FrameThrottle.h`): interval >= 1 waits like any Wayland EGL; interval 0 (Chrome) drops to ~1 fps once a callback goes unanswered for 200 ms.
Measured 2026-10-03 (Espryt, Chrome on webglsamples aquarium; % of one core, phone = all of Android): open-to-desktop cold 7.5-12.5 s (daemon 0.5, server 1.0, container 1.5, kwin ~5, plasmashell ~6-7), after a phone reboot 8.5 s, reopen of a running desktop 0.2 s; visible phone 249% / kwin 13 / chrome 99 / server 57 / GPU 22%, hidden 54 / 0 / 6 / 2 / 0%, locked 38 / 0 / 8 / 3 / 0%. Stop desktop 1.7 s. Wireless adb does not come back by itself after a reboot (re-enable it on the phone). **Stop desktop** (notification action, or `am startservice -n <pkg>/com.anland.consumer.MobileGLWorker -a com.anland.consumer.mobilegl.STOP`) runs `mobilegl-desktop.sh down` (session + container stopped, daemon stays), closes the windows, ends `:mobilegl`.
Nothing of the session survives a reboot. Either `adb shell 'su -c "sh /data/local/tmp/anl/bringup.sh [DirectGLES|DirectVulkan]"'`, or by hand, in this order:
```sh
adb connect <ip>:<port> # only for wireless debugging
adb connect <ip>:<port> # only for wireless debugging (e.g. USB cannot power it)
export MSYS_NO_PATHCONV=1
adb shell 'su -c "sh /data/local/tmp/anl/bringup.sh"' # after a reboot: wake, dismiss keyguard, open the app, print the timeline
bash scripts/desktop-verify.sh push cold reopen idle # timed cold start, swipe-away + reopen, CPU/GPU visible/hidden/locked
adb shell 'su -c "sh /data/local/tmp/anl/status.sh"'
adb shell 'su -c "svc power stayon true"'
adb shell 'su -c "setprop debug.mobilegl.backend DirectVulkan"' # or DirectGLES; match /etc/mobilegl/backend
adb shell 'su -c "am start -n com.anland.consumer.mobilegl/com.anland.consumer.MainActivity --es socket_path /data/local/tmp/anland-mobilegl/display.sock"'
adb shell 'su -c "/data/local/Droidspaces/bin/droidspaces -C /data/local/Droidspaces/Containers/arch-kde-mgl/container.config start"'
adb shell 'su -c "sh /data/local/tmp/anl/restart-daemon.sh"' # experiment display daemon, chmod 777 dir / 666 socket
adb shell 'su -c "sh /data/local/tmp/anl/run-plasma.sh"' # restarts app + desktop-session, ~90 s
```
`droidspaces` has no `status` command; `droidspaces show` lists running containers. `device/run-plasma.sh` is a developer restart (session + logind user, then the app), needed after a rebuild because KWin does not reconnect to a new server process. `device/desktop-reset.sh` takes everything down to the post-reboot state. The old manual sequence (setprop, start container, `restart-daemon.sh`, `run-plasma.sh`) is gone; `restart-daemon.sh` remains for daemon debugging only.
`droidspaces` has no `status` command; `droidspaces show` lists running containers. Do not use the old
`/data/local/tmp/restart-daemon.sh` (it kills a hard-coded PID). Check with `device/status.sh`.
## Build and deploy loops
@@ -91,7 +91,7 @@ MSYS2_ARG_CONV_EXCL='*' wsl -d archlinux -- bash -lc 'cd ~/mgl-anl-bld && ctest
## Switching backends
In the app: Settings > Connection > MobileGL desktop > Renderer backend, then Stop desktop and open the app. Or `adb shell 'su -c "sh /data/local/tmp/anl/switch.sh DirectGLES"'`, which does the same (saves the setting through the launch extra, STOPs the service, reopens; clears a stale `debug.mobilegl.backend`). No setprop, no file to edit in the container: the session copies the published backend into `/etc/mobilegl/backend` on its next start. `cyc.sh` keeps whatever is set.
`adb shell 'su -c "sh /data/local/tmp/anl/switch.sh DirectGLES"'` (sets the prop, writes `/etc/mobilegl/backend`, restarts the app), then `run-plasma.sh` - the running session's clients are pinned to the old backend. `cyc.sh` keeps whatever is set.
## System-wide vendor and fallback
@@ -102,13 +102,13 @@ Installed by `xdeploy.sh` (and anland's `anland-build-client.sh`), so any proces
| `/usr/share/glvnd/egl_vendor.d/10_mobilegl.json` | EGL vendor, asked before the system's `50_*.json` |
| `/opt/mobilegl/share/glvnd/egl_vendor.d/50_mobilegl.json` | same JSON, for per-process forcing with `__EGL_VENDOR_LIBRARY_FILENAMES` |
| `/etc/mobilegl/client.conf` | `KEY=value` defaults for every client (transport, data, endpoint); rewritten on deploy |
| `/etc/mobilegl/backend` | the backend (the session's `sync-backend` step copies the app's choice in); wins over a `MOBILEGL_BACKEND_TYPE` line in client.conf |
| `/etc/mobilegl/backend` | the backend (`switch.sh` writes it); wins over a `MOBILEGL_BACKEND_TYPE` line in client.conf |
| `/etc/environment.d/10-mobilegl.conf` | `__GLX_VENDOR_LIBRARY_NAME=mobilegl`, `GBM_BACKEND=mobilegl` for the systemd user manager (all Plasma services and what they start, terminals included) |
| `/etc/profile.d/mobilegl.sh` | the same two for login shells (`bash -l`, `su -l`, ssh, `droidspaces run bash -l`) |
Precedence is environment > `/etc/mobilegl/backend` (backend only) > client.conf > built-in; `MOBILEGL_CONFIG_FILE` / `MOBILEGL_BACKEND_FILE` name other files (empty = off); a server process never reads them.
**Fallback.** Before bringing anything up the client probes the configured endpoint (one non-blocking connect, `MOBILEGL_IPC_PROBE_TIMEOUT_MS`, default 250, 0 = off; a refused abstract socket answers in ~0.2 ms). With no server: the EGL vendor returns `EGL_NO_DISPLAY` and no devices (glvnd moves on to the other vendor), the GLX vendor fails `__glx_Main` (libGLX falls back to the vendor Xwayland names), and `mobilegl_gbm` fails `create_device` (libgbm falls back to the device's own backend). Client queries (`eglQueryString(EGL_NO_DISPLAY)`, `eglGetProcAddress`) never bring a session up. MobileGL also steps aside for a GBM device another backend created and for `LIBGL_ALWAYS_SOFTWARE=1` - that is how 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:
**Fallback.** Before bringing anything up the client probes the configured endpoint (one non-blocking connect, `MOBILEGL_IPC_PROBE_TIMEOUT_MS`, default 250, 0 = off; a refused abstract socket answers in ~0.2 ms). With no server: the EGL vendor returns `EGL_NO_DISPLAY` and no devices (glvnd moves on to the other vendor), the GLX vendor fails `__glx_Main` (libGLX falls back to the vendor Xwayland names), and `mobilegl_gbm` fails `create_device` (libgbm falls back to the device's own backend). Client queries (`eglQueryString(EGL_NO_DISPLAY)`, `eglGetProcAddress`) never bring a session up. MobileGL also steps aside for a GBM device another backend created and for `LIBGL_ALWAYS_SOFTWARE=1` - that is how Xwayland (KWin's patch sets it) keeps the software stack. Show it without stopping the real server:
```sh
sed 's|^MOBILEGL_IPC_CONTROL=.*|MOBILEGL_IPC_CONTROL=unix:@nobody|' /etc/mobilegl/client.conf > /tmp/down.conf
sudo -u swung0x48 env -i HOME=/home/swung0x48 PATH=/usr/bin XDG_RUNTIME_DIR=/run/user/1000 WAYLAND_DISPLAY=wayland-0 \
@@ -117,19 +117,14 @@ 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_GPU=in-process` puts the GPU back in the browser, which cannot recover from a device loss).
Video: Chrome decodes in hardware. The GPU process's render node has a VA-API driver in the container (`/usr/lib/dri/msm_drm_drv_video.so`, DroidSpaces' V4L2 driver): Chrome allocates its frames with `vaCreateSurfaces` and exports them (`vaExportSurfaceHandle`, one fd, R8 + GR88 layers) - the driver's own buffers, never GBM ones - and imports each as an NV12 (P010 for 10-bit) EGLImage bound to `GL_TEXTURE_EXTERNAL_OES`. MobileGL takes such a FOREIGN YUV dma-buf through its labelled CPU-copy fallback: the server maps it and copies it into a YUV AHardwareBuffer of its own (`AHardwareBuffer_lockPlanes`) at the reader's first use in each frame (any present, publishing flush or native fence), then converts that into the texture's RGBA level on the GPU (Espryt: `GL_EXT_YUV_target` with the import's colour hints, `MOBILEGL_YUV_DRIVER_CONVERSION=1` for the driver's external sampler; Magma: `VkSamplerYcbcrConversion` on the AHB's external format). A server-allocated NV12/P010 buffer (GBM `gbm_bo_create(NV12)`) needs no copy. `MOBILEGL_CHROME_VIDEO_DECODE=software` in `mobilegl-startup.sh chrome` brings back `--disable-accelerated-video-decode`. Check a video with `scripts/probes/cdpmedia.py <port> <s>` in the container (CDP `Media.enable`: `kVideoDecoderName = VaapiVideoDecoder`, `kIsPlatformVideoDecoder = true`; `CDP_NAVIGATE=<url>` / `CDP_EXPR=<js>`), which needs Chrome started with `--remote-debugging-port` and a non-default `--user-data-dir` (a fresh profile also needs `--password-store=basic`, else page loads wait forever on KWallet), and grep Chrome's log for `exit_code` (a GPU-process restart). `scripts/probes/yuvprobe.c` pixel-checks foreign NV12/P010 imports, their per-frame refresh and a GBM NV12 buffer (`mgrun offscreen mgl-yuvprobe`, exit 0 = pass). KWin's own NV12 path (it splits a YUV buffer into R8 + GR88 imports) is not served: MobileGL imports no single-channel dma-bufs, so KWin advertises no YUV format over linux-dmabuf. A vendor-agnostic replacement driver (MobileVA: VA-API on Android MediaCodec, decoding into server YUV images with no CPU copy, the current driver kept as an A/B fallback) is planned, not built: `docs/MobileVA/plan.md`.
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), `yuvprobe.c` (YUV dma-buf sampling, `gcc -O1 /root/yuvprobe.c -o /usr/local/bin/mgl-yuvprobe -lEGL -lGLESv2 -lgbm -lm`), `cdpmedia.py` (which decoder a Chrome page uses); build in the container, e.g. `gcc -O1 /root/texfmt.c -o /usr/local/bin/mgl-texfmt -lEGL`, run with `mgrun offscreen`.
GPU hangs: a shader that never ends stops the WHOLE GPU (every process, MobileGL or not) until the kernel resets it - ~2 s, or ~10 s ("Preemption Fault" in dmesg) when a higher-priority context waits; nothing in user space shortens one stall. What the server does is end the guilty session so it cannot hang the GPU again (Magma: event-bracketed submissions + `mgl-gpu-watch`, budget `MOBILEGL_GPU_HANG_BUDGET_MS` / `debug.mobilegl.gpu_hang_budget_ms`, default 2000; Espryt: the driver's GUILTY reset status, which it reports after the ~2 s reset only). Repro: `scripts/probes/hangclient.c` (Wayland + GL 3.3 core; `-H 60 -N 1 -E 60` hangs every 60 frames, `-H -1` is a frame-gap observer; build with wayland-scanner's xdg-shell files, `-lwayland-client -lwayland-egl -lEGL -lOpenGL -lm`), and `gpuprobe.c` (NDK, plain adb shell; `gpuprobe 30 high` is a high-priority GLES context outside MobileGL - it both measures the device-wide stall and forces the 10 s preemption path).
Chrome: `bash scripts/chrome-launch.sh <tag> [flags]` (log `/tmp/mgl-chrome-<tag>.client.log`, screenshot `ch-<tag>.png`).
Probes: `scripts/probes/texfmt.c` (texture formats keep alpha?), `dmahash.c` (hash a process's dma-bufs); build in the container, e.g. `gcc -O1 /root/texfmt.c -o /usr/local/bin/mgl-texfmt -lEGL`, run with `mgrun offscreen`.
A result counts only if ALL hold:
- client log says `presented through linux-dmabuf shared images` (not `wl_shm`; `could not be presented through a linux-dmabuf shared image` = fell back);
@@ -149,8 +144,6 @@ Reference (glmark2-es2-wayland 1280x720, zero-copy vs wl_shm): Espryt 187 vs 49,
| Native crashes | `adb logcat -b crash -d`; container `coredumpctl list` |
| Session / KWin stderr | container `journalctl -u desktop-session --no-pager`, `journalctl --no-pager --since -2min \| grep kwin_wayland` |
| Display daemon | `/data/local/tmp/anland-mobilegl/display-daemon.log` |
| Desktop start/stop (app's su script) | `/data/local/tmp/anland-mobilegl/desktop.log`, `container-start.log`; logcat `-s AnlandMobileGL` |
| Session wait / backend sync | container `journalctl -u desktop-session --no-pager` ("waiting for the MobileGL server ...") |
`MOBILEGL_LOG_FILE_PATH=/tmp/x.log` produces `/tmp/x.client.log` (and `.server.log` for forwarded lines); files are truncated on open, so one base per process. Client builds log at INFO. Symbolize server frames with `$ANDROID_NDK/toolchains/llvm/prebuilt/windows-x86_64/bin/llvm-addr2line.exe -Cfe build-android/libMobileGL.so <offset>`.
@@ -158,10 +151,10 @@ Reference (glmark2-es2-wayland 1280x720, zero-copy vs wl_shm): Espryt 187 vs 49,
- **pkill -f self-match**: a `ct.sh`/`droidspaces run bash -lc "<script>"` process carries the script in its argv; `pkill -f chrome` kills the runner. Use `pkill -x`.
- **Root-owned /tmp files**: a log created by a root-run client cannot be reopened by swung0x48 later (no log appears). `rm -f` it as root first.
- **Sticky Plasma software renderer**: after any server crash Plasma writes `[QtQuickRendererSettings] SceneGraphBackend=software` into `~swung0x48/.config/kdeglobals`; plasmashell then renders on the CPU and screenshots still look fine (tray icon "正在使用的软件渲染器"). `mobilegl-startup.sh plasma` deletes it at every session start; within a running session that hit a crash, restart the session (`run-plasma.sh`) before any verdict.
- **Sticky Plasma software renderer**: after any server crash Plasma writes `[QtQuickRendererSettings] SceneGraphBackend=software` into `~swung0x48/.config/kdeglobals`; plasmashell then renders on the CPU and screenshots still look fine (tray icon "正在使用的软件渲染器"). Delete before any verdict: `sudo -u swung0x48 kwriteconfig6 --file kdeglobals --group QtQuickRendererSettings --key SceneGraphBackend --delete` (cyc.sh does it), restart the session.
- **Lock screen**: autolock is off (`kscreenlockerrc [Daemon] Autolock=false`); a real lock can only be left by typing the password (logind lock/unlock is not supported for this session type - `device/unlock.sh` is unverified). Test the greeter with `/usr/lib/kscreenlocker_greet --testing` and kill it.
- **CRLF**: `core.autocrlf=true` here; anland's backend sources and `sync-build-kwin.sh` are CRLF in the Windows checkout. Strip CR before anything runs on Linux/Android (`tr -d '\r'`; `ct.sh`, `push-tools.sh`, `kwin-stage.sh` do). This skill has a `.gitattributes` forcing LF.
- **Display daemon**: the app starts it; the session's `wait` step keeps KWin from starting without it (a KWin that cannot reach it logs "failed to connect to display daemon at /run/anland-mobilegl/display.sock" and exits in ~3 s). Anything started from the app's `su` must leave the app's cgroup (`echo $$ > /sys/fs/cgroup/cgroup.procs`) or a force-stop kills it.
- **Display daemon not auto-started** after reboot: KWin logs "failed to connect to display daemon at /run/anland-mobilegl/display.sock" and the session exits in ~3 s.
- **Device power/connection**: low battery or the screen turning off (30 s default) can kill the SurfaceView - `svc power stayon true`; wireless adb `ip:port` changes per pairing - never pin `-s HA27Q3LQ`, use `ANDROID_SERIAL` if several devices are attached.
- **Container vs phone paths**: container `/tmp` is a different place from the phone's `/data/local/tmp`; move files via `/mnt/Droidspaces/arch-kde-mgl/root` (container `/root`) or `/data/local/tmp/anland-mobilegl` (= container `/run/anland-mobilegl`).
- **Never overwrite a mapped .so in place** (container or APK while running): copy to a new inode and `mv -f`; the APK swap force-stops the app first.
@@ -72,7 +72,7 @@ bash scripts/build-android.sh # -> <worktree>/build-android/libMobileGL
```
The script runs, with the NDK toolchain:
```
-DANDROID_ABI=arm64-v8a -DANDROID_PLATFORM=android-30 -DCMAKE_BUILD_TYPE=RelWithDebInfo
-DANDROID_ABI=arm64-v8a -DANDROID_PLATFORM=android-26 -DCMAKE_BUILD_TYPE=RelWithDebInfo
-DMOBILEGL_PIPE_PUSH=ON -DMOBILEGL_BUILD_DISAGGREGATED=ON -DMOBILEGL_BUILD_DISAGGREGATED_INPROC=ON
-DMOBILEGL_BUILD_TEST=OFF -DMOBILEGL_BUILD_BENCHMARK=OFF
```
@@ -81,8 +81,7 @@ APK, from anland `consumers/anland_v5/android_consumer` (details in its `MOBILEG
```sh
mkdir -p dist/arm64-v8a && cp <worktree>/build-android/libMobileGL.so dist/arm64-v8a/
MOBILEGL_DIST=$PWD/dist ./gradlew :app:assemblePlainDebug \
-PanlandNdkVersion=27.2.12479018 -PmobileglApplicationId=com.anland.consumer.mobilegl \
-PanlandDefaultSocket=/data/local/tmp/anland-mobilegl/display.sock
-PanlandNdkVersion=27.2.12479018 -PmobileglApplicationId=com.anland.consumer.mobilegl
adb install -r app/build/outputs/apk/plain/debug/app-plain-debug.apk
```
- **Grant root:** the app needs root for its helper; approve it in KernelSU.
@@ -135,26 +134,14 @@ The MobileGL session runs a rebuilt KWin from `/opt/mobilegl/kwin`, so the packa
## 7. Bring it up
Nothing has to be started by hand, and the order no longer matters: **open the app** (its launcher
icon, or `am start -n com.anland.consumer.mobilegl/com.anland.consumer.MainActivity` with no extras).
That is the single trigger. The app starts its foreground service and runs its bundled
`mobilegl-desktop.sh up` as root, which:
1. starts the display daemon if it is not running;
2. publishes the backend (the app setting "Renderer backend", default DirectGLES) to
`/data/local/tmp/anland-mobilegl/backend`;
3. starts the container if it is stopped;
4. starts `desktop-session`, which waits for the server and the daemon socket, copies the backend into
`/etc/mobilegl/backend` and runs Plasma.
Until the app-driven auto-start lands, the order matters:
1. **Backend:** `setprop debug.mobilegl.backend DirectVulkan`; it must match `/etc/mobilegl/backend`.
2. **App:** start it with `--es socket_path /data/local/tmp/anland-mobilegl/display.sock`.
3. **Container:** start it.
4. **Display daemon:** start the MobileGL daemon instance.
5. **Plasma:** `run-plasma.sh`.
Cold start to a desktop takes about 8-12 s. `scripts/device/bringup.sh` wakes the phone, dismisses the
keyguard, opens the app and prints the timeline. To change the backend, use the app setting and then
Stop desktop and reopen, or run `scripts/device/switch.sh DirectGLES|DirectVulkan`. Do not use
`setprop debug.mobilegl.backend`: it overrides the setting until the next reboot. **Stop desktop**
(the notification action) stops the session and the container.
**After a phone reboot:** wireless adb does not come back by itself. Re-enable it on the phone
(Developer options > Wireless debugging), then `adb connect <ip>:<port>`; the port changes. After
that, open the app as above. See SKILL.md "Starting, idling, stopping".
`scripts/device/bringup.sh [DirectVulkan|DirectGLES]` does all five. See SKILL.md "Bring-up after a phone reboot".
## 8. Verify
@@ -4,8 +4,7 @@
# llvm-addr2line, it is what cyc.sh pushes). Stamp = worktree HEAD, so the container client
# (xbuild.sh, same stamp) and the server agree on the build ("compatible wire with different build"
# WARN otherwise). Env: MGL_WORKTREE, ANDROID_NDK, BUILD_DIR (default build-android), JOBS (12).
# Log level is compiled to INFO. android-30 = the APK's minSdk: thread_local is then the platform's
# own TLS rather than the emulated one (which cost 7-12% of an apply thread on the API 26 build).
# Log level is compiled to INFO.
set -euo pipefail
. "$(dirname "$0")/env.sh"
W=$MGL_WORKTREE
@@ -13,7 +12,7 @@ B=$W/${BUILD_DIR:-build-android}
STAMP=$(git -C "$W" rev-parse HEAD)
if [ ! -f "$B/build.ninja" ]; then
cmake -S "$W" -B "$B" -G Ninja -DCMAKE_TOOLCHAIN_FILE="$ANDROID_NDK/build/cmake/android.toolchain.cmake" \
-DANDROID_ABI=arm64-v8a -DANDROID_PLATFORM=android-30 -DCMAKE_BUILD_TYPE=RelWithDebInfo \
-DANDROID_ABI=arm64-v8a -DANDROID_PLATFORM=android-26 -DCMAKE_BUILD_TYPE=RelWithDebInfo \
-DMOBILEGL_PIPE_PUSH=ON -DMOBILEGL_BUILD_DISAGGREGATED=ON -DMOBILEGL_BUILD_DISAGGREGATED_INPROC=ON \
-DMOBILEGL_BUILD_TEST=OFF -DMOBILEGL_BUILD_BENCHMARK=OFF \
-DCMAKE_CXX_FLAGS=-DMOBILEGL_LOG_ACTIVE_LEVEL=MOBILEGL_LOG_LEVEL_INFO \
@@ -1,14 +1,10 @@
#!/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), 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, in-process GPU), client
# log /tmp/mgl-chrome-<tag>.client.log, then print its "presented through" line and save a screenshot
# to $ANL_DIR/ch-<tag>.png. Kills the running chrome first (pkill -x, never -f). MobileGL is the
# container's system-wide vendor (10_mobilegl.json + /etc/mobilegl/client.conf), so only the log is set here.
# Env: WAIT (s before checking, default 20), CHANNEL (ct.sh channel, default chrome),
# 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.
# Env: WAIT (s before checking, default 20), CHANNEL (ct.sh channel, default chrome).
set -euo pipefail
here=$(cd "$(dirname "$0")" && pwd)
. "$here/env.sh"
@@ -16,8 +12,7 @@ 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)
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 &'
sudo -u $MGL_DESKTOP_USER env XDG_RUNTIME_DIR=/run/user/\$U WAYLAND_DISPLAY=wayland-0 DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/\$U/bus MOBILEGL_LOG_FILE_PATH=/tmp/mgl-chrome-$TAG.log bash -c 'nohup /opt/mobilegl/bin/mobilegl-startup.sh chrome --restore-last-session $* > /tmp/chrome-$TAG-out.log 2>&1 &'
sleep ${WAIT:-20}
grep -ah 'presented through' /tmp/mgl-chrome-$TAG.client.log | head -3
IN
@@ -1,146 +0,0 @@
#!/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"
@@ -1,94 +0,0 @@
#!/usr/bin/env bash
# desktop-verify.sh <phase>... - check that the MobileGL desktop starts, idles and stops by itself
# (anland app: foreground service + mobilegl-desktop.sh; container: desktop-session.service).
# Phases run in the order given; screenshots go to $ANL_DIR/dv-<phase>.png.
#
# push install device/*.sh into $DEV_TOOLS (push-tools.sh's device half)
# reset everything down: app force-stopped (its service with it), container stopped,
# experiment display daemon killed - the state after a phone reboot
# cold reset, then open the app like its icon does and time each piece (desktop-timeline.sh)
# open open the app without resetting (after a reboot: the reboot was the reset)
# chrome (re)start Chrome in the session on an animated WebGL page (kills a running Chrome)
# idle CPU/GPU for visible, hidden (HOME), locked (screen off), visible again (measure.sh)
# reopen swipe the app away (remove its task), check KWin survives, open it again, time it
# stop Stop desktop from the notification (the service's STOP action) and check it all ends
# rtest lock/unlock + window resize regression ($ANL_DIR/rtest.sh)
# Env: SECS (idle window, default 20), URL (chrome page).
set -euo pipefail
here=$(cd "$(dirname "$0")" && pwd)
. "$here/env.sh"
SECS=${SECS:-20}
URL=${URL:-https://webglsamples.org/aquarium/aquarium.html}
SOCK=$DEV_SHARE/display.sock
su_() { adb_ shell "su -c '$*'"; }
shot() {
su_ "screencap -p $DEV_SHARE/dv-$1.png"
adb_ pull "$DEV_SHARE/dv-$1.png" "$ANL_DIR/dv-$1.png" > /dev/null && echo "screenshot $ANL_DIR/dv-$1.png"
}
kwin_log() { # the anland backend's lines since <time>
printf '%s\n' "journalctl --no-pager --since '$1' 2>/dev/null | grep -a -E 'viewer (gone|back)|consumer (reconnected|disconnected)|failed to connect' | tail -${2:-8}" |
bash "$here/ct.sh" dv 2>/dev/null | grep -v pushed || true
}
task_id() {
su_ "am stack list" | tr -d '\r' | grep -m1 "$MGL_PKG/" | sed -n 's/.*taskId=\([0-9]*\).*/\1/p'
}
wake() {
su_ "input keyevent KEYCODE_WAKEUP"; sleep 1; su_ "wm dismiss-keyguard"; sleep 2
}
for phase in "$@"; do
echo "=== $phase"
case $phase in
push)
for f in "$here"/device/*.sh; do
tr -d '\r' < "$f" > "$ANL_DIR/push.tmp"
adb_ push "$ANL_DIR/push.tmp" "$DEV_TOOLS/$(basename "$f")" > /dev/null
done
rm -f "$ANL_DIR/push.tmp"; echo "device scripts in $DEV_TOOLS" ;;
reset)
su_ "sh $DEV_TOOLS/desktop-reset.sh" ;;
cold)
bash "$0" reset
wake
su_ "sh $DEV_TOOLS/desktop-timeline.sh 240"
sleep 3; shot cold ;;
open)
wake
su_ "sh $DEV_TOOLS/desktop-timeline.sh 300"
sleep 3; shot open ;;
chrome)
WAIT=15 bash "$here/chrome-launch.sh" dv "$URL" ;;
idle)
su_ "sh $DEV_TOOLS/measure.sh visible $SECS"
t=$(date -u '+%Y-%m-%d %H:%M:%S UTC')
su_ "input keyevent KEYCODE_HOME"; sleep 4
su_ "sh $DEV_TOOLS/measure.sh hidden $SECS"
su_ "am start -n $MGL_PKG/com.anland.consumer.MainActivity >/dev/null"; sleep 5
su_ "input keyevent KEYCODE_SLEEP"; sleep 4
su_ "sh $DEV_TOOLS/measure.sh locked $SECS"
wake
su_ "am start -n $MGL_PKG/com.anland.consumer.MainActivity >/dev/null"; sleep 5
su_ "sh $DEV_TOOLS/measure.sh visible2 $SECS"
shot idle
kwin_log "$t" 12 ;;
reopen)
t=$(date -u '+%Y-%m-%d %H:%M:%S UTC')
id=$(task_id); echo "removing task $id"
[ -n "$id" ] && su_ "am stack remove $id"
sleep 8
su_ "echo server: \$(pidof $MGL_PKG:mobilegl) ui: \$(pidof $MGL_PKG) kwin: \$(pidof kwin_wayland) plasmashell: \$(pidof plasmashell)"
su_ "sh $DEV_TOOLS/measure.sh closed 10"
su_ "sh $DEV_TOOLS/desktop-timeline.sh 120"
sleep 3; shot reopen
kwin_log "$t" ;;
stop)
su_ "am startservice -n $MGL_PKG/com.anland.consumer.MobileGLWorker -a com.anland.consumer.mobilegl.STOP" || true
sleep 25
su_ "echo server: \$(pidof $MGL_PKG:mobilegl) ui: \$(pidof $MGL_PKG); $DS_BIN show"
su_ "tail -3 $DEV_SHARE/desktop.log" ;;
rtest)
bash "$ANL_DIR/rtest.sh" dv ;;
*)
echo "unknown phase $phase" >&2; exit 2 ;;
esac
done
@@ -1,7 +1,29 @@
# bringup.sh - (Android root shell) bring the MobileGL desktop up after a phone reboot. There is
# nothing left to do by hand: opening the anland app (its launcher icon, or this am start) starts
# the display daemon, the MobileGL server, the container and its Plasma session. Prints the timeline.
# Run: su -c "sh /data/local/tmp/anl/bringup.sh" Env: as desktop-timeline.sh.
input keyevent KEYCODE_WAKEUP
wm dismiss-keyguard
sh "$(dirname "$0")/desktop-timeline.sh" 300
# bringup.sh [DirectGLES|DirectVulkan] - (Android root shell) bring the stack up after a phone reboot:
# stay-awake, container, backend property, experiment display daemon, anland app, then the Plasma
# session (run-plasma.sh, ~90 s; skip with NO_PLASMA=1). The backend defaults to the container's
# /etc/mobilegl/backend (persists across reboots; the property does not).
# Assembled from the documented manual steps; not exercised as one unit yet. Re-running restarts the
# daemon, the app and the session. Run: su -c "sh /data/local/tmp/anl/bringup.sh"
# Env: PKG, CONTAINER, DS, SOCK, TOOLS (dir holding run-plasma.sh / restart-daemon.sh; default: this dir).
D=${DS:-/data/local/Droidspaces/bin/droidspaces}
P=${PKG:-com.anland.consumer.mobilegl}
C=${CONTAINER:-arch-kde-mgl}
SOCK=${SOCK:-/data/local/tmp/anland-mobilegl/display.sock}
T=${TOOLS:-$(dirname $0)}
svc power stayon true
if $D show 2>/dev/null | grep -q " $C "; then
echo "container $C already running"
else
$D -C /data/local/Droidspaces/Containers/$C/container.config start
sleep 5
fi
B=${1:-$(cat /mnt/Droidspaces/$C/etc/mobilegl/backend 2>/dev/null)}
B=${B:-DirectGLES}
setprop debug.mobilegl.backend $B
echo "$B" > /mnt/Droidspaces/$C/etc/mobilegl/backend
echo "backend: $(getprop debug.mobilegl.backend)"
sh $T/restart-daemon.sh
am start -n $P/com.anland.consumer.MainActivity --es socket_path $SOCK >/dev/null
sleep 3
if pidof $P:mobilegl >/dev/null; then echo "server process $P:mobilegl up"; else echo "WARNING: $P:mobilegl not running"; fi
[ "${NO_PLASMA:-0}" = 1 ] || sh $T/run-plasma.sh
@@ -1,17 +0,0 @@
# desktop-reset.sh - (Android root shell) take the MobileGL desktop fully down, as after a phone
# reboot: the app force-stopped (its foreground service and server with it), the container
# stopped, the experiment display daemon killed. Leaves the original anland daemon alone.
# Run: su -c "sh /data/local/tmp/anl/desktop-reset.sh" Env: PKG, CONTAINER, SOCK, DS.
P=${PKG:-com.anland.consumer.mobilegl}
C=${CONTAINER:-arch-kde-mgl}
SOCK=${SOCK:-/data/local/tmp/anland-mobilegl/display.sock}
D=${DS:-/data/local/Droidspaces/bin/droidspaces}
am force-stop $P
$D --name=$C stop > /dev/null 2>&1
for p in $(pidof display_daemon); do
tr '\0' ' ' < /proc/$p/cmdline | grep -qF " $SOCK " && kill $p
done
rm -f $SOCK
sleep 2
echo "app: $(pidof $P) server: $(pidof $P:mobilegl) daemon: $(ls $SOCK 2>/dev/null)"
$D show
@@ -1,30 +0,0 @@
# desktop-timeline.sh [timeout-s] - (Android root shell) open the anland app the way its launcher
# icon does (am start, no extras) and print when each piece of the MobileGL desktop comes up,
# in seconds after the open: display daemon socket, the app's MobileGL server listening, the
# container, kwin_wayland, plasmashell, and the splash (ksplashqml) gone = desktop on screen.
# Pieces that already run show 0.0. Read-only apart from the am start.
# Run: su -c "sh /data/local/tmp/anl/desktop-timeline.sh 180" Env: PKG, CONTAINER, SOCK, DS.
T=${1:-180}
P=${PKG:-com.anland.consumer.mobilegl}
C=${CONTAINER:-arch-kde-mgl}
SOCK=${SOCK:-/data/local/tmp/anland-mobilegl/display.sock}
D=${DS:-/data/local/Droidspaces/bin/droidspaces}
now() { awk '{print $1}' /proc/uptime; }
since() { awk -v a="$1" -v b="$(now)" 'BEGIN{printf "%.1f", b - a}'; }
listening() { grep -q '00010000 0001 01 [0-9]* @anland-mobilegl$' /proc/net/unix; }
t0=$(now)
am start -n $P/com.anland.consumer.MainActivity > /dev/null
for k in daemon server container kwin shell splash_seen shown; do eval "t_$k="; done
while :; do
[ -z "$t_daemon" ] && [ -S "$SOCK" ] && t_daemon=$(since $t0) && echo "daemon socket +${t_daemon}s"
[ -z "$t_server" ] && listening && t_server=$(since $t0) && echo "server listening +${t_server}s"
[ -z "$t_container" ] && [ -n "$($D --name=$C pid 2>/dev/null | tr -dc 0-9)" ] && t_container=$(since $t0) && echo "container up +${t_container}s"
[ -z "$t_kwin" ] && pidof kwin_wayland > /dev/null && t_kwin=$(since $t0) && echo "kwin_wayland +${t_kwin}s"
[ -z "$t_shell" ] && pidof plasmashell > /dev/null && t_shell=$(since $t0) && echo "plasmashell +${t_shell}s"
[ -z "$t_splash_seen" ] && pidof ksplashqml > /dev/null && t_splash_seen=1
if [ -n "$t_shell" ] && [ -z "$t_shown" ] && ! pidof ksplashqml > /dev/null; then
t_shown=$(since $t0); echo "splash gone +${t_shown}s (desktop on screen)"; break
fi
[ "$(since $t0 | cut -d. -f1)" -ge "$T" ] && { echo "TIMEOUT after ${T}s"; break; }
sleep 0.3
done
@@ -1,47 +0,0 @@
# measure.sh <label> [seconds] - (Android root shell) CPU and GPU load of the MobileGL desktop over a
# window: % of ONE core (so 800 = all 8 cores) for the whole phone, KWin (+Xwayland), plasmashell,
# Chrome (all its processes), the app's :mobilegl server and its UI process, plus the mean of the
# kgsl gpu_busy_percentage samples (1/s). The container's processes are visible from Android's
# /proc (Droidspaces only gives them their own pid namespace).
# Run: su -c "sh /data/local/tmp/anl/measure.sh visible 20" Env: PKG.
L=${1:-sample}
N=${2:-20}
P=${PKG:-com.anland.consumer.mobilegl}
GPU=/sys/class/kgsl/kgsl-3d0/gpu_busy_percentage
pids_named() { # exact process names (comm or argv0 basename)
for n in "$@"; do pidof "$n"; done
}
pids_matching() { # argv contains the word
for d in /proc/[0-9]*; do
{ tr '\0' ' ' < $d/cmdline; } 2>/dev/null | grep -q "$1" && echo ${d#/proc/}
done
}
ticks() { # utime+stime of the pids, in clock 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; }
KW="$(pids_named kwin_wayland Xwayland)"
SH="$(pids_named plasmashell)"
CH="$(pids_matching /opt/google/chrome/)"
SV="$(pidof $P:mobilegl)"
UI="$(pidof $P)"
a0=$(total); k0=$(ticks $KW); s0=$(ticks $SH); c0=$(ticks $CH); v0=$(ticks $SV); u0=$(ticks $UI)
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); k1=$(ticks $KW); s1=$(ticks $SH); c1=$(ticks $CH); v1=$(ticks $SV); u1=$(ticks $UI)
# CLK_TCK is 100: ticks per second == percent of one core.
pct() { echo $(( ($2 - $1) / N )); }
printf '%-10s %3ss phone %4s%% kwin %3s%% plasmashell %3s%% chrome %3s%% server %3s%% app-ui %3s%% gpu %3s%%\n' \
"$L" "$N" "$(pct $a0 $a1)" "$(pct $k0 $k1)" "$(pct $s0 $s1)" "$(pct $c0 $c1)" "$(pct $v0 $v1)" "$(pct $u0 $u1)" "$((g / N))"
@@ -1,25 +1,24 @@
# run-plasma.sh - (Android root shell) DEVELOPER restart of the whole MobileGL desktop, e.g. after a
# server, client or KWin rebuild: ends the Plasma session (and the user's logind session, which takes
# a while to wind down), then restarts the anland app; opening it brings up the server, starts
# desktop-session.service again and the session waits for the server. Normal use needs none of this:
# opening the app is enough. ~60 s. Prints the unit status, plasma user units and recent coredumps.
# Run: su -c "sh /data/local/tmp/anl/run-plasma.sh"
# Env: PKG, CONTAINER, DESKTOP_USER (swung0x48), DS (droidspaces binary).
# run-plasma.sh - (Android root shell) restart the anland app and the container's Plasma session
# (desktop-session.service -> mobilegl-startup.sh plasma). Takes ~90 s (two 40 s waits: logind must
# finish tearing the old user session down before the new one starts). Prints the unit status, the
# plasma user units and recent coredumps. Run: su -c "sh /data/local/tmp/anl/run-plasma.sh"
# Env: PKG, CONTAINER, DESKTOP_USER (swung0x48), SOCK, DS (droidspaces binary).
D=${DS:-/data/local/Droidspaces/bin/droidspaces}
P=${PKG:-com.anland.consumer.mobilegl}
C=${CONTAINER:-arch-kde-mgl}
U=${DESKTOP_USER:-swung0x48}
SOCK=${SOCK:-/data/local/tmp/anland-mobilegl/display.sock}
am force-stop $P
am start -n $P/com.anland.consumer.MainActivity --es socket_path $SOCK >/dev/null
sleep 3
$D --name=$C run bash -lc "
systemctl stop desktop-session.service 2>/dev/null
loginctl terminate-user $U 2>/dev/null; sleep 30
loginctl terminate-user $U 2>/dev/null; sleep 40
systemctl reset-failed desktop-session.service
rm -f /tmp/mobilegl-compositor.log
date +%s > /tmp/plasma-start
"
am force-stop $P
am start -n $P/com.anland.consumer.MainActivity > /dev/null
sleep 30
$D --name=$C run bash -lc "
systemctl start desktop-session.service
sleep 40
systemctl --no-pager status desktop-session.service | head -8
UID_=\$(id -u $U)
sudo -u $U XDG_RUNTIME_DIR=/run/user/\$UID_ systemctl --user --no-pager list-units --all 'plasma*' 2>&1 | head -30
@@ -5,8 +5,7 @@ P=${PKG:-com.anland.consumer.mobilegl}
C=${CONTAINER:-arch-kde-mgl}
SOCK=${SOCK:-/data/local/tmp/anland-mobilegl/display.sock}
echo "battery: $(dumpsys battery | grep ' level:' | tr -d ' ') $(dumpsys power | grep -o 'mStayOn=[a-z]*')"
echo "backend: app setting=$(cat /data/data/$P/files/mobilegl-backend 2>/dev/null || echo 'DirectGLES (default)') published=$(cat ${SOCK%/*}/backend 2>/dev/null) container /etc/mobilegl/backend=$(cat /mnt/Droidspaces/$C/etc/mobilegl/backend 2>/dev/null) prop override=$(getprop debug.mobilegl.backend)"
echo "desktop service log: $(tail -1 ${SOCK%/*}/desktop.log 2>/dev/null)"
echo "prop debug.mobilegl.backend=$(getprop debug.mobilegl.backend) container /etc/mobilegl/backend=$(cat /mnt/Droidspaces/$C/etc/mobilegl/backend 2>/dev/null)"
echo "app pid: $(pidof $P) server (:mobilegl) pid: $(pidof $P:mobilegl)"
ps -A -o PID,ARGS | grep "display_daemon $SOCK" | grep -v grep || echo "experiment display daemon NOT running"
$D show
@@ -1,17 +1,15 @@
# switch.sh <DirectGLES|DirectVulkan> - (Android root shell) change the MobileGL backend the anland
# app's server runs (Espryt = DirectGLES, Magma = DirectVulkan). The choice is the app's setting
# (Settings > Connection > MobileGL desktop, saved in the app's files/mobilegl-backend); this does
# what a user does there: save it, Stop desktop, open the app again. The new server publishes the
# backend and the container's session copies it to /etc/mobilegl/backend before it starts, so
# server and clients agree. ~30-60 s. No setprop: debug.mobilegl.backend, if set, still overrides
# the setting until the next reboot - this clears it.
# Env: PKG, SOCK.
# switch.sh <DirectGLES|DirectVulkan> - (Android root shell) select the server backend: Espryt =
# DirectGLES, Magma = DirectVulkan. Sets the system property the server reads (lost on reboot), writes
# the container's /etc/mobilegl/backend (what every client and the KWin drop-in report; it must match or
# the server refuses the client: "Hello.backendType disagrees with pinned backend"), restarts the app.
# The running Plasma session still speaks the old backend: run run-plasma.sh afterwards.
# Env: PKG, CONTAINER (arch-kde-mgl), SOCK (display daemon socket).
B=${1:?usage: switch.sh DirectGLES|DirectVulkan}
P=${PKG:-com.anland.consumer.mobilegl}
[ -n "$(getprop debug.mobilegl.backend)" ] && setprop debug.mobilegl.backend ""
if pidof $P:mobilegl > /dev/null; then
am startservice -n $P/com.anland.consumer.MobileGLWorker -a com.anland.consumer.mobilegl.STOP > /dev/null
i=0; while pidof $P:mobilegl > /dev/null && [ $i -lt 60 ]; do sleep 1; i=$((i + 1)); done
fi
am start -n $P/com.anland.consumer.MainActivity --es mobilegl_backend $B > /dev/null
echo "backend $B saved; the desktop is starting (watch: sh $(dirname $0)/status.sh)"
C=${CONTAINER:-arch-kde-mgl}
SOCK=${SOCK:-/data/local/tmp/anland-mobilegl/display.sock}
setprop debug.mobilegl.backend $B
echo $B > /mnt/Droidspaces/$C/etc/mobilegl/backend
am force-stop $P
am start -n $P/com.anland.consumer.MainActivity --es socket_path $SOCK >/dev/null
sleep 4
@@ -1,47 +0,0 @@
# 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"
@@ -1,146 +0,0 @@
#!/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" ]
@@ -27,7 +27,7 @@ for f in "$K"/anland_backend_Arch_v5/src/backends/anland/*; do
lf "$f" "$st/kwsync/anland_backend_Arch_v5/src/backends/anland/$b"
lf "$f" "$st/kwin-sync/anland/$b"
done
for f in kwin.patch mobilegl-startup.sh desktop-session-mobilegl.conf; do
for f in kwin.patch mobilegl-startup.sh; do
lf "$K/Arch_v5/$f" "$st/kwsync/Arch_v5/$f"
lf "$K/Arch_v5/$f" "$st/kwin-sync/misc/$f"
done
@@ -1,94 +0,0 @@
#!/usr/bin/env python3
# cdpmedia.py [port] [seconds] - ask a Chrome started with --remote-debugging-port=<port> (and a
# non-default --user-data-dir) which video decoder its first page's players use, and evaluate
# `window.__mglStats` / the element `#t` text of the page. Standard library only (no websocket
# module in the container): a minimal RFC 6455 client.
# python3 cdpmedia.py 9333 6
# Prints kVideoDecoderName / kIsPlatformVideoDecoder / kVideoTracks properties and media errors as
# they arrive, then the page's stats text.
import base64, json, os, socket, struct, sys, time, urllib.request
port = int(sys.argv[1]) if len(sys.argv) > 1 else 9333
seconds = float(sys.argv[2]) if len(sys.argv) > 2 else 6.0
targets = json.load(urllib.request.urlopen(f"http://127.0.0.1:{port}/json"))
page = next(t for t in targets if t.get("type") == "page")
url = page["webSocketDebuggerUrl"]
path = url.split(f"127.0.0.1:{port}", 1)[1]
sock = socket.create_connection(("127.0.0.1", port))
key = base64.b64encode(os.urandom(16)).decode()
sock.sendall((f"GET {path} HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n"
f"Sec-WebSocket-Key: {key}\r\nSec-WebSocket-Version: 13\r\n\r\n").encode())
response = b""
while b"\r\n\r\n" not in response:
response += sock.recv(4096)
buffer = response.split(b"\r\n\r\n", 1)[1]
def send(message):
data = json.dumps(message).encode()
header = bytes([0x81])
mask = os.urandom(4)
if len(data) < 126:
header += bytes([0x80 | len(data)])
elif len(data) < 65536:
header += bytes([0x80 | 126]) + struct.pack(">H", len(data))
else:
header += bytes([0x80 | 127]) + struct.pack(">Q", len(data))
sock.sendall(header + mask + bytes(b ^ mask[i % 4] for i, b in enumerate(data)))
def recv_exact(n):
global buffer
while len(buffer) < n:
chunk = sock.recv(65536)
if not chunk:
raise EOFError
buffer += chunk
out, buffer = buffer[:n], buffer[n:]
return out
def recv():
first, second = recv_exact(2)
length = second & 0x7F
if length == 126:
length = struct.unpack(">H", recv_exact(2))[0]
elif length == 127:
length = struct.unpack(">Q", recv_exact(8))[0]
payload = recv_exact(length)
return json.loads(payload) if first & 0x0F == 1 else None
send({"id": 1, "method": "Media.enable"})
# Players created before the domain was enabled report nothing: reload so the page makes new ones.
if os.environ.get("CDP_NAVIGATE"):
send({"id": 3, "method": "Page.navigate", "params": {"url": os.environ["CDP_NAVIGATE"]}})
elif os.environ.get("CDP_RELOAD", "1") == "1":
send({"id": 3, "method": "Page.reload"})
deadline = time.time() + seconds
sock.settimeout(0.5)
seen = set()
while time.time() < deadline:
try:
message = recv()
except socket.timeout:
continue
if not message or "method" not in message:
continue
if message["method"] == "Media.playerPropertiesChanged":
for prop in message["params"]["properties"]:
if prop["name"] in ("kVideoDecoderName", "kIsPlatformVideoDecoder", "kVideoTracks", "kResolution"):
line = f"{prop['name']} = {prop['value']}"
if line not in seen:
seen.add(line)
print(line)
elif message["method"] in ("Media.playerErrorsRaised",):
print("media error:", json.dumps(message["params"])[:300])
send({"id": 2, "method": "Runtime.evaluate",
"params": {"expression": os.environ.get("CDP_EXPR", "(document.getElementById('t')||{}).textContent"), "returnByValue": True}})
sock.settimeout(3)
while True:
message = recv()
if message and message.get("id") == 2:
print("page:", message.get("result", {}).get("result", {}).get("value"))
break
@@ -1,55 +0,0 @@
// gpuprobe - a plain Android process (outside MobileGL) that measures whether the GPU keeps executing
// other contexts' work: a pbuffer GLES context clears + draws and glFinish()es every ~10 ms, printing any
// round trip over 50 ms with a CLOCK_REALTIME timestamp. Usage: gpuprobe <seconds> [priority: low|med|high]
#include <EGL/egl.h>
#include <EGL/eglext.h>
#include <GLES3/gl3.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#ifndef EGL_CONTEXT_PRIORITY_LEVEL_IMG
#define EGL_CONTEXT_PRIORITY_LEVEL_IMG 0x3100
#define EGL_CONTEXT_PRIORITY_HIGH_IMG 0x3101
#define EGL_CONTEXT_PRIORITY_MEDIUM_IMG 0x3102
#define EGL_CONTEXT_PRIORITY_LOW_IMG 0x3103
#endif
static double now_ms(void) { struct timespec ts; clock_gettime(CLOCK_REALTIME, &ts); return ts.tv_sec * 1e3 + ts.tv_nsec / 1e6; }
int main(int argc, char** argv) {
int seconds = argc > 1 ? atoi(argv[1]) : 20;
EGLint prio = EGL_CONTEXT_PRIORITY_MEDIUM_IMG;
if (argc > 2 && !strcmp(argv[2], "high")) prio = EGL_CONTEXT_PRIORITY_HIGH_IMG;
if (argc > 2 && !strcmp(argv[2], "low")) prio = EGL_CONTEXT_PRIORITY_LOW_IMG;
setvbuf(stdout, NULL, _IOLBF, 0);
EGLDisplay d = eglGetDisplay(EGL_DEFAULT_DISPLAY);
eglInitialize(d, NULL, NULL);
const EGLint ca[] = {EGL_SURFACE_TYPE, EGL_PBUFFER_BIT, EGL_RENDERABLE_TYPE, EGL_OPENGL_ES3_BIT, EGL_RED_SIZE, 8, EGL_NONE};
EGLConfig c; EGLint n;
eglChooseConfig(d, ca, &c, 1, &n);
const EGLint pa[] = {EGL_WIDTH, 256, EGL_HEIGHT, 256, EGL_NONE};
EGLSurface s = eglCreatePbufferSurface(d, c, pa);
const EGLint xa[] = {EGL_CONTEXT_CLIENT_VERSION, 3, EGL_CONTEXT_PRIORITY_LEVEL_IMG, prio, EGL_NONE};
EGLContext x = eglCreateContext(d, c, EGL_NO_CONTEXT, xa);
if (x == EGL_NO_CONTEXT) { printf("no ctx 0x%x\n", eglGetError()); return 1; }
eglMakeCurrent(d, s, s, x);
EGLint got = 0; eglQueryContext(d, x, EGL_CONTEXT_PRIORITY_LEVEL_IMG, &got);
const double t0 = now_ms(); double maxRt = 0; long iters = 0, slow = 0;
printf("[probe] start %.0f prio=0x%x\n", t0, got);
while (now_ms() - t0 < seconds * 1000.0) {
const double a = now_ms();
glClearColor((iters & 1) ? 1.f : 0.f, 0.f, 0.f, 1.f);
glClear(GL_COLOR_BUFFER_BIT);
glFinish();
const double rt = now_ms() - a;
if (rt > maxRt) maxRt = rt;
if (rt > 50) { ++slow; printf("[probe] glFinish %.0f ms ending at %.0f\n", rt, now_ms()); }
++iters;
usleep(10000);
}
printf("[probe] END iters=%ld max=%.0f ms slow=%ld\n", iters, maxRt, slow);
return 0;
}
@@ -1,150 +0,0 @@
// hangclient - a Wayland xdg-toplevel, EGL + desktop GL 3.3 core client that animates and, on request,
// submits fragment work that never ends (the driver has to reset it). Prints per-frame gaps so the same
// binary measures "other app" frame pacing (frame callbacks come from the compositor) when run with -H -1.
//
// hangclient -T tag [-H hang_at_frame] [-N hang_repeat] [-I iters] [-S seconds] [-W w] [-X h] [-F]
// -H n frame at which the hanging draw is submitted (-1: never; default -1)
// -N k how many consecutive hanging frames (default 1)
// -E e re-arm a hang every e frames after the first (0: once)
// -I i loop count of the hanging shader (default 2^31-1)
// -S s run time in seconds (default 30)
// -F glFinish after every frame (puts the wait inside the client's own session)
#define GL_GLEXT_PROTOTYPES 1
#include <EGL/egl.h>
#include <EGL/eglext.h>
#include <GL/glcorearb.h>
#include <wayland-client.h>
#include <wayland-egl.h>
#include "xdg-shell-client-protocol.h"
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
static struct wl_compositor* g_comp;
static struct xdg_wm_base* g_wm;
static int g_configured, g_closed;
static int g_w = 480, g_h = 360;
static void reg_global(void* d, struct wl_registry* r, uint32_t name, const char* iface, uint32_t ver) {
(void)d;
if (!strcmp(iface, "wl_compositor")) g_comp = wl_registry_bind(r, name, &wl_compositor_interface, 4);
else if (!strcmp(iface, "xdg_wm_base")) g_wm = wl_registry_bind(r, name, &xdg_wm_base_interface, 1);
}
static void reg_remove(void* d, struct wl_registry* r, uint32_t n) { (void)d; (void)r; (void)n; }
static const struct wl_registry_listener reg_l = {reg_global, reg_remove};
static void wm_ping(void* d, struct xdg_wm_base* wm, uint32_t s) { (void)d; xdg_wm_base_pong(wm, s); }
static const struct xdg_wm_base_listener wm_l = {wm_ping};
static void xs_conf(void* d, struct xdg_surface* s, uint32_t serial) { (void)d; xdg_surface_ack_configure(s, serial); g_configured = 1; }
static const struct xdg_surface_listener xs_l = {xs_conf};
static void tl_conf(void* d, struct xdg_toplevel* t, int32_t w, int32_t h, struct wl_array* st) { (void)d; (void)t; (void)st; (void)w; (void)h; }
static void tl_close(void* d, struct xdg_toplevel* t) { (void)d; (void)t; g_closed = 1; }
static const struct xdg_toplevel_listener tl_l = {tl_conf, tl_close};
static double now_ms(void) { struct timespec ts; clock_gettime(CLOCK_REALTIME, &ts); return ts.tv_sec * 1e3 + ts.tv_nsec / 1e6; }
static GLuint sh(GLenum type, const char* src) {
GLuint s = glCreateShader(type);
glShaderSource(s, 1, &src, NULL);
glCompileShader(s);
GLint ok = 0; glGetShaderiv(s, GL_COMPILE_STATUS, &ok);
if (!ok) { char log[2048]; glGetShaderInfoLog(s, sizeof log, NULL, log); fprintf(stderr, "shader: %s\n", log); exit(2); }
return s;
}
int main(int argc, char** argv) {
const char* tag = "hc"; int hangAt = -1, hangN = 1, every = 0, seconds = 30, finish = 0; long iters = 2147483647L;
for (int i = 1; i < argc; ++i) {
if (!strcmp(argv[i], "-T") && i + 1 < argc) tag = argv[++i];
else if (!strcmp(argv[i], "-H") && i + 1 < argc) hangAt = atoi(argv[++i]);
else if (!strcmp(argv[i], "-N") && i + 1 < argc) hangN = atoi(argv[++i]);
else if (!strcmp(argv[i], "-E") && i + 1 < argc) every = atoi(argv[++i]);
else if (!strcmp(argv[i], "-I") && i + 1 < argc) iters = atol(argv[++i]);
else if (!strcmp(argv[i], "-S") && i + 1 < argc) seconds = atoi(argv[++i]);
else if (!strcmp(argv[i], "-W") && i + 1 < argc) g_w = atoi(argv[++i]);
else if (!strcmp(argv[i], "-X") && i + 1 < argc) g_h = atoi(argv[++i]);
else if (!strcmp(argv[i], "-F")) finish = 1;
}
setvbuf(stdout, NULL, _IOLBF, 0);
struct wl_display* dpy = wl_display_connect(NULL);
if (!dpy) { fprintf(stderr, "no wayland\n"); return 1; }
struct wl_registry* reg = wl_display_get_registry(dpy);
wl_registry_add_listener(reg, &reg_l, NULL);
wl_display_roundtrip(dpy);
if (!g_comp || !g_wm) { fprintf(stderr, "no compositor/xdg_wm_base\n"); return 1; }
xdg_wm_base_add_listener(g_wm, &wm_l, NULL);
struct wl_surface* surf = wl_compositor_create_surface(g_comp);
struct xdg_surface* xs = xdg_wm_base_get_xdg_surface(g_wm, surf);
xdg_surface_add_listener(xs, &xs_l, NULL);
struct xdg_toplevel* tl = xdg_surface_get_toplevel(xs);
xdg_toplevel_add_listener(tl, &tl_l, NULL);
xdg_toplevel_set_title(tl, tag);
wl_surface_commit(surf);
while (!g_configured) wl_display_dispatch(dpy);
EGLDisplay ed = eglGetPlatformDisplay(EGL_PLATFORM_WAYLAND_KHR, dpy, NULL);
if (!eglInitialize(ed, NULL, NULL)) { fprintf(stderr, "eglInitialize\n"); return 1; }
eglBindAPI(EGL_OPENGL_API);
const EGLint ca[] = {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_NONE};
EGLConfig cfg; EGLint n = 0;
if (!eglChooseConfig(ed, ca, &cfg, 1, &n) || n < 1) { fprintf(stderr, "no config\n"); return 1; }
const EGLint xa[] = {EGL_CONTEXT_MAJOR_VERSION, 3, EGL_CONTEXT_MINOR_VERSION, 3, EGL_CONTEXT_OPENGL_PROFILE_MASK, EGL_CONTEXT_OPENGL_CORE_PROFILE_BIT, EGL_NONE};
EGLContext ctx = eglCreateContext(ed, cfg, EGL_NO_CONTEXT, xa);
if (ctx == EGL_NO_CONTEXT) { fprintf(stderr, "no context 0x%x\n", eglGetError()); return 1; }
struct wl_egl_window* ew = wl_egl_window_create(surf, g_w, g_h);
EGLSurface es = eglCreatePlatformWindowSurface(ed, cfg, ew, NULL);
eglMakeCurrent(ed, es, es, ctx);
eglSwapInterval(ed, 1);
const char* vs = "#version 330 core\nlayout(location=0) in vec2 p; uniform float t; out vec2 uv;\n"
"void main(){ uv=p*0.5+0.5; gl_Position=vec4(p*0.4+vec2(0.5*sin(t),0.0),0.0,1.0);}";
const char* fs = "#version 330 core\nin vec2 uv; uniform int iters; uniform float t; out vec4 c;\n"
"void main(){ float a=uv.x; for(int i=0;i<iters;++i){ a=fract(a*1.0001+0.37+uv.y); }\n"
" c=vec4(uv, 0.5+0.5*sin(t)+a*1e-6, 1.0);}";
GLuint prog = glCreateProgram();
glAttachShader(prog, sh(GL_VERTEX_SHADER, vs));
glAttachShader(prog, sh(GL_FRAGMENT_SHADER, fs));
glLinkProgram(prog);
GLint ok = 0; glGetProgramiv(prog, GL_LINK_STATUS, &ok);
if (!ok) { fprintf(stderr, "link failed\n"); return 2; }
GLint uIt = glGetUniformLocation(prog, "iters"), uT = glGetUniformLocation(prog, "t");
GLuint vao, vbo; glGenVertexArrays(1, &vao); glBindVertexArray(vao);
const float q[] = {-1, -1, 1, -1, -1, 1, 1, 1};
glGenBuffers(1, &vbo); glBindBuffer(GL_ARRAY_BUFFER, vbo); glBufferData(GL_ARRAY_BUFFER, sizeof q, q, GL_STATIC_DRAW);
glEnableVertexAttribArray(0); glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, 0);
const double t0 = now_ms(); double last = t0, maxGap = 0; long frames = 0, gaps100 = 0;
printf("[%s] start %.0f renderer=%s hangAt=%d N=%d every=%d iters=%ld\n", tag, t0, glGetString(GL_RENDERER), hangAt, hangN, every, iters);
while (!g_closed && now_ms() - t0 < seconds * 1000.0) {
wl_display_dispatch_pending(dpy);
const double t = (now_ms() - t0) / 1000.0;
int hang = 0;
if (hangAt >= 0 && frames >= hangAt) {
long rel = frames - hangAt;
if (every > 0) rel %= every;
hang = rel < hangN;
}
glViewport(0, 0, g_w, g_h);
glClearColor(0.5f + 0.5f * (float)sin(t * 3.0), 0.2f, 0.4f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
glUseProgram(prog);
glUniform1i(uIt, hang ? (int)iters : 0);
glUniform1f(uT, (float)t);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
if (hang) printf("[%s] HANG submitted frame %ld at %.0f\n", tag, frames, now_ms());
if (finish) glFinish();
if (!eglSwapBuffers(ed, es)) printf("[%s] swap failed 0x%x at %.0f\n", tag, eglGetError(), now_ms());
const GLenum rs = glGetError();
if (rs != GL_NO_ERROR) printf("[%s] glGetError 0x%x at %.0f\n", tag, rs, now_ms());
const double nowv = now_ms(), gap = nowv - last;
last = nowv; ++frames;
if (gap > maxGap) maxGap = gap;
if (gap > 100.0) { ++gaps100; printf("[%s] GAP %.0f ms ending at %.0f (frame %ld)\n", tag, gap, nowv, frames); }
if (frames % 120 == 0) printf("[%s] frame %ld t=%.1fs fps=%.1f\n", tag, frames, (nowv - t0) / 1e3, frames * 1e3 / (nowv - t0));
}
const double total = now_ms() - t0;
printf("[%s] END frames=%ld fps=%.1f maxGap=%.0f ms gaps>100ms=%ld\n", tag, frames, frames * 1e3 / total, maxGap, gaps100);
return 0;
}
@@ -1,410 +0,0 @@
// yuvprobe.c - pixel check of YUV dma-buf sampling through MobileGL (GL_OES_EGL_image_external).
//
// gcc -O1 yuvprobe.c -o /usr/local/bin/mgl-yuvprobe -lEGL -lGLESv2 -lgbm
// mgrun offscreen mgl-yuvprobe # exit 0 = every check passed
//
// What it does, in an ES 3.0 context on a pbuffer:
// 1. FOREIGN NV12 (and P010): a dma-buf from /dev/dma_heap/system - a buffer the MobileGL server
// did not allocate, as a video decoder's would be - with padded pitches and a gap before the
// chroma plane, filled with four vertical bars (red, green, blue, white) in BT.709 narrow
// range. Imported with eglCreateImage(EGL_LINUX_DMA_BUF_EXT) and its colour hints, bound to
// GL_TEXTURE_EXTERNAL_OES, drawn through a samplerExternalOES shader into an RGBA8 FBO and read
// back: each bar must come out its colour. The buffer is then rewritten with the bars in
// reverse order and, after a native fence (what ends a frame for an offscreen producer), drawn
// again: the new order must show (the server refreshes a foreign buffer at each frame).
// 2. GBM NV12: gbm_bo_create(NV12) through the mobilegl GBM backend (a server-allocated YUV
// buffer, zero-copy), its planes printed, imported and sampled once (content undefined; the
// check is that every call succeeds).
// Also prints the dma-buf formats/modifiers EGL lists for NV12/P010.
#define _GNU_SOURCE
#include <EGL/egl.h>
#include <EGL/eglext.h>
#include <GLES3/gl3.h>
#include <GLES2/gl2ext.h>
#include <fcntl.h>
#include <gbm.h>
#include <linux/dma-buf.h>
#include <linux/dma-heap.h>
#include <math.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <unistd.h>
#ifndef DRM_FORMAT_NV12
#define DRM_FORMAT_NV12 0x3231564E
#endif
#ifndef DRM_FORMAT_P010
#define DRM_FORMAT_P010 0x30313050
#endif
static int g_failures = 0;
#define CHECK(cond, ...) \
do { \
if (!(cond)) { \
printf("FAIL: " __VA_ARGS__); \
printf("\n"); \
++g_failures; \
} \
} while (0)
static PFNEGLCREATEIMAGEKHRPROC pCreateImage;
static PFNEGLDESTROYIMAGEKHRPROC pDestroyImage;
static PFNGLEGLIMAGETARGETTEXTURE2DOESPROC pTargetTexture;
static PFNEGLQUERYDMABUFFORMATSEXTPROC pQueryFormats;
static PFNEGLQUERYDMABUFMODIFIERSEXTPROC pQueryModifiers;
static PFNEGLCREATESYNCKHRPROC pCreateSync;
static PFNEGLDESTROYSYNCKHRPROC pDestroySync;
static EGLDisplay g_display;
enum { W = 256, H = 128, BARS = 4 };
static const unsigned char kBars[BARS][3] = {{255, 0, 0}, {0, 255, 0}, {0, 0, 255}, {255, 255, 255}};
// RGB -> BT.709 narrow-range codes at `bits` (8 or 10).
static void Encode709(const unsigned char rgb[3], int bits, int out[3]) {
const double kr = 0.2126, kb = 0.0722, kg = 1.0 - kr - kb;
const double r = rgb[0] / 255.0, g = rgb[1] / 255.0, b = rgb[2] / 255.0;
const double y = kr * r + kg * g + kb * b;
const double cb = (b - y) / (2.0 * (1.0 - kb)), cr = (r - y) / (2.0 * (1.0 - kr));
const double scale = (double)(1 << (bits - 8));
out[0] = (int)lround((16.0 + 219.0 * y) * scale);
out[1] = (int)lround((128.0 + 224.0 * cb) * scale);
out[2] = (int)lround((128.0 + 224.0 * cr) * scale);
}
// Writes the bars (`reverse`d or not) into a semi-planar buffer: 1 byte samples, or P010's 16-bit
// samples with the 10 significant bits high.
static void FillBars(uint8_t* base, uint32_t pitchY, uint32_t offsetC, uint32_t pitchC, int bytes, int reverse) {
const int bits = bytes == 1 ? 8 : 10;
for (int y = 0; y < H; ++y) {
for (int x = 0; x < W; ++x) {
int bar = x * BARS / W;
if (reverse) bar = BARS - 1 - bar;
int code[3];
Encode709(kBars[bar], bits, code);
uint8_t* py = base + (size_t)y * pitchY + (size_t)x * bytes;
if (bytes == 1) py[0] = (uint8_t)code[0];
else *(uint16_t*)py = (uint16_t)(code[0] << 6);
if ((x & 1) == 0 && (y & 1) == 0) {
uint8_t* pc = base + offsetC + (size_t)(y / 2) * pitchC + (size_t)(x / 2) * 2 * bytes;
if (bytes == 1) {
pc[0] = (uint8_t)code[1];
pc[1] = (uint8_t)code[2];
} else {
((uint16_t*)pc)[0] = (uint16_t)(code[1] << 6);
((uint16_t*)pc)[1] = (uint16_t)(code[2] << 6);
}
}
}
}
}
static GLuint Compile(GLenum type, const char* source) {
GLuint shader = glCreateShader(type);
glShaderSource(shader, 1, &source, NULL);
glCompileShader(shader);
GLint ok = 0;
glGetShaderiv(shader, GL_COMPILE_STATUS, &ok);
if (!ok) {
char log[2048];
glGetShaderInfoLog(shader, sizeof(log), NULL, log);
printf("shader: %s\n", log);
}
return shader;
}
static GLuint g_program, g_fbo, g_rgba;
static void SetUpDraw(void) {
const char* vs = "#version 300 es\n"
"out vec2 uv;\n"
"void main() {\n"
" vec2 p = vec2(float((gl_VertexID << 1) & 2), float(gl_VertexID & 2));\n"
" gl_Position = vec4(p * 2.0 - 1.0, 0.0, 1.0);\n"
" uv = p;\n"
"}\n";
const char* fs = "#version 300 es\n"
"#extension GL_OES_EGL_image_external_essl3 : require\n"
"precision mediump float;\n"
"uniform samplerExternalOES tex;\n"
"in vec2 uv;\n"
"out vec4 color;\n"
"void main() { color = texture(tex, uv); }\n";
g_program = glCreateProgram();
glAttachShader(g_program, Compile(GL_VERTEX_SHADER, vs));
glAttachShader(g_program, Compile(GL_FRAGMENT_SHADER, fs));
glLinkProgram(g_program);
GLint linked = 0;
glGetProgramiv(g_program, GL_LINK_STATUS, &linked);
CHECK(linked, "the samplerExternalOES program did not link");
GLint type = 0, size = 0;
char name[64];
glGetActiveUniform(g_program, 0, sizeof(name), NULL, &size, (GLenum*)&type, name);
printf("uniform 0: %s type 0x%04x\n", name, type);
CHECK(type == GL_SAMPLER_EXTERNAL_OES, "the sampler reports type 0x%04x, not GL_SAMPLER_EXTERNAL_OES", type);
glGenTextures(1, &g_rgba);
glBindTexture(GL_TEXTURE_2D, g_rgba);
glTexStorage2D(GL_TEXTURE_2D, 1, GL_RGBA8, W, H);
glGenFramebuffers(1, &g_fbo);
glBindFramebuffer(GL_FRAMEBUFFER, g_fbo);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, g_rgba, 0);
CHECK(glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE, "the readback FBO is incomplete");
GLuint vao;
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
}
// Draws the external texture `texture` and checks each bar's center (row `y` of the image).
static void DrawAndCheck(GLuint texture, const char* what, int reverse, int tolerance) {
glBindFramebuffer(GL_FRAMEBUFFER, g_fbo);
glViewport(0, 0, W, H);
glUseProgram(g_program);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_EXTERNAL_OES, texture);
glUniform1i(glGetUniformLocation(g_program, "tex"), 0);
glDrawArrays(GL_TRIANGLES, 0, 3);
static unsigned char pixels[W * H * 4];
glReadPixels(0, 0, W, H, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
GLenum error = glGetError();
CHECK(error == GL_NO_ERROR, "%s: GL error 0x%04x", what, error);
if (tolerance < 0) {
printf("%s: center pixel %d %d %d %d (content undefined)\n", what, pixels[(H / 2 * W + W / 2) * 4],
pixels[(H / 2 * W + W / 2) * 4 + 1], pixels[(H / 2 * W + W / 2) * 4 + 2],
pixels[(H / 2 * W + W / 2) * 4 + 3]);
return;
}
// Rows: GL row 0 is the image's first row (the uv mapping above), and the bars are vertical,
// so any row does; take two to catch a broken chroma row pitch.
const int rows[2] = {H / 4, (3 * H) / 4};
for (int r = 0; r < 2; ++r) {
for (int bar = 0; bar < BARS; ++bar) {
const int x = bar * (W / BARS) + W / (2 * BARS);
const unsigned char* p = &pixels[(rows[r] * W + x) * 4];
const unsigned char* want = kBars[reverse ? BARS - 1 - bar : bar];
int worst = 0;
for (int c = 0; c < 3; ++c) {
int d = abs((int)p[c] - (int)want[c]);
if (d > worst) worst = d;
}
printf("%s: row %d bar %d -> %3d %3d %3d %3d (want %3d %3d %3d)%s\n", what, rows[r], bar, p[0], p[1], p[2],
p[3], want[0], want[1], want[2], worst > tolerance ? " <-- off" : "");
CHECK(worst <= tolerance, "%s: bar %d is off by %d", what, bar, worst);
}
}
}
static int AllocateDmaHeap(size_t size) {
int heap = open("/dev/dma_heap/system", O_RDWR | O_CLOEXEC);
if (heap < 0) {
perror("open /dev/dma_heap/system");
return -1;
}
struct dma_heap_allocation_data data = {.len = size, .fd_flags = O_RDWR | O_CLOEXEC};
if (ioctl(heap, DMA_HEAP_IOCTL_ALLOC, &data) != 0) {
perror("DMA_HEAP_IOCTL_ALLOC");
close(heap);
return -1;
}
close(heap);
return (int)data.fd;
}
static void Sync(int fd, int start) {
struct dma_buf_sync sync = {.flags = DMA_BUF_SYNC_WRITE | (start ? DMA_BUF_SYNC_START : DMA_BUF_SYNC_END)};
ioctl(fd, DMA_BUF_IOCTL_SYNC, &sync);
}
static EGLImageKHR Import(int fd, uint32_t fourcc, uint32_t pitchY, uint32_t offsetC, uint32_t pitchC, int modifier) {
EGLint attribs[64];
int n = 0;
#define A(k, v) (attribs[n++] = (k), attribs[n++] = (EGLint)(v))
A(EGL_WIDTH, W);
A(EGL_HEIGHT, H);
A(EGL_LINUX_DRM_FOURCC_EXT, fourcc);
A(EGL_DMA_BUF_PLANE0_FD_EXT, fd);
A(EGL_DMA_BUF_PLANE0_OFFSET_EXT, 0);
A(EGL_DMA_BUF_PLANE0_PITCH_EXT, pitchY);
A(EGL_DMA_BUF_PLANE1_FD_EXT, fd);
A(EGL_DMA_BUF_PLANE1_OFFSET_EXT, offsetC);
A(EGL_DMA_BUF_PLANE1_PITCH_EXT, pitchC);
if (modifier) {
A(EGL_DMA_BUF_PLANE0_MODIFIER_LO_EXT, 0);
A(EGL_DMA_BUF_PLANE0_MODIFIER_HI_EXT, 0);
A(EGL_DMA_BUF_PLANE1_MODIFIER_LO_EXT, 0);
A(EGL_DMA_BUF_PLANE1_MODIFIER_HI_EXT, 0);
}
A(EGL_YUV_COLOR_SPACE_HINT_EXT, EGL_ITU_REC709_EXT);
A(EGL_SAMPLE_RANGE_HINT_EXT, EGL_YUV_NARROW_RANGE_EXT);
attribs[n] = EGL_NONE;
#undef A
EGLImageKHR image = pCreateImage(g_display, EGL_NO_CONTEXT, EGL_LINUX_DMA_BUF_EXT, NULL, attribs);
if (image == EGL_NO_IMAGE_KHR) printf("eglCreateImage failed: 0x%04x\n", eglGetError());
return image;
}
static GLuint ExternalTexture(EGLImageKHR image) {
GLuint texture;
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_EXTERNAL_OES, texture);
pTargetTexture(GL_TEXTURE_EXTERNAL_OES, image);
GLenum error = glGetError();
CHECK(error == GL_NO_ERROR, "glEGLImageTargetTexture2DOES(GL_TEXTURE_EXTERNAL_OES) -> 0x%04x", error);
GLint bound = 0;
glGetIntegerv(GL_TEXTURE_BINDING_EXTERNAL_OES, &bound);
CHECK((GLuint)bound == texture, "GL_TEXTURE_BINDING_EXTERNAL_OES reads %d", bound);
return texture;
}
// A frame boundary as an offscreen producer makes one: a native fence.
static void EndFrame(void) {
EGLint attribs[] = {EGL_NONE};
EGLSyncKHR sync = pCreateSync(g_display, EGL_SYNC_NATIVE_FENCE_ANDROID, attribs);
CHECK(sync != EGL_NO_SYNC_KHR, "eglCreateSync(native fence) failed");
if (sync != EGL_NO_SYNC_KHR) pDestroySync(g_display, sync);
}
static void ForeignTest(uint32_t fourcc, int bytes, int tolerance) {
const char* what = fourcc == DRM_FORMAT_NV12 ? "foreign NV12" : "foreign P010";
// Padded pitches and a gap before the chroma plane, as decoders lay buffers out.
const uint32_t pitchY = W * bytes + 64, pitchC = W * bytes + 128;
const uint32_t offsetC = pitchY * (H + 16);
const size_t size = offsetC + (size_t)pitchC * (H / 2) + 4096;
int fd = AllocateDmaHeap(size);
if (fd < 0) {
CHECK(0, "%s: no dma-buf to test with", what);
return;
}
uint8_t* map = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
CHECK(map != MAP_FAILED, "%s: mmap failed", what);
if (map == MAP_FAILED) return;
Sync(fd, 1);
FillBars(map, pitchY, offsetC, pitchC, bytes, 0);
Sync(fd, 0);
EGLImageKHR image = Import(fd, fourcc, pitchY, offsetC, pitchC, fourcc == DRM_FORMAT_NV12);
CHECK(image != EGL_NO_IMAGE_KHR, "%s: import refused", what);
if (image == EGL_NO_IMAGE_KHR) return;
GLuint texture = ExternalTexture(image);
DrawAndCheck(texture, what, 0, tolerance);
EndFrame();
// New content, same buffer: shows after the frame boundary.
Sync(fd, 1);
FillBars(map, pitchY, offsetC, pitchC, bytes, 1);
Sync(fd, 0);
EndFrame();
DrawAndCheck(texture, what, 1, tolerance);
glDeleteTextures(1, &texture);
pDestroyImage(g_display, image);
munmap(map, size);
close(fd);
}
static void GbmTest(void) {
int node = open("/dev/dri/renderD128", O_RDWR | O_CLOEXEC);
if (node < 0) node = open("/dev/null", O_RDWR | O_CLOEXEC);
struct gbm_device* gbm = gbm_create_device(node);
if (gbm == NULL) {
CHECK(0, "gbm_create_device failed");
return;
}
printf("gbm backend: %s\n", gbm_device_get_backend_name(gbm));
const int supported = gbm_device_is_format_supported(gbm, DRM_FORMAT_NV12, 0);
printf("gbm NV12 supported: %d, P010: %d\n", supported,
gbm_device_is_format_supported(gbm, DRM_FORMAT_P010, 0));
CHECK(supported == 1, "gbm does not support NV12");
struct gbm_bo* bo = gbm_bo_create(gbm, W, H, DRM_FORMAT_NV12, 0);
CHECK(bo != NULL, "gbm_bo_create(NV12) failed");
if (bo != NULL) {
const int planes = gbm_bo_get_plane_count(bo);
printf("gbm NV12 bo: planes %d, stride %u/%u, offset %u/%u, modifier 0x%llx\n", planes,
gbm_bo_get_stride_for_plane(bo, 0), gbm_bo_get_stride_for_plane(bo, 1), gbm_bo_get_offset(bo, 0),
gbm_bo_get_offset(bo, 1), (unsigned long long)gbm_bo_get_modifier(bo));
CHECK(planes == 2, "the NV12 bo has %d planes", planes);
int fd = gbm_bo_get_fd(bo);
EGLImageKHR image =
Import(fd, DRM_FORMAT_NV12, gbm_bo_get_stride_for_plane(bo, 0), gbm_bo_get_offset(bo, 1),
gbm_bo_get_stride_for_plane(bo, 1), 0);
CHECK(image != EGL_NO_IMAGE_KHR, "the server's own NV12 buffer was not imported");
if (image != EGL_NO_IMAGE_KHR) {
GLuint texture = ExternalTexture(image);
DrawAndCheck(texture, "gbm NV12", 0, -1);
glDeleteTextures(1, &texture);
pDestroyImage(g_display, image);
}
close(fd);
gbm_bo_destroy(bo);
}
gbm_device_destroy(gbm);
close(node);
}
int main(void) {
setvbuf(stdout, NULL, _IONBF, 0);
g_display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
EGLint major, minor;
if (!eglInitialize(g_display, &major, &minor)) {
printf("FAIL: eglInitialize\n");
return 2;
}
const char* eglExtensions = eglQueryString(g_display, EGL_EXTENSIONS);
printf("EGL %d.%d dma_buf_import: %s\n", major, minor,
strstr(eglExtensions, "EGL_EXT_image_dma_buf_import") ? "yes" : "no");
eglBindAPI(EGL_OPENGL_ES_API);
const EGLint configAttribs[] = {EGL_SURFACE_TYPE, EGL_PBUFFER_BIT, EGL_RENDERABLE_TYPE, EGL_OPENGL_ES3_BIT,
EGL_RED_SIZE, 8, EGL_GREEN_SIZE, 8, EGL_BLUE_SIZE, 8, EGL_NONE};
EGLConfig config;
EGLint count = 0;
eglChooseConfig(g_display, configAttribs, &config, 1, &count);
if (count < 1) {
printf("FAIL: no config\n");
return 2;
}
const EGLint pbufferAttribs[] = {EGL_WIDTH, 16, EGL_HEIGHT, 16, EGL_NONE};
EGLSurface surface = eglCreatePbufferSurface(g_display, config, pbufferAttribs);
const EGLint contextAttribs[] = {EGL_CONTEXT_MAJOR_VERSION, 3, EGL_NONE};
EGLContext context = eglCreateContext(g_display, config, EGL_NO_CONTEXT, contextAttribs);
if (context == EGL_NO_CONTEXT || !eglMakeCurrent(g_display, surface, surface, context)) {
printf("FAIL: no ES 3 context\n");
return 2;
}
pCreateImage = (PFNEGLCREATEIMAGEKHRPROC)eglGetProcAddress("eglCreateImageKHR");
pDestroyImage = (PFNEGLDESTROYIMAGEKHRPROC)eglGetProcAddress("eglDestroyImageKHR");
pTargetTexture = (PFNGLEGLIMAGETARGETTEXTURE2DOESPROC)eglGetProcAddress("glEGLImageTargetTexture2DOES");
pQueryFormats = (PFNEGLQUERYDMABUFFORMATSEXTPROC)eglGetProcAddress("eglQueryDmaBufFormatsEXT");
pQueryModifiers = (PFNEGLQUERYDMABUFMODIFIERSEXTPROC)eglGetProcAddress("eglQueryDmaBufModifiersEXT");
pCreateSync = (PFNEGLCREATESYNCKHRPROC)eglGetProcAddress("eglCreateSyncKHR");
pDestroySync = (PFNEGLDESTROYSYNCKHRPROC)eglGetProcAddress("eglDestroySyncKHR");
printf("GL_RENDERER: %s\n", glGetString(GL_RENDERER));
const char* glExtensions = (const char*)glGetString(GL_EXTENSIONS);
const int external = strstr(glExtensions, "GL_OES_EGL_image_external_essl3") != NULL;
printf("GL_OES_EGL_image_external_essl3: %s\n", external ? "yes" : "no");
CHECK(external, "GL_OES_EGL_image_external_essl3 is not advertised");
EGLint formats[32], formatCount = 0;
pQueryFormats(g_display, 32, formats, &formatCount);
int nv12 = 0;
for (int i = 0; i < formatCount; ++i) {
printf("dma-buf format %.4s", (const char*)&formats[i]);
EGLuint64KHR modifiers[4];
EGLBoolean externalOnly[4];
EGLint modifierCount = 0;
pQueryModifiers(g_display, formats[i], 4, modifiers, externalOnly, &modifierCount);
for (int m = 0; m < modifierCount; ++m)
printf(" [modifier 0x%llx%s]", (unsigned long long)modifiers[m], externalOnly[m] ? " external-only" : "");
printf("\n");
nv12 |= formats[i] == (EGLint)DRM_FORMAT_NV12;
}
CHECK(nv12, "NV12 is not a listed dma-buf format");
SetUpDraw();
ForeignTest(DRM_FORMAT_NV12, 1, 12);
ForeignTest(DRM_FORMAT_P010, 2, 16);
GbmTest();
printf("%s (%d failure(s))\n", g_failures ? "FAILED" : "PASSED", g_failures);
eglMakeCurrent(g_display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
eglTerminate(g_display);
return g_failures ? 1 : 0;
}
@@ -1,135 +0,0 @@
#!/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
+3 -7
View File
@@ -18,10 +18,6 @@ on:
- '**/*.md'
workflow_dispatch:
env:
# Software-rendered CI submissions may exceed the interactive GPU hang budget.
MOBILEGL_GPU_HANG_BUDGET_MS: "0"
# ONE LIVE RUN PER BRANCH, as in test.yml: a superseded push is cancelled rather than left queued
# behind its successor; a manual dispatch gets a group of its own; dev queues rather than cancels.
concurrency:
@@ -481,7 +477,7 @@ jobs:
extra_retrace_args=()
if [ "${MOBILEGL_CI_TRANSPORT}" = "inproc" ]; then
extra_retrace_args+=(
--env "MOBILEGL_TRANSPORT=inproc;MOBILEGL_IPC_ROLE_SPLIT_STATE=1;MOBILEGL_IPC_STRICT_ERRORS=1;MOBILEGL_IPC_RUN_AHEAD=1;MOBILEGL_GPU_HANG_BUDGET_MS=${MOBILEGL_GPU_HANG_BUDGET_MS}"
--env "MOBILEGL_TRANSPORT=inproc;MOBILEGL_IPC_ROLE_SPLIT_STATE=1;MOBILEGL_IPC_STRICT_ERRORS=1;MOBILEGL_IPC_RUN_AHEAD=1"
--require-inproc
)
elif [ "${MOBILEGL_CI_TRANSPORT}" = "spawn" ]; then
@@ -497,12 +493,12 @@ jobs:
# into the CLIENT's process and SetWindowHandle is refused on the way across with
# Fatal{UnmigratedSurface, "AndroidNativeWindow@P12"} (Rule H).
extra_retrace_args+=(
--env "MOBILEGL_TRANSPORT=spawn;MOBILEGL_IPC_ROLE_SPLIT_STATE=1;MOBILEGL_IPC_STRICT_ERRORS=1;MOBILEGL_IPC_RUN_AHEAD=1;MOBILEGL_GPU_HANG_BUDGET_MS=${MOBILEGL_GPU_HANG_BUDGET_MS}"
--env "MOBILEGL_TRANSPORT=spawn;MOBILEGL_IPC_ROLE_SPLIT_STATE=1;MOBILEGL_IPC_STRICT_ERRORS=1;MOBILEGL_IPC_RUN_AHEAD=1"
--use-pbuffer
--require-spawn
)
else
extra_retrace_args+=(--env "MOBILEGL_TRANSPORT=monolith;MOBILEGL_GPU_HANG_BUDGET_MS=${MOBILEGL_GPU_HANG_BUDGET_MS}")
extra_retrace_args+=(--env "MOBILEGL_TRANSPORT=monolith")
fi
# Bliss needs the newer signed ANGLE variant plus sampler mipmap
# min-filter downgrading on ANGLE llvmpipe.
+90 -35
View File
@@ -21,10 +21,6 @@ on:
required: false
default: "087685d1"
env:
# Software-rendered CI submissions may exceed the interactive GPU hang budget.
MOBILEGL_GPU_HANG_BUDGET_MS: "0"
# ONE LIVE RUN PER BRANCH. The disaggregation branch pushes (often docs-only) commits minutes apart
# and each push fans out to ~330 retrace legs here and ~275 jobs in apk.yml; with no group, runs
# sat queued for 10+ hours behind their own successors. A manual dispatch gets a group of its own,
@@ -417,12 +413,6 @@ jobs:
--discovery "${RUNNER_TEMP}/primary-inproc-lane.json" \
--junit "${RUNNER_TEMP}/primary-inproc.xml" --output "${RUNNER_TEMP}/primary-inproc-proof.json"
# The run log needs a signed-in reader; annotations do not. Name every failed ctest entry,
# with the lines of its output that say why, where anyone reading the run can see them.
- name: Annotate failed entries
if: failure()
run: python3 scripts/ci/junit_annotate.py "${RUNNER_TEMP}"
- name: Upload integration lane evidence
if: always()
uses: actions/upload-artifact@v7
@@ -1179,12 +1169,6 @@ jobs:
# arm proof read; verify-split-logs/ is whatever the control steps left behind, which for
# twelve entries is a deliberately red re-run under the same name. Uploading only the
# second - which is what this step did before the copy above existed - loses the first.
# The run log needs a signed-in reader; annotations do not. Name every failed ctest entry,
# with the lines of its output that say why, where anyone reading the run can see them.
- name: Annotate failed entries
if: failure()
run: python3 scripts/ci/junit_annotate.py "${RUNNER_TEMP}"
- name: Upload verify-split lane logs
if: always()
uses: actions/upload-artifact@v7
@@ -1497,7 +1481,7 @@ jobs:
working-directory: build-split
env:
MOBILEGL_ITEST_REQUIRE_GPU: "1"
run: ctest --output-on-failure -L unit --no-tests=error -j "$(nproc)" --output-junit "${RUNNER_TEMP}/unit-split.xml"
run: ctest --output-on-failure -L unit --no-tests=error -j "$(nproc)"
# P7 wave 2-F, PH-7 (1). THE TCP SUPERVISOR LANE NEEDS flatc, AND CI HAD NONE.
#
@@ -1664,12 +1648,6 @@ jobs:
CONTROL_TMPDIR: ${{ runner.temp }}
run: bash "${GITHUB_WORKSPACE}/scripts/ci/split_negative_controls.sh"
# The run log needs a signed-in reader; annotations do not. Name every failed ctest entry,
# with the lines of its output that say why, where anyone reading the run can see them.
- name: Annotate failed entries
if: failure()
run: python3 scripts/ci/junit_annotate.py "${RUNNER_TEMP}"
- name: Upload split lane logs
if: always()
uses: actions/upload-artifact@v7
@@ -1759,7 +1737,7 @@ jobs:
env:
MOBILEGL_ITEST_REQUIRE_GPU: "1"
MOBILEGL_IPC_STRICT_ERRORS: "1"
run: ctest --output-on-failure -L unit --no-tests=error -j "$(nproc)" --output-junit "${RUNNER_TEMP}/unit-strict.xml"
run: ctest --output-on-failure -L unit --no-tests=error -j "$(nproc)"
# ---- P5e (ra), MG_Remote/CONTRACT-P5E.md §7: ONE STEP, TWO ARMS, AND THE TREE PICKS ----
#
@@ -2268,12 +2246,6 @@ jobs:
slp.require_green(lane, sys.argv[3], names)
PY
# The run log needs a signed-in reader; annotations do not. Name every failed ctest entry,
# with the lines of its output that say why, where anyone reading the run can see them.
- name: Annotate failed entries
if: failure()
run: python3 scripts/ci/junit_annotate.py "${RUNNER_TEMP}"
- name: Upload strict lane logs
if: always()
uses: actions/upload-artifact@v7
@@ -2779,11 +2751,7 @@ jobs:
&& [ '${{ matrix.case }}' = 'improved-transparency-minecraft-26.3' ]; then
export MOBILEGL_MAGMA_DISABLE_BLENDED_DEPTH_WRITE=1
fi
ctest -V --no-tests=error -R '^MobileGLTraceReplay\.${{ matrix.case }}\.${{ matrix.backend }}$' --output-junit "${RUNNER_TEMP}/retrace.xml"
- name: Annotate failed entries
if: failure()
run: python3 scripts/ci/junit_annotate.py --excerpts 1 "${RUNNER_TEMP}"
ctest -V --no-tests=error -R '^MobileGLTraceReplay\.${{ matrix.case }}\.${{ matrix.backend }}$'
- name: Upload core dumps
if: failure()
@@ -3538,10 +3506,27 @@ jobs:
runs-on: ubuntu-latest
# Deliberately independent of build-linux: these are source-level gates, they take
# seconds, and a broken build must not hide a drifted interface.
env:
# THE CURRENT PHASE's base ref, for the two G5 region gates below. It is 37da3c3a - P4a's
# base ref, INTEGRATOR-DECISIONS ID-1 - and NOT the workflow's baseline_sha input: that input
# is the SYMBOL baseline (087685d1, P1's G1 reading) and it is empty on a push, whereas these
# gates ask "did the do-not-touch list move since the phase started".
#
# IT MOVED FROM P3a's 44c2b5cf TO P4a's 37da3c3a WITH THE PHASE, and that is a deliberate
# narrowing rather than a loss: P3a's eleven functions were compared against 44c2b5cf at P3a's
# own exit and were byte-identical there, so 37da3c3a carries the same bodies (measured: the
# eleven shas at 37da3c3a are the eleven shas at 44c2b5cf, and FlushPendingRangesFrom's is
# still the sha pinned in the script at 3e298c9a). What the two gates now both answer is "did
# anything on the list move during P4a", which is the question this phase can act on.
BASELINE: "37da3c3a"
steps:
- name: Checkout repo
uses: actions/checkout@v6
with:
# The G5 gate reads Managers.cpp at BASELINE with `git show`, which a depth-1 checkout
# does not have. Nothing else in this job needs history.
fetch-depth: 0
# The seven generators all read MG_Pipe/*.def, so regenerating and diffing is what
# keeps the two interface tables, the wire records, the verify comparators, the
@@ -3670,6 +3655,76 @@ jobs:
python3 tools/trace_replay/test_run_tcp_matrix.py
python3 tools/trace_replay/test_compare_actuals.py
# A GATE as of P3a (G5). "pool 与延迟释放原样搬" (ROADMAP.md:19) is meant literally: the
# buffer pool, the deferred-release drain and the three persistently mapped rings move
# VERBATIM, and ARCHITECTURE.md:515 says why - their retire happens only inside Present, so
# a batching or ordering change there starves them, and nothing else in this workflow can
# see it. P3a rewrites the rest of Managers.cpp by design, so a file diff says nothing; the
# script extracts the ELEVEN named bodies and compares their hashes on their own.
#
# Eleven and not ten (ID-15): Managers.cpp carries the three-tier flush drain TWICE, once
# per preprocessor arm, and a push build compiles only FlushPendingRangesFrom while the
# untouched FlushPendingRangesNow lives in the `#else`. Hashing the pull name alone would
# protect text no shipping build compiles, so both are hashed - the pull ladder against
# BASELINE, the push ladder against a sha pinned in the script at 3dadd4c1 (ID-41), because
# that one was born in P3a and is compared against the reviewed body rather than against the
# base ref.
#
# Scoped to the disaggregation branch and to a manual dispatch, deliberately: the question
# is "did these eleven move since P3a started", and BASELINE is P3a's base ref. On dev,
# where unrelated buffer fixes land on their own schedule, the same comparison would be
# asking a question nobody posed - it belongs with the TEMPORARY trigger lines at the top
# of this file and retires with them.
#
# --self-test is the half that keeps it honest, and it is not optional: a comparison that
# silently stopped comparing produces exactly the same green as eleven untouched bodies. It
# runs eight canned controls - eleven bodies extracted, an untouched copy compared equal, an
# edit OUTSIDE them ignored, each of the three perturbation targets (ClearBufferPool and BOTH
# flush ladders) reported BY NAME, plus the pin-precedence control and a one-token edit to the
# pinned ladder compared against the pin - and fails if any of them does not answer.
# Same shape as gen_pipe.py --self-test above.
- name: P3a regions unchanged (G5)
if: ${{ github.ref == 'refs/heads/feat/disaggregated' || github.event_name == 'workflow_dispatch' }}
run: bash scripts/p3a_untouched_regions.sh "${BASELINE}" HEAD
- name: P3a untouched-region self-test (G5)
if: ${{ github.ref == 'refs/heads/feat/disaggregated' || github.event_name == 'workflow_dispatch' }}
run: bash scripts/p3a_untouched_regions.sh --self-test
# A GATE AS OF P4a (G5), and a SECOND script rather than an edit to the one above. P4a extends
# the same claim to the rest of ARCHITECTURE.md:318's do-not-touch list - the unpack PBO ring's
# staging repack and its two helpers, the attachment permutation, the D24S8 sampling-emulation
# core and the format-caveat handler - which is SEVENTEEN regions across THREE files
# (BRIEF-P4A.md D-N: P3a's eleven, which P4a must not touch either, plus P4a's six). The
# parent's SOURCE_PATH is a single file, so the extension needed a per-region source path and
# a region KIND (DepthStencilSamplingReadImpl is a namespace, not a function); everything else
# about the extraction is its parent's, verbatim.
#
# Both scripts run. The parent keeps answering its own question against its own eleven, so a
# regression in either half names itself, and neither gate can be silenced by editing the
# other's list.
#
# Same feat/disaggregated-or-dispatch guard as the P3a step, for the same reason: the question
# is "did these move since the phase started", and on dev - where unrelated buffer and texture
# fixes land on their own schedule - it would be a question nobody posed. It belongs with the
# TEMPORARY trigger lines at the top of this file and retires with them.
#
# --self-test is the half that keeps it honest and is not optional: a comparison that silently
# stopped comparing produces exactly the same green as seventeen untouched regions. It runs
# three positive controls (seventeen regions extracted, an untouched copy compared equal, an
# edit OUTSIDE them invisible in all three files) and NINE negative ones - ClearBufferPool,
# FlushPendingRangesNow, RecomputeBackendColorSlots and StageBlocksIntoUnpackRing, each
# perturbed at its HEAD and at its TAIL and each required to be named BY NAME, plus a
# one-token edit to the pinned FlushPendingRangesFrom body compared against the pin - and
# fails if any of them does not answer.
- name: P4a regions unchanged (G5)
if: ${{ github.ref == 'refs/heads/feat/disaggregated' || github.event_name == 'workflow_dispatch' }}
run: bash scripts/p4a_untouched_regions.sh "${BASELINE}" HEAD
- name: P4a untouched-region self-test (G5)
if: ${{ github.ref == 'refs/heads/feat/disaggregated' || github.event_name == 'workflow_dispatch' }}
run: bash scripts/p4a_untouched_regions.sh --self-test
# Warning only for now: the disaggregation documents are still being written, and a
# lint that fails a rewrite in progress teaches people to ignore it. It becomes
# --strict when the documents settle.
-31
View File
@@ -1,31 +0,0 @@
name: Arch WSL GPU smoke
on:
workflow_dispatch:
push:
branches:
- ci/arch-wsl-gpu-runner
paths:
- .github/workflows/wsl-gpu-smoke.yml
- docs/ci/arch-wsl-gpu-runner.md
permissions: {}
concurrency:
group: arch-wsl-gpu-smoke
cancel-in-progress: false
jobs:
gpu-smoke:
runs-on: [self-hosted, Linux, X64, arch, wsl, gpu, gles, vulkan]
timeout-minutes: 5
steps:
- name: Report runner identity
shell: bash
run: |
printf 'Runner: %s\n' "$RUNNER_NAME"
uname -n
uname -a
- name: Verify hardware GLES and Vulkan
shell: bash
run: /usr/local/libexec/mobilegl-runner/gpu-smoke
-17
View File
@@ -304,7 +304,6 @@ 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
@@ -372,7 +371,6 @@ set(SOURCE_FILES
MobileGL/MG_Util/ShaderTranspiler/SpirvPasses/FixIterationRPSubgroupScratchPass.cpp
MobileGL/MG_Util/ShaderTranspiler/SpirvPasses/EmulateSubgroupsPass.cpp
MobileGL/MG_Util/ShaderTranspiler/SpirvPasses/NormalizeRectCoordinatesPass.cpp
MobileGL/MG_Util/ShaderTranspiler/SpirvPasses/DeduplicateImageTypesPass.cpp
MobileGL/MG_Util/ShaderTranspiler/SpirvPasses/Lower1DArrayImagesPass.cpp
MobileGL/MG_Util/ShaderTranspiler/SpirvPasses/Lower1DSampledImagesPass.cpp
MobileGL/MG_Util/ShaderTranspiler/SpirvPasses/BakeImageFormatsPass.cpp
@@ -403,8 +401,6 @@ 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
@@ -441,7 +437,6 @@ set(SOURCE_FILES
MobileGL/MG_Backend/Init.cpp
MobileGL/MG_Backend/BackendObject.cpp
MobileGL/MG_Backend/GpuHangWatch.cpp
MobileGL/MG_Backend/DirectGLES/DirectGLES.cpp
MobileGL/MG_Backend/DirectGLES/BackendObject_DirectGLES.cpp
@@ -469,7 +464,6 @@ set(SOURCE_FILES
MobileGL/MG_Backend/DirectVulkan/Renderer/VkSamplerManager.cpp
MobileGL/MG_Backend/DirectVulkan/Renderer/VkClearManager.cpp
MobileGL/MG_Backend/DirectVulkan/Renderer/VkRenderPassManager.cpp
MobileGL/MG_Backend/DirectVulkan/Renderer/GpuProgressMarkers.cpp
MobileGL/MG_State/GLState/Core.cpp
MobileGL/MG_State/GLState/ShareGroupState.cpp
@@ -1010,17 +1004,6 @@ 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
-12
View File
@@ -130,11 +130,6 @@ namespace MobileGL::MG_Config {
Bool AdvertiseFp64 = false;
// MOBILEGL_MAGMA_R11G11B10F_FALLBACK: use fallback format for R11G11B10F on Vulkan.
Bool MagmaR11G11B10FFallback = false;
// MOBILEGL_MAGMA_ALLOW_INVALID_SPIRV: hand a shader module that fails SPIR-V validation to
// the driver anyway. Off by default: Magma declines such a program (no shader module, its
// draws refused by name), because a driver that accepts invalid SPIR-V may fault the GPU
// into device loss. For diagnosing a driver that copes with a specific module only.
Bool MagmaAllowInvalidSpirv = false;
// MOBILEGL_MAGMA_FRAMESINFLIGHT: requested Magma frames in flight, defaulting to 3.
Uint32 MagmaFramesInFlight = 3;
// MOBILEGL_MAGMA_MAX_DRAWS_PER_COMMAND_BUFFER: GL draws and dispatches Magma records into
@@ -634,13 +629,6 @@ namespace MobileGL::MG_Config {
// poll loop cannot outlive a late report. 0 = every poll crosses, as before P10: the A/B
// arm and the red-once of the no-reply gate (FencePollScenario).
Uint32 PollEscalate = 64;
// MOBILEGL_IPC_RECOVER (client): 1 (default) = after a device loss ends this client's
// session, the application's next eglCreateContext / eglCreate*Surface / eglInitialize
// dials the server for a FRESH session, and contexts created from then on work. Contexts
// (and their objects) from before the loss stay lost, as EGL's power-management event
// has them; surfaces survive and are re-created on the new session when next used.
// 0 = the loss is final for the process (every verb DECLINED for the rest of its life).
Uint32 RecoverAfterLoss = 1;
// MOBILEGL_IPC_ADOPT_TIER, THE ZERO-COPY SWITCH (ruling ID-P11-14, CONTRACT-P11 B2):
// UNSET (kAdoptTierUnset, the default since 2026-09-29, the user's decision) = T0 where the
// session can run it, T2 QUIETLY where it cannot (MGLOG_D only, still counted);
-3
View File
@@ -348,7 +348,6 @@ namespace MobileGL::MG_ConfigLoader {
features.MagmaDeriveNumSubgroups = QueryEnvQuirkOverride("MOBILEGL_MAGMA_DERIVE_NUM_SUBGROUPS");
features.AdvertiseFp64 = QueryEnvFlag("MOBILEGL_ADVERTISE_FP64");
features.MagmaR11G11B10FFallback = QueryEnvFlag("MOBILEGL_MAGMA_R11G11B10F_FALLBACK");
features.MagmaAllowInvalidSpirv = QueryEnvFlag("MOBILEGL_MAGMA_ALLOW_INVALID_SPIRV");
features.MagmaFramesInFlight = QueryEnvUint32("MOBILEGL_MAGMA_FRAMESINFLIGHT", 3, 1, 64);
features.MagmaMaxDrawsPerCommandBuffer =
QueryEnvUint32("MOBILEGL_MAGMA_MAX_DRAWS_PER_COMMAND_BUFFER", 16384, 0, 1u << 24);
@@ -559,8 +558,6 @@ namespace MobileGL::MG_ConfigLoader {
ipc.PboReadbackSync = QueryEnvUint32("MOBILEGL_IPC_PBO_READBACK_SYNC", 0, 0, 1);
// P10: fence polls answered locally; 0 is the A/B arm (Config.h).
ipc.PollEscalate = QueryEnvUint32("MOBILEGL_IPC_POLL_ESCALATE", 64, 0, 1000000);
// A lost session is replaced by a fresh one on the application's next create (Config.h).
ipc.RecoverAfterLoss = QueryEnvUint32("MOBILEGL_IPC_RECOVER", 1, 0, 1);
// The verify harness compares the pushed block against the applier per verb; a
// batched queue lets the comparer read a supplied field mid-apply, which is a
// torn read rather than a divergence. The batch is therefore off whenever the
+12
View File
@@ -238,6 +238,18 @@ namespace MobileGL {
#endif
return true;
}
#if defined(__linux__) && !defined(__ANDROID__)
// LIBGL_ALWAYS_SOFTWARE is how a process (or whoever launched it) asks the system's GL for a
// software renderer. MobileGL is a GPU forwarder, so it steps aside and lets the system's
// other implementation give the process what it asked for.
{
String software;
if (MG_ConfigLoader::LookupSetting("LIBGL_ALWAYS_SOFTWARE", software) && !software.empty() &&
software != "0" && software != "false") {
return false;
}
}
#endif
#if MOBILEGL_BUILD_DISAGGREGATED
// Not yet: the bring-up would dial the configured server and wait for it. Ask first.
return MG_Remote::Client::ConfiguredServerAvailable();
-4
View File
@@ -46,9 +46,5 @@ namespace MobileGL {
namespace MG_Impl {
void Init();
// GL framebuffer 0, built into the calling thread's GLContext (the process default at
// Init) and installed as the one every later context starts with. Init's step, and the
// rebuild after a recovered device loss, whose fresh session holds none of the old one's.
void BuildDefaultFramebuffer();
} // namespace MG_Impl
} // namespace MobileGL
-2
View File
@@ -97,8 +97,6 @@ namespace MobileGL::MG_Backend {
static_cast<SizeT>(target) >= kFormatCapabilityTextureTargetCount) {
return kFormatCapabilityTargetCount;
}
// An external texture is a 2D one wherever a format can go.
if (target == TextureTarget::External) return static_cast<SizeT>(TextureTarget::Texture2D);
return static_cast<SizeT>(target);
}
+1 -60
View File
@@ -9,9 +9,9 @@
#pragma once
#include <Includes.h>
#include "MG_State/GLState/TextureState/TextureEnum.h"
#include <MG_Util/Damage/Damage.h>
#if MOBILEGL_BUILD_DISAGGREGATED
#include <MG_Pipe/MGPipeHandles.h>
#include <MG_Util/Damage/Damage.h>
#endif
namespace MobileGL {
@@ -610,24 +610,6 @@ namespace MobileGL {
Uint32 Stride = 0;
Uint32 Offset = 0;
Uint64 Modifier = 0;
// A YUV image's Cb Cr plane: in the same descriptor, at this offset and pitch.
Uint32 Plane1Stride = 0;
Uint32 Plane1Offset = 0;
};
// An import of a two-plane (YUV) dma-buf: where its planes are in the one descriptor, and
// EGL_EXT_image_dma_buf_import's colour hints (0 = not given).
struct SharedImageImportLayout {
Uint32 PlaneCount = 1;
Uint32 Offset[2] = {0, 0};
Uint32 Pitch[2] = {0, 0};
Uint32 ColorSpace = 0;
Uint32 Range = 0;
Uint32 SitingX = 0;
Uint32 SitingY = 0;
// The DRM format modifier the import named; HasModifier false = none (the implicit one).
Bool HasModifier = false;
Uint64 Modifier = 0;
};
// THE DAMAGE OF THE PRESENT BEING APPLIED on this thread: the server's apply thread sets it
@@ -684,23 +666,6 @@ 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) ----------
//
@@ -715,13 +680,6 @@ namespace MobileGL {
(void)fd, (void)width, (void)height, (void)fourcc, (void)outId;
return false;
}
// The same for a YUV fourcc, whose planes and hints `layout` gives. A YUV buffer the
// server did not export is taken too (its labelled CPU-copy fallback).
virtual Bool ImportSharedImagePlanes(int fd, Uint32 width, Uint32 height, Uint32 fourcc,
const SharedImageImportLayout& layout, Uint64* outId) {
(void)fd, (void)width, (void)height, (void)fourcc, (void)layout, (void)outId;
return false;
}
// Drops this client's reference (an allocation's or an import's).
virtual Bool ReleaseSharedImage(Uint64 id) {
(void)id;
@@ -753,17 +711,6 @@ 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;
@@ -774,12 +721,6 @@ namespace MobileGL {
// native state is process-global by construction gives this object its own copy and binds
// it to the calling thread. The default has nothing per process to separate.
virtual void BindSessionStateToThisThread() {}
// A served session's apply thread asks this each time it wakes, BEFORE it applies another
// record: true when this session's own GPU work faulted or hung the GPU and the backend has
// latched the session for it (MGPipeSessionLatch, family DeviceLost), so the next frame -
// which would very likely stop the GPU again - is never applied. Cheap by contract: no
// wait, at most a status read. The default knows of no fault.
virtual Bool LatchIfGpuFaulted() { return false; }
// A served session's ring moved to another of its client's contexts (bind_context). A
// backend whose surface follows the native context it binds needs nothing; one that keeps
// a single native surface binding re-binds the surface that context was last made current
@@ -961,14 +961,6 @@ namespace MobileGL::MG_Backend::DirectGLES {
return true;
}
Bool BackendObject_DirectGLES::LatchIfGpuFaulted() {
#if MOBILEGL_BUILD_DISAGGREGATED
return LatchIfGuiltyBeforeApply();
#else
return false;
#endif
}
void BackendObject_DirectGLES::Initialize() {
MG_Util::BackendLoader::AcquireEGLFunctions(m_EGLFunctions);
MG_Util::BackendLoader::AcquireGLESFunctions(m_GLESFunctions, m_EGLFunctions.eglGetProcAddress);
@@ -1238,23 +1230,6 @@ 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);
}
@@ -32,8 +32,6 @@ namespace MobileGL::MG_Backend::DirectGLES {
public:
~BackendObject_DirectGLES() override;
// The driver's verdict on this session's context (DirectGLES::LatchIfDeviceLost).
Bool LatchIfGpuFaulted() override;
void Initialize() override;
Bool InitCapabilities() override;
Bool InitWindowSurface() override;
@@ -53,10 +51,6 @@ 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
+42 -432
View File
@@ -8,7 +8,6 @@
#include "DirectGLES.h"
#include "ContextEpoch.h"
#include "MG_Util/X11/DisplayGuard.h"
#include "EGL/egl.h"
#include "MG_Util/Types.h"
#include "Utils.h"
@@ -427,8 +426,6 @@ namespace MobileGL::MG_Backend::DirectGLES {
// targets with no mip chain map to Unknown so the lookup falls back to no bias.
TextureTarget SamplerUniformTextureTarget(GLenum uniformType) {
switch (uniformType) {
case GL_SAMPLER_EXTERNAL_OES:
return TextureTarget::External;
case GL_SAMPLER_1D:
case GL_INT_SAMPLER_1D:
case GL_UNSIGNED_INT_SAMPLER_1D:
@@ -16772,7 +16769,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
static EGLint QueryDefaultX11VisualId() {
#if defined(__linux__) && !defined(__ANDROID__)
const char* displayName = std::getenv("DISPLAY");
if (!displayName || !MG_Util::X11::MayDialX11Display(displayName)) {
if (!displayName) {
return 0;
}
@@ -16819,7 +16816,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
return 0;
}
const char* displayName = std::getenv("DISPLAY");
if (!displayName || !MG_Util::X11::MayDialX11Display(displayName)) {
if (!displayName) {
return 0;
}
@@ -16984,53 +16981,6 @@ namespace MobileGL::MG_Backend::DirectGLES {
#endif
}
// RESET NOTIFICATION, decided once per process by its first native context (EnsureNativeContext
// says why). MOBILEGL_ESPRYT_RESET_NOTIFICATION=0 keeps the driver's default.
namespace {
// EGL_EXT_create_context_robustness (eglext.h is not part of this file's include set).
constexpr EGLint kEglResetNotificationStrategyExt = 0x3138;
constexpr EGLint kEglLoseContextOnResetExt = 0x31BF;
enum class ResetNotification : Uint8 { Undecided, On, Off };
std::atomic<ResetNotification> g_resetNotification{ResetNotification::Undecided};
Bool ResetNotificationWanted() {
const ResetNotification decided = g_resetNotification.load(std::memory_order_acquire);
if (decided != ResetNotification::Undecided) return decided == ResetNotification::On;
if (const char* value = std::getenv("MOBILEGL_ESPRYT_RESET_NOTIFICATION"); value != nullptr && value[0] == '0')
return false;
if (g_Display == EGL_NO_DISPLAY || !g_EGLFuncs.eglQueryString) return false;
const char* extensions = g_EGLFuncs.eglQueryString(g_Display, EGL_EXTENSIONS);
if (extensions == nullptr) return false;
constexpr const char kWord[] = "EGL_EXT_create_context_robustness";
for (const char* at = std::strstr(extensions, kWord); at != nullptr; at = std::strstr(at + 1, kWord)) {
const char after = at[sizeof(kWord) - 1];
if ((at == extensions || at[-1] == ' ') && (after == '\0' || after == ' ')) return true;
}
return false;
}
void NoteResetNotificationRefused() {
ResetNotification expected = ResetNotification::Undecided;
if (g_resetNotification.compare_exchange_strong(expected, ResetNotification::Off, std::memory_order_acq_rel))
MGLOG_W("DirectGLES: the driver refused EGL_LOSE_CONTEXT_ON_RESET; a context that hangs the GPU is "
"not told, and its session cannot be ended for it");
}
void NoteResetNotificationDecided(Bool used) {
ResetNotification expected = ResetNotification::Undecided;
const ResetNotification decided = used ? ResetNotification::On : ResetNotification::Off;
if (g_resetNotification.compare_exchange_strong(expected, decided, std::memory_order_acq_rel))
MGLOG_I("DirectGLES: native contexts %s reset notification (EGL_LOSE_CONTEXT_ON_RESET): a context "
"whose work hangs or faults the GPU %s",
used ? "ask for" : "do not ask for",
used ? "is named by the driver and ends its own session" : "is not told");
}
} // namespace
Bool NativeContextsNotifyResets() {
return g_resetNotification.load(std::memory_order_acquire) == ResetNotification::On;
}
static Bool EnsureNativeContext(NativeContextTuple& tuple, EGLint surfaceBit, NativeWindowType window) {
if (!EnsureDisplayInitialized()) {
MGLOG_E("EnsureNativeContext: the EGL display did not initialize");
@@ -17079,47 +17029,21 @@ namespace MobileGL::MG_Backend::DirectGLES {
// request yields a 3.0 context that lacks the 3.1/3.2 texture targets the
// capability probes exercise; mobile drivers ignore the minor and hand out
// their maximum either way.
//
// RESET NOTIFICATION. With the driver's default strategy a context whose work hung the GPU
// is never told: after Adreno's ~2 s timeout reset it silently drops everything that context
// submits (the client's window just stops), and its client never learns it should recreate.
// Asking for EGL_LOSE_CONTEXT_ON_RESET lets the driver name the guilty context
// (glGetGraphicsResetStatus answers GUILTY, once) and LatchIfDeviceLost ends that session
// alone, so the client reads a lost context and can recover. (A ~10 s reset that a failed
// preemption ends was not reported to the server's contexts in measurement - see
// GpuHangWatch.h.) Every context of the process shares one group, and contexts that share
// must agree on the strategy, so it is decided once, by the first context, and kept.
for (const EGLint minorVersion : {2, 1, 0}) {
const Bool notify = ResetNotificationWanted();
const EGLint contextAttribs[] = {EGL_CONTEXT_MAJOR_VERSION, 3,
EGL_CONTEXT_MINOR_VERSION, minorVersion,
notify ? kEglResetNotificationStrategyExt : EGL_NONE,
kEglLoseContextOnResetExt,
EGL_NONE};
tuple.Context = g_EGLFuncs.eglCreateContext(g_Display, tuple.Config, share, contextAttribs);
if (tuple.Context == EGL_NO_CONTEXT && notify && share == EGL_NO_CONTEXT) {
// The process's first context: if the same version WITHOUT the strategy is accepted,
// it was the strategy the driver refused, and no context of the process asks for it.
const EGLint plainAttribs[] = {EGL_CONTEXT_MAJOR_VERSION, 3, EGL_CONTEXT_MINOR_VERSION, minorVersion,
EGL_NONE};
tuple.Context = g_EGLFuncs.eglCreateContext(g_Display, tuple.Config, share, plainAttribs);
if (tuple.Context != EGL_NO_CONTEXT) NoteResetNotificationRefused();
}
if (tuple.Context != EGL_NO_CONTEXT) {
NoteResetNotificationDecided(notify);
tuple.Serial = g_nativeContextSerials.fetch_add(1, std::memory_order_relaxed) + 1;
++g_displayUsers;
return true;
}
}
const Bool notify = ResetNotificationWanted();
const EGLint legacyContextAttribs[] = {EGL_CONTEXT_CLIENT_VERSION, 3,
notify ? kEglResetNotificationStrategyExt : EGL_NONE,
kEglLoseContextOnResetExt, EGL_NONE};
const EGLint legacyContextAttribs[] = {EGL_CONTEXT_CLIENT_VERSION, 3, EGL_NONE};
tuple.Context = g_EGLFuncs.eglCreateContext(g_Display, tuple.Config, share, legacyContextAttribs);
if (tuple.Context == EGL_NO_CONTEXT) return false;
NoteResetNotificationDecided(notify);
tuple.Serial = g_nativeContextSerials.fetch_add(1, std::memory_order_relaxed) + 1;
++g_displayUsers;
return true;
@@ -17185,14 +17109,7 @@ 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;
// 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) {
if (g_displayUsers == 0 && g_Display != EGL_NO_DISPLAY && g_EGLFuncs.eglTerminate) {
g_EGLFuncs.eglTerminate(g_Display);
NoteDisplayTerminated();
g_Display = EGL_NO_DISPLAY;
@@ -17220,12 +17137,6 @@ 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;
@@ -17767,8 +17678,6 @@ namespace MobileGL::MG_Backend::DirectGLES {
MGLOG_E_ONCE("DirectGLES::MakeCurrent failed: native eglMakeCurrent returned error 0x%04x", error);
return false;
}
g_EGLFuncs.eglSwapBuffersWithDamageEXT =
MG_Util::BackendLoader::ResolveSwapBuffersWithDamage(g_EGLFuncs);
InvalidateEglVerifiedStamp();
t_boundNativeContext = tuple.Context;
t_boundNativeDraw = session.Draw;
@@ -18306,61 +18215,25 @@ namespace MobileGL::MG_Backend::DirectGLES {
}
#if MOBILEGL_BUILD_DISAGGREGATED
namespace {
// Once per thread: a latched session declines everything after this verb anyway, and the
// apply thread is the session's own.
thread_local Bool t_deviceLossLatched = false;
Bool LatchOnResetStatus(const char* site, GLenum status) {
if (status == GL_NO_ERROR) return false;
// ONLY THE GUILTY CONTEXT ENDS ITS SESSION. The contexts ask for reset notification
// (EnsureNativeContext) so the driver can name the context whose work hung or faulted the
// GPU; a reset it reports to an INNOCENT context - one whose work only waited behind the
// stall, the compositor's above all - is noted and the session goes on as it did before
// contexts were told. Adreno 750 measured: the guilty context reads GUILTY once, after
// which the driver drops everything it submits; innocent ones read NO_ERROR.
static thread_local Bool innocentNoted = false;
if (status == GL_INNOCENT_CONTEXT_RESET) {
if (!innocentNoted) {
innocentNoted = true;
MGLOG_W("Espryt:%s - the driver reports a GPU reset this session's context did not cause "
"(GL_INNOCENT_CONTEXT_RESET); the session goes on",
site != nullptr ? site : "?");
}
return false;
}
t_deviceLossLatched = true;
(void)MG_Pipe::MGPipeSessionLatch(MG_Pipe::MGPipeFatalFamily::DeviceLost,
"MGPipe: Fatal{BackendDeviceLost, \"Espryt:%s\"} - this session's EGL "
"context was reset (glGetGraphicsResetStatus 0x%x); the session ends "
"and its client reads a lost context, every other session keeps running",
site != nullptr ? site : "?", static_cast<unsigned>(status));
return true;
}
} // namespace
Bool LatchIfDeviceLost(const char* site, Bool debugKnob) {
if (MG_Config::Transport == MG_Config::TransportMode::Monolith) return false;
if (t_deviceLossLatched) return true;
// Once per thread: a latched session declines everything after this verb anyway, and the
// apply thread is the session's own.
static thread_local Bool latched = false;
if (latched) return true;
GLenum status = GL_NO_ERROR;
if (g_GLESFuncs.glGetGraphicsResetStatus != nullptr && IsBackendContextCurrentOnThisThread()) {
status = g_GLESFuncs.glGetGraphicsResetStatus();
}
if (status == GL_NO_ERROR && debugKnob && MG_Pipe::MGPipeDebugDeviceLossDue()) status = GL_UNKNOWN_CONTEXT_RESET;
return LatchOnResetStatus(site, status);
}
Bool LatchIfGuiltyBeforeApply() {
if (MG_Config::Transport == MG_Config::TransportMode::Monolith) return false;
if (t_deviceLossLatched) return true;
// Asked every time the apply thread wakes, so it must leave nothing behind: not
// IsBackendContextCurrentOnThisThread, whose once-per-frame EGL verification stamp it would
// spend at the top of the loop (where the session may be between two of its contexts) - only
// whether this thread holds a native context and the backend's ownership.
if (g_GLESFuncs.glGetGraphicsResetStatus == nullptr || t_boundNativeContext == EGL_NO_CONTEXT ||
g_backendContextOwnerThread.load(std::memory_order_acquire) != std::this_thread::get_id())
return false;
return LatchOnResetStatus("apply", g_GLESFuncs.glGetGraphicsResetStatus());
if (status == GL_NO_ERROR) return false;
latched = true;
(void)MG_Pipe::MGPipeSessionLatch(MG_Pipe::MGPipeFatalFamily::DeviceLost,
"MGPipe: Fatal{BackendDeviceLost, \"Espryt:%s\"} - this session's EGL "
"context was reset (glGetGraphicsResetStatus 0x%x); the session ends "
"and its client reads a lost context, every other session keeps running",
site != nullptr ? site : "?", static_cast<unsigned>(status));
return true;
}
#endif
@@ -18416,13 +18289,25 @@ namespace MobileGL::MG_Backend::DirectGLES {
if (const auto* entry = FindSessionSurfaceLocked(session, drawSurface))
windowSurface = entry->Window != static_cast<NativeWindowType>(0);
}
EGLBoolean mglSwapped = EGL_FALSE;
if (g_EGLFuncs.eglSwapBuffersWithDamageEXT != nullptr) {
const MG_Util::Damage::Region& damage = MG_Backend::CurrentPresentDamage();
EGLint rects[MG_Util::Damage::kMaxRects * 4] = {};
const EGLint count = static_cast<EGLint>(MG_Util::Damage::NativeSwapRects(windowSurface, damage, rects));
g_EGLFuncs.eglSwapBuffersWithDamageEXT(g_Display, drawSurface, count > 0 ? rects : nullptr, count);
} else {
g_EGLFuncs.eglSwapBuffers(g_Display, drawSurface);
mglSwapped = g_EGLFuncs.eglSwapBuffersWithDamageEXT(g_Display, drawSurface, count > 0 ? rects : nullptr, count);
// A DRIVER THAT NAMES THE ENTRY POINT AND THEN REFUSES THE SWAP. Some vendor EGLs
// export eglSwapBuffersWithDamageEXT and answer EGL_FALSE on a window surface without
// setting an error (measured on a 4.14 vendor kernel with an Adreno driver; the plain
// entry point presents the same surface happily). Keeping the frame on that answer
// queues nothing at all: the compositor composites into a window whose buffer queue
// never sees a buffer. Fall back to the plain call instead of dropping the frame.
if (mglSwapped == EGL_FALSE && g_EGLFuncs.eglSwapBuffers != nullptr) {
MGLOG_W_ONCE("DirectGLES: this driver's eglSwapBuffersWithDamageEXT refused a window "
"surface; presenting through eglSwapBuffers for the rest of the process");
mglSwapped = g_EGLFuncs.eglSwapBuffers(g_Display, drawSurface);
}
} else if (g_EGLFuncs.eglSwapBuffers != nullptr) {
mglSwapped = g_EGLFuncs.eglSwapBuffers(g_Display, drawSurface);
}
if (drawSurface != EGL_NO_SURFACE) {
const std::lock_guard<std::mutex> lock(g_nativeRegistryMutex);
@@ -18608,14 +18493,18 @@ namespace MobileGL::MG_Backend::DirectGLES {
WaitSyncKhrFn WaitSync = nullptr;
ClientWaitSyncKhrFn ClientWaitSync = nullptr;
DupNativeFenceFdFn DupNativeFenceFd = nullptr;
// YUV images: sampled as external textures (GL_OES_EGL_image_external_essl3), and
// through GL_EXT_YUV_target's raw Y'CbCr sampler where the driver has it, so the
// conversion is the import's own (its colour hints) rather than the driver's guess.
Bool ExternalEssl3 = false;
Bool YuvTarget = false;
};
using MG_Util::BackendLoader::HasExtensionWord;
Bool HasExtensionWord(const char* list, const char* word) {
if (list == nullptr) return false;
const SizeT n = std::strlen(word);
for (const char* at = std::strstr(list, word); at != nullptr; at = std::strstr(at + 1, word)) {
const Bool startOk = at == list || at[-1] == ' ';
const Bool endOk = at[n] == '\0' || at[n] == ' ';
if (startOk && endOk) return true;
}
return false;
}
// None of these is in the loader's tables, and eglGetProcAddress hands back live-looking
// stubs for entry points a driver lacks, so the extension strings decide first. Resolved
@@ -18667,8 +18556,6 @@ namespace MobileGL::MG_Backend::DirectGLES {
entry->Why = "GL_OES_EGL_image is not advertised";
return *entry;
}
entry->ExternalEssl3 = HasExtensionWord(gl, "GL_OES_EGL_image_external_essl3");
entry->YuvTarget = HasExtensionWord(gl, "GL_EXT_YUV_target");
entry->GetNativeClientBuffer = reinterpret_cast<GetNativeClientBufferFn>(
g_EGLFuncs.eglGetProcAddress("eglGetNativeClientBufferANDROID"));
entry->CreateImage =
@@ -18708,11 +18595,6 @@ namespace MobileGL::MG_Backend::DirectGLES {
Uint64 WaitedGeneration = 0;
Uint64 WaitedContext = 0;
Uint64 NotedFrame = 0;
// A YUV image (ConvertYuvForSampling): an external texture over the EGLImage, the source
// of the conversion into the texture's own RGBA storage, and the reader's frame the
// conversion last ran in.
GLuint ExternalTexture = 0;
Uint64 ConvertedFrame = 0;
~EglImage() {
// eglDestroyImageKHR needs the display, not a context, so a session's twin teardown
@@ -18720,10 +18602,6 @@ namespace MobileGL::MG_Backend::DirectGLES {
// display - which destroyed the image itself - skip it.
if (Handle == nullptr || Destroy == nullptr || InProcessExit()) return;
if (g_displayTerminations.load(std::memory_order_acquire) != DisplayTerminations) return;
// Texture names are the share group's: deleting one needs any context of it, and
// without one current the name goes with the display.
if (ExternalTexture != 0 && t_boundNativeContext != EGL_NO_CONTEXT)
g_GLESFuncs.glDeleteTextures(1, &ExternalTexture);
Destroy(Display, Handle);
}
#endif
@@ -18946,26 +18824,14 @@ 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;
// When a YUV image is converted again (ConvertYuvForSampling): renewed at EVERY
// boundary - present, publishing flush, and each native fence whatever the session
// is - since an offscreen producer (a browser's GPU process) may have no other.
Uint64 YuvEpoch = 0;
};
std::atomic<Uint64> g_readFrameIds{0};
ReadFrame& CurrentReadFrame() {
thread_local ReadFrame frame;
if (frame.Id == 0) frame.Id = g_readFrameIds.fetch_add(1, std::memory_order_relaxed) + 1;
if (frame.YuvEpoch == 0) frame.YuvEpoch = g_readFrameIds.fetch_add(1, std::memory_order_relaxed) + 1;
return frame;
}
void RenewYuvEpoch(ReadFrame& frame) {
frame.YuvEpoch = g_readFrameIds.fetch_add(1, std::memory_order_relaxed) + 1;
}
} // namespace
void AcquireForSampling(const EglImageRef& image) {
@@ -18985,250 +18851,13 @@ 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 IsYuv(const EglImageRef& image) {
return image != nullptr && image->Image != nullptr && SI::FourccIsYuv(image->Image->Fourcc);
}
namespace {
// THE CONVERSION PASS: one triangle over the texture, sampling the image through an
// external texture. Programs are the share group's and rebuilt with a new context
// generation; the framebuffer and vertex array are per context (never shared).
struct YuvConversion {
Uint ContextGeneration = ~0u;
GLuint ExternalProgram = 0; // the driver's conversion (samplerExternalOES)
GLuint TargetProgram = 0; // the import's own (GL_EXT_YUV_target)
GLint TargetMatrix = -1;
GLint TargetOffset = -1;
Bool Failed = false;
NativeContextName Framebuffer;
NativeContextName VertexArray;
};
YuvConversion& Conversion() {
static auto* conversion = new YuvConversion();
return *conversion;
}
constexpr const char* kYuvVertexSource =
"#version 300 es\n"
"out vec2 vUv;\n"
"void main() {\n"
" vec2 p = vec2(float((gl_VertexID << 1) & 2), float(gl_VertexID & 2));\n"
" gl_Position = vec4(p * 2.0 - 1.0, 0.0, 1.0);\n"
" vUv = p;\n"
"}\n";
constexpr const char* kYuvExternalFragmentSource =
"#version 300 es\n"
"#extension GL_OES_EGL_image_external_essl3 : require\n"
"precision highp float;\n"
"uniform samplerExternalOES uSource;\n"
"in vec2 vUv;\n"
"out vec4 oColor;\n"
"void main() { oColor = vec4(texture(uSource, vUv).rgb, 1.0); }\n";
constexpr const char* kYuvTargetFragmentSource =
"#version 300 es\n"
"#extension GL_EXT_YUV_target : require\n"
"precision highp float;\n"
"uniform __samplerExternal2DY2YEXT uSource;\n"
"uniform mat3 uMatrix;\n"
"uniform vec3 uOffset;\n"
"in vec2 vUv;\n"
"out vec4 oColor;\n"
"void main() {\n"
" vec3 ycbcr = texture(uSource, vUv).xyz;\n"
" oColor = vec4(clamp(uMatrix * (ycbcr - uOffset), 0.0, 1.0), 1.0);\n"
"}\n";
GLuint BuildYuvProgram(const char* fragmentSource) {
const GLuint vertexShader = g_GLESFuncs.glCreateShader(GL_VERTEX_SHADER);
const GLuint fragmentShader = g_GLESFuncs.glCreateShader(GL_FRAGMENT_SHADER);
GLint linked = GL_FALSE;
GLuint program = 0;
if (vertexShader != 0 && fragmentShader != 0) {
g_GLESFuncs.glShaderSource(vertexShader, 1, &kYuvVertexSource, nullptr);
g_GLESFuncs.glCompileShader(vertexShader);
g_GLESFuncs.glShaderSource(fragmentShader, 1, &fragmentSource, nullptr);
g_GLESFuncs.glCompileShader(fragmentShader);
program = g_GLESFuncs.glCreateProgram();
if (program != 0) {
g_GLESFuncs.glAttachShader(program, vertexShader);
g_GLESFuncs.glAttachShader(program, fragmentShader);
g_GLESFuncs.glLinkProgram(program);
g_GLESFuncs.glGetProgramiv(program, GL_LINK_STATUS, &linked);
}
}
if (vertexShader != 0) g_GLESFuncs.glDeleteShader(vertexShader);
if (fragmentShader != 0) g_GLESFuncs.glDeleteShader(fragmentShader);
if (linked != GL_TRUE) {
if (program != 0) g_GLESFuncs.glDeleteProgram(program);
return 0;
}
return program;
}
// MOBILEGL_YUV_DRIVER_CONVERSION=1: always the driver's conversion (samplerExternalOES),
// even where GL_EXT_YUV_target would let the import's hints decide.
Bool DriverConversionForced() {
static const Bool forced = [] {
const char* value = std::getenv("MOBILEGL_YUV_DRIVER_CONVERSION");
return value != nullptr && value[0] == '1';
}();
return forced;
}
} // namespace
void ConvertYuvForSampling(const EglImageRef& image, GLuint target, Uint32 width, Uint32 height) {
if (!IsYuv(image) || target == 0 || width == 0 || height == 0) return;
EglImage& state = *image;
ReadFrame& frame = CurrentReadFrame();
if (state.ConvertedFrame == frame.YuvEpoch) return;
// Whatever happens below, this frame does not try again.
state.ConvertedFrame = frame.YuvEpoch;
const EntryPoints& entry = ResolvedEntryPoints();
if (!entry.Usable || !entry.ExternalEssl3) {
MGLOG_E_ONCE("Shared images: a YUV image cannot be sampled here (%s)",
entry.Usable ? "no GL_OES_EGL_image_external_essl3" : entry.Why.c_str());
return;
}
// THE CPU-COPY FALLBACK, for a buffer this server did not allocate (SharedImageRegistry.h).
String why;
if (state.Image->IsForeign() && !SI::RefreshForeign(*state.Image, why)) {
MGLOG_E_ONCE("Shared images: foreign YUV image %llu could not be refreshed: %s",
static_cast<unsigned long long>(state.Image->Id), why.c_str());
}
YuvConversion& conversion = Conversion();
if (conversion.ContextGeneration != g_backendContextGeneration) {
conversion.ExternalProgram = 0;
conversion.TargetProgram = 0;
conversion.TargetMatrix = conversion.TargetOffset = -1;
conversion.Failed = false;
conversion.ContextGeneration = g_backendContextGeneration;
}
if (conversion.Failed) return;
const Bool ownConversion = entry.YuvTarget && !DriverConversionForced();
GLuint& program = ownConversion ? conversion.TargetProgram : conversion.ExternalProgram;
if (program == 0) {
program = BuildYuvProgram(ownConversion ? kYuvTargetFragmentSource : kYuvExternalFragmentSource);
if (program == 0) {
conversion.Failed = true;
MGLOG_E_ONCE("Shared images: the YUV conversion program could not be built");
return;
}
if (ownConversion) {
conversion.TargetMatrix = g_GLESFuncs.glGetUniformLocation(program, "uMatrix");
conversion.TargetOffset = g_GLESFuncs.glGetUniformLocation(program, "uOffset");
}
MGLOG_I("Shared images: YUV images convert through %s",
ownConversion ? "GL_EXT_YUV_target with the import's colour hints"
: "the driver's external-sampler conversion");
}
if (conversion.Framebuffer == 0) g_GLESFuncs.glGenFramebuffers(1, &conversion.Framebuffer);
if (conversion.VertexArray == 0) g_GLESFuncs.glGenVertexArrays(1, &conversion.VertexArray);
if (conversion.Framebuffer == 0 || conversion.VertexArray == 0) return;
// Every binding goes through Espryt's shadows or a guard that puts it back.
ScopedEmulationDrawState drawState; // also activates TextureImpl::TempTextureUnit
ScopedFramebufferBinding binding(/*saveRead=*/false, /*saveDraw=*/true);
DrainErrors();
if (state.ExternalTexture == 0) {
g_GLESFuncs.glGenTextures(1, &state.ExternalTexture);
g_GLESFuncs.glBindTexture(GL_TEXTURE_EXTERNAL_OES, state.ExternalTexture);
entry.TargetTexture2D(GL_TEXTURE_EXTERNAL_OES, state.Handle);
g_GLESFuncs.glTexParameteri(GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
g_GLESFuncs.glTexParameteri(GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
g_GLESFuncs.glTexParameteri(GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
g_GLESFuncs.glTexParameteri(GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
const GLenum error = g_GLESFuncs.glGetError();
if (error != GL_NO_ERROR) {
MGLOG_E_ONCE("Shared images: YUV image %llu cannot be bound as an external texture (0x%04x)",
static_cast<unsigned long long>(state.Image->Id), static_cast<unsigned>(error));
}
} else {
g_GLESFuncs.glBindTexture(GL_TEXTURE_EXTERNAL_OES, state.ExternalTexture);
}
FramebufferImpl::BindFramebufferId(GL_DRAW_FRAMEBUFFER, conversion.Framebuffer);
g_GLESFuncs.glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, target, 0);
const GLenum status = g_GLESFuncs.glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER);
if (status == GL_FRAMEBUFFER_COMPLETE) {
VertexArrayImpl::BindBackendVAOId(conversion.VertexArray);
g_GLESFuncs.glUseProgram(program);
g_GLESFuncs.glUniform1i(g_GLESFuncs.glGetUniformLocation(program, "uSource"),
static_cast<GLint>(TextureImpl::TempTextureUnit));
if (ownConversion) {
// A Y2Y sample is the stored code normalized as the format stores it: 8 bits, or
// P010's 10 in the high end of 16.
const double sampleMax = state.Image->Fourcc == SI::kFourccP010 ? 65535.0 / 64.0 : 255.0;
const auto c = SI::Yuv::ConversionFor(SI::GetYuvHints(*state.Image), sampleMax);
g_GLESFuncs.glUniformMatrix3fv(conversion.TargetMatrix, 1, GL_FALSE, c.Matrix);
g_GLESFuncs.glUniform3fv(conversion.TargetOffset, 1, c.Offset);
}
g_GLESFuncs.glViewport(0, 0, static_cast<GLsizei>(width), static_cast<GLsizei>(height));
g_GLESFuncs.glDrawArrays(GL_TRIANGLES, 0, 3);
const GLenum error = g_GLESFuncs.glGetError();
if (error != GL_NO_ERROR) {
MGLOG_E_ONCE("Shared images: the YUV conversion draw failed (0x%04x)", static_cast<unsigned>(error));
}
} else {
MGLOG_E_ONCE("Shared images: a YUV conversion target is not renderable (0x%04x)",
static_cast<unsigned>(status));
}
g_GLESFuncs.glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, 0, 0);
g_GLESFuncs.glBindTexture(GL_TEXTURE_EXTERNAL_OES, 0);
}
Bool PublishPendingAccesses() {
ReadFrame& frame = CurrentReadFrame();
frame.ImplicitSync = true;
RenewYuvEpoch(frame);
// 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();
RenewYuvEpoch(frame);
// 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();
RenewYuvEpoch(frame);
if (frame.Tracker.Pending() == 0) return;
int fence = -1;
// No context current: the reads' context is gone (and its work with it), and there is
@@ -19239,12 +18868,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
// producer), nothing it submitted still samples the image.
(void)WaitForCompletion();
}
// 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.Tracker.PublishFrame(fence);
frame.Id = g_readFrameIds.fetch_add(1, std::memory_order_relaxed) + 1;
}
@@ -19421,21 +19045,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
return false;
}
void AcquireForSampling(const EglImageRef& image) { (void)image; }
Bool IsYuv(const EglImageRef& image) {
(void)image;
return false;
}
void ConvertYuvForSampling(const EglImageRef& image, GLuint target, Uint32 width, Uint32 height) {
(void)image, (void)target, (void)width, (void)height;
}
void PublishPendingReads() {}
Bool PublishPendingAccesses() { return true; }
Bool ExportNativeFence(int* fence) {
*fence = -1;
return true;
}
void ForgetPresentTargetsAfterTerminate() {}
#endif
} // namespace SharedImageImpl
+4 -28
View File
@@ -162,21 +162,14 @@ namespace MobileGL::MG_Backend::DirectGLES {
// driver whether the calling thread's context was reset (glGetGraphicsResetStatus); a reset -
// or the debug knob MGPipeDebugDeviceLossDue - latches THIS session through
// MGPipeSessionLatch and answers true, and the caller returns from its verb without issuing
// more GL. Asked at the frame boundaries (Present, a shared-image present), before a readback,
// and by the apply loop each time it wakes (LatchIfGpuFaulted), never per draw. The contexts ask
// for reset notification (NativeContextsNotifyResets) so the driver can name the GUILTY one;
// only GUILTY (or a reset of unknown cause) ends the session - an INNOCENT report, a context
// whose work merely waited behind another's hang (the compositor's among them), is only noted.
// more GL. Asked at the frame boundaries (Present, a shared-image present) and before a
// readback, never per draw. The contexts keep the driver's default reset strategy: asking
// every context to lose itself on reset would also end the INNOCENT ones - the compositor's
// among them - on any other client's GPU fault.
// `debugKnob` false: the knob is not consulted here (the on-screen Present, so an injected loss
// lands on an offscreen client's shared-image present or readback, never on the compositor's).
Bool LatchIfDeviceLost(const char* site, Bool debugKnob = true);
// The apply loop's form of it (BackendObject::LatchIfGpuFaulted), asked each time the apply thread
// wakes: the driver's report only, no debug knob, and no EGL ground-truth verification spent.
Bool LatchIfGuiltyBeforeApply();
#endif
// True once the process's native contexts were created with EGL_LOSE_CONTEXT_ON_RESET (decided
// by the first one; the driver must offer EGL_EXT_create_context_robustness).
Bool NativeContextsNotifyResets();
// GL fence sync objects, backed by native ES fences. FenceSync returns null
// (the frontend then falls back to an always-signaled sync) when the calling
// thread does not own the ES context. Waits/queries degrade to "signaled" in
@@ -548,28 +541,11 @@ namespace MobileGL::MG_Backend::DirectGLES {
// landed since this context last waited, the context's later commands wait for its fence
// on the GPU; and the image is noted as read by the calling session's current frame.
void AcquireForSampling(const EglImageRef& image);
// YUV IMAGES (NV12/P010, MG_Remote/Server/SharedImageYuv.h) are never a name's level 0: the
// name keeps its own RGBA8 storage `target` (width x height), into which the image is
// converted at its first use in each of the calling session's frames - the image bound as
// an external texture, one triangle drawn - after the registry's CPU copy for a foreign
// buffer. Every touched binding is put back. Called after AcquireForSampling.
Bool IsYuv(const EglImageRef& image);
void ConvertYuvForSampling(const EglImageRef& image, GLuint target, Uint32 width, Uint32 height);
// The calling session's frame boundary for what it has read: hands a fence for everything
// the current context has submitted to every image noted since the last boundary. Called
// at Present and wherever the current native context stops being current (its reads can
// only be fenced from it). Nothing noted = nothing done.
void PublishPendingReads();
// 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
+31 -121
View File
@@ -2898,7 +2898,16 @@ namespace MobileGL::MG_Backend::DirectGLES {
kT0MapReadBit | kT0MapWriteBit | kMapPersistentBit | kMapCoherentBit | kDynamicStorageBit;
constexpr GLbitfield kT0MapFlags = kT0MapReadBit | kT0MapWriteBit | kMapPersistentBit | kMapCoherentBit;
using MG_Util::BackendLoader::HasExtensionWord;
Bool HasExtensionWord(const char* list, const char* word) {
if (list == nullptr) return false;
const SizeT n = std::strlen(word);
for (const char* at = std::strstr(list, word); at != nullptr; at = std::strstr(at + 1, word)) {
const Bool startOk = at == list || at[-1] == ' ';
const Bool endOk = at[n] == '\0' || at[n] == ' ';
if (startOk && endOk) return true;
}
return false;
}
Bool ResolveT0EntryPoints(String& why) {
if (g_t0GetNativeClientBuffer != nullptr && g_t0BufferStorageExternal != nullptr) return true;
@@ -3894,13 +3903,8 @@ namespace MobileGL::MG_Backend::DirectGLES {
MG_Pipe::MGPipeSetResourceOps(&g_glesResourceOps);
#endif
// Frontend writes issued while ops were unregistered advanced change
// serials with no per-op bump; re-open every draw-clean memo. Advanced directly,
// past BumpBufferMutationEpoch's apply-thread pin: a registration mutates no buffer
// and only makes every memo probe again, and with several sessions in one process
// a new session's backend registers on its own thread while another session's
// apply thread is already running - which the pin would otherwise read as a
// client-thread producer and, under the strict lane, abort the server for.
g_bufferMutationEpoch.fetch_add(1, std::memory_order_release);
// serials with no per-op bump; re-open every draw-clean memo.
BumpBufferMutationEpoch();
}
void UnregisterBufferBackendOps() {
@@ -8854,12 +8858,27 @@ 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. Pending sub-data is the caller's
// (ReplaySharedImageUploads), after the image's sync state has been acquired.
// retried only once the record moves.
if (m_sharedImageId == imageId && m_isInitialized &&
(m_sharedImage != nullptr || m_syncedResourceSerial == record.Serial)) {
dropPendingUploads();
m_syncedResourceSerial = record.Serial;
return true;
}
@@ -8874,6 +8893,7 @@ 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) {
@@ -8889,26 +8909,12 @@ namespace MobileGL::MG_Backend::DirectGLES {
return true;
}
Bind(GL_TEXTURE_2D);
if (SharedImageImpl::IsYuv(image)) {
// A YUV image is CONVERTED into the name's own RGBA8 level at each frame's first use
// (SharedImageImpl::ConvertYuvForSampling), never made its storage.
while (g_GLESFuncs.glGetError() != GL_NO_ERROR) {
}
g_GLESFuncs.glTexStorage2D(GL_TEXTURE_2D, 1, GL_RGBA8, static_cast<GLsizei>(record.Desc.Width),
static_cast<GLsizei>(record.Desc.Height));
if (g_GLESFuncs.glGetError() != GL_NO_ERROR) {
MGLOG_E_ONCE("Shared image texture %u: no %ux%u RGBA8 storage for YUV image %llu; left empty",
record.Desc.GlNameForDiag, record.Desc.Width, record.Desc.Height,
static_cast<unsigned long long>(imageId));
return true;
}
} else if (!SharedImageImpl::TargetBoundTexture2D(image)) {
if (!SharedImageImpl::TargetBoundTexture2D(image)) {
MGLOG_E_ONCE("Shared image texture %u: glEGLImageTargetTexture2DOES refused image %llu; left empty",
record.Desc.GlNameForDiag, static_cast<unsigned long long>(imageId));
return true;
}
m_sharedImage = std::move(image);
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,
@@ -8920,83 +8926,6 @@ 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(
@@ -9050,11 +8979,6 @@ 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);
// A YUV image is converted into the name at the frame's first use.
if (m_sharedImage != nullptr && SharedImageImpl::IsYuv(m_sharedImage))
SharedImageImpl::ConvertYuvForSampling(m_sharedImage, GetBackendTextureId(),
pushedStorage->Desc.Width, pushedStorage->Desc.Height);
return;
}
// P5e (tx2), CONTRACT-P5E §5.2 (scout G-S2-2): THE VIEW TEST MOVES BEHIND THE
@@ -11324,20 +11248,6 @@ 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.
-11
View File
@@ -1944,7 +1944,6 @@ namespace MobileGL::MG_Backend::DirectGLES {
switch (target) {
case TextureTarget::Texture1D:
case TextureTarget::TextureRectangle:
case TextureTarget::External:
return TextureTarget::Texture2D;
case TextureTarget::Texture1DArray:
return TextureTarget::Texture2DArray;
@@ -2112,10 +2111,6 @@ 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
@@ -2488,12 +2483,6 @@ 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;
+1 -4
View File
@@ -572,10 +572,7 @@ namespace MobileGL::MG_Backend::DirectGLES {
ZoneScopedC(TRACY_ZONECOLOR_BACKEND);
#endif
// The name is the marker: ShaderSourceProcessor only emits it when the source
// 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.
// wrote gl_FragColor, and such a shader can have no other output.
static const char* const kLoweredName = "mg_FragColor";
if (shaderType != GL_FRAGMENT_SHADER || drawBufferCount <= 1) {
return glslCode;
@@ -422,14 +422,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
static_cast<unsigned long long>(m_magmaSession->Id()));
}
Bool BackendObject_DirectVulkan::LatchIfGpuFaulted() {
#if MOBILEGL_BUILD_DISAGGREGATED
return pVulkanRenderer != nullptr && pVulkanRenderer->LatchIfGpuHung("apply");
#else
return false;
#endif
}
void BackendObject_DirectVulkan::Initialize() {
#if MOBILEGL_BUILD_DISAGGREGATED
VkBufferManager::RegisterWireResourceOps();
@@ -593,25 +585,6 @@ 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) {
@@ -28,8 +28,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
void Initialize() override;
void BindSessionStateToThisThread() override;
// The GPU hang watch's verdict on this session's device (VulkanRenderer::LatchIfGpuHung).
Bool LatchIfGpuFaulted() override;
void OnClientContextBound(Uint64 token) override;
Bool InitWindowSurface() override;
Bool InitCapabilities() override;
@@ -44,10 +42,6 @@ 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,
@@ -66,11 +66,7 @@ namespace MobileGL::MG_Backend::DirectVulkan {
FreeRetiredCommandBuffers(frame);
}
vkFreeCommandBuffers(device, commandPool, frameCount * 2, commandBuffers.data());
if (!m_spareCommandBuffers.empty())
vkFreeCommandBuffers(device, commandPool, static_cast<Uint32>(m_spareCommandBuffers.size()),
m_spareCommandBuffers.data());
}
m_spareCommandBuffers.clear();
m_frames.clear();
currentFrameIndex = 0;
m_device = VK_NULL_HANDLE;
@@ -366,16 +362,21 @@ namespace MobileGL::MG_Backend::DirectVulkan {
MOBILEGL_ASSERT(!frame.isPreCommandRecording,
"RetireCurrentCommandBuffer called while the pre-pass stream is still recording");
VkCommandBufferAllocateInfo allocInfo{};
allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
allocInfo.commandPool = m_commandPool;
allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
allocInfo.commandBufferCount = 1;
VkCommandBuffer replacement = VK_NULL_HANDLE;
VkResult result = TakeCommandBuffer(replacement);
VkResult result = vkAllocateCommandBuffers(m_device, &allocInfo, &replacement);
if (result != VK_SUCCESS) {
return result;
}
if (retirePreCommandBuffer) {
VkCommandBuffer preReplacement = VK_NULL_HANDLE;
result = TakeCommandBuffer(preReplacement);
result = vkAllocateCommandBuffers(m_device, &allocInfo, &preReplacement);
if (result != VK_SUCCESS) {
RecycleCommandBuffer(replacement);
vkFreeCommandBuffers(m_device, m_commandPool, 1, &replacement);
return result;
}
frame.retiredCommandBuffers.push_back({frame.preCommandBuffer, frame.lastSubmitIndex});
@@ -410,7 +411,8 @@ namespace MobileGL::MG_Backend::DirectVulkan {
SizeT completedCount = 0;
while (completedCount < frame.retiredCommandBuffers.size() &&
frame.retiredCommandBuffers[completedCount].submitIndex <= completedSubmitIndex) {
RecycleCommandBuffer(frame.retiredCommandBuffers[completedCount].commandBuffer);
vkFreeCommandBuffers(m_device, m_commandPool, 1,
&frame.retiredCommandBuffers[completedCount].commandBuffer);
++completedCount;
}
if (completedCount > 0) {
@@ -420,31 +422,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
}
}
VkResult FrameContext::TakeCommandBuffer(VkCommandBuffer& out) {
if (!m_spareCommandBuffers.empty()) {
out = m_spareCommandBuffers.back();
m_spareCommandBuffers.pop_back();
return VK_SUCCESS;
}
VkCommandBufferAllocateInfo allocInfo{};
allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
allocInfo.commandPool = m_commandPool;
allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
allocInfo.commandBufferCount = 1;
return vkAllocateCommandBuffers(m_device, &allocInfo, &out);
}
void FrameContext::RecycleCommandBuffer(VkCommandBuffer commandBuffer) {
// A handful covers the buffers in flight between two completions; beyond that, free.
constexpr SizeT kSpareCommandBuffers = 8;
if (commandBuffer == VK_NULL_HANDLE) return;
if (m_spareCommandBuffers.size() < kSpareCommandBuffers) {
m_spareCommandBuffers.push_back(commandBuffer);
return;
}
vkFreeCommandBuffers(m_device, m_commandPool, 1, &commandBuffer);
}
void FrameContext::FreeAllRetiredCommandBuffers() {
for (auto& frame : m_frames) {
FreeRetiredCommandBuffers(frame);
@@ -150,10 +150,5 @@ namespace MobileGL::MG_Backend::DirectVulkan {
// Stored at Initialize for retired-command-buffer management.
VkDevice m_device = VK_NULL_HANDLE;
VkCommandPool m_commandPool = VK_NULL_HANDLE;
// Completed command buffers kept for the next retirement instead of being freed and
// reallocated: the pool resets a buffer implicitly at its next vkBeginCommandBuffer.
Vector<VkCommandBuffer> m_spareCommandBuffers;
VkResult TakeCommandBuffer(VkCommandBuffer& out);
void RecycleCommandBuffer(VkCommandBuffer commandBuffer);
};
} // namespace MobileGL::MG_Backend::DirectVulkan
@@ -1,202 +0,0 @@
// MobileGL - MobileGL/MG_Backend/DirectVulkan/Renderer/GpuProgressMarkers.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 "GpuProgressMarkers.h"
#include <MG_Util/Debug/Log.h>
namespace MobileGL::MG_Backend::DirectVulkan {
namespace Watch = MG_Backend::GpuHangWatch;
void GpuProgressMarkers::Init(VkDevice device, Uint32 queueFamilyIndex) {
if (m_device != VK_NULL_HANDLE || device == VK_NULL_HANDLE) return;
if (Watch::BudgetMs() == 0) {
MGLOG_I("Magma: GPU hang watch off (MOBILEGL_GPU_HANG_BUDGET_MS=0)");
return;
}
VkCommandPoolCreateInfo poolInfo{VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO};
poolInfo.queueFamilyIndex = queueFamilyIndex;
if (vkCreateCommandPool(device, &poolInfo, nullptr, &m_pool) != VK_SUCCESS) {
MGLOG_W("Magma: GPU hang watch off - no command pool for its markers");
m_pool = VK_NULL_HANDLE;
return;
}
m_device = device;
{
const std::lock_guard<std::mutex> lock(m_mutex);
if (!AddSlot()) {
MGLOG_W("Magma: GPU hang watch off - the device cannot make its progress markers");
vkDestroyCommandPool(m_device, m_pool, nullptr);
m_pool = VK_NULL_HANDLE;
m_device = VK_NULL_HANDLE;
return;
}
}
m_watch = Watch::Register(this, &Sample, &OnHung);
MGLOG_I("Magma: GPU hang watch on - a submission the GPU started and has not finished after %u ms ends "
"its session",
Watch::BudgetMs());
}
void GpuProgressMarkers::Shutdown() {
// The watch first, outside m_mutex: Unregister waits out a sample in progress, which takes it.
Watch::Unregister(m_watch);
m_watch = 0;
if (m_device == VK_NULL_HANDLE) return;
const std::lock_guard<std::mutex> lock(m_mutex);
for (Slot& slot : m_slots) {
if (slot.Started != VK_NULL_HANDLE) vkDestroyEvent(m_device, slot.Started, nullptr);
if (slot.Finished != VK_NULL_HANDLE) vkDestroyEvent(m_device, slot.Finished, nullptr);
}
m_slots.clear();
if (m_pool != VK_NULL_HANDLE) vkDestroyCommandPool(m_device, m_pool, nullptr); // frees the buffers
m_pool = VK_NULL_HANDLE;
m_device = VK_NULL_HANDLE;
}
Bool GpuProgressMarkers::AddSlot() {
if (m_slots.size() >= kMaxSlots) return false;
Slot slot;
const VkEventCreateInfo eventInfo{VK_STRUCTURE_TYPE_EVENT_CREATE_INFO};
VkCommandBuffer buffers[2] = {VK_NULL_HANDLE, VK_NULL_HANDLE};
VkCommandBufferAllocateInfo allocInfo{VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO};
allocInfo.commandPool = m_pool;
allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
allocInfo.commandBufferCount = 2;
const auto fail = [&] {
if (slot.Started != VK_NULL_HANDLE) vkDestroyEvent(m_device, slot.Started, nullptr);
if (slot.Finished != VK_NULL_HANDLE) vkDestroyEvent(m_device, slot.Finished, nullptr);
if (buffers[0] != VK_NULL_HANDLE) vkFreeCommandBuffers(m_device, m_pool, 2, buffers);
return false;
};
if (vkCreateEvent(m_device, &eventInfo, nullptr, &slot.Started) != VK_SUCCESS ||
vkCreateEvent(m_device, &eventInfo, nullptr, &slot.Finished) != VK_SUCCESS ||
vkAllocateCommandBuffers(m_device, &allocInfo, buffers) != VK_SUCCESS)
return fail();
// Prerecorded once and resubmitted for every submission the slot brackets; SIMULTANEOUS_USE
// because the slot is reused once its `finished` event is set, which can be a moment before
// the submission that set it formally leaves the pending state.
VkCommandBufferBeginInfo beginInfo{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO};
beginInfo.flags = VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT;
if (vkBeginCommandBuffer(buffers[0], &beginInfo) != VK_SUCCESS) return fail();
vkCmdSetEvent(buffers[0], slot.Started, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT);
if (vkEndCommandBuffer(buffers[0]) != VK_SUCCESS) return fail();
if (vkBeginCommandBuffer(buffers[1], &beginInfo) != VK_SUCCESS) return fail();
vkCmdSetEvent(buffers[1], slot.Finished, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT);
if (vkEndCommandBuffer(buffers[1]) != VK_SUCCESS) return fail();
slot.Begin = buffers[0];
slot.End = buffers[1];
m_slots.push_back(slot);
return true;
}
GpuProgressMarkers::Bracket GpuProgressMarkers::Acquire() {
Bracket bracket;
if (m_device == VK_NULL_HANDLE) return bracket;
const std::lock_guard<std::mutex> lock(m_mutex);
if (m_lost) return bracket;
Slot* free = nullptr;
for (Slot& slot : m_slots) {
if (slot.Claimed) continue;
// Retire what finished since the watch last looked: frames come faster than its polls.
if (slot.InFlight && vkGetEventStatus(m_device, slot.Finished) == VK_EVENT_SET) slot.InFlight = false;
if (!slot.InFlight && free == nullptr) free = &slot;
}
if (free == nullptr) {
if (!AddSlot()) return bracket;
free = &m_slots.back();
}
if (free->Dirty) {
if (vkResetEvent(m_device, free->Started) != VK_SUCCESS ||
vkResetEvent(m_device, free->Finished) != VK_SUCCESS)
return bracket;
free->Dirty = false;
}
free->Claimed = true;
bracket.Begin = free->Begin;
bracket.End = free->End;
bracket.Slot = static_cast<Uint32>(free - m_slots.data());
return bracket;
}
void GpuProgressMarkers::Submitted(const Bracket& bracket) {
if (!bracket.Valid()) return;
const std::lock_guard<std::mutex> lock(m_mutex);
if (bracket.Slot >= m_slots.size()) return;
Slot& slot = m_slots[bracket.Slot];
slot.Claimed = false;
slot.InFlight = true;
slot.Dirty = true;
slot.Id = m_nextId++;
}
void GpuProgressMarkers::Abandon(const Bracket& bracket) {
if (!bracket.Valid()) return;
const std::lock_guard<std::mutex> lock(m_mutex);
if (bracket.Slot >= m_slots.size()) return;
// A failed vkQueueSubmit may still have consumed nothing or something: reset before reuse.
m_slots[bracket.Slot].Claimed = false;
m_slots[bracket.Slot].Dirty = true;
}
Bool GpuProgressMarkers::Sample(void* self, Vector<MG_Backend::GpuHangWatch::SubmissionProgress>& out) {
auto* markers = static_cast<GpuProgressMarkers*>(self);
const std::lock_guard<std::mutex> lock(markers->m_mutex);
if (markers->m_lost || markers->m_device == VK_NULL_HANDLE) return false;
for (Slot& slot : markers->m_slots) {
if (!slot.InFlight) continue;
const VkResult finished = vkGetEventStatus(markers->m_device, slot.Finished);
const VkResult started = vkGetEventStatus(markers->m_device, slot.Started);
if ((finished != VK_EVENT_SET && finished != VK_EVENT_RESET) ||
(started != VK_EVENT_SET && started != VK_EVENT_RESET)) {
// VK_ERROR_DEVICE_LOST: the driver already reset the device and says so itself.
markers->m_lost = true;
return false;
}
if (finished == VK_EVENT_SET) {
slot.InFlight = false;
continue;
}
out.push_back({slot.Id, started == VK_EVENT_SET, false});
}
return true;
}
void GpuProgressMarkers::OnHung(void* self, Uint64 submissionId, Uint64 runningMs) {
auto* markers = static_cast<GpuProgressMarkers*>(self);
markers->m_hungRunningMs.store(runningMs, std::memory_order_release);
markers->m_hung.store(true, std::memory_order_release);
MGLOG_E("Magma: submission %llu of this session's VkDevice has run %llu ms on the GPU and has not finished - "
"it is what stops the GPU for every process; the session ends at its next record and submits "
"nothing more (budget %u ms, MOBILEGL_GPU_HANG_BUDGET_MS)",
static_cast<unsigned long long>(submissionId), static_cast<unsigned long long>(runningMs),
MG_Backend::GpuHangWatch::BudgetMs());
}
VkResult GpuProgressMarkers::SubmitBracketed(VkQueue queue, VkSubmitInfo& info, VkFence fence,
const Bracket& bracket) {
constexpr Uint32 kMaxOwn = 6;
if (!bracket.Valid() || info.commandBufferCount == 0 || info.commandBufferCount > kMaxOwn)
return vkQueueSubmit(queue, 1, &info, fence);
VkCommandBuffer buffers[kMaxOwn + 2];
Uint32 count = 0;
buffers[count++] = bracket.Begin;
for (Uint32 i = 0; i < info.commandBufferCount; ++i) buffers[count++] = info.pCommandBuffers[i];
buffers[count++] = bracket.End;
const VkCommandBuffer* own = info.pCommandBuffers;
const Uint32 ownCount = info.commandBufferCount;
info.pCommandBuffers = buffers;
info.commandBufferCount = count;
const VkResult result = vkQueueSubmit(queue, 1, &info, fence);
info.pCommandBuffers = own;
info.commandBufferCount = ownCount;
return result;
}
} // namespace MobileGL::MG_Backend::DirectVulkan
@@ -1,95 +0,0 @@
// MobileGL - MobileGL/MG_Backend/DirectVulkan/Renderer/GpuProgressMarkers.h
// Copyright (c) 2025-2026 MobileGL-Dev
// Licensed under the GNU Lesser General Public License v3.0:
// https://www.gnu.org/licenses/gpl-3.0.txt
// https://www.gnu.org/licenses/lgpl-3.0.txt
// SPDX-License-Identifier: LGPL-3.0-only
// End of Source File Header
#pragma once
#include "../VkIncludes.h"
#include <Includes.h>
#include <MG_Backend/GpuHangWatch.h>
#include <atomic>
#include <mutex>
namespace MobileGL::MG_Backend::DirectVulkan {
// WHICH OF THIS DEVICE'S SUBMISSIONS THE GPU HAS STARTED, AND WHICH IT HAS FINISHED
// (GpuHangWatch.h says why that is the whole attribution of a GPU hang).
//
// A frame's submission is bracketed by two prerecorded one-command buffers: the first sets a
// `started` event at TOP_OF_PIPE, the last sets a `finished` event once everything before it in
// the queue has completed. The host reads both with vkGetEventStatus from the watch thread - no
// fence is shared with the renderer's own waits and resets. On Adreno 750 a submission whose
// fragment shader never ends reads started=SET from its first poll until the kernel resets the
// GPU, and a submission queued behind it reads started=RESET for the whole stall.
//
// The renderer's thread brackets submissions (Acquire / Submitted / Abandon) and asks Hung(); the
// watch thread samples. Everything Vulkan the two share - the events - is touched under m_mutex.
class GpuProgressMarkers {
public:
struct Bracket {
VkCommandBuffer Begin = VK_NULL_HANDLE;
VkCommandBuffer End = VK_NULL_HANDLE;
Uint32 Slot = ~0u;
Bool Valid() const { return Slot != ~0u; }
};
GpuProgressMarkers() = default;
~GpuProgressMarkers() { Shutdown(); }
GpuProgressMarkers(const GpuProgressMarkers&) = delete;
GpuProgressMarkers& operator=(const GpuProgressMarkers&) = delete;
// Off (no brackets, never hung) when the budget is 0 or the device cannot make events.
void Init(VkDevice device, Uint32 queueFamilyIndex);
// Before the device goes; its queue must be idle. Stops the watch first.
void Shutdown();
// The two buffers to put first and last in one submission (an invalid bracket when off or
// when every slot is in flight: the submission then goes unwatched).
Bracket Acquire();
// The submission carrying `bracket` was accepted by vkQueueSubmit / was not submitted.
void Submitted(const Bracket& bracket);
void Abandon(const Bracket& bracket);
// The watch named one of this device's submissions as hanging the GPU.
Bool Hung() const { return m_hung.load(std::memory_order_acquire); }
Uint64 HungRunningMs() const { return m_hungRunningMs.load(std::memory_order_acquire); }
Bool Active() const { return m_watch != 0; }
// vkQueueSubmit of `info` with `bracket` wrapped around its command buffers (which it puts
// back before returning). At most 6 buffers of the caller's.
static VkResult SubmitBracketed(VkQueue queue, VkSubmitInfo& info, VkFence fence, const Bracket& bracket);
private:
struct Slot {
VkEvent Started = VK_NULL_HANDLE;
VkEvent Finished = VK_NULL_HANDLE;
VkCommandBuffer Begin = VK_NULL_HANDLE;
VkCommandBuffer End = VK_NULL_HANDLE;
Uint64 Id = 0;
Bool InFlight = false; // submitted and not yet seen finished
Bool Claimed = false; // handed out by Acquire, not yet submitted or abandoned
Bool Dirty = false; // its events were set by a past submission: reset before reuse
};
static constexpr Uint32 kMaxSlots = 16;
Bool AddSlot();
static Bool Sample(void* self, Vector<MG_Backend::GpuHangWatch::SubmissionProgress>& out);
static void OnHung(void* self, Uint64 submissionId, Uint64 runningMs);
std::mutex m_mutex;
VkDevice m_device = VK_NULL_HANDLE;
VkCommandPool m_pool = VK_NULL_HANDLE;
Vector<Slot> m_slots;
Uint64 m_nextId = 1;
Uint64 m_watch = 0;
Bool m_lost = false;
std::atomic<Bool> m_hung{false};
std::atomic<Uint64> m_hungRunningMs{0};
};
} // namespace MobileGL::MG_Backend::DirectVulkan
@@ -391,15 +391,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
VkPipeline PipelineFactory::CreatePipeline(const PipelineCreatePayload& payload) const {
MOBILEGL_ASSERT(payload.stages != nullptr && !payload.stages->empty(), "PipelineFactory: stages are empty");
// The assert compiles out of shipping builds, and a program declined for an invalid
// module (VkProgramObject::invalidSpirvDeclined) has no stages at all: a caller that
// forgot to refuse it must get a skipped draw, not a stageCount=0 pipeline.
if (payload.stages == nullptr || payload.stages->empty()) {
MGLOG_E_ONCE("PipelineFactory::CreatePipeline: refusing a pipeline with no shader stages "
"(programHash=0x%llx); its draws are skipped",
static_cast<unsigned long long>(payload.programHash));
return VK_NULL_HANDLE;
}
MOBILEGL_ASSERT(payload.vertexInputState != nullptr, "PipelineFactory: vertexInputState is null");
MOBILEGL_ASSERT(payload.pipelineLayout != VK_NULL_HANDLE, "PipelineFactory: pipelineLayout is null");
MOBILEGL_ASSERT(payload.renderPass != VK_NULL_HANDLE, "PipelineFactory: renderPass is null");
@@ -12,9 +12,7 @@
#include "MG_Util/ShaderTranspiler/ShaderCompiler.h"
#include "MG_Util/ShaderTranspiler/SpvcSession.h"
#include "MG_Util/ShaderTranspiler/Types.h"
#include <Config.h>
#include <algorithm>
#include <atomic>
#include <bit>
#include <cmath>
#include <cstring>
@@ -2275,84 +2273,8 @@ namespace MobileGL::MG_Backend::DirectVulkan {
return false;
}
}
// ScreenModuleForDriver's memory. Keyed by content, never by program: the same bytes get
// the same answer whichever program, variant or session carries them.
struct DriverModuleVerdictCache {
struct Entry {
Uint64 wordCount = 0;
Bool valid = true;
String reason;
};
// Generous for any one application's distinct stage modules; past it the whole table
// is dropped rather than tracked per entry - a re-validation is the only cost.
static constexpr SizeT kMaxEntries = 8192;
std::mutex mutex;
UnorderedMap<Uint64, Entry> entries;
std::atomic<Uint64> validatorRuns{0};
};
DriverModuleVerdictCache& GetDriverModuleVerdictCache() {
// Leaked on purpose: screened from session threads that may outlive static destruction.
static auto* cache = new DriverModuleVerdictCache();
return *cache;
}
} // namespace
ProgramFactory::DriverModuleVerdict ProgramFactory::ScreenModuleForDriver(const Vector<Uint>& spirv,
Bool allowInvalid, String* outReason) {
if (outReason != nullptr) outReason->clear();
if (spirv.empty()) return DriverModuleVerdict::Valid;
auto& cache = GetDriverModuleVerdictCache();
const Uint64 key = XXH64(spirv.data(), spirv.size() * sizeof(Uint), 0);
Bool valid = true;
String reason;
Bool known = false;
{
const std::lock_guard<std::mutex> lock(cache.mutex);
const auto it = cache.entries.find(key);
if (it != cache.entries.end() && it->second.wordCount == spirv.size()) {
known = true;
valid = it->second.valid;
reason = it->second.reason;
}
}
if (!known) {
// Outside the lock: two threads screening the same new module both validate, and
// agree; nothing waits on another session's spirv-val.
MG_Util::ShaderTranspiler::ShaderCompiler::PrepareSpirvValidation();
cache.validatorRuns.fetch_add(1, std::memory_order_relaxed);
spv_context context = spvContextCreate(GetSpirvTargetEnv(spirv));
spv_validator_options options = spvValidatorOptionsCreate();
spvValidatorOptionsSetFriendlyNames(options, true);
spv_const_binary_t binary = {spirv.data(), spirv.size()};
spv_diagnostic diagnostic = nullptr;
const spv_result_t result = spvValidateWithOptions(context, options, &binary, &diagnostic);
valid = result == SPV_SUCCESS;
if (!valid) {
reason = diagnostic != nullptr && diagnostic->error != nullptr ? diagnostic->error : "<no diagnostic>";
// The process-wide counter the validating test lanes assert on.
MG_Util::ShaderTranspiler::ShaderCompiler::NoteSpirvValidationFailure();
}
spvDiagnosticDestroy(diagnostic);
spvValidatorOptionsDestroy(options);
spvContextDestroy(context);
const std::lock_guard<std::mutex> lock(cache.mutex);
if (cache.entries.size() >= DriverModuleVerdictCache::kMaxEntries) cache.entries.clear();
cache.entries[key] = DriverModuleVerdictCache::Entry{spirv.size(), valid, reason};
}
if (valid) return DriverModuleVerdict::Valid;
if (outReason != nullptr) *outReason = Move(reason);
return allowInvalid ? DriverModuleVerdict::AdmittedInvalid : DriverModuleVerdict::DeclinedInvalid;
}
Uint64 ProgramFactory::DriverModuleValidatorRuns() {
return GetDriverModuleVerdictCache().validatorRuns.load(std::memory_order_relaxed);
}
// A shader that assigns gl_FragDepth (SPIR-V DepthReplacing) supplies depth itself
// instead of taking the pipeline's interpolated Z, so a driver that varies the vertex
// position math between pipelines cannot desynchronize it; the blended depth-write
@@ -2529,7 +2451,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
return SamplerNumericDomain::UnsignedInteger;
case GL_SAMPLER_1D:
case GL_SAMPLER_2D:
case GL_SAMPLER_EXTERNAL_OES:
case GL_SAMPLER_3D:
case GL_SAMPLER_CUBE:
case GL_SAMPLER_2D_RECT:
@@ -2720,7 +2641,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
case GL_UNSIGNED_INT_IMAGE_CUBE_MAP_ARRAY:
return TextureTarget::TextureCubeMapArray;
case GL_SAMPLER_2D:
case GL_SAMPLER_EXTERNAL_OES: // a 2D texture below the frontend
case GL_SAMPLER_2D_SHADOW:
case GL_INT_SAMPLER_2D:
case GL_UNSIGNED_INT_SAMPLER_2D:
@@ -3894,42 +3814,27 @@ namespace MobileGL::MG_Backend::DirectVulkan {
const Bool remapOk = RemapDescriptorBindingsForVulkan(moduleSpirvs, m_maxBindings, moduleSpirvs);
MOBILEGL_ASSERT(remapOk, "ProgramFactory::GetOrCreateProgram: descriptor binding remap failed");
// Last look at the exact bytes the driver receives, in EVERY build rather than only in
// DEBUG or with MOBILEGL_ENABLE_SPIRV_VALIDATION armed, and for every stage BEFORE any
// module is created. By here the descriptor bindings have been remapped and the layout
// about to be reflected describes the remapped module, so there is no module left that
// is both valid and consistent with it to fall back to (the recovery that exists lives
// one step earlier, at the clip/XFB fixups). What is left is to keep the bytes away from
// the driver: a driver is not a validating entry point, and an invalid module it accepts
// can fault the GPU into device loss (a frontend translation once put a sampler inside
// the default uniform block, and Adreno page-faulted reading its "descriptor" out of
// uniform-buffer bytes). One invalid stage declines the whole program: no shader module
// of it is created, and every draw or dispatch of it is refused by name
// (VkProgramObject::invalidSpirvDeclined). MOBILEGL_MAGMA_ALLOW_INVALID_SPIRV hands the
// bytes over anyway, for diagnosing a driver that copes.
for (SizeT i = 0; i < moduleCount; ++i) {
String reason;
const DriverModuleVerdict verdict = ScreenModuleForDriver(
moduleSpirvs[i], MG_Config::Features.MagmaAllowInvalidSpirv, &reason);
if (verdict == DriverModuleVerdict::DeclinedInvalid) {
MGLOG_E_ONCE("ProgramFactory: declining program %u - its stage %d module fails SPIR-V validation (%s); "
"no shader module is created and its draws are refused. "
"MOBILEGL_MAGMA_ALLOW_INVALID_SPIRV=1 hands such modules to the driver anyway.",
program.GetExternalIndex(), static_cast<Int>(stages[i]), reason.c_str());
entry.invalidSpirvDeclined = true;
break;
}
if (verdict == DriverModuleVerdict::AdmittedInvalid) {
MGLOG_E_ONCE("ProgramFactory: handing vkCreateShaderModule an INVALID module for program %u stage %d "
"because MOBILEGL_MAGMA_ALLOW_INVALID_SPIRV is set (%s)",
program.GetExternalIndex(), static_cast<Int>(stages[i]), reason.c_str());
}
}
for (SizeT i = 0; i < moduleCount && !entry.invalidSpirvDeclined; ++i) {
auto& moduleSpv = moduleSpirvs[i];
if (moduleSpv.empty()) continue;
// Last look at the exact bytes the driver receives, in EVERY build rather than only
// in DEBUG or with MOBILEGL_ENABLE_SPIRV_VALIDATION armed. This one only reports:
// by here the descriptor bindings have been remapped and the layout about to be
// reflected describes the remapped module, so there is no module left that is both
// valid and consistent with it to fall back to. The recovery lives one step earlier,
// at the clip/XFB fixups (see the revert there) - which is where a transform can
// introduce a reference to a delisted interface variable, the failure this whole
// guard exists for. Anything that reaches this line names itself in the log of a
// shipping build instead of dying anonymously inside the driver.
SpirvValidationFailure finalFailure{};
if (!ValidateTransformedSpirv(moduleSpv, stages[i], program.GetExternalIndex(), &finalFailure)) {
MGLOG_E_ONCE("ProgramFactory: handing vkCreateShaderModule an INVALID module for program %u stage %d - "
"a backend transform after the clip/XFB fixups broke it (%s)",
program.GetExternalIndex(), static_cast<Int>(stages[i]),
finalFailure.message.c_str());
}
// Does the stage the driver will treat as the last pre-rasterization one actually
// carry Xfb? Asked of the FINAL bytes, so it answers for whatever the whole transform
// chain produced - a rewound clip/XFB backstop, a capture pass that resolved no
@@ -229,11 +229,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
// the cache entry, so every later draw of the same program variant reads the same
// answer instead of re-deciding it.
Bool pointSizeCapabilityUnsupported = false;
// One of the program's final modules fails SPIR-V validation, so none of its modules
// was created and every draw or dispatch of it is refused by name (the ProgramInvalidSpirv /
// ComputeProgramInvalidSpirv wire declines) - see ProgramFactory::ScreenModuleForDriver.
// Sticky like the flag above: it lives on the cache entry, so the one log line is honest.
Bool invalidSpirvDeclined = false;
Bool needsPassthroughTessControl = false;
// ...and the pass-through this renderer can synthesize carries gl_Position and
// nothing else, so it is only correct when the evaluation stage's inputs are
@@ -294,11 +289,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
storageBlockIndexByBinding = std::move(other.storageBlockIndexByBinding);
hasStorageImages = other.hasStorageImages;
declinedDescriptors = other.declinedDescriptors;
// The three refusal flags travel like every other field: a robin-hood insert swaps
// entries, and a flag left behind would refuse (or admit) the wrong program.
invalidSpirvDeclined = other.invalidSpirvDeclined;
xfbCaptureDeclined = other.xfbCaptureDeclined;
pointSizeCapabilityUnsupported = other.pointSizeCapabilityUnsupported;
globalUboBinding = other.globalUboBinding;
activeVertexInputLocationMask = other.activeVertexInputLocationMask;
vertexInputTypes = other.vertexInputTypes;
@@ -320,9 +310,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
other.pipelineLayout = VK_NULL_HANDLE;
other.hasStorageImages = false;
other.declinedDescriptors = false;
other.invalidSpirvDeclined = false;
other.xfbCaptureDeclined = false;
other.pointSizeCapabilityUnsupported = false;
other.globalUboBinding = -1;
other.activeVertexInputLocationMask = 0;
other.activeFragmentOutputLocationMask = 0;
@@ -366,11 +353,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
storageBlockIndexByBinding = std::move(other.storageBlockIndexByBinding);
hasStorageImages = other.hasStorageImages;
declinedDescriptors = other.declinedDescriptors;
// The three refusal flags travel like every other field: a robin-hood insert swaps
// entries, and a flag left behind would refuse (or admit) the wrong program.
invalidSpirvDeclined = other.invalidSpirvDeclined;
xfbCaptureDeclined = other.xfbCaptureDeclined;
pointSizeCapabilityUnsupported = other.pointSizeCapabilityUnsupported;
globalUboBinding = other.globalUboBinding;
activeVertexInputLocationMask = other.activeVertexInputLocationMask;
vertexInputTypes = other.vertexInputTypes;
@@ -392,9 +374,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
other.pipelineLayout = VK_NULL_HANDLE;
other.hasStorageImages = false;
other.declinedDescriptors = false;
other.invalidSpirvDeclined = false;
other.xfbCaptureDeclined = false;
other.pointSizeCapabilityUnsupported = false;
other.globalUboBinding = -1;
other.activeVertexInputLocationMask = 0;
other.activeFragmentOutputLocationMask = 0;
@@ -525,29 +504,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
// VkRenderPassManager::OnPresent's sweep.
void OnFrameBoundary();
// What the last look at a module's final bytes - the exact words vkCreateShaderModule
// would receive - decided.
enum class DriverModuleVerdict : Uint8 {
Valid, // validates: handed to the driver
DeclinedInvalid, // fails validation: never handed over, the program's work is declined
AdmittedInvalid, // fails validation, handed over anyway (MOBILEGL_MAGMA_ALLOW_INVALID_SPIRV)
};
// Validates `spirv` for the Vulkan environment its version word names and turns the
// result into a verdict. A driver is not a validating entry point: Adreno page-faulted
// into device loss on a module that carried a sampler inside a uniform block, Mali
// SIGSEGVs inside pipeline creation. So an invalid module is declined unless
// `allowInvalid` (the escape hatch) says to hand it over regardless.
//
// The validator's answer is remembered per module content (64-bit hash plus word count),
// process-wide: a program variant, an evicted-then-rebuilt entry and two programs that
// share a stage all re-screen the same bytes, and only the first pays for spirv-val.
// `outReason` receives the validator's message for an invalid module.
static DriverModuleVerdict ScreenModuleForDriver(const Vector<Uint>& spirv, Bool allowInvalid,
String* outReason = nullptr);
// How many times ScreenModuleForDriver actually ran the validator (cache misses), for
// the tests that pin the cache.
static Uint64 DriverModuleValidatorRuns();
static VkShaderStageFlagBits ToVkStage(ShaderStage stage);
static VkFormat ConvertSpirvImageFormatToVkFormat(SpvImageFormat format);
static SamplerNumericDomain UniformTypeToSamplerNumericDomain(GLenum glType);
@@ -1,27 +0,0 @@
// MobileGL - MobileGL/MG_Backend/DirectVulkan/Renderer/RenderPassGuard.h
// Copyright (c) 2025-2026 MobileGL-Dev
// Licensed under the GNU Lesser General Public License v3.0:
// https://www.gnu.org/licenses/gpl-3.0.txt
// https://www.gnu.org/licenses/lgpl-3.0.txt
// SPDX-License-Identifier: LGPL-3.0-only
// End of Source File Header
#pragma once
#include "../VkIncludes.h"
#include <Includes.h>
namespace MobileGL::MG_Backend::DirectVulkan {
// Ends the render pass that is active on `commandBuffer`, if there is one. Called right before
// recording a command a render pass may not contain (a barrier, a copy, a blit, a clear of an
// image) into a command buffer that may hold an open pass: the wire draw path keeps its pass
// open across consecutive draws to the same attachments, so the resource work that falls
// between two draws must close it first. A pass on another command buffer is left alone.
void EndActiveRenderPassOn(VkCommandBuffer commandBuffer);
// A counter that moves whenever images may have been written since it was last read: a render
// pass ended (its attachments), resource work recorded outside a pass (copies, clears, blits,
// dispatches all close the pass first), or a draw with storage images. A sampled image needs
// the memory barrier that makes earlier writes visible only when this moved since the last one.
Uint64 WireImageWriteEpoch();
void BumpWireImageWriteEpoch();
} // namespace MobileGL::MG_Backend::DirectVulkan
@@ -6,7 +6,6 @@
// SPDX-License-Identifier: LGPL-3.0-only
// End of Source File Header
#include "RenderPassGuard.h"
#include "UniformManager.h"
#include "MG_Backend/DirectVulkan/DirectVulkanResourceState.h"
@@ -252,18 +251,11 @@ namespace MobileGL::MG_Backend::DirectVulkan {
WireDescriptorFatal("image-descriptor-transition");
// A second descriptor/draw can keep GENERAL after a shader write. A layout
// equality fast return is not a memory dependency for that prior write.
// Only when something may have written an image since the last such barrier
// (WireImageWriteEpoch): with nothing written in between, consecutive draws keep their
// render pass open instead of closing it for a barrier that orders nothing.
if (WireImageWriteEpoch() != m_wireImageBarrierEpoch) {
VkMemoryBarrier memory{VK_STRUCTURE_TYPE_MEMORY_BARRIER};
memory.srcAccessMask = VK_ACCESS_MEMORY_WRITE_BIT;
memory.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT;
EndActiveRenderPassOn(commandBuffer);
vkCmdPipelineBarrier(commandBuffer, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
0, 1, &memory, 0, nullptr, 0, nullptr);
m_wireImageBarrierEpoch = WireImageWriteEpoch();
}
VkMemoryBarrier memory{VK_STRUCTURE_TYPE_MEMORY_BARRIER};
memory.srcAccessMask = VK_ACCESS_MEMORY_WRITE_BIT;
memory.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT;
vkCmdPipelineBarrier(commandBuffer, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
0, 1, &memory, 0, nullptr, 0, nullptr);
VkImageViewCreateInfo info{VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO};
info.image = resource->image;
info.viewType = type;
@@ -3206,8 +3198,7 @@ namespace MobileGL::MG_Backend::DirectVulkan {
const auto* resource = m_textureManager->SyncTextureResourceByHandle(handle, false, storage);
if (resource == nullptr) return false;
// Another session writes it: the renderer acquires it before this use.
if (resource->sharedImageId != 0 || resource->yuvImageId != 0)
m_textureManager->NoteSharedImageUse(*resource);
if (resource->sharedImageId != 0) m_textureManager->NoteSharedImageUse(*resource);
}
}
}
@@ -660,7 +660,5 @@ namespace MobileGL::MG_Backend::DirectVulkan {
m_samplerResolveMemoHighWater = binding + 1;
}
}
// WireImageWriteEpoch() when ResolveWireImageDescriptor last made image writes visible.
mutable Uint64 m_wireImageBarrierEpoch = 0;
};
} // namespace MobileGL::MG_Backend::DirectVulkan
@@ -6,7 +6,6 @@
// SPDX-License-Identifier: LGPL-3.0-only
// End of Source File Header
#include "RenderPassGuard.h"
#include "VkBufferManager.h"
#include "../DirectVulkan.h"
#include "VulkanRenderer.h"
@@ -338,7 +337,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
VkMemoryBarrier barrier{VK_STRUCTURE_TYPE_MEMORY_BARRIER};
barrier.srcAccessMask = VK_ACCESS_MEMORY_WRITE_BIT;
barrier.dstAccessMask = VK_ACCESS_HOST_READ_BIT | VK_ACCESS_HOST_WRITE_BIT;
EndActiveRenderPassOn(commands);
vkCmdPipelineBarrier(commands, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_HOST_BIT,
0, 1, &barrier, 0, nullptr, 0, nullptr);
// P8-D: counted here, past the idle early-out, so `whw` is waits TAKEN, not calls.
@@ -533,16 +531,13 @@ namespace MobileGL::MG_Backend::DirectVulkan {
VkMemoryBarrier before{VK_STRUCTURE_TYPE_MEMORY_BARRIER};
before.srcAccessMask = VK_ACCESS_MEMORY_WRITE_BIT | VK_ACCESS_HOST_WRITE_BIT;
before.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT;
EndActiveRenderPassOn(commands);
vkCmdPipelineBarrier(commands, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT | VK_PIPELINE_STAGE_HOST_BIT,
VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 1, &before, 0, nullptr, 0, nullptr);
const VkBufferCopy copy{offset, dst.offset, size};
EndActiveRenderPassOn(commands);
vkCmdCopyBuffer(commands, resource->buffer.GetHandle(), dst.buffer, 1, &copy);
VkMemoryBarrier after{VK_STRUCTURE_TYPE_MEMORY_BARRIER};
after.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
after.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT;
EndActiveRenderPassOn(commands);
vkCmdPipelineBarrier(commands, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
0, 1, &after, 0, nullptr, 0, nullptr);
resource->lastUseSerial = m_frameSerial;
@@ -580,27 +575,22 @@ namespace MobileGL::MG_Backend::DirectVulkan {
VkMemoryBarrier before{VK_STRUCTURE_TYPE_MEMORY_BARRIER};
before.srcAccessMask = VK_ACCESS_MEMORY_WRITE_BIT | VK_ACCESS_HOST_WRITE_BIT;
before.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT;
EndActiveRenderPassOn(commands);
vkCmdPipelineBarrier(commands, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT | VK_PIPELINE_STAGE_HOST_BIT,
VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 1, &before, 0, nullptr, 0, nullptr);
const VkBufferCopy widen{alignedOffset, staging.offset, stagedSize};
EndActiveRenderPassOn(commands);
vkCmdCopyBuffer(commands, resource->buffer.GetHandle(), staging.buffer, 1, &widen);
// The shift reads what the widening copy just wrote, so it needs its own edge even
// though both halves are transfers on one command buffer.
VkMemoryBarrier staged{VK_STRUCTURE_TYPE_MEMORY_BARRIER};
staged.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
staged.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
EndActiveRenderPassOn(commands);
vkCmdPipelineBarrier(commands, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT,
0, 1, &staged, 0, nullptr, 0, nullptr);
const VkBufferCopy shift{staging.offset + headPad, dst.offset + dstSkip, size};
EndActiveRenderPassOn(commands);
vkCmdCopyBuffer(commands, staging.buffer, dst.buffer, 1, &shift);
VkMemoryBarrier after{VK_STRUCTURE_TYPE_MEMORY_BARRIER};
after.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
after.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT;
EndActiveRenderPassOn(commands);
vkCmdPipelineBarrier(commands, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
0, 1, &after, 0, nullptr, 0, nullptr);
resource->lastUseSerial = m_frameSerial;
@@ -918,18 +908,14 @@ namespace MobileGL::MG_Backend::DirectVulkan {
VkMemoryBarrier hostWrites{VK_STRUCTURE_TYPE_MEMORY_BARRIER};
hostWrites.srcAccessMask = VK_ACCESS_HOST_WRITE_BIT;
hostWrites.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT;
EndActiveRenderPassOn(commands);
vkCmdPipelineBarrier(commands, VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 1,
&hostWrites, 0, nullptr, 0, nullptr);
VkBufferCopy region{0, 0, kWords * 4};
EndActiveRenderPassOn(commands);
vkCmdCopyBuffer(commands, imported.buffer, staging.buffer, 1, &region);
EndActiveRenderPassOn(commands);
vkCmdFillBuffer(commands, imported.buffer, kFillAt, kWords * 4, kFillWord);
VkMemoryBarrier toHost{VK_STRUCTURE_TYPE_MEMORY_BARRIER};
toHost.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
toHost.dstAccessMask = VK_ACCESS_HOST_READ_BIT;
EndActiveRenderPassOn(commands);
vkCmdPipelineBarrier(commands, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_HOST_BIT, 0, 1, &toHost,
0, nullptr, 0, nullptr);
vkEndCommandBuffer(commands);
@@ -979,15 +965,11 @@ namespace MobileGL::MG_Backend::DirectVulkan {
verdict = "steady: the second submission could not be recorded";
break;
}
EndActiveRenderPassOn(commands);
vkCmdPipelineBarrier(commands, VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 1,
&hostWrites, 0, nullptr, 0, nullptr);
VkBufferCopy steadyRegion{kSteadyAt, 0, kWords * 4};
EndActiveRenderPassOn(commands);
vkCmdCopyBuffer(commands, imported.buffer, staging.buffer, 1, &steadyRegion);
EndActiveRenderPassOn(commands);
vkCmdFillBuffer(commands, imported.buffer, kFillAt, kWords * 4, kSteadyFillWord);
EndActiveRenderPassOn(commands);
vkCmdPipelineBarrier(commands, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_HOST_BIT, 0, 1, &toHost,
0, nullptr, 0, nullptr);
vkEndCommandBuffer(commands);
@@ -1506,7 +1488,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
VkMemoryBarrier beforeBarrier{VK_STRUCTURE_TYPE_MEMORY_BARRIER};
beforeBarrier.srcAccessMask = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT;
beforeBarrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
EndActiveRenderPassOn(commandBuffer);
vkCmdPipelineBarrier(commandBuffer, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 1,
&beforeBarrier, 0, nullptr, 0, nullptr);
@@ -1514,13 +1495,11 @@ namespace MobileGL::MG_Backend::DirectVulkan {
region.srcOffset = staging.offset;
region.dstOffset = static_cast<VkDeviceSize>(offset);
region.size = static_cast<VkDeviceSize>(size);
EndActiveRenderPassOn(commandBuffer);
vkCmdCopyBuffer(commandBuffer, staging.buffer, resource.buffer.GetHandle(), 1, &region);
VkMemoryBarrier afterBarrier{VK_STRUCTURE_TYPE_MEMORY_BARRIER};
afterBarrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
afterBarrier.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT;
EndActiveRenderPassOn(commandBuffer);
vkCmdPipelineBarrier(commandBuffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, 1,
&afterBarrier, 0, nullptr, 0, nullptr);
@@ -1555,7 +1534,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
VkMemoryBarrier beforeBarrier{VK_STRUCTURE_TYPE_MEMORY_BARRIER};
beforeBarrier.srcAccessMask = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT;
beforeBarrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
EndActiveRenderPassOn(commandBuffer);
vkCmdPipelineBarrier(commandBuffer, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 1,
&beforeBarrier, 0, nullptr, 0, nullptr);
@@ -1563,13 +1541,11 @@ namespace MobileGL::MG_Backend::DirectVulkan {
region.srcOffset = staging.offset;
region.dstOffset = static_cast<VkDeviceSize>(offset);
region.size = static_cast<VkDeviceSize>(size);
EndActiveRenderPassOn(commandBuffer);
vkCmdCopyBuffer(commandBuffer, staging.buffer, resource.buffer.GetHandle(), 1, &region);
VkMemoryBarrier afterBarrier{VK_STRUCTURE_TYPE_MEMORY_BARRIER};
afterBarrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
afterBarrier.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT;
EndActiveRenderPassOn(commandBuffer);
vkCmdPipelineBarrier(commandBuffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, 1,
&afterBarrier, 0, nullptr, 0, nullptr);
@@ -7,8 +7,6 @@
// End of Source File Header
#include "VkRenderPassManager.h"
#include "RenderPassGuard.h"
#include <atomic>
#include "MG_Impl/GLImpl/Framebuffer/GL_Framebuffer.h"
#include "MG_State/GLState/TextureState/TextureObject2D.h"
@@ -1668,7 +1666,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
s_clearManager.Get()->PopPendingClear(pending.key);
}
}
s_activeRenderPass.Get().commandBuffer = commandBuffer;
s_activeRenderPass.Get().hash = renderPassEntry.hash;
s_activeRenderPass.Get().compatibilityHash = renderPassEntry.compatibilityHash;
s_activeRenderPass.Get().trackedAttachmentLayouts = renderPassEntry.trackedAttachmentLayouts;
@@ -1679,24 +1676,15 @@ namespace MobileGL::MG_Backend::DirectVulkan {
}
Bool VkRenderPassManager::EndRenderPass(VkCommandBuffer commandBuffer) {
BumpWireImageWriteEpoch();
auto* activeRenderPass = GetActiveRenderPass();
Vector<TrackedAttachmentLayoutInfo> trackedAttachmentLayouts;
if (activeRenderPass != nullptr) {
trackedAttachmentLayouts = Move(activeRenderPass->trackedAttachmentLayouts);
}
vkCmdEndRenderPass(commandBuffer);
// Layout reconciliation below may record barriers, whose guard closes an active
// pass. Detach the ended pass first so that guard cannot recursively end it again.
s_activeRenderPass.Get() = {};
s_hasActiveRenderPass.Get() = false;
// The fast-path memo reuses the ACTIVE render pass; once the pass ends it must not carry
// over (the next span may be a different FBO resolved before its render pass is begun).
if (s_renderPassManager.Get() != nullptr) {
s_renderPassManager.Get()->m_rpFastValid = false;
}
if (!trackedAttachmentLayouts.empty()) {
for (const auto& trackedAttachment : trackedAttachmentLayouts) {
if (activeRenderPass != nullptr && !activeRenderPass->trackedAttachmentLayouts.empty()) {
for (const auto& trackedAttachment : activeRenderPass->trackedAttachmentLayouts) {
switch (trackedAttachment.target) {
case TrackedAttachmentTarget::Texture:
MOBILEGL_ASSERT(s_textureManager.Get() != nullptr, "EndRenderPass: texture manager is null");
@@ -1738,23 +1726,12 @@ namespace MobileGL::MG_Backend::DirectVulkan {
}
}
}
s_activeRenderPass.Get() = {};
s_hasActiveRenderPass.Get() = false;
return true;
}
ActiveRenderPassInfo* VkRenderPassManager::GetActiveRenderPass() {
return s_hasActiveRenderPass.Get() ? &s_activeRenderPass.Get() : nullptr;
}
namespace {
std::atomic<Uint64> g_wireImageWriteEpoch{1};
}
Uint64 WireImageWriteEpoch() { return g_wireImageWriteEpoch.load(std::memory_order_relaxed); }
void BumpWireImageWriteEpoch() { g_wireImageWriteEpoch.fetch_add(1, std::memory_order_relaxed); }
void EndActiveRenderPassOn(VkCommandBuffer commandBuffer) {
BumpWireImageWriteEpoch();
const auto* active = VkRenderPassManager::GetActiveRenderPass();
if (active != nullptr && active->commandBuffer == commandBuffer && commandBuffer != VK_NULL_HANDLE)
VkRenderPassManager::EndRenderPass(commandBuffer);
}
} // namespace MobileGL::MG_Backend::DirectVulkan
@@ -185,7 +185,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
struct ActiveRenderPassInfo {
Uint64 hash = 0;
Uint64 compatibilityHash = 0;
VkCommandBuffer commandBuffer = VK_NULL_HANDLE;
Vector<TrackedAttachmentLayoutInfo> trackedAttachmentLayouts;
IntVec2 extent = {0, 0};
@@ -6,7 +6,6 @@
// SPDX-License-Identifier: LGPL-3.0-only
// End of Source File Header
#include "RenderPassGuard.h"
#include "VkTextureManager.h"
#include "ProgramFactory.h"
@@ -56,22 +55,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
};
static SessionLocal<SampledReadStages> s_sampledReadStagesSlot;
static VkImageUsageFlags ResolveTextureUsage(VkImageAspectFlags aspect,
VkFormatFeatureFlags formatFeatures,
Bool supportsStorageImage) {
VkImageUsageFlags usage = VK_IMAGE_USAGE_SAMPLED_BIT;
if (supportsStorageImage) usage |= VK_IMAGE_USAGE_STORAGE_BIT;
// A color aspect does not imply renderability (for example, RGB9_E5).
if ((aspect & VK_IMAGE_ASPECT_COLOR_BIT) &&
(formatFeatures & VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT)) {
usage |= VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
}
if (aspect & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT)) {
usage |= VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT;
}
return usage;
}
static Uint32 ComputeFullMipLevelCount(const IntVec3& baseTexelSize) {
Int maxDimension = std::max<Int>(baseTexelSize.x(),
std::max<Int>(baseTexelSize.y(), std::max<Int>(baseTexelSize.z(), 1)));
@@ -393,7 +376,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
copyRegions.push_back(copy);
}
EndActiveRenderPassOn(commandBuffer);
vkCmdCopyImage(commandBuffer,
oldResource.image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
newResource.image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
@@ -1676,7 +1658,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
std::max(source->depth >> level, 1u)};
copyRegions.push_back(copy);
}
EndActiveRenderPassOn(commandBuffer);
vkCmdCopyImage(commandBuffer, source->image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, snapshot.image,
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, static_cast<Uint32>(copyRegions.size()), copyRegions.data());
@@ -1791,7 +1772,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
// slices" but will read as "depth slice 0" once VK_KHR_maintenance9 is enabled. The
// validation layer warns about that literal 1 by name.
barrier.subresourceRange.layerCount = VK_REMAINING_ARRAY_LAYERS;
EndActiveRenderPassOn(commandBuffer);
vkCmdPipelineBarrier(commandBuffer, srcStageMask, dstStageMask, 0, 0, nullptr, 0, nullptr, 1, &barrier);
trackedLayout = newLayout;
@@ -2135,41 +2115,9 @@ namespace MobileGL::MG_Backend::DirectVulkan {
Bool VkTextureManager::SyncWireTextureShape(const MG_Pipe::MGPipeResourceRecord& record,
TextureResource& resource, Bool requireStorage) {
const MG_Pipe::MGPResourceDesc& desc = record.Desc;
// A YUV shared image is converted INTO the texture's own RGBA8 storage, which the rest of
// this function defines as for any texture; the image is only named here, and the
// renderer converts it at its first use in each frame (WireYuvImage.inc).
if (record.SharedImageId != resource.yuvImageId && !m_syncingYuvTextureStorage) {
// Respecified away from (or to another) YUV image: its source goes with it, once the
// GPU is done with it (a released resource's Reset is deferred).
if (resource.yuvSource != nullptr) {
TextureResource retired;
retired.yuvSource = std::move(resource.yuvSource);
DeferResourceRelease(Move(retired));
}
resource.yuvImageId = 0;
resource.yuvOwner.reset();
resource.yuvSource.reset();
resource.yuvConvertedFrame = 0;
}
if (record.SharedImageId != 0 && !m_syncingYuvTextureStorage) {
const auto yuv = MG_Remote::Server::SharedImages::Find(record.SharedImageId);
if (yuv != nullptr && MG_Remote::Server::SharedImages::FourccIsYuv(yuv->Fourcc)) {
m_syncingYuvTextureStorage = true;
const Bool defined = SyncWireTextureShape(record, resource, requireStorage);
m_syncingYuvTextureStorage = false;
if (!defined) return false;
if (resource.yuvImageId != record.SharedImageId) {
resource.yuvImageId = record.SharedImageId;
resource.yuvOwner = yuv;
resource.yuvSource.reset();
resource.yuvConvertedFrame = 0;
}
return true;
}
}
// Level 0 is a shared image: bind its buffer. An image that cannot be bound here leaves
// the texture the storage its NULL-data definition asked for, below.
if (record.SharedImageId != 0 && !m_syncingYuvTextureStorage) {
if (record.SharedImageId != 0) {
const SharedImageBind bound = SyncWireSharedImage(record, resource, requireStorage);
if (bound != SharedImageBind::Unresolved) return bound == SharedImageBind::Bound;
}
@@ -2272,7 +2220,13 @@ namespace MobileGL::MG_Backend::DirectVulkan {
}
VkImageUsageFlags desiredUsage =
ResolveTextureUsage(aspect, formatProperties.optimalTilingFeatures, supportsStorageImage);
VK_IMAGE_USAGE_SAMPLED_BIT | (supportsStorageImage ? VK_IMAGE_USAGE_STORAGE_BIT : 0) |
((aspect & VK_IMAGE_ASPECT_COLOR_BIT) &&
(formatProperties.optimalTilingFeatures & VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT)
? VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT : 0) |
(((aspect & VK_IMAGE_ASPECT_DEPTH_BIT) || (aspect & VK_IMAGE_ASPECT_STENCIL_BIT))
? VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT
: 0);
// Multisample attachments are also transfer sources for vkCmdResolveImage.
desiredUsage |= VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT;
@@ -2748,11 +2702,9 @@ namespace MobileGL::MG_Backend::DirectVulkan {
stencilCopy.imageSubresource.aspectMask = VK_IMAGE_ASPECT_STENCIL_BIT;
stencilCopy.bufferOffset = stagingBase + item.offset + static_cast<VkDeviceSize>(texelCount) * 4;
const VkBufferImageCopy copies[2] = {depthCopy, stencilCopy};
EndActiveRenderPassOn(commandBuffer);
vkCmdCopyBufferToImage(commandBuffer, stagingBuffer, resource.image,
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 2, copies);
} else {
EndActiveRenderPassOn(commandBuffer);
vkCmdCopyBufferToImage(commandBuffer, stagingBuffer, resource.image,
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &copy);
}
@@ -3105,7 +3057,7 @@ namespace MobileGL::MG_Backend::DirectVulkan {
handle.Slot, handle.Gen);
return nullptr;
}
resource.sharedImageKey = resource.sharedImageId != 0 || resource.yuvImageId != 0 ? key : 0;
resource.sharedImageKey = resource.sharedImageId != 0 ? key : 0;
resource.syncedWireSerial = record.Serial;
return &resource;
}
@@ -3227,7 +3179,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
if ((aspect & copyAspect) == 0) continue;
copy.srcSubresource.aspectMask = copyAspect;
copy.dstSubresource.aspectMask = copyAspect;
EndActiveRenderPassOn(commandBuffer);
vkCmdCopyImage(commandBuffer, old.image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, grown.image,
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &copy);
}
@@ -3523,7 +3474,12 @@ namespace MobileGL::MG_Backend::DirectVulkan {
}
VkImageUsageFlags desiredUsage =
ResolveTextureUsage(aspect, formatProperties.optimalTilingFeatures, supportsStorageImage);
VK_IMAGE_USAGE_SAMPLED_BIT |
(supportsStorageImage ? VK_IMAGE_USAGE_STORAGE_BIT : 0) |
((aspect & VK_IMAGE_ASPECT_COLOR_BIT) ? VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT : 0) |
(((aspect & VK_IMAGE_ASPECT_DEPTH_BIT) || (aspect & VK_IMAGE_ASPECT_STENCIL_BIT)) ?
VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT :
0);
if (!isMultisampleTexture) {
desiredUsage |= VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT;
}
@@ -3818,11 +3774,7 @@ namespace MobileGL::MG_Backend::DirectVulkan {
resource.sampledView == VK_NULL_HANDLE &&
resource.perMipViews.empty() && resource.perMipSampledViews.empty() &&
resource.attachmentViews.empty() && resource.alternateSampledViews.empty() &&
resource.storageImageViews.empty()
#if MOBILEGL_BUILD_DISAGGREGATED
&& resource.yuvSource == nullptr
#endif
) {
resource.storageImageViews.empty()) {
return;
}
@@ -4782,7 +4734,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
rectCopies[rectCopyCount++] = rectCopy;
runningOffset += static_cast<VkDeviceSize>(rect.TexelCount() * item.texelBytes);
}
EndActiveRenderPassOn(commandBuffer);
vkCmdCopyBufferToImage(commandBuffer, stagingBuffer, outResource.image,
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, rectCopyCount, rectCopies.data());
continue;
@@ -4824,12 +4775,10 @@ namespace MobileGL::MG_Backend::DirectVulkan {
stencilCopy.imageSubresource.aspectMask = VK_IMAGE_ASPECT_STENCIL_BIT;
stencilCopy.bufferOffset = stagingBase + item.offset + static_cast<VkDeviceSize>(texelCount) * 4;
const VkBufferImageCopy copies[2] = {depthCopy, stencilCopy};
EndActiveRenderPassOn(commandBuffer);
vkCmdCopyBufferToImage(commandBuffer, stagingBuffer, outResource.image,
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 2, copies);
continue;
}
EndActiveRenderPassOn(commandBuffer);
vkCmdCopyBufferToImage(commandBuffer, stagingBuffer, outResource.image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
1, &copy);
}
@@ -372,15 +372,6 @@ public:
Bool sharedImageHeld = false;
Uint64 sharedImageGeneration = 0;
Uint64 sharedImageKey = 0;
// A YUV shared image (NV12/P010) is never the texture's image: the texture keeps its own
// RGBA8 level 0, into which the renderer converts the image at its first use in each frame
// (WireYuvImage.inc) - `yuvSource` being that conversion's import of the buffer, made on
// first use, and `yuvConvertedFrame` the frame it last ran in. `yuvOwner` holds the
// registry's image for as long as the texture names it.
Uint64 yuvImageId = 0;
SharedPtr<const void> yuvOwner;
SharedPtr<void> yuvSource;
Uint64 yuvConvertedFrame = 0;
#endif
TextureResource() = default;
@@ -424,10 +415,6 @@ public:
std::swap(this->sharedImageHeld, that.sharedImageHeld);
std::swap(this->sharedImageGeneration, that.sharedImageGeneration);
std::swap(this->sharedImageKey, that.sharedImageKey);
std::swap(this->yuvImageId, that.yuvImageId);
std::swap(this->yuvOwner, that.yuvOwner);
std::swap(this->yuvSource, that.yuvSource);
std::swap(this->yuvConvertedFrame, that.yuvConvertedFrame);
#endif
}
@@ -478,10 +465,6 @@ public:
sharedImageHeld = false;
sharedImageGeneration = 0;
sharedImageKey = 0;
yuvImageId = 0;
yuvOwner.reset();
yuvSource.reset();
yuvConvertedFrame = 0;
#endif
fullView = VK_NULL_HANDLE;
sampledView = VK_NULL_HANDLE;
@@ -899,8 +882,6 @@ private:
// Active only between BeginDrawSyncScope/EndDrawSyncScope; identities of
// textures already fully synced in the current draw (small N -> flat scan).
Bool m_drawSyncScopeActive = false;
// SyncWireTextureShape defining the RGBA8 storage a YUV shared image is converted into.
Bool m_syncingYuvTextureStorage = false;
// Per-draw sync memo: the identity plus the resolved resource pointer. The pointer is stable
// across rehash in the node-based m_textureResources and stays valid for the draw (a texture
// synced this draw is alive and is not erased mid-draw), so a repeat sync of the same texture
@@ -6,10 +6,8 @@
// SPDX-License-Identifier: LGPL-3.0-only
// End of Source File Header
#include "RenderPassGuard.h"
#include "VulkanRenderer.h"
#include "SubmitFencePrefix.h"
#include "MG_Util/X11/DisplayGuard.h"
#include "OffscreenSurfaceRoute.h"
#include "MG_Backend/DirectVulkan/SubgroupSupportPolicy.h"
@@ -3276,9 +3274,6 @@ void main() {
CreateAllocator();
CreateCommandPool();
#if MOBILEGL_BUILD_DISAGGREGATED
m_progressMarkers.Init(m_device, m_physicalDevice.queueFamilies.graphicsFamily);
#endif
// Frames-in-flight is a request, not a guarantee: it also seeds the swapchain image
// count (SwapchainObject clamps the hint into [minImageCount, maxImageCount]). Not every
@@ -3508,9 +3503,6 @@ void main() {
if (m_device != VK_NULL_HANDLE) {
VK_VERIFY(vkDeviceWaitIdle(m_device));
}
#if MOBILEGL_BUILD_DISAGGREGATED
m_progressMarkers.Shutdown();
#endif
// Parked surface targets (ActivateSurfaceTarget) go before the device and instance.
for (auto& [_, target] : m_parkedTargets) DestroyParkedTarget(target);
m_parkedTargets.clear();
@@ -3518,15 +3510,10 @@ void main() {
// P7 wave 2 package B3: the session's decline tally. Silent when nothing declined, so a
// green lane stays quiet and a lane that dropped a draw cannot (rule I's observable).
WireDeclineTally::Dump("shutdown");
// The SPIR-V screen's engagement proof: a decline-free session above reads as "screened
// and valid" only with this count beside it (distinct modules, process-wide).
MGLOG_I("MGWIRE-SPIRV-SCREEN[shutdown] modulesValidated=%llu",
static_cast<unsigned long long>(ProgramFactory::DriverModuleValidatorRuns()));
DestroyWireDrawPass();
CollectWireObjects(m_submitCounter, true);
ClearAllWireDrawPassCaches();
DestroyWireColorBlitResources();
DestroyWireYuvResources();
DestroyWireDepthMipmapResources();
DestroyWireMultisampleResolveResources();
DestroySharedImagePresentTargets(false);
@@ -5201,7 +5188,6 @@ void main() {
static_cast<Uint32>(dstTexelSize.x()), static_cast<Uint32>(dstTexelSize.y())
};
EndActiveRenderPassOn(frame.commandBuffer);
vkCmdBeginRenderPass(frame.commandBuffer, &renderPassBeginInfo, VK_SUBPASS_CONTENTS_INLINE);
VkViewport viewport{};
@@ -6849,7 +6835,7 @@ void main() {
// A refused program cannot reach here today - the full path refuses before it ever
// records a snapshot - but declining the fast path costs one compare and means the
// refusal does not depend on that ordering staying true.
if (programObj.pointSizeCapabilityUnsupported || programObj.invalidSpirvDeclined) {
if (programObj.pointSizeCapabilityUnsupported) {
return false;
}
@@ -7332,7 +7318,7 @@ void main() {
// The build already said why, once, naming the program and the stage. Refusing here -
// before any pipeline is built from it - is what makes that message a decline rather
// than a note attached to invalid usage the driver still receives.
if (programObj.pointSizeCapabilityUnsupported || programObj.invalidSpirvDeclined) {
if (programObj.pointSizeCapabilityUnsupported) {
return false;
}
// For the snapshot's memoised entry pointer: if anything below inserts into the
@@ -7792,8 +7778,6 @@ void main() {
}
ProgramFactory::CompileOptionFlags transformFlags = 0;
const auto& programObj = m_programFactory->GetOrCreateProgram(program, transformFlags);
// No shader module of a program that failed validation exists; the build said why, once.
if (programObj.invalidSpirvDeclined) return;
if (!frame.isCommandRecording) {
m_frameContext.BeginCommandRecording();
@@ -7831,7 +7815,6 @@ void main() {
}
MGLOG_D("DirectVulkan: glDispatchCompute(%u, %u, %u)", numGroupsX, numGroupsY, numGroupsZ);
EndActiveRenderPassOn(frame.commandBuffer);
vkCmdDispatch(frame.commandBuffer, numGroupsX, numGroupsY, numGroupsZ);
}
@@ -7857,8 +7840,6 @@ void main() {
}
ProgramFactory::CompileOptionFlags transformFlags = 0;
const auto& programObj = m_programFactory->GetOrCreateProgram(program, transformFlags);
// No shader module of a program that failed validation exists; the build said why, once.
if (programObj.invalidSpirvDeclined) return;
if (!frame.isCommandRecording) {
m_frameContext.BeginCommandRecording();
@@ -7909,7 +7890,6 @@ void main() {
}
MGLOG_D("DirectVulkan: glDispatchComputeIndirect(offset=%zu)", static_cast<SizeT>(indirect));
EndActiveRenderPassOn(frame.commandBuffer);
vkCmdDispatchIndirect(frame.commandBuffer, slice.buffer, slice.offset + static_cast<VkDeviceSize>(indirect));
}
@@ -8112,8 +8092,6 @@ void main() {
#include "WireDraw.inc"
// AFTER WireFramebuffer.inc: the shared-image present is that file's readback, into an image.
#include "WireSharedImage.inc"
// AFTER WireSharedImage.inc: a YUV image is that file's reading side, converted on the way.
#include "WireYuvImage.inc"
void VulkanRenderer::Clear(GLbitfield mask) {
#if MOBILEGL_BUILD_DISAGGREGATED
@@ -8754,7 +8732,6 @@ void main() {
beginInfo.clearValueCount = 1;
beginInfo.pClearValues = &clearValue;
// The load op is the whole operation: begin and end with nothing in between.
EndActiveRenderPassOn(commandBuffer);
vkCmdBeginRenderPass(commandBuffer, &beginInfo, VK_SUBPASS_CONTENTS_INLINE);
vkCmdEndRenderPass(commandBuffer);
@@ -10678,6 +10655,15 @@ void main() {
return;
}
auto& frame = m_frameContext.GetCurrent();
if (!frame.isCommandRecording) {
m_frameContext.BeginCommandRecording();
}
if (VkRenderPassManager::GetActiveRenderPass() != nullptr) {
VkRenderPassManager::EndRenderPass(frame.commandBuffer);
}
// One resolver for both object kinds. The texture arm is the same
// SyncTextureAndGetDescriptor the copy always used; the renderbuffer arm goes through the
// render-pass manager, which is where a renderbuffer's VkImage lives.
@@ -10929,16 +10915,6 @@ void main() {
}
#endif
// Syncing either endpoint can flush and retire the current command buffer for
// a texture upload. Prepare recording only after both images and uploads are ready.
auto& frame = m_frameContext.GetCurrent();
if (!frame.isCommandRecording) {
m_frameContext.BeginCommandRecording();
}
if (VkRenderPassManager::GetActiveRenderPass() != nullptr) {
VkRenderPassManager::EndRenderPass(frame.commandBuffer);
}
const auto materializeClear = [this, &frame](const CopyImageEndpoint& endpoint) {
#if MOBILEGL_BUILD_DISAGGREGATED
if (MG_Config::Transport != MG_Config::TransportMode::Monolith) return true;
@@ -14188,16 +14164,10 @@ void main() {
submitInfo.pCommandBuffers = commandBuffers;
#if MOBILEGL_BUILD_DISAGGREGATED
// Shared-image fences staged for the work recorded since the last submission.
if (LatchIfGpuHung("flush-submit")) return false;
SharedImageSubmitSync sharedImageSync;
AttachSharedImageSync(submitInfo, sharedImageSync);
const GpuProgressMarkers::Bracket bracket = m_progressMarkers.Acquire();
const VkResult result = GpuProgressMarkers::SubmitBracketed(m_graphicsQueue, submitInfo, fence, bracket);
if (result == VK_SUCCESS) m_progressMarkers.Submitted(bracket);
else m_progressMarkers.Abandon(bracket);
#else
const VkResult result = vkQueueSubmit(m_graphicsQueue, 1, &submitInfo, fence);
#endif
const VkResult result = vkQueueSubmit(m_graphicsQueue, 1, &submitInfo, fence);
if (result != VK_SUCCESS) {
NoteDeviceLoss(result, "SubmitPendingCommandBuffer vkQueueSubmit");
MGLOG_E_ONCE("SubmitPendingCommandBuffer: vkQueueSubmit returned %d", result);
@@ -14328,31 +14298,6 @@ void main() {
}
return true;
}
Bool VulkanRenderer::LatchIfGpuHung(const char* site) {
if (!m_progressMarkers.Hung()) return false;
if (!m_deviceLost) {
// NOT LOST TO THE DRIVER: a submission that a failed preemption leaves running is reset
// without a device loss, and the next one would stop the GPU again. Treated as lost from
// here on - nothing more is submitted - and the session ends as one whose device was.
m_deviceLost = true;
MGLOG_E("DirectVulkan: the GPU hang watch named this session's VkDevice (a submission ran %llu ms "
"without finishing, at %s); the device is treated as LOST and nothing more is submitted",
static_cast<unsigned long long>(m_progressMarkers.HungRunningMs()),
site != nullptr ? site : "?");
}
// Where no session latch is armed (no served session) the device only stays "lost".
if (!m_deviceLossLatched && MG_Pipe::MGPipeSessionLatchArmed()) {
m_deviceLossLatched = true;
(void)MG_Pipe::MGPipeSessionLatch(MG_Pipe::MGPipeFatalFamily::DeviceLost,
"MGPipe: Fatal{BackendDeviceLost, \"Magma:gpu-hang:%s\"} - this "
"session's GPU work ran past the hang budget and stopped the GPU for "
"every process; the session ends and its client reads a lost context, "
"every other session keeps running",
site != nullptr ? site : "?");
}
return true;
}
#endif
Bool VulkanRenderer::FlushForSyncPoint(Uint64 submitIndex) {
@@ -14702,17 +14647,10 @@ void main() {
}
auto submitPacket = m_frameContext.GetSubmitInfo(shouldSubmitCommandBuffer, m_imageIndexAcquired);
#if MOBILEGL_BUILD_DISAGGREGATED
if (LatchIfGpuHung("present-submit")) return;
SharedImageSubmitSync sharedImageSync;
AttachSharedImageSync(submitPacket.submitInfo, sharedImageSync);
const GpuProgressMarkers::Bracket bracket = m_progressMarkers.Acquire();
const VkResult presentSubmit = GpuProgressMarkers::SubmitBracketed(m_graphicsQueue, submitPacket.submitInfo,
frame.imageInFlightFence, bracket);
if (presentSubmit == VK_SUCCESS) m_progressMarkers.Submitted(bracket);
else m_progressMarkers.Abandon(bracket);
#else
const VkResult presentSubmit = vkQueueSubmit(m_graphicsQueue, 1, &submitPacket.submitInfo, frame.imageInFlightFence);
#endif
const VkResult presentSubmit = vkQueueSubmit(m_graphicsQueue, 1, &submitPacket.submitInfo, frame.imageInFlightFence);
NoteDeviceLoss(presentSubmit, "Present vkQueueSubmit");
#if MOBILEGL_BUILD_DISAGGREGATED
if (presentSubmit != VK_SUCCESS && LatchWireDeviceLoss("present-submit")) return;
@@ -16041,25 +15979,6 @@ void main() {
}
}
#if MOBILEGL_BUILD_DISAGGREGATED
// YUV shared images (WireYuvImage.inc) are sampled through a VkSamplerYcbcrConversion, a
// feature of its own; asked only where AHardwareBuffers are imported at all.
m_samplerYcbcrConversion = false;
VkPhysicalDeviceSamplerYcbcrConversionFeatures ycbcrFeatures{};
ycbcrFeatures.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SAMPLER_YCBCR_CONVERSION_FEATURES;
if (m_wireAhbImport && getPhysicalDeviceFeatures2 != nullptr) {
VkPhysicalDeviceFeatures2 featureQuery{};
featureQuery.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;
featureQuery.pNext = &ycbcrFeatures;
getPhysicalDeviceFeatures2(m_physicalDevice.handle, &featureQuery);
if (ycbcrFeatures.samplerYcbcrConversion == VK_TRUE) {
ycbcrFeatures.pNext = const_cast<void*>(deviceCreateInfo.pNext);
deviceCreateInfo.pNext = &ycbcrFeatures;
m_samplerYcbcrConversion = true;
}
}
#endif
// VK_EXT_multi_draw: tier 1 of the multi-draw dispatch - one vkCmdDrawMulti(Indexed)EXT
// for a whole glMultiDraw* batch (VkMultiDrawIndexedInfoEXT carries per-draw
// firstIndex/indexCount/vertexOffset, so glMultiDrawElementsBaseVertex fits natively).
@@ -16793,10 +16712,7 @@ void main() {
}
const char* displayName = std::getenv("DISPLAY");
// Never the display this process serves (MG_Util/X11/DisplayGuard.h).
auto* display = displayName != nullptr && MG_Util::X11::MayDialX11Display(displayName)
? xOpenDisplay(displayName)
: nullptr;
auto* display = xOpenDisplay(displayName);
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",
@@ -23,7 +23,6 @@
#include "VkTextureManager.h"
#include "VkTimerQueryManager.h"
#if MOBILEGL_BUILD_DISAGGREGATED
#include "GpuProgressMarkers.h"
#include "WireRenderPassCompatibility.h"
#include <MG_Remote/Server/SharedImageRegistry.h>
#endif
@@ -146,10 +145,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
// IBufferCopyCommandProvider: recording command buffer, outside any
// render pass, for immediate staged buffer copies.
VkCommandBuffer AcquireBufferCopyCommandBuffer() override;
// EGL_BUFFER_AGE_EXT of the active target's default framebuffer for the next frame: the age
// of the swapchain image acquired for it (SwapchainObject::BufferAgeOf). Asking makes the
// target keep its presented images' content from then on.
Int32 CurrentDrawBufferAge();
#if MOBILEGL_BUILD_DISAGGREGATED
VkBufferManager& GetWireBufferManager() { return m_bufferManager; }
Bool FlushWirePendingCommandsForTextureUpdate() {
@@ -196,15 +191,10 @@ 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.
Int32 CurrentDrawBufferAge();
// The reading side's per-use hook (WireSharedImage.inc): every shared-image texture the
// wire draw or dispatch being set up samples (VkTextureManager::NoteSharedImageUse) is
// acquired from the foreign family before it, when it moved or is not held.
@@ -409,11 +399,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
// without recording or submitting anything more. False: an ordinary failure, the site
// keeps the death it had. `site` names it in the latch line.
Bool LatchWireDeviceLoss(const char* site);
// THE GPU HANG WATCH (GpuProgressMarkers.h): true once the watch named one of this device's
// submissions as the one that stops the GPU. The device is then treated as lost, this session
// is latched, and the caller returns from its verb without submitting anything more. Asked
// before every frame submission and by the apply loop before it applies another record.
Bool LatchIfGpuHung(const char* site);
#endif
// Flush gated on usefulness: only flushes when `submitIndex` is still
// unsubmitted, so poll loops on already-submitted fences do not split
@@ -632,8 +617,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
Bool m_deviceLost = false;
Bool m_deviceLossLatched = false;
#if MOBILEGL_BUILD_DISAGGREGATED
// Brackets this device's frame submissions for the GPU hang watch (LatchIfGpuHung).
GpuProgressMarkers m_progressMarkers;
struct WireImage {
VkImage image = VK_NULL_HANDLE;
VkFormat format = VK_FORMAT_UNDEFINED;
@@ -717,16 +700,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
// one entry point the import needs (PFN_vkGetAndroidHardwareBufferPropertiesANDROID).
Bool m_wireAhbImport = false;
void* m_wireGetAhbProperties = nullptr;
// YUV shared images (WireYuvImage.inc): the device enabled samplerYcbcrConversion, and the
// conversion pipelines made so far (one per buffer format and colour conversion).
Bool m_samplerYcbcrConversion = false;
struct WireYuvResources;
WireYuvResources* m_wireYuvResources = nullptr;
void DestroyWireYuvResources();
// A YUV texture's first use in a frame converts its image (yuvConvertedFrame against this,
// which every frame boundary - present, publishing flush, native fence - moves).
Uint64 m_yuvFrameSerial = 1;
Bool ConvertYuvSharedImage(VkTextureManager::TextureResource& resource);
// Shared images this session presents into, imported once each and keyed by the image's
// id (monotonic, never reused). `owner` watches the registry's image: an entry whose image
// died is dropped at a later present once `lastSubmit`, its last copy, has completed.
@@ -748,11 +721,6 @@ 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 {
@@ -378,7 +378,6 @@
begin.renderPass = target->renderPass;
begin.framebuffer = framebuffer;
begin.renderArea = {{0, 0}, destination.extent};
EndActiveRenderPassOn(frame.commandBuffer);
vkCmdBeginRenderPass(frame.commandBuffer, &begin, VK_SUBPASS_CONTENTS_INLINE);
vkCmdBindPipeline(frame.commandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, target->pipeline);
const VkViewport viewport{0.0f, 0.0f, static_cast<float>(destination.extent.width),
@@ -126,11 +126,3 @@ MGL_WIRE_DECLINE(MipmapDepthStencilAspect)
// is missing, or the three group-count words lie outside it or are misaligned.
MGL_WIRE_DECLINE(DispatchIndirectBufferUnbound)
MGL_WIRE_DECLINE(DispatchIndirectRange)
// ---- ProgramFactory::ScreenModuleForDriver ------------------------------------------------
// One of the bound program's final modules fails SPIR-V validation, so no shader module of it was
// created (VkProgramObject::invalidSpirvDeclined): SetupWireDraw refuses the draw, and the two
// dispatch arms the dispatch. A driver handed the module could fault the GPU into device loss.
// MOBILEGL_MAGMA_ALLOW_INVALID_SPIRV=1 builds the module anyway, and then neither row moves.
MGL_WIRE_DECLINE(ProgramInvalidSpirv)
MGL_WIRE_DECLINE(ComputeProgramInvalidSpirv)
@@ -299,7 +299,6 @@
begin.renderPass = target->renderPass;
begin.framebuffer = framebuffer;
begin.renderArea = {{0, 0}, destination.extent};
EndActiveRenderPassOn(frame.commandBuffer);
vkCmdBeginRenderPass(frame.commandBuffer, &begin, VK_SUBPASS_CONTENTS_INLINE);
vkCmdBindPipeline(frame.commandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, target->pipeline);
const VkViewport viewport{0.0f, 0.0f, static_cast<float>(destination.extent.width),
@@ -11,7 +11,6 @@
// PrimitivesGeneratedNoXfbProbe.cpp): one throwaway command buffer, a bounded fence wait that
// leaks rather than idle-waits a hung GPU, teardown on every other path.
#include "RenderPassGuard.h"
#include "WireDepthResolveProbe.h"
#include <MG_Util/Debug/Log.h>
@@ -238,7 +237,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
// The RECTANGLE is the render area, exactly as the render-pass arm's renderArea is - the
// scratch outside it is never read.
begin.renderArea = rect;
EndActiveRenderPassOn(commandBuffer);
vkCmdBeginRenderPass(commandBuffer, &begin, VK_SUBPASS_CONTENTS_INLINE);
vkCmdBindPipeline(commandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline);
// THE VIEWPORT IS THE WHOLE ATTACHMENT AND THE SCISSOR IS THE RECT, and the two are not
@@ -748,7 +746,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
begin.renderPass = clear.pass;
begin.framebuffer = clear.framebuffer;
begin.renderArea = fullRect;
EndActiveRenderPassOn(cmd);
vkCmdBeginRenderPass(cmd, &begin, VK_SUBPASS_CONTENTS_INLINE);
VkClearAttachment attachment{};
attachment.aspectMask = clear.aspects;
@@ -775,7 +772,6 @@ namespace MobileGL::MG_Backend::DirectVulkan {
begin.renderPass = item.resolvePass;
begin.framebuffer = item.resolveFramebuffer;
begin.renderArea = fullRect;
EndActiveRenderPassOn(cmd);
vkCmdBeginRenderPass(cmd, &begin, VK_SUBPASS_CONTENTS_INLINE);
vkCmdEndRenderPass(cmd);
}
@@ -215,10 +215,7 @@
MakeXfbWritesVisible();
const auto* fbo = state.DrawFramebuffer();
if (!fbo) MagmaWireFatal("draw-framebuffer-record");
// THE PREVIOUS DRAW'S RENDER PASS STAYS OPEN until this draw's attachments are known: a
// draw to the same attachments continues it (below), and on a tiler a pass per draw also
// loaded and stored every attachment once per draw. Resource work in between that may not
// sit inside a pass (a barrier, a copy, a clear) closes it itself (RenderPassGuard.h).
RetireWireDrawPass();
// CPU preparation may synchronize GPU-produced vertex/index bytes. Do
// not rewind an arena while this draw owns as-yet-unrecorded slices.
WirePreparationScope preparing(m_wirePreparationDepth);
@@ -233,10 +230,6 @@
flags |= ProgramFactory::CompileOptionBit::ZeroBaseVertex;
programObject = &m_programFactory->GetOrCreateProgram(program, flags);
}
if (programObject->invalidSpirvDeclined) {
MGL_WIRE_DECLINE_AT(ProgramInvalidSpirv, "a module of the program fails SPIR-V validation and was never built");
return false;
}
if (programObject->pointSizeCapabilityUnsupported) {
MGL_WIRE_DECLINE_AT(PointSizeCapability, "the program writes gl_PointSize and the device cannot express it");
return false;
@@ -493,7 +486,6 @@
// attachments below resolve the same index, so this key has to be taken after it.
passKey.swapchainImageIndex = DefaultFramebufferWriteIndex(true);
}
Vector<WireImage> sameLayoutAttachments;
const auto add = [&](const MG_Pipe::MGPSurface& surface, VkImageAspectFlags aspect) -> Uint32 {
WireImage image = ResolveWireImage(*fbo, surface, aspect, /*isWriteTarget=*/true);
if (!image.image) return VK_ATTACHMENT_UNUSED;
@@ -503,10 +495,7 @@
MGB_CTX->IsCapabilityEnabled(CapabilityInput::FramebufferSrgb));
const VkImageLayout layout = aspect == VK_IMAGE_ASPECT_COLOR_BIT ?
VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_GENERAL;
// Already in its attachment layout: its barrier (which closes any open pass) waits until
// it is known whether the open pass continues with this very attachment.
if (image.layout == layout) sameLayoutAttachments.push_back(image);
else TransitionWireImage(image, layout);
TransitionWireImage(image, layout);
VkImageViewCreateInfo info{VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO};
info.image = image.image;
info.viewType = image.viewType;
@@ -572,17 +561,7 @@
passInfo.pAttachments = attachments.data();
passInfo.subpassCount = 1;
passInfo.pSubpasses = &subpass;
const Bool continuing = m_wireDrawPass && m_wireDrawPassKey == passKey;
{
const auto* active = VkRenderPassManager::GetActiveRenderPass();
const Bool stillOpen = continuing && active != nullptr && active->commandBuffer == frame.commandBuffer;
// A new pass orders itself after earlier writes to its attachments; a continued one
// is the same pass, whose attachment writes are ordered by rasterization.
if (!stillOpen)
for (auto& image : sameLayoutAttachments) TransitionWireImage(image, VK_IMAGE_LAYOUT_GENERAL);
}
if (!continuing) RetireWireDrawPass();
if (!continuing && !AcquireCachedWireDrawPass(passKey)) {
if (!AcquireCachedWireDrawPass(passKey)) {
m_wireDrawPassKey = Move(passKey);
Vector<VkImageView> views;
views.reserve(viewInfos.size());
@@ -646,20 +625,13 @@
vkCmdBindVertexBuffers(frame.commandBuffer, binding++, 1, &slice.buffer, &slice.offset);
}
if (indexSlice.IsValid()) vkCmdBindIndexBuffer(frame.commandBuffer, indexSlice.buffer, indexSlice.offset, indexType);
// Still open from the previous draw (nothing closed it, same command buffer): continue.
const auto* active = VkRenderPassManager::GetActiveRenderPass();
const Bool open = continuing && active != nullptr && active->commandBuffer == frame.commandBuffer &&
active->hash == pass.hash;
if (!open && active != nullptr) VkRenderPassManager::EndRenderPass(frame.commandBuffer);
if (!open && !VkRenderPassManager::BeginRenderPass(frame.commandBuffer, pass)) {
if (!VkRenderPassManager::BeginRenderPass(frame.commandBuffer, pass)) {
MGL_WIRE_DECLINE_AT(BeginRenderPass, "the render pass for this draw could not be begun");
return false;
}
vkCmdBindPipeline(frame.commandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline);
ApplyDynamicDrawStateTail(frame, pass.extent, fbo->IsDefault,
ResolveDrawViewportCount(programObj.writesViewportIndexBuiltin));
// Storage images this draw writes are what the next sampled-image barrier must cover.
if (programObj.hasStorageImages) BumpWireImageWriteEpoch();
if (MG_Util::PipeStats::Enabled()) MG_Util::PipeStats::AddCalls(MG_Util::PipeStats::CallClass::Draws, 1);
return true;
}
@@ -803,10 +775,6 @@
return;
}
const auto& programObj = m_programFactory->GetOrCreateProgram(program, {});
if (programObj.invalidSpirvDeclined) {
MGL_WIRE_DECLINE_AT(ComputeProgramInvalidSpirv, "a module of the compute program fails SPIR-V validation and was never built");
return;
}
if (!m_uniformManager->PrepareWireTextureResources(program, programObj)) {
MGL_WIRE_DECLINE_AT(ComputeTextureResourcesUnprepared, "a sampled/storage image could not be made ready for the dispatch");
return;
@@ -824,7 +792,6 @@
return;
}
vkCmdBindPipeline(frame.commandBuffer, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline);
EndActiveRenderPassOn(frame.commandBuffer);
vkCmdDispatch(frame.commandBuffer, x, y, z);
}
@@ -880,10 +847,6 @@
return;
}
const auto& programObj = m_programFactory->GetOrCreateProgram(program, {});
if (programObj.invalidSpirvDeclined) {
MGL_WIRE_DECLINE_AT(ComputeProgramInvalidSpirv, "a module of the compute program fails SPIR-V validation and was never built");
return;
}
if (!m_uniformManager->PrepareWireTextureResources(program, programObj)) {
MGL_WIRE_DECLINE_AT(ComputeTextureResourcesUnprepared, "a sampled/storage image could not be made ready for the dispatch");
return;
@@ -903,7 +866,6 @@
return;
}
vkCmdBindPipeline(dispatchFrame.commandBuffer, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline);
EndActiveRenderPassOn(dispatchFrame.commandBuffer);
vkCmdDispatchIndirect(dispatchFrame.commandBuffer, parameters.buffer,
parameters.offset + static_cast<VkDeviceSize>(offset));
if (MG_Util::PipeStats::Enabled())
@@ -161,12 +161,7 @@
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.
// 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);
}
if (resource->sharedImageId != 0) AcquireSharedImage(*resource);
out.image = resource->image;
out.format = viewFormat != VK_FORMAT_UNDEFINED ? viewFormat : resource->format;
out.extent = {std::max(resource->extent.width >> level, 1u),
@@ -233,13 +228,6 @@
void VulkanRenderer::ClearWireFramebuffer(const MG_Pipe::MGPFramebufferState& fbo,
const ClearAttachmentPayload& payload, GLint drawbuffer) {
RetireWireDrawPass();
// A stream that neither presents nor finishes (an off-screen loop) never submits, so its
// recording and the per-clear objects retired below would grow until host memory runs
// out. Past a bound, submit what is recorded: the objects then retire with that work.
constexpr SizeT kRetiredObjectsBeforeSubmit = 1024;
if (m_wireRetiredObjects.size() >= kRetiredObjectsBeforeSubmit && m_wirePreparationDepth == 0 &&
HasPendingRecordedWork())
(void)FlushPendingCommands();
if (MGB_CTX->IsCapabilityEnabled(CapabilityInput::RasterizerDiscard)) return;
const auto clearSurface = [&](const MG_Pipe::MGPSurface& surface, VkImageAspectFlags aspect,
Uint32 colorIndex) {
@@ -326,7 +314,6 @@
if (!color) clear.clearValue.depthStencil = {payload.depth, payload.stencil};
VkClearRect rect{area, 0, image.layers};
auto& frame = m_frameContext.GetCurrent();
EndActiveRenderPassOn(frame.commandBuffer);
vkCmdBeginRenderPass(frame.commandBuffer, &begin, VK_SUBPASS_CONTENTS_INLINE);
vkCmdClearAttachments(frame.commandBuffer, 1, &clear, 1, &rect);
vkCmdEndRenderPass(frame.commandBuffer);
@@ -838,7 +825,6 @@
begin.renderPass = pass;
begin.framebuffer = framebuffer;
begin.renderArea = {{sxMin, syMin}, {static_cast<Uint32>(width), static_cast<Uint32>(height)}};
EndActiveRenderPassOn(m_frameContext.GetCurrent().commandBuffer);
vkCmdBeginRenderPass(m_frameContext.GetCurrent().commandBuffer, &begin, VK_SUBPASS_CONTENTS_INLINE);
vkCmdEndRenderPass(m_frameContext.GetCurrent().commandBuffer);
} else if (!resolvedByShader) {
@@ -215,7 +215,6 @@
VkRenderPassBeginInfo begin{VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO};
begin.renderPass = image.clearPass; begin.framebuffer = image.clearFramebuffer;
begin.renderArea.extent = {1, 1}; begin.clearValueCount = 1; begin.pClearValues = &clear;
EndActiveRenderPassOn(commands);
vkCmdBeginRenderPass(commands, &begin, VK_SUBPASS_CONTENTS_INLINE);
vkCmdEndRenderPass(commands);
image.layout = VK_IMAGE_LAYOUT_GENERAL;
@@ -227,7 +226,6 @@
const VkImageSubresourceRange range{image.aspect, 0, 1, 0, image.layers};
if (shadow) {
const VkClearDepthStencilValue depth{0.0f, 0};
EndActiveRenderPassOn(commands);
vkCmdClearDepthStencilImage(commands, image.image, image.layout, &depth, 1, &range);
} else vkCmdClearColorImage(commands, image.image, image.layout, &clear.color, 1, &range);
if (!VkTextureManager::TransitionImageLayout(commands, image.image, image.layout,
@@ -238,7 +236,6 @@
VkMemoryBarrier visible{VK_STRUCTURE_TYPE_MEMORY_BARRIER};
visible.srcAccessMask = multisample ? VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT : VK_ACCESS_TRANSFER_WRITE_BIT;
visible.dstAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
EndActiveRenderPassOn(commands);
vkCmdPipelineBarrier(commands, multisample ? VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT : VK_PIPELINE_STAGE_TRANSFER_BIT,
VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, 1, &visible, 0, nullptr, 0, nullptr);
}
@@ -499,11 +499,6 @@
void VulkanRenderer::AcquireSharedImage(VkTextureManager::TextureResource& resource) {
namespace SI = MG_Remote::Server::SharedImages;
// A YUV image is converted into the texture's own image instead (WireYuvImage.inc).
if (resource.yuvImageId != 0) {
(void)ConvertYuvSharedImage(resource);
return;
}
if (resource.sharedImageId == 0 || resource.image == VK_NULL_HANDLE || resource.sharedImageOwner == nullptr)
return;
const auto image = std::static_pointer_cast<const SI::Image>(resource.sharedImageOwner);
@@ -522,11 +517,6 @@
// 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};
@@ -572,8 +562,6 @@
// family in the frame's last recording, and that recording's submission signals the semaphore
// whose sync_file is published as the frame's read fence for all of them at once.
void VulkanRenderer::ReleaseHeldSharedImages() {
// A frame boundary: a YUV texture's next use converts its image again.
++m_yuvFrameSerial;
if (m_sharedImagesHeld.empty()) return;
const Uint32 family = static_cast<Uint32>(m_physicalDevice.queueFamilies.graphicsFamily);
Vector<VkImageMemoryBarrier> releases;
@@ -607,75 +595,6 @@
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;
// Every fence the application asks for ends one of its frames as far as a YUV texture is
// concerned (an offscreen producer - a browser's GPU process - has no present to do it).
++m_yuvFrameSerial;
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;
@@ -688,11 +607,7 @@
}
// No fence (no export on this device): the frame's reads go unpublished - the file
// comment says why that is the choice.
// A session that writes images publishes every boundary as a write (PublishSharedImageAccesses).
if (m_sharedImageImplicitSync)
m_sharedImageReads.PublishFrameAsWrite(fence);
else
m_sharedImageReads.PublishFrame(fence);
m_sharedImageReads.PublishFrame(fence);
}
void VulkanRenderer::AbandonSharedImageReads() {
@@ -1,10 +0,0 @@
#version 450
// The image is bound through an immutable sampler that carries its VkSamplerYcbcrConversion, so
// a plain sample already returns RGB.
layout(set = 0, binding = 0) uniform sampler2D yuvImage;
layout(location = 0) in vec2 texCoord;
layout(location = 0) out vec4 outColor;
void main() {
outColor = vec4(textureLod(yuvImage, texCoord, 0.0).rgb, 1.0);
}
@@ -1,11 +0,0 @@
#version 450
// A YUV shared image converted into an RGBA texture (WireYuvImage.inc): one triangle over the
// whole target, its first row at the image's first row.
layout(location = 0) out vec2 texCoord;
void main() {
const vec2 corners[3] = vec2[](vec2(-1.0, -1.0), vec2(3.0, -1.0), vec2(-1.0, 3.0));
vec2 p = corners[gl_VertexIndex];
gl_Position = vec4(p, 0.0, 1.0);
texCoord = (p + 1.0) * 0.5;
}
@@ -1,78 +0,0 @@
// Generated from WireYuvConvert.vert / WireYuvConvert.frag (Vulkan 1.0 / SPIR-V 1.0) by
// scripts/bake_internal_shaders.py, which runs MG_Test's BakedInternalShadersTest with the
// IN-TREE glslang and splices the words it emits into the arrays below. Do not edit the words
// by hand: MOBILEGL_BAKED_INTERNAL_SHADERS (the same test, run as a gate) recompiles every
// source in its table and reds on the first word that disagrees.
#pragma once
static constexpr Uint32 kWireYuvConvertVertexSpirv[] = {
0x07230203u, 0x00010000u, 0x0008000bu, 0x00000031u, 0x00000000u, 0x00020011u, 0x00000001u, 0x0006000bu,
0x00000001u, 0x4c534c47u, 0x6474732eu, 0x3035342eu, 0x00000000u, 0x0003000eu, 0x00000000u, 0x00000001u,
0x0008000fu, 0x00000000u, 0x00000004u, 0x6e69616du, 0x00000000u, 0x00000015u, 0x00000020u, 0x0000002bu,
0x00030003u, 0x00000002u, 0x000001c2u, 0x00040005u, 0x00000004u, 0x6e69616du, 0x00000000u, 0x00030005u,
0x00000009u, 0x00000070u, 0x00060005u, 0x00000015u, 0x565f6c67u, 0x65747265u, 0x646e4978u, 0x00007865u,
0x00050005u, 0x00000018u, 0x65646e69u, 0x6c626178u, 0x00000065u, 0x00060005u, 0x0000001eu, 0x505f6c67u,
0x65567265u, 0x78657472u, 0x00000000u, 0x00060006u, 0x0000001eu, 0x00000000u, 0x505f6c67u, 0x7469736fu,
0x006e6f69u, 0x00070006u, 0x0000001eu, 0x00000001u, 0x505f6c67u, 0x746e696fu, 0x657a6953u, 0x00000000u,
0x00070006u, 0x0000001eu, 0x00000002u, 0x435f6c67u, 0x4470696cu, 0x61747369u, 0x0065636eu, 0x00070006u,
0x0000001eu, 0x00000003u, 0x435f6c67u, 0x446c6c75u, 0x61747369u, 0x0065636eu, 0x00030005u, 0x00000020u,
0x00000000u, 0x00050005u, 0x0000002bu, 0x43786574u, 0x64726f6fu, 0x00000000u, 0x00040047u, 0x00000015u,
0x0000000bu, 0x0000002au, 0x00030047u, 0x0000001eu, 0x00000002u, 0x00050048u, 0x0000001eu, 0x00000000u,
0x0000000bu, 0x00000000u, 0x00050048u, 0x0000001eu, 0x00000001u, 0x0000000bu, 0x00000001u, 0x00050048u,
0x0000001eu, 0x00000002u, 0x0000000bu, 0x00000003u, 0x00050048u, 0x0000001eu, 0x00000003u, 0x0000000bu,
0x00000004u, 0x00040047u, 0x0000002bu, 0x0000001eu, 0x00000000u, 0x00020013u, 0x00000002u, 0x00030021u,
0x00000003u, 0x00000002u, 0x00030016u, 0x00000006u, 0x00000020u, 0x00040017u, 0x00000007u, 0x00000006u,
0x00000002u, 0x00040020u, 0x00000008u, 0x00000007u, 0x00000007u, 0x00040015u, 0x0000000au, 0x00000020u,
0x00000000u, 0x0004002bu, 0x0000000au, 0x0000000bu, 0x00000003u, 0x0004001cu, 0x0000000cu, 0x00000007u,
0x0000000bu, 0x0004002bu, 0x00000006u, 0x0000000du, 0xbf800000u, 0x0005002cu, 0x00000007u, 0x0000000eu,
0x0000000du, 0x0000000du, 0x0004002bu, 0x00000006u, 0x0000000fu, 0x40400000u, 0x0005002cu, 0x00000007u,
0x00000010u, 0x0000000fu, 0x0000000du, 0x0005002cu, 0x00000007u, 0x00000011u, 0x0000000du, 0x0000000fu,
0x0006002cu, 0x0000000cu, 0x00000012u, 0x0000000eu, 0x00000010u, 0x00000011u, 0x00040015u, 0x00000013u,
0x00000020u, 0x00000001u, 0x00040020u, 0x00000014u, 0x00000001u, 0x00000013u, 0x0004003bu, 0x00000014u,
0x00000015u, 0x00000001u, 0x00040020u, 0x00000017u, 0x00000007u, 0x0000000cu, 0x00040017u, 0x0000001bu,
0x00000006u, 0x00000004u, 0x0004002bu, 0x0000000au, 0x0000001cu, 0x00000001u, 0x0004001cu, 0x0000001du,
0x00000006u, 0x0000001cu, 0x0006001eu, 0x0000001eu, 0x0000001bu, 0x00000006u, 0x0000001du, 0x0000001du,
0x00040020u, 0x0000001fu, 0x00000003u, 0x0000001eu, 0x0004003bu, 0x0000001fu, 0x00000020u, 0x00000003u,
0x0004002bu, 0x00000013u, 0x00000021u, 0x00000000u, 0x0004002bu, 0x00000006u, 0x00000023u, 0x00000000u,
0x0004002bu, 0x00000006u, 0x00000024u, 0x3f800000u, 0x00040020u, 0x00000028u, 0x00000003u, 0x0000001bu,
0x00040020u, 0x0000002au, 0x00000003u, 0x00000007u, 0x0004003bu, 0x0000002au, 0x0000002bu, 0x00000003u,
0x0004002bu, 0x00000006u, 0x0000002fu, 0x3f000000u, 0x00050036u, 0x00000002u, 0x00000004u, 0x00000000u,
0x00000003u, 0x000200f8u, 0x00000005u, 0x0004003bu, 0x00000008u, 0x00000009u, 0x00000007u, 0x0004003bu,
0x00000017u, 0x00000018u, 0x00000007u, 0x0004003du, 0x00000013u, 0x00000016u, 0x00000015u, 0x0003003eu,
0x00000018u, 0x00000012u, 0x00050041u, 0x00000008u, 0x00000019u, 0x00000018u, 0x00000016u, 0x0004003du,
0x00000007u, 0x0000001au, 0x00000019u, 0x0003003eu, 0x00000009u, 0x0000001au, 0x0004003du, 0x00000007u,
0x00000022u, 0x00000009u, 0x00050051u, 0x00000006u, 0x00000025u, 0x00000022u, 0x00000000u, 0x00050051u,
0x00000006u, 0x00000026u, 0x00000022u, 0x00000001u, 0x00070050u, 0x0000001bu, 0x00000027u, 0x00000025u,
0x00000026u, 0x00000023u, 0x00000024u, 0x00050041u, 0x00000028u, 0x00000029u, 0x00000020u, 0x00000021u,
0x0003003eu, 0x00000029u, 0x00000027u, 0x0004003du, 0x00000007u, 0x0000002cu, 0x00000009u, 0x00050050u,
0x00000007u, 0x0000002du, 0x00000024u, 0x00000024u, 0x00050081u, 0x00000007u, 0x0000002eu, 0x0000002cu,
0x0000002du, 0x0005008eu, 0x00000007u, 0x00000030u, 0x0000002eu, 0x0000002fu, 0x0003003eu, 0x0000002bu,
0x00000030u, 0x000100fdu, 0x00010038u,
};
static constexpr Uint32 kWireYuvConvertFragmentSpirv[] = {
0x07230203u, 0x00010000u, 0x0008000bu, 0x0000001cu, 0x00000000u, 0x00020011u, 0x00000001u, 0x0006000bu,
0x00000001u, 0x4c534c47u, 0x6474732eu, 0x3035342eu, 0x00000000u, 0x0003000eu, 0x00000000u, 0x00000001u,
0x0007000fu, 0x00000004u, 0x00000004u, 0x6e69616du, 0x00000000u, 0x00000009u, 0x00000011u, 0x00030010u,
0x00000004u, 0x00000007u, 0x00030003u, 0x00000002u, 0x000001c2u, 0x00040005u, 0x00000004u, 0x6e69616du,
0x00000000u, 0x00050005u, 0x00000009u, 0x4374756fu, 0x726f6c6fu, 0x00000000u, 0x00050005u, 0x0000000du,
0x49767579u, 0x6567616du, 0x00000000u, 0x00050005u, 0x00000011u, 0x43786574u, 0x64726f6fu, 0x00000000u,
0x00040047u, 0x00000009u, 0x0000001eu, 0x00000000u, 0x00040047u, 0x0000000du, 0x00000021u, 0x00000000u,
0x00040047u, 0x0000000du, 0x00000022u, 0x00000000u, 0x00040047u, 0x00000011u, 0x0000001eu, 0x00000000u,
0x00020013u, 0x00000002u, 0x00030021u, 0x00000003u, 0x00000002u, 0x00030016u, 0x00000006u, 0x00000020u,
0x00040017u, 0x00000007u, 0x00000006u, 0x00000004u, 0x00040020u, 0x00000008u, 0x00000003u, 0x00000007u,
0x0004003bu, 0x00000008u, 0x00000009u, 0x00000003u, 0x00090019u, 0x0000000au, 0x00000006u, 0x00000001u,
0x00000000u, 0x00000000u, 0x00000000u, 0x00000001u, 0x00000000u, 0x0003001bu, 0x0000000bu, 0x0000000au,
0x00040020u, 0x0000000cu, 0x00000000u, 0x0000000bu, 0x0004003bu, 0x0000000cu, 0x0000000du, 0x00000000u,
0x00040017u, 0x0000000fu, 0x00000006u, 0x00000002u, 0x00040020u, 0x00000010u, 0x00000001u, 0x0000000fu,
0x0004003bu, 0x00000010u, 0x00000011u, 0x00000001u, 0x0004002bu, 0x00000006u, 0x00000013u, 0x00000000u,
0x00040017u, 0x00000015u, 0x00000006u, 0x00000003u, 0x0004002bu, 0x00000006u, 0x00000017u, 0x3f800000u,
0x00050036u, 0x00000002u, 0x00000004u, 0x00000000u, 0x00000003u, 0x000200f8u, 0x00000005u, 0x0004003du,
0x0000000bu, 0x0000000eu, 0x0000000du, 0x0004003du, 0x0000000fu, 0x00000012u, 0x00000011u, 0x00070058u,
0x00000007u, 0x00000014u, 0x0000000eu, 0x00000012u, 0x00000002u, 0x00000013u, 0x0008004fu, 0x00000015u,
0x00000016u, 0x00000014u, 0x00000014u, 0x00000000u, 0x00000001u, 0x00000002u, 0x00050051u, 0x00000006u,
0x00000018u, 0x00000016u, 0x00000000u, 0x00050051u, 0x00000006u, 0x00000019u, 0x00000016u, 0x00000001u,
0x00050051u, 0x00000006u, 0x0000001au, 0x00000016u, 0x00000002u, 0x00070050u, 0x00000007u, 0x0000001bu,
0x00000018u, 0x00000019u, 0x0000001au, 0x00000017u, 0x0003003eu, 0x00000009u, 0x0000001bu, 0x000100fdu,
0x00010038u,
};
@@ -1,515 +0,0 @@
// Included by VulkanRenderer.cpp inside the backend namespace, after WireSharedImage.inc.
//
// YUV SHARED IMAGES (NV12, P010; MG_Remote/Server/SharedImageYuv.h). A YUV image is never a
// texture's image: the texture keeps its own RGBA8 level 0 (VkTextureManager::SyncWireTextureShape)
// and, at its first use in each frame, the image is CONVERTED into it here - the image's
// AHardwareBuffer imported with its external format, sampled through an immutable sampler that
// carries a VkSamplerYcbcrConversion built from the import's colour hints, one triangle over the
// target. Zero CPU copies for an image this server allocated; a foreign one (a video decoder's
// buffer) is first brought up to date by the registry's labelled CPU copy (RefreshForeign).
//
// Why converted rather than sampled in place: a Y'CbCr conversion is an immutable sampler, which
// lives in the descriptor set layout and therefore in every application pipeline that samples the
// texture. A conversion pass keeps those pipelines exactly what they are for an RGBA texture, at
// the cost of one small pass per new frame of the video.
#if MOBILEGL_BUILD_DISAGGREGATED
#include "WireYuvConvertSpirv.h"
struct VulkanRenderer::WireYuvResources {
PFN_vkCreateSamplerYcbcrConversion createConversion = nullptr;
PFN_vkDestroySamplerYcbcrConversion destroyConversion = nullptr;
VkShaderModule vertex = VK_NULL_HANDLE, fragment = VK_NULL_HANDLE;
// One per (buffer format, conversion, target format). Never dropped before shutdown: a
// device sees a handful of them.
struct Pipeline {
Uint64 externalFormat = 0;
VkFormat format = VK_FORMAT_UNDEFINED;
VkSamplerYcbcrModelConversion model = VK_SAMPLER_YCBCR_MODEL_CONVERSION_RGB_IDENTITY;
VkSamplerYcbcrRange range = VK_SAMPLER_YCBCR_RANGE_ITU_FULL;
VkComponentMapping components{};
VkChromaLocation xOffset = VK_CHROMA_LOCATION_COSITED_EVEN;
VkChromaLocation yOffset = VK_CHROMA_LOCATION_COSITED_EVEN;
VkFilter chromaFilter = VK_FILTER_NEAREST;
VkFormat target = VK_FORMAT_UNDEFINED;
VkSamplerYcbcrConversion conversion = VK_NULL_HANDLE;
VkSampler sampler = VK_NULL_HANDLE;
VkDescriptorSetLayout descriptorLayout = VK_NULL_HANDLE;
VkPipelineLayout pipelineLayout = VK_NULL_HANDLE;
VkRenderPass renderPass = VK_NULL_HANDLE;
VkPipeline pipeline = VK_NULL_HANDLE;
};
Vector<Pipeline> pipelines;
};
namespace {
// One texture's import of its YUV buffer (TextureResource::yuvSource): the image on the
// buffer's memory and a view through the conversion of `pipeline`. Destroyed by the
// resource's (deferred) Reset, so never under a submission still reading it.
struct WireYuvSource {
VkDevice device = VK_NULL_HANDLE;
VkImage image = VK_NULL_HANDLE;
VkDeviceMemory memory = VK_NULL_HANDLE;
VkImageView view = VK_NULL_HANDLE;
SizeT pipeline = 0;
MG_Remote::Server::SharedImages::Yuv::Hints hints;
~WireYuvSource() {
if (device == VK_NULL_HANDLE) return;
if (view != VK_NULL_HANDLE) vkDestroyImageView(device, view, nullptr);
if (image != VK_NULL_HANDLE) vkDestroyImage(device, image, nullptr);
if (memory != VK_NULL_HANDLE) vkFreeMemory(device, memory, nullptr);
}
};
VkSamplerYcbcrModelConversion YcbcrModelFor(const MG_Remote::Server::SharedImages::Yuv::Hints& hints) {
namespace Yuv = MG_Remote::Server::SharedImages::Yuv;
switch (hints.EffectiveColorSpace()) {
case Yuv::kEglItuRec709:
return VK_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_709;
case Yuv::kEglItuRec2020:
return VK_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_2020;
default:
return VK_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_601;
}
}
} // namespace
void VulkanRenderer::DestroyWireYuvResources() {
if (!m_wireYuvResources) return;
auto& cache = *m_wireYuvResources;
for (const auto& entry : cache.pipelines) {
vkDestroyPipeline(m_device, entry.pipeline, nullptr);
vkDestroyRenderPass(m_device, entry.renderPass, nullptr);
vkDestroyPipelineLayout(m_device, entry.pipelineLayout, nullptr);
vkDestroyDescriptorSetLayout(m_device, entry.descriptorLayout, nullptr);
vkDestroySampler(m_device, entry.sampler, nullptr);
if (cache.destroyConversion != nullptr) cache.destroyConversion(m_device, entry.conversion, nullptr);
}
vkDestroyShaderModule(m_device, cache.vertex, nullptr);
vkDestroyShaderModule(m_device, cache.fragment, nullptr);
delete m_wireYuvResources;
m_wireYuvResources = nullptr;
}
Bool VulkanRenderer::ConvertYuvSharedImage(VkTextureManager::TextureResource& resource) {
#if defined(__ANDROID__)
namespace SI = MG_Remote::Server::SharedImages;
if (resource.yuvConvertedFrame == m_yuvFrameSerial) return true;
const auto image = std::static_pointer_cast<const SI::Image>(resource.yuvOwner);
if (image == nullptr || image->Native == nullptr || resource.image == VK_NULL_HANDLE) return false;
if (!m_samplerYcbcrConversion) {
MGLOG_E_ONCE("Magma: YUV shared image %llu cannot be sampled: the device has no samplerYcbcrConversion",
static_cast<unsigned long long>(image->Id));
return false;
}
// Whatever happens below, this frame does not try again.
resource.yuvConvertedFrame = m_yuvFrameSerial;
// THE CPU-COPY FALLBACK, for a buffer this server did not allocate (SharedImageRegistry.h).
String why;
if (image->IsForeign() && !SI::RefreshForeign(*image, why)) {
MGLOG_E_ONCE("Magma: foreign YUV image %llu could not be refreshed: %s",
static_cast<unsigned long long>(image->Id), why.c_str());
}
const SI::Yuv::Hints hints = SI::GetYuvHints(*image);
if (!m_wireYuvResources) {
m_wireYuvResources = new WireYuvResources;
auto& cache = *m_wireYuvResources;
cache.createConversion = reinterpret_cast<PFN_vkCreateSamplerYcbcrConversion>(
vkGetDeviceProcAddr(m_device, "vkCreateSamplerYcbcrConversion"));
if (cache.createConversion == nullptr)
cache.createConversion = reinterpret_cast<PFN_vkCreateSamplerYcbcrConversion>(
vkGetDeviceProcAddr(m_device, "vkCreateSamplerYcbcrConversionKHR"));
cache.destroyConversion = reinterpret_cast<PFN_vkDestroySamplerYcbcrConversion>(
vkGetDeviceProcAddr(m_device, "vkDestroySamplerYcbcrConversion"));
if (cache.destroyConversion == nullptr)
cache.destroyConversion = reinterpret_cast<PFN_vkDestroySamplerYcbcrConversion>(
vkGetDeviceProcAddr(m_device, "vkDestroySamplerYcbcrConversionKHR"));
const auto shader = [&](const Uint32* code, SizeT bytes, VkShaderModule& module) {
VkShaderModuleCreateInfo info{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO};
info.codeSize = bytes;
info.pCode = code;
VK_VERIFY(vkCreateShaderModule(m_device, &info, nullptr, &module));
};
shader(kWireYuvConvertVertexSpirv, sizeof(kWireYuvConvertVertexSpirv), cache.vertex);
shader(kWireYuvConvertFragmentSpirv, sizeof(kWireYuvConvertFragmentSpirv), cache.fragment);
}
auto& cache = *m_wireYuvResources;
if (cache.createConversion == nullptr || cache.destroyConversion == nullptr) {
MGLOG_E_ONCE("Magma: vkCreateSamplerYcbcrConversion is not available; YUV images cannot be sampled");
return false;
}
// ---- the texture's import of the buffer, and the pipeline its conversion needs ----
auto* source = static_cast<WireYuvSource*>(resource.yuvSource.get());
if (source != nullptr && !(source->hints == hints)) {
// Re-imported with other colour hints: the conversion (and so the view) changes.
auto retired = MakeUnique<VkTextureManager::TextureResource>();
retired->yuvSource = std::move(resource.yuvSource);
WireRetiredObjects objects{};
objects.textures.push_back(Move(retired));
RetireWireObjects(Move(objects));
source = nullptr;
}
if (source == nullptr) {
WireAhbImport ctx;
if (!GetWireAhbImport(ctx)) return false;
auto* ahb = static_cast<AHardwareBuffer*>(image->Native);
const auto getProperties =
reinterpret_cast<PFN_vkGetAndroidHardwareBufferPropertiesANDROID>(ctx.getAhbProperties);
VkAndroidHardwareBufferFormatPropertiesANDROID format{
VK_STRUCTURE_TYPE_ANDROID_HARDWARE_BUFFER_FORMAT_PROPERTIES_ANDROID};
VkAndroidHardwareBufferPropertiesANDROID properties{
VK_STRUCTURE_TYPE_ANDROID_HARDWARE_BUFFER_PROPERTIES_ANDROID};
properties.pNext = &format;
if (getProperties(m_device, ahb, &properties) != VK_SUCCESS) {
MGLOG_E_ONCE("Magma: YUV image %llu: vkGetAndroidHardwareBufferPropertiesANDROID failed",
static_cast<unsigned long long>(image->Id));
return false;
}
// The conversion: the import's hints where it gave them, else what the buffer suggests.
WireYuvResources::Pipeline key;
key.externalFormat = format.format == VK_FORMAT_UNDEFINED ? format.externalFormat : 0;
key.format = format.format;
key.model = hints.ColorSpace != 0 ? YcbcrModelFor(hints) : format.suggestedYcbcrModel;
key.range = hints.Range != 0 ? (hints.FullRange() ? VK_SAMPLER_YCBCR_RANGE_ITU_FULL
: VK_SAMPLER_YCBCR_RANGE_ITU_NARROW)
: format.suggestedYcbcrRange;
key.components = format.samplerYcbcrConversionComponents;
const auto chroma = [&format](Uint32 siting, VkChromaLocation suggested) {
const Bool midpoint = siting == SI::Yuv::kEglYuvChromaSiting0_5;
const Bool cosited = siting == SI::Yuv::kEglYuvChromaSiting0;
if (midpoint && (format.formatFeatures & VK_FORMAT_FEATURE_MIDPOINT_CHROMA_SAMPLES_BIT))
return VK_CHROMA_LOCATION_MIDPOINT;
if (cosited && (format.formatFeatures & VK_FORMAT_FEATURE_COSITED_CHROMA_SAMPLES_BIT))
return VK_CHROMA_LOCATION_COSITED_EVEN;
return suggested;
};
key.xOffset = chroma(hints.SitingX, format.suggestedXChromaOffset);
key.yOffset = chroma(hints.SitingY, format.suggestedYChromaOffset);
key.chromaFilter =
(format.formatFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_YCBCR_CONVERSION_LINEAR_FILTER_BIT) != 0
? VK_FILTER_LINEAR
: VK_FILTER_NEAREST;
key.target = resource.format;
SizeT index = cache.pipelines.size();
for (SizeT i = 0; i < cache.pipelines.size(); ++i) {
const auto& p = cache.pipelines[i];
if (p.externalFormat == key.externalFormat && p.format == key.format && p.model == key.model &&
p.range == key.range && p.components.r == key.components.r &&
p.components.g == key.components.g && p.components.b == key.components.b &&
p.components.a == key.components.a && p.xOffset == key.xOffset && p.yOffset == key.yOffset &&
p.chromaFilter == key.chromaFilter && p.target == key.target) {
index = i;
break;
}
}
if (index == cache.pipelines.size()) {
VkExternalFormatANDROID external{VK_STRUCTURE_TYPE_EXTERNAL_FORMAT_ANDROID};
external.externalFormat = key.externalFormat;
VkSamplerYcbcrConversionCreateInfo conversion{VK_STRUCTURE_TYPE_SAMPLER_YCBCR_CONVERSION_CREATE_INFO};
conversion.pNext = key.externalFormat != 0 ? &external : nullptr;
conversion.format = key.format;
conversion.ycbcrModel = key.model;
conversion.ycbcrRange = key.range;
conversion.components = key.components;
conversion.xChromaOffset = key.xOffset;
conversion.yChromaOffset = key.yOffset;
conversion.chromaFilter = key.chromaFilter;
conversion.forceExplicitReconstruction = VK_FALSE;
if (cache.createConversion(m_device, &conversion, nullptr, &key.conversion) != VK_SUCCESS) {
MGLOG_E_ONCE("Magma: YUV image %llu: vkCreateSamplerYcbcrConversion failed",
static_cast<unsigned long long>(image->Id));
return false;
}
VkSamplerYcbcrConversionInfo conversionInfo{VK_STRUCTURE_TYPE_SAMPLER_YCBCR_CONVERSION_INFO};
conversionInfo.conversion = key.conversion;
VkSamplerCreateInfo sampler{VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO};
sampler.pNext = &conversionInfo;
// Without separate reconstruction filters the sampler filters as the conversion does.
sampler.magFilter = sampler.minFilter = key.chromaFilter;
sampler.mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST;
sampler.addressModeU = sampler.addressModeV = sampler.addressModeW =
VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE;
sampler.maxLod = 0.0f;
VK_VERIFY(vkCreateSampler(m_device, &sampler, nullptr, &key.sampler));
const VkDescriptorSetLayoutBinding binding{0, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1,
VK_SHADER_STAGE_FRAGMENT_BIT, &key.sampler};
VkDescriptorSetLayoutCreateInfo layout{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO};
layout.bindingCount = 1;
layout.pBindings = &binding;
VK_VERIFY(vkCreateDescriptorSetLayout(m_device, &layout, nullptr, &key.descriptorLayout));
VkPipelineLayoutCreateInfo pipelineLayout{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO};
pipelineLayout.setLayoutCount = 1;
pipelineLayout.pSetLayouts = &key.descriptorLayout;
VK_VERIFY(vkCreatePipelineLayout(m_device, &pipelineLayout, nullptr, &key.pipelineLayout));
// Every texel of the target is written: nothing to load.
VkAttachmentDescription attachment{};
attachment.format = key.target;
attachment.samples = VK_SAMPLE_COUNT_1_BIT;
attachment.loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
attachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
attachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
attachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
attachment.initialLayout = attachment.finalLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
const VkAttachmentReference color{0, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL};
VkSubpassDescription subpass{};
subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
subpass.colorAttachmentCount = 1;
subpass.pColorAttachments = &color;
VkRenderPassCreateInfo pass{VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO};
pass.attachmentCount = 1;
pass.pAttachments = &attachment;
pass.subpassCount = 1;
pass.pSubpasses = &subpass;
VK_VERIFY(vkCreateRenderPass(m_device, &pass, nullptr, &key.renderPass));
VkPipelineShaderStageCreateInfo stages[2]{};
for (auto& stage : stages) {
stage.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
stage.pName = "main";
}
stages[0].stage = VK_SHADER_STAGE_VERTEX_BIT;
stages[0].module = cache.vertex;
stages[1].stage = VK_SHADER_STAGE_FRAGMENT_BIT;
stages[1].module = cache.fragment;
const VkPipelineVertexInputStateCreateInfo vertex{
VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO};
VkPipelineInputAssemblyStateCreateInfo assembly{
VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO};
assembly.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
VkPipelineViewportStateCreateInfo viewport{VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO};
viewport.viewportCount = viewport.scissorCount = 1;
VkPipelineRasterizationStateCreateInfo raster{
VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO};
raster.polygonMode = VK_POLYGON_MODE_FILL;
raster.cullMode = VK_CULL_MODE_NONE;
raster.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE;
raster.lineWidth = 1.0f;
VkPipelineMultisampleStateCreateInfo samples{
VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO};
samples.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT;
VkPipelineColorBlendAttachmentState colorMask{};
colorMask.colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT |
VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT;
VkPipelineColorBlendStateCreateInfo blend{VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO};
blend.attachmentCount = 1;
blend.pAttachments = &colorMask;
const VkDynamicState dynamicStates[]{VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR};
VkPipelineDynamicStateCreateInfo dynamic{VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO};
dynamic.dynamicStateCount = 2;
dynamic.pDynamicStates = dynamicStates;
VkGraphicsPipelineCreateInfo pipeline{VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO};
pipeline.stageCount = 2;
pipeline.pStages = stages;
pipeline.pVertexInputState = &vertex;
pipeline.pInputAssemblyState = &assembly;
pipeline.pViewportState = &viewport;
pipeline.pRasterizationState = &raster;
pipeline.pMultisampleState = &samples;
pipeline.pColorBlendState = &blend;
pipeline.pDynamicState = &dynamic;
pipeline.layout = key.pipelineLayout;
pipeline.renderPass = key.renderPass;
VK_VERIFY(vkCreateGraphicsPipelines(m_device, VK_NULL_HANDLE, 1, &pipeline, nullptr, &key.pipeline));
cache.pipelines.push_back(key);
MGLOG_I("Magma: YUV conversion pipeline %zu: %s format %llu, model %d, range %d, chroma %d/%d, "
"filter %d",
index, key.externalFormat != 0 ? "external" : "Vulkan",
static_cast<unsigned long long>(key.externalFormat != 0 ? key.externalFormat
: static_cast<Uint64>(key.format)),
static_cast<Int>(key.model), static_cast<Int>(key.range), static_cast<Int>(key.xOffset),
static_cast<Int>(key.yOffset), static_cast<Int>(key.chromaFilter));
}
const auto& chosen = cache.pipelines[index];
// The buffer, imported with its external format, sampled only.
auto created = std::make_shared<WireYuvSource>();
created->device = m_device;
created->pipeline = index;
created->hints = hints;
VkExternalFormatANDROID external{VK_STRUCTURE_TYPE_EXTERNAL_FORMAT_ANDROID};
external.externalFormat = chosen.externalFormat;
VkExternalMemoryImageCreateInfo externalMemory{VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO};
externalMemory.pNext = chosen.externalFormat != 0 ? &external : nullptr;
externalMemory.handleTypes = VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID;
VkImageCreateInfo imageInfo{VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO};
imageInfo.pNext = &externalMemory;
imageInfo.imageType = VK_IMAGE_TYPE_2D;
imageInfo.format = chosen.format;
imageInfo.extent = {image->Width, image->Height, 1};
imageInfo.mipLevels = 1;
imageInfo.arrayLayers = 1;
imageInfo.samples = VK_SAMPLE_COUNT_1_BIT;
imageInfo.tiling = VK_IMAGE_TILING_OPTIMAL;
imageInfo.usage = VK_IMAGE_USAGE_SAMPLED_BIT;
imageInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
imageInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
if (vkCreateImage(m_device, &imageInfo, nullptr, &created->image) != VK_SUCCESS) {
created->image = VK_NULL_HANDLE;
MGLOG_E_ONCE("Magma: YUV image %llu: vkCreateImage(external format) failed",
static_cast<unsigned long long>(image->Id));
return false;
}
Int32 type = -1;
for (Uint32 i = 0; i < ctx.memory.memoryTypeCount && type < 0; ++i) {
if ((properties.memoryTypeBits & (1u << i)) != 0) type = static_cast<Int32>(i);
}
VkMemoryDedicatedAllocateInfo dedicated{VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO};
dedicated.image = created->image;
VkImportAndroidHardwareBufferInfoANDROID import{
VK_STRUCTURE_TYPE_IMPORT_ANDROID_HARDWARE_BUFFER_INFO_ANDROID};
import.pNext = &dedicated;
import.buffer = ahb;
VkMemoryAllocateInfo allocate{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO};
allocate.pNext = &import;
allocate.allocationSize = properties.allocationSize;
allocate.memoryTypeIndex = static_cast<Uint32>(type < 0 ? 0 : type);
if (type < 0 || vkAllocateMemory(m_device, &allocate, nullptr, &created->memory) != VK_SUCCESS ||
vkBindImageMemory(m_device, created->image, created->memory, 0) != VK_SUCCESS) {
MGLOG_E_ONCE("Magma: YUV image %llu: its buffer could not be imported",
static_cast<unsigned long long>(image->Id));
return false;
}
VkSamplerYcbcrConversionInfo conversionInfo{VK_STRUCTURE_TYPE_SAMPLER_YCBCR_CONVERSION_INFO};
conversionInfo.conversion = chosen.conversion;
VkImageViewCreateInfo view{VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO};
view.pNext = &conversionInfo;
view.image = created->image;
view.viewType = VK_IMAGE_VIEW_TYPE_2D;
view.format = chosen.format;
view.components = {VK_COMPONENT_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_IDENTITY,
VK_COMPONENT_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_IDENTITY};
view.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
if (vkCreateImageView(m_device, &view, nullptr, &created->view) != VK_SUCCESS) {
created->view = VK_NULL_HANDLE;
MGLOG_E_ONCE("Magma: YUV image %llu: its view could not be created",
static_cast<unsigned long long>(image->Id));
return false;
}
MGLOG_I("Magma: YUV image %llu (%ux%u%s) sampled through conversion pipeline %zu",
static_cast<unsigned long long>(image->Id), image->Width, image->Height,
image->IsForeign() ? ", foreign: CPU-copied" : ", zero-copy", index);
resource.yuvSource = created;
source = created.get();
}
const auto& chosen = cache.pipelines[source->pipeline];
// ---- the pass ----
auto& frame = m_frameContext.GetCurrent();
if (!frame.isCommandRecording) m_frameContext.BeginCommandRecording();
if (VkRenderPassManager::GetActiveRenderPass()) VkRenderPassManager::EndRenderPass(frame.commandBuffer);
m_textureManager->FlushPendingUploads();
const Uint32 family = static_cast<Uint32>(m_physicalDevice.queueFamilies.graphicsFamily);
// The buffer's content is its producer's (the CPU's copy, or the allocator's writer): it is
// acquired from the foreign family for the read and handed back after it.
VkImageMemoryBarrier acquire{VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER};
acquire.srcAccessMask = 0;
acquire.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
acquire.oldLayout = VK_IMAGE_LAYOUT_GENERAL;
acquire.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
acquire.srcQueueFamilyIndex = VK_QUEUE_FAMILY_FOREIGN_EXT;
acquire.dstQueueFamilyIndex = family;
acquire.image = source->image;
acquire.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
EndActiveRenderPassOn(frame.commandBuffer);
vkCmdPipelineBarrier(frame.commandBuffer, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, 0, 0, nullptr, 0, nullptr, 1, &acquire);
WireImage target{};
target.image = resource.image;
target.format = resource.format;
target.viewType = VK_IMAGE_VIEW_TYPE_2D;
target.extent = resource.extent;
target.layout = resource.layout;
target.trackedLayout = &resource.layout;
target.aspect = VK_IMAGE_ASPECT_COLOR_BIT;
target.usageFlags = resource.usageFlags;
target.levels = resource.mipLevels;
TransitionWireImage(target, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL);
VkImageViewCreateInfo targetViewInfo{VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO};
targetViewInfo.image = resource.image;
targetViewInfo.viewType = VK_IMAGE_VIEW_TYPE_2D;
targetViewInfo.format = resource.format;
targetViewInfo.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
VkImageView targetView = VK_NULL_HANDLE;
VK_VERIFY(vkCreateImageView(m_device, &targetViewInfo, nullptr, &targetView));
VkFramebufferCreateInfo framebufferInfo{VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO};
framebufferInfo.renderPass = chosen.renderPass;
framebufferInfo.attachmentCount = 1;
framebufferInfo.pAttachments = &targetView;
framebufferInfo.width = resource.extent.width;
framebufferInfo.height = resource.extent.height;
framebufferInfo.layers = 1;
VkFramebuffer framebuffer = VK_NULL_HANDLE;
VK_VERIFY(vkCreateFramebuffer(m_device, &framebufferInfo, nullptr, &framebuffer));
// A multi-planar image may take more than one descriptor of its binding.
VkDescriptorPool descriptorPool = VK_NULL_HANDLE;
VkDescriptorSet descriptorSet = VK_NULL_HANDLE;
const VkDescriptorPoolSize poolSize{VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 3};
VkDescriptorPoolCreateInfo pool{VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO};
pool.maxSets = 1;
pool.poolSizeCount = 1;
pool.pPoolSizes = &poolSize;
VK_VERIFY(vkCreateDescriptorPool(m_device, &pool, nullptr, &descriptorPool));
VkDescriptorSetAllocateInfo alloc{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO};
alloc.descriptorPool = descriptorPool;
alloc.descriptorSetCount = 1;
alloc.pSetLayouts = &chosen.descriptorLayout;
VK_VERIFY(vkAllocateDescriptorSets(m_device, &alloc, &descriptorSet));
const VkDescriptorImageInfo sampled{chosen.sampler, source->view, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL};
VkWriteDescriptorSet write{VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET};
write.dstSet = descriptorSet;
write.dstBinding = 0;
write.descriptorCount = 1;
write.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
write.pImageInfo = &sampled;
vkUpdateDescriptorSets(m_device, 1, &write, 0, nullptr);
VkRenderPassBeginInfo begin{VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO};
begin.renderPass = chosen.renderPass;
begin.framebuffer = framebuffer;
begin.renderArea = {{0, 0}, resource.extent};
vkCmdBeginRenderPass(frame.commandBuffer, &begin, VK_SUBPASS_CONTENTS_INLINE);
vkCmdBindPipeline(frame.commandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, chosen.pipeline);
const VkViewport viewport{0.0f, 0.0f, static_cast<float>(resource.extent.width),
static_cast<float>(resource.extent.height), 0.0f, 1.0f};
const VkRect2D scissor{{0, 0}, resource.extent};
vkCmdSetViewport(frame.commandBuffer, 0, 1, &viewport);
vkCmdSetScissor(frame.commandBuffer, 0, 1, &scissor);
vkCmdBindDescriptorSets(frame.commandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, chosen.pipelineLayout, 0, 1,
&descriptorSet, 0, nullptr);
vkCmdDraw(frame.commandBuffer, 3, 1, 0, 0);
vkCmdEndRenderPass(frame.commandBuffer);
VkImageMemoryBarrier release = acquire;
release.srcAccessMask = VK_ACCESS_SHADER_READ_BIT;
release.dstAccessMask = 0;
release.oldLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
release.newLayout = VK_IMAGE_LAYOUT_GENERAL;
release.srcQueueFamilyIndex = family;
release.dstQueueFamilyIndex = VK_QUEUE_FAMILY_FOREIGN_EXT;
EndActiveRenderPassOn(frame.commandBuffer);
vkCmdPipelineBarrier(frame.commandBuffer, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT,
VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, 0, 0, nullptr, 0, nullptr, 1, &release);
// GENERAL, the layout every wire descriptor samples in, with the pass's writes made visible.
target.layout = resource.layout;
TransitionWireImage(target, VK_IMAGE_LAYOUT_GENERAL);
ResetDynamicStateShadow();
InvalidatePipelineMemo();
if (m_uniformManager) m_uniformManager->OnCommandBufferBoundary();
m_textureManager->StampResourceRecordingUse(resource);
m_textureManager->StampResourceRecordingWrite(resource);
WireRetiredObjects retired{};
retired.framebuffers.push_back(framebuffer);
retired.imageViews = {targetView};
retired.descriptorPools.push_back(descriptorPool);
RetireWireObjects(Move(retired));
// The frame's fence orders the next refresh of a foreign buffer after this read.
m_sharedImageReads.NoteRead(image);
return true;
#else
(void)resource;
return false;
#endif
}
#endif // MOBILEGL_BUILD_DISAGGREGATED
-184
View File
@@ -1,184 +0,0 @@
// MobileGL - MobileGL/MG_Backend/GpuHangWatch.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 "GpuHangWatch.h"
#include <MG_Util/Debug/Log.h>
#include <algorithm>
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <cstdlib>
#include <thread>
#if defined(__ANDROID__)
#include <sys/system_properties.h>
#endif
#if defined(__linux__) || defined(__ANDROID__)
#include <pthread.h>
#endif
namespace MobileGL::MG_Backend::GpuHangWatch {
namespace {
constexpr Uint32 kDefaultPollMs = 250;
std::atomic<Uint32> g_pollOverrideMs{0};
std::atomic<Uint32> g_budgetOverrideMs{0};
std::atomic<Bool> g_budgetOverridden{false};
Uint64 NowMs() {
return static_cast<Uint64>(std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now().time_since_epoch())
.count());
}
Uint32 ReadBudgetMs() {
const char* value = std::getenv("MOBILEGL_GPU_HANG_BUDGET_MS");
#if defined(__ANDROID__)
char property[PROP_VALUE_MAX] = {};
if (value == nullptr && __system_property_get("debug.mobilegl.gpu_hang_budget_ms", property) > 0)
value = property;
#endif
if (value == nullptr || *value == '\0') return kDefaultBudgetMs;
char* end = nullptr;
const unsigned long parsed = std::strtoul(value, &end, 10);
if (end == value) return kDefaultBudgetMs;
return static_cast<Uint32>(std::min<unsigned long>(parsed, 600000ul));
}
struct Entry {
Uint64 Handle = 0;
void* Self = nullptr;
SampleFn Sample = nullptr;
HungFn Hung = nullptr;
Detector Decide{0};
Bool Done = false; // named a hang, or its device is gone: never sampled again
};
// Leaked at exit, with its thread: the watch holds no GPU object of its own, and a backend
// unregisters before it destroys what its sampler reads.
struct Watch {
std::mutex Mutex;
std::condition_variable Wake;
Vector<Entry> Entries;
Uint64 NextHandle = 1;
Bool ThreadStarted = false;
};
Watch& TheWatch() {
static Watch& watch = *new Watch();
return watch;
}
void PollOnce(Watch& watch) {
const Uint64 now = NowMs();
Vector<SubmissionProgress> sample;
for (Entry& entry : watch.Entries) {
if (entry.Done) continue;
sample.clear();
if (!entry.Sample(entry.Self, sample)) {
entry.Done = true;
continue;
}
const Uint64 hung = entry.Decide.Observe(sample, now);
if (hung == 0) continue;
entry.Done = true;
entry.Hung(entry.Self, hung, entry.Decide.RunningMs(hung, now));
}
}
void WatchThreadMain() {
#if defined(__linux__) || defined(__ANDROID__)
pthread_setname_np(pthread_self(), "mgl-gpu-watch");
#endif
Watch& watch = TheWatch();
std::unique_lock<std::mutex> lock(watch.Mutex);
for (;;) {
watch.Wake.wait_for(lock, std::chrono::milliseconds(PollIntervalMs()));
PollOnce(watch);
}
}
} // namespace
Uint32 BudgetMs() {
if (g_budgetOverridden.load(std::memory_order_acquire)) return g_budgetOverrideMs.load(std::memory_order_acquire);
static const Uint32 budget = ReadBudgetMs();
return budget;
}
Uint32 PollIntervalMs() {
const Uint32 overrideMs = g_pollOverrideMs.load(std::memory_order_acquire);
return overrideMs != 0 ? overrideMs : kDefaultPollMs;
}
void SetPollIntervalForTesting(Uint32 ms) { g_pollOverrideMs.store(ms, std::memory_order_release); }
void SetBudgetForTesting(Uint32 ms) {
g_budgetOverrideMs.store(ms, std::memory_order_release);
g_budgetOverridden.store(ms != 0, std::memory_order_release);
}
Uint64 Detector::Observe(const Vector<SubmissionProgress>& sample, Uint64 nowMs) {
Vector<Running> still;
still.reserve(sample.size());
Uint64 named = 0;
for (const SubmissionProgress& progress : sample) {
if (!progress.Started || progress.Finished) continue;
Uint64 since = nowMs;
for (const Running& seen : m_running) {
if (seen.Id == progress.Id) {
since = seen.SinceMs;
break;
}
}
still.push_back({progress.Id, since});
if (named == 0 && m_budgetMs != 0 && nowMs - since >= m_budgetMs) named = progress.Id;
}
m_running.swap(still);
return named;
}
Uint64 Detector::RunningMs(Uint64 id, Uint64 nowMs) const {
for (const Running& seen : m_running)
if (seen.Id == id) return nowMs - seen.SinceMs;
return 0;
}
Uint64 Register(void* self, SampleFn sample, HungFn hung) {
const Uint32 budget = BudgetMs();
if (budget == 0 || sample == nullptr || hung == nullptr) return 0;
Watch& watch = TheWatch();
const std::lock_guard<std::mutex> lock(watch.Mutex);
Entry entry;
entry.Handle = watch.NextHandle++;
entry.Self = self;
entry.Sample = sample;
entry.Hung = hung;
entry.Decide = Detector(budget);
watch.Entries.push_back(entry);
if (!watch.ThreadStarted) {
watch.ThreadStarted = true;
std::thread(WatchThreadMain).detach();
}
return entry.Handle;
}
void Unregister(Uint64 handle) {
if (handle == 0) return;
Watch& watch = TheWatch();
// The poll pass runs under this lock, so taking it waits out any call into the entry.
const std::lock_guard<std::mutex> lock(watch.Mutex);
for (SizeT i = 0; i < watch.Entries.size(); ++i) {
if (watch.Entries[i].Handle != handle) continue;
watch.Entries.erase(watch.Entries.begin() + static_cast<std::ptrdiff_t>(i));
return;
}
}
} // namespace MobileGL::MG_Backend::GpuHangWatch
-94
View File
@@ -1,94 +0,0 @@
// MobileGL - MobileGL/MG_Backend/GpuHangWatch.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
// A SESSION WHOSE GPU WORK NEVER ENDS IS FOUND AND NAMED, SO IT CANNOT HANG THE GPU AGAIN.
//
// A submission whose shader never ends stops the whole GPU, not one context: every process's work -
// the compositor's, other clients', processes outside MobileGL at the highest context priority -
// waits until the kernel resets it. Measured on Adreno 750: ~2 s when nothing of higher priority
// waits (the context is then lost: Vulkan answers VK_ERROR_DEVICE_LOST), ~10 s when something of
// higher priority does (a failed preemption; the context is NOT lost, and its next frame hangs the
// GPU again). Nothing in user space can shorten one such stall; what the server can do is make sure
// the session that caused it never submits again, so a page or program that hangs every frame
// costs the desktop one stall instead of one per frame.
//
// The attribution must be exact - every session's work is pending while the GPU is stuck, and the
// compositor's must never be blamed. A backend that can tell, per in-flight submission, whether the
// GPU has STARTED it and whether it has FINISHED it gives exactly that: the GPU runs one submission
// at a time on a ring, so the one that started and does not finish is the one that hangs, and the
// ones queued behind it have not started. Magma brackets each submission with two events
// (DirectVulkan/Renderer/GpuProgressMarkers.h). Espryt relies on the driver instead: its contexts ask
// for reset notification and glGetGraphicsResetStatus names the guilty one - measured after a ~2 s
// timeout reset; after a ~10 s failed-preemption reset the server's contexts were NOT told (a
// standalone process's context was), so on Espryt that path is not contained yet.
//
// The Detector is the decision, pure and testable; the watch thread samples every registered backend
// on its own clock, because the session that hangs is often not running - its apply thread waits for
// its own fence, or for the backend turn another session holds while it waits for the GPU.
#include <Includes.h>
#include <mutex>
namespace MobileGL::MG_Backend::GpuHangWatch {
// MOBILEGL_GPU_HANG_BUDGET_MS: how long one submission may run once the GPU has started it before
// its session is ended as the one that hangs the GPU. Default 2000 - the kernel resets a hung GPU
// by itself after about that when nothing preempts it, and no desktop frame runs that long. 0 = off.
Uint32 BudgetMs();
constexpr Uint32 kDefaultBudgetMs = 2000;
// One in-flight submission as the GPU reports progress on it.
struct SubmissionProgress {
Uint64 Id = 0; // the backend's own monotonic id for it; never reused
Bool Started = false; // the GPU has begun executing it
Bool Finished = false; // ... and completed it
};
// Which submission, if any, has run past the budget: started, not finished, and seen in that
// state for at least `budgetMs` (from the first sample that saw it running - the watch cannot know
// when between two samples it began, so a hang is named between budget and budget + one interval).
class Detector {
public:
explicit Detector(Uint32 budgetMs) : m_budgetMs(budgetMs) {}
// One sample of every in-flight submission at `nowMs`. Returns the id of the submission that
// ran past the budget, or 0. Submissions missing from the sample are forgotten.
Uint64 Observe(const Vector<SubmissionProgress>& sample, Uint64 nowMs);
// How long the named submission had been seen running when Observe named it.
Uint64 RunningMs(Uint64 id, Uint64 nowMs) const;
private:
struct Running {
Uint64 Id = 0;
Uint64 SinceMs = 0;
};
Uint32 m_budgetMs = 0;
Vector<Running> m_running;
};
// ---- the process-wide watch ---------------------------------------------------------------
//
// A backend registers a sampler and a callback. The watch thread calls the sampler every
// PollIntervalMs() on its own thread, and the callback once, when the Detector names a
// submission; the backend acts on it from its own thread (it may not latch a session from this
// one). Both are called with the watch's lock held: keep them short, and never call Unregister
// from them. Unregister returns only once no call into the registration runs or will run.
using SampleFn = Bool (*)(void* self, Vector<SubmissionProgress>& out); // false: stop watching it
using HungFn = void (*)(void* self, Uint64 submissionId, Uint64 runningMs);
Uint64 Register(void* self, SampleFn sample, HungFn hung);
void Unregister(Uint64 handle);
Uint32 PollIntervalMs();
// Tests: the interval and the budget the next Register uses (0 restores the defaults).
void SetPollIntervalForTesting(Uint32 ms);
void SetBudgetForTesting(Uint32 ms);
} // namespace MobileGL::MG_Backend::GpuHangWatch
+17 -114
View File
@@ -17,14 +17,9 @@
// process's MobileGL client session. Whatever node the caller holds is therefore equally good,
// and none is vendor-specific.
//
// THE LAYOUT IS THE ALLOCATOR'S. Buffers report DRM_FORMAT_MOD_INVALID and a single plane (two for
// the YUV formats, both in the one descriptor); a request that needs a known layout (LINEAR, or a
// modifier list without INVALID) is refused rather than answered with a buffer whose layout is not
// what was asked for.
//
// YUV (NV12, P010) buffers exist when the server's platform allocates them (the shared-image ABI's
// format list says so). They are sampled, never rendered to: a GBM_BO_USE_RENDERING request for one
// is refused.
// THE LAYOUT IS THE ALLOCATOR'S. Buffers report DRM_FORMAT_MOD_INVALID and a single plane; a
// request that needs a known layout (LINEAR, or a modifier list without INVALID) is refused
// rather than answered with a buffer whose layout is not what was asked for.
//
// Buffer operations reach the server through libMobileGL.so's shared-image C ABI
// (MG_Impl/SharedImageApi.h), resolved with dlsym on first use - preferably from the instance the
@@ -45,7 +40,6 @@
#include <dlfcn.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
#define MOBILEGL_GBM_EXPORT extern "C" __attribute__((visibility("default")))
@@ -71,10 +65,6 @@ namespace {
int fd; // owned; every get_fd hands out a duplicate
uint32_t offset;
uint64_t modifier;
// A YUV buffer's plane 1, in the same descriptor.
uint32_t planes;
uint32_t plane1Stride;
uint32_t plane1Offset;
};
// ---- libMobileGL's shared-image ABI -----------------------------------------------------
@@ -84,9 +74,6 @@ namespace {
PFN_mobilegl_shared_image_import import = nullptr;
PFN_mobilegl_shared_image_release release = nullptr;
PFN_mobilegl_server_available serverAvailable = nullptr; // optional (older libraries lack it)
// ABI 2 (YUV); null on an older library.
PFN_mobilegl_shared_image_formats formats = nullptr;
PFN_mobilegl_shared_image_import_planes importPlanes = nullptr;
};
// The library the process already has (by its soname: glvnd loads it by path, which records
@@ -120,12 +107,6 @@ namespace {
std::fprintf(stderr, "mobilegl_gbm: this libMobileGL.so has no shared-image ABI\n");
return;
}
if (version() >= 2) {
api.formats = reinterpret_cast<PFN_mobilegl_shared_image_formats>(
dlsym(lib, "mobilegl_shared_image_formats"));
api.importPlanes = reinterpret_cast<PFN_mobilegl_shared_image_import_planes>(
dlsym(lib, "mobilegl_shared_image_import_planes"));
}
resolved = true;
});
return resolved ? &api : nullptr;
@@ -144,41 +125,11 @@ namespace {
// What a shared image can be. The ARGB/XRGB orders are stored like the ABGR/XBGR ones: the
// layout is the server's (modifier INVALID, no map is offered), so no reader can tell, and
// every GL that touches the image addresses its channels logically.
bool FormatIsYuv(uint32_t format) {
return format == MOBILEGL_SHARED_IMAGE_FOURCC_NV12 || format == MOBILEGL_SHARED_IMAGE_FOURCC_P010;
}
// Whether the server holds YUV images: the library's format list, asked once (it takes the
// process's session, which the first buffer would anyway).
bool YuvFormatAvailable(uint32_t format) {
static std::once_flag once;
static bool nv12 = false, p010 = false;
std::call_once(once, [] {
const SharedImageApi* api = Api();
if (api == nullptr || api->formats == nullptr || api->importPlanes == nullptr) return;
uint32_t formats[16] = {};
const int total = api->formats(formats, 16);
for (int i = 0; i < total && i < 16; ++i) {
nv12 |= formats[i] == MOBILEGL_SHARED_IMAGE_FOURCC_NV12;
p010 |= formats[i] == MOBILEGL_SHARED_IMAGE_FOURCC_P010;
}
});
return format == MOBILEGL_SHARED_IMAGE_FOURCC_NV12 ? nv12 : format == MOBILEGL_SHARED_IMAGE_FOURCC_P010 && p010;
}
bool FormatSupported(uint32_t format) {
if (FormatIsYuv(format)) return YuvFormatAvailable(format);
return format == MOBILEGL_SHARED_IMAGE_FOURCC_ABGR8888 || format == MOBILEGL_SHARED_IMAGE_FOURCC_XBGR8888 ||
format == MOBILEGL_SHARED_IMAGE_FOURCC_ARGB8888 || format == MOBILEGL_SHARED_IMAGE_FOURCC_XRGB8888;
}
uint32_t PlaneCount(uint32_t format) { return FormatIsYuv(format) ? 2 : 1; }
// A YUV buffer is sampled only.
uint32_t RefusedUsage(uint32_t format) {
return kRefusedUsage | (FormatIsYuv(format) ? static_cast<uint32_t>(GBM_BO_USE_RENDERING) : 0u);
}
bool ModifierAcceptable(uint64_t modifier) { return modifier == kModifierInvalid || modifier == kModifierLinear; }
// There is no GEM handle behind a shared image; callers that only use the handle as a key
@@ -191,8 +142,7 @@ namespace {
}
gbm_bo* NewBo(gbm_device* gbm, uint64_t imageId, int fd, uint32_t width, uint32_t height, uint32_t format,
uint32_t stride, uint32_t offset, uint64_t modifier, uint32_t plane1Stride = 0,
uint32_t plane1Offset = 0) {
uint32_t stride, uint32_t offset, uint64_t modifier) {
auto* bo = new (std::nothrow) Bo{};
if (bo == nullptr) {
errno = ENOMEM;
@@ -208,9 +158,6 @@ namespace {
bo->fd = fd;
bo->offset = offset;
bo->modifier = modifier;
bo->planes = PlaneCount(format);
bo->plane1Stride = plane1Stride;
bo->plane1Offset = plane1Offset;
return &bo->base;
}
@@ -221,20 +168,18 @@ namespace {
void DeviceDestroy(gbm_device* gbm) { delete reinterpret_cast<Device*>(gbm); }
int IsFormatSupported(gbm_device*, uint32_t format, uint32_t usage) {
format = Canonical(format);
return FormatSupported(format) && (usage & RefusedUsage(format)) == 0 ? 1 : 0;
return FormatSupported(Canonical(format)) && (usage & kRefusedUsage) == 0 ? 1 : 0;
}
int GetFormatModifierPlaneCount(gbm_device*, uint32_t format, uint64_t modifier) {
format = Canonical(format);
if (!FormatSupported(format) || !ModifierAcceptable(modifier)) return -1;
return static_cast<int>(PlaneCount(format));
if (!FormatSupported(Canonical(format)) || !ModifierAcceptable(modifier)) return -1;
return 1;
}
gbm_bo* BoCreate(gbm_device* gbm, uint32_t width, uint32_t height, uint32_t format, uint32_t usage,
const uint64_t* modifiers, const unsigned int count) {
format = Canonical(format);
if (!FormatSupported(format) || (usage & RefusedUsage(format)) != 0) {
if (!FormatSupported(format) || (usage & kRefusedUsage) != 0) {
errno = EINVAL;
return nullptr;
}
@@ -262,7 +207,7 @@ namespace {
return nullptr;
}
gbm_bo* bo = NewBo(gbm, image.id, image.fd, image.width, image.height, image.fourcc, image.stride,
image.offset, image.modifier, image.plane1_stride, image.plane1_offset);
image.offset, image.modifier);
if (bo == nullptr) {
api->release(image.id);
::close(image.fd);
@@ -270,13 +215,6 @@ namespace {
return bo;
}
// Whether two descriptors name one dma-buf: a YUV buffer's planes must be in one.
bool SameBuffer(int a, int b) {
if (a == b) return true;
struct stat sa {}, sb {};
return ::fstat(a, &sa) == 0 && ::fstat(b, &sb) == 0 && sa.st_dev == sb.st_dev && sa.st_ino == sb.st_ino;
}
gbm_bo* BoImport(gbm_device* gbm, uint32_t type, void* buffer, uint32_t usage) {
(void)usage;
if (buffer == nullptr) {
@@ -285,7 +223,6 @@ namespace {
}
int fd = -1;
uint32_t width = 0, height = 0, format = 0, stride = 0, offset = 0;
uint32_t plane1Stride = 0, plane1Offset = 0;
uint64_t modifier = kModifierInvalid;
switch (type) {
case GBM_BO_IMPORT_FD: {
@@ -295,19 +232,11 @@ namespace {
height = data->height;
format = data->format;
stride = data->stride;
// One fd and one stride cannot say where a second plane is.
if (FormatIsYuv(Canonical(format))) {
errno = EINVAL;
return nullptr;
}
break;
}
case GBM_BO_IMPORT_FD_MODIFIER: {
const auto* data = static_cast<const gbm_import_fd_modifier_data*>(buffer);
const bool yuv = FormatIsYuv(Canonical(data->format));
const unsigned int planes = yuv ? 2u : 1u;
if (data->num_fds < 1 || data->num_fds > planes || !ModifierAcceptable(data->modifier) ||
(data->num_fds == 2 && !SameBuffer(data->fds[0], data->fds[1]))) {
if (data->num_fds != 1 || !ModifierAcceptable(data->modifier)) {
errno = EINVAL;
return nullptr;
}
@@ -317,10 +246,6 @@ namespace {
format = data->format;
stride = static_cast<uint32_t>(data->strides[0]);
offset = static_cast<uint32_t>(data->offsets[0]);
if (yuv) {
plane1Stride = static_cast<uint32_t>(data->strides[1]);
plane1Offset = static_cast<uint32_t>(data->offsets[1]);
}
modifier = data->modifier;
break;
}
@@ -344,26 +269,13 @@ namespace {
const int owned = ::fcntl(fd, F_DUPFD_CLOEXEC, 0);
if (owned < 0) return nullptr;
uint64_t id = 0;
int rc = 0;
if (FormatIsYuv(format)) {
mobilegl_shared_image_planes planes{};
planes.struct_size = sizeof(planes);
planes.plane_count = 2;
planes.offset[0] = offset;
planes.offset[1] = plane1Offset;
planes.pitch[0] = stride;
planes.pitch[1] = plane1Stride;
planes.modifier = modifier;
rc = api->importPlanes(owned, width, height, format, &planes, &id);
} else {
rc = api->import(owned, width, height, format, &id);
}
const int rc = api->import(owned, width, height, format, &id);
if (rc != 0) {
::close(owned);
errno = -rc;
return nullptr;
}
gbm_bo* bo = NewBo(gbm, id, owned, width, height, format, stride, offset, modifier, plane1Stride, plane1Offset);
gbm_bo* bo = NewBo(gbm, id, owned, width, height, format, stride, offset, modifier);
if (bo == nullptr) {
api->release(id);
::close(owned);
@@ -387,14 +299,11 @@ namespace {
int BoGetFd(gbm_bo* bo) { return ::fcntl(AsBo(bo)->fd, F_DUPFD_CLOEXEC, 0); }
int BoGetPlanes(gbm_bo* bo) { return static_cast<int>(AsBo(bo)->planes); }
int BoGetPlanes(gbm_bo*) { return 1; }
bool ValidPlane(gbm_bo* bo, int plane) { return plane >= 0 && static_cast<uint32_t>(plane) < AsBo(bo)->planes; }
// Every plane is in the one buffer, so every plane has its handle.
gbm_bo_handle BoGetHandle(gbm_bo* bo, int plane) {
gbm_bo_handle handle{};
if (!ValidPlane(bo, plane)) {
if (plane != 0) {
errno = EINVAL;
handle.s32 = -1;
return handle;
@@ -403,22 +312,16 @@ namespace {
}
int BoGetPlaneFd(gbm_bo* bo, int plane) {
if (!ValidPlane(bo, plane)) {
if (plane != 0) {
errno = EINVAL;
return -1;
}
return BoGetFd(bo);
}
uint32_t BoGetStride(gbm_bo* bo, int plane) {
if (plane == 0) return bo->v0.stride;
return plane == 1 && AsBo(bo)->planes == 2 ? AsBo(bo)->plane1Stride : 0;
}
uint32_t BoGetStride(gbm_bo* bo, int plane) { return plane == 0 ? bo->v0.stride : 0; }
uint32_t BoGetOffset(gbm_bo* bo, int plane) {
if (plane == 0) return AsBo(bo)->offset;
return plane == 1 && AsBo(bo)->planes == 2 ? AsBo(bo)->plane1Offset : 0;
}
uint32_t BoGetOffset(gbm_bo* bo, int plane) { return plane == 0 ? AsBo(bo)->offset : 0; }
uint64_t BoGetModifier(gbm_bo* bo) { return AsBo(bo)->modifier; }
+37 -636
View File
@@ -8,7 +8,6 @@
#include "EGLImpl.h"
#include "EGLPlatformExtensions.h"
#include "SharedImageFlushPolicy.h"
#include "WaylandWindow.h"
#include "../GetProcAddress.h"
#include <Init.h>
@@ -25,35 +24,18 @@
// (PipeFill.cpp's emitters) and because the frame channel belongs to the server role - this
// file must not name ServerLoop's forwarders directly.
#include <MG_Remote/Client/WireTables.h>
// The recovery after a device loss (RecoverLostSession below): the session, the remote backend's
// surface book, and the GL framebuffer 0 that is rebuilt on the fresh session.
#include <MG_Remote/Client/BackendObject_Remote.h>
#include <MG_Remote/Client/ClientSession.h>
#include <MG_Impl/GLImpl/Framebuffer/GL_Framebuffer.h>
#include <MG_State/GLState/Core.h>
#include <optional>
#endif
#include <atomic>
#include <cstdlib>
#include <cstring>
#include <mutex>
#include <sstream>
#if !defined(_WIN32)
#include <sys/stat.h>
#include <unistd.h>
#endif
#if defined(__linux__) && !defined(__ANDROID__)
#include <dlfcn.h>
#endif
#include <algorithm>
#include <type_traits>
#include <unordered_map>
#include <unordered_set>
namespace MobileGL::MG_Impl::EGLImpl {
namespace {
// SetDispatcherCurrentApiHook.
std::atomic<EGLenum (*)()> g_dispatcherCurrentApi{nullptr};
using EGLStateContext = MG_State::EGLState::EGLContext;
EGLStateContext* GetState() {
@@ -92,8 +74,6 @@ 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.
//
@@ -165,82 +145,6 @@ 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;
@@ -312,43 +216,6 @@ namespace MobileGL::MG_Impl::EGLImpl {
return *surfaces;
}
// EGL_KHR_surfaceless_context. The EGL state records a surfaceless binding as exactly that
// (eglGetCurrentSurface answers EGL_NO_SURFACE), but every backend renders into the surface
// it was bound to, and a session's capabilities are published on its first bind to one. So
// the backend is bound to a 1x1 pbuffer of the display's own instead: one per display, made
// on the first surfaceless bind, never handed to the application, and gone with the display
// (eglTerminate). Guarded by EGLOperationMutex.
std::unordered_map<EGLDisplay, EGLSurface>& SurfacelessStandIns() {
static auto* standIns = new std::unordered_map<EGLDisplay, EGLSurface>();
return *standIns;
}
// eglCreatePbufferSurface for the stand-in, except that a split client creates it on the
// server as a stand-in, which takes no surface mode there (a server-owned window may follow).
EGLSurface CreateSurfacelessStandInPbuffer(EGLStateContext* state, EGLDisplay dpy, EGLConfig config,
const EGLint* attribs);
// The display's stand-in, made now if it has none (or the one it had did not survive).
// EGL_NO_SURFACE when the backend could not make a pbuffer; the EGL error is then set.
EGLSurface SurfacelessStandIn(EGLStateContext* state, EGLDisplay dpy) {
auto& standIns = SurfacelessStandIns();
if (const auto it = standIns.find(dpy); it != standIns.end()) {
if (state->ValidateSurfaceOnDisplay(dpy, it->second)) return it->second;
standIns.erase(it);
}
// Any of the display's configs will do: a stand-in is never read back or presented.
EGLConfig config = nullptr;
EGLint count = 0;
if (!state->GetConfigs(dpy, &config, 1, &count) || count < 1 || config == nullptr) {
state->SetError(EGL_BAD_ALLOC);
return EGL_NO_SURFACE;
}
const EGLint attribs[] = {EGL_WIDTH, 1, EGL_HEIGHT, 1, EGL_NONE};
const EGLSurface standIn = CreateSurfacelessStandInPbuffer(state, dpy, config, attribs);
if (standIn != EGL_NO_SURFACE) standIns[dpy] = standIn;
return standIn;
}
#if MOBILEGL_WAYLAND_WINDOWS
// Every Wayland window surface's presentation, by surface. Guarded by EGLOperationMutex,
// which every entry point that reaches it holds.
@@ -447,130 +314,6 @@ namespace MobileGL::MG_Impl::EGLImpl {
}
}
#endif
#if MOBILEGL_BUILD_DISAGGREGATED
using MG_Remote::Client::ClientSession;
// IS `context` LOST. It was built against a server session that has since ended (a device
// loss, recovered), or it lives on the session that is lost right now: either way its
// objects are on no server this process can reach, and EGL's answer for it is
// EGL_CONTEXT_LOST until the application destroys it.
Bool ContextIsLost(EGLStateContext* state, EGLContext context) {
if (!StreamGateActive() || context == EGL_NO_CONTEXT) return false;
const SharedPtr<MG_State::GLState::GLContext> glState = state->GetContextGLState(context);
if (!glState) return false;
return glState->IsFromEndedWireSession() || ClientSession::SessionLatchedLost();
}
// THE RECOVERY'S EGL HALF. The caller holds EGLOperationMutex - which every GL entry point
// takes too (GLStreamScope), so no other thread is in the middle of a GL call - and is an
// entry point an application reaches when it rebuilds after a loss: eglCreateContext,
// eglCreate*Surface, eglInitialize. A no-op unless the session is latched lost.
//
// 1. ClientSession ends the lost session and dials a fresh one; its FinishStartup forgets
// every client cache of the old one and moves the wire epoch, which is what makes every
// context built before lost (their objects die later without a word on the new wire).
// 2. The process default context and GL framebuffer 0 are rebuilt on the fresh session:
// every context created from now on starts with framebuffer 0 bound, and the old one's
// attachments are textures the fresh server never heard of.
// 3. The remote backend initializes the display again on the new server and forgets which
// surfaces and shared images the old one had; each surface is re-created there when it
// is next made current (EGL keeps surfaces across a power-management loss).
// 4. Wayland presentations drop the lost session's shared images and allocate new ones.
Bool RecoverLostSession() {
if (!StreamGateActive() || !ClientSession::SessionLatchedLost()) return true;
ClientSession* session = ClientSession::Active();
{
const ClientSession::ScopedWireMute mute;
if (session->RecoverAfterDeviceLoss() != MOBILEGL_OK) return false;
}
// Nothing is bound on the fresh session: the next thread that writes binds its own.
g_boundContextToken = 0;
g_boundShareGroupToken = 0;
const ClientSession::ScopedCurrentSessionWork work;
SharedPtr<MG_State::GLState::GLContext> lostDefault = MG_State::ReplaceProcessDefaultGLContext();
UniquePtr<MG_Impl::GLImpl::FramebufferImpl::DefaultFramebufferInfo> lostFramebuffer =
Move(MG_Impl::GLImpl::FramebufferImpl::pDefaultFramebufferInfo);
{
// Built into the new default context, whatever this thread has current (a lost
// context stays this thread's GL state until the application releases it).
SharedPtr<MG_State::GLState::GLContext> caller = MG_State::pGLContext;
MG_State::pGLContext = MG_State::ProcessDefaultGLContext();
MG_Impl::BuildDefaultFramebuffer();
MG_State::pGLContext = Move(caller);
}
{
const ClientSession::ScopedWireMute mute;
lostFramebuffer.reset();
lostDefault.reset();
}
if (auto* remote = dynamic_cast<MG_Remote::Client::BackendObject_Remote*>(MG_Backend::pActiveBackendObject.get()))
remote->OnSessionReplaced();
#if MOBILEGL_WAYLAND_WINDOWS
for (auto& [surface, presentation] : WaylandSurfaces()) presentation->OnSessionReplaced();
#endif
return true;
}
// THE SHARE GROUPS THAT REPLACE LOST ONES, by the lost group's token. An application that
// keeps one long-lived context to share with (Qt's global share context) recreates its
// other contexts after a loss still naming that context, which is lost and stays so. Those
// contexts are put in ONE new share group instead of each in a group of its own: the first
// starts it, the later ones share with a live member of it. Without this, every window of
// such an application lands in a separate share group after the loss, a shape the
// application never asked for. Guarded by EGLOperationMutex.
std::unordered_map<Uint64, Vector<EGLContext>>& ReplacementShareContexts() {
static auto* replacements = new std::unordered_map<Uint64, Vector<EGLContext>>();
return *replacements;
}
// The context a new context should share with in place of the lost `shareCtx`: a live
// member of the group that replaces the lost one, or EGL_NO_CONTEXT to start that group.
EGLContext ReplacementShareContext(EGLStateContext* state, EGLDisplay dpy, Uint64 lostGroup) {
Vector<EGLContext>& members = ReplacementShareContexts()[lostGroup];
members.erase(std::remove_if(members.begin(), members.end(),
[&](EGLContext member) {
return !state->ValidateContextOnDisplay(dpy, member) ||
ContextIsLost(state, member);
}),
members.end());
return members.empty() ? EGL_NO_CONTEXT : members.front();
}
void ForgetReplacementShareContext(EGLContext context) {
for (auto& [group, members] : ReplacementShareContexts())
members.erase(std::remove(members.begin(), members.end(), context), members.end());
}
// The surface entry points' guard: a surface created after a loss is created on a fresh
// session. EGL_BAD_ALLOC when no session could be brought up.
Bool RecoverBeforeCreatingSurface(EGLStateContext* state) {
const std::lock_guard<std::recursive_mutex> operationLock(EGLOperationMutex());
if (RecoverLostSession()) return true;
state->SetError(EGL_BAD_ALLOC);
return false;
}
#endif
EGLSurface CreateSurfacelessStandInPbuffer(EGLStateContext* state, EGLDisplay dpy, EGLConfig config,
const EGLint* attribs) {
#if MOBILEGL_BUILD_DISAGGREGATED
auto* remote = dynamic_cast<MG_Remote::Client::BackendObject_Remote*>(GetBackendObject(state));
if (remote == nullptr) return CreatePbufferSurface(dpy, config, attribs);
if (!RecoverBeforeCreatingSurface(state)) return EGL_NO_SURFACE;
const EGLSurface surface = state->CreatePbufferSurface(dpy, config, attribs);
if (surface == EGL_NO_SURFACE) return EGL_NO_SURFACE;
if (!remote->CreateEGLSurfacelessStandIn(surface, GetAttribValue(attribs, EGL_WIDTH, 1),
GetAttribValue(attribs, EGL_HEIGHT, 1))) {
state->DestroySurface(dpy, surface);
state->SetError(EGL_BAD_ALLOC);
return EGL_NO_SURFACE;
}
return surface;
#else
return CreatePbufferSurface(dpy, config, attribs);
#endif
}
} // namespace
EGLSurface CreateWindowSurface(EGLDisplay dpy, EGLConfig config, NativeWindowType window,
@@ -579,9 +322,6 @@ namespace MobileGL::MG_Impl::EGLImpl {
if (!state) {
return EGL_NO_SURFACE;
}
#if MOBILEGL_BUILD_DISAGGREGATED
if (!RecoverBeforeCreatingSurface(state)) return EGL_NO_SURFACE;
#endif
#if MOBILEGL_WAYLAND_WINDOWS
if (RefuseGbmWindow(state, dpy)) return EGL_NO_SURFACE;
{
@@ -694,20 +434,6 @@ namespace MobileGL::MG_Impl::EGLImpl {
state->SetError(EGL_BAD_SURFACE);
return EGL_FALSE;
}
#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;
}
#endif
auto* backendObject = GetBackendObject(state);
if (!backendObject) {
@@ -731,28 +457,9 @@ 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()) {
#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;
}
if (auto it = WaylandSurfaces().find(draw); it != WaylandSurfaces().end() && !it->second->Present(damage)) {
state->SetError(EGL_BAD_SURFACE);
return EGL_FALSE;
}
#endif
const Bool swapped = damage.IsFull() ? backendObject->SwapEGLBuffers(dpy, draw)
@@ -783,56 +490,10 @@ 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
// building it already emits the creates of its default objects. Sharing with a lost
// context would share objects no reachable server holds.
const std::lock_guard<std::recursive_mutex> operationLock(EGLOperationMutex());
// The lost share group this context replaces (ReplacementShareContexts), 0 for none.
Uint64 replacedGroup = 0;
if (StreamGateActive()) {
if (!RecoverLostSession()) {
state->SetError(EGL_BAD_ALLOC);
return EGL_NO_CONTEXT;
}
if (shareCtx != EGL_NO_CONTEXT && ContextIsLost(state, shareCtx)) {
// Its objects are on no server, so the context does not share them: it joins the
// group that replaces the lost one (the other contexts recreated in its place).
if (!state->ValidateContextOnDisplay(dpy, shareCtx)) {
state->SetError(EGL_BAD_CONTEXT);
return EGL_NO_CONTEXT;
}
replacedGroup = state->GetContextShareGroupToken(shareCtx);
const EGLContext lostShare = shareCtx;
shareCtx = ReplacementShareContext(state, dpy, replacedGroup);
MGLOG_I_ONCE("eglCreateContext: the share context %p was lost with its session (device loss); "
"contexts that name it share with each other in a new share group instead",
lostShare);
}
}
// 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, splitClient);
const EGLContext context = state->CreateContext(dpy, config, shareCtx, attrib_list);
if (context == EGL_NO_CONTEXT) {
return EGL_NO_CONTEXT;
}
#if MOBILEGL_BUILD_DISAGGREGATED
if (replacedGroup != 0) ReplacementShareContexts()[replacedGroup].push_back(context);
#endif
#if MOBILEGL_BUILD_DISAGGREGATED
// P14 S1 (docs/Disaggregated/design/11-state-ownership.md). THE TOKEN CROSSES BEFORE
// eglCreateContext RETURNS. EGLState minted it, together with the share group it was
@@ -848,49 +509,13 @@ namespace MobileGL::MG_Impl::EGLImpl {
// pre-Start bring-up, the server role) keeps it: there is no server to refuse.
if (MG_Config::Transport != MG_Config::TransportMode::Monolith &&
!MG_Remote::Client::RunsAsTheServerRole()) {
auto emitted = MG_Remote::Client::SendCreateContextFrame(
const auto emitted = MG_Remote::Client::SendCreateContextFrame(
state->GetContextClientToken(context), state->GetContextShareGroupToken(context), 0);
// THE LOSS CAN BE FOUND OUT HERE: a session whose server is gone, which nothing had
// noticed yet, refuses the create by hanging up on it. That is the loss, not a refusal:
// the half-built context goes (its objects silently - they were never on any server),
// a fresh session comes up, and the context is built again on it, once.
if (emitted == MG_Remote::Client::ContextFrameEmit::Refused && ClientSession::SessionLatchedLost()) {
{
const ClientSession::ScopedWireMute mute;
state->DestroyContext(dpy, context);
}
context = EGL_NO_CONTEXT;
if (RecoverLostSession()) {
// The context it was to share with went with the session, too.
if (shareCtx != EGL_NO_CONTEXT && ContextIsLost(state, shareCtx)) {
replacedGroup = state->GetContextShareGroupToken(shareCtx);
shareCtx = ReplacementShareContext(state, dpy, replacedGroup);
}
context = state->CreateContext(dpy, config, shareCtx, attrib_list, splitClient);
}
if (context == EGL_NO_CONTEXT) {
state->SetError(EGL_BAD_ALLOC);
return EGL_NO_CONTEXT;
}
if (replacedGroup != 0) ReplacementShareContexts()[replacedGroup].push_back(context);
emitted = MG_Remote::Client::SendCreateContextFrame(state->GetContextClientToken(context),
state->GetContextShareGroupToken(context), 0);
}
if (emitted == MG_Remote::Client::ContextFrameEmit::Refused) {
state->DestroyContext(dpy, context);
state->SetError(EGL_BAD_ACCESS);
return EGL_NO_CONTEXT;
}
// 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;
@@ -901,12 +526,6 @@ namespace MobileGL::MG_Impl::EGLImpl {
if (!state) {
return EGL_FALSE;
}
#if MOBILEGL_BUILD_DISAGGREGATED
// An application that re-initializes a display after a loss (without the eglTerminate that
// would have torn the library down) gets a fresh session here, as eglCreateContext would.
const std::lock_guard<std::recursive_mutex> operationLock(EGLOperationMutex());
(void)RecoverLostSession();
#endif
if (!state->InitializeDisplay(dpy, major, minor)) {
return EGL_FALSE;
}
@@ -950,13 +569,6 @@ 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);
@@ -967,28 +579,11 @@ 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();
MGLOG_D("eglMakeCurrent begin thread=%s dpy=%p draw=%p read=%p ctx=%p oldDpy=%p oldDraw=%p oldRead=%p oldCtx=%p",
threadId.c_str(), dpy, draw, read, ctx, oldDisplay, oldDraw, oldRead, oldContext);
#if MOBILEGL_BUILD_DISAGGREGATED
// EGL 1.5 3.7.3 / 3.2: after a power-management event - a lost device, here - making a
// context created before it current fails with EGL_CONTEXT_LOST. The application destroys
// it and creates another; a release, and every context created since, go on as usual.
if (ctx != EGL_NO_CONTEXT && ContextIsLost(state, ctx)) {
// Once per process: an application that keeps binding the context it lost (instead of
// destroying it and creating another) never reaches the recovery.
MGLOG_I_ONCE("eglMakeCurrent: context %p was lost with its session (device loss): EGL_CONTEXT_LOST "
"until the application destroys it; a context created after the loss gets a fresh session",
ctx);
state->SetError(EGL_CONTEXT_LOST);
return EGL_FALSE;
}
#endif
#if MOBILEGL_WAYLAND_WINDOWS
if (draw != EGL_NO_SURFACE) ApplyWaylandResize(state, dpy, draw);
@@ -1013,11 +608,7 @@ namespace MobileGL::MG_Impl::EGLImpl {
}
MGLOG_D("eglMakeCurrent release succeeded thread=%s", threadId.c_str());
#if MOBILEGL_BUILD_DISAGGREGATED
{
std::optional<ClientSession::ScopedWireMute> silence;
if (oldContextLost) silence.emplace();
EmitContextBinding(state, EGL_NO_CONTEXT, oldContextToken);
}
EmitContextBinding(state, EGL_NO_CONTEXT, oldContextToken);
#endif
return EGL_TRUE;
}
@@ -1028,22 +619,7 @@ namespace MobileGL::MG_Impl::EGLImpl {
state->MakeCurrent(oldDisplay, oldDraw, oldRead, oldContext);
return EGL_FALSE;
}
// A surfaceless binding (EGL_KHR_surfaceless_context; EGLState took it above and records
// EGL_NO_SURFACE): the backend gets the display's stand-in pbuffer to render into.
EGLSurface backendDraw = draw;
EGLSurface backendRead = read;
if (draw == EGL_NO_SURFACE && read == EGL_NO_SURFACE) {
backendDraw = backendRead = SurfacelessStandIn(state, dpy);
if (backendDraw == EGL_NO_SURFACE) {
const EGLint error = state->ConsumeError();
MGLOG_E_ONCE("eglMakeCurrent: no stand-in pbuffer for a surfaceless binding thread=%s (error=0x%04x)",
threadId.c_str(), error);
state->MakeCurrent(oldDisplay, oldDraw, oldRead, oldContext);
state->SetError(error != EGL_SUCCESS ? error : EGL_BAD_ALLOC);
return EGL_FALSE;
}
}
if (!backendObject->MakeEGLCurrent(dpy, backendDraw, backendRead, ctx)) {
if (!backendObject->MakeEGLCurrent(dpy, draw, read, ctx)) {
MGLOG_E_ONCE("eglMakeCurrent backend attach failed thread=%s dpy=%p draw=%p read=%p ctx=%p", threadId.c_str(),
dpy, draw, read, ctx);
state->SetError(EGL_BAD_ACCESS);
@@ -1064,35 +640,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 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 (a
// context still current on some thread, EGL_BAD_ACCESS) never reaches the server - the
// two ends stay in step without the server having to guess why a token vanished.
const Uint64 contextToken = state->GetContextClientToken(ctx);
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.
const Bool lost = ContextIsLost(state, 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;
}
ForgetReplacementShareContext(ctx);
// 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
#endif
if (!state->DestroyContext(dpy, ctx)) {
return EGL_FALSE;
}
#if MOBILEGL_BUILD_DISAGGREGATED
if (contextToken != 0 && MG_Config::Transport != MG_Config::TransportMode::Monolith &&
!MG_Remote::Client::RunsAsTheServerRole()) {
const 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));
}
}
#endif
return EGL_TRUE;
}
@@ -1124,12 +699,6 @@ namespace MobileGL::MG_Impl::EGLImpl {
if (!state->TerminateDisplay(dpy)) {
return EGL_FALSE;
}
{
// The display's surfaces went with it, its surfaceless stand-in among them; the backend
// side goes with ReleaseEGLResources below.
const std::lock_guard<std::recursive_mutex> operationLock(EGLOperationMutex());
SurfacelessStandIns().erase(dpy);
}
if (auto* backendObject = MG_Backend::pActiveBackendObject.get()) {
// The display's dma-buf EGLImages went with it; so do their shared-image references.
for (const Uint64 sharedImageId : state->TakeOrphanedSharedImages()) {
@@ -1156,18 +725,11 @@ 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;
}
@@ -1369,9 +931,6 @@ namespace MobileGL::MG_Impl::EGLImpl {
if (!state) {
return EGL_NO_SURFACE;
}
#if MOBILEGL_BUILD_DISAGGREGATED
if (!RecoverBeforeCreatingSurface(state)) return EGL_NO_SURFACE;
#endif
const EGLint width = GetAttribValue(attrib_list, EGL_WIDTH, 1);
const EGLint height = GetAttribValue(attrib_list, EGL_HEIGHT, 1);
EGLSurface surface = state->CreatePbufferSurface(dpy, config, attrib_list);
@@ -1533,49 +1092,9 @@ 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) {
@@ -1600,8 +1119,6 @@ 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
@@ -1612,38 +1129,6 @@ namespace MobileGL::MG_Impl::EGLImpl {
#endif
}
// Whether the server can hold YUV images (its platform allocates the formats): asked once, by
// allocating and dropping a small NV12 image, and only when a YUV question first comes up.
Bool SharedImageYuvAvailable() {
if (!SharedImagesAvailable()) return false;
static std::atomic<Int> answer{-1};
const Int known = answer.load(std::memory_order_acquire);
if (known >= 0) return known != 0;
auto* backendObject = MG_Backend::pActiveBackendObject.get();
if (backendObject == nullptr) return false;
MG_Backend::SharedImageExport probe{};
const Bool allocated = backendObject->AllocateSharedImage(
16, 16, MG_State::EGLState::EGLContext::kDrmFourccNv12, &probe);
#if !defined(_WIN32)
if (probe.Fd >= 0) ::close(probe.Fd);
#endif
if (allocated && probe.Id != 0) (void)backendObject->ReleaseSharedImage(probe.Id);
answer.store(allocated ? 1 : 0, std::memory_order_release);
MGLOG_I("Shared images: the server %s YUV (NV12) images", allocated ? "holds" : "has no");
return allocated;
}
// Whether two descriptors name one dma-buf (a YUV import's planes must be in one buffer).
Bool SameDmaBuf(int a, int b) {
if (a == b) return true;
#if defined(_WIN32)
return false;
#else
struct stat sa {}, sb {};
return ::fstat(a, &sa) == 0 && ::fstat(b, &sb) == 0 && sa.st_dev == sb.st_dev && sa.st_ino == sb.st_ino;
#endif
}
Bool LookupSharedImage(EGLImage image, Uint64* id, EGLint* width, EGLint* height) {
auto* state = GetState();
MG_State::EGLState::EGLContext::SharedImageInfo info;
@@ -1654,38 +1139,6 @@ 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();
@@ -1709,57 +1162,18 @@ namespace MobileGL::MG_Impl::EGLImpl {
}
auto* backendObject = GetBackendObject(state);
Uint64 sharedImageId = 0;
Bool imported = false;
if (MG_State::EGLState::EGLContext::IsDmaBufFourccYuv(request.Fourcc)) {
// YUV: both planes in one buffer (what video decoders and this server's allocator hand
// out), sampled through GL_OES_EGL_image_external. Planes in two buffers are refused.
if (!SharedImageYuvAvailable() || !SameDmaBuf(request.Fd, request.Plane1Fd)) {
MGLOG_I_ONCE("eglCreateImage: a %dx%d YUV dma-buf cannot be imported (%s); refused (EGL_BAD_MATCH)",
request.Width, request.Height,
SharedImageYuvAvailable() ? "its planes are in two buffers"
: "the server has no YUV images");
state->SetError(EGL_BAD_MATCH);
return EGL_NO_IMAGE;
}
MG_Backend::SharedImageImportLayout layout;
layout.PlaneCount = 2;
layout.Offset[0] = static_cast<Uint32>(request.Offset);
layout.Offset[1] = static_cast<Uint32>(request.Plane1Offset);
layout.Pitch[0] = static_cast<Uint32>(request.Pitch);
layout.Pitch[1] = static_cast<Uint32>(request.Plane1Pitch);
layout.ColorSpace = request.ColorSpace;
layout.Range = request.Range;
layout.SitingX = request.SitingX;
layout.SitingY = request.SitingY;
layout.HasModifier = request.HasModifier;
layout.Modifier = request.Modifier;
imported = backendObject != nullptr &&
backendObject->ImportSharedImagePlanes(request.Fd, static_cast<Uint32>(request.Width),
static_cast<Uint32>(request.Height), request.Fourcc,
layout, &sharedImageId);
} else {
imported = backendObject != nullptr &&
backendObject->ImportSharedImage(request.Fd, static_cast<Uint32>(request.Width),
static_cast<Uint32>(request.Height), request.Fourcc,
&sharedImageId);
}
if (!imported || sharedImageId == 0) {
if (!backendObject ||
!backendObject->ImportSharedImage(request.Fd, static_cast<Uint32>(request.Width),
static_cast<Uint32>(request.Height), request.Fourcc, &sharedImageId) ||
sharedImageId == 0) {
MGLOG_I_ONCE("eglCreateImage: a %dx%d dma-buf is not one of the server's shared images; refused "
"(EGL_BAD_MATCH)",
request.Width, request.Height);
state->SetError(EGL_BAD_MATCH);
return EGL_NO_IMAGE;
}
#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});
const EGLImage image = state->CreateSharedImage(
dpy, {.Id = sharedImageId, .Width = request.Width, .Height = request.Height, .Fourcc = request.Fourcc});
if (image == EGL_NO_IMAGE) (void)backendObject->ReleaseSharedImage(sharedImageId);
return image;
}
@@ -1769,20 +1183,10 @@ 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) {
@@ -1798,7 +1202,7 @@ namespace MobileGL::MG_Impl::EGLImpl {
if (!state) {
return EGL_FALSE;
}
return state->QueryDmaBufFormats(dpy, SharedImagesAvailable(), SharedImageYuvAvailable(), max_formats, formats, num_formats)
return state->QueryDmaBufFormats(dpy, SharedImagesAvailable(), max_formats, formats, num_formats)
? EGL_TRUE
: EGL_FALSE;
}
@@ -1810,7 +1214,7 @@ namespace MobileGL::MG_Impl::EGLImpl {
if (!state) {
return EGL_FALSE;
}
return state->QueryDmaBufModifiers(dpy, SharedImagesAvailable(), SharedImageYuvAvailable(), format, max_modifiers,
return state->QueryDmaBufModifiers(dpy, SharedImagesAvailable(), format, max_modifiers,
reinterpret_cast<Uint64*>(modifiers), external_only, num_modifiers)
? EGL_TRUE
: EGL_FALSE;
@@ -1862,9 +1266,6 @@ namespace MobileGL::MG_Impl::EGLImpl {
if (!state) {
return EGL_NO_SURFACE;
}
#if MOBILEGL_BUILD_DISAGGREGATED
if (!RecoverBeforeCreatingSurface(state)) return EGL_NO_SURFACE;
#endif
#if MOBILEGL_WAYLAND_WINDOWS
if (RefuseGbmWindow(state, dpy)) return EGL_NO_SURFACE;
{
-16
View File
@@ -56,8 +56,6 @@ 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);
@@ -68,22 +66,8 @@ 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();
// Whether the server also holds YUV (NV12/P010) images: decides the YUV dma-buf formats and
// GL_OES_EGL_image_external. One round trip the first time it is asked, cached after.
Bool SharedImageYuvAvailable();
// 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,30 +18,19 @@ 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_EXT_create_context_robustness EGL_KHR_platform_base "
"EGL_KHR_create_context EGL_EXT_platform_base EGL_KHR_platform_base "
"EGL_MESA_platform_surfaceless" MOBILEGL_PLATFORM_WAYLAND_EXTENSIONS;
// The display list again, with the dma-buf import a backend with shared images has (a split
// client: the server allocates the images and names the descriptors that come back). A
// monolith has no allocator to recognise a dma-buf with, so it never advertises these. The
// same server answers the buffer age of its surfaces and takes swap damage to its presents.
inline constexpr const char* kDisplayExtensionStringWithSharedImages =
"EGL_KHR_create_context EGL_KHR_surfaceless_context EGL_KHR_no_config_context EGL_EXT_platform_base "
"EGL_EXT_create_context_robustness EGL_KHR_platform_base "
"EGL_KHR_create_context EGL_EXT_platform_base EGL_KHR_platform_base "
"EGL_MESA_platform_surfaceless" MOBILEGL_PLATFORM_WAYLAND_EXTENSIONS
" EGL_KHR_image_base EGL_EXT_image_dma_buf_import EGL_EXT_image_dma_buf_import_modifiers"
" EGL_EXT_buffer_age EGL_KHR_partial_update EGL_KHR_swap_buffers_with_damage"
" EGL_EXT_swap_buffers_with_damage"
// 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";
" EGL_EXT_swap_buffers_with_damage";
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,10 +287,8 @@ 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);
@@ -302,65 +300,6 @@ 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;
@@ -445,8 +384,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,12 +44,6 @@ 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,
@@ -270,12 +264,6 @@ 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)},
@@ -364,12 +352,6 @@ 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;
-63
View File
@@ -1,63 +0,0 @@
// MobileGL - MobileGL/MG_Impl/EGLImpl/FrameThrottle.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
// HOW A WAYLAND WINDOW'S SWAPS ARE PACED. A Wayland compositor tells a client when to draw next with
// wl_surface.frame: the callback is done when the compositor has used the frame - painted it, or
// decided it would not be seen - and a compositor that shows nothing (its output is off, the window
// is hidden) sends none at all. Every commit asks for one (one outstanding at a time), and the swap
// after it may wait:
//
// - swap interval above 0: until the callback is done, however long that takes. An application
// drawing as fast as eglSwapBuffers lets it then draws at the compositor's pace, and stops while
// the compositor shows nothing (what every EGL on Wayland does).
// - swap interval 0: not while the compositor keeps answering - an unpaced application stays
// unpaced. But a callback left unanswered for kStarvedAfterMs means nothing of the window is
// being shown; the swap then waits up to kStarvedWaitMs for it, so an application that draws on
// its own clock (a browser on an animated page) drops to about one frame a second instead of
// burning CPU and GPU on frames nobody sees, and is back at full rate with the first answer.
//
// The bookkeeping, apart from libwayland (WaylandWindow.cpp issues the requests and dispatches).
#include <Includes.h>
namespace MobileGL::MG_Impl::EGLImpl::Wayland {
class FrameThrottle {
public:
static constexpr Int64 kStarvedAfterMs = 200;
static constexpr Int64 kStarvedWaitMs = 1000;
static constexpr Int64 kForever = -1;
// Before a commit: whether it carries a frame request (none is outstanding).
Bool WantsFrameRequest() const { return !m_outstanding; }
// A frame request went with the commit made at `nowMs` (a monotonic clock).
void Requested(Int64 nowMs) {
m_outstanding = true;
m_requestedAtMs = nowMs;
}
// The compositor answered the request (wl_callback.done).
void Done() { m_outstanding = false; }
// Before a swap's frame is drawn into a buffer, at `nowMs`: how long it waits for the
// outstanding callback - 0 = not at all, kForever = until it comes.
Int64 WaitBudgetMs(Int swapInterval, Int64 nowMs) const {
if (!m_outstanding) return 0;
if (swapInterval > 0) return kForever;
return nowMs - m_requestedAtMs >= kStarvedAfterMs ? kStarvedWaitMs : 0;
}
Bool Outstanding() const { return m_outstanding; }
private:
Bool m_outstanding = false;
Int64 m_requestedAtMs = 0;
};
} // namespace MobileGL::MG_Impl::EGLImpl::Wayland
@@ -1,42 +0,0 @@
// 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
+5 -157
View File
@@ -7,7 +7,6 @@
// End of Source File Header
#include "WaylandWindow.h"
#include "FrameThrottle.h"
#if MOBILEGL_WAYLAND_WINDOWS
@@ -19,14 +18,12 @@
#include <MG_Impl/GLImpl/RenderState/GL_RenderState.h>
#include <MG_Util/Debug/Log.h>
#include <cerrno>
#include <chrono>
#include <cstdarg>
#include <cstdint>
#include <cstring>
#include <dlfcn.h>
#include <fcntl.h>
#include <mutex>
#include <poll.h>
#include <sys/mman.h>
#include <sys/uio.h>
#include <unistd.h>
@@ -120,7 +117,6 @@ namespace MobileGL::MG_Impl::EGLImpl::Wayland {
constexpr uint32_t kBufferDestroy = 0;
constexpr uint32_t kSurfaceAttach = 1;
constexpr uint32_t kSurfaceDamage = 2;
constexpr uint32_t kSurfaceFrame = 3;
constexpr uint32_t kSurfaceCommit = 6;
constexpr uint32_t kSurfaceDamageBuffer = 9; // since wl_surface version 4
constexpr uint32_t kMarshalFlagDestroy = 1u << 0;
@@ -148,8 +144,6 @@ namespace MobileGL::MG_Impl::EGLImpl::Wayland {
const wl_interface* shmInterface = nullptr;
const wl_interface* shmPoolInterface = nullptr;
const wl_interface* bufferInterface = nullptr;
// Optional: without it a window's swaps are not paced by frame callbacks.
const wl_interface* callbackInterface = nullptr;
wl_proxy* (*marshalFlags)(wl_proxy*, uint32_t, const wl_interface*, uint32_t, uint32_t, ...) = nullptr;
int (*addListener)(wl_proxy*, void (**)(void), void*) = nullptr;
void (*destroy)(wl_proxy*) = nullptr;
@@ -163,11 +157,6 @@ namespace MobileGL::MG_Impl::EGLImpl::Wayland {
int (*dispatchQueue)(void*, wl_event_queue*) = nullptr;
int (*dispatchQueuePending)(void*, wl_event_queue*) = nullptr;
int (*flush)(void*) = nullptr;
// Optional: a bounded wait for a frame callback (FrameThrottle's interval-0 case).
int (*prepareReadQueue)(void*, wl_event_queue*) = nullptr;
int (*getFd)(void*) = nullptr;
int (*readEvents)(void*) = nullptr;
void (*cancelRead)(void*) = nullptr;
};
// Loaded once. RTLD_NOLOAD first: a Wayland client has the library already, and the copy
@@ -185,7 +174,6 @@ namespace MobileGL::MG_Impl::EGLImpl::Wayland {
api.shmInterface = static_cast<const wl_interface*>(sym("wl_shm_interface"));
api.shmPoolInterface = static_cast<const wl_interface*>(sym("wl_shm_pool_interface"));
api.bufferInterface = static_cast<const wl_interface*>(sym("wl_buffer_interface"));
api.callbackInterface = static_cast<const wl_interface*>(sym("wl_callback_interface"));
api.marshalFlags = reinterpret_cast<decltype(api.marshalFlags)>(sym("wl_proxy_marshal_flags"));
api.addListener = reinterpret_cast<decltype(api.addListener)>(sym("wl_proxy_add_listener"));
api.destroy = reinterpret_cast<decltype(api.destroy)>(sym("wl_proxy_destroy"));
@@ -200,11 +188,6 @@ namespace MobileGL::MG_Impl::EGLImpl::Wayland {
api.dispatchQueuePending =
reinterpret_cast<decltype(api.dispatchQueuePending)>(sym("wl_display_dispatch_queue_pending"));
api.flush = reinterpret_cast<decltype(api.flush)>(sym("wl_display_flush"));
api.prepareReadQueue =
reinterpret_cast<decltype(api.prepareReadQueue)>(sym("wl_display_prepare_read_queue"));
api.getFd = reinterpret_cast<decltype(api.getFd)>(sym("wl_display_get_fd"));
api.readEvents = reinterpret_cast<decltype(api.readEvents)>(sym("wl_display_read_events"));
api.cancelRead = reinterpret_cast<decltype(api.cancelRead)>(sym("wl_display_cancel_read"));
api.loaded = api.displayInterface && api.registryInterface && api.shmInterface &&
api.shmPoolInterface && api.bufferInterface && api.marshalFlags && api.addListener && api.destroy &&
api.getVersion && api.createWrapper && api.wrapperDestroy && api.setQueue &&
@@ -345,18 +328,8 @@ namespace MobileGL::MG_Impl::EGLImpl::Wayland {
EGLint committedWidth = 0;
EGLint committedHeight = 0;
// SWAP PACING (FrameThrottle.h). The frame request goes through a wrapper of the
// application's wl_surface that lives on this window's queue, so its callback is
// dispatched here and never by the application.
void* surfaceWrapper = nullptr;
wl_proxy* frameCallback = nullptr;
FrameThrottle throttle;
Int loggedInterval = -1;
~Impl() {
const Api& api = WaylandApi();
if (frameCallback) api.destroy(frameCallback);
if (surfaceWrapper) api.wrapperDestroy(surfaceWrapper);
for (auto& buffer : buffers) Release(buffer);
for (auto& buffer : dmabufBuffers) Release(buffer);
if (dmabuf) api.marshalFlags(dmabuf, kDmabufDestroy, nullptr, api.getVersion(dmabuf), kMarshalFlagDestroy);
@@ -550,71 +523,6 @@ namespace MobileGL::MG_Impl::EGLImpl::Wayland {
useDmabuf = false;
}
void FrameDone(wl_proxy* callback) {
if (callback != frameCallback) return;
WaylandApi().destroy(callback);
frameCallback = nullptr;
throttle.Done();
}
static Int64 NowMs() {
return std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now().time_since_epoch())
.count();
}
// A broken connection answers nothing again; stop pacing on it.
void AbandonFrame() {
if (frameCallback) WaylandApi().destroy(frameCallback);
frameCallback = nullptr;
throttle.Done();
}
// Waits, as FrameThrottle decides, for the callback of the frame before this one: the
// compositor has used that one. It sends none while it shows nothing.
void WaitForFrame(Int swapInterval) {
const Api& api = WaylandApi();
const Int64 budget = throttle.WaitBudgetMs(swapInterval, NowMs());
if (budget == 0) return;
if (budget == FrameThrottle::kForever) {
while (throttle.Outstanding()) {
if (api.dispatchQueue(display, queue) < 0) return AbandonFrame();
}
return;
}
if (!api.prepareReadQueue || !api.getFd || !api.readEvents || !api.cancelRead) return;
const Int64 deadline = NowMs() + budget;
while (throttle.Outstanding()) {
// libwayland's read protocol: whatever is queued first, then one read of the
// socket for this queue, bounded by the deadline.
while (api.prepareReadQueue(display, queue) != 0) {
if (api.dispatchQueuePending(display, queue) < 0) return AbandonFrame();
}
if (!throttle.Outstanding()) {
api.cancelRead(display);
return;
}
api.flush(display);
const Int64 remaining = deadline - NowMs();
if (remaining <= 0) {
api.cancelRead(display);
return;
}
pollfd fd{api.getFd(display), POLLIN, 0};
const int ready = poll(&fd, 1, static_cast<int>(remaining));
if (ready <= 0) {
api.cancelRead(display);
if (ready < 0 && errno == EINTR) continue;
return;
}
if (api.readEvents(display) < 0) return AbandonFrame();
if (api.dispatchQueuePending(display, queue) < 0) return AbandonFrame();
}
}
// The next commit asks for a frame callback (none outstanding).
void RequestFrame(wl_proxy* surface);
// `wlBuffer` becomes the window's content: attach, damage, commit. `damage` is the frame's
// (GL window coordinates); a buffer's rows run top-down, so each rectangle is flipped. A
// compositor without damage_buffer (wl_surface < 4), a new size or the first commit is
@@ -623,7 +531,6 @@ namespace MobileGL::MG_Impl::EGLImpl::Wayland {
const Api& api = WaylandApi();
wl_proxy* surface = window->surface;
const uint32_t surfaceVersion = api.getVersion(surface);
RequestFrame(surface);
api.marshalFlags(surface, kSurfaceAttach, nullptr, surfaceVersion, 0, wlBuffer, window->dx, window->dy);
const Bool whole = damage.IsFull() || surfaceVersion < 4 || committedWidth != width ||
committedHeight != height || window->dx != 0 || window->dy != 0;
@@ -674,11 +581,6 @@ namespace MobileGL::MG_Impl::EGLImpl::Wayland {
void (*const kRegistryListener[])(void) = {reinterpret_cast<void (*)(void)>(&OnRegistryGlobal),
reinterpret_cast<void (*)(void)>(&OnRegistryGlobalRemove)};
void OnFrameDone(void* data, wl_proxy* callback, uint32_t) {
static_cast<WindowSurface::Impl*>(data)->FrameDone(callback);
}
void (*const kFrameListener[])(void) = {reinterpret_cast<void (*)(void)>(&OnFrameDone)};
// The application destroyed its wl_egl_window first: nothing may be read from it after this.
void OnWindowDestroyed(void* data) { static_cast<WindowSurface::Impl*>(data)->window = nullptr; }
} // namespace
@@ -725,22 +627,6 @@ namespace MobileGL::MG_Impl::EGLImpl::Wayland {
return eglWindow->width > 0 && eglWindow->height > 0;
}
void WindowSurface::Impl::RequestFrame(wl_proxy* surface) {
const Api& api = WaylandApi();
if (api.callbackInterface == nullptr || !throttle.WantsFrameRequest()) return;
if (surfaceWrapper == nullptr) {
surfaceWrapper = api.createWrapper(surface);
if (surfaceWrapper == nullptr) return;
api.setQueue(static_cast<wl_proxy*>(surfaceWrapper), queue);
}
auto* wrapper = static_cast<wl_proxy*>(surfaceWrapper);
frameCallback = api.marshalFlags(wrapper, kSurfaceFrame, api.callbackInterface, api.getVersion(wrapper), 0,
nullptr);
if (frameCallback == nullptr) return;
api.addListener(frameCallback, const_cast<void (**)(void)>(kFrameListener), this);
throttle.Requested(NowMs());
}
WindowSurface::WindowSurface(UniquePtr<Impl> impl) : m_impl(std::move(impl)) {}
WindowSurface::~WindowSurface() = default;
@@ -806,42 +692,9 @@ namespace MobileGL::MG_Impl::EGLImpl::Wayland {
return true;
}
void WindowSurface::OnSessionReplaced() {
Bool WindowSurface::Present(const MG_Util::Damage::Region& damage) {
Impl& impl = *m_impl;
const Api& api = WaylandApi();
for (auto& buffer : impl.dmabufBuffers) {
if (buffer.buffer) {
api.marshalFlags(buffer.buffer, kBufferDestroy, nullptr, api.getVersion(buffer.buffer),
kMarshalFlagDestroy);
}
buffer = DmabufBuffer{};
}
impl.dmabufDamage.InvalidateAll();
// The linux-dmabuf global is still bound (FallBackToShm keeps it); a window that never had
// it, or gave it up at creation because nothing could be allocated, stays on wl_shm.
impl.useDmabuf = impl.dmabufWanted && impl.dmabuf != nullptr;
}
void WindowSurface::CommitPendingState() {
Impl& impl = *m_impl;
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),
swapInterval > 0 ? "paced by frame callbacks" : "unpaced while the compositor shows it");
impl.loggedInterval = swapInterval;
}
impl.WaitForFrame(swapInterval);
if (impl.window == nullptr) return false;
if (impl.useDmabuf) {
// The server copies the frame into the image GPU-side, top row first - a wl_buffer's
@@ -856,12 +709,9 @@ namespace MobileGL::MG_Impl::EGLImpl::Wayland {
if (backendObject->PresentToSharedImage(buffer->imageId, copy)) {
impl.Commit(buffer->buffer, damage);
buffer->busy = true;
return PresentResult::kPresented;
return true;
}
}
// 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();
@@ -870,17 +720,15 @@ 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 PresentResult::kNotShown;
return false;
}
// 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 PresentResult::kPresented;
return true;
}
} // namespace MobileGL::MG_Impl::EGLImpl::Wayland
+3 -25
View File
@@ -75,42 +75,20 @@ 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. kNotShown (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. False (logged) when the frame
// did not reach the window; the swap itself goes on regardless.
//
// `damage` (GL window coordinates, clipped to the window; Full = all of it) is what the
// frame changed. A shared image is copied only where it differs from the frame - the
// frame's damage and every frame's since that image was last written - and the surface is
// damaged only where the frame changed, flipped to the buffer's top-left origin.
//
// `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).
//
// `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)());
Bool Present(const MG_Util::Damage::Region& damage);
// wl_egl_window_resize's effect, taken: true (with the new size) when the application gave
// its wl_egl_window a size this presentation is not at yet. The presentation adopts it -
// its next buffer is that size - and the caller resizes the drawable behind it.
Bool TakeResize(EGLint* width, EGLint* height);
// 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
// back to shared images - allocated anew, on the fresh server, at the next present - if
// it was using them, or had fallen back to wl_shm only for a present the loss broke.
void OnSessionReplaced();
struct Impl;
private:
@@ -123,8 +123,6 @@ 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
}
@@ -132,7 +130,6 @@ 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
}
@@ -435,9 +432,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_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_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, 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)
@@ -1121,7 +1118,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_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, 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_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)
@@ -1292,6 +1289,7 @@ 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)
@@ -2992,50 +2990,6 @@ 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);
+15 -174
View File
@@ -434,7 +434,6 @@ namespace MobileGL::MG_Impl::GLImpl {
case GL_TEXTURE_BINDING_CUBE_MAP: outTarget = TextureTarget::TextureCubeMap; return true;
case GL_TEXTURE_BINDING_CUBE_MAP_ARRAY: outTarget = TextureTarget::TextureCubeMapArray; return true;
case GL_TEXTURE_BINDING_RECTANGLE: outTarget = TextureTarget::TextureRectangle; return true;
case GL_TEXTURE_BINDING_EXTERNAL_OES: outTarget = TextureTarget::External; return true;
default: return false;
}
}
@@ -593,117 +592,12 @@ namespace MobileGL::MG_Impl::GLImpl {
}
namespace {
// 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() {
// GL_OES_EGL_image_external(_essl3) only where the server samples YUV images: an
// external texture is a 2D texture holding the image converted to RGBA, which needs
// the server to hold the YUV image in the first place (EGLImpl::SharedImageYuvAvailable).
static const auto build = [](Bool images, Bool external, Bool es, Bool esApi) {
Vector<const char*> list;
if (images) list.push_back("GL_OES_EGL_image");
if (images && external) {
list.push_back("GL_OES_EGL_image_external");
list.push_back("GL_OES_EGL_image_external_essl3");
}
for (const char* name : {"GL_KHR_robustness", "GL_ARB_robustness", "GL_EXT_robustness"})
list.push_back(name);
// 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.
if (es) {
list.push_back("GL_EXT_texture_format_BGRA8888");
list.push_back("GL_EXT_read_format_bgra");
}
// Any context created for the OpenGL ES API, whatever it calls itself: the ES 2.0
// names of what desktop GL has in core - RGB8/RGBA8 and DEPTH_COMPONENT24
// renderbuffers, and glMapBuffer (exported under its OES names as well).
if (esApi) {
list.push_back("GL_OES_rgb8_rgba8");
list.push_back("GL_OES_depth24");
list.push_back("GL_OES_mapbuffer");
}
return list;
};
static const Vector<const char*> lists[16] = {
build(false, false, false, false), build(false, false, false, true),
build(false, false, true, false), build(false, false, true, true),
build(false, true, false, false), build(false, true, false, true),
build(false, true, true, false), build(false, true, true, true),
build(true, false, false, false), build(true, false, false, true),
build(true, false, true, false), build(true, false, true, true),
build(true, true, false, false), build(true, true, false, true),
build(true, true, true, false), build(true, true, true, true)};
const Bool images = MG_Impl::EGLImpl::SharedImagesAvailable();
const Bool external = images && MG_Impl::EGLImpl::SharedImageYuvAvailable();
const Bool esApi = MG_State::pEGLContext &&
MG_State::pEGLContext->GetCurrentContextClientAPI() == EGL_OPENGL_ES_API;
return lists[(images ? 8 : 0) + (external ? 4 : 0) + (EsIdentityActive() ? 2 : 0) + (esApi ? 1 : 0)];
// 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;
}
// 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@ */
@@ -741,12 +635,6 @@ 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,
@@ -763,7 +651,6 @@ 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);
@@ -777,7 +664,7 @@ namespace MobileGL::MG_Impl::GLImpl {
}
extensionsString += MG_Util::ConvertGLExtToString(ext);
}
for (const char* extra : ClientSideExtensions()) {
if (const char* extra = ClientSideExtension()) {
if (!extensionsString.empty()) extensionsString += " ";
extensionsString += extra;
}
@@ -801,9 +688,8 @@ namespace MobileGL::MG_Impl::GLImpl {
const auto& rendererInfo = activeBackendObject->GetRendererInfo();
const auto& exts = rendererInfo.RendererGLInfo.Extensions;
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()) {
if (const char* extra = ClientSideExtension()) return (const GLubyte*)extra;
}
if (index >= exts.size()) {
return nullptr;
@@ -1789,20 +1675,8 @@ 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;
@@ -2648,7 +2522,7 @@ namespace MobileGL::MG_Impl::GLImpl {
GetIntegeri_v(GL_MAX_COMPUTE_WORK_GROUP_SIZE, 2, &params[2]);
break;
case GL_MAJOR_VERSION:
*params = EsIdentityActive() ? 3 : rendererInfo.RendererGLInfo.TargetGLVersion.Major;
*params = rendererInfo.RendererGLInfo.TargetGLVersion.Major;
break;
case GL_MAX_3D_TEXTURE_SIZE:
*params = dynamicParameters.Max3DTextureSize;
@@ -2935,10 +2809,11 @@ namespace MobileGL::MG_Impl::GLImpl {
*params = static_cast<GLint>(RenderStateParameters::MAX_VIEWPORTS);
break;
case GL_MINOR_VERSION:
*params = EsIdentityActive() ? 2 : rendererInfo.RendererGLInfo.TargetGLVersion.Minor;
*params = rendererInfo.RendererGLInfo.TargetGLVersion.Minor;
break;
case GL_NUM_EXTENSIONS:
*params = static_cast<Int>(rendererInfo.RendererGLInfo.Extensions.size() + ClientSideExtensions().size());
*params = static_cast<Int>(rendererInfo.RendererGLInfo.Extensions.size()) +
(ClientSideExtension() != nullptr ? 1 : 0);
break;
case GL_POINT_SIZE_GRANULARITY:
*params = static_cast<GLint>(dynamicParameters.PointSizeGranularity);
@@ -3003,18 +2878,6 @@ namespace MobileGL::MG_Impl::GLImpl {
}
GLenum GetError() {
#if MOBILEGL_BUILD_DISAGGREGATED
// KHR_robustness: a lost context's commands generate GL_CONTEXT_LOST. Reported ONCE per
// 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.
// 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;
}
#endif
auto error = MG_State::pGLContext->PopGLError();
if (!error || !error->get()) {
return GL_NO_ERROR;
@@ -3034,35 +2897,13 @@ 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:
// * 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).
// 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.
//
// 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,36 +1380,6 @@ 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.
@@ -2583,22 +2553,6 @@ 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,11 +46,6 @@ 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);
+11 -66
View File
@@ -1194,25 +1194,6 @@ namespace MobileGL::MG_Impl::GLImpl {
return false;
}
// GL_OES_EGL_image_external: base level 0, CLAMP_TO_EDGE only, NEAREST or LINEAR only.
if (target == TextureTarget::External) {
if (pname == GL_TEXTURE_BASE_LEVEL && param != 0) {
MG_State::pGLContext->RecordError(
ErrorCode::InvalidOperation,
MakeUnique<GenericErrorInfo>("MG_Impl/GLImpl", caller, "External texture base level must be zero."));
return false;
}
if (((pname == GL_TEXTURE_WRAP_S || pname == GL_TEXTURE_WRAP_T || pname == GL_TEXTURE_WRAP_R) &&
param != GL_CLAMP_TO_EDGE) ||
(pname == GL_TEXTURE_MIN_FILTER && param != GL_NEAREST && param != GL_LINEAR)) {
MG_State::pGLContext->RecordError(
ErrorCode::InvalidEnum,
MakeUnique<GenericErrorInfo>("MG_Impl/GLImpl", caller,
"External textures clamp to edge and filter without mipmaps."));
return false;
}
}
if (target == TextureTarget::TextureRectangle && pname == GL_TEXTURE_BASE_LEVEL && param != 0) {
MG_State::pGLContext->RecordError(
ErrorCode::InvalidOperation,
@@ -1654,7 +1635,6 @@ namespace MobileGL::MG_Impl::GLImpl {
case GL_TEXTURE_CUBE_MAP_ARRAY:
case GL_TEXTURE_2D_MULTISAMPLE:
case GL_TEXTURE_2D_MULTISAMPLE_ARRAY:
case GL_TEXTURE_EXTERNAL_OES:
return true;
default:
return false;
@@ -3165,17 +3145,6 @@ namespace MobileGL::MG_Impl::GLImpl {
if (!TextureImpl::ValidateTextureObject(textureObject)) return false;
switch (pname) {
// GL_OES_EGL_image_external: one unit per external texture (the image arrives as RGBA).
case GL_REQUIRED_TEXTURE_IMAGE_UNITS_OES:
if (textureTarget != TextureTarget::External) {
MG_State::pGLContext->RecordError(
ErrorCode::InvalidEnum,
MakeUnique<GenericErrorInfo>("MG_Impl/GLImpl", __func__,
"GL_REQUIRED_TEXTURE_IMAGE_UNITS_OES is an external texture's."));
return false;
}
if (params) *params = 1;
break;
case GL_TEXTURE_MAG_FILTER:
if (params) {
*params = (GLint)MG_Util::ConvertSamplerFilterModeToGLEnum(
@@ -6836,13 +6805,6 @@ namespace MobileGL::MG_Impl::GLImpl {
const char* caller) {
if (!textureObject) return false;
const auto target = textureObject->GetTarget();
// GL_OES_EGL_image_external: an external texture has no mip chain to generate.
if (target == TextureTarget::External) {
MG_State::pGLContext->RecordError(
ErrorCode::InvalidEnum,
MakeUnique<GenericErrorInfo>("MG_Impl/GLImpl", caller, "External textures have no mipmaps."));
return false;
}
if ((target == TextureTarget::TextureCubeMap || target == TextureTarget::TextureCubeMapArray) &&
!textureObject->IsComplete()) {
MG_State::pGLContext->RecordError(
@@ -7176,20 +7138,15 @@ namespace MobileGL::MG_Impl::GLImpl {
// GL_OES_EGL_image. The only EGLImages with storage behind them are the server's shared images
// (EGL_LINUX_DMA_BUF_EXT): level 0 of the bound texture is defined at the image's size through
// glTexImage2D's own path - so the respecification is recorded and announced as for any other
// - and the backend then swaps that storage for the image.
//
// GL_OES_EGL_image_external's target takes it the same way: an external texture is a 2D one
// below the frontend. A YUV image (NV12/P010) is taken by either target; the backend converts it
// into the texture's RGBA level at the first use in each frame (SharedImageYuv.h).
// - and the backend then swaps that storage for the image. The frontend has no external-image
// target, so GL_TEXTURE_2D is the only one taken.
void EGLImageTargetTexture2DOES(GLenum target, GLeglImageOES image) {
if (target != GL_TEXTURE_2D && target != GL_TEXTURE_EXTERNAL_OES) {
if (target != GL_TEXTURE_2D) {
MG_State::pGLContext->RecordError(
ErrorCode::InvalidEnum,
MakeUnique<GenericErrorInfo>("MG_Impl/GLImpl", __func__,
"target must be GL_TEXTURE_2D or GL_TEXTURE_EXTERNAL_OES."));
MakeUnique<GenericErrorInfo>("MG_Impl/GLImpl", __func__, "target must be GL_TEXTURE_2D."));
return;
}
const Bool external = target == GL_TEXTURE_EXTERNAL_OES;
Uint64 sharedImageId = 0;
EGLint width = 0;
EGLint height = 0;
@@ -7201,27 +7158,17 @@ namespace MobileGL::MG_Impl::GLImpl {
}
auto& activeUnit = MG_State::pGLContext->GetTextureUnitObject(MG_State::pGLContext->GetActiveTextureUnit());
const SharedPtr<MG_State::GLState::ITextureObject> textureObject =
activeUnit.GetBindingSlot(external ? TextureTarget::External : TextureTarget::Texture2D).GetBoundObject();
activeUnit.GetBindingSlot(TextureTarget::Texture2D).GetBoundObject();
if (!TextureImpl::ValidateTextureObject(textureObject)) return;
if (!ValidateTextureMutable(textureObject, __func__)) return;
if (!TextureImpl::ValidateTextureSizeRange(width, height, 1)) return;
if (external) {
// glTexImage2D does not take the external target, so its level 0 is defined here the way
// that call defines a 2D one without data: an RGBA8 base, any older chain dropped.
textureObject->SetInternalFormat(TextureInternalFormat::RGBA8);
auto* mipmapObject = static_cast<MG_State::GLState::TextureObjectMipmap*>(textureObject.get());
DiscardMipmapChainOnBaseRespecification(mipmapObject, TextureUploadTarget::Texture2D, 0);
mipmapObject->AllocateStorage(TextureUploadTarget::Texture2D, 0,
{{width, height, 1}, static_cast<SizeT>(width) * height * 4});
} else {
// NULL is an offset into a bound unpack buffer; the definition must read nothing.
GLint unpackBuffer = 0;
GetIntegerv(GL_PIXEL_UNPACK_BUFFER_BINDING, &unpackBuffer);
if (unpackBuffer != 0) BindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
TexImage2D_State(GL_TEXTURE_2D, 0, GL_RGBA8, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr);
if (unpackBuffer != 0) BindBuffer(GL_PIXEL_UNPACK_BUFFER, static_cast<GLuint>(unpackBuffer));
}
// NULL is an offset into a bound unpack buffer; the definition must read nothing.
GLint unpackBuffer = 0;
GetIntegerv(GL_PIXEL_UNPACK_BUFFER_BINDING, &unpackBuffer);
if (unpackBuffer != 0) BindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
TexImage2D_State(GL_TEXTURE_2D, 0, GL_RGBA8, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr);
if (unpackBuffer != 0) BindBuffer(GL_PIXEL_UNPACK_BUFFER, static_cast<GLuint>(unpackBuffer));
auto* backendObject = MG_Backend::pActiveBackendObject.get();
if (backendObject == nullptr ||
@@ -7231,9 +7178,7 @@ 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,
+9 -169
View File
@@ -12,11 +12,8 @@
#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 {
@@ -75,8 +72,6 @@ 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;
@@ -91,15 +86,6 @@ 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) ----
@@ -244,33 +230,6 @@ 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;
@@ -285,14 +244,6 @@ 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() {
@@ -328,18 +279,8 @@ 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(VblankForcedOff() ? 0 : 1);
static auto* interval = new Int(1);
return *interval;
}
@@ -393,62 +334,10 @@ 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 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.
// 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.
void PresentRemoteDrawable(GLXDrawableHandle drawable, DrawableSurface& surface) {
const EGLImpl::GLStreamScope stream; // the readback is GL records of this thread's context
const auto& xcb = Xcb();
@@ -459,20 +348,6 @@ 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);
@@ -480,15 +355,6 @@ 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);
@@ -508,8 +374,6 @@ 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) {
@@ -544,8 +408,6 @@ 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));
}
}
@@ -594,7 +456,7 @@ namespace MobileGL::MG_Impl::GLXImpl {
record.XDisplay = dpy;
record.Depth = depth;
record.LastSizePoll = std::chrono::steady_clock::now();
auto [inserted, _] = surfaces.emplace(drawable, std::move(record));
auto [inserted, _] = surfaces.emplace(drawable, record);
return &inserted->second;
}
@@ -808,7 +670,7 @@ namespace MobileGL::MG_Impl::GLXImpl {
}
const char* QueryExtensionsString(Display*, int) {
return GLXExtensions();
return kGLXExtensions;
}
const char* GetClientString(Display*, int name) {
@@ -818,7 +680,7 @@ namespace MobileGL::MG_Impl::GLXImpl {
case GLX_VERSION:
return "1.4";
case GLX_EXTENSIONS:
return GLXExtensions();
return kGLXExtensions;
default:
return nullptr;
}
@@ -1224,15 +1086,8 @@ 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: 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);
// A resize takes effect for the next frame.
SyncSurfaceSize(dpy, drawable, it->second);
}
GLXDrawableHandle CreateWindow(Display*, GLXFBConfigHandle config, GLXDrawableHandle window,
@@ -1332,21 +1187,6 @@ 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;
@@ -1370,7 +1210,7 @@ namespace MobileGL::MG_Impl::GLXImpl {
return;
}
// MobileGL validates 0..4; adaptive vsync (negative) clamps to regular.
interval = VblankForcedOff() ? 0 : std::clamp(interval, 0, 4);
interval = std::clamp(interval, 0, 4);
EGLImpl::SwapInterval(display, interval);
SwapIntervalShadow() = interval;
}
-284
View File
@@ -1,284 +0,0 @@
// 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
@@ -1,199 +0,0 @@
// 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
@@ -1,522 +0,0 @@
// 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
@@ -1,48 +0,0 @@
// 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
-39
View File
@@ -29,26 +29,6 @@ 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) { \
@@ -96,12 +76,6 @@ 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);
@@ -246,10 +220,6 @@ namespace MobileGL::MG_Impl {
GETPROC(glBufferSubData, name);
GETPROC(glGetBufferSubData, name);
GETPROC(glMapBuffer, name);
// GL_OES_mapbuffer (ES contexts): the same three calls under their OES names.
if (strcmp(name, "glMapBufferOES") == 0) return (void*)glMapBuffer;
if (strcmp(name, "glUnmapBufferOES") == 0) return (void*)glUnmapBuffer;
if (strcmp(name, "glGetBufferPointervOES") == 0) return (void*)glGetBufferPointerv;
GETPROC(glUnmapBuffer, name);
GETPROC(glGetBufferParameteriv, name);
GETPROC(glGetBufferPointerv, name);
@@ -906,15 +876,6 @@ 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);
+3 -7
View File
@@ -7,7 +7,6 @@
// End of Source File Header
#include <Includes.h>
#include <Init.h>
#include "GLImpl/Texture/ProxyTexture.h"
#include "GLImpl/Framebuffer/GL_Framebuffer.h"
@@ -23,13 +22,7 @@ namespace MobileGL::MG_Impl {
void Init() {
MGLOG_D("Initializing MobileGL Implementation...");
GLImpl::TextureImpl::pProxyTextureManager = MakeUnique<GLImpl::TextureImpl::ProxyTextureManager>();
BuildDefaultFramebuffer();
#if defined(__APPLE__) && !defined(MOBILEGL_IOS)
NSOpenGLImpl::InstallHooks();
#endif
}
void BuildDefaultFramebuffer() {
// TODO: get real info in EGL
auto& fbo0 = MG_State::pGLContext->CreateFramebufferObject(0);
auto colorTex = MakeShared<MG_State::GLState::TextureObject2D>(0);
@@ -59,5 +52,8 @@ namespace MobileGL::MG_Impl {
// framebuffer, so a context the application creates after this one is not left with an
// unbound framebuffer 0.
MG_State::SetDefaultFramebuffer(fbo0);
#if defined(__APPLE__) && !defined(MOBILEGL_IOS)
NSOpenGLImpl::InstallHooks();
#endif
}
} // namespace MobileGL::MG_Impl
+1 -3
View File
@@ -234,9 +234,7 @@ namespace MobileGL::MG_Pipe {
m_vertices.push_back(static_cast<Uint64>(vertex));
}
}
// An array draw's single range arrives ascending already; sorting it again was most of
// the client's time on a client-array draw.
if (!std::is_sorted(m_vertices.begin(), m_vertices.end())) std::sort(m_vertices.begin(), m_vertices.end());
std::sort(m_vertices.begin(), m_vertices.end());
m_vertices.erase(std::unique(m_vertices.begin(), m_vertices.end()), m_vertices.end());
return true;
}
+11 -17
View File
@@ -132,7 +132,7 @@ namespace MobileGL::MG_Pipe {
// TextureUploadTarget -> TextureTarget inverse exists anywhere in the tree, so
// without this the inline InternalFormat cannot make them fall out at push time and
// the backend keeps reading the frontend attachment objects.
surface.TextureTarget = static_cast<Uint16>(MGPipeWireTextureTarget(texture->GetTarget()));
surface.TextureTarget = static_cast<Uint16>(texture->GetTarget());
return surface;
}
const auto& renderbuffer = attachment.GetRenderbuffer();
@@ -524,28 +524,22 @@ namespace MobileGL::MG_Pipe {
out.Target = static_cast<Uint8>(target);
out.IsDefault = fbo.IsDefaultFramebuffer() ? 1 : 0;
// 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) {
// 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 {
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) {
+4 -20
View File
@@ -34,12 +34,6 @@ namespace MobileGL::MG_Pipe {
MGPipeVertexInputEmitterInstance().EmitVertexBuffers(m_context, m_baseInstance);
if (m_indexBindingChanged)
MGPipeVertexInputEmitterInstance().EmitIndexBuffer(m_context);
// The bindings no longer name them: the buffers go back to the share group for the
// next client-array draw. Their next respecify orphans the store this draw reads.
auto& group = *m_context.GetShareGroup();
for (auto& buffer : m_vertexBuffers)
if (buffer) group.ReturnClientArrayBuffer(std::move(buffer));
if (m_indexBuffer) group.ReturnClientArrayBuffer(std::move(m_indexBuffer));
}
Bool Prepare(MGPDrawInfo& info, const MGPDrawRange* ranges, Uint32 rangeCount,
@@ -52,8 +46,7 @@ namespace MobileGL::MG_Pipe {
// Start remains an element offset, so base vertex and draw IDs are unchanged.
if (clientIndexBytes != 0) {
if (!clientIndices || clientIndexBytes > std::numeric_limits<Uint32>::max()) return false;
m_indexBuffer = MakeOwnedBuffer(m_context, clientIndices, static_cast<SizeT>(clientIndexBytes),
BufferTarget::Index);
m_indexBuffer = MakeOwnedBuffer(clientIndices, static_cast<SizeT>(clientIndexBytes), BufferTarget::Index);
info.IndexResource = MGPipeResourceTrackerInstance().Find(*m_indexBuffer);
info.Flags &= ~static_cast<Uint8>(kDrawHasUserIndices);
MGPIndexBuffer binding{};
@@ -122,14 +115,8 @@ namespace MobileGL::MG_Pipe {
if (attribute.Offset == 0 || byteCount > std::numeric_limits<SizeT>::max() - attribute.Offset)
return false;
const auto* source = reinterpret_cast<const Uint8*>(attribute.Offset);
const Uint64 first = referenced.front();
if (stride == 0) {
std::memcpy(bytes.data(), source, elementBytes);
} else if (last - first + 1 == referenced.size()) {
// Contiguous elements (every array draw, most indexed ones): the vertex
// records from the first fetched one to the end of the last, in one copy.
const SizeT begin = static_cast<SizeT>(first * stride);
std::memcpy(bytes.data() + begin, source + begin, byteCount - begin);
} else {
// Only dereference fetched elements: sparse indices and first>0
// do not grant permission to read intervening application memory.
@@ -139,7 +126,7 @@ namespace MobileGL::MG_Pipe {
}
}
}
m_vertexBuffers[location] = MakeOwnedBuffer(m_context, bytes.data(), bytes.size(), BufferTarget::Vertex);
m_vertexBuffers[location] = MakeOwnedBuffer(bytes.data(), bytes.size(), BufferTarget::Vertex);
handles[location] = MGPipeResourceTrackerInstance().Find(*m_vertexBuffers[location]);
}
MGPipeVertexInputEmitterInstance().EmitVertexBuffers(m_context, info.StartInstance, &handles);
@@ -186,11 +173,8 @@ namespace MobileGL::MG_Pipe {
return attribute.Size > 0 && attribute.Size <= 4 ? component * attribute.Size : 0;
}
static UniquePtr<Buffer> MakeOwnedBuffer(Context& context, const void* bytes, SizeT size, BufferTarget target) {
// A kept buffer is already a published resource: respecifying it is fire-and-forget,
// where a new one costs a blocking create (and a destroy after the draw).
auto buffer = context.GetShareGroup()->TakeClientArrayBuffer();
if (!buffer) buffer = MakeUnique<Buffer>(0);
static UniquePtr<Buffer> MakeOwnedBuffer(const void* bytes, SizeT size, BufferTarget target) {
auto buffer = MakeUnique<Buffer>(0);
const auto handle = MGPipeResourceTrackerInstance().Find(*buffer);
MGPipeResourceTrackerInstance().NoteBoundAs(handle, target);
buffer->SetUsage(BufferUsage::StreamDraw);
+107 -84
View File
@@ -70,11 +70,6 @@ namespace MobileGL::MG_Pipe {
// The one door into PipeInputs' storage on the client side. A struct rather than a
// list of friend functions so the header names exactly one friend.
struct MGPipeFillAccess {
static void CopyServerPackReference(PipeInputs& dst, const PipeInputs& actual,
const PixelStoreParameters& pack) {
dst.m_pixelStore[0] = pack;
dst.m_pixelStore[1] = actual.m_pixelStore[1];
}
// Copies ONE field's storage out of the live context by calling the GLContext
// accessor of the same name (P1 brief D4: no derivation logic is re-implemented
// here, which is what keeps the copy semantically identical by construction).
@@ -664,6 +659,56 @@ namespace MobileGL::MG_Pipe {
if (!MGPipeVerifyInputs(inputs, g_snapshot, mask, &differing)) ReportDivergence(differing, "entry");
}
#if MOBILEGL_BUILD_DISAGGREGATED
// ---- P7 wave 3 (V1): the compare-at-read oracle inside the server's read_pixels ----
//
// WHAT THE SPLIT ARM FOUND THE FIRST TIME VERIFY AND SPLIT SHARED A BUILD. Every
// glReadPixels on the inproc arm - 8530 reads over 220 of the lane's 1068 entries, and the
// VerifySplitArming. entries on both backends - aborted with
//
// MGPipe: verify read of GetPixelStoreParameters (index 0, 0) differs from the live context
// MGPipe: Fatal{PipeVerifyDiffer, "GetPixelStoreParameters@ReadPixels", verb=6, where=read}
//
// on the server's apply thread, and it was the ONLY field that diverged anywhere in the
// lane. The mechanism is ID-49 and is deliberate: the pack state never shapes the wire
// answer, so MG_Remote/Server/PipeApplier.cpp's read_pixels body writes a NEUTRAL pack
// into the applier's copy of the field (MGPipeApplySetPixelPackState), makes the backend
// read, and restores the pushed one; the client then scatters the tight reply through the
// application's own pack state. The frontend context - this comparator's oracle - still
// holds the application's pack (Alignment 4 by default), so the backend's read of the
// pack half answers {Alignment 1} where the live context says {Alignment 4}. On the
// monolith arm the same neutral window is opened on the frontend context itself
// (GL_Texture.cpp's ScopedNeutralPackState), which is why the monolith lane never saw it.
//
// SO THE ORACLE, NOT THE RULE, IS WHAT CHANGES, AND ONLY IN THAT WINDOW: under a server
// stamp, on the ReadPixels verb, the pack half's expected value is the neutral pack the
// applier reads with, and the UNPACK half and every other field keep the live context as
// their oracle. A server read of the pack half that is neither the application's value
// nor exactly the neutral one is still a divergence and still Fatal.
//
// WHAT THIS GIVES UP IS ONE VALUE, NOT THE FIELD (corrected in P7 wave 3's V1 fix round;
// the first statement of it here said the comparator could no longer see a client that
// pushed a WRONG pack state at all, which is too broad). PipeApplier.cpp's read_pixels
// reads `savedPack` THROUGH THE ACCESSOR - and therefore through this hook - BEFORE it
// installs the neutral value, so the pushed pack has already been compared against the
// live one by then: a correct push is equal and returns, and a wrong push that is not
// exactly the neutral pack fails both compares and is still Fatal. The blind spot is the
// single value {SwapBytes 0, LSBFirst 0, RowLength 0, ImageHeight 0, Skip* 0, Alignment 1},
// and only while the application's own pack differs from it. The client-side scatter that
// consumes the real pack is covered by the readback matrix cases, which compare bytes,
// not fields.
Bool ServerReadsInsideTheNeutralPackWindow(const PipeInputs& self, MGPipeInputField field) {
return field == MGPipeInputField::GetPixelStoreParameters && self.ServerStampedVerb() &&
self.CurrentVerb() == MGPipeVerb::ReadPixels;
}
// The constant itself is MG_Pipe's (MGPipeTypes.h's MGPipeNeutralReadPixelsPack), which is
// the same function MG_Remote/Server/PipeApplier.cpp's read_pixels installs. It used to be
// re-typed here, field for field, to avoid reaching into MG_Remote/Server from MG_Impl -
// but the owner of MGPPixelPackState is MG_Pipe, both sites already include it, and a
// drift between the two spellings would have cost a false divergence rather than a build
// break.
#endif // MOBILEGL_BUILD_DISAGGREGATED
#endif // MOBILEGL_PIPE_VERIFY
} // namespace
@@ -681,28 +726,9 @@ namespace MobileGL::MG_Pipe {
}
void MGPipeVerifyReadHook(const PipeInputs& self, MGPipeInputField field, Uint index0, Uint index1) {
if (&self != &gPipeInputs || !g_verify.Enabled) return;
if (&self != &gPipeInputs || !g_verify.Enabled || g_verify.InHook) return;
const auto index = static_cast<SizeT>(field);
if (kMGPipeInputFieldSticky[index]) return;
#if MOBILEGL_BUILD_DISAGGREGATED
if (self.ServerStampedVerb() && field == MGPipeInputField::GetPixelStoreParameters) {
// Compare the backend's pack field against the last payload applied to this
// context, including the neutral-pack override during readback. Never obtain
// the reference by reading the field being checked, or consult the client's
// GLContext from the server thread. Unpack has no server-side reader.
static thread_local PipeInputs reference;
MGPipeFillAccess::CopyServerPackReference(reference, self, MGPipeApplier().VerifyPixelPack);
if (g_verify.Corrupt && *g_verify.Corrupt == field) {
MGPipeApplyVerifyCorruption(reference, field);
}
if (!MGPipeInputsFieldEqual(field, self, reference)) {
MGLOG_E("MGPipe: verify read of pixel pack differs from the applied pack payload");
ReportDivergence(field, "read");
}
return;
}
#endif
if (g_verify.InHook) return;
auto* ctx = LiveContext();
if (ctx == nullptr) return;
// The whole field is re-read and compared - a superset of "the same indices", so a
@@ -717,13 +743,68 @@ namespace MobileGL::MG_Pipe {
// never recurses (and never reports the inner read against a half-copied scratch).
g_verify.InHook = true;
MGPipeFillAccess::CopyField(g_readScratch, *ctx, field);
// Corrupt the reference, not the backend field, to test the comparison itself.
// P7 wave 3 (V1): NEGATIVE CONTROL A REACHES THIS ARM TOO. Until this line the knob only
// ever perturbed EntryCompare's snapshot, so every red it could produce said `where=entry`
// and was produced on the CLIENT thread - which left the compare-at-read hook, the arm
// that runs on the server's apply thread and does the whole of the split lane's per-read
// work, with no falsifier at all: a hook that had stopped comparing would have looked
// exactly like a hook with nothing to report. The perturbation goes on the ORACLE, for
// EntryCompare's reason: the arm under test is the stored value, so corrupting THAT would
// be testing the corruption.
//
// WHICH READ THIS BLOCK TURNS RED (V1 fix round 2). The server reads the pack field TWICE
// inside the ReadPixels verb window, and both reads sit inside
// ServerReadsInsideTheNeutralPackWindow below (the verb stamp is up for the whole apply):
// PipeApplier::read_pixels saves the application's pack through the accessor BEFORE it
// installs the neutral one, and the backend's ReadPixels reads the field AFTER. This block
// is what turns the FIRST of them red: at that read `self` still holds the application's
// pack, so the first compare only reaches the window if this perturbation made it differ,
// and inside the window the application's pack against the neutral oracle differs on its
// own. It does nothing for the second read - `self` IS the neutral pack there - which is
// what the re-application inside the window is for.
if (g_verify.Corrupt && *g_verify.Corrupt == field) {
MGPipeApplyVerifyCorruption(g_readScratch, field);
}
const Bool equal = MGPipeInputsFieldEqual(field, self, g_readScratch);
g_verify.InHook = false;
if (equal) return;
#if MOBILEGL_BUILD_DISAGGREGATED
if (ServerReadsInsideTheNeutralPackWindow(self, field)) {
// The live context is the application's pack state and the server is, by ID-49,
// reading with the neutral one; the oracle for THAT HALF is the neutral pack, and
// every other byte of the field still has to match the live context.
g_verify.InHook = true;
PipeInputs::VisitStorage(field, g_readScratch, g_readScratch, [](auto& live, auto&) {
if constexpr (std::is_same_v<std::remove_reference_t<decltype(live)>, PixelStoreParameters[2]>) {
live[0] = MGPipeNeutralReadPixelsPack().Pack;
}
return true;
});
// AND THE CONTROL IS RE-APPLIED, because the overwrite above replaces the pack half
// WHOLESALE - the corruption included, since CorruptStorage perturbs an array's FIRST
// ELEMENT and the pack half is element 0. This is the block for the POST-INSTALL read
// (the backend's ReadPixels, after PipeApplier::read_pixels installed the neutral pack
// into gPipeInputs): there `self` is the neutral pack, the overwrite just made the
// oracle equal to it, and only a perturbation applied AFTER the overwrite can make
// that compare differ - the block above cannot reach it. Without this line the one
// window in which this arm is most load-bearing (the server's read_pixels, 8530 reads
// over 220 of the lane's entries) would be the one window MOBILEGL_PIPE_VERIFY_CORRUPT=
// GetPixelStoreParameters cannot turn red - and a control that accepted ONE report
// would never notice, because the saved-pack read still reports through the block
// above. The VerifySplitReadCorrupted. entries and the CI step therefore require at
// least TWO `where=read` reports in the server half (V1 fix round 2). Measured: 3 on
// DirectGLES (its backend reads the field twice after the install) / 2 on
// DirectVulkan; without this block both drop to 1, without the block above
// DirectVulkan drops to 1 while DirectGLES's two post-install reports keep it at 2 -
// so this block is falsified on both backends and the one above on DirectVulkan.
if (g_verify.Corrupt && *g_verify.Corrupt == field) {
MGPipeApplyVerifyCorruption(g_readScratch, field);
}
const Bool equalToTheNeutralPack = MGPipeInputsFieldEqual(field, self, g_readScratch);
g_verify.InHook = false;
if (equalToTheNeutralPack) return;
}
#endif
MGLOG_E("MGPipe: verify read of %s (index %u, %u) differs from the live context", kMGPipeInputFieldNames[index],
index0, index1);
ReportDivergence(field, "read");
@@ -1747,12 +1828,6 @@ namespace MobileGL::MG_Pipe {
*entry = Entry{};
}
// A fresh server holds no record at all (MGPipeForgetEndedSession).
void ForgetAll() {
for (Vector<Entry>& table : m_kinds) table.clear();
m_band.clear();
}
private:
struct Entry {
Uint32 Gen = 0;
@@ -1867,13 +1942,6 @@ namespace MobileGL::MG_Pipe {
void MGPipeNoteTextureLevelDirty(ITextureObject& storageOwner, Uint32 uploadTarget, Uint32 level) {
if (!FamilyIsLive(kMGPipeSubsystemTextureResources, kMGPipeWiredTextureSubsystem)) return;
#if MOBILEGL_BUILD_DISAGGREGATED
// AN UPLOAD ON A LOST CONTEXT IS OWED TO NOBODY. The drain list is process-wide and the
// next verb of ANY context drains it; queued from a thread still on a lost context (or
// while the session is lost), it would be carried to a fresh session that never created
// the texture. The level stays dirty on the object, which no live context can reach.
if (MG_Remote::Client::ClientSession::DeviceLost()) return;
#endif
ForwardWhenWired<kMGPipeWiredTextureSubsystem>(
MGPipeTextureEmitterInstance(),
[&](auto& emitter) { emitter.NoteLevelDirty(storageOwner, uploadTarget, level); });
@@ -3905,49 +3973,4 @@ namespace MobileGL::MG_Pipe {
EntryCompare(inputs, mask);
#endif
}
void MGPipeClientDrainTextureUploads() {
#if MOBILEGL_BUILD_DISAGGREGATED
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);
}
#endif
}
#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
// cache entry - finds its handle unpublished and puts nothing on the new wire; then the
// references the emitters hold into the caches go back, then the caches themselves.
void MGPipeForgetEndedSession() {
PublicationLatch().ForgetAll();
MGPipeResourceTrackerInstance().ForgetPublication();
MGPipeReleaseResidualFillPins();
MGPipeDrainDeferredDestroys();
MGPipeTrackerInstance().Reset();
// The texture emitter's records and its owed uploads belong to the ended server; its
// sampler references go back to the cache before the cache is emptied.
MGPipeTextureEmitterInstance().ResetForTest();
MGPipeSamplerEmitterInstance().Reset();
MGPipeSamplerCsoCacheInstance().ResetForTest();
MGPipeCsoCacheInstance().Reset();
MGPipeSetHashSuppressorInstance().InvalidateAll();
MGPipeVertexInputEmitterInstance().Reset();
MGPipeFramebufferEmitterInstance().ResetForTest();
MGPipeImageEmitterInstance().Reset();
MGPipeProgramEmitterInstance().Reset();
MGPipeShaderBufferEmitterInstance().Reset();
g_residualDue = true;
g_attribDefaultLastHeader = MGPVertexAttribDefaults{};
g_lastFillWasBarriered = true;
}
#endif
} // namespace MobileGL::MG_Pipe
-6
View File
@@ -340,12 +340,6 @@ namespace MobileGL::MG_Pipe {
const SizeT slot = handle.Slot;
return slot < m_bySlot.size() && m_bySlot[slot].Published;
}
// A session that replaces an ended one has no record for any buffer the ended one was
// told about: a live buffer of the ended session's contexts dies with no destroy on the
// new wire, and the inverse entries stay so the handles still resolve locally.
void ForgetPublication() {
for (Entry& entry : m_bySlot) entry.Published = false;
}
// The sticky everBoundAs mask. Sticky exactly as MGPResourceDesc::ImageBindableHint's
// everImageBound is: ORed, never cleared, so a buffer that was an element array once
+8 -12
View File
@@ -373,8 +373,7 @@ namespace MobileGL::MG_Pipe {
return false;
}
// A unit test's fixture, and a session that replaced an ended one (MGPipeForgetEndedSession:
// the fresh server holds none of these records). NOT called from the validate point's
// A unit test's fixture, and nothing else. NOT called from the validate point's
// FreshlyPrimed arm: MGPipeApplierReset is a make-current and does NOT drop object
// records, so a sampler CSO the applier holds outlives a context switch. Dropping the
// cache there would leak the applier's record and re-mint a value it already has.
@@ -576,12 +575,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 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) {
// 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())) {
MGPipeRouteDeleteSamplerState(handle);
}
// AND THE LATCH GOES WITH THE DELETE. This is the "an emitter that drops a record
@@ -629,9 +628,6 @@ namespace MobileGL::MG_Pipe {
// sample this unit".
inline MobileGL::TextureTarget MGPipeSamplerUniformTextureTarget(GLenum uniformType) {
switch (uniformType) {
// GL_OES_EGL_image_external: the unit's external binding, whose texture is a 2D one below.
case GL_SAMPLER_EXTERNAL_OES:
return TextureTarget::External;
case GL_SAMPLER_1D:
case GL_INT_SAMPLER_1D:
case GL_UNSIGNED_INT_SAMPLER_1D:
@@ -998,7 +994,7 @@ namespace MobileGL::MG_Pipe {
// and not the storage owner's, which is the whole point of the call; for an
// ordinary texture it is simply its format.
m_lastView.InternalFormat = static_cast<Uint32>(texture.GetFormat());
m_lastView.Target = static_cast<Uint8>(MGPipeWireTextureTarget(texture.GetTarget()));
m_lastView.Target = static_cast<Uint8>(texture.GetTarget());
// THE FOUR RESTRICTIONS COME FROM ONE PLACE. TextureObjectBase leaves all four at
// 0 for an ordinary texture and glTextureView writes them for a view, and a view
// always has NumLevels >= 1 - so a zero here unambiguously means "no restriction,
+2 -26
View File
@@ -1166,10 +1166,7 @@ namespace MobileGL::MG_Pipe {
if (present == key) return;
}
entry.DrainKeys.push_back(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()});
m_drain.push_back(DrainEntry{handle, key});
}
// The DRAIN, at the validate point: one resource_subdata per dirty (storage owner,
@@ -1192,19 +1189,7 @@ 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);
}
@@ -1259,13 +1244,6 @@ namespace MobileGL::MG_Pipe {
return entry.Gen == handle.Gen ? entry.BuiltinSampler : kMGPipeNullHandle;
}
SizeT DrainListSize() const { return m_drain.size(); }
// Whether a level of `handle` is still owed to the server (on the drain list).
Bool OwesUpload(MGPipeHandle handle) const {
for (const DrainEntry& pending : m_drain) {
if (pending.Handle == handle) return true;
}
return false;
}
// A fresh context: what the server has is no longer what this emitter last sent. Only
// LATCHES reset here - the applier's object records survive a make-current and
@@ -1285,8 +1263,7 @@ namespace MobileGL::MG_Pipe {
m_deadResolves = 0;
}
// A unit fixture's per-case reset, and the reset of a session that replaced an ended one
// (MGPipeForgetEndedSession: the fresh server holds none of these records). See
// A unit fixture's per-case reset; the library never calls it. See
// MGPipeResourceTracker::ResetForTest for the rule this restates: a texture handle and
// the applier record it names are SHARE-GROUP OBJECT STATE, so nothing here is
// per-context and no re-publication path exists or may exist.
@@ -1334,7 +1311,6 @@ 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) {

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