RediWM is a Wayland compositor written in Zig (OpenGL ES) that includes everything in one process
fifo-v1: wp_fifo_v1 with latch-paced barriers
oxydizerec3397034817
diff --git a/build/protocols.zig b/build/protocols.zigindex 46ed3ed..eabadbc 100644--- a/build/protocols.zig+++ b/build/protocols.zig@@ -35,6 +35,7 @@ pub fn module(b: *std.Build) *std.Build.Module {scanner.addSystemProtocol("unstable/pointer-constraints/pointer-constraints-unstable-v1.xml");scanner.addSystemProtocol("unstable/relative-pointer/relative-pointer-unstable-v1.xml");scanner.addSystemProtocol("staging/pointer-warp/pointer-warp-v1.xml");+ scanner.addSystemProtocol("staging/fifo/fifo-v1.xml");scanner.addSystemProtocol("staging/ext-session-lock/ext-session-lock-v1.xml");scanner.addCustomProtocol(b.path("protocol/wlr-output-power-management-unstable-v1.xml"));@@ -65,6 +66,7 @@ pub fn module(b: *std.Build) *std.Build.Module {scanner.generate("zwp_pointer_constraints_v1", 1);scanner.generate("zwp_relative_pointer_manager_v1", 1);scanner.generate("wp_pointer_warp_v1", 1);+ scanner.generate("wp_fifo_manager_v1", 1);scanner.generate("ext_session_lock_manager_v1", 1);scanner.generate("zwlr_output_power_manager_v1", 1);diff --git a/docs/agent-notes/map.md b/docs/agent-notes/map.mdindex 0877d34..6abe8a2 100644--- a/docs/agent-notes/map.md+++ b/docs/agent-notes/map.md@@ -72,7 +72,8 @@ seam for other operating systems.Also in `src/`: `Shell.zig` (xdg-shell and decorations), `TitlebarTabs.zig` (client-publishedtitlebar tabs, `protocol/rediwm-titlebar-tabs-v1.xml`), `Popup.zig`,`LayerSurface.zig`, `Xwayland.zig` (+ `xwayland_*.zig`), `Switcher.zig`-(Alt+Tab), `workspaces.zig`, `snap.zig`, `auto_tiling.zig`, `window_tabs.zig`.+(Alt+Tab), `workspaces.zig`, `snap.zig`, `auto_tiling.zig`, `window_tabs.zig`,+`fifo.zig` (wp_fifo_v1 barriers, `docs/plans/fifo.md`).**Rendering** (read [rendering details](rendering.md) first): own scene nodes`node.zig`/`node.c`, client surfaces `node_surface.c` (+ `node_subsurface_tree.c`,diff --git a/docs/agent-notes/rendering.md b/docs/agent-notes/rendering.mdindex b722ff3..9332666 100644--- a/docs/agent-notes/rendering.md+++ b/docs/agent-notes/rendering.md@@ -156,6 +156,16 @@ chrome, capture, or retained panel painting. General rules remain inone swapchain damage history. It reads graph geometry and the buffers,textures and wait points of the source nodes(`docs/plans/scene-graph-stage3.md`, `scene-graph-stage6.md`).+* **Latches are not frame callbacks.** `Output.latch_seq` counts latching+ deadlines: a successful non-tearing buffer commit in `commitFrameState`, and+ the `vblank_timer` refresh after a skipped commit (`handleVblank`). fifo-v1+ barriers (`fifo.zig`) clear only on a latch of the surface's frame-pacing+ output, never on frame callbacks, which late render sends before it+ renders. A new commit path must go through `commitFrameState` or the+ barrier waits for its forward-progress fallback (two refreshes; the+ `rediwm-msg perf` `fifo.late` counter shows it). Releasing a held update+ applies client state: never from inside the frame or a projection walk+ (`fifo.zig` defers it to an idle callback).* **Shapes in the owned pass** (`scene_pass.h`): a window's rounded clip, ringand shadow are `rediwm_scene_pass_add_*_shaped` calls, device pixels, snapped bythe caller. The programs cost the driver about 430 KiB (a GL program costsdiff --git a/docs/plans/fifo.md b/docs/plans/fifo.mdnew file mode 100644index 0000000..335b080--- /dev/null+++ b/docs/plans/fifo.md@@ -0,0 +1,122 @@+# fifo-v1 in RediWM++Status: implemented on `feat/fifo-v1` (2026-11-24, uncommitted). Headless,+Debug and ReleaseSafe verified, including Mesa's Vulkan WSI. A DRM run on real+hardware is still open (see the end).++## Why ourselves++`wp_fifo_v1` (wayland-protocols staging) lets a content update wait until the+surface's previous update has been on screen for one refresh. Mesa's Vulkan+WSI uses it for `VK_PRESENT_MODE_FIFO_KHR`. SDL3 uses it for vsync, and it no+longer requires commit-timing-v1 alongside it. wlroots 0.20.2 has no+implementation. The upstream one, wlroots MR !4463 (sway PR #8371), was still+open on 2026-11-12, and its glue code hooks into wlr_scene, which RediWM has+replaced. The pieces it needs are public in 0.20 and already bound in+`src/wlr/compositor.zig`: `wlr_surface_synced`, `events.client_commit` and+`wlr_surface_lock_pending`/`unlock_cached`.++Mesa 26.2 with fifo-v1 offered requests **no frame callbacks at all**: barriers+are its only pacing. That decides two things. Hidden surfaces must still be+throttled (D2), and the barrier must clear at real refresh boundaries.++## Decisions (accepted 2026-11-24)++* **D1:** hidden surfaces are released at 20 Hz (`Fifo.hidden_period_ns`).+* **D2:** hidden surfaces are throttled, not ignored.+* **D3:** no early latch for updates that may tear. A torn flip is not a+ latch, so a FIFO surface on a tearing output falls back to the late release.+* **Release point** (review): barriers clear on a dedicated per-output+ latch, not on frame callbacks. `Output.latch_seq` is bumped by+ `output/frame.zig` on a successful non-tearing buffer commit+ (`commitFrameState`) and on the `vblank_timer` refresh after a skipped+ commit (`handleVblank`). Late render sends frame callbacks before it+ renders, so callbacks would release an update a refresh early. Fallbacks+ are separate and counted: `hidden` (no pacing output, 20 Hz) and `late`+ (shown, but no latch within two refreshes + 1 ms, so the client keeps+ making progress).++## How it works (`src/fifo.zig`)++* **State.** The double-buffered `set_barrier`/`wait_barrier` bits are a+ `wlr_surface_synced` state. The bookkeeping, `Fifo.Barriers`, works in+ wlroots' per-surface state sequence numbers (they start at 1 and carry into+ `current`). It tracks the latest committed `set_barrier` (`last_set`), the+ latest applied one (`applied`/`armed`) and the latest cleared one+ (`cleared`). It has no wlroots calls and is unit tested in+ `fifo_tests.zig`.+* **Hold.** On `client_commit`, an update with `wait_barrier` is held when+ the latest earlier `set_barrier` has not cleared, *even if that barrier has+ not been applied yet* (it may still sit behind an explicit-sync acquire+ point). The upstream MR checks only the applied barrier, so there the two+ updates land in the same refresh. A held update is locked with+ `wlr_surface_lock_pending`, so wlroots keeps every later commit cached+ behind it, in order. Waits from a synchronized subsurface, directly or+ through a parent (wlroots' `subsurface_is_synchronized` walk), are ignored.+ Their `set_barrier` still counts.+* **Apply.** On `commit`, an applied `set_barrier` arms the barrier and+ records its pacing output and that output's `latch_seq`. It then calls+ `Output.frameCallbacksWanted`, so an update that changed nothing still gets+ a latch from the skipped-commit vblank.+* **Latch.** `Manager.latched(output, seq)` clears the armed barriers of the+ surfaces this output paces, unless the barrier was applied at this same+ generation. This is bookkeeping only. The unlocks run from an idle callback,+ because unlocking applies client state synchronously and a latch happens+ inside the output frame.+* **Occlusion.** The pacing output is `rediwm_surface_frame_pacing_output`+ (`node_surface.c`). It comes from the occlusion-aware projection feedback,+ so a surface that is covered, minimized, on another workspace, unmapped or+ on an output that is off has none. One deadline timer serves both+ fallbacks. It is armed only while some surface has an update held behind an+ applied barrier, and disarmed once nothing is held: no idle wakeups.+* **Teardown.** Destroying the fifo unlocks its held updates (the spec says+ earlier state changes are unaffected). On surface destroy, held updates are+ dropped *without* unlocking. wlroots 0.20.2 emits `destroy`, then finishes+ addons, then frees cached states (`surface_handle_resource_destroy`).+ Unlocking there, as the MR's addon destroy does, applies state to a surface+ whose role is gone.+* **Counters.** `rediwm-msg perf` → `fifo: {held, latched, hidden, late}`.++The global is unprivileged (not in `global_filter.zig`), not created in the+greeter, and created after the extra protocols in `server/setup.zig`.+Teardown destroys it after the clients.++## Tests++* `zig build test`: `fifo_tests.zig` covers barriers across two commits,+ release up to the next barrier only, a barrier queued behind another lock,+ the synchronized-subsurface exemption, and sequence wrap.+* `python3 tests/fifo.py` (headless GLES2; the fixture is `tests/fifo_client.c`):+ * Control: 6 commits without fifo collapse into one refresh (5 discarded).+ * 8 back-to-back fifo commits are presented on 8 refreshes (≈16.5 ms apart),+ all cleared by latches.+ * A barrier-only (empty) update is latched by the skipped-commit vblank,+ with no `late` fallback.+ * Synchronized subsurface: exempt (collapses). Desynchronized: paced.+ * Minimized, and covered by an opaque window: 10 held updates released in+ 0.52 s (20 Hz) with no `late` releases; pacing resumes after.+ * Explicit sync (GBM dmabuf + drm syncobj): commit 1 sets a barrier but its+ acquire point is unmaterialized; commit 2 waits. Signalling the point+ applies 1, and 2 still reaches a later refresh.+ * Destroying the fifo with updates held lets the last one show. Destroying+ the surface with updates held is survived.+ * Protocol errors: `already_exists`, `surface_destroyed`; a fifo can be made+ again after its destroy.+ * vkcube (Mesa WSI, FIFO): binds fifo-v1, sends 0 frame-callback requests,+ 57–58 presents/s shown at 60 Hz, 20.0/s minimized, back to 57–58/s restored.+* Mutation checks. The upstream "applied barrier only" hold rule fails the+ explicit-sync case (`es1` discarded). Dropping the subsurface exemption+ fails the sync-subsurface case. Unlocking on surface destroy (the MR's+ behaviour) did **not** fail anything here: the held states applied to the+ dying surface without a crash or a log line. We still drop them, since the+ role is gone by then.+* Also passing: `wlr_protocols.py` (global listed, advertised once),+ `presentation_time.py`, `explicit_sync.py`, `greeter.py`.++## Open++* DRM run on the laptop: vkcube and an SDL3 game windowed and fullscreen.+ Check pacing at the panel's rate, `fifo.late` staying 0, late render on+ (`[compositor] late_render`), VRR once P2 lands, and the async-flip path+ where the driver allows it.+* Proton/Wine through the Wine Wayland driver (Vulkan via DXVK → Mesa WSI).diff --git a/src/Output.zig b/src/Output.zigindex 1f3304a..0a63214 100644--- a/src/Output.zig+++ b/src/Output.zig@@ -101,6 +101,10 @@ frame_wanted: bool = false,/// Last known vblank: a page-flip frame event or a fired `vblank_timer`.last_vblank_ns: u64 = 0,flip_pending: bool = false,+/// Latching deadlines passed: a non-tearing buffer commit, or a `vblank_timer`+/// refresh after a skipped commit. fifo-v1 barriers clear on these, never on+/// frame callbacks (late render sends those before it renders).+latch_seq: u64 = 0,/// Late rendering (`output/late.zig`): the decision model, the timer that/// starts a deferred frame, whether one is waiting (frame events are ignored/// meanwhile), the plan `runFrame` takes when it runs, and whether the lastdiff --git a/src/Server.zig b/src/Server.zigindex 977cdd6..d25d7f8 100644--- a/src/Server.zig+++ b/src/Server.zig@@ -92,6 +92,7 @@ pub const CompositorError = error{PointerGesturesCreateFailed,PointerConstraintsCreateFailed,PointerWarpCreateFailed,+ FifoManagerCreateFailed,ShortcutsInhibitCreateFailed,};@@ -153,6 +154,8 @@ layer_surfaces: wl.list.Head(@import("LayerSurface.zig"), .link) = undefined,input: Input,activation: @import("input/activation.zig") = .{},extra_protocols: ?*@import("extra_protocols.zig").Protocols = null,+/// wp_fifo_v1 (`fifo.zig`); null in the greeter.+fifo: ?*@import("fifo.zig").Manager = null,launch_feedback: @import("launch_feedback.zig") = .{},window_tabs: @import("window_tabs.zig") = .{},text_input: ?*@import("input/text_input.zig") = null,diff --git a/src/fifo.zig b/src/fifo.zignew file mode 100644index 0000000..d0bf5e1--- /dev/null+++ b/src/fifo.zig@@ -0,0 +1,434 @@+//! wp_fifo_v1: a content update can wait until the surface's previous update+//! has been on screen for one refresh (Vulkan FIFO in Mesa, SDL3 vsync).+//! Plan and decisions: docs/plans/fifo.md.+//!+//! A held update stays in the surface's cached-state queue+//! (`wlr_surface_lock_pending`), so wlroots keeps every later commit behind+//! it in order. A barrier is cleared by a *latch* of the output that paces+//! the surface (`Output.latch_seq`: a non-tearing buffer commit, or the+//! `vblank_timer` refresh after a skipped commit), never by frame callbacks,+//! which late render sends before it renders. Two fallbacks keep clients+//! going: a hidden surface (no pacing output: covered, minimized, another+//! workspace, outputs off) is released at 20 Hz, and a shown one whose+//! output has not latched within two refreshes (torn flips, failed commits)+//! is released late. One deadline timer serves both, armed only while+//! something is held.+//!+//! Releasing applies client state synchronously and can create scene nodes,+//! and latches happen inside the output frame; so a latch only clears the+//! barrier (bookkeeping) and the unlocks run from an idle callback.+const std = @import("std");+const wl = @import("wayland").server.wl;+const wp = @import("wayland").server.wp;+const wlr = @import("wlroots");+const Server = @import("Server.zig");+const Output = @import("Output.zig");+const stats = @import("ipc/stats.zig");+const gpa = @import("main.zig").gpa;++const Fifo = @This();++extern fn rediwm_surface_frame_pacing_output(surface: *wlr.Surface) ?*wlr.Output;++/// D1: how often a hidden surface's barrier clears.+pub const hidden_period_ns: u64 = 50 * std.time.ns_per_ms;+/// Refreshes a shown surface waits for its output's latch before it is+/// released anyway (forward progress).+pub const late_refreshes: u64 = 2;++/// The double-buffered requests (`wlr_surface_synced` state).+const State = extern struct {+ set_barrier: bool = false,+ wait_barrier: bool = false,+};++fn moveState(dst: *anyopaque, src: *anyopaque) callconv(.c) void {+ const to: *State = @ptrCast(@alignCast(dst));+ const from: *State = @ptrCast(@alignCast(src));+ to.* = from.*;+ from.* = .{};+}++const synced_impl: wlr.Surface.Synced.Impl = .{+ .state_size = @sizeOf(State),+ .init_state = null,+ .finish_state = null,+ .move_state = moveState,+};++/// Barrier bookkeeping of one surface, in wl_surface state sequence numbers+/// (wlroots numbers every commit; cached and applied states keep theirs).+/// No wlroots calls, so the rules are unit tested (`fifo_tests.zig`).+pub const Barriers = struct {+ pub const Held = struct {+ /// The held state (`wlr_surface_lock_pending`).+ seq: u32,+ /// The set_barrier commit whose condition it waits for.+ waits_on: u32,+ };++ /// The latest committed set_barrier, applied or still queued behind a+ /// lock (explicit sync, a held update).+ last_set: ?u32 = null,+ /// The latest applied set_barrier, and whether its condition holds.+ applied: ?u32 = null,+ armed: bool = false,+ /// The latest set_barrier whose condition has cleared.+ cleared: ?u32 = null,+ /// Held updates, oldest first.+ held: std.ArrayList(Held) = .empty,++ pub fn deinit(self: *Barriers) void {+ self.held.deinit(gpa);+ }++ /// `a` was committed after `b` (wrapping).+ fn after(a: u32, b: u32) bool {+ return @as(i32, @bitCast(a -% b)) > 0;+ }++ /// Whether the condition set by commit `seq` has cleared.+ fn clearedFor(self: *const Barriers, seq: u32) bool {+ const cleared = self.cleared orelse return false;+ return !after(seq, cleared);+ }++ /// A client commit numbered `seq`. Returns the commit it must wait for,+ /// or null when it is ready. A synchronized subsurface's wait is ignored+ /// (the spec says so); its set_barrier still counts.+ pub fn committed(self: *Barriers, seq: u32, set: bool, wait: bool, exempt: bool) ?u32 {+ const before = self.last_set;+ if (set) self.last_set = seq;+ if (!wait or exempt) return null;+ // An earlier set_barrier that has not even been applied (a lock+ // ahead of it) must be waited for too, not just the applied one.+ const target = before orelse return null;+ return if (self.clearedFor(target)) null else target;+ }++ /// State `seq` was applied.+ pub fn appliedState(self: *Barriers, seq: u32, set: bool) void {+ if (!set) return;+ self.applied = seq;+ self.armed = true;+ }++ /// A latch (or a fallback) clears the applied condition. Returns whether+ /// it cleared one.+ pub fn clear(self: *Barriers) bool {+ if (!self.armed) return false;+ self.armed = false;+ self.cleared = self.applied;+ return true;+ }++ /// Whether the oldest held update waits for the applied condition (so+ /// clearing it releases something).+ pub fn waitingOnArmed(self: *const Barriers) bool {+ if (!self.armed or self.held.items.len == 0) return false;+ return !after(self.held.items[0].waits_on, self.applied.?);+ }++ /// The next held update that may be released, removed from the queue.+ pub fn nextReleasable(self: *Barriers) ?Held {+ if (self.held.items.len == 0) return null;+ const first = self.held.items[0];+ if (!self.clearedFor(first.waits_on)) return null;+ _ = self.held.orderedRemove(0);+ return first;+ }+};++manager: *Manager,+resource: *wp.FifoV1,+surface: ?*wlr.Surface,+synced: wlr.Surface.Synced = undefined,+pending: State = .{},+current: State = .{},+barriers: Barriers = .{},+/// The applied barrier: when, and its pacing output's latch generation then.+armed_ns: u64 = 0,+armed_output: ?*wlr.Output = null,+armed_latch: u64 = 0,+/// A latch cleared the barrier; the idle callback releases what waited.+release_pending: bool = false,+link: wl.list.Link = undefined,+client_commit: wl.Listener(void) = .init(handleClientCommit),+commit: wl.Listener(*wlr.Surface) = .init(handleCommit),+surface_destroy: wl.Listener(*wlr.Surface) = .init(handleSurfaceDestroy),++pub const Manager = struct {+ server: *Server,+ global: *wl.Global,+ fifos: wl.list.Head(Fifo, .link) = undefined,+ timer: *wl.EventSource,+ /// When `timer` fires, 0 while disarmed.+ deadline_ns: u64 = 0,+ release_idle: ?*wl.EventSource = null,++ pub fn create(server: *Server) !*Manager {+ const self = try gpa.create(Manager);+ errdefer gpa.destroy(self);+ const timer = try server.wl_server.getEventLoop().addTimer(*Manager, handleTimer, self);+ errdefer timer.remove();+ self.* = .{+ .server = server,+ .timer = timer,+ .global = try wl.Global.create(server.wl_server, wp.FifoManagerV1, 1, *Manager, self, bind),+ };+ self.fifos.init();+ return self;+ }++ /// Clients are gone by now (teardown destroys them first); any fifo left+ /// is destroyed like a client would.+ pub fn destroy(self: *Manager) void {+ self.global.destroy();+ while (self.fifos.first()) |fifo| fifo.resource.destroy();+ if (self.release_idle) |idle| idle.remove();+ self.timer.remove();+ gpa.destroy(self);+ }++ /// `output` latched (`Output.latch_seq` is now `latch`): clear the+ /// barriers of the surfaces it paces that were applied before it.+ pub fn latched(self: *Manager, output: *wlr.Output, latch: u64) void {+ var any = false;+ var it = self.fifos.iterator(.forward);+ while (it.next()) |fifo| {+ const surface = fifo.surface orelse continue;+ if (!fifo.barriers.armed) continue;+ if (rediwm_surface_frame_pacing_output(surface) != output) continue;+ // Applied at this generation on this output: not latched yet.+ if (fifo.armed_output == output and fifo.armed_latch == latch) continue;+ const releases = fifo.barriers.waitingOnArmed();+ _ = fifo.barriers.clear();+ stats.global_stats.fifo.latched +%= 1;+ if (releases) {+ fifo.release_pending = true;+ any = true;+ }+ }+ if (any and self.release_idle == null) {+ self.release_idle = self.server.wl_server.getEventLoop().addIdle(*Manager, releaseIdle, self) catch null;+ // Without an idle the deadline timer releases them.+ if (self.release_idle == null) self.rearm();+ }+ }++ fn releaseIdle(self: *Manager) void {+ self.release_idle = null;+ var it = self.fifos.iterator(.forward);+ while (it.next()) |fifo| {+ if (!fifo.release_pending) continue;+ fifo.release_pending = false;+ fifo.release();+ }+ self.rearm();+ }++ /// When the oldest held update of `fifo` is released anyway, if it waits+ /// for an applied barrier.+ fn deadlineOf(fifo: *Fifo) ?u64 {+ const surface = fifo.surface orelse return null;+ if (!fifo.barriers.waitingOnArmed()) return null;+ const output = rediwm_surface_frame_pacing_output(surface) orelse+ return fifo.armed_ns + hidden_period_ns;+ return fifo.armed_ns + late_refreshes * refreshPeriodNs(output) + std.time.ns_per_ms;+ }++ /// Arms the timer for the earliest deadline, or disarms it.+ fn rearm(self: *Manager) void {+ var earliest: u64 = 0;+ var it = self.fifos.iterator(.forward);+ while (it.next()) |fifo| {+ const deadline = deadlineOf(fifo) orelse continue;+ if (earliest == 0 or deadline < earliest) earliest = deadline;+ }+ if (earliest == self.deadline_ns) return;+ self.deadline_ns = earliest;+ if (earliest == 0) {+ self.timer.timerUpdate(0) catch {};+ return;+ }+ const now = stats.nowNs();+ const delay_ms: c_int = if (earliest <= now) 1 else @intCast(@min(+ std.math.divCeil(u64, earliest - now, std.time.ns_per_ms) catch 1,+ std.math.maxInt(c_int),+ ));+ self.timer.timerUpdate(delay_ms) catch {+ self.deadline_ns = 0;+ };+ }++ fn handleTimer(self: *Manager) c_int {+ self.deadline_ns = 0;+ const now = stats.nowNs();+ var it = self.fifos.iterator(.forward);+ while (it.next()) |fifo| {+ const deadline = deadlineOf(fifo) orelse continue;+ if (deadline > now) continue;+ const hidden = rediwm_surface_frame_pacing_output(fifo.surface.?) == null;+ _ = fifo.barriers.clear();+ if (hidden) stats.global_stats.fifo.hidden +%= 1 else stats.global_stats.fifo.late +%= 1;+ fifo.release_pending = false;+ fifo.release();+ }+ self.rearm();+ return 0;+ }++ fn bind(client: *wl.Client, self: *Manager, version: u32, id: u32) void {+ const resource = wp.FifoManagerV1.create(client, version, id) catch {+ client.postNoMemory();+ return;+ };+ resource.setHandler(*Manager, handleRequest, null, self);+ }++ fn handleRequest(manager: *wp.FifoManagerV1, request: wp.FifoManagerV1.Request, self: *Manager) void {+ switch (request) {+ .destroy => manager.destroy(),+ .get_fifo => |args| {+ const surface = wlr.Surface.fromWlSurface(args.surface);+ var it = self.fifos.iterator(.forward);+ while (it.next()) |existing| {+ if (existing.surface == surface) {+ manager.postError(.already_exists, "the surface already has a wp_fifo_v1");+ return;+ }+ }+ self.createFifo(manager, args.id, surface) catch manager.getClient().postNoMemory();+ },+ }+ }++ fn createFifo(self: *Manager, manager: *wp.FifoManagerV1, id: u32, surface: *wlr.Surface) !void {+ const fifo = try gpa.create(Fifo);+ errdefer gpa.destroy(fifo);+ const resource = try wp.FifoV1.create(manager.getClient(), manager.getVersion(), id);+ errdefer resource.destroy();+ fifo.* = .{ .manager = self, .resource = resource, .surface = surface };+ try fifo.synced.init(surface, &synced_impl, &fifo.pending, &fifo.current);+ surface.events.client_commit.add(&fifo.client_commit);+ surface.events.commit.add(&fifo.commit);+ surface.events.destroy.add(&fifo.surface_destroy);+ self.fifos.append(fifo);+ resource.setHandler(*Fifo, handleFifoRequest, handleResourceDestroy, fifo);+ }+};++fn refreshPeriodNs(output: *wlr.Output) u64 {+ const mhz: u64 = if (output.refresh > 0) @intCast(output.refresh) else 60_000;+ return 1_000_000_000_000 / mhz;+}++/// A synchronized subsurface, directly or through a synchronized parent+/// (wlroots' subsurface_is_synchronized).+fn isSynchronized(surface: *wlr.Surface) bool {+ var current = surface;+ while (wlr.Subsurface.tryFromWlrSurface(current)) |sub| {+ if (sub.synchronized) return true;+ current = sub.parent;+ }+ return false;+}++fn handleFifoRequest(resource: *wp.FifoV1, request: wp.FifoV1.Request, fifo: *Fifo) void {+ switch (request) {+ .destroy => resource.destroy(),+ .set_barrier, .wait_barrier => {+ if (fifo.surface == null) {+ resource.postError(.surface_destroyed, "the wl_surface of this wp_fifo_v1 was destroyed");+ return;+ }+ if (request == .set_barrier) fifo.pending.set_barrier = true else fifo.pending.wait_barrier = true;+ },+ }+}++/// Before wlroots applies or caches the commit: hold it behind its barrier.+fn handleClientCommit(listener: *wl.Listener(void)) void {+ const fifo: *Fifo = @fieldParentPtr("client_commit", listener);+ const surface = fifo.surface.?;+ const seq = surface.pending.seq;+ const waits_on = fifo.barriers.committed(seq, fifo.pending.set_barrier, fifo.pending.wait_barrier, isSynchronized(surface)) orelse return;+ fifo.barriers.held.append(gpa, .{ .seq = seq, .waits_on = waits_on }) catch {+ // Unheld, the update shows a refresh early; nothing worse.+ surface.resource.getClient().postNoMemory();+ return;+ };+ const locked = surface.lockPending();+ std.debug.assert(locked == seq);+ stats.global_stats.fifo.held +%= 1;+ fifo.manager.rearm();+}++/// A state was applied: arm its barrier, and make sure a latch will come.+fn handleCommit(listener: *wl.Listener(*wlr.Surface), surface: *wlr.Surface) void {+ const fifo: *Fifo = @fieldParentPtr("commit", listener);+ if (!fifo.current.set_barrier) return;+ fifo.barriers.appliedState(surface.current.seq, true);+ fifo.armed_ns = stats.nowNs();+ const output = rediwm_surface_frame_pacing_output(surface);+ fifo.armed_output = output;+ fifo.armed_latch = if (output) |o| latchOf(o) else 0;+ // An update that changed nothing builds no frame; this either finds+ // one coming or arms the skipped-commit vblank, which latches.+ if (output) |o| Output.frameCallbacksWanted(o);+ if (fifo.barriers.waitingOnArmed()) fifo.manager.rearm();+}++fn latchOf(output: *wlr.Output) u64 {+ const owner: *Output = @ptrCast(@alignCast(output.data orelse return 0));+ return owner.latch_seq;+}++/// Unlocks the held updates whose barrier has cleared, oldest first. An+/// unlock can apply several states (and so arm a new barrier) at once.+fn release(fifo: *Fifo) void {+ const surface = fifo.surface orelse return;+ while (fifo.barriers.nextReleasable()) |held| surface.unlockCached(held.seq);+}++/// Stops following the surface. wlroots frees cached states after the+/// destroy signal; unlocking them here would apply state to a surface whose+/// role is gone, so held updates are dropped.+fn detach(fifo: *Fifo) void {+ if (fifo.surface == null) return;+ fifo.client_commit.link.remove();+ fifo.commit.link.remove();+ fifo.surface_destroy.link.remove();+ fifo.synced.deinit();+ fifo.barriers.held.clearRetainingCapacity();+ fifo.barriers.armed = false;+ fifo.release_pending = false;+ fifo.surface = null;+}++fn handleSurfaceDestroy(listener: *wl.Listener(*wlr.Surface), _: *wlr.Surface) void {+ const fifo: *Fifo = @fieldParentPtr("surface_destroy", listener);+ detach(fifo);+ fifo.manager.rearm();+}++/// "Surface state changes previously made by this protocol are unaffected":+/// held updates go ahead now, in order.+fn handleResourceDestroy(_: *wp.FifoV1, fifo: *Fifo) void {+ if (fifo.surface) |surface| {+ while (fifo.barriers.held.items.len > 0) {+ const held = fifo.barriers.held.orderedRemove(0);+ surface.unlockCached(held.seq);+ }+ }+ detach(fifo);+ fifo.barriers.deinit();+ fifo.link.remove();+ const manager = fifo.manager;+ gpa.destroy(fifo);+ manager.rearm();+}++test {+ _ = @import("fifo_tests.zig");+}diff --git a/src/fifo_tests.zig b/src/fifo_tests.zignew file mode 100644index 0000000..7c29008--- /dev/null+++ b/src/fifo_tests.zig@@ -0,0 +1,109 @@+//! Barrier rules of `fifo.zig`, without wlroots. Sequence numbers stand for+//! wl_surface commits in order; `hold` mimics what the commit handler does.+const std = @import("std");+const Barriers = @import("fifo.zig").Barriers;+const gpa = @import("main.zig").gpa;++fn hold(b: *Barriers, seq: u32, set: bool, wait: bool) !bool {+ const waits_on = b.committed(seq, set, wait, false) orelse return false;+ try b.held.append(gpa, .{ .seq = seq, .waits_on = waits_on });+ return true;+}++fn releasedSeqs(b: *Barriers, out: []u32) []u32 {+ var n: usize = 0;+ while (b.nextReleasable()) |held| : (n += 1) out[n] = held.seq;+ return out[0..n];+}++test "a wait with no barrier ever set is ready" {+ var b: Barriers = .{};+ defer b.deinit();+ try std.testing.expect(!try hold(&b, 1, false, true));+ try std.testing.expect(!try hold(&b, 2, true, true));+}++test "two commits in one refresh: the second waits for a latch" {+ var b: Barriers = .{};+ defer b.deinit();+ // Commit 1 sets the barrier and applies at once.+ try std.testing.expect(!try hold(&b, 1, true, true));+ b.appliedState(1, true);+ // Commit 2 arrives before the output latched: held.+ try std.testing.expect(try hold(&b, 2, true, true));+ try std.testing.expect(b.waitingOnArmed());+ var buf: [4]u32 = undefined;+ try std.testing.expectEqual(@as(usize, 0), releasedSeqs(&b, &buf).len);+ // The latch clears it and releases commit 2, which sets a new barrier.+ try std.testing.expect(b.clear());+ try std.testing.expectEqualSlices(u32, &.{2}, releasedSeqs(&b, &buf));+ b.appliedState(2, true);+ // Commit 3 waits for the next latch, not the one that released 2.+ try std.testing.expect(try hold(&b, 3, true, true));+ try std.testing.expectEqual(@as(usize, 0), releasedSeqs(&b, &buf).len);+ try std.testing.expect(b.clear());+ try std.testing.expectEqualSlices(u32, &.{3}, releasedSeqs(&b, &buf));+}++test "a latch releases waits up to the next barrier only" {+ var b: Barriers = .{};+ defer b.deinit();+ _ = try hold(&b, 1, true, false);+ b.appliedState(1, true);+ try std.testing.expect(try hold(&b, 2, false, true)); // waits on 1+ try std.testing.expect(try hold(&b, 3, true, true)); // waits on 1, sets+ try std.testing.expect(try hold(&b, 4, false, true)); // waits on 3+ try std.testing.expect(b.clear());+ var buf: [4]u32 = undefined;+ try std.testing.expectEqualSlices(u32, &.{ 2, 3 }, releasedSeqs(&b, &buf));+ b.appliedState(2, false);+ b.appliedState(3, true);+ try std.testing.expectEqual(@as(usize, 0), releasedSeqs(&b, &buf).len);+ try std.testing.expect(b.clear());+ try std.testing.expectEqualSlices(u32, &.{4}, releasedSeqs(&b, &buf));+}++test "a barrier still queued behind another lock (explicit sync) is waited for" {+ var b: Barriers = .{};+ defer b.deinit();+ // Commit 1 sets a barrier but waits on its acquire point: not applied.+ try std.testing.expect(!try hold(&b, 1, true, false));+ // Commit 2 waits: barrier_set alone (nothing applied) would let it pass.+ try std.testing.expect(try hold(&b, 2, true, true));+ // A latch before commit 1 applies clears nothing.+ try std.testing.expect(!b.clear());+ var buf: [4]u32 = undefined;+ try std.testing.expectEqual(@as(usize, 0), releasedSeqs(&b, &buf).len);+ try std.testing.expect(!b.waitingOnArmed());+ // The fence materializes: commit 1 applies; commit 2 still waits a latch.+ b.appliedState(1, true);+ try std.testing.expect(b.waitingOnArmed());+ try std.testing.expectEqual(@as(usize, 0), releasedSeqs(&b, &buf).len);+ try std.testing.expect(b.clear());+ try std.testing.expectEqualSlices(u32, &.{2}, releasedSeqs(&b, &buf));+}++test "a synchronized subsurface's wait is ignored, its set_barrier kept" {+ var b: Barriers = .{};+ defer b.deinit();+ try std.testing.expectEqual(@as(?u32, null), b.committed(1, true, false, true));+ b.appliedState(1, true);+ try std.testing.expectEqual(@as(?u32, null), b.committed(2, true, true, true));+ // Once desynchronized, waits count against the barrier it set.+ try std.testing.expectEqual(@as(?u32, 2), b.committed(3, false, true, false));+}++test "sequence numbers wrap" {+ var b: Barriers = .{};+ defer b.deinit();+ const max = std.math.maxInt(u32);+ _ = try hold(&b, max, true, false);+ b.appliedState(max, true);+ try std.testing.expect(try hold(&b, 0, true, true));+ try std.testing.expect(b.clear());+ var buf: [2]u32 = undefined;+ try std.testing.expectEqualSlices(u32, &.{0}, releasedSeqs(&b, &buf));+ b.appliedState(0, true);+ try std.testing.expect(try hold(&b, 1, false, true));+ try std.testing.expectEqual(@as(usize, 0), releasedSeqs(&b, &buf).len);+}diff --git a/src/ipc/handlers_frames.zig b/src/ipc/handlers_frames.zigindex 48ce739..5c2085b 100644--- a/src/ipc/handlers_frames.zig+++ b/src/ipc/handlers_frames.zig@@ -186,6 +186,7 @@ pub fn handleFrameAction(.glass_reblurs = @import("../scene_output.zig").reblurs.*,.tearing_async_flips = stats.global_stats.tearing_async_flips,.tearing_refused_flips = stats.global_stats.tearing_refused_flips,+ .fifo = stats.global_stats.fifo,} } };},.reset_performance_stats => {diff --git a/src/ipc/protocol.zig b/src/ipc/protocol.zigindex 166b6cc..f2e5637 100644--- a/src/ipc/protocol.zig+++ b/src/ipc/protocol.zig@@ -75,6 +75,7 @@ pub const SamplePixelsResult = protocol_results.SamplePixelsResult;pub const ScreenshotSelectionStats = protocol_results.ScreenshotSelectionStats;pub const PerformanceStatsResult = protocol_results.PerformanceStatsResult;pub const DesktopStats = protocol_results.DesktopStats;+pub const FifoStats = protocol_results.FifoStats;pub const StartupStats = protocol_results.StartupStats;pub const InhibitorData = protocol_results.InhibitorData;pub const IdleStateResult = protocol_results.IdleStateResult;diff --git a/src/ipc/protocol_results.zig b/src/ipc/protocol_results.zigindex 7d26557..d367487 100644--- a/src/ipc/protocol_results.zig+++ b/src/ipc/protocol_results.zig@@ -161,6 +161,19 @@ pub const PerformanceStatsResult = struct {/// Asynchronous (tearing) flips, and those the driver refused, all outputs.tearing_async_flips: ?u64 = null,tearing_refused_flips: ?u64 = null,+ fifo: ?FifoStats = null,+};++/// wp_fifo_v1 barrier work since the last reset (`fifo.zig`).+pub const FifoStats = struct {+ /// Content updates held behind a barrier.+ held: u64 = 0,+ /// Barriers cleared by their pacing output's latch (commit or skipped-frame vblank).+ latched: u64 = 0,+ /// Barriers cleared by the hidden-surface rate (no output paces the surface).+ hidden: u64 = 0,+ /// Barriers cleared early on a shown surface because no latch came in time.+ late: u64 = 0,};/// The compositor-drawn desktop's repaint work since the last reset.diff --git a/src/ipc/protocol_stringify.zig b/src/ipc/protocol_stringify.zigindex 4983f22..cf86da9 100644--- a/src/ipc/protocol_stringify.zig+++ b/src/ipc/protocol_stringify.zig@@ -547,6 +547,9 @@ pub fn stringifyPerformanceStats(res: PerformanceStatsResult, writer: anytype) !if (res.tearing_refused_flips) |flips| {try writer.print("\"tearing_refused_flips\":{d},", .{flips});}+ if (res.fifo) |fifo| {+ try writer.print("\"fifo\":{f},", .{std.json.fmt(fifo, .{})});+ }try writer.print("\"output_commits\":{d},\"output_failed_commits\":{d},\"fps\":{d:.1},\"frame_time_ms\":{d:.1},\"missed_frames\":{d},\"refresh_hz\":{d:.1},\"titlebar_paints\":{d},\"footer_paints\":{d},\"edge_samples_attempted\":{d},\"edge_samples_succeeded\":{d},\"edge_samples_skipped\":{d},\"edge_sample_ns\":{d},\"panel_paints\":{d},\"panel_allocated_bytes\":{d},\"panel_reused_bytes\":{d},\"icon_cache_hits\":{d},\"icon_cache_misses\":{d},\"icon_decode_ns\":{d},\"icon_decode_count\":{d},\"icon_decoded_bytes\":{d},\"icon_queue_depth_max\":{d},", .{res.output_commits,res.output_failed_commits,diff --git a/src/ipc/stats.zig b/src/ipc/stats.zigindex 32d2870..fac12c4 100644--- a/src/ipc/stats.zig+++ b/src/ipc/stats.zig@@ -69,6 +69,7 @@ pub const PerformanceStats = struct {taskbar_press_paints: u64 = 0,taskbar_audio_paints: u64 = 0,desktop: @import("protocol.zig").DesktopStats = .{},+ fifo: @import("protocol.zig").FifoStats = .{},anim_frames_scheduled: u64 = 0,anim_wasted_wakeups: u64 = 0,anim_longest_ms: u64 = 0,@@ -141,6 +142,7 @@ pub const PerformanceStats = struct {self.taskbar_press_paints = 0;self.taskbar_audio_paints = 0;self.desktop = .{};+ self.fifo = .{};self.anim_frames_scheduled = 0;self.anim_wasted_wakeups = 0;self.anim_longest_ms = 0;diff --git a/src/ipc_serializers.jsonl b/src/ipc_serializers.jsonlindex 7a67713..0389b34 100644--- a/src/ipc_serializers.jsonl+++ b/src/ipc_serializers.jsonl@@ -67,7 +67,7 @@{"Ok":{"SamplePixels":{"output":"text \"quoted\"\n\\","x":0,"y":0,"width":0,"height":0,"gpu_readback":false,"pixels":[0]}}}{"Ok":{"SamplePixels":{"output":"text \"quoted\"\n\\","x":7,"y":7,"width":7,"height":7,"gpu_readback":true,"pixels":[7]}}}{"Ok":{"PerformanceStats":{"output_commits":0,"output_failed_commits":0,"fps":0.0,"frame_time_ms":0.0,"missed_frames":0,"refresh_hz":0.0,"titlebar_paints":0,"footer_paints":0,"edge_samples_attempted":0,"edge_samples_succeeded":0,"edge_samples_skipped":0,"edge_sample_ns":0,"panel_paints":0,"panel_allocated_bytes":0,"panel_reused_bytes":0,"icon_cache_hits":0,"icon_cache_misses":0,"icon_decode_ns":0,"icon_decode_count":0,"icon_decoded_bytes":0,"icon_queue_depth_max":0,"taskbar_paints":0,"taskbar_paint_ns":0,"taskbar_raster_pixels":0,"taskbar_clock_frame_requests":0,"taskbar_clock_paints":0,"taskbar_start_paints":0,"taskbar_chip_paints":0,"taskbar_tray_paints":0,"taskbar_hover_paints":0,"taskbar_press_paints":0,"taskbar_audio_paints":0,"recent_errors_count":0,"anim_frames_scheduled":0,"anim_wasted_wakeups":0,"anim_longest_ms":0,"anim_speed":0,"anim_enabled":false,"anim_reduced_motion":false}}}-{"Ok":{"PerformanceStats":{"screenshot_selection":{"motion_events":7,"updates":7,"update_ns":7,"toolbar_paints":7,"label_paints":7,"scene_nodes_created":7},"frame_work":{"cpu_frame":{"samples":7,"total_samples":7,"avg_ms":1.23456,"p50_ms":1.23456,"p95_ms":1.23456,"p99_ms":1.23456,"max_ms":1.23456},"taskbar_cpu":{"samples":7,"total_samples":7,"avg_ms":1.23456,"p50_ms":1.23456,"p95_ms":1.23456,"p99_ms":1.23456,"max_ms":1.23456},"chrome_cpu":{"samples":7,"total_samples":7,"avg_ms":1.23456,"p50_ms":1.23456,"p95_ms":1.23456,"p99_ms":1.23456,"max_ms":1.23456},"panels_cpu":{"samples":7,"total_samples":7,"avg_ms":1.23456,"p50_ms":1.23456,"p95_ms":1.23456,"p99_ms":1.23456,"max_ms":1.23456},"anim_cpu":{"samples":7,"total_samples":7,"avg_ms":1.23456,"p50_ms":1.23456,"p95_ms":1.23456,"p99_ms":1.23456,"max_ms":1.23456},"projection_cpu":{"samples":7,"total_samples":7,"avg_ms":1.23456,"p50_ms":1.23456,"p95_ms":1.23456,"p99_ms":1.23456,"max_ms":1.23456},"glass_cpu":{"samples":7,"total_samples":7,"avg_ms":1.23456,"p50_ms":1.23456,"p95_ms":1.23456,"p99_ms":1.23456,"max_ms":1.23456},"scene_commit_cpu":{"samples":7,"total_samples":7,"avg_ms":1.23456,"p50_ms":1.23456,"p95_ms":1.23456,"p99_ms":1.23456,"max_ms":1.23456},"gpu_elapsed":{"samples":7,"total_samples":7,"avg_ms":1.23456,"p50_ms":1.23456,"p95_ms":1.23456,"p99_ms":1.23456,"max_ms":1.23456},"gpu_timing_available":true,"gpu_samples_dropped":7},"output_commits":7,"output_failed_commits":7,"fps":1.2,"frame_time_ms":1.2,"missed_frames":7,"refresh_hz":1.2,"titlebar_paints":7,"footer_paints":7,"edge_samples_attempted":7,"edge_samples_succeeded":7,"edge_samples_skipped":7,"edge_sample_ns":7,"panel_paints":7,"panel_allocated_bytes":7,"panel_reused_bytes":7,"icon_cache_hits":7,"icon_cache_misses":7,"icon_decode_ns":7,"icon_decode_count":7,"icon_decoded_bytes":7,"icon_queue_depth_max":7,"taskbar_paints":7,"taskbar_paint_ns":7,"taskbar_raster_pixels":7,"taskbar_clock_frame_requests":7,"taskbar_clock_paints":7,"taskbar_start_paints":7,"taskbar_chip_paints":7,"taskbar_tray_paints":7,"taskbar_hover_paints":7,"taskbar_press_paints":7,"taskbar_audio_paints":7,"recent_errors_count":7,"anim_frames_scheduled":7,"anim_wasted_wakeups":7,"anim_longest_ms":7,"anim_speed":1.23456,"anim_enabled":true,"anim_reduced_motion":true,"startup":{"build_mode":"text \"quoted\"\n\\","renderer":"text \"quoted\"\n\\","scale":1.23,"output_count":7,"catalog_entries":7,"autostart_count":7,"catalog_state":"text \"quoted\"\n\\","wallpaper_state":"text \"quoted\"\n\\","catalog_provisional":true,"catalog_loading":true,"catalog_generation":7,"renderer_ready_ns":7,"config_ready_ns":7,"catalog_cache_read_ns":7,"catalog_scan_ns":7,"wallpaper_decode_ns":7,"socket_ready_ns":7,"ipc_ready_ns":7,"session_ready_ns":7,"session_clients_started_ns":7,"xwayland_ready_ns":7,"first_presented_ns":7,"first_ipc_ns":7,"first_input_ns":7,"catalog_published_ns":7,"wallpaper_presented_ns":7,"catalog_cache_read_duration_ns":7,"catalog_scan_duration_ns":7,"wallpaper_decode_duration_ns":7,"backend_start_ns":7,"backend_ready_ns":7,"input_ready_ns":7,"first_visible_ns":7,"services_started_ns":7,"login_to_compositor_ns":7,"login_to_visible_ns":7,"reveal_done_ns":7},"desktop":{"paints":7,"damage_pixels":7,"tile_presents":7,"texture_uploads":7},"output_skipped_commits":7,"glass_reblurs":7,"tearing_async_flips":7,"tearing_refused_flips":7}}}+{"Ok":{"PerformanceStats":{"screenshot_selection":{"motion_events":7,"updates":7,"update_ns":7,"toolbar_paints":7,"label_paints":7,"scene_nodes_created":7},"frame_work":{"cpu_frame":{"samples":7,"total_samples":7,"avg_ms":1.23456,"p50_ms":1.23456,"p95_ms":1.23456,"p99_ms":1.23456,"max_ms":1.23456},"taskbar_cpu":{"samples":7,"total_samples":7,"avg_ms":1.23456,"p50_ms":1.23456,"p95_ms":1.23456,"p99_ms":1.23456,"max_ms":1.23456},"chrome_cpu":{"samples":7,"total_samples":7,"avg_ms":1.23456,"p50_ms":1.23456,"p95_ms":1.23456,"p99_ms":1.23456,"max_ms":1.23456},"panels_cpu":{"samples":7,"total_samples":7,"avg_ms":1.23456,"p50_ms":1.23456,"p95_ms":1.23456,"p99_ms":1.23456,"max_ms":1.23456},"anim_cpu":{"samples":7,"total_samples":7,"avg_ms":1.23456,"p50_ms":1.23456,"p95_ms":1.23456,"p99_ms":1.23456,"max_ms":1.23456},"projection_cpu":{"samples":7,"total_samples":7,"avg_ms":1.23456,"p50_ms":1.23456,"p95_ms":1.23456,"p99_ms":1.23456,"max_ms":1.23456},"glass_cpu":{"samples":7,"total_samples":7,"avg_ms":1.23456,"p50_ms":1.23456,"p95_ms":1.23456,"p99_ms":1.23456,"max_ms":1.23456},"scene_commit_cpu":{"samples":7,"total_samples":7,"avg_ms":1.23456,"p50_ms":1.23456,"p95_ms":1.23456,"p99_ms":1.23456,"max_ms":1.23456},"gpu_elapsed":{"samples":7,"total_samples":7,"avg_ms":1.23456,"p50_ms":1.23456,"p95_ms":1.23456,"p99_ms":1.23456,"max_ms":1.23456},"gpu_timing_available":true,"gpu_samples_dropped":7},"output_commits":7,"output_failed_commits":7,"fps":1.2,"frame_time_ms":1.2,"missed_frames":7,"refresh_hz":1.2,"titlebar_paints":7,"footer_paints":7,"edge_samples_attempted":7,"edge_samples_succeeded":7,"edge_samples_skipped":7,"edge_sample_ns":7,"panel_paints":7,"panel_allocated_bytes":7,"panel_reused_bytes":7,"icon_cache_hits":7,"icon_cache_misses":7,"icon_decode_ns":7,"icon_decode_count":7,"icon_decoded_bytes":7,"icon_queue_depth_max":7,"taskbar_paints":7,"taskbar_paint_ns":7,"taskbar_raster_pixels":7,"taskbar_clock_frame_requests":7,"taskbar_clock_paints":7,"taskbar_start_paints":7,"taskbar_chip_paints":7,"taskbar_tray_paints":7,"taskbar_hover_paints":7,"taskbar_press_paints":7,"taskbar_audio_paints":7,"recent_errors_count":7,"anim_frames_scheduled":7,"anim_wasted_wakeups":7,"anim_longest_ms":7,"anim_speed":1.23456,"anim_enabled":true,"anim_reduced_motion":true,"startup":{"build_mode":"text \"quoted\"\n\\","renderer":"text \"quoted\"\n\\","scale":1.23,"output_count":7,"catalog_entries":7,"autostart_count":7,"catalog_state":"text \"quoted\"\n\\","wallpaper_state":"text \"quoted\"\n\\","catalog_provisional":true,"catalog_loading":true,"catalog_generation":7,"renderer_ready_ns":7,"config_ready_ns":7,"catalog_cache_read_ns":7,"catalog_scan_ns":7,"wallpaper_decode_ns":7,"socket_ready_ns":7,"ipc_ready_ns":7,"session_ready_ns":7,"session_clients_started_ns":7,"xwayland_ready_ns":7,"first_presented_ns":7,"first_ipc_ns":7,"first_input_ns":7,"catalog_published_ns":7,"wallpaper_presented_ns":7,"catalog_cache_read_duration_ns":7,"catalog_scan_duration_ns":7,"wallpaper_decode_duration_ns":7,"backend_start_ns":7,"backend_ready_ns":7,"input_ready_ns":7,"first_visible_ns":7,"services_started_ns":7,"login_to_compositor_ns":7,"login_to_visible_ns":7,"reveal_done_ns":7},"desktop":{"paints":7,"damage_pixels":7,"tile_presents":7,"texture_uploads":7},"output_skipped_commits":7,"glass_reblurs":7,"tearing_async_flips":7,"tearing_refused_flips":7,"fifo":{"held":7,"latched":7,"hidden":7,"late":7}}}}{"Ok":{"IdleState":{"enabled":false,"state":"text \"quoted\"\n\\","blank_after_seconds":0,"suspend_after_seconds":0,"idle_ms":0,"is_inhibited":false,"inhibitor_count":0,"suspend_request_count":0,"inhibitors":[{"surface_ptr":0,"window_id":null,"app_id":null,"title":null,"is_active":false,"reason":null}]}}}{"Ok":{"IdleState":{"enabled":true,"state":"text \"quoted\"\n\\","blank_after_seconds":7,"suspend_after_seconds":7,"idle_ms":7,"is_inhibited":true,"inhibitor_count":7,"suspend_request_count":7,"inhibitors":[{"surface_ptr":7,"window_id":7,"app_id":"text \"quoted\"\n\\","title":"text \"quoted\"\n\\","is_active":true,"reason":"text \"quoted\"\n\\"}]}}}{"Ok":{"CaptureState":{"supported":false,"active_sessions":0,"sessions":[{"output":null,"window_id":null}],"last_failure":null,"indicator":null}}}diff --git a/src/node_surface.c b/src/node_surface.cindex 4ef106c..6dd4841 100644--- a/src/node_surface.c+++ b/src/node_surface.c@@ -44,6 +44,10 @@ static struct wlr_output *get_surface_frame_pacing_output(struct wlr_surface *sureturn frame_pacing_output;}+struct wlr_output *rediwm_surface_frame_pacing_output(struct wlr_surface *surface) {+ return get_surface_frame_pacing_output(surface);+}+static int get_tf_preference(enum wlr_color_transfer_function tf) {switch (tf) {case WLR_COLOR_TRANSFER_FUNCTION_GAMMA22:diff --git a/src/node_surface.h b/src/node_surface.hindex a762005..d678f9f 100644--- a/src/node_surface.h+++ b/src/node_surface.h@@ -30,6 +30,11 @@ struct rediwm_surface *rediwm_surface_create(struct rediwm_tree *parent, struct// clip when NULL. The subsurface tree sets it; others use rediwm_subsurface_tree_set_clip.void rediwm_surface_set_clip(struct rediwm_surface *surface, const struct wlr_box *clip);+// The output that paces `surface` (frame callbacks, presentation feedback, fifo-v1+// barriers): the highest-refresh output it is shown on. NULL while it is hidden on every+// output (covered, minimized, another workspace, unmapped, outputs off).+struct wlr_output *rediwm_surface_frame_pacing_output(struct wlr_surface *surface);+// The surface and its subsurfaces, in a tree that follows them, enabled while mapped.struct rediwm_tree *rediwm_subsurface_tree_create(struct rediwm_tree *parent, struct wlr_surface *);// Clips every surface of the subsurface trees at or under `node` to `clip` (in thediff --git a/src/output/frame.zig b/src/output/frame.zigindex c433844..ab642b3 100644--- a/src/output/frame.zig+++ b/src/output/frame.zig@@ -56,6 +56,8 @@ pub fn commitFrameState(output: *Output, state: *wlr.Output.State) bool {if (success) {tearing.committed(output, state);vrr.committed(output, state);+ // A torn flip is not a refresh boundary (fifo-v1 D3).+ if (state.committed.buffer and !state.tearing_page_flip) latched(output);}if (had_transform) {if (success) {@@ -151,9 +153,17 @@ fn callbacksIdle(output: *Output) void {deferFrameDone(output);}+/// The output has latched what it shows for the coming refresh.+fn latched(output: *Output) void {+ output.latch_seq +%= 1;+ if (output.server.fifo) |fifo| fifo.latched(output.wlr_output, output.latch_seq);+}+pub fn handleVblank(output: *Output) c_int {output.vblank_armed = false;output.last_vblank_ns = output.vblank_target_ns;+ // A skipped commit's refresh: the unchanged picture was latched again.+ latched(output);sendFrameDone(output);if (output.frame_wanted) {output.frame_wanted = false;diff --git a/src/server/setup.zig b/src/server/setup.zigindex a93cb3a..0f4fe6f 100644--- a/src/server/setup.zig+++ b/src/server/setup.zig@@ -226,6 +226,11 @@ fn initSession(server: *Server, world_tree: *sn.Tree) CompositorError!void {errdefer server.input.deinit();if (!greeter) server.extra_protocols = @import("../extra_protocols.zig").create(server) orelse return error.ExtraProtocolsCreateFailed;errdefer @import("../extra_protocols.zig").rediwm_protocols_destroy(server.extra_protocols);+ if (!greeter) server.fifo = @import("../fifo.zig").Manager.create(server) catch return error.FifoManagerCreateFailed;+ errdefer if (server.fifo) |fifo| {+ server.fifo = null;+ fifo.destroy();+ };server.activation.init(server) catch return error.ActivationManagerCreateFailed;errdefer server.activation.deinit();server.launch_feedback.init(server);diff --git a/src/server/teardown.zig b/src/server/teardown.zigindex cd839c5..bfc2ce9 100644--- a/src/server/teardown.zig+++ b/src/server/teardown.zig@@ -76,6 +76,10 @@ pub fn deinit(server: *Server) void {server.window_tabs.deinit();@import("../extra_protocols.zig").rediwm_protocols_destroy(server.extra_protocols);server.extra_protocols = null;+ if (server.fifo) |fifo| {+ server.fifo = null;+ fifo.destroy();+ }server.activation.deinit();server.launch_feedback.deinit();if (server.text_input) |relay| {diff --git a/src/ui_tests.zig b/src/ui_tests.zigindex 16dea2c..6a6d64a 100644--- a/src/ui_tests.zig+++ b/src/ui_tests.zig@@ -84,6 +84,7 @@ test {_ = @import("output/late_render_tests.zig");_ = @import("output/tearing_policy.zig");_ = @import("output/vrr_policy.zig");+ _ = @import("fifo.zig");_ = @import("config").keybinds;_ = @import("osd_paint.zig");_ = @import("osd.zig");diff --git a/tests/fifo.py b/tests/fifo.pynew file mode 100644index 0000000..643f9f2--- /dev/null+++ b/tests/fifo.py@@ -0,0 +1,304 @@+#!/usr/bin/env python3+"""wp_fifo_v1 on a headless GLES2 output (docs/plans/fifo.md).++The fixture (tests/fifo_client.c) sends commits back to back, so only the+compositor's barrier can spread them over refreshes; presentation feedback+shows the outcome. Cases: barriers across two and more commits (with a+no-fifo control that must collapse), an update that only sets a barrier,+synchronized and desynchronized subsurfaces, hidden surfaces (minimized and+covered) released at the 20 Hz fallback, a barrier queued behind an explicit+sync acquire point, destroying the fifo or the surface with commits held,+and both protocol errors; then vkcube (Mesa's Vulkan WSI) shown and+minimized. Explicit sync skips without a render node, GBM or a+timeline-capable renderer; the vkcube case without vkcube or a driver that+uses fifo-v1.+"""+import os+from pathlib import Path+import shutil+import subprocess+import sys+import tempfile+import time++from desktop_zoom import ROOT, wait_for+from ipc_client import IPCClient, spawn_compositor, stop_process++PROTOCOLS = (+ ("xdg-shell", "stable/xdg-shell/xdg-shell.xml"),+ ("presentation-time", "stable/presentation-time/presentation-time.xml"),+ ("fifo-v1", "staging/fifo/fifo-v1.xml"),+ ("linux-dmabuf-v1", "stable/linux-dmabuf/linux-dmabuf-v1.xml"),+ ("linux-drm-syncobj-v1", "staging/linux-drm-syncobj/linux-drm-syncobj-v1.xml"),+)+HIDDEN_PERIOD = 0.050+++def render_node():+ return next((str(p) for p in sorted(Path("/dev/dri").glob("renderD*"))), None)+++def build_client(tmp):+ protocols = Path(subprocess.check_output(+ ["pkg-config", "--variable=pkgdatadir", "wayland-protocols"], text=True).strip())+ sources = []+ for name, path in PROTOCOLS:+ for mode, suffix in (("client-header", "client-protocol.h"), ("private-code", "protocol.c")):+ subprocess.run(["wayland-scanner", mode, str(protocols / path),+ str(tmp / f"{name}-{suffix}")], check=True)+ sources.append(str(tmp / f"{name}-protocol.c"))+ flags = subprocess.check_output(["pkg-config", "--cflags", "--libs", "libdrm", "gbm"], text=True).split()+ subprocess.run(["cc", "-Wall", "-Wextra", "-Werror", f"-I{tmp}", str(ROOT / "tests/fifo_client.c"),+ *sources, *flags, "-lwayland-client", "-o", str(tmp / "client")], check=True)+++def parse(lines):+ presented, discarded, other = {}, [], []+ for line in lines:+ fields = line.split()+ if fields[0] == "presented":+ presented[fields[1]] = (int(fields[2]), int(fields[3]))+ elif fields[0] == "discarded":+ discarded.append(fields[1])+ else:+ other.append(line)+ return presented, discarded, other+++def assert_paced(presented, labels, period_ns):+ """Every update reached its own refresh, in order."""+ missing = [label for label in labels if label not in presented]+ assert not missing, f"not presented: {missing} ({presented})"+ # Headless reports no refresh counter (seq 0): judge by presentation time.+ times = [presented[label][1] for label in labels]+ gaps = [b - a for a, b in zip(times, times[1:])]+ assert all(gap >= period_ns // 2 for gap in gaps), f"two updates shared a refresh: gaps {gaps} ns"+++def vkcube_case(tmp, env, ipc, refresh_hz):+ """Mesa's Vulkan WSI in FIFO mode: paced by barriers alone (it asks for+ no frame callbacks once fifo-v1 is offered), 20 Hz while minimized."""+ if not shutil.which("vkcube"):+ print("SKIP: vkcube (not installed)")+ return+ log_path = tmp / "vkcube.log"+ with log_path.open("w") as output:+ vk = subprocess.Popen(["vkcube", "--wsi", "wayland"], env=dict(env, WAYLAND_DEBUG="1"),+ stdout=subprocess.DEVNULL, stderr=output)+ try:+ def waits():+ return log_path.read_text(errors="replace").count(".wait_barrier(")++ def rate(seconds):+ start, began = waits(), time.monotonic()+ time.sleep(seconds)+ return (waits() - start) / (time.monotonic() - began)++ win = wait_for(lambda: next((w for w in ipc.get_windows() if w["app_id"] != "rediwm.fifo-fixture"), None),+ "vkcube did not map", timeout=30)+ time.sleep(0.5)+ if waits() == 0:+ print("SKIP: vkcube's Vulkan driver does not use wp_fifo_v1")+ return+ ipc.reset_perf()+ shown = rate(2.0)+ stats = dict(ipc.get_perf().get("fifo") or {})+ assert 0.8 * refresh_hz <= shown <= 1.1 * refresh_hz, (shown, refresh_hz)+ assert stats["late"] == 0 and stats["latched"] > 0, stats+ ipc.minimize(win["id"])+ wait_for(lambda: ipc.get_window_debug(win["id"])["minimized"], "vkcube did not minimize")+ time.sleep(0.5)+ hidden = rate(2.0)+ assert 0.6 / HIDDEN_PERIOD <= hidden <= 1.2 / HIDDEN_PERIOD, hidden+ ipc.restore(win["id"])+ time.sleep(1.0)+ restored = rate(1.0)+ assert restored >= 0.8 * refresh_hz, restored+ text = log_path.read_text(errors="replace")+ frames = text.count(".frame(new id")+ print(f"fifo: vkcube {shown:.0f}/s shown, {hidden:.1f}/s minimized, {restored:.0f}/s restored "+ f"({frames} frame callbacks requested)")+ finally:+ vk.terminate()+ vk.wait(timeout=10)+++def run():+ node = render_node()+ with tempfile.TemporaryDirectory(prefix="rediwm-fifo-") as directory:+ tmp = Path(directory)+ build_client(tmp)+ extra = {"XDG_CACHE_HOME": str(tmp / "cache")}+ if node:+ extra["WLR_RENDER_DRM_DEVICE"] = node+ compositor, log = spawn_compositor(+ tmp, renderer=os.environ.get("REDIWM_TEST_RENDERER", "gles2"),+ config_content="[compositor]\nxwayland = false\n", env_extra=extra)+ client = None+ client_log = tmp / "client.log"+ try:+ socket_path = wait_for(lambda: next(tmp.glob("rediwm-*.sock"), None), "IPC unavailable")+ display = next(p.name for p in tmp.glob("wayland-*") if not p.name.endswith(".lock"))+ env = dict(os.environ, XDG_RUNTIME_DIR=str(tmp), WAYLAND_DISPLAY=display)+ if node:+ env["FIFO_RENDER_NODE"] = node+ with client_log.open("w") as output:+ client = subprocess.Popen([str(tmp / "client")], stdin=subprocess.PIPE, stdout=output,+ stderr=output, text=True, env=env)+ done_count = 1+ wait_for(lambda: client_log.read_text().splitlines().count("done") >= 1, "fixture did not start")+ ready = next(l for l in client_log.read_text().splitlines() if l.startswith("ready")).split()+ has_dmabuf, has_syncobj = ready[1] == "1", ready[2] == "1"++ def command(value, timeout=20):+ nonlocal done_count+ start = len(client_log.read_text().splitlines())+ client.stdin.write(value + "\n")+ client.stdin.flush()+ done_count += 1+ wait_for(lambda: client_log.read_text().splitlines().count("done") >= done_count,+ f"fixture did not finish {value!r}", timeout=timeout)+ lines = [l for l in client_log.read_text().splitlines()[start:] if l != "done"]+ assert not any(l.startswith(("pending", "timeout", "unknown", "display error"))+ for l in lines), (value, lines)+ return lines++ with IPCClient(socket_path) as ipc:+ win = wait_for(lambda: next((w for w in ipc.get_windows()+ if w["app_id"] == "rediwm.fifo-fixture"), None), "fixture did not map")+ output = ipc.get_outputs()[0]+ refresh_hz = output.get("refresh") or 60+ if refresh_hz > 1000:+ refresh_hz /= 1000+ period_ns = int(1e9 / refresh_hz)+ ipc.action("move_window_to", {"id": win["id"], "x": 200, "y": 200})+ ipc.wait_for("window_geometry_settled", window_id=win["id"])++ def fifo_stats():+ return dict(ipc.get_perf().get("fifo") or {})++ # Control: without barriers a burst collapses into one refresh.+ presented, discarded, _ = parse(command("plain 6"))+ assert discarded, f"control burst was not collapsed: {presented}"++ # Barriers across commits: each update gets its own refresh.+ before = fifo_stats()+ presented, discarded, _ = parse(command("burst 8"))+ assert not discarded, discarded+ assert_paced(presented, [f"b{i}" for i in range(8)], period_ns)+ after = fifo_stats()+ assert after["held"] - before["held"] >= 7, (before, after)+ assert after["late"] == before["late"], f"latches missed: {before} -> {after}"+ assert after["hidden"] == before["hidden"], (before, after)+ print(f"fifo: 8 back-to-back commits on 8 refreshes ({refresh_hz:g} Hz)")++ # An update that changes nothing still gets a latch (vblank).+ before = fifo_stats()+ lines = command("empty")+ presented, _, other = parse(lines)+ assert "e" in presented, lines+ latency = float(next(l for l in other if l.startswith("latency_ms")).split()[1])+ after = fifo_stats()+ assert after["late"] == before["late"], f"empty barrier fell back: {before} -> {after}"+ assert after["latched"] > before["latched"], (before, after)+ assert latency < 4 * period_ns / 1e6, latency+ print(f"fifo: barrier-only update latched by the vblank ({latency:.1f} ms)")++ # Synchronized subsurfaces ignore wait_barrier; desynchronized do not.+ presented, discarded, _ = parse(command("sub 6 sync"))+ assert discarded, f"a synchronized subsurface was held: {presented}"+ presented, discarded, _ = parse(command("sub 6 desync"))+ assert not discarded, discarded+ assert_paced(presented, [f"s{i}" for i in range(6)], period_ns)+ print("fifo: synchronized subsurface exempt, desynchronized paced")++ # Hidden surfaces: released at the 20 Hz fallback, never stuck.+ def hidden_case(label):+ ipc.reset_perf()+ started = time.monotonic()+ command("send 11")+ wait_for(lambda: fifo_stats().get("hidden", 0) >= 10,+ f"{label}: hidden updates were not released", timeout=10)+ elapsed = time.monotonic() - started+ stats = fifo_stats()+ assert 8 * HIDDEN_PERIOD <= elapsed <= 40 * HIDDEN_PERIOD, (label, elapsed, stats)+ assert stats["late"] == 0, (label, stats)+ print(f"fifo: {label} surface released 10 updates in {elapsed:.2f} s")++ ipc.minimize(win["id"])+ wait_for(lambda: ipc.get_window_debug(win["id"])["minimized"], "fixture did not minimize")+ time.sleep(0.2)+ hidden_case("minimized")+ ipc.restore(win["id"])+ ipc.wait_for("window_geometry_settled", window_id=win["id"])+ presented, discarded, _ = parse(command("burst 3"))+ assert_paced(presented, ["b0", "b1", "b2"], period_ns)++ command("cover")+ cover = wait_for(lambda: next((w for w in ipc.get_windows()+ if w["app_id"] == "rediwm.fifo-cover"), None), "cover did not map")+ ipc.action("move_window_to", {"id": cover["id"], "x": 60, "y": 60})+ ipc.focus_window(cover["id"])+ ipc.wait_for("window_geometry_settled", window_id=cover["id"])+ time.sleep(0.2)+ hidden_case("covered")+ command("uncover")+ presented, discarded, _ = parse(command("burst 3"))+ assert_paced(presented, ["b0", "b1", "b2"], period_ns)++ # Explicit sync: a barrier still waiting on its acquire point.+ if has_dmabuf and has_syncobj and node:+ lines = command("explicit-sync")+ presented, discarded, other = parse(lines)+ assert "unresolved-before-signal 1" in other, lines+ assert not discarded, lines+ gap = presented["es2"][1] - presented["es1"][1]+ assert gap >= period_ns // 2, f"es1 and es2 shared a refresh ({gap} ns): {lines}"+ print("fifo: barrier queued behind an acquire point was waited for")+ else:+ print("SKIP: explicit sync (no dmabuf/syncobj or render node)")++ # Destroying the fifo releases held updates; the last one shows.+ presented, discarded, _ = parse(command("destroy-fifo 6"))+ assert "d5" in presented, (presented, discarded)+ # Destroying the surface with updates held drops them safely.+ before = fifo_stats()+ assert "survived" in command("destroy-surface 6")+ after = fifo_stats()+ assert after["held"] - before["held"] >= 4, f"nothing was held at destroy: {before} -> {after}"+ presented, _, _ = parse(command("burst 3"))+ assert_paced(presented, ["b0", "b1", "b2"], period_ns)+ assert ipc.get_windows() is not None+ print("fifo: destroying the fifo or its surface with updates held")++ vkcube_case(tmp, env, ipc, refresh_hz)++ for mode, expected in (("already-exists", "error wp_fifo_manager_v1 0"),+ ("surface-destroyed", "error wp_fifo_v1 0"),+ ("recreate", "error none 0")):+ result = subprocess.run([str(tmp / "client"), mode], env=env, capture_output=True,+ text=True, timeout=10)+ assert result.returncode == 0 and expected in result.stdout, (mode, result.stdout, result.stderr)+ print("fifo: protocol errors")++ client.stdin.close()+ client.wait(timeout=5)+ assert client.returncode == 0, client_log.read_text()+ assert compositor.poll() is None, "compositor exited"+ except Exception:+ print((tmp / "compositor.log").read_text()[-6000:])+ if client_log.exists():+ print(client_log.read_text()[-4000:])+ raise+ finally:+ if client and client.poll() is None:+ stop_process(client)+ if compositor.poll() is None:+ stop_process(compositor)+ log.close()+ print("fifo checks passed")+ return 0+++if __name__ == "__main__":+ sys.exit(run())diff --git a/tests/fifo_client.c b/tests/fifo_client.cnew file mode 100644index 0000000..00966d3--- /dev/null+++ b/tests/fifo_client.c@@ -0,0 +1,554 @@+// wp_fifo_v1 fixture for tests/fifo.py. No host-session access.+//+// Default mode reads one command per stdin line and answers on stdout, ending+// each answer with "done". Commits are sent back to back (no waiting between+// them) so only the compositor's barrier can spread them over refreshes; the+// outcome is read from presentation feedback ("presented <label> <seq> <ns>"+// or "discarded <label>"). `fifo_client already-exists` and+// `fifo_client surface-destroyed` provoke the two protocol errors instead.+#define _GNU_SOURCE+#include "fifo-v1-client-protocol.h"+#include "linux-dmabuf-v1-client-protocol.h"+#include "linux-drm-syncobj-v1-client-protocol.h"+#include "presentation-time-client-protocol.h"+#include "xdg-shell-client-protocol.h"+#include <assert.h>+#include <errno.h>+#include <fcntl.h>+#include <gbm.h>+#include <inttypes.h>+#include <poll.h>+#include <stdbool.h>+#include <stdint.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>+#include <sys/mman.h>+#include <time.h>+#include <unistd.h>+#include <wayland-client.h>+#include <xf86drm.h>++static struct wl_display *display;+static struct wl_compositor *compositor;+static struct wl_subcompositor *subcompositor;+static struct wl_shm *shm;+static struct xdg_wm_base *wm;+static struct wp_presentation *presentation;+static struct wp_fifo_manager_v1 *fifo_manager;+static struct zwp_linux_dmabuf_v1 *dmabuf;+static struct wp_linux_drm_syncobj_manager_v1 *syncobj_manager;+static clockid_t clock_id = CLOCK_MONOTONIC;+static unsigned color_seq;++struct window {+ struct wl_surface *surface;+ struct xdg_surface *xdg;+ struct xdg_toplevel *toplevel;+ struct wp_fifo_v1 *fifo;+ bool configured;+ int width, height;+ bool opaque;+};++#define MAX_FEEDBACK 64+// Heap records: a forgotten feedback ("send") still gets its event later and+// must not land in a record the next command reuses.+struct feedback {+ char label[16];+ bool resolved, presented, orphan;+ uint64_t seq, ns;+};+static struct feedback *feedbacks[MAX_FEEDBACK];+static unsigned feedback_count;++static void feedback_resolved(struct feedback *fb) {+ fb->resolved = true;+ if (fb->orphan) free(fb);+}++// Stops tracking the current feedbacks; they free themselves when resolved.+static void forget_feedback(void) {+ for (unsigned i = 0; i < feedback_count; i++) {+ if (feedbacks[i]->resolved) free(feedbacks[i]);+ else feedbacks[i]->orphan = true;+ }+ feedback_count = 0;+}++static uint64_t now_ns(void) {+ struct timespec ts;+ clock_gettime(clock_id, &ts);+ return (uint64_t)ts.tv_sec * 1000000000u + (uint64_t)ts.tv_nsec;+}++// ---- Registry ------------------------------------------------------------------++static void registry_global(void *data, struct wl_registry *registry, uint32_t name,+ const char *interface, uint32_t version) {+ (void)data;+ if (strcmp(interface, wl_compositor_interface.name) == 0)+ compositor = wl_registry_bind(registry, name, &wl_compositor_interface, 4);+ else if (strcmp(interface, wl_subcompositor_interface.name) == 0)+ subcompositor = wl_registry_bind(registry, name, &wl_subcompositor_interface, 1);+ else if (strcmp(interface, wl_shm_interface.name) == 0)+ shm = wl_registry_bind(registry, name, &wl_shm_interface, 1);+ else if (strcmp(interface, xdg_wm_base_interface.name) == 0)+ wm = wl_registry_bind(registry, name, &xdg_wm_base_interface, 1);+ else if (strcmp(interface, wp_presentation_interface.name) == 0)+ presentation = wl_registry_bind(registry, name, &wp_presentation_interface, 1);+ else if (strcmp(interface, wp_fifo_manager_v1_interface.name) == 0)+ fifo_manager = wl_registry_bind(registry, name, &wp_fifo_manager_v1_interface, 1);+ else if (strcmp(interface, zwp_linux_dmabuf_v1_interface.name) == 0 && version >= 3)+ dmabuf = wl_registry_bind(registry, name, &zwp_linux_dmabuf_v1_interface, 3);+ else if (strcmp(interface, wp_linux_drm_syncobj_manager_v1_interface.name) == 0)+ syncobj_manager = wl_registry_bind(registry, name, &wp_linux_drm_syncobj_manager_v1_interface, 1);+}+static void registry_remove(void *data, struct wl_registry *registry, uint32_t name) {+ (void)data, (void)registry, (void)name;+}+static const struct wl_registry_listener registry_listener = {registry_global, registry_remove};++static void wm_ping(void *data, struct xdg_wm_base *base, uint32_t serial) {+ (void)data;+ xdg_wm_base_pong(base, serial);+}+static const struct xdg_wm_base_listener wm_listener = {wm_ping};++static void presentation_clock(void *data, struct wp_presentation *p, uint32_t id) {+ (void)data, (void)p;+ clock_id = (clockid_t)id;+}+static const struct wp_presentation_listener presentation_listener = {presentation_clock};++// ---- Feedback ------------------------------------------------------------------++static void fb_sync_output(void *data, struct wp_presentation_feedback *f, struct wl_output *o) {+ (void)data, (void)f, (void)o;+}+static void fb_presented(void *data, struct wp_presentation_feedback *f, uint32_t sec_hi,+ uint32_t sec_lo, uint32_t nsec, uint32_t refresh, uint32_t seq_hi,+ uint32_t seq_lo, uint32_t flags) {+ (void)refresh, (void)flags;+ struct feedback *fb = data;+ fb->presented = true;+ fb->seq = ((uint64_t)seq_hi << 32) | seq_lo;+ fb->ns = ((((uint64_t)sec_hi << 32) | sec_lo) * 1000000000u) + nsec;+ wp_presentation_feedback_destroy(f);+ feedback_resolved(fb);+}+static void fb_discarded(void *data, struct wp_presentation_feedback *f) {+ wp_presentation_feedback_destroy(f);+ feedback_resolved(data);+}+static const struct wp_presentation_feedback_listener fb_listener = {fb_sync_output, fb_presented,+ fb_discarded};++static void request_feedback(struct wl_surface *surface, const char *label) {+ assert(feedback_count < MAX_FEEDBACK);+ struct feedback *fb = calloc(1, sizeof(*fb));+ assert(fb);+ feedbacks[feedback_count++] = fb;+ snprintf(fb->label, sizeof(fb->label), "%s", label);+ wp_presentation_feedback_add_listener(wp_presentation_feedback(presentation, surface),+ &fb_listener, fb);+}++// Dispatches until `done()` or the timeout; false on timeout or error.+static bool pump(bool (*done)(void), int timeout_ms) {+ uint64_t deadline = now_ns() + (uint64_t)timeout_ms * 1000000u;+ while (!done()) {+ if (wl_display_dispatch_pending(display) < 0) return false;+ if (done()) break;+ if (wl_display_flush(display) < 0 && errno != EAGAIN) return false;+ uint64_t now = now_ns();+ if (now >= deadline) return false;+ struct pollfd pfd = {.fd = wl_display_get_fd(display), .events = POLLIN};+ if (wl_display_prepare_read(display) != 0) continue;+ int ready = poll(&pfd, 1, (int)((deadline - now) / 1000000u) + 1);+ if (ready > 0) {+ if (wl_display_read_events(display) < 0) return false;+ } else {+ wl_display_cancel_read(display);+ }+ }+ return true;+}++static bool all_resolved(void) {+ for (unsigned i = 0; i < feedback_count; i++)+ if (!feedbacks[i]->resolved) return false;+ return true;+}++// Reports and forgets every feedback.+static void report(void) {+ bool ok = pump(all_resolved, 10000);+ for (unsigned i = 0; i < feedback_count; i++) {+ struct feedback *fb = feedbacks[i];+ if (!fb->resolved)+ printf("pending %s\n", fb->label);+ else if (fb->presented)+ printf("presented %s %" PRIu64 " %" PRIu64 "\n", fb->label, fb->seq, fb->ns);+ else+ printf("discarded %s\n", fb->label);+ }+ if (!ok) printf("timeout\n");+ forget_feedback();+}++// ---- Buffers -------------------------------------------------------------------++static void buffer_release(void *data, struct wl_buffer *buffer) {+ (void)data;+ wl_buffer_destroy(buffer);+}+static const struct wl_buffer_listener buffer_listener = {buffer_release};++static void attach_shm(struct wl_surface *surface, int width, int height, bool opaque) {+ const int stride = width * 4;+ const size_t size = (size_t)stride * (size_t)height;+ int fd = memfd_create("fifo-fixture", MFD_CLOEXEC);+ assert(fd >= 0 && ftruncate(fd, (off_t)size) == 0);+ uint32_t *pixels = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);+ assert(pixels != MAP_FAILED);+ uint32_t color = 0xff203050u + ((++color_seq & 0x3f) << 16);+ for (size_t i = 0; i < size / 4; i++) pixels[i] = color;+ struct wl_shm_pool *pool = wl_shm_create_pool(shm, fd, (int32_t)size);+ struct wl_buffer *buffer = wl_shm_pool_create_buffer(+ pool, 0, width, height, stride, opaque ? WL_SHM_FORMAT_XRGB8888 : WL_SHM_FORMAT_ARGB8888);+ wl_buffer_add_listener(buffer, &buffer_listener, NULL);+ wl_surface_attach(surface, buffer, 0, 0);+ wl_surface_damage_buffer(surface, 0, 0, width, height);+ wl_shm_pool_destroy(pool);+ munmap(pixels, size);+ close(fd);+}++// ---- Windows -------------------------------------------------------------------++static void xdg_configure(void *data, struct xdg_surface *xdg, uint32_t serial) {+ struct window *w = data;+ xdg_surface_ack_configure(xdg, serial);+ w->configured = true;+}+static const struct xdg_surface_listener xdg_listener = {xdg_configure};++static void toplevel_configure(void *data, struct xdg_toplevel *t, int32_t w, int32_t h,+ struct wl_array *states) {+ (void)data, (void)t, (void)w, (void)h, (void)states;+}+static void toplevel_close(void *data, struct xdg_toplevel *t) { (void)data, (void)t; }+static const struct xdg_toplevel_listener toplevel_listener = {+ .configure = toplevel_configure, .close = toplevel_close};++static struct window *configuring;+static bool window_configured(void) { return configuring->configured; }++// Maps a toplevel with a first shm buffer (none when `no_buffer`) and waits+// until it is shown.+static void window_create(struct window *w, const char *app_id, int width, int height, bool opaque,+ bool with_fifo, bool no_buffer) {+ *w = (struct window){.width = width, .height = height, .opaque = opaque};+ w->surface = wl_compositor_create_surface(compositor);+ if (with_fifo) w->fifo = wp_fifo_manager_v1_get_fifo(fifo_manager, w->surface);+ w->xdg = xdg_wm_base_get_xdg_surface(wm, w->surface);+ xdg_surface_add_listener(w->xdg, &xdg_listener, w);+ w->toplevel = xdg_surface_get_toplevel(w->xdg);+ xdg_toplevel_add_listener(w->toplevel, &toplevel_listener, w);+ xdg_toplevel_set_app_id(w->toplevel, app_id);+ xdg_toplevel_set_title(w->toplevel, app_id);+ wl_surface_commit(w->surface);+ configuring = w;+ assert(pump(window_configured, 5000));+ if (no_buffer) return;+ attach_shm(w->surface, width, height, opaque);+ request_feedback(w->surface, "map");+ wl_surface_commit(w->surface);+ report();+}++static void window_destroy(struct window *w) {+ if (w->fifo) wp_fifo_v1_destroy(w->fifo);+ xdg_toplevel_destroy(w->toplevel);+ xdg_surface_destroy(w->xdg);+ wl_surface_destroy(w->surface);+ *w = (struct window){0};+}++// Commits `n` buffers back to back, each with set_barrier + wait_barrier+// when `fifo`, and presentation feedback.+static void burst(struct window *w, const char *prefix, int n, bool fifo) {+ for (int i = 0; i < n; i++) {+ char label[16];+ snprintf(label, sizeof(label), "%s%d", prefix, i);+ attach_shm(w->surface, w->width, w->height, w->opaque);+ if (fifo) {+ wp_fifo_v1_set_barrier(w->fifo);+ wp_fifo_v1_wait_barrier(w->fifo);+ }+ request_feedback(w->surface, label);+ wl_surface_commit(w->surface);+ }+ wl_display_flush(display);+}++// ---- Subsurfaces ---------------------------------------------------------------++static void subsurface_case(struct window *parent, int n, bool sync) {+ struct wl_surface *surface = wl_compositor_create_surface(compositor);+ struct wl_subsurface *sub = wl_subcompositor_get_subsurface(subcompositor, surface, parent->surface);+ struct wp_fifo_v1 *fifo = wp_fifo_manager_v1_get_fifo(fifo_manager, surface);+ wl_subsurface_set_position(sub, 20, 20);+ if (sync) wl_subsurface_set_sync(sub);+ else wl_subsurface_set_desync(sub);+ attach_shm(surface, 120, 80, true);+ request_feedback(surface, "sub-map");+ wl_surface_commit(surface);+ wl_surface_commit(parent->surface);+ report();+ for (int i = 0; i < n; i++) {+ char label[16];+ snprintf(label, sizeof(label), "s%d", i);+ attach_shm(surface, 120, 80, true);+ wp_fifo_v1_set_barrier(fifo);+ wp_fifo_v1_wait_barrier(fifo);+ request_feedback(surface, label);+ wl_surface_commit(surface);+ // A synchronized subsurface's state applies with its parent's commit.+ wl_surface_commit(parent->surface);+ }+ wl_display_flush(display);+ report();+ wp_fifo_v1_destroy(fifo);+ wl_subsurface_destroy(sub);+ wl_surface_destroy(surface);+ wl_surface_commit(parent->surface);+ wl_display_roundtrip(display);+}++// ---- Explicit sync -------------------------------------------------------------++struct timeline {+ uint32_t handle;+ struct wp_linux_drm_syncobj_timeline_v1 *proxy;+};++static int drm_fd = -1;+static struct gbm_device *gbm;++static void timeline_create(struct timeline *t) {+ assert(drmSyncobjCreate(drm_fd, 0, &t->handle) == 0);+ int fd = -1;+ assert(drmSyncobjHandleToFD(drm_fd, t->handle, &fd) == 0);+ t->proxy = wp_linux_drm_syncobj_manager_v1_import_timeline(syncobj_manager, fd);+ close(fd);+}++static void timeline_signal(struct timeline *t, uint64_t point) {+ assert(drmSyncobjTimelineSignal(drm_fd, &t->handle, &point, 1) == 0);+}++static struct wl_buffer *dmabuf_buffer(int width, int height) {+ struct gbm_bo *bo = gbm_bo_create(gbm, (uint32_t)width, (uint32_t)height, GBM_FORMAT_XRGB8888,+ GBM_BO_USE_LINEAR | GBM_BO_USE_RENDERING);+ assert(bo);+ int fd = gbm_bo_get_fd(bo);+ assert(fd >= 0);+ uint64_t modifier = gbm_bo_get_modifier(bo);+ struct zwp_linux_buffer_params_v1 *params = zwp_linux_dmabuf_v1_create_params(dmabuf);+ zwp_linux_buffer_params_v1_add(params, fd, 0, gbm_bo_get_offset(bo, 0), gbm_bo_get_stride(bo),+ (uint32_t)(modifier >> 32), (uint32_t)modifier);+ struct wl_buffer *buffer = zwp_linux_buffer_params_v1_create_immed(+ params, width, height, GBM_FORMAT_XRGB8888, 0);+ zwp_linux_buffer_params_v1_destroy(params);+ close(fd);+ // The compositor imported the dmabuf; the bo can go once the buffer does.+ // A fixture this short keeps it for its lifetime.+ return buffer;+}++// Commit 1 sets a barrier but its acquire point is not yet materialized, so+// wlroots caches it; commit 2 waits for that barrier. When the point is+// signalled, commit 1 applies and commit 2 must still wait one latch.+static void explicit_sync_case(void) {+ const char *node = getenv("FIFO_RENDER_NODE");+ drm_fd = open(node ? node : "/dev/dri/renderD128", O_RDWR | O_CLOEXEC);+ assert(drm_fd >= 0);+ gbm = gbm_create_device(drm_fd);+ assert(gbm);+ struct window w;+ window_create(&w, "rediwm.fifo-sync", 320, 200, true, true, true);+ struct wp_linux_drm_syncobj_surface_v1 *sync =+ wp_linux_drm_syncobj_manager_v1_get_surface(syncobj_manager, w.surface);+ struct timeline map_tl, first_tl, second_tl, release_tl;+ timeline_create(&map_tl);+ timeline_create(&first_tl);+ timeline_create(&second_tl);+ timeline_create(&release_tl);++ timeline_signal(&map_tl, 1);+ wl_surface_attach(w.surface, dmabuf_buffer(320, 200), 0, 0);+ wl_surface_damage_buffer(w.surface, 0, 0, 320, 200);+ wp_linux_drm_syncobj_surface_v1_set_acquire_point(sync, map_tl.proxy, 0, 1);+ wp_linux_drm_syncobj_surface_v1_set_release_point(sync, release_tl.proxy, 0, 1);+ request_feedback(w.surface, "es-map");+ wl_surface_commit(w.surface);+ report();++ wl_surface_attach(w.surface, dmabuf_buffer(320, 200), 0, 0);+ wl_surface_damage_buffer(w.surface, 0, 0, 320, 200);+ wp_linux_drm_syncobj_surface_v1_set_acquire_point(sync, first_tl.proxy, 0, 1);+ wp_linux_drm_syncobj_surface_v1_set_release_point(sync, release_tl.proxy, 0, 2);+ wp_fifo_v1_set_barrier(w.fifo);+ request_feedback(w.surface, "es1");+ wl_surface_commit(w.surface);++ timeline_signal(&second_tl, 1);+ wl_surface_attach(w.surface, dmabuf_buffer(320, 200), 0, 0);+ wl_surface_damage_buffer(w.surface, 0, 0, 320, 200);+ wp_linux_drm_syncobj_surface_v1_set_acquire_point(sync, second_tl.proxy, 0, 1);+ wp_linux_drm_syncobj_surface_v1_set_release_point(sync, release_tl.proxy, 0, 3);+ wp_fifo_v1_set_barrier(w.fifo);+ wp_fifo_v1_wait_barrier(w.fifo);+ request_feedback(w.surface, "es2");+ wl_surface_commit(w.surface);+ // Both commits are queued in the compositor before the first can apply.+ wl_display_roundtrip(display);+ usleep(50000);+ wl_display_roundtrip(display);+ printf("unresolved-before-signal %d\n", feedbacks[0]->resolved || feedbacks[1]->resolved ? 0 : 1);+ timeline_signal(&first_tl, 1);+ report();++ wp_linux_drm_syncobj_surface_v1_destroy(sync);+ window_destroy(&w);+ wl_display_roundtrip(display);+}++// ---- Protocol errors -------------------------------------------------------------++static int expect_error(const struct wl_interface *interface, uint32_t code) {+ wl_display_roundtrip(display);+ const struct wl_interface *got = NULL;+ uint32_t id = 0;+ if (wl_display_get_error(display) != EPROTO) {+ printf("no protocol error\n");+ return 1;+ }+ uint32_t got_code = wl_display_get_protocol_error(display, &got, &id);+ printf("error %s %u\n", got ? got->name : "?", got_code);+ return got == interface && got_code == code ? 0 : 1;+}++static int error_mode(const char *mode) {+ struct wl_surface *surface = wl_compositor_create_surface(compositor);+ struct wp_fifo_v1 *fifo = wp_fifo_manager_v1_get_fifo(fifo_manager, surface);+ if (strcmp(mode, "already-exists") == 0) {+ wp_fifo_manager_v1_get_fifo(fifo_manager, surface);+ return expect_error(&wp_fifo_manager_v1_interface, WP_FIFO_MANAGER_V1_ERROR_ALREADY_EXISTS);+ }+ if (strcmp(mode, "recreate") == 0) {+ // A fifo may be made again once the first is destroyed.+ wp_fifo_v1_destroy(fifo);+ wp_fifo_manager_v1_get_fifo(fifo_manager, surface);+ wl_display_roundtrip(display);+ printf("error none %d\n", wl_display_get_error(display));+ return wl_display_get_error(display) == 0 ? 0 : 1;+ }+ wl_surface_destroy(surface);+ wp_fifo_v1_set_barrier(fifo);+ return expect_error(&wp_fifo_v1_interface, WP_FIFO_V1_ERROR_SURFACE_DESTROYED);+}++// ---- Commands --------------------------------------------------------------------++int main(int argc, char **argv) {+ display = wl_display_connect(NULL);+ assert(display);+ struct wl_registry *registry = wl_display_get_registry(display);+ wl_registry_add_listener(registry, ®istry_listener, NULL);+ wl_display_roundtrip(display);+ if (!fifo_manager) {+ printf("no wp_fifo_manager_v1\n");+ return 1;+ }+ assert(compositor && subcompositor && shm && wm && presentation);+ xdg_wm_base_add_listener(wm, &wm_listener, NULL);+ wp_presentation_add_listener(presentation, &presentation_listener, NULL);+ wl_display_roundtrip(display);+ if (argc > 1) return error_mode(argv[1]);++ struct window main_window, cover = {0}, extra;+ window_create(&main_window, "rediwm.fifo-fixture", 320, 200, false, true, false);+ printf("ready %d %d\n", dmabuf != NULL, syncobj_manager != NULL);+ printf("done\n");+ fflush(stdout);++ char line[128];+ while (fgets(line, sizeof(line), stdin)) {+ int n = 0;+ if (sscanf(line, "burst %d", &n) == 1) {+ burst(&main_window, "b", n, true);+ report();+ } else if (sscanf(line, "plain %d", &n) == 1) {+ burst(&main_window, "p", n, false);+ report();+ } else if (sscanf(line, "send %d", &n) == 1) {+ // Fire and forget (the window is hidden: feedback never resolves).+ burst(&main_window, "h", n, true);+ wl_display_roundtrip(display);+ forget_feedback();+ } else if (strncmp(line, "empty", 5) == 0) {+ // An update that only sets a barrier changes nothing on screen.+ wp_fifo_v1_set_barrier(main_window.fifo);+ wl_surface_commit(main_window.surface);+ uint64_t sent = now_ns();+ attach_shm(main_window.surface, main_window.width, main_window.height, false);+ wp_fifo_v1_set_barrier(main_window.fifo);+ wp_fifo_v1_wait_barrier(main_window.fifo);+ request_feedback(main_window.surface, "e");+ wl_surface_commit(main_window.surface);+ bool ok = pump(all_resolved, 10000);+ if (ok && feedbacks[0]->presented)+ printf("latency_ms %.2f\n", (double)(feedbacks[0]->ns - sent) / 1e6);+ report();+ } else if (sscanf(line, "sub %d", &n) == 1) {+ subsurface_case(&main_window, n, strstr(line, "sync") && !strstr(line, "desync"));+ } else if (sscanf(line, "destroy-fifo %d", &n) == 1) {+ burst(&main_window, "d", n, true);+ wp_fifo_v1_destroy(main_window.fifo);+ main_window.fifo = NULL;+ report();+ main_window.fifo = wp_fifo_manager_v1_get_fifo(fifo_manager, main_window.surface);+ } else if (sscanf(line, "destroy-surface %d", &n) == 1) {+ window_create(&extra, "rediwm.fifo-extra", 200, 150, false, true, false);+ burst(&extra, "x", n, true);+ // Keep the fifo object; its surface goes with commits still held.+ struct wp_fifo_v1 *orphan = extra.fifo;+ extra.fifo = NULL;+ window_destroy(&extra);+ wl_display_roundtrip(display);+ wp_fifo_v1_destroy(orphan);+ wl_display_roundtrip(display);+ forget_feedback();+ printf("survived\n");+ } else if (strncmp(line, "cover", 5) == 0) {+ window_create(&cover, "rediwm.fifo-cover", 900, 700, true, false, false);+ } else if (strncmp(line, "uncover", 7) == 0) {+ window_destroy(&cover);+ wl_display_roundtrip(display);+ } else if (strncmp(line, "explicit-sync", 13) == 0) {+ explicit_sync_case();+ } else {+ printf("unknown %s", line);+ }+ printf("done\n");+ fflush(stdout);+ if (wl_display_get_error(display)) {+ printf("display error %d\n", wl_display_get_error(display));+ return 1;+ }+ }+ return 0;+}diff --git a/tests/wlr_protocols.py b/tests/wlr_protocols.pyindex 654a000..2077a20 100644--- a/tests/wlr_protocols.py+++ b/tests/wlr_protocols.py@@ -258,7 +258,7 @@ def extra_protocols(tmp):for interface in ("ext_workspace_manager_v1", "wp_color_manager_v1","wp_color_representation_manager_v1", "xdg_toplevel_tag_manager_v1","wp_content_type_manager_v1", "wp_tearing_control_manager_v1",- "xdg_activation_v1"):+ "xdg_activation_v1", "wp_fifo_manager_v1"):assert interface in registry, interfaceassert "wp_drm_lease_device_v1" not in registry, "headless backend must not offer DRM leases"# Every global is advertised once. linux-dmabuf used to be created both