feat: non-Adreno graphics stack (Venus, open driver pairs, gamescope patches) (#2029)

* Retain compositor resources when GPU completion is unconfirmed

* Stop quarantined GPU callers before retries and mapped writes

* Support Android hardware-buffer presentation over Wayland

* Support PowerVR swapchains and linear image imports in Gamescope

* Bundle verified PowerVR graphics components through existing build preparation

* Detect and select the system Vulkan backend on PowerVR

* Apply PowerVR Steam and game compatibility during normal launches

* Show PowerVR support through existing driver and component controls

* Update existing hardware guidance for system Vulkan support

* Import the shared system Vulkan readiness check

* Discover and propagate the actual PowerVR render node

* Prune obsolete PowerVR runtimes after guest processes exit

* Retain external DMA-BUF ownership after GPU quarantine

* Name the PowerVR HAL selection explicitly

* Isolate component UI tests from application startup

* Cover the inherited FEX preset in PowerVR profile tests

* Log test worker failures for CI diagnosis

* Remove temporary test logging after diagnostic CI

* Prefer system dependencies for the Android Vulkan loader

* Capture raw stderr before test worker termination

* Remove the temporary test worker crash probe

* Import pinned DXVK recipe prerequisite from PowerVR PR570

Copy only the standalone build recipe, source pin, BC-format prerequisite
and presentation-sync patch/check from wallentx/DroidDeck at d0f7264ea8.
Source: https://github.com/Droid-Deck/DroidDeck/pull/570
Preserve that proposal attribution; no Android app, compositor, managed
pack, private data or fork development history is imported.

* Add opt-in low32 GPU mapping adapter and integrity probes

* Add opt-in D3D9 single-sample workaround and fix HUD texel format

* Document verified production game workaround and publication scope

* Restrict reset diagnostics and create private output atomically

* Target official runtime review and document PR570 prerequisite provenance

* Fix runtime tool output isolation, mmap64 chaining and DST ambiguity

* Normalize swapchain backbuffers for the opt-in D3D9 single-sample path

* Experimental Samsung Xclipse support on the system Vulkan path

Detect Samsung's Vulkan HAL (vulkan.samsung.so) and its sgpu render node
alongside PowerVR, and run Xclipse through the same libhybris bridge:

- VK_LAYER_DROIDDECK_xclipse (tools/linuxfs/xclipse-layer), built with the
  glibc preloads and enabled only on Xclipse: sets bionic's environ for the
  driver's shader compiler, avoids immutable YCbCr samplers in compute
  layouts, forwards the KHR calibrated-timestamp entry points to the EXT
  ones, and reports textureCompressionBC and BC4/BC5 filtering over the
  compat layer's BC emulation.
- Upstream DXVK 2.6.2, pinned as a tar.gz component and selected on Xclipse:
  the driver has 128 bytes of push constants, DXVK 3 needs 256.
- android_wlegl accepts a zero stride and passes it through unchanged:
  Samsung's gralloc records none for GPU-only buffers.

Tested on a Galaxy A56 (Xclipse 540, driver 24.0.560): Steam Big Picture
and PICO PARK (D3D9).

* Xclipse layer: copy the device chain and track samplers per device

- Clear textureCompressionBC in a copy of the device-create chain (every
  structure up to the VkPhysicalDeviceFeatures2 that enables it) instead of
  writing the caller's structure; a chain led by a structure of unknown size
  is passed on unchanged.
- Track YCbCr samplers per device in a growable list, drop them on
  vkDestroySampler and device teardown, and fail sampler creation rather
  than leave one untracked when the list cannot grow.
- Fail descriptor set layout creation with VK_ERROR_OUT_OF_HOST_MEMORY when
  a replacement sampler array cannot be allocated, instead of passing the
  original YCbCr samplers to the driver.

* Xclipse layer: copy any device-chain structure the headers define

The chain copy that clears the emulated textureCompressionBC only knew a
handful of structure sizes, so a valid chain such as
VkPhysicalDeviceTimelineSemaphoreFeatures -> VkPhysicalDeviceFeatures2 was
passed on unchanged and the compat layer refused the bit. Size every
structure that may extend VkDeviceCreateInfo from a table generated from the
Vulkan registry (gen_device_chain.py, Vulkan-Headers 1.3.275, the headers
the build compiles with), and copy onto the heap instead of a fixed buffer.
Only a structure newer than those headers still passes the chain unchanged.

Add a regression test that runs the layer between a simulated loader and a
mock driver: the timeline-semaphore chain, pEnabledFeatures, an unknown
structure, the caller's structures left untouched, per-device YCbCr sampler
tracking with handle reuse, and the KHR calibrated-timestamp forwarding. CI
installs libvulkan-dev for it.

* Mali bridge (#517, by ASEbrahim) on the non-Adreno test branch

Squash of Droid-Deck/DroidDeck#517 (ASEbrahim/DroidDeck mali-bridge @ 6b823341): the Vulkan
bridge (tools/vkbridge) that runs the guest's Vulkan on the phone's own driver, with BC1-BC7,
clip/cull distance, vertex-divisor and depth-clip emulation and dma-heap memory sharing for Mali.
All of the bridge is ASEbrahim's work; squashed only to carry it on this test branch.

Combined with #570 on this branch, a device draws through exactly one path:
- Adreno: Turnip, unchanged (checked first; the bridge setting is ignored there).
- PowerVR / Xclipse with the system HAL and a render node: the system-Vulkan path (#570).
- Anything else with the Setup toggle on (Mali): the bridge.

* Test branch: keep #570's DXVK build recipe so its pinned PowerVR components verify

#602 adds output checks to tools/dxvk/build.sh; tools/powervr/fetch.py pins the exact
recipe the published PowerVR DXVK was built from, so the branch carries #570's copy.

* Test branch: make #570, #602 and #560/#561 pass each other's tests

- tools/dxvk/build.sh: #602's copy (its output checks) and the PowerVR pin in
  tools/powervr/release.json moved to that file's hash; the recipe's outputs are unchanged.
- droiddeck-session: the presentation block sets _bl_cef for #570's PowerVR path, and the UI
  block keeps main's order, defaulting to -cef-use-angle=vulkan when the block has not run.
- Compositor test harnesses: AHardwareBuffer stubs for #570's AHB import, and a stub for
  vkp_effects_forget_image (main #597) that #561's caller harness predates.

* Auto drivers for Mali and Xclipse on the non-Adreno test branch

Auto now picks an open driver pair for the GPU, the way it does for Adreno:
- Mali (no KGSL, /dev/mali0): the GPU's name ("Mali-G720-Immortalis MC12", from the vendor
  Vulkan driver or kbase's gpuinfo) picks the PanVK build: G52-G78 (Job Manager), G610/G710,
  G615 or G720. A Mali none of them covers (G925...), or one whose pair is not published yet,
  draws through the Mali bridge, switched on by Auto.
- Xclipse keeps the system-driver path as Auto; the RADV pair is offered as a manual choice.
- The pairs come from The412Banner/droiddeck-nonadreno-drivers (one pre-release per driver,
  each a DriverBundle zip). Only a device without an Adreno reads that repo.
- The importers accept PanVK and RADV libraries (libvulkan_panfrost / libvulkan_radeon).
- An open driver pair and the Mali bridge are alternatives: a selected pair turns the bridge off.
- TU_DEBUG is only set for Turnip, on an Adreno.

Every new branch is reached only when the device has no Adreno; an Adreno's detection, release
sources, Auto choice and session environment are unchanged.

* Auto: the one-binary PanVK kbase build for Mali v9-v13 on Android 15+

The412Banner/droiddeck-nonadreno-drivers adds panvk-mali-kbase: one PanVK build for
G57/G68/G77/G78, G610/G710, G615/G715, G720/G725 and G925, whose display half needs Android 15.
On Android 15+ Auto prefers it for every Mali it covers; below 15, and whenever its release is
not listed, Auto falls back to the GPU generation's own pair. G52/G76 keep the Job Manager
build; a G715/G725/G925 below Android 15, or any Mali no pair covers, draws through the bridge.
Every pair stays selectable by hand.

* Test: the G925 is in the kbase build's family now

* Offer faux123's device PanVK builds (RP4 Pro, Ace, RG556) as manual pairs for their Mali

* Detailed graphics logs for non-Adreno test reports

- graphics-report.txt in every session folder: the graphics path the session draws with and why
  (Turnip, system Vulkan #570, Mali bridge #517, or an open driver pair with its release), the
  driver mode and choices, what Auto would pick, the GPU (family, Vulkan device name, kbase
  gpuinfo, Android, SoC, kernel), the GPU nodes the app can see (access, device numbers, SELinux
  label; nothing is opened) and the guest's graphics environment. At the end it adds the
  compositor's driver lines from app.log and the game launches that were logged.
- vulkan-summary.txt: the session's own vulkaninfo --summary with the driver as exported, in the
  background with a 10 s timeout.
- Per-game logs under games/<time>-<appid>/: Proton's log, DXVK's and vkd3d-proton's, Mesa's and
  PanVK's startup messages and the launch environment, from droiddeck-game-env. Each file is cut
  to 20 MB and the folder to 120 MB at the session's end.
- The per-game logs and the Vulkan summary are on for a GPU that is not an Adreno, and on an
  Adreno only with Setup's new "Detailed graphics logs" switch. Share logs already takes the
  whole session folder, so all of it is in the zip, scrubbed as before.

* Mali pairs: a stand-in render node, the driver's real library name, and a Mali known by its chip

- Auto on Jim's Dimensity 9300+ chose the bridge: the GPU had no name (the app had not asked
  Vulkan yet and kbase's gpuinfo is unreadable under SELinux), so a Mali-G720 counted as a Mali
  no build covers. The name now falls back to the GPU the chip is known to carry (Dimensity,
  Helio, Kompanio, Tensor); and when nothing names it, Auto asks the vendor Vulkan driver off the
  main thread before it settles for the bridge. Auto logs what it decided and why.
- An open Mali driver pair gets /dev/mali0 as the guest's render node, as the bridge does
  (bindGpuNode, BL_DRM_STANDIN): gamescope needs the node the driver reports. The session shim
  only answers libdrm's PRIME and GEM-close calls on it, which PanVK on kbase never makes.
- A PanVK or RADV runtime half is installed as libvulkan_panfrost.so / libvulkan_radeon.so rather
  than under Turnip's name; Turnip keeps libvulkan_freedreno.so.
- graphics-report.txt names the render node the guest got, adds the session script's driver lines
  and flags a failed Mali-bridge self-test at the top.

* Auto takes the RADV pair on a Samsung Xclipse, with the system route as its fallback

A tester's Galaxy S24 FE (Xclipse 940) boots to Steam with the RADV-Xclipse pair, where the
system-driver route fails at Steam's OpenGL (glamor and GLX cannot load a driver). Auto now
downloads and selects RADV on an Xclipse like the Mali pairs, and falls back to the system route
only when RADV is not published. #570's reset of both drivers at each start no longer undoes an
open driver pair. PowerVR (vulkan.powervr.so) keeps the system driver as before.

* An Exynos with a Mali is a Mali, not an Xclipse

The system route took vulkan.samsung.so as Samsung's Xclipse, but an Exynos 1280/1380 (Galaxy Tab
S9 FE: Mali-G68) may name its HAL the same; with /dev/mali0 present that HAL is not the system
route's, and the device is detected as the Mali it is. The chip table adds the Exynos 1380 and
1280 (s5e8835, s5e8825: Mali-G68).

* Auto fetches the open drivers itself; Xclipse named as such; sound and frame-gen in the logs

- Auto looks online again when its saved release list predates this device's open drivers, so a
  Samsung or Mali phone gets its pair without pressing refresh first.
- A Samsung Xclipse is labelled "Samsung Xclipse" (not PowerVR), with its own support line.
- Per-game logs add audio-streams.txt: PulseAudio's sink inputs 20 s and 60 s into the launch,
  so a silent game shows whether its stream reached Pulse.
- graphics-report.txt states the frame-generation setting and keeps the LSFG gate, FrameGen and
  audio lines from app.log.

* Client sound retries a briefly disconnected AAudio; kbase ioctl refusals explained in the report

A Galaxy S24 FE's session had no sound at all: the DirectAudio sink's AAudio stream opened with
AAUDIO_ERROR_DISCONNECTED while the output route was still changing at session start, and the
plain AAudio fallback failed the same moment. The sink guard now retries DirectAudio, then the
plain sink, five times over ten seconds and says which one it got. graphics-report.txt keeps the
client-sink and kbase lines, and explains a KBASE_IOCTL_MEM_EXEC_INIT EPERM as the kbase driver's
own answer rather than the session's sandbox.

* Mali pairs draw the display on the phone's own Mali driver; Xwayland falls back without glamor

- Testers' Mali pairs got the guest drawing (gamescope on the stand-in node, Zink on PanVK) but
  the compositor's PanVK Android half failed on Mali gralloc: it probes AHB formats 0x38/0x3b that
  mali_gralloc does not have, and "vkCreateImage w/ native buffer failed". Under Auto a Mali pair
  now leaves the display on the phone's own Vulkan driver (dma-buf, modifiers and AHB all pass the
  testers' checks) and runs the pair's PanVK in the guest; the Android half stays installed for a
  manual pick. "Pair in use" now follows the runtime half.
- A session after one whose Xwayland crashed (segfault, then gamescope's X11 I/O error) starts
  Xwayland with XWAYLAND_NO_GLAMOR=1 on a non-Adreno device, and says so in app.log.
- graphics-report.txt names the display driver the compositor used, and keeps gralloc, dma-buf,
  modifier and import lines from app.log and Xwayland's own lines from the session log.

* Non-Adreno sound: the daemon falls back on its own; the build's commit in device.txt and the report

The S24 FE's session still had no sound: its AAudio refuses DirectAudio's low-latency stream with
AAUDIO_ERROR_DISCONNECTED, and the sink guard never got to retry because pactl did not reach the
daemon in time ("the daemon did not answer in 15 s"). On a GPU that is not an Adreno the daemon's
own start-up script now asks DirectAudio again without low latency and loads the plain AAudio sink
underneath it, so a default sink exists whatever pactl does. device.txt and graphics-report.txt
name the build label and source commit, so a log says which build it came from.

* Non-Adreno sound: no second DirectAudio load (it hung the daemon); the plain AAudio sink underneath

On the S24 FE the daemon stopped after DirectAudio's failed low-latency load: the second
DirectAudio load in the same daemon never returned, so nothing after it ran and pactl never
connected. The daemon now loads only the plain AAudio sink (no low latency) after DirectAudio,
inside .nofail, and sets whichever exists as the default.

* gamescope: explicit sync off where the kernel or the stand-in node cannot signal its timelines

Adds tools/gamescope/patches/0126 (GAMESCOPE_DISABLE_EXPLICIT_SYNC=1 for the nested backends) and
sets it on a GPU that is not an Adreno when the kernel is older than 6.6 (no
DRM_IOCTL_SYNCOBJ_EVENTFD) or the guest's render node is Mali's stand-in. The graphics report
lists it with the rest of the guest's graphics environment.

* Test branch: gamescope with the explicit-sync switch (0126), pinned by sha

Built by build-gamescope.yml run 38335744351 from 0136fb61 and published as a component release
of The412Banner/droiddeck-nonadreno-drivers; the apk build fetches it by tag and checks the sha.

* Sound: nothing that can block in the daemon's start-up; Steam's web compositing in software on open pairs

- The S24 FE (US) daemon hung loading the plain AAudio sink from default.pa (its AAudio open
  blocks rather than fails), so it never finished starting. default.pa is back to DirectAudio
  alone inside .nofail; the fallbacks are loaded from the app once the daemon answers, each pactl
  bounded by its timeout (DirectAudio, then the plain sink with and without low latency). The
  guard waits 30 s and logs, with timestamps, how long the daemon took, whether its socket and
  pactl exist, and what it finally got.
- With an open driver pair on a GPU that is not an Adreno, Steam's CEF composites in software
  (-cef-disable-gpu-compositing) with GPU raster kept: RADV on Xclipse showed stale, half-written
  tiles, as #570 saw on PowerVR. The session log says so.

* Mali under Auto: the display always on Android's own Vulkan loader; a reboot hint for refused audio

Axel's Tab S9 FE still drew its display with the PanVK Android half, set by an earlier build, and
stalled at "Waiting for Steam's first frame" on Mali gralloc's format probes. Under Auto a Mali's
display now goes to Android's own loader whatever was set before (DriverMenus resets it, and the
compositor's driver choice ignores a pair's Android half), with no HAL path to find first. A pair
counts as in use when its runtime half is. A manual pick of the PanVK display is kept.
When audio.log shows AAUDIO_ERROR_DISCONNECTED, the report and the client-sink line say Android
refused the output and that rebooting the phone usually fixes it.

* Fix: call SessionPrefs.gpuDriverMode through its instance from Java

* Compositor: log each new dma-buf format/modifier/size it imports (for colour and swizzle reports)

Steam's software web compositing already covers every open driver pair, Mali included.

* Open driver pairs: vkd3d-proton reports the driver's caps; buffer attach/release tracing; Mesa log

- With a PanVK or RADV pair (BL_OPEN_DRIVER=1), droiddeck-game-env drops the app-wide
  VKD3D_FEATURE_LEVEL=12_2 and VKD3D_SHADER_MODEL=6_9 so vkd3d-proton reports what the driver has
  (an Unreal DX12 game crashed at start on PanVK with the overrides); a game's own setting still
  wins, and launch.txt records DROIDDECK_VKD3D_CAPS=driver.
- The compositor traces, on a GPU that is not an Adreno, the first 400 dma-buf attaches and buffer
  releases by wl_buffer id and sending line, and logs any release of a buffer already released
  and not attached again (gamescope's "Compositor released us but we were not acquired" on G925).
- Per-game logs no longer set MESA_DEBUG=silent, which kept mesa.log empty.

* Tests: the dma-buf quarantine harness follows send_buffer_release's tracing macro

* Mali (Venus): David Cimo's Venus route sources and recipes

From DavidCimo/droiddeck-mali, branch mali-venus @ 4f838891 (prototype 13; his 12 commits on top
of DroidDeck 0.3.1, GPL-3.0), by David Cimo:
- tools/venus: Mesa Venus vtest patch (incl. the per-queue submit_mutex fix and the cached-memory
  frame readback), virglrenderer Android patch, the Mali compatibility layer (the six features
  DXVK needs: fill modes, multi-viewport, robustness2, clip/cull distance, BC1-BC7) and his tools.
- tools/linuxfs/preload/venus.c: keeps Zink's kopper under Venus.
- tools/gamescope/patches/0127 (his 0114): shm buffers uploaded on every commit.
- docs/development/mali-venus.md: his design notes.
- tools/venus/ci-build.sh and build-venus.yml: his build recipes as one CI job that packs the
  component (vtest server, ICD, layer) as venus.tzst for the apk.

Co-authored-by: Dersim Abbas <derabb0620@gmail.com>

* Mali (Venus) as a selectable route, by David Cimo

Ports David Cimo's Venus route (DavidCimo/droiddeck-mali, mali-venus @ 4f838891) onto this branch
as "Mali (Venus)", one tap in Setup next to the Mali bridge:
- VenusComponent (his): stages the Venus ICD and runs virglrenderer's vtest server over the
  phone's own Vulkan driver; the guest gets VK_ICD_FILENAMES, VN_DEBUG=vtest, VTEST_SOCKET_NAME and
  MESA_VK_WSI_DEBUG=sw.
- Selection rule: Venus when Setup's "Mali (Venus)" is on, on a GPU that is neither an Adreno nor
  a system-driver one (PowerVR, Xclipse), and the apk carries it. It then replaces the Mali bridge
  and any open driver pair for the session, and the display stays on the phone's own driver.
  Auto is unchanged (the PanVK pair). Adreno never takes any of it.
- The compositor enables only the dma-buf extensions the driver has, logs a vendor driver's
  extension list, and gives a zero row pitch a packed row (his vk_present.c changes).
- The Mali compatibility layer is staged into the runtime on non-Adreno devices only.
- The component (vtest server, ICD, layer) comes from build-venus.yml as venus.tzst, published on
  The412Banner/droiddeck-nonadreno-drivers and pinned by sha in tools/venus/release.env.
- gamescope 3.16.29-p15 adds his shm upload patch (0127) next to 0126; pinned by sha.
- device.txt and graphics-report.txt name the route.

Co-authored-by: Dersim Abbas <derabb0620@gmail.com>

* Mali: Venus gamescope without robustness2, the bridge switch honoured and kept, clean driver switches

- gamescope 0128: VK_EXT_robustness2 is optional. A Mali driver through Venus has none, and
  gamescope stopped at "Missing required extension: VK_EXT_robustness2" (the wayland_surface error
  after it was only the knock-on). Without it, unused descriptor slots point at a 1x1 texture
  instead of VK_NULL_HANDLE. (David Cimo's Pixel 9 driver has robustness2, so his build never
  needed this.) gamescope component rebuilt and pinned by sha.
- Open-files limit: on a GPU that is not an Adreno the session script raises the soft limit to the
  hard limit for the whole session tree (a PanVK-kbase session froze on "Too many open files"
  after ten minutes) and graphics-report.txt shows before and after. A stopgap; the driver leak is
  fixed separately.
- The Mali bridge switch is honoured: when on and usable it wins over a PanVK pair for the
  session (Venus still wins over it). Selecting a pair no longer switches the bridge off, which is
  why the switch did not survive an app restart (Auto re-selected the pair at start). Setup says
  when this phone cannot use the bridge at all.
- Driver switching: picking a Mali pair by hand keeps the display on the phone's own driver, as
  Auto does (a PanVK Android display stalls on Mali gralloc at "Waiting for Steam's first frame",
  and stayed set after switching back); installing a bundle again replaces it instead of adding a
  "-2" copy beside the old one.
- graphics-report.txt names the runtime driver's folder and libraries, and the previous session's
  drivers, flagged when they changed.

* gamescope p16 (0128 robustness2 optional), pinned by sha; graphics-report says who chose the display driver

* Bundle replace only for open non-Adreno pairs; Adreno bundles keep their numbered copies

* Rebuilt open drivers reach phones: re-downloaded when their digest changes, release list hourly on non-Adreno

The non-Adreno driver releases replace their assets in place (the PanVK kbase sync-file fd leak
fix). A download is now remembered with its GitHub sha256, and an asset whose digest changed
counts as not installed, so Auto fetches it again and the bundle replaces the old one; the release
list is re-read after an hour instead of a day on a GPU that is not an Adreno.

* Mali compatibility layer: multiDrawIndirect, depthClipEnable and robustness2 for DXVK on Venus

A Galaxy A15 (Mali-G57) on Venus got gamescope and Steam up, but DXVK refused the GPU:
"Device does not support required feature 'multiDrawIndirect'". DXVK 3.1 stops at the first
missing feature, so the rest of its required list (dxvk_device_info.cpp) was checked against what
the testers' Mali drivers cannot have, and covered in the same pass, on top of David Cimo's six:
- multiDrawIndirect: reported, taken off the device, and an indirect draw with drawCount > 1 is
  recorded as single draws at offset + i * stride; maxDrawIndirectCount reported as 2^30.
  (drawIndirectCount is optional for DXVK and stays as the driver says.)
- VK_EXT_depth_clip_enable (required): offered when the driver lacks it; depthClipEnable off in a
  pipeline becomes depthClampEnable, and the extension's structures never reach the driver.
- VK_EXT_robustness2 missing entirely (gamescope saw the same on these phones): offered with
  robustBufferAccess2 (as robustBufferAccess, as before) and nullDescriptor, emulated by small
  stand-ins (a zeroed buffer, a 1x1 image) for VK_NULL_HANDLE buffers, image views and vertex
  buffers in plain, template and push descriptor writes and vertex-buffer binds. A null
  texel-buffer view stays null (its format is not known).
The layer logs every feature it emulates per device.

* Venus component 22694a38 (layer: multiDrawIndirect, depthClipEnable, robustness2), pinned by sha

* Non-Adreno round 3: bridge images, Venus GL, shared buffers, Steam GPU drawing

- vkbridge: the memory model skips lazily allocated types. Mali-G615 lists
  DEVICE_LOCAL|LAZILY_ALLOCATED first; taken as the device-local type it left
  images with no memory type (self-test "image clear/draw: setup" FAIL,
  gamescope "No compatible image memory type").
- Session: a bridge self-test that fails images or draws falls back to the
  runtime's driver pair for that session (BL_VKBRIDGE_FALLBACK_ICD); Setup
  and the graphics report say so.
- Venus: the Mali compatibility layer runs in every process but gamescope
  (DROIDDECK_MALI_COMPAT=1), so Zink in Steam and Xwayland gets
  nullDescriptor; null texel-buffer views get stand-ins too. Without
  nullDescriptor the session's GL goes to llvmpipe.
- gamescope 0129: a refused compute pipeline is named with its SPIR-V
  capabilities.
- Compositor: a buffer on two surfaces at once (gamescope's planes while a
  notification is up) is released only when the last one lets go.
- Open driver pairs: processes.txt timeline for the first three minutes;
  Setup "Steam interface: GPU drawing" turns off software web compositing.

* Pin gamescope p17 (0129) and Venus 55b30fbf

* Non-Adreno round 4: Mali GPU-drawing block, gamescope YCbCr retry, GL probe, bridge draw sync

- Setup's "Steam interface: GPU drawing" is hidden on Mali and a saved "on" is
  cleared: with PanVK it rebooted an Edge 60 (G615) as steamwebhelper started.
  Kept for Xclipse.
- gamescope 0130: a composite pipeline refused at start-up is retried with a
  layout without immutable YCbCr samplers (G615 through Venus refused every
  composite shader; their SPIR-V has no Float16, so fp16 was not the cause).
- Venus: droiddeck-glprobe opens GL through GLX the way the Steam client does,
  with the loader's reasons logged; when it fails the client's GL goes to
  llvmpipe.
- vkbridge self-test: the draw check waits for the render pass's stores before
  copying out (a tiler read zeros without the dependency).

* Pin gamescope p18 (0130)

* Non-Adreno round 5: gamescope memory fallback, Venus destroy guard, OpenAL depot

- gamescope 0131: DEVICE_LOCAL|HOST_VISIBLE requests fall back to host-visible
  memory (the bridge's unified-memory model lists none with both), with the
  request, type bits and memory types logged on failure; 0130's probe pipeline
  is kept and skipped when forced.
- Venus: GAMESCOPE_NO_YCBCR_SAMPLERS=1 from the start; virglrenderer ignores
  the destroy of a pipeline it never created instead of marking the context
  fatal (vtest server exit 137 on a Mali-G615).
- Steam's OpenAL depot (229020) maps to oalinst_dll, so games that list it
  (Hotline Miami) get OpenAL in their prefix.

* Pin gamescope p19 (0131) and Venus 6199a93f

* Non-Adreno round 6: PowerVR PRIME on old kernels, thermal, hang-up names, bridge flippable images, Venus Zink variants

- drm.c: PR #570's current PRIME ownership check (F_DUPFD_QUERY, then kcmp,
  then the F_SETOWN_EX owner marker): on a kernel before 6.10 with kcmp
  blocked, drmPrimeFDToHandle answered EOPNOTSUPP for every PowerVR import
  (Pixel 10, Android 17: Zink "failed drmPrimeFDToHandle", Xwayland error 7,
  gamescope X11 I/O error). The Mali stand-in node is kept.
- A /sys/class/thermal the kernel will not list gets an empty directory, so
  mangoapp no longer aborts on it.
- gamescope 0132: a hung-up waitable is named before the abort; 0133: the
  bridge's flippable images use supported-but-unexportable modifiers instead
  of asserting.
- Venus: when Zink does not start, the loader's view is logged and Zink is
  retried without ZINK_DEBUG=compact, with ZINK_DESCRIPTORS=auto and without
  kopper before falling back to llvmpipe.

* Pin gamescope p20 (0132, 0133)

* Non-Adreno round 7: bridge command-buffer guard, Venus Zink trace, PowerVR mangoapp, Xclipse label

- vkbridge server: every command buffer a device hands out is tracked; Begin,
  End (stream replay) and QueueSubmit refuse one it never allocated or has
  freed (VK_ERROR_DEVICE_LOST, logged) instead of passing it to the driver,
  where Mali's vkBeginCommandBuffer crashed the app (SIGSEGV 0x10, Steam's
  Zink on an Edge 60 and a Tab S11).
- vkbridge server: a fault inside the driver while serving a request cuts
  that client off (SIGSEGV/SIGBUS guard per request) and leaves its objects
  alone; the app and the other clients carry on. Other faults go to the
  previous handler.
- vkbridge server: the pipeline cache directory is copied; the JNI string it
  pointed at was freed (garbage in the cache path).
- Venus: DROIDDECK_MALI_COMPAT_TRACE=1 makes the Mali compatibility layer log
  what an application queries before vkCreateDevice; a failed glprobe adds a
  traced run and vulkaninfo --summary under the same environment.
- PowerVR: mangoapp draws with llvmpipe (Zink could not make it a swapchain
  and it crashed at every start).
- Setup: an Xclipse GPU reads "Experimental: RADV or the system Xclipse
  driver", not the PowerVR line.

* Pin Venus e40cd361 (layer trace)

* Non-Adreno round 8: bridge sharing fallback and crash detail, Venus diagnostics and 1.2 gate, compositor disconnect reasons, RADV upstream

- Mali bridge: the self-test fails "memory sharing" when the server offers
  no host-visible memory type (no sharing method passed, RP4 Pro G77); the
  session then falls back to the PanVK pair like a failed draw, and Setup
  says the bridge cannot share memory with that driver. Without a pair to
  fall back on, the log says so.
- Mali bridge: a guarded driver crash now logs the sub-command it was in,
  the fault address and pc (library + offset via dladdr), the command
  buffer's level, begin flags, pool flags and state, and the last 32
  replayed commands. Begin on an executable buffer from a pool without
  RESET_COMMAND_BUFFER_BIT is logged once (implicit reset).
- Venus: vulkan-summary.txt gets the device extension list and key
  features (full vulkaninfo in vulkan-full.txt); a failed GL probe runs
  once with VN_DEBUG=init,result, ZINK_DEBUG=mem, MESA_LOG_LEVEL=debug and
  the layer trace into glprobe-trace.txt. The Mali compatibility layer's
  trace covers every pre-device query (devices, memory, queue families,
  formats, image formats, external handles) and names the extensions.
- Venus: off when the phone's driver reports Vulkan below 1.2 (gamescope
  skips such a device); Setup and the graphics report say why and the
  session uses the PanVK pair.
- Compositor: libwayland's own disconnect reasons go to wayland.log, and a
  client's buffer may grow to 1 MB before a slow reader is dropped. A
  session that ended without teardown records Android's exit reasons.
- Drivers: RADV-Xclipse upstream (radv-xclipse-upstream) is a manual
  choice for Xclipse; Auto keeps radv-xclipse.

* Tests: the terminal-callers harness stubs the Quest layer and Cardboard modules and Android's system properties

* Pin gamescope p21 (main's patches + 0120-0133) and Venus a4d47cf3 (layer trace)

* Display driver Auto: Quest's patched Turnip first; the system driver only for a Mali, other GPUs keep the generic fallback

* Open driver pairs: the installed build's version, its upload date, and an Update when the release is rebuilt in place

- The release check records each asset's GitHub id and updated_at; a
  download records them (with the digest) for an open non-Adreno pair.
- Components > GPU drivers: an installed open pair shows its manifest
  version ("android <tag> + linux <commit>"), one not yet installed shows
  "built YYYY-MM-DD". A different digest, asset id or upload time on the
  same tag marks the installed pair "Update available" with an Update
  action: the pair is downloaded again and replaced in place, and stays
  selected only if it was. Adreno and DD-Turnip pairs are unchanged.
- graphics-report.txt: the pair release line gives the installed and the
  listed upload dates and flags a newer build; an exact bundle id match is
  preferred (RADV-Xclipse-upstream is not RADV-Xclipse).

* Session preload: drop oom_score_adj raises so lmkd does not treat games as cached apps

steam-launch-wrapper starts every game with --oom-score-adjust 900; on
Android 900 is CACHED_APP_MIN_ADJ, so lmkd kills the running game first
when memory runs short (and on Linux 6.1 the raise becomes the process's
permanent minimum). A process in the app cannot go below the score it
inherits, so the writes that succeed from inside are raises: every
write-open of /proc/<pid|self|thread-self>[/task/<tid>]/oom_score_adj (or
oom_adj), through open/openat or fopen, goes to /dev/null, logged once.

Based on the oom_score_adj redirect in the preload's opens.c by jdmg28 (https://github.com/jdmg28/DroidDeck-Mali/commit/6be00e00)

* Display: why presenting failed on the session-ended screen, and the display driver that really loaded

- The compositor records why it cannot present (no Vulkan driver loaded,
  vkCreateInstance/vkCreateDevice failed, no GPU or graphics queue, no
  swapchain on the screen with the driver's reason, device lost, GPU work
  unconfirmed). Each is a DD_PRESENT_FAULT line in wayland.log, read back
  over JNI or from wayland.log; the session-ended screen shows it instead
  of a black screen, and graphics-report.txt gets "!! DISPLAY FAILED". A
  first frame or a working swapchain clears it.
- After the display device is created, the driver that answered is logged
  from VkPhysicalDeviceDriverProperties (device, driverName, driverInfo,
  driver id, Vulkan version) and reported in graphics-report.txt. When a
  driver pair's display half was requested but a vendor driver answered
  (adrenotools falls back to the system driver when the requested one does
  not load), it says so.

Based on DD_PRESENT_FAULT in vk_present.c / waylandcomp_jni.c / SessionActivity by jdmg28 (https://github.com/jdmg28/DroidDeck-Mali/blob/arena/cd8ab18a-droiddeck-mali/app/src/main/cpp/waylandcomp/src/vk_present.c)
Based on the adrenotools silent-fallback finding by ryanistr (https://github.com/ryanistr/DroidDeck-Mali/blob/main/docs/development/panvk-mali-g77-bringup.md)

* tests: steam presentation test sets 0.5.0's steam_client

* Non-Adreno: find every driver pair, Venus before the bridge, fix the bridge's begin info

From the logs testers sent since c9ebb247:
- The app read the drivers repo's newest 15 releases only; the component releases (gamescope,
  Venus) pushed every PanVK pair and RADV-Xclipse past them, so Auto found no pair on any Mali
  and switched the Mali bridge on. The non-Adreno repo is now read in one page of 100.
- Auto's stand-in for a missing pair: Mali (Venus) where the apk carries it (Steam runs on it
  from the G57 to the G1-Ultra), the bridge otherwise, nothing on a driver below Vulkan 1.2. It
  no longer clears the Linux driver, does nothing when the list could not be read, records that
  it chose the route, and turns it off again once a pair is installed. A bridge that earlier
  builds left on under Auto is taken as Auto's.
- Mali bridge: vkBeginCommandBuffer sent its begin info without the count the server decodes, so
  Mali got a zeroed begin info with stale flags and crashed at 0x10 (Pixel 8 Pro G715, Lenovo
  G615, Xiaomi G925, Tab S11).
- Mali-G1 series (MT6993, arch v14) known by its chip; its label says Venus, not the bridge.
- A session Android killed for memory is said so on the next start (the S24 FE "crashes" were
  low-memory kills, not driver faults).
- The in-app updater never installs an official (Adreno-only) build over this test build.

* Venus: destroy the device's object mutex after the objects that lock it

Bionic aborts on locking a destroyed mutex ("pthread_mutex_lock called on a destroyed mutex",
Tab S9 FE G68, Pixel 9a), so a client that exited holding objects took the render worker down.
From BattleTempest's DroidDeck-Pixel (kevinbryant551-ux/DroidDeck-Pixel, GPL-3.0).

* release check: a session helper may be extracted to another runtime path

droiddeck-steam-taskset (#570) goes to usr/local/libexec/droiddeck-steam/taskset, where PATH puts
it in front of Steam's own taskset for the client only; 0.5.0's check wanted every droiddeck-*
helper at its own path.

* Venus component 93038b7d (destroyed-mutex fix)

* Update MaliBridge to v0.5.1 (#1135)

* Mali Auto: never leave a session on the runtime's Turnip

Logs from a Retroid Pocket 4 Pro (G77), Galaxy S21 Ultra (G78), Tab S11 Ultra
(G925) and Xiaomi G610 showed Auto ending on the runtime's Turnip, where
gamescope finds no GPU ("failed to find physical device"): after a pair's
trial rolled back, when the pair is on the bad list, and when the driver
list could not be read. In each case Auto now switches on its stand-in
(Venus, or the bridge) when no open driver, Venus or bridge is set.
Under Auto the Mali display also leaves any imported driver, not only a
pair's PanVK half (a lone PanVK_G720 import gave a black screen).

* Mali bridge: MaliBridge 224b6e36 (v0.5.3 source, by ASEbrahim)

From c65062b6 (v0.5.1). v0.5.2/v0.5.3: Steam mode on older Mali drivers
(G77/G710/G610/G57) gets past "starting display and audio", OpenGL 4.6 on
most Malis through dynamic-rendering and vertex-format emulation, Dimensity
9500 texture fixes, async pipeline compile, RE2 flicker on G925, DirectX on
the Pixel 8 family. JNI entry and session env names are unchanged.

* gamescope 0134: linear when the backend offers no modifier; Venus on Mesa 26.2.5

0134: CVulkanTexture::BInit asserted !modifiers.empty() when the nested Wayland
backend offered no modifier for a flippable image's format (NieR Replicant on a
Pixel 9a under Venus, session exit 134). It now tries linear and logs it.
Venus ICD: mesa-26.2.5 (venus TLS teardown from an unloaded driver, virtio-gpu
devices without 3D skipped); virglrenderer stays on 1.3.0.

* gamescope p22-nonadreno (0134 + main's 0116 cursor fix; build run 40159674290)

* CI: build the non-Adreno additions before the preload check

* build.gradle: drop verifyHandModel (main moved the hand models into the tracking pack)

* Venus component venus-proto13-e24ed8ab (Mesa 26.2.5; build run 40161447324)

* CI: fetch the Mali (Venus) component again (lost when build.yml took main's jobs)

Build a7a1ebf1 (run 40161734101) had no assets/venus or libvirgl_test_server.so, so
VenusComponent.available() was false and Auto's stand-in would have been the bridge.

* Auto: the Mali bridge stands in on a Vulkan 1.1 Mali driver

Auto refused both Venus and the bridge when the phone's driver reports Vulkan
below 1.2, so on the G77, G78 and G610 (r32p1/r38, Vulkan 1.1) a rolled-back or
missing pair left the runtime's Turnip: "failed to find physical device"
(Retroid Pocket 4 Pro after the JM pair's trial, Xiaomi 13T). Only Venus needs
1.2; the bridge raises the driver for gamescope and runs on these phones. A
Venus switch that cannot start on such a driver no longer counts as a route.

* Tests: stub main's g_release_unpaced in the DMA-BUF quarantine probe

The probe copies release_buffer out of compositor.c; since the merge it reads
g_release_unpaced, which the harness did not declare (setUpClass failed to compile).

* Update MaliBridge to v0.5.4 (ASEbrahim)

48477fe6 (tag v0.5.4): Dimensity 9500 green squares and red-tinted textures,
Balatro and other OpenGL text, fewer crashes when memory runs low, one screen
update per game frame, picture kept after a long background pause (SIGHUP no
longer stops the server), wrong colours after changing graphics settings on
the G720, more in the session report. The app-side changes of his DroidDeck
Mali app (Steam menus setting, per-game setup, Send logs, updates) are not
part of the MaliBridge repository and are not in this build.

* gamescope 0135: linear when the driver rejects every offered modifier

An r32p1 Mali-G610 (Vulkan 1.1) behind the Mali bridge answered both of the
backend's modifiers for AR24 with VK_ERROR_FORMAT_NOT_SUPPORTED, so the first
flippable image failed and gamescope asserted in vulkan_create_flat_texture
(Xiaomi 13T). Linear, when offered, is tried anyway; the bridge makes such
images without the handle type and exports them through a dma-heap. If the
image cannot be made, BInit fails as before.

* gamescope: pin the non-Adreno p23 build (0135)

* Tests: the terminal-callers harness stubs take_shm's game-frame detection

Main's take_shm now reads surface damage, parent/role/mapped and the HUD state
to spot game frames; the harness declares them so the copied function compiles
(setUpClass failed in Build APK run 40505286127). No damage, so it stays off.

* gamescope: number the test branch's patches 0920-0935

Main now has its own 0121-0125 (window override walk, host-event wake, commit fences, done at
import, HUD frame times), which sorted in between this branch's 0120-0135. The branch's sixteen
patches move to 0920-0935 with the same last two digits, so they apply after main's set and stay
clear of its next numbers. Applying all 38 to gamescope 3.16.29 in the old order and the new one
gives the same tree (checked with patch -p1, as build-in-arch.sh does). PATCHES.md and the one
code comment that named 0130 follow the new numbers.

* check_session_assets: helpers count in usr/local/bin or the Steam taskset folder only

The merge kept this branch's pattern (any usr/ target), which main's new test rejects: a helper
extracted into a subfolder of usr/local/bin must not count. The pattern now takes usr/local/bin
under any name, as on main, plus usr/local/libexec/droiddeck-steam for droiddeck-steam-taskset.
Every helper in the overlay is still found extracted in SessionFiles.kt.

* gamescope: pin 3.16.29 p24 (non-Adreno)

Built from this branch @d13b9d88 (run 41119284267): main a5b035b2's patches plus this branch's,
now 0920-0935. All 38 applied, gamescope's tests 2/2. sha256 1d1088d4.

* Update MaliBridge to v0.5.4.2 (ASEbrahim)

95a1e600 (tag v0.5.4.2), was v0.5.4 (48477fe6). For the bridge: memory sharing without the handle
type where that is all the self-test passed (unflagged buffers, client/memory.c, server_memory.c),
the older-Mali (G52-G77) game-mode start fixes, the r38p1 beta geometry-shader erratum (gs_hide),
present timeouts and an API cap per process. Client, server and the in-app library all build from
the submodule with MaliBridge's own scripts, which did not change; the protocol only gained
fields an older server sends as 0.

* Session end: the compositor fault query no longer fails the hint when the native library is absent

presentationFault() (6778a224) called WaylandCompositor.compositorFault() directly. Main's new
SessionEndHintTest runs sessionEndHint() in Robolectric, where libdroiddeckwayland cannot load, so
all six cases ended in UnsatisfiedLinkError (Build APK run 41125749537). The call is now wrapped
like runtimeDamageHint()'s, and without an answer the hint reads wayland.log as before.

* test: stub the GPU busy reader in the caller harness

* fix: release build is not debuggable, Mali uses the system display driver, staging failure ends its own session

* fix: address non-Adreno review findings

* fix: preserve current gamescope and GPU warning behavior

* fix: retain graphics failure hints and launch diagnostics

* fix: identify non-Adreno GPUs in driver failure hints

* test: harnesses follow the external client barrier and effects upscaling changes

* fix: client sources return to foreign ownership after the overlay draws

---------

Co-authored-by: Leask Wong <i@leaskh.com>
Co-authored-by: wallentx <william.allentx@gmail.com>
Co-authored-by: Stefan Zijlstra <6730062+stefanz92@users.noreply.github.com>
Co-authored-by: William Allen <wallentx@users.noreply.github.com>
Co-authored-by: The412Banner <the412banner@users.noreply.github.com>
Co-authored-by: Dersim Abbas <derabb0620@gmail.com>
Co-authored-by: root <root@localhost.localdomain>
Co-authored-by: ASEbrahim <ahmadsmain@gmail.com>
Co-authored-by: The412Banner <the412banner@gmail.com>
Co-authored-by: The412Banner <205237651+The412Banner@users.noreply.github.com>
This commit is contained in:
215 files changed
+19024 -428

No files matched your search

@@ -11,6 +11,7 @@ add_library(droiddeckwayland SHARED
src/gpu_clock_pin.c
src/droiddeck_ext.c
src/wl_dmabuf.c
src/wl_android_buffer.c
src/wl_clipboard.c
src/wl_text_input.c
src/wl_toplevel_icon.c
@@ -22,6 +23,7 @@ add_library(droiddeckwayland SHARED
generated/color-management-v1-protocol.c
generated/xdg-shell-protocol.c
generated/linux-dmabuf-v1-protocol.c
generated/wayland-android-protocol.c
generated/viewporter-protocol.c
generated/banner-desktop-v1-protocol.c
generated/presentation-time-protocol.c
@@ -0,0 +1,104 @@
/* Generated by wayland-scanner 1.26.0 */
/*
* Copyright © 2012 Collabora, Ltd.
*
* Permission to use, copy, modify, distribute, and sell this
* software and its documentation for any purpose is hereby granted
* without fee, provided that the above copyright notice appear in
* all copies and that both that copyright notice and this permission
* notice appear in supporting documentation, and that the name of
* the copyright holders not be used in advertising or publicity
* pertaining to distribution of the software without specific,
* written prior permission. The copyright holders make no
* representations about the suitability of this software for any
* purpose. It is provided "as is" without express or implied
* warranty.
*
* THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS
* SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS, IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY
* SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
* AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
* ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
* THIS SOFTWARE.
*/
#include <stdbool.h>
#include <stdlib.h>
#include <stdint.h>
#include "wayland-util.h"
#ifndef __has_attribute
# define __has_attribute(x) 0 /* Compatibility with non-clang compilers. */
#endif
#if (__has_attribute(visibility) || defined(__GNUC__) && __GNUC__ >= 4)
#define WL_PRIVATE __attribute__ ((visibility("hidden")))
#else
#define WL_PRIVATE
#endif
extern const struct wl_interface android_wlegl_handle_interface;
extern const struct wl_interface android_wlegl_server_buffer_handle_interface;
extern const struct wl_interface wl_buffer_interface;
static const struct wl_interface *android_types[] = {
NULL,
NULL,
&android_wlegl_handle_interface,
NULL,
NULL,
&wl_buffer_interface,
NULL,
NULL,
NULL,
NULL,
NULL,
&android_wlegl_handle_interface,
&android_wlegl_server_buffer_handle_interface,
NULL,
NULL,
NULL,
NULL,
&wl_buffer_interface,
NULL,
NULL,
};
static const struct wl_message android_wlegl_requests[] = {
{ "create_handle", "nia", android_types + 2 },
{ "create_buffer", "niiiiio", android_types + 5 },
{ "get_server_buffer_handle", "2niiii", android_types + 12 },
};
WL_PRIVATE const struct wl_interface android_wlegl_interface = {
"android_wlegl", 3,
3, android_wlegl_requests,
0, NULL,
};
static const struct wl_message android_wlegl_handle_requests[] = {
{ "add_fd", "h", android_types + 0 },
{ "destroy", "", android_types + 0 },
};
WL_PRIVATE const struct wl_interface android_wlegl_handle_interface = {
"android_wlegl_handle", 1,
2, android_wlegl_handle_requests,
0, NULL,
};
static const struct wl_message android_wlegl_server_buffer_handle_events[] = {
{ "buffer_fd", "h", android_types + 0 },
{ "buffer_ints", "a", android_types + 0 },
{ "buffer", "nii", android_types + 17 },
{ "linear_layout", "3uu", android_types + 0 },
};
WL_PRIVATE const struct wl_interface android_wlegl_server_buffer_handle_interface = {
"android_wlegl_server_buffer_handle", 3,
0, NULL,
4, android_wlegl_server_buffer_handle_events,
};
@@ -0,0 +1,341 @@
/* Generated by wayland-scanner 1.26.0 */
#ifndef ANDROID_SERVER_PROTOCOL_H
#define ANDROID_SERVER_PROTOCOL_H
#include <stdint.h>
#include <stddef.h>
#include "wayland-server.h"
#ifdef __cplusplus
extern "C" {
#endif
struct wl_client;
struct wl_resource;
/**
* @page page_android The android protocol
* @section page_ifaces_android Interfaces
* - @subpage page_iface_android_wlegl - Android EGL graphics buffer support
* - @subpage page_iface_android_wlegl_handle - An Android native_handle_t object
* - @subpage page_iface_android_wlegl_server_buffer_handle - a server allocated buffer
* @section page_copyright_android Copyright
* <pre>
*
* Copyright © 2012 Collabora, Ltd.
*
* Permission to use, copy, modify, distribute, and sell this
* software and its documentation for any purpose is hereby granted
* without fee, provided that the above copyright notice appear in
* all copies and that both that copyright notice and this permission
* notice appear in supporting documentation, and that the name of
* the copyright holders not be used in advertising or publicity
* pertaining to distribution of the software without specific,
* written prior permission. The copyright holders make no
* representations about the suitability of this software for any
* purpose. It is provided "as is" without express or implied
* warranty.
*
* THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS
* SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS, IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY
* SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
* AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
* ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
* THIS SOFTWARE.
* </pre>
*/
struct android_wlegl;
struct android_wlegl_handle;
struct android_wlegl_server_buffer_handle;
struct wl_buffer;
#ifndef ANDROID_WLEGL_INTERFACE
#define ANDROID_WLEGL_INTERFACE
/**
* @page page_iface_android_wlegl android_wlegl
* @section page_iface_android_wlegl_desc Description
*
* Interface used in the Android wrapper libEGL to share
* graphics buffers between the server and the client.
* @section page_iface_android_wlegl_api API
* See @ref iface_android_wlegl.
*/
/**
* @defgroup iface_android_wlegl The android_wlegl interface
*
* Interface used in the Android wrapper libEGL to share
* graphics buffers between the server and the client.
*/
extern const struct wl_interface android_wlegl_interface;
#endif
#ifndef ANDROID_WLEGL_HANDLE_INTERFACE
#define ANDROID_WLEGL_HANDLE_INTERFACE
/**
* @page page_iface_android_wlegl_handle android_wlegl_handle
* @section page_iface_android_wlegl_handle_desc Description
*
* The Android native_handle_t is a semi-opaque object, that
* contains an EGL implementation specific number of int32
* values and file descriptors.
*
* We cannot send a variable size array of file descriptors
* over the Wayland protocol, so we send them one by one.
* @section page_iface_android_wlegl_handle_api API
* See @ref iface_android_wlegl_handle.
*/
/**
* @defgroup iface_android_wlegl_handle The android_wlegl_handle interface
*
* The Android native_handle_t is a semi-opaque object, that
* contains an EGL implementation specific number of int32
* values and file descriptors.
*
* We cannot send a variable size array of file descriptors
* over the Wayland protocol, so we send them one by one.
*/
extern const struct wl_interface android_wlegl_handle_interface;
#endif
#ifndef ANDROID_WLEGL_SERVER_BUFFER_HANDLE_INTERFACE
#define ANDROID_WLEGL_SERVER_BUFFER_HANDLE_INTERFACE
/**
* @page page_iface_android_wlegl_server_buffer_handle android_wlegl_server_buffer_handle
* @section page_iface_android_wlegl_server_buffer_handle_desc Description
*
* On creation a server_side_buffer object will immediately send
* the "buffer_fd" and "buffer_ints" events needed by the client to
* reference the gralloc buffer, followed by the "buffer" event carrying
* the wl_buffer object.
* @section page_iface_android_wlegl_server_buffer_handle_api API
* See @ref iface_android_wlegl_server_buffer_handle.
*/
/**
* @defgroup iface_android_wlegl_server_buffer_handle The android_wlegl_server_buffer_handle interface
*
* On creation a server_side_buffer object will immediately send
* the "buffer_fd" and "buffer_ints" events needed by the client to
* reference the gralloc buffer, followed by the "buffer" event carrying
* the wl_buffer object.
*/
extern const struct wl_interface android_wlegl_server_buffer_handle_interface;
#endif
#ifndef ANDROID_WLEGL_ERROR_ENUM
#define ANDROID_WLEGL_ERROR_ENUM
enum android_wlegl_error {
ANDROID_WLEGL_ERROR_BAD_HANDLE = 0,
ANDROID_WLEGL_ERROR_BAD_VALUE = 1,
};
#endif /* ANDROID_WLEGL_ERROR_ENUM */
#ifndef ANDROID_WLEGL_ERROR_ENUM_IS_VALID
#define ANDROID_WLEGL_ERROR_ENUM_IS_VALID
/**
* @ingroup iface_android_wlegl
* Validate a android_wlegl error value.
*
* @return true on success, false on error.
* @ref android_wlegl_error
*/
static inline bool
android_wlegl_error_is_valid(uint32_t value, uint32_t version) {
switch (value) {
case ANDROID_WLEGL_ERROR_BAD_HANDLE:
return version >= 1;
case ANDROID_WLEGL_ERROR_BAD_VALUE:
return version >= 1;
default:
return false;
}
}
#endif /* ANDROID_WLEGL_ERROR_ENUM_IS_VALID */
/**
* @ingroup iface_android_wlegl
* @struct android_wlegl_interface
*/
struct android_wlegl_interface {
/**
* Create an Android native_handle_t object
*
* This creator method initialises the native_handle_t object
* with everything except the file descriptors, which have to be
* submitted separately.
* @param ints an array of int32_t
*/
void (*create_handle)(struct wl_client *client,
struct wl_resource *resource,
uint32_t id,
int32_t num_fds,
struct wl_array *ints);
/**
* Create a wl_buffer from the native handle
*
* Pass the Android native_handle_t to the server and attach it
* to the new wl_buffer object.
*
* The android_wlegl_handle object must be destroyed immediately
* after this request.
*/
void (*create_buffer)(struct wl_client *client,
struct wl_resource *resource,
uint32_t id,
int32_t width,
int32_t height,
int32_t stride,
int32_t format,
int32_t usage,
struct wl_resource *native_handle);
/**
* @since 2
*/
void (*get_server_buffer_handle)(struct wl_client *client,
struct wl_resource *resource,
uint32_t id,
int32_t width,
int32_t height,
int32_t format,
int32_t usage);
};
/**
* @ingroup iface_android_wlegl
*/
#define ANDROID_WLEGL_CREATE_HANDLE_SINCE_VERSION 1
/**
* @ingroup iface_android_wlegl
*/
#define ANDROID_WLEGL_CREATE_BUFFER_SINCE_VERSION 1
/**
* @ingroup iface_android_wlegl
*/
#define ANDROID_WLEGL_GET_SERVER_BUFFER_HANDLE_SINCE_VERSION 2
#ifndef ANDROID_WLEGL_HANDLE_ERROR_ENUM
#define ANDROID_WLEGL_HANDLE_ERROR_ENUM
enum android_wlegl_handle_error {
ANDROID_WLEGL_HANDLE_ERROR_TOO_MANY_FDS = 0,
};
#endif /* ANDROID_WLEGL_HANDLE_ERROR_ENUM */
#ifndef ANDROID_WLEGL_HANDLE_ERROR_ENUM_IS_VALID
#define ANDROID_WLEGL_HANDLE_ERROR_ENUM_IS_VALID
/**
* @ingroup iface_android_wlegl_handle
* Validate a android_wlegl_handle error value.
*
* @return true on success, false on error.
* @ref android_wlegl_handle_error
*/
static inline bool
android_wlegl_handle_error_is_valid(uint32_t value, uint32_t version) {
switch (value) {
case ANDROID_WLEGL_HANDLE_ERROR_TOO_MANY_FDS:
return version >= 1;
default:
return false;
}
}
#endif /* ANDROID_WLEGL_HANDLE_ERROR_ENUM_IS_VALID */
/**
* @ingroup iface_android_wlegl_handle
* @struct android_wlegl_handle_interface
*/
struct android_wlegl_handle_interface {
/**
*/
void (*add_fd)(struct wl_client *client,
struct wl_resource *resource,
int32_t fd);
/**
*/
void (*destroy)(struct wl_client *client,
struct wl_resource *resource);
};
/**
* @ingroup iface_android_wlegl_handle
*/
#define ANDROID_WLEGL_HANDLE_ADD_FD_SINCE_VERSION 1
/**
* @ingroup iface_android_wlegl_handle
*/
#define ANDROID_WLEGL_HANDLE_DESTROY_SINCE_VERSION 1
#define ANDROID_WLEGL_SERVER_BUFFER_HANDLE_BUFFER_FD 0
#define ANDROID_WLEGL_SERVER_BUFFER_HANDLE_BUFFER_INTS 1
#define ANDROID_WLEGL_SERVER_BUFFER_HANDLE_BUFFER 2
#define ANDROID_WLEGL_SERVER_BUFFER_HANDLE_LINEAR_LAYOUT 3
/**
* @ingroup iface_android_wlegl_server_buffer_handle
*/
#define ANDROID_WLEGL_SERVER_BUFFER_HANDLE_BUFFER_FD_SINCE_VERSION 1
/**
* @ingroup iface_android_wlegl_server_buffer_handle
*/
#define ANDROID_WLEGL_SERVER_BUFFER_HANDLE_BUFFER_INTS_SINCE_VERSION 1
/**
* @ingroup iface_android_wlegl_server_buffer_handle
*/
#define ANDROID_WLEGL_SERVER_BUFFER_HANDLE_BUFFER_SINCE_VERSION 1
/**
* @ingroup iface_android_wlegl_server_buffer_handle
*/
#define ANDROID_WLEGL_SERVER_BUFFER_HANDLE_LINEAR_LAYOUT_SINCE_VERSION 3
/**
* @ingroup iface_android_wlegl_server_buffer_handle
* Sends an buffer_fd event to the client owning the resource.
* @param resource_ The client's resource
*/
static inline void
android_wlegl_server_buffer_handle_send_buffer_fd(struct wl_resource *resource_, int32_t fd)
{
wl_resource_post_event(resource_, ANDROID_WLEGL_SERVER_BUFFER_HANDLE_BUFFER_FD, fd);
}
/**
* @ingroup iface_android_wlegl_server_buffer_handle
* Sends an buffer_ints event to the client owning the resource.
* @param resource_ The client's resource
*/
static inline void
android_wlegl_server_buffer_handle_send_buffer_ints(struct wl_resource *resource_, struct wl_array *ints)
{
wl_resource_post_event(resource_, ANDROID_WLEGL_SERVER_BUFFER_HANDLE_BUFFER_INTS, ints);
}
/**
* @ingroup iface_android_wlegl_server_buffer_handle
* Sends an buffer event to the client owning the resource.
* @param resource_ The client's resource
*/
static inline void
android_wlegl_server_buffer_handle_send_buffer(struct wl_resource *resource_, struct wl_resource *buffer, int32_t format, int32_t stride)
{
wl_resource_post_event(resource_, ANDROID_WLEGL_SERVER_BUFFER_HANDLE_BUFFER, buffer, format, stride);
}
/**
* @ingroup iface_android_wlegl_server_buffer_handle
* Sends an linear_layout event to the client owning the resource.
* @param resource_ The client's resource
*/
static inline void
android_wlegl_server_buffer_handle_send_linear_layout(struct wl_resource *resource_, uint32_t drm_format, uint32_t stride)
{
wl_resource_post_event(resource_, ANDROID_WLEGL_SERVER_BUFFER_HANDLE_LINEAR_LAYOUT, drm_format, stride);
}
#ifdef __cplusplus
}
#endif
#endif
@@ -0,0 +1,139 @@
<?xml version="1.0" encoding="UTF-8"?>
<protocol name="android">
<copyright>
Copyright © 2012 Collabora, Ltd.
Permission to use, copy, modify, distribute, and sell this
software and its documentation for any purpose is hereby granted
without fee, provided that the above copyright notice appear in
all copies and that both that copyright notice and this permission
notice appear in supporting documentation, and that the name of
the copyright holders not be used in advertising or publicity
pertaining to distribution of the software without specific,
written prior permission. The copyright holders make no
representations about the suitability of this software for any
purpose. It is provided "as is" without express or implied
warranty.
THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS
SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS, IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY
SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
THIS SOFTWARE.
</copyright>
<interface name="android_wlegl" version="3">
<description summary="Android EGL graphics buffer support">
Interface used in the Android wrapper libEGL to share
graphics buffers between the server and the client.
</description>
<enum name="error">
<entry name="bad_handle" value="0" />
<entry name="bad_value" value="1" />
</enum>
<request name="create_handle">
<description summary="Create an Android native_handle_t object">
This creator method initialises the native_handle_t object
with everything except the file descriptors, which have to be
submitted separately.
</description>
<arg name="id" type="new_id" interface="android_wlegl_handle" />
<arg name="num_fds" type="int" />
<arg name="ints" type="array" summary="an array of int32_t" />
</request>
<request name="create_buffer">
<description summary="Create a wl_buffer from the native handle">
Pass the Android native_handle_t to the server and attach it
to the new wl_buffer object.
The android_wlegl_handle object must be destroyed immediately
after this request.
</description>
<arg name="id" type="new_id" interface="wl_buffer" />
<arg name="width" type="int" />
<arg name="height" type="int" />
<arg name="stride" type="int" />
<arg name="format" type="int" />
<arg name="usage" type="int" />
<arg name="native_handle" type="object" interface="android_wlegl_handle" />
</request>
<request name="get_server_buffer_handle" since="2">
<arg name="id" type="new_id" interface="android_wlegl_server_buffer_handle"/>
<arg name="width" type="int"/>
<arg name="height" type="int"/>
<arg name="format" type="int"/>
<arg name="usage" type="int"/>
</request>
</interface>
<interface name="android_wlegl_handle" version="1">
<description summary="An Android native_handle_t object">
The Android native_handle_t is a semi-opaque object, that
contains an EGL implementation specific number of int32
values and file descriptors.
We cannot send a variable size array of file descriptors
over the Wayland protocol, so we send them one by one.
</description>
<enum name="error">
<entry name="too_many_fds" value="0" />
</enum>
<request name="add_fd">
<arg name="fd" type="fd" />
</request>
<request name="destroy" type="destructor" />
</interface>
<interface name="android_wlegl_server_buffer_handle" version="3">
<description summary="a server allocated buffer">
On creation a server_side_buffer object will immediately send
the "buffer_fd" and "buffer_ints" events needed by the client to
reference the gralloc buffer, followed by the "buffer" event carrying
the wl_buffer object.
</description>
<event name="buffer_fd">
<arg name="fd" type="fd"/>
</event>
<event name="buffer_ints">
<arg name="ints" type="array"/>
</event>
<event name="buffer">
<description summary="the wl_buffer">
This event will be sent after the ints and all the fds have been sent
</description>
<arg name="buffer" type="new_id" interface="wl_buffer"/>
<arg name="format" type="int"/>
<arg name="stride" type="int"/>
</event>
<event name="linear_layout" since="3">
<description summary="verified single-plane linear allocation">
Optional metadata sent before the buffer event. The first buffer_fd
contains one uncompressed 32-bit RGB plane at byte offset zero.
drm_format is its DRM FourCC and stride is its row pitch in bytes.
The server has verified the layout and allocation bounds using
Android mapper metadata, not inferred them from opaque handle ints.
Absence of this event means the layout is unspecified.
</description>
<arg name="drm_format" type="uint"/>
<arg name="stride" type="uint"/>
</event>
</interface>
</protocol>
@@ -79,6 +79,9 @@ static struct ahb_buf *find_buf(uint64_t id) {
}
static void buf_free(struct ahb_buf *ab) {
/* A display release does not prove the compositor's Vulkan reads finished.
* Keep the AHB reference and its DMA-BUF record even if the client is gone. */
if (vkp_completion_unknown()) return;
if (ab->resource) { wl_list_remove(&ab->resource_destroy.link); ab->resource = NULL; }
if (ab->fence_src) { wl_event_source_remove(ab->fence_src); ab->fence_src = NULL; }
if (ab->fence_fd >= 0) { close(ab->fence_fd); ab->fence_fd = -1; }
@@ -103,6 +106,7 @@ static void on_buffer_resource_destroyed(struct wl_listener *l, void *data) {
static void send_deferred_release(struct ahb_buf *ab) {
if (vkp_completion_unknown()) return;
if (ab->release_pending && ab->resource)
droiddeck_release_buffer(ab->surface, ab->resource, ab->surface != NULL, ab->deferred_ns);
ab->release_pending = 0;
+102 -16
View File
@@ -154,6 +154,16 @@ static void on_client_destroyed(struct wl_listener *l, void *data) {
free(ci);
}
/* libwayland's own reasons for dropping a client (a failed read or flush, an invalid object, a
* malformed request) go through wl_log, which on Android writes to a closed stderr. */
static void wl_log_to_session(const char *fmt, va_list ap) {
char line[512];
vsnprintf(line, sizeof(line), fmt, ap);
size_t n = strlen(line);
while (n && (line[n - 1] == '\n' || line[n - 1] == '\r')) line[--n] = 0;
droiddeck_log("program", "libwayland: %s", line);
}
static void on_client_created(struct wl_listener *l, void *data) {
struct wl_client *client = data;
struct client_info *ci = calloc(1, sizeof(*ci));
@@ -349,6 +359,62 @@ static void perf_note_release(int64_t since_ns) {
}
/* Completion-unknown is terminal for externally owned DMA-BUF contents too.
* Keeping a VkImage alone cannot stop the client from overwriting its backing
* memory after wl_buffer.release. All paths (including cursors and idle roles)
* use this gate; copied SHM buffers retain their normal release behaviour. */
static struct dmabuf_buffer *get_dmabuf(struct wl_resource *buffer);
static int buffer_release_blocked(struct wl_resource *buffer) {
return vkp_completion_unknown() && get_dmabuf(buffer) != NULL;
}
/* Buffer tracing on a GPU that is not an Adreno (no KGSL node): every attach and release of the
* first 400 buffer events, by wl_buffer id and the line that sent it, and any release of a buffer
* already released and not attached again since (gamescope: "Compositor released us but we were
* not acquired"). Off on an Adreno. */
static int g_buf_trace = -1;
static int g_buf_trace_left = 400;
static uint32_t g_released_ids[128];
static int buf_trace_on(void) {
if (g_buf_trace < 0) g_buf_trace = access("/dev/kgsl-3d0", F_OK) != 0;
return g_buf_trace;
}
static void buf_trace_attach(struct wl_resource *buffer) {
if (!buffer || !buf_trace_on()) return;
uint32_t id = wl_resource_get_id(buffer);
for (int i = 0; i < 128; i++) if (g_released_ids[i] == id) g_released_ids[i] = 0;
if (g_buf_trace_left > 0) { g_buf_trace_left--; droiddeck_log("buffer", "attach id %u", id); }
}
static void buf_trace_release(struct wl_resource *buffer, int line) {
if (!buffer || !buf_trace_on()) return;
uint32_t id = wl_resource_get_id(buffer);
int twice = 0, slot = -1;
for (int i = 0; i < 128; i++) {
if (g_released_ids[i] == id) twice = 1;
if (slot < 0 && g_released_ids[i] == 0) slot = i;
}
if (twice) droiddeck_log("buffer", "DOUBLE release id %u (line %d): released again without an attach", id, line);
else if (slot >= 0) g_released_ids[slot] = id;
if (g_buf_trace_left > 0) { g_buf_trace_left--; droiddeck_log("buffer", "release id %u (line %d)", id, line); }
}
#define send_buffer_release(b) send_buffer_release_at((b), __LINE__)
static void send_buffer_release_at(struct wl_resource *buffer, int line) {
if (!buffer_release_blocked(buffer)) { buf_trace_release(buffer, line); wl_buffer_send_release(buffer); }
}
/* Whether a surface other than `except` is showing this buffer right now. gamescope's Wayland
* backend moves one buffer between its planes (the game's frame goes from the window to a
* subsurface above a black backing while a Steam notification is up): releasing it when the first
* surface lets go handed gamescope a buffer still on screen ("Compositor released us but we were
* not acquired"). Only the last surface to let go releases it. */
static int buffer_shown_elsewhere(struct wl_resource *buffer, const struct surface *except) {
struct surface *o;
if (!buffer) return 0;
wl_list_for_each(o, &g_surfaces, link)
if (o != except && o->dmabuf == buffer) return 1;
return 0;
}
static void pending_release_free(struct pending_release *pr) {
if (pr->surface && pr->surface->releases_pending > 0) pr->surface->releases_pending--;
wl_list_remove(&pr->destroy.link);
@@ -372,7 +438,8 @@ static void arm_release_timer(void) {
int64_t earliest = 0;
if (g_release_timer_fd < 0) return;
wl_list_for_each(pr, &g_pending_releases, link)
if (!earliest || pr->at_ns < earliest) earliest = pr->at_ns;
if (!buffer_release_blocked(pr->buffer) && (!earliest || pr->at_ns < earliest))
earliest = pr->at_ns;
struct itimerspec its = {0};
if (earliest) { its.it_value.tv_sec = earliest / 1000000000LL; its.it_value.tv_nsec = earliest % 1000000000LL; }
timerfd_settime(g_release_timer_fd, TFD_TIMER_ABSTIME, &its, NULL);
@@ -384,8 +451,13 @@ static int on_release_timer(int fd, uint32_t mask, void *data) {
int64_t now = now_ns() + 300000;
if (read(fd, &expirations, sizeof(expirations)) < 0 && errno != EAGAIN) return 0;
wl_list_for_each_safe(pr, tmp, &g_pending_releases, link) {
if (pr->at_ns <= now) {
wl_buffer_send_release(pr->buffer);
if (pr->at_ns <= now && !buffer_release_blocked(pr->buffer)) {
/* Attached again since (to its surface or another): that surface releases it later. */
if (buffer_shown_elsewhere(pr->buffer, NULL)) {
pending_release_free(pr);
continue;
}
send_buffer_release(pr->buffer);
perf_note_release(pr->since_ns);
pending_release_free(pr);
}
@@ -396,9 +468,12 @@ static int on_release_timer(int fd, uint32_t mask, void *data) {
}
static void release_buffer(struct surface *s, struct wl_resource *buffer, int64_t since_ns) {
/* No allocation or immediate-release fallback is allowed for a quarantined
* DMA-BUF. Existing queued releases stay held; their timer is disarmed. */
if (buffer_release_blocked(buffer)) return;
const int limit = g_fps_limit;
const int64_t interval = limit > 0 ? 1000000000LL / limit : g_refresh_ns;
if (g_release_unpaced || interval <= 0 || g_release_timer_fd < 0) { wl_buffer_send_release(buffer); perf_note_release(since_ns); return; }
if (g_release_unpaced || interval <= 0 || g_release_timer_fd < 0) { send_buffer_release(buffer); perf_note_release(since_ns); return; }
int64_t now = now_ns();
int64_t at = s->next_release_ns + interval;
int64_t latest = now + interval * (int64_t)(s->releases_pending + 1);
@@ -406,7 +481,7 @@ static void release_buffer(struct surface *s, struct wl_resource *buffer, int64_
if (at > latest) at = latest;
s->next_release_ns = at;
struct pending_release *pr = calloc(1, sizeof(*pr));
if (!pr) { wl_buffer_send_release(buffer); perf_note_release(since_ns); return; }
if (!pr) { send_buffer_release(buffer); perf_note_release(since_ns); return; }
pr->buffer = buffer;
pr->surface = s;
pr->at_ns = at;
@@ -523,7 +598,10 @@ static void constraints_focus_entered(struct wl_resource *target, struct wl_clie
void dmabuf_buffer_unref(struct dmabuf_buffer *b) {
if (!b || --b->refs > 0) return;
/* Surface/client destruction must not close the backing FDs or free the
* imported-buffer record while a GPU read may still be pending. Retain the
* reference without allocating a quarantine node; process exit reclaims it. */
if (!b || vkp_completion_unknown() || --b->refs > 0) return;
vkp_image_destroy(b->img);
for (int i = 0; i < b->n_planes; i++)
if (b->fd[i] >= 0) close(b->fd[i]);
@@ -622,9 +700,10 @@ static void unmap_toplevel(struct surface *s) {
static void drop_dmabuf(struct surface *s, int paced) {
if (s->dmabuf) {
wl_list_remove(&s->dmabuf_destroy.link);
if (!ahb_swapchain_defer_release(s->dmabuf_buf, s->dmabuf, s, paced)) {
if (buffer_shown_elsewhere(s->dmabuf, s)) {
} else if (!ahb_swapchain_defer_release(s->dmabuf_buf, s->dmabuf, s, paced)) {
if (paced) release_buffer(s, s->dmabuf, now_ns());
else wl_buffer_send_release(s->dmabuf);
else send_buffer_release(s->dmabuf);
}
s->dmabuf = NULL;
}
@@ -733,7 +812,7 @@ static void take_shm(struct surface *s, struct wl_shm_buffer *shm, struct wl_res
vkp_image_upload_shm(s->shm_img, wl_shm_buffer_get_data(shm), stride);
wl_shm_buffer_end_access(shm);
}
wl_buffer_send_release(buffer);
send_buffer_release(buffer);
s->buf_w = w;
s->buf_h = h;
s->buf_alpha = wl_shm_buffer_get_format(shm) == WL_SHM_FORMAT_ARGB8888;
@@ -777,7 +856,7 @@ static void take_pixel(struct surface *s, const uint8_t bgra[4], struct wl_resou
}
if (!s->shm_img) s->shm_img = vkp_image_create_shm(1, 1);
if (s->shm_img) vkp_image_upload_shm(s->shm_img, bgra, 4);
wl_buffer_send_release(buffer);
send_buffer_release(buffer);
s->buf_w = 1;
s->buf_h = 1;
s->buf_alpha = bgra[3] != 0xff;
@@ -880,8 +959,9 @@ void **droiddeck_dmabuf_ahb_slot(struct dmabuf_buffer *b) { return &b->ahb_state
void droiddeck_dmabuf_ref(struct dmabuf_buffer *b) { b->refs++; }
void droiddeck_dmabuf_unref(struct dmabuf_buffer *b) { dmabuf_buffer_unref(b); }
void droiddeck_release_buffer(struct surface *s, struct wl_resource *buffer, int paced, int64_t since_ns) {
if (buffer_release_blocked(buffer)) return;
if (paced && s) release_buffer(s, buffer, since_ns);
else { wl_buffer_send_release(buffer); perf_note_release(since_ns); }
else { send_buffer_release(buffer); perf_note_release(since_ns); }
}
void droiddeck_surface_describe(const struct surface *s, char *out, size_t size) { describe(s, out, size); }
const struct droiddeck_color *droiddeck_surface_color(const struct surface *s) {
@@ -1101,7 +1181,7 @@ static void surface_hold_idle(struct surface *s, struct wl_resource *buffer) {
struct wl_shm_buffer *shm = db ? NULL : wl_shm_buffer_get(buffer);
int64_t px = db ? (int64_t)db->width * db->height
: shm ? (int64_t)wl_shm_buffer_get_width(shm) * wl_shm_buffer_get_height(shm) : 0;
if (px <= 0 || px > CURSOR_MAX_PX) { wl_buffer_send_release(buffer); return; }
if (px <= 0 || px > CURSOR_MAX_PX) { send_buffer_release(buffer); return; }
s->idle_buffer = buffer;
s->idle_buffer_destroy.notify = on_idle_buffer_destroyed;
wl_resource_add_destroy_listener(buffer, &s->idle_buffer_destroy);
@@ -1119,7 +1199,7 @@ static struct wl_resource *surface_take_idle(struct surface *s) {
static void surface_drop_idle(struct surface *s) {
surface_forget_idle_px(s);
struct wl_resource *buffer = surface_take_idle(s);
if (buffer) wl_buffer_send_release(buffer);
if (buffer) send_buffer_release(buffer);
}
static void surface_commit(struct wl_client *c, struct wl_resource *r) {
@@ -1172,11 +1252,12 @@ static void surface_commit(struct wl_client *c, struct wl_resource *r) {
cursor_publish_hidden();
} else {
cursor_publish_buffer(s, buffer);
wl_buffer_send_release(buffer);
send_buffer_release(buffer);
}
} else if (s->role == ROLE_NONE) {
if (buffer) surface_hold_idle(s, buffer);
} else if (db) {
buf_trace_attach(buffer);
take_dmabuf(s, db, buffer);
} else if (shm) {
drop_dmabuf(s, 1);
@@ -1187,7 +1268,7 @@ static void surface_commit(struct wl_client *c, struct wl_resource *r) {
} else {
drop_dmabuf(s, 1);
s->has_content = 0;
if (buffer) wl_buffer_send_release(buffer);
if (buffer) send_buffer_release(buffer);
}
}
@@ -2437,7 +2518,7 @@ static void pointer_set_cursor(struct wl_client *c, struct wl_resource *r, uint3
struct wl_resource *buffer = surface_take_idle(s);
if (buffer) {
cursor_publish_buffer(s, buffer);
wl_buffer_send_release(buffer);
send_buffer_release(buffer);
} else if (g_cursor_shown == s) {
cursor_publish_shown();
} else if (s->idle_px) {
@@ -3836,6 +3917,10 @@ int droiddeck_wayland_run(void) {
return 1;
}
droiddeck_log("display", "Wayland compositor listening on %s/wayland-0", rt ? rt : "?");
wl_log_set_handler_server(wl_log_to_session);
/* A client that falls behind reading (gamescope at a few fps) must not be dropped for a full
* event buffer: libwayland's default is 4 KB per direction. */
wl_display_set_default_max_buffer_size(display, 1u << 20);
wl_display_add_client_created_listener(display, &g_client_created);
wl_global_create(display, &wl_compositor_interface, 6, NULL, bind_compositor);
@@ -3846,6 +3931,7 @@ int droiddeck_wayland_run(void) {
wl_global_create(display, &wl_output_interface, 4, NULL, bind_output);
wl_global_create(display, &xdg_wm_base_interface, 1, NULL, bind_xdg_wm_base);
wl_global_create(display, &zwp_linux_dmabuf_v1_interface, 4, NULL, bind_dmabuf);
droiddeck_android_wlegl_init(display);
wl_global_create(display, &wl_seat_interface, 9, NULL, bind_seat);
wl_global_create(display, &banner_desktop_v1_interface, 1, NULL, bind_desktop);
wl_global_create(display, &wp_presentation_interface, 2, NULL, bind_presentation);
@@ -61,3 +61,6 @@ extern volatile int g_no_render_node;
COMPOSITOR_INTERNAL extern dev_t g_main_device;
COMPOSITOR_INTERNAL void bind_dmabuf(struct wl_client *c, void *data, uint32_t ver, uint32_t id);
/* ---- wl_android_buffer.c */
COMPOSITOR_INTERNAL void droiddeck_android_wlegl_init(struct wl_display *display);
@@ -0,0 +1,47 @@
#ifndef VK_EXTERNAL_IMAGE_SYNC_H
#define VK_EXTERNAL_IMAGE_SYNC_H
#include <vulkan/vulkan.h>
struct vkp_external_client_barrier_pair {
VkImageMemoryBarrier acquire;
VkImageMemoryBarrier release;
};
static inline int vkp_is_external_client_image(int dmabuf, int blit_dst) {
return dmabuf && !blit_dst;
}
/* Client-owned dma-bufs, including AHardwareBuffers, live in GENERAL while
* FOREIGN owns them. Layer pool dma-bufs are destinations with a separate
* acquire/release lifecycle and must never take this source-image path. */
static inline int vkp_external_client_barrier_pair(
VkImage image, uint32_t queue_family, int dmabuf, int blit_dst,
struct vkp_external_client_barrier_pair *pair) {
if (!vkp_is_external_client_image(dmabuf, blit_dst) || !pair) return 0;
const VkImageSubresourceRange range = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
pair->acquire = (VkImageMemoryBarrier){
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER,
.oldLayout = VK_IMAGE_LAYOUT_GENERAL,
.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_FOREIGN_EXT,
.dstQueueFamilyIndex = queue_family,
.image = image,
.subresourceRange = range,
.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT,
};
pair->release = (VkImageMemoryBarrier){
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER,
.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
.newLayout = VK_IMAGE_LAYOUT_GENERAL,
.srcQueueFamilyIndex = queue_family,
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_FOREIGN_EXT,
.image = image,
.subresourceRange = range,
.srcAccessMask = VK_ACCESS_MEMORY_READ_BIT,
};
return 1;
}
#endif
+1 -1
View File
@@ -12,7 +12,7 @@
X(CreateAndroidSurfaceKHR) X(DestroySurfaceKHR) X(CreateDevice) \
X(GetDeviceProcAddr) X(EnumerateDeviceExtensionProperties) \
X(GetPhysicalDeviceMemoryProperties) X(GetPhysicalDeviceFormatProperties2) \
X(GetPhysicalDeviceImageFormatProperties2)
X(GetPhysicalDeviceImageFormatProperties2) X(GetPhysicalDeviceProperties2)
#define VK_DEVICE_FUNCS(X) \
X(GetDeviceQueue) X(CreateSwapchainKHR) X(DestroySwapchainKHR) X(GetSwapchainImagesKHR) \
+337 -52
View File
@@ -1,6 +1,7 @@
#define _POSIX_C_SOURCE 200809L
#include "vk_present.h"
#include "vk_loader.h"
#include "vk_external_image_sync.h"
#include "sc_layer.h"
#include "effects_chain.h"
#include "cardboard.h"
@@ -19,6 +20,7 @@
#include <poll.h>
#include <time.h>
#include <pthread.h>
#include <stdarg.h>
#include <android/log.h>
#include <android/hardware_buffer.h>
@@ -38,16 +40,59 @@ struct vkp_image {
int in_general;
VkFormat fmt;
int sampled;
AHardwareBuffer *android_buffer;
};
static ANativeWindow *g_window;
static int g_ahb_import;
static char *g_driver_path, *g_library_name, *g_native_lib_dir;
static int g_dev_state;
static void device_lost(const char *where);
static const char *vk_result_name(VkResult r);
/* Why the compositor cannot present ("" while it can). Logged as a DD_PRESENT_FAULT line, read
* back over JNI, and shown on the session-ended screen instead of a silent black one. */
static char g_fault[256];
static char g_swap_reason[160];
static pthread_mutex_t g_fault_lock = PTHREAD_MUTEX_INITIALIZER;
static void set_fault(const char *fmt, ...) __attribute__((format(printf, 1, 2)));
static void set_fault(const char *fmt, ...) {
char msg[sizeof(g_fault)];
va_list ap;
va_start(ap, fmt);
vsnprintf(msg, sizeof(msg), fmt, ap);
va_end(ap);
pthread_mutex_lock(&g_fault_lock);
int same = !strcmp(msg, g_fault);
if (!same) snprintf(g_fault, sizeof(g_fault), "%s", msg);
pthread_mutex_unlock(&g_fault_lock);
if (!same) droiddeck_log("present", "DD_PRESENT_FAULT: %s", msg);
}
static void clear_fault(void) {
pthread_mutex_lock(&g_fault_lock);
int had = g_fault[0] != 0;
g_fault[0] = 0;
pthread_mutex_unlock(&g_fault_lock);
if (had) droiddeck_log("present", "presentation recovered: fault cleared");
}
const char *vkp_fault(void) {
static __thread char copy[sizeof(g_fault)];
pthread_mutex_lock(&g_fault_lock);
snprintf(copy, sizeof(copy), "%s", g_fault);
pthread_mutex_unlock(&g_fault_lock);
if (!copy[0] && g_dev_state == -3)
snprintf(copy, sizeof(copy), "the GPU did not confirm the compositor's work finished; presenting stopped");
return copy;
}
/* The driver that answered for the display, as the driver itself reports it. */
static char g_display_driver[320];
const char *vkp_display_driver(void) { return g_display_driver; }
static VkInstance g_inst;
static VkPhysicalDevice g_pd;
static VkDevice g_dev;
static VkQueue g_queue;
static PFN_vkGetAndroidHardwareBufferPropertiesANDROID g_ahb_properties;
static uint32_t g_qfam;
static VkCommandPool g_pool;
#define MAX_PRESENTS (1 + VKP_FG_MAX_GENERATIONS)
@@ -108,10 +153,22 @@ static void perf_add(int64_t *sum, int64_t *max, unsigned *count, int64_t d) {
if (d > *max) *max = d;
(*count)++;
}
static void quarantine_pending_work(VkResult result, const char *where) {
if (g_dev_state != 1) return;
g_dev_state = -3;
g_base_black = 0;
LOGE("GPU completion unconfirmed (%d in %s): presenting stopped; pending resources retained; "
"restart DroidDeck", (int)result, where);
}
static VkResult timed_wait(VkFence fence, uint64_t timeout) {
if (g_dev_state != 1)
return g_dev_state == -2 ? VK_ERROR_DEVICE_LOST : VK_ERROR_UNKNOWN;
int64_t t0 = perf_now();
VkResult r = g_vk.WaitForFences(g_dev, 1, &fence, VK_TRUE, timeout);
perf_add(&g_perf.wait_ns, &g_perf.wait_max_ns, &g_perf.waits, perf_now() - t0);
if (r != VK_SUCCESS && r != VK_ERROR_DEVICE_LOST)
quarantine_pending_work(r, "fence wait");
return r;
}
@@ -206,7 +263,12 @@ static void reset_sync(void) {
static void destroy_swapchain(void) {
g_base_black = 0;
if (g_dev_state != 1) return;
g_vk.DeviceWaitIdle(g_dev);
VkResult idle = g_vk.DeviceWaitIdle(g_dev);
if (idle != VK_SUCCESS) {
if (idle == VK_ERROR_DEVICE_LOST) device_lost("swapchain idle");
else quarantine_pending_work(idle, "swapchain idle");
return;
}
reset_sync();
for (uint32_t i = 0; i < g_nimg; i++) blendp_forget_image(g_images[i]);
if (g_swapchain) g_vk.DestroySwapchainKHR(g_dev, g_swapchain, NULL);
@@ -296,6 +358,7 @@ int vkp_has_window(void) {
}
int vkp_device_lost(void) { return g_dev_state == -2; }
int vkp_completion_unknown(void) { return g_dev_state == -3; }
void vk_present_set_scale_mode(int mode, int alignment) {
if (mode < VKP_MODE_OFF || mode > VKP_MODE_INTEGER) mode = VKP_MODE_FIT;
@@ -406,11 +469,43 @@ static int has_ext(VkExtensionProperties *e, uint32_t n, const char *name) {
return 0;
}
static int is_proprietary(VkDriverId id) {
return id == VK_DRIVER_ID_ARM_PROPRIETARY || id == VK_DRIVER_ID_QUALCOMM_PROPRIETARY ||
id == VK_DRIVER_ID_IMAGINATION_PROPRIETARY || id == VK_DRIVER_ID_SAMSUNG_PROPRIETARY ||
id == VK_DRIVER_ID_BROADCOM_PROPRIETARY;
}
/* What really loaded: adrenotools falls back to the vendor driver when the requested one fails
* to load (hook_impl.cpp), so the name asked for is not proof of the driver in use. */
static void log_display_driver(void) {
PFN_vkGetPhysicalDeviceProperties2 props2 = g_vk.GetPhysicalDeviceProperties2;
VkPhysicalDeviceDriverProperties drv = {.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DRIVER_PROPERTIES};
VkPhysicalDeviceProperties2 p2 = {.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, .pNext = &drv};
if (!props2) {
snprintf(g_display_driver, sizeof(g_display_driver), "%.200s (driver properties not available)", g_gpu_name);
droiddeck_log("gpu", "display driver: %s", g_display_driver);
return;
}
props2(g_pd, &p2);
int fell_back = g_library_name && is_proprietary(drv.driverID);
snprintf(g_display_driver, sizeof(g_display_driver), "%.80s: %.64s %.96s (driver id %d, Vulkan %u.%u.%u)%s", p2.properties.deviceName,
drv.driverName, drv.driverInfo, (int)drv.driverID, VK_API_VERSION_MAJOR(p2.properties.apiVersion),
VK_API_VERSION_MINOR(p2.properties.apiVersion), VK_API_VERSION_PATCH(p2.properties.apiVersion),
fell_back ? " - FELL BACK to the phone's own driver" : "");
droiddeck_log("gpu", "display driver loaded: %s", g_display_driver);
if (fell_back)
droiddeck_log("gpu", "display driver: %s was requested but the phone's own driver answered; the requested "
"driver did not load (a missing library beside it, or a rejected ABI - see the adrenotools lines)",
g_library_name);
}
static int dev_init(void) {
if (g_dev_state != 0) return g_dev_state == 1 ? 0 : -1;
if (vk_loader_open(g_driver_path, g_library_name, g_native_lib_dir) != 0) {
LOGE("present: vk_loader_open failed"); g_dev_state = -1; return -1;
LOGE("present: vk_loader_open failed"); g_dev_state = -1;
set_fault("no Vulkan driver could be loaded for the display (%s)", g_library_name ? g_library_name : "libvulkan.so");
return -1;
}
const char *inst_exts[3] = {VK_KHR_SURFACE_EXTENSION_NAME,
@@ -441,13 +536,19 @@ static int dev_init(void) {
.enabledExtensionCount = n_inst_exts,
.ppEnabledExtensionNames = inst_exts};
if (g_vk.CreateInstance(&ici, NULL, &g_inst) != VK_SUCCESS) {
LOGE("present: vkCreateInstance failed"); g_dev_state = -1; return -1;
LOGE("present: vkCreateInstance failed"); g_dev_state = -1;
set_fault("vkCreateInstance failed on the display driver (%s)", g_library_name ? g_library_name : "the phone's own");
return -1;
}
vk_loader_load_instance(g_inst);
uint32_t npd = 0;
g_vk.EnumeratePhysicalDevices(g_inst, &npd, NULL);
if (!npd) { LOGE("present: no physical devices"); g_dev_state = -1; return -1; }
if (!npd) {
LOGE("present: no physical devices"); g_dev_state = -1;
set_fault("the display driver exposed no GPU to the app");
return -1;
}
VkPhysicalDevice pds[8]; if (npd > 8) npd = 8;
g_vk.EnumeratePhysicalDevices(g_inst, &npd, pds);
g_pd = VK_NULL_HANDLE;
@@ -459,7 +560,11 @@ static int dev_init(void) {
for (uint32_t q = 0; q < nq; q++)
if (qs[q].queueFlags & VK_QUEUE_GRAPHICS_BIT) { g_pd = pds[i]; g_qfam = q; break; }
}
if (g_pd == VK_NULL_HANDLE) { LOGE("present: no graphics queue"); g_dev_state = -1; return -1; }
if (g_pd == VK_NULL_HANDLE) {
LOGE("present: no graphics queue"); g_dev_state = -1;
set_fault("the display GPU offers no graphics queue");
return -1;
}
{
VkPhysicalDeviceProperties props;
g_vk.GetPhysicalDeviceProperties(g_pd, &props);
@@ -479,6 +584,21 @@ static int dev_init(void) {
g_vk.EnumerateDeviceExtensionProperties(g_pd, NULL, &ne, NULL);
VkExtensionProperties *exts = calloc(ne ? ne : 1, sizeof(*exts));
g_vk.EnumerateDeviceExtensionProperties(g_pd, NULL, &ne, exts);
if (!g_library_name || !strstr(g_library_name, "freedreno")) {
char names[440];
size_t len = 0;
names[0] = 0;
droiddeck_log("gpu", "device extensions: %u", ne);
for (uint32_t i = 0; i < ne; i++) {
if (len + strlen(exts[i].extensionName) + 2 > sizeof(names)) {
droiddeck_log("gpu", " %s", names);
len = 0;
names[0] = 0;
}
len += (size_t)snprintf(names + len, sizeof(names) - len, "%s%s", len ? " " : "", exts[i].extensionName);
}
if (len) droiddeck_log("gpu", " %s", names);
}
for (unsigned i = 0; i < 4; i++) {
if (has_ext(exts, ne, import_exts[i])) dev_exts[n_dev_exts++] = import_exts[i];
else LOGE("present: driver MISSING %s (dmabuf import will fail)", import_exts[i]);
@@ -492,6 +612,8 @@ static int dev_init(void) {
if (want_sem_fd) dev_exts[n_dev_exts++] = VK_KHR_EXTERNAL_SEMAPHORE_FD_EXTENSION_NAME;
g_ahb_import = has_ext(exts, ne, VK_ANDROID_EXTERNAL_MEMORY_ANDROID_HARDWARE_BUFFER_EXTENSION_NAME) &&
has_ext(exts, ne, VK_EXT_QUEUE_FAMILY_FOREIGN_EXTENSION_NAME);
/* The present path's own AHB import (#561) stays on the phone's own driver. */
const int want_ahb = !g_library_name && g_ahb_import;
if (g_ahb_import) {
dev_exts[n_dev_exts++] = VK_ANDROID_EXTERNAL_MEMORY_ANDROID_HARDWARE_BUFFER_EXTENSION_NAME;
dev_exts[n_dev_exts++] = VK_EXT_QUEUE_FAMILY_FOREIGN_EXTENSION_NAME;
@@ -514,11 +636,17 @@ static int dev_init(void) {
dr = g_vk.CreateDevice(g_pd, &dci, NULL, &g_dev);
}
if (dr != VK_SUCCESS) {
LOGE("present: vkCreateDevice failed"); g_dev_state = -1; return -1;
LOGE("present: vkCreateDevice failed"); g_dev_state = -1;
set_fault("vkCreateDevice failed on %s (%s)", g_gpu_name[0] ? g_gpu_name : "the display GPU", vk_result_name(dr));
return -1;
}
vk_loader_load_device(g_dev);
log_display_driver();
g_vk.GetDeviceQueue(g_dev, g_qfam, 0, &g_queue);
vkp_gpu_busy_device(g_pd, g_dev, g_qfam);
if (want_ahb)
g_ahb_properties = (PFN_vkGetAndroidHardwareBufferPropertiesANDROID)
g_vk.GetDeviceProcAddr(g_dev, "vkGetAndroidHardwareBufferPropertiesANDROID");
if (want_sem_fd) {
g_import_sem_fd = (PFN_vkImportSemaphoreFdKHR)g_vk.GetDeviceProcAddr(g_dev, "vkImportSemaphoreFdKHR");
VkSemaphoreCreateInfo wsci = {.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO};
@@ -555,6 +683,7 @@ static int dev_init(void) {
g_dev_state = 1;
reset_sync();
init_black_image();
if (g_dev_state != 1) return -1;
vkp_framegen_device_ready(g_dev, g_queue, g_qfam, fg_features != NULL);
return 0;
}
@@ -566,13 +695,15 @@ static int swap_init_locked(void);
static int swap_init(void) {
struct timespec ts;
int64_t now;
if (!g_window) return -1;
if (!g_window || g_dev_state != 1) return -1;
clock_gettime(CLOCK_MONOTONIC, &ts);
now = (int64_t)ts.tv_sec * 1000000000LL + ts.tv_nsec;
if (now < g_swap_retry_at_ns) return -1;
g_swap_reason[0] = 0;
if (swap_init_locked() == 0) {
g_swap_retry_at_ns = 0;
g_swap_fail_logged = 0;
clear_fault();
return 0;
}
destroy_swapchain();
@@ -580,11 +711,12 @@ static int swap_init(void) {
if (!g_swap_fail_logged) {
g_swap_fail_logged = 1;
LOGE("present: no swapchain on the screen surface; retrying every 0.5 s");
set_fault("no swapchain on the session screen (%s)", g_swap_reason[0] ? g_swap_reason : "unknown reason");
}
return -1;
}
#define SWLOGE(...) do { if (!g_swap_fail_logged) LOGE(__VA_ARGS__); } while (0)
#define SWLOGE(...) do { snprintf(g_swap_reason, sizeof(g_swap_reason), __VA_ARGS__); if (!g_swap_fail_logged) LOGE(__VA_ARGS__); } while (0)
static void vk_format_short(VkFormat f, char *out, size_t n) {
const char *s = NULL;
@@ -824,10 +956,15 @@ static void init_black_image(void) {
g_vk.EndCommandBuffer(cmd);
VkSubmitInfo si = {.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO, .commandBufferCount = 1, .pCommandBuffers = &cmd};
g_vk.ResetFences(g_dev, 1, &g_fence);
if (g_vk.QueueSubmit(g_queue, 1, &si, g_fence) == VK_SUCCESS &&
g_vk.WaitForFences(g_dev, 1, &g_fence, VK_TRUE, 1000000000ULL) == VK_SUCCESS)
g_black_state = 1;
else
VkResult qr = g_vk.QueueSubmit(g_queue, 1, &si, g_fence);
if (qr == VK_SUCCESS) {
VkResult fr = timed_wait(g_fence, 1000000000ULL);
if (fr == VK_SUCCESS) g_black_state = 1;
else if (fr == VK_ERROR_DEVICE_LOST) device_lost("black image");
} else if (qr == VK_ERROR_DEVICE_LOST) {
device_lost("black image submit");
}
if (g_black_state != 1)
droiddeck_log("gpu", "letterbox black image unavailable: the whole output is cleared every copy-path frame");
}
@@ -926,7 +1063,98 @@ struct vkp_image *vkp_image_from_dmabuf(int fd, uint32_t drm_format, uint64_t mo
return vkp_image_import_dmabuf(fd, drm_format, modifier, w, h, stride, offset, 0);
}
int vkp_image_is_dmabuf(const struct vkp_image *img) { return img && img->dmabuf && !img->blit_dst; }
/* Return client sources to FOREIGN after their final read. The consuming paths
* wait for our fence before Wayland can release an ordinary dma-buf or an
* android_wlegl AHardwareBuffer. Producer-fence synchronization is separate from
* these image-layout and ownership transfers. */
static void release_external_client_image(VkCommandBuffer cmd, struct vkp_image *img) {
struct vkp_external_client_barrier_pair pair;
if (!img || !vkp_external_client_barrier_pair(
img->image, g_qfam, img->dmabuf, img->blit_dst, &pair))
return;
g_vk.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, 0, 0, NULL, 0, NULL, 1, &pair.release);
}
static void release_external_client_draws(VkCommandBuffer cmd, const struct vkp_draw *draws, int count) {
for (int i = 0; i < count; i++) {
int seen = 0;
for (int j = 0; j < i; j++) if (draws[j].img == draws[i].img) { seen = 1; break; }
if (!seen) release_external_client_image(cmd, draws[i].img);
}
}
int vkp_image_is_dmabuf(const struct vkp_image *img) {
return img && vkp_is_external_client_image(img->dmabuf, img->blit_dst);
}
int vkp_android_buffer_supported(void) {
return dev_init() == 0 && g_ahb_properties != NULL;
}
struct vkp_image *vkp_image_from_android_buffer(AHardwareBuffer *buffer) {
if (!buffer || !vkp_android_buffer_supported()) return NULL;
AHardwareBuffer_Desc desc;
AHardwareBuffer_describe(buffer, &desc);
if (!desc.width || !desc.height || desc.layers != 1 ||
(desc.usage & (AHARDWAREBUFFER_USAGE_PROTECTED_CONTENT | AHARDWAREBUFFER_USAGE_GPU_MIPMAP_COMPLETE)) ||
!(desc.usage & AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE)) return NULL;
VkAndroidHardwareBufferFormatPropertiesANDROID format = {
.sType = VK_STRUCTURE_TYPE_ANDROID_HARDWARE_BUFFER_FORMAT_PROPERTIES_ANDROID};
VkAndroidHardwareBufferPropertiesANDROID props = {
.sType = VK_STRUCTURE_TYPE_ANDROID_HARDWARE_BUFFER_PROPERTIES_ANDROID, .pNext = &format};
VkResult result = g_ahb_properties(g_dev, buffer, &props);
if (result != VK_SUCCESS ||
(format.format != VK_FORMAT_R8G8B8A8_UNORM && format.format != VK_FORMAT_R8G8B8A8_SRGB &&
format.format != VK_FORMAT_B8G8R8A8_UNORM && format.format != VK_FORMAT_B8G8R8A8_SRGB) ||
!props.memoryTypeBits ||
!(format.formatFeatures & VK_FORMAT_FEATURE_BLIT_SRC_BIT)) {
LOGE("android_wlegl: unsupported Android buffer import (%s, format %d)",
vk_result_name(result), format.format);
return NULL;
}
struct vkp_image *img = calloc(1, sizeof(*img));
if (!img) return NULL;
img->w = (int)desc.width; img->h = (int)desc.height;
img->fmt = format.format; img->dmabuf = 1;
const VkFormatFeatureFlags sampled = VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT |
VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT;
img->sampled = (format.formatFeatures & sampled) == sampled;
VkExternalMemoryImageCreateInfo external = {
.sType = VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO,
.handleTypes = VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID};
VkImageCreateInfo create = {
.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, .pNext = &external,
.imageType = VK_IMAGE_TYPE_2D, .format = img->fmt,
.extent = {desc.width, desc.height, 1}, .mipLevels = 1, .arrayLayers = 1,
.samples = VK_SAMPLE_COUNT_1_BIT, .tiling = VK_IMAGE_TILING_OPTIMAL,
.usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT | (img->sampled ? VK_IMAGE_USAGE_SAMPLED_BIT : 0),
.sharingMode = VK_SHARING_MODE_EXCLUSIVE, .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED};
result = g_vk.CreateImage(g_dev, &create, NULL, &img->image);
if (result != VK_SUCCESS) goto fail;
/* AHB image requirements are not queryable before binding. The AHB query supplies them. */
uint32_t memory_type = 0;
while (!(props.memoryTypeBits & (1u << memory_type))) memory_type++;
VkImportAndroidHardwareBufferInfoANDROID import = {
.sType = VK_STRUCTURE_TYPE_IMPORT_ANDROID_HARDWARE_BUFFER_INFO_ANDROID, .buffer = buffer};
VkMemoryDedicatedAllocateInfo dedicated = {
.sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO,
.pNext = &import, .image = img->image};
VkMemoryAllocateInfo allocate = {
.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, .pNext = &dedicated,
.allocationSize = props.allocationSize, .memoryTypeIndex = memory_type};
result = g_vk.AllocateMemory(g_dev, &allocate, NULL, &img->mem);
if (result != VK_SUCCESS) goto fail;
result = g_vk.BindImageMemory(g_dev, img->image, img->mem, 0);
if (result != VK_SUCCESS) goto fail;
AHardwareBuffer_acquire(buffer);
img->android_buffer = buffer;
return img;
fail:
LOGE("android_wlegl: Vulkan buffer import failed: %s", vk_result_name(result));
vkp_image_destroy(img);
return NULL;
}
struct vkp_image *vkp_image_import_dmabuf(int fd, uint32_t drm_format, uint64_t modifier, int w, int h,
uint32_t stride, uint32_t offset, int as_blit_dst) {
@@ -940,7 +1168,27 @@ struct vkp_image *vkp_image_import_dmabuf(int fd, uint32_t drm_format, uint64_t
const VkImageUsageFlags sampled_usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_SAMPLED_BIT;
img->sampled = !as_blit_dst && g_vk.GetPhysicalDeviceImageFormatProperties2 &&
modifier_importable(img->fmt, modifier, sampled_usage);
/* Each new format/modifier/size a client hands over, once, for the graphics report: a colour
* or swizzle mismatch on a non-Adreno driver shows up as the pair it arrived as. */
{
static struct { uint32_t fmt; uint64_t mod; int w, h; } seen[32];
static int nseen;
int known = 0;
for (int i = 0; i < nseen; i++)
if (seen[i].fmt == drm_format && seen[i].mod == modifier && seen[i].w == w && seen[i].h == h) known = 1;
if (!known && nseen < 32) {
seen[nseen].fmt = drm_format; seen[nseen].mod = modifier; seen[nseen].w = w; seen[nseen].h = h; nseen++;
droiddeck_log("gpu", "dmabuf import: %c%c%c%c %s %dx%d stride %u offset %u -> vk format %d, %s%s",
drm_format & 0xff, (drm_format >> 8) & 0xff, (drm_format >> 16) & 0xff, (drm_format >> 24) & 0xff,
vkp_modifier_name(modifier), w, h, stride, offset, (int)img->fmt,
img->sampled ? "sampled" : "copied", as_blit_dst ? ", blit target" : "");
}
}
/* Venus reports a row pitch of 0 for gamescope's 1x1 root buffer, and a zero pitch fails
* vkCreateImage, which left the whole window unshown (David Cimo). One packed, 64-byte aligned
* row is what a linear buffer that small holds. */
if (stride == 0 && modifier == 0) stride = ((uint32_t)w * 4 + 63) & ~63u;
VkSubresourceLayout plane = {.offset = offset, .rowPitch = stride};
VkImageDrmFormatModifierExplicitCreateInfoEXT modInfo = {
.sType = VK_STRUCTURE_TYPE_IMAGE_DRM_FORMAT_MODIFIER_EXPLICIT_CREATE_INFO_EXT,
@@ -1211,7 +1459,7 @@ struct vkp_image *vkp_image_create_shm(int w, int h) {
}
void vkp_image_upload_shm(struct vkp_image *img, const void *data, int stride) {
if (!img || !img->map || !data) return;
if (g_dev_state != 1 || !img || !img->map || !data) return;
size_t rowbytes = (size_t)img->w * 4;
if ((size_t)stride < rowbytes) rowbytes = (size_t)stride;
for (int y = 0; y < img->h; y++)
@@ -1224,12 +1472,14 @@ int vkp_image_height(const struct vkp_image *img) { return img ? img->h : 0; }
void vkp_image_destroy(struct vkp_image *img) {
if (!img) return;
if (g_dev_state == -3) return; /* completion unknown: retain GPU ownership */
if (g_dev) {
blendp_forget_image(img->image);
if (img->map) g_vk.UnmapMemory(g_dev, img->mem);
if (img->image) g_vk.DestroyImage(g_dev, img->image, NULL);
if (img->mem) g_vk.FreeMemory(g_dev, img->mem, NULL);
}
if (img->android_buffer) AHardwareBuffer_release(img->android_buffer);
free(img);
}
@@ -1325,11 +1575,14 @@ static void effects_source_note(int scene_w, int scene_h, const struct vkp_draw
static void record_draw(VkCommandBuffer cmd, const struct vkp_draw *d, const VkImageBlit *blit, VkImage target,
VkFormat target_fmt, int target_w, int target_h, VkFilter filter) {
const struct vkp_image *im = d->img;
const int external_client = vkp_image_is_dmabuf(im);
if (d->blend && im->sampled &&
blendp_draw(cmd, im->image, im->fmt, im->w, im->h, !im->dmabuf, target, target_fmt, target_w, target_h,
blendp_draw(cmd, im->image, im->fmt, im->w, im->h, !external_client,
target, target_fmt, target_w, target_h,
blit) == 0)
return;
g_vk.CmdBlitImage(cmd, im->image, im->dmabuf ? VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL : VK_IMAGE_LAYOUT_GENERAL,
g_vk.CmdBlitImage(cmd, im->image,
external_client ? VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL : VK_IMAGE_LAYOUT_GENERAL,
target, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, blit, filter);
}
@@ -1491,6 +1744,7 @@ static void device_lost(const char *where) {
vkp_gpu_busy_device_lost();
droiddeck_log("error", "GPU device lost (VK_ERROR_DEVICE_LOST in %s): the compositor has stopped presenting; "
"restart the session", where);
set_fault("the display GPU was lost (VK_ERROR_DEVICE_LOST in %s)", where);
for (uint32_t i = 0; i < g_nimg; i++) blendp_forget_image(g_images[i]);
if (g_swapchain) g_vk.DestroySwapchainKHR(g_dev, g_swapchain, NULL);
g_swapchain = VK_NULL_HANDLE;
@@ -1588,6 +1842,7 @@ static void record_screen_blit(VkCommandBuffer cmd, VkImage src, int src_w, int
static int acquire_image(int k, int first, uint32_t *img, VkResult *ar_out) {
for (int attempt = 0; ; attempt++) {
if (g_dev_state != 1) return -1;
if (!g_swapchain && (!first || swap_init() != 0)) return -1;
const int64_t t_acq = perf_now();
VkResult ar = g_vk.AcquireNextImageKHR(g_dev, g_swapchain, 1000000000ULL, g_acqs[k], VK_NULL_HANDLE, img);
@@ -1597,7 +1852,7 @@ static int acquire_image(int k, int first, uint32_t *img, VkResult *ar_out) {
if (ar == VK_ERROR_OUT_OF_DATE_KHR || ar == VK_ERROR_SURFACE_LOST_KHR) {
droiddeck_log("gpu", "screen surface %s on acquire: rebuilding the swapchain", vk_result_name(ar));
destroy_swapchain();
if (first && attempt == 0) continue;
if (first && attempt == 0 && g_dev_state == 1) continue;
return -1;
}
droiddeck_log("error", "present: acquire %d failed (%s %d)", k, vk_result_name(ar), (int)ar);
@@ -1714,6 +1969,7 @@ static void send_hdr_metadata(const struct droiddeck_color *c) {
static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, int n,
const struct vkp_hdr_frame *hf, int *how) {
if (how) *how = 0;
if (g_dev_state < 0) return -1;
vkp_apply_window_request();
sc_layer_hide_base();
check_surface_changed();
@@ -1732,6 +1988,7 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i
: "no HDR frames through the screen swapchain any more: rebuilding it as SDR");
destroy_swapchain();
}
if (g_dev_state != 1) return -1;
g_swap_hdr_want = want_hdr;
uint32_t img = 0;
@@ -1815,13 +2072,11 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i
int seen = 0;
for (int j = 0; j < i; j++) if (draws[j].img == im) { seen = 1; break; }
if (seen || !im) continue;
if (im->dmabuf) {
bars[nb++] = (VkImageMemoryBarrier){
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_FOREIGN_EXT, .dstQueueFamilyIndex = g_qfam,
.image = im->image, .subresourceRange = range, .dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT};
} else if (!im->in_general) {
struct vkp_external_client_barrier_pair pair;
if (vkp_external_client_barrier_pair(
im->image, g_qfam, im->dmabuf, im->blit_dst, &pair)) {
bars[nb++] = pair.acquire;
} else if (!im->blit_dst && !im->in_general) {
bars[nb++] = (VkImageMemoryBarrier){
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_PREINITIALIZED,
.newLayout = VK_IMAGE_LAYOUT_GENERAL,
@@ -1880,6 +2135,7 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i
drawn++;
}
if (!(pass && fx)) release_external_client_draws(cmd, draws, n);
int ngen = 0;
VkImage gens[VKP_FG_MAX_GENERATIONS] = {VK_NULL_HANDLE};
VkImage result = scene_img;
@@ -1901,6 +2157,7 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i
result = vkp_effects_run(cmd, scene_img, input_w, input_h, mapped_w, mapped_h, &rw, &rh);
effects_overlay_draws(cmd, result, rw, rh, scene_w, scene_h,
draws ? draws + overlay_start : NULL, n - overlay_start);
release_external_client_draws(cmd, draws, n);
result_layout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
}
VkImageMemoryBarrier b_general = {
@@ -1932,6 +2189,10 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i
if (k > 0) {
VkResult ark;
if (acquire_image(k, 0, &img, &ark) != 0) {
/* Teardown may have retained this frame's pending work, or
* acquire may have reported real device loss. Neither permits
* a completion-marker submit or another fence wait. */
if (g_dev_state != 1) return -1;
droiddeck_log("framegen", "present %d/%d: no swapchain image; the frame ends early", k + 1, presents);
pr = VK_ERROR_OUT_OF_DATE_KHR;
break;
@@ -1963,15 +2224,22 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i
pr = g_vk.QueuePresentKHR(g_queue, &pi);
perf_add(&g_perf.present_ns, &g_perf.present_max_ns, &g_perf.presents, perf_now() - t_pres);
if (k < ngen) presented_gen++;
if (pr == VK_ERROR_OUT_OF_DATE_KHR || pr == VK_ERROR_SURFACE_LOST_KHR || pr == VK_ERROR_DEVICE_LOST) break;
if (pr == VK_ERROR_DEVICE_LOST) { device_lost("present"); return -1; }
if (pr == VK_ERROR_OUT_OF_DATE_KHR || pr == VK_ERROR_SURFACE_LOST_KHR) break;
}
if (!fence_submitted) {
VkSubmitInfo si = {.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO};
g_vk.QueueSubmit(g_queue, 1, &si, g_fence);
VkResult marker = g_vk.QueueSubmit(g_queue, 1, &si, g_fence);
if (marker != VK_SUCCESS) {
if (marker == VK_ERROR_DEVICE_LOST) device_lost("frame completion submit");
else quarantine_pending_work(marker, "frame completion submit");
return -1; /* no fence was submitted; never wait on its unsignalled state */
}
}
VkResult fr = timed_wait(g_fence, UINT64_MAX);
if (fg) vkp_framegen_presented(presented_gen);
if (fr == VK_ERROR_DEVICE_LOST || pr == VK_ERROR_DEVICE_LOST) { device_lost("present"); return -1; }
if (fr != VK_SUCCESS) return -1;
if (fg) vkp_framegen_presented(presented_gen);
if (pr == VK_ERROR_OUT_OF_DATE_KHR || pr == VK_ERROR_SURFACE_LOST_KHR) {
droiddeck_log("gpu", "screen surface %s on present: rebuilding the swapchain", vk_result_name(pr));
destroy_swapchain();
@@ -2038,6 +2306,7 @@ void vkp_reset_first_frame(void) {
void vkp_signal_first_frame(void) {
if (g_first_frame_done) return;
g_first_frame_done = 1;
clear_fault();
droiddeck_on_first_frame();
}
@@ -2051,6 +2320,7 @@ int vkp_update_map(int scene_w, int scene_h) {
return g_map.valid ? 0 : -1;
}
check_surface_changed();
if (g_dev_state != 1) return -1;
if (!g_swapchain && swap_init() != 0) return -1;
update_map(scene_w, scene_h);
return g_map.valid ? 0 : -1;
@@ -2073,7 +2343,7 @@ int vkp_map_draw(const struct vkp_draw *d, int out[8]) {
}
int vkp_blit_image(struct vkp_image *src, struct vkp_image *dst, int wait_fd) {
if (!src || !dst || !dst->blit_dst || g_dev_state == -2 || dev_init() != 0) {
if (!src || src->blit_dst || !dst || !dst->blit_dst || g_dev_state == -2 || dev_init() != 0) {
if (wait_fd >= 0) close(wait_fd);
return -1;
}
@@ -2086,17 +2356,21 @@ int vkp_blit_image(struct vkp_image *src, struct vkp_image *dst, int wait_fd) {
VkCommandBufferBeginInfo bi = {.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT};
g_vk.BeginCommandBuffer(g_cmd, &bi);
struct vkp_external_client_barrier_pair src_pair;
const int src_external = vkp_external_client_barrier_pair(
src->image, g_qfam, src->dmabuf, src->blit_dst, &src_pair);
VkImageMemoryBarrier acq[2] = {
{.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
src_external ? src_pair.acquire : (VkImageMemoryBarrier){
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
.srcQueueFamilyIndex = src->dmabuf ? VK_QUEUE_FAMILY_FOREIGN_EXT : VK_QUEUE_FAMILY_IGNORED,
.dstQueueFamilyIndex = src->dmabuf ? g_qfam : VK_QUEUE_FAMILY_IGNORED,
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.image = src->image, .subresourceRange = range, .dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT},
{.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_FOREIGN_EXT, .dstQueueFamilyIndex = g_qfam,
.image = dst->image, .subresourceRange = range, .dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT}};
if (!src->dmabuf) {
if (!src_external) {
acq[0].oldLayout = src->in_general ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_PREINITIALIZED;
acq[0].newLayout = VK_IMAGE_LAYOUT_GENERAL;
acq[0].srcAccessMask = VK_ACCESS_HOST_WRITE_BIT;
@@ -2110,8 +2384,9 @@ int vkp_blit_image(struct vkp_image *src, struct vkp_image *dst, int wait_fd) {
.dstSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1},
.dstOffsets = {{0, 0, 0}, {bw, bh, 1}}};
g_vk.CmdBlitImage(g_cmd, src->image,
src->dmabuf ? VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL : VK_IMAGE_LAYOUT_GENERAL,
src_external ? VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL : VK_IMAGE_LAYOUT_GENERAL,
dst->image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &blit, VK_FILTER_NEAREST);
release_external_client_image(g_cmd, src);
VkImageMemoryBarrier rel = {
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
.newLayout = VK_IMAGE_LAYOUT_GENERAL, .srcQueueFamilyIndex = g_qfam,
@@ -2146,7 +2421,7 @@ int vkp_blit_image(struct vkp_image *src, struct vkp_image *dst, int wait_fd) {
static struct vkp_image *g_rb;
int vkp_image_readback(struct vkp_image *src, uint32_t *out, int max_px) {
if (!src || !out || src->w <= 0 || src->h <= 0 || src->w * src->h > max_px ||
if (!src || src->blit_dst || !out || src->w <= 0 || src->h <= 0 || src->w * src->h > max_px ||
g_dev_state == -2 || dev_init() != 0)
return -1;
if (g_rb && (g_rb->w != src->w || g_rb->h != src->h)) { vkp_image_destroy(g_rb); g_rb = NULL; }
@@ -2187,11 +2462,15 @@ int vkp_image_readback(struct vkp_image *src, uint32_t *out, int max_px) {
VkCommandBufferBeginInfo bi = {.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT};
g_vk.BeginCommandBuffer(cmd, &bi);
struct vkp_external_client_barrier_pair src_pair;
const int src_external = vkp_external_client_barrier_pair(
src->image, g_qfam, src->dmabuf, src->blit_dst, &src_pair);
VkImageMemoryBarrier acq[2] = {
{.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
src_external ? src_pair.acquire : (VkImageMemoryBarrier){
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
.srcQueueFamilyIndex = src->dmabuf ? VK_QUEUE_FAMILY_FOREIGN_EXT : VK_QUEUE_FAMILY_IGNORED,
.dstQueueFamilyIndex = src->dmabuf ? g_qfam : VK_QUEUE_FAMILY_IGNORED,
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.image = src->image, .subresourceRange = range, .dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT},
{.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
.newLayout = VK_IMAGE_LAYOUT_GENERAL, .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
@@ -2209,15 +2488,20 @@ int vkp_image_readback(struct vkp_image *src, uint32_t *out, int max_px) {
{.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_GENERAL,
.newLayout = VK_IMAGE_LAYOUT_GENERAL, .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, .image = g_rb->image, .subresourceRange = range,
.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT, .dstAccessMask = VK_ACCESS_HOST_READ_BIT},
{.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT, .dstAccessMask = VK_ACCESS_HOST_READ_BIT}};
uint32_t done_count = 1;
if (!src_external) {
done[done_count++] = (VkImageMemoryBarrier){
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
.newLayout = VK_IMAGE_LAYOUT_GENERAL,
.srcQueueFamilyIndex = src->dmabuf ? g_qfam : VK_QUEUE_FAMILY_IGNORED,
.dstQueueFamilyIndex = src->dmabuf ? VK_QUEUE_FAMILY_FOREIGN_EXT : VK_QUEUE_FAMILY_IGNORED,
.image = src->image, .subresourceRange = range, .srcAccessMask = VK_ACCESS_TRANSFER_READ_BIT}};
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.image = src->image, .subresourceRange = range, .srcAccessMask = VK_ACCESS_TRANSFER_READ_BIT};
}
g_vk.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT,
VK_PIPELINE_STAGE_HOST_BIT | VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
0, 0, NULL, 0, NULL, 2, done);
0, 0, NULL, 0, NULL, done_count, done);
release_external_client_image(cmd, src);
g_vk.EndCommandBuffer(cmd);
VkSubmitInfo si = {.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO, .commandBufferCount = 1, .pCommandBuffers = &cmd};
g_vk.ResetFences(g_dev, 1, &g_fence);
@@ -2307,13 +2591,11 @@ static int pass_begin_impl(int scene_w, int scene_h, const struct vkp_draw *draw
int seen = 0;
for (int j = 0; j < i; j++) if (draws[j].img == im) { seen = 1; break; }
if (seen || !im) continue;
if (im->dmabuf) {
bars[nb++] = (VkImageMemoryBarrier){
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_FOREIGN_EXT, .dstQueueFamilyIndex = g_qfam,
.image = im->image, .subresourceRange = range, .dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT};
} else if (!im->in_general) {
struct vkp_external_client_barrier_pair pair;
if (vkp_external_client_barrier_pair(
im->image, g_qfam, im->dmabuf, im->blit_dst, &pair)) {
bars[nb++] = pair.acquire;
} else if (!im->blit_dst && !im->in_general) {
bars[nb++] = (VkImageMemoryBarrier){
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_PREINITIALIZED,
.newLayout = VK_IMAGE_LAYOUT_GENERAL,
@@ -2358,6 +2640,7 @@ static int pass_begin_impl(int scene_w, int scene_h, const struct vkp_draw *draw
&g_pass.rw, &g_pass.rh);
effects_overlay_draws(cmd, g_pass.result, g_pass.rw, g_pass.rh, scene_w, scene_h,
draws ? draws + overlay_start : NULL, n - overlay_start);
release_external_client_draws(cmd, draws, n);
g_pass.active = 1;
if (rw) *rw = g_pass.rw;
if (rh) *rh = g_pass.rh;
@@ -2367,8 +2650,9 @@ static int pass_begin_impl(int scene_w, int scene_h, const struct vkp_draw *draw
int vkp_pass_copy_to(struct vkp_image *dst, int wait_fd) {
if (!g_pass.active) { if (wait_fd >= 0) close(wait_fd); return -1; }
g_pass.active = 0;
if (g_dev_state != 1) { if (wait_fd >= 0) close(wait_fd); return -1; }
VkCommandBuffer cmd = g_cmds[0];
if (!dst || !dst->blit_dst || g_dev_state == -2) {
if (!dst || !dst->blit_dst) {
if (wait_fd >= 0) close(wait_fd);
g_vk.EndCommandBuffer(cmd);
return -1;
@@ -2420,5 +2704,6 @@ int vkp_pass_copy_to(struct vkp_image *dst, int wait_fd) {
void vkp_pass_abort(void) {
if (!g_pass.active) return;
g_pass.active = 0;
g_vk.EndCommandBuffer(g_cmds[0]);
if (g_dev_state == 1)
g_vk.EndCommandBuffer(g_cmds[0]);
}
@@ -3,6 +3,8 @@
#include <stdint.h>
#include <stddef.h>
#include <android/native_window.h>
#include <android/hardware_buffer.h>
void vk_present_set_driver(const char *driver_path, const char *library_name,
const char *native_lib_dir);
@@ -22,6 +24,9 @@ void vkp_output_size(int *w, int *h);
struct vkp_image;
int vkp_android_buffer_supported(void);
struct vkp_image *vkp_image_from_android_buffer(AHardwareBuffer *buffer);
#define VKP_MOD_LINEAR 0x0000000000000000ULL
#define VKP_MOD_QCOM_COMPRESSED 0x0500000000000001ULL
#define VKP_MOD_INVALID 0x00ffffffffffffffULL
@@ -61,6 +66,10 @@ int vkp_ready(void);
int vkp_has_window(void);
int vkp_wait_window_request(int timeout_ms);
int vkp_device_lost(void);
/* Compositor thread only. Submitted reads may still be pending: retain imported
* buffer references and withhold DMA-BUF releases until the app process exits.
* This terminal state is distinct from genuine device loss. */
int vkp_completion_unknown(void);
int vkp_render(int scene_w, int scene_h, const struct vkp_draw *draws, int n);
int vkp_render_plain(int scene_w, int scene_h);
@@ -216,6 +216,24 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeCompositorTid(JNIEnv
return (jint)g_comp_tid;
}
/* Why presenting failed ("" while it works), for the session-ended screen and the report. */
JNIEXPORT jstring JNICALL
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeCompositorFault(JNIEnv *env, jclass clazz) {
(void)clazz;
extern const char *vkp_fault(void);
const char *f = vkp_fault();
return (*env)->NewStringUTF(env, f ? f : "");
}
/* The display driver as the driver itself reports it ("" before the compositor's device exists). */
JNIEXPORT jstring JNICALL
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeDisplayDriver(JNIEnv *env, jclass clazz) {
(void)clazz;
extern const char *vkp_display_driver(void);
const char *d = vkp_display_driver();
return (*env)->NewStringUTF(env, d ? d : "");
}
JNIEXPORT void JNICALL
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeStart(JNIEnv *env, jclass clazz,
jstring xdgRuntimeDir) {
@@ -0,0 +1,216 @@
/* android_wlegl buffer import for the existing libhybris Wayland WSI.
* Protocol: Collabora/libhybris, vendored with its license in protocols/wayland-android.xml.
* Native handles are cloned through Android; opaque vendor integers are never interpreted. */
#include "compositor_internal.h"
#include "droiddeck_ext.h"
#include "wayland-android-server-protocol.h"
#include <android/hardware_buffer.h>
#include <dlfcn.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
/* Stable native_handle_t ABI, unavailable in the public NDK. */
struct android_native_handle {
int version, num_fds, num_ints;
int data[];
};
struct wire_handle {
struct android_native_handle *handle;
int received;
};
enum { MAX_HANDLE_FDS = 64, MAX_HANDLE_INTS = 256, MAX_BUFFER_SIDE = 8192 };
/* VNDK ABI (not exposed by the NDK): frameworks/native/libs/nativewindow/include/
* vndk/hardware_buffer.h, AHARDWAREBUFFER_CREATE_FROM_HANDLE_METHOD_CLONE = 3.
* Method 1 is not accepted by AHardwareBuffer_createFromHandle. */
enum { CREATE_FROM_HANDLE_CLONE = 3 };
static int (*import_handle)(const AHardwareBuffer_Desc *, const struct android_native_handle *,
int32_t, AHardwareBuffer **);
static const struct android_native_handle *(*native_handle)(const AHardwareBuffer *);
static int valid_description(int32_t width, int32_t height, int32_t stride, int32_t format) {
return width > 0 && height > 0 && width <= MAX_BUFFER_SIDE && height <= MAX_BUFFER_SIDE &&
stride >= width && stride <= MAX_BUFFER_SIDE * 4 &&
(format == 1 || format == 2 || format == 5);
}
static void handle_resource_destroy(struct wl_resource *resource) {
struct wire_handle *wire = wl_resource_get_user_data(resource);
if (!wire) return;
for (int i = 0; i < wire->received; i++) close(wire->handle->data[i]);
free(wire->handle);
free(wire);
}
static void handle_add_fd(struct wl_client *client, struct wl_resource *resource, int32_t fd) {
struct wire_handle *wire = wl_resource_get_user_data(resource);
if (wire->received >= wire->handle->num_fds) {
close(fd);
wl_resource_post_error(resource, ANDROID_WLEGL_HANDLE_ERROR_TOO_MANY_FDS,
"more native handle descriptors than declared");
return;
}
wire->handle->data[wire->received++] = fd;
}
static void handle_destroy(struct wl_client *client, struct wl_resource *resource) {
wl_resource_destroy(resource);
}
static const struct android_wlegl_handle_interface handle_impl = {
.add_fd = handle_add_fd, .destroy = handle_destroy,
};
static void create_handle(struct wl_client *client, struct wl_resource *resource,
uint32_t id, int32_t fds, struct wl_array *ints) {
if (fds < 0 || fds > MAX_HANDLE_FDS || ints->size % sizeof(int32_t) ||
ints->size > MAX_HANDLE_INTS * sizeof(int32_t)) {
wl_resource_post_error(resource, ANDROID_WLEGL_ERROR_BAD_VALUE, "invalid native handle size");
return;
}
struct wire_handle *wire = calloc(1, sizeof(*wire));
if (!wire) { wl_client_post_no_memory(client); return; }
wire->handle = calloc(1, sizeof(*wire->handle) + (size_t)fds * sizeof(int32_t) + ints->size);
if (!wire->handle) { free(wire); wl_client_post_no_memory(client); return; }
wire->handle->version = sizeof(*wire->handle);
wire->handle->num_fds = fds;
wire->handle->num_ints = (int)(ints->size / sizeof(int32_t));
if (ints->size) memcpy(wire->handle->data + fds, ints->data, ints->size);
struct wl_resource *handle = wl_resource_create(client, &android_wlegl_handle_interface, 1, id);
if (!handle) {
free(wire->handle); free(wire); wl_client_post_no_memory(client); return;
}
wl_resource_set_implementation(handle, &handle_impl, wire, handle_resource_destroy);
}
static void buffer_resource_destroy(struct wl_resource *resource) {
dmabuf_buffer_unref(wl_resource_get_user_data(resource));
}
static struct wl_resource *create_android_buffer(struct wl_client *client, uint32_t id,
AHardwareBuffer *hardware) {
AHardwareBuffer_Desc desc;
AHardwareBuffer_describe(hardware, &desc);
struct vkp_image *image = vkp_image_from_android_buffer(hardware);
if (!image) return NULL;
struct dmabuf_buffer *buffer = calloc(1, sizeof(*buffer));
if (!buffer) { vkp_image_destroy(image); wl_client_post_no_memory(client); return NULL; }
buffer->refs = 1;
buffer->width = (int32_t)desc.width; buffer->height = (int32_t)desc.height;
buffer->format = desc.format == 5 ? DRM_ARGB8888 : desc.format == 2 ? DRM_XBGR8888 : DRM_ABGR8888;
buffer->modifier = MOD_INVALID; /* No DMA-BUF layout was inferred from the native handle. */
buffer->img = image;
for (int i = 0; i < MAX_PLANES; i++) buffer->fd[i] = -1;
struct wl_resource *result = wl_resource_create(client, &wl_buffer_interface, 1, id);
if (!result) { dmabuf_buffer_unref(buffer); wl_client_post_no_memory(client); return NULL; }
wl_resource_set_implementation(result, &dbuf_buffer_impl, buffer, buffer_resource_destroy);
struct client_info *info = client_info_of(client);
if (info) info->dmabuf_buffers++;
return result;
}
static void create_buffer(struct wl_client *client, struct wl_resource *resource, uint32_t id,
int32_t width, int32_t height, int32_t stride, int32_t format,
int32_t usage, struct wl_resource *handle_resource) {
/* Some vendor allocators (Samsung Xclipse) record no stride for GPU-only buffers. The import
* must pass that 0 back unchanged: gralloc validates it against the handle's own value. */
if (!valid_description(width, height, stride ? stride : width, format) ||
!wl_resource_instance_of(handle_resource, &android_wlegl_handle_interface, &handle_impl)) {
droiddeck_log("display", "android_wlegl rejected: %dx%d stride=%d format=%d usage=0x%x",
width, height, stride, format, (uint32_t)usage);
wl_resource_post_error(resource, ANDROID_WLEGL_ERROR_BAD_VALUE, "invalid Android buffer description");
return;
}
struct wire_handle *wire = wl_resource_get_user_data(handle_resource);
if (wire->received != wire->handle->num_fds || !wire->received) {
wl_resource_post_error(resource, ANDROID_WLEGL_ERROR_BAD_HANDLE, "incomplete native handle");
return;
}
AHardwareBuffer_Desc desc = {
.width = (uint32_t)width, .height = (uint32_t)height, .layers = 1,
.format = (uint32_t)format, .usage = (uint32_t)usage, .stride = (uint32_t)stride};
AHardwareBuffer *hardware = NULL;
int status = import_handle(&desc, wire->handle, CREATE_FROM_HANDLE_CLONE, &hardware);
if (status != 0 || !hardware) {
droiddeck_log("display", "android_wlegl import failed: status=%d %dx%d stride=%d format=%d usage=0x%x fds=%d ints=%d",
status, width, height, stride, format, (uint32_t)usage,
wire->handle->num_fds, wire->handle->num_ints);
wl_resource_post_error(resource, ANDROID_WLEGL_ERROR_BAD_HANDLE,
"Android rejected the native handle (status %d)", status);
return;
}
struct wl_resource *buffer = create_android_buffer(client, id, hardware);
AHardwareBuffer_release(hardware);
if (!buffer) wl_resource_post_error(resource, ANDROID_WLEGL_ERROR_BAD_HANDLE, "Vulkan cannot import this buffer");
}
static void get_server_buffer(struct wl_client *client, struct wl_resource *resource, uint32_t id,
int32_t width, int32_t height, int32_t format, int32_t usage) {
if (!format) format = 1;
if (!valid_description(width, height, width, format)) {
wl_resource_post_error(resource, ANDROID_WLEGL_ERROR_BAD_VALUE, "invalid buffer allocation request");
return;
}
AHardwareBuffer_Desc desc = {
.width = (uint32_t)width, .height = (uint32_t)height, .layers = 1,
.format = (uint32_t)format,
.usage = (uint32_t)usage | AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE | AHARDWAREBUFFER_USAGE_GPU_COLOR_OUTPUT};
AHardwareBuffer *hardware = NULL;
if (AHardwareBuffer_allocate(&desc, &hardware) != 0 || !hardware) {
wl_resource_post_error(resource, ANDROID_WLEGL_ERROR_BAD_VALUE, "Android buffer allocation failed");
return;
}
AHardwareBuffer_describe(hardware, &desc);
const struct android_native_handle *handle = native_handle(hardware);
if (!handle || handle->num_fds < 1 || handle->num_fds > MAX_HANDLE_FDS ||
handle->num_ints < 0 || handle->num_ints > MAX_HANDLE_INTS) {
AHardwareBuffer_release(hardware);
wl_resource_post_error(resource, ANDROID_WLEGL_ERROR_BAD_HANDLE, "invalid allocated native handle");
return;
}
struct wl_resource *buffer = create_android_buffer(client, 0, hardware);
if (!buffer) {
AHardwareBuffer_release(hardware);
wl_resource_post_error(resource, ANDROID_WLEGL_ERROR_BAD_HANDLE, "Vulkan cannot import allocated buffer");
return;
}
struct wl_resource *reply = wl_resource_create(client, &android_wlegl_server_buffer_handle_interface,
wl_resource_get_version(resource), id);
if (!reply) {
wl_resource_destroy(buffer); AHardwareBuffer_release(hardware);
wl_client_post_no_memory(client); return;
}
struct wl_array ints = {.size = (size_t)handle->num_ints * sizeof(int32_t),
.alloc = 0, .data = (void *)(handle->data + handle->num_fds)};
android_wlegl_server_buffer_handle_send_buffer_ints(reply, &ints);
for (int i = 0; i < handle->num_fds; i++)
android_wlegl_server_buffer_handle_send_buffer_fd(reply, handle->data[i]);
/* No linear_layout event: Android's opaque allocation need not be linear. */
android_wlegl_server_buffer_handle_send_buffer(reply, buffer, (int32_t)desc.format, (int32_t)desc.stride);
wl_resource_destroy(reply);
AHardwareBuffer_release(hardware);
}
static const struct android_wlegl_interface wlegl_impl = {
.create_handle = create_handle, .create_buffer = create_buffer,
.get_server_buffer_handle = get_server_buffer,
};
static void bind_android_wlegl(struct wl_client *client, void *data, uint32_t version, uint32_t id) {
struct wl_resource *resource = wl_resource_create(client, &android_wlegl_interface,
version < 3 ? version : 3, id);
if (!resource) { wl_client_post_no_memory(client); return; }
wl_resource_set_implementation(resource, &wlegl_impl, NULL, NULL);
}
void droiddeck_android_wlegl_init(struct wl_display *display) {
if (!vkp_android_buffer_supported()) return;
void *library = dlopen("libnativewindow.so", RTLD_NOW | RTLD_LOCAL);
if (!library) return;
import_handle = dlsym(library, "AHardwareBuffer_createFromHandle");
native_handle = dlsym(library, "AHardwareBuffer_getNativeHandle");
if (!import_handle || !native_handle) { dlclose(library); return; }
/* Keep the platform entry points valid for the compositor's lifetime. */
if (wl_global_create(display, &android_wlegl_interface, 3, NULL, bind_android_wlegl))
droiddeck_log("display", "android_wlegl v3: Android buffer import available");
}