Advertise zwp_linux_dmabuf_v1 so Mesa EGL clients stop using llvmpipe

- Add zwp_linux_dmabuf_v1 (v4 feedback names the render node). Only linear ARGB8888 and XRGB8888 are accepted, because the compositor reads a buffer by mapping its dma-buf.
- Bracket dma-buf reads with DMA_BUF_IOCTL_SYNC in the compositor and in the wasm host, so the CPU sees the GPU's finished writes.
- Keep every wl_surface.frame callback since the last commit instead of only the last one. Zed and Mesa's EGL queue several and wait on all of them.
- rs_capture maps a dma-buf afresh on each capture rather than using the pool cache, which could hand a later buffer an earlier buffer's pixels.
- Restart xdg-desktop-portal in the background once the compositor socket exists, so the restart no longer delays compositor startup by about 30 s.
This commit is contained in:
nandi committed 2026-11-30 11:49:48 -08:00
1 parent d81003f176
commit 51852f0dac
5 files changed
+366 -16

No files matched your search

+58
View File
@@ -498,3 +498,61 @@ test "swapchain pools sent in one message all keep their fds, and a bare commit
@sys.close_fd(c.fd)
comp.close()
}
///|
test "a linear zwp_linux_dmabuf_v1 buffer is shown like an shm one" {
// Without this global Mesa's Wayland EGL falls back to llvmpipe and Zed warns about it.
let socket_path = "/tmp/wayland-moon-dmabuf-" + @sys.getpid().to_string() + ".sock"
let theme = @scene.ThemeTokens::moon_night()
let comp = @host.ChandraCompositor::new(socket_path, theme, 1280, 720).unwrap()
let (c, _shm, surf, xdg, _tl, _deco) = open_and_configure_client(
comp, socket_path, "Zed", "dev.zed.Zed",
)
match c.configure_serial {
Some(ser) => {
let ack = @wayland.WireWriter::new()
ack.u32(ser)
c.send(ack.finish_msg(xdg, 4U))
}
None => ()
}
assert_true(c.globals.contains("zwp_linux_dmabuf_v1"))
let dmabuf = bind_global(c, 2U, "zwp_linux_dmabuf_v1", 4U)
let params = c.alloc_id()
let cp = @wayland.WireWriter::new()
cp.u32(params)
c.send(cp.finish_msg(dmabuf, 1U))
let w = c.configured_w
let h = c.configured_h
let fd = solid_memfd(w, h, b'\x00', b'\xff', b'\x00')
// add(fd, plane 0, offset 0, stride, modifier LINEAR) and create_immed in one flush.
let msg : Array[Byte] = []
let add = @wayland.WireWriter::new()
add.u32(0U)
add.u32(0U)
add.u32((w * 4).reinterpret_as_uint())
add.u32(0U)
add.u32(0U)
for b in add.finish_msg(params, 1U) {
msg.push(b)
}
let buf = c.alloc_id()
let ci = @wayland.WireWriter::new()
ci.u32(buf)
ci.i32(w)
ci.i32(h)
ci.u32(0x34325241U)
ci.u32(0U)
for b in ci.finish_msg(params, 3U) {
msg.push(b)
}
assert_true(@sys.sendmsg_fds(c.fd, Bytes::from_array(msg), [fd]) > 0)
let win = comp.windows.get(1UL).unwrap()
let cx = win.geometry.x + win.geometry.w / 2
let cy = win.geometry.y + win.geometry.h / 2
attach_commit(comp, c, surf, Some(buf))
assert_eq(comp.compose_frame().pixel(cx, cy), Some(@scene.Rgba::new(0, 0xff, 0, 0xff)))
@sys.close_fd(fd)
@sys.close_fd(c.fd)
comp.close()
}
+11
View File
@@ -288,6 +288,15 @@ int32_t mp_pwrite_bytes(int32_t fd, moonbit_bytes_t buf, int32_t len, int32_t of
return w < 0 ? -1 : (int32_t)w;
}
#include <sys/ioctl.h>
#include <linux/dma-buf.h>
/* Wait for the GPU to finish writing a dma-buf before the CPU reads it; harmless on shm files. */
static void dmabuf_sync(int fd, int start) {
struct dma_buf_sync sync = { .flags = (start ? DMA_BUF_SYNC_START : DMA_BUF_SYNC_END) | DMA_BUF_SYNC_READ };
ioctl(fd, DMA_BUF_IOCTL_SYNC, &sync);
}
MOONBIT_FFI_EXPORT
moonbit_bytes_t mp_mmap_read(int32_t fd, int32_t size) {
if (fd < 0 || size <= 0) {
@@ -302,7 +311,9 @@ moonbit_bytes_t mp_mmap_read(int32_t fd, int32_t size) {
return moonbit_make_bytes_raw(0);
}
moonbit_bytes_t out = moonbit_make_bytes_raw(size);
dmabuf_sync(fd, 1);
memcpy(out, ptr, (size_t)size);
dmabuf_sync(fd, 0);
munmap(ptr, (size_t)size);
return out;
}
+262 -12
View File
@@ -106,6 +106,9 @@ enum ObjKind {
/// zwp_text_input_manager_v3 and its zwp_text_input_v3 objects (text_input.mbt).
ObjTextInputMgr
ObjTextInput
ObjDmabuf
ObjDmabufParams(UInt)
ObjDmabufFeedback
}
///|
@@ -127,13 +130,23 @@ struct ShmBufferState {
format : Int
}
///| A zwp_linux_buffer_params_v1 being filled in: only one linear plane is supported.
struct DmabufParams {
mut fd : Int
mut offset : Int
mut stride : Int
mut modifier_ok : Bool
}
///|
struct SurfaceState {
/// Pending state: the buffer attached since the last commit. A commit takes it, so a commit
/// without a new attach (a client changing only its regions or geometry) neither shows the
/// old buffer again nor releases it a second time: the client may already be drawing into it.
mut attached_buffer : UInt?
mut pending_frame_cb : UInt?
/// Every wl_surface.frame callback since the last commit; a client may queue several (Zed
/// and Mesa's EGL each do) and waits on all of them.
pending_frame_cbs : Array[UInt]
mut xdg_surface_id : UInt?
mut window_id : UInt64?
/// wl_surface.set_buffer_scale: the buffer is this many times the window's size.
@@ -223,6 +236,7 @@ struct ClientConn {
surfaces : Map[UInt, SurfaceState]
shm_pools : Map[UInt, ShmPoolState]
shm_buffers : Map[UInt, ShmBufferState]
dmabuf_params : Map[UInt, DmabufParams]
xdg_surfaces : Map[UInt, XdgSurfaceState]
subsurfaces : Map[UInt, SubState]
toplevels : Map[UInt64, ToplevelState]
@@ -267,6 +281,7 @@ fn ClientConn::new(client_id : UInt, fd : Int) -> ClientConn {
surfaces: {},
shm_pools: {},
shm_buffers: {},
dmabuf_params: {},
xdg_surfaces: {},
subsurfaces: {},
toplevels: {},
@@ -334,6 +349,11 @@ fn ClientConn::close_all(self : ClientConn) -> Unit {
for _, pool in self.shm_pools {
@sys.close_fd(pool.fd)
}
for _, p in self.dmabuf_params {
if p.fd >= 0 {
@sys.close_fd(p.fd)
}
}
for fd in self.pending_fds {
@sys.close_fd(fd)
}
@@ -485,6 +505,7 @@ fn emit_registry_globals(c : ClientConn, reg_id : UInt) -> Unit {
(10U, "org_kde_kwin_server_decoration_manager", 1U),
(11U, "zwp_primary_selection_device_manager_v1", 1U),
(12U, "zwp_text_input_manager_v3", 1U),
(13U, "zwp_linux_dmabuf_v1", 4U),
]
for g in globals {
let w = WireWriter::new()
@@ -505,6 +526,147 @@ fn emit_shm_formats(c : ClientConn, shm_id : UInt) -> Unit {
}
}
///| zwp_linux_dmabuf_v1 (version 3): ARGB8888 and XRGB8888, linear only, because the
/// compositor reads a buffer by mapping its dma-buf. Mesa's Wayland EGL needs this global to use
/// the GPU (with v4 feedback naming the render node); without it clients fall back to llvmpipe.
fn emit_dmabuf_formats(c : ClientConn, id : UInt, ver : UInt) -> Unit {
// DRM fourcc codes (ARGB8888, XRGB8888), not the wl_shm 0 and 1.
for fmt in [0x34325241U, 0x34325258U] {
if ver < 3U {
let w = WireWriter::new()
w.u32(fmt)
c.send_msg(w.finish_msg(id, 0U))
} else {
let w = WireWriter::new()
w.u32(fmt)
w.u32(0U) // modifier_hi
w.u32(0U) // modifier_lo: DRM_FORMAT_MOD_LINEAR
c.send_msg(w.finish_msg(id, 1U))
}
}
}
///| The render node's dev_t as 8 native-endian bytes, from /sys/class/drm/renderD*/dev ("226:128").
fn render_node_dev() -> Array[Byte]? {
for minor = 128; minor < 192; minor = minor + 1 {
let txt = @sys.read_proc_bytes("/sys/class/drm/renderD" + minor.to_string() + "/dev")
if txt.length() == 0 {
continue
}
let mut major = 0
let mut mnr = 0
let mut after = false
for i = 0; i < txt.length(); i = i + 1 {
let b = txt[i].to_int()
if b == 58 {
after = true
} else if b >= 48 && b <= 57 {
if after {
mnr = mnr * 10 + (b - 48)
} else {
major = major * 10 + (b - 48)
}
}
}
// glibc makedev() for a 12-bit major and an 8-bit minor (a render node's), as a u64.
let dev = ((major & 0xfff) << 8) | (mnr & 0xff)
let out : Array[Byte] = []
for i = 0; i < 4; i = i + 1 {
out.push(((dev >> (8 * i)) & 0xff).to_byte())
}
for _i = 0; _i < 4; _i = _i + 1 {
out.push(b'\x00')
}
return Some(out)
}
None
}
///| zwp_linux_dmabuf_feedback_v1: one tranche on the render node with the linear formats. Mesa
/// reads the device from here to pick the GPU driver; without it a v3 client uses llvmpipe.
fn emit_dmabuf_feedback(c : ClientConn, id : UInt) -> Unit {
let dev = match render_node_dev() {
Some(d) => d
None => []
}
// format table: (fourcc u32, padding u32, modifier u64) per entry
let table : Array[Byte] = []
for fmt in [0x34325241U, 0x34325258U] {
for i = 0; i < 4; i = i + 1 {
table.push(((fmt >> (8 * i)) & 0xffU).to_byte())
}
for _i = 0; _i < 12; _i = _i + 1 {
table.push(b'\x00')
}
}
let fd = @sys.memfd_create("dmabuf-format-table", table.length())
if fd >= 0 {
ignore(@sys.pwrite_bytes(fd, Bytes::from_array(table), 0))
let w = WireWriter::new()
w.u32(table.length().reinterpret_as_uint())
if c.alive {
let n = @sys.sendmsg_fd(c.fd, w.finish_msg(id, 1U), fd)
if n < 0 {
c.alive = false
}
}
@sys.close_fd(fd)
}
let w1 = WireWriter::new()
w1.array(dev)
c.send_msg(w1.finish_msg(id, 2U)) // main_device
let w2 = WireWriter::new()
w2.array(dev)
c.send_msg(w2.finish_msg(id, 4U)) // tranche_target_device
let w3 = WireWriter::new()
w3.array([b'\x00', b'\x00', b'\x01', b'\x00'])
c.send_msg(w3.finish_msg(id, 5U)) // tranche_formats: indices 0 and 1
let w4 = WireWriter::new()
w4.u32(0U)
c.send_msg(w4.finish_msg(id, 6U)) // tranche_flags
c.send_msg(WireWriter::new().finish_msg(id, 3U)) // tranche_done
c.send_msg(WireWriter::new().finish_msg(id, 0U)) // done
}
///| Turn the filled-in params into a wl_buffer; false when they can't be imported.
fn ClientConn::import_dmabuf(
self : ClientConn,
params_id : UInt,
buf_id : UInt,
width : Int,
height : Int,
format : Int,
) -> Bool {
let p = match self.dmabuf_params.get(params_id) {
Some(p) => p
None => return false
}
let format = if format == 0x34325241 {
0
} else if format == 0x34325258 {
1
} else {
-1
}
if p.fd < 0 || !p.modifier_ok || format < 0 || width <= 0 ||
height <= 0 || p.stride < width * 4 {
return false
}
// The buffer owns the fd, like a one-buffer pool that is already destroyed.
self.shm_pools.set(buf_id, { fd: p.fd, size: p.offset + p.stride * height, destroyed: true })
p.fd = -1
self.objects.set(buf_id, ObjBuffer(buf_id))
self.shm_buffers.set(buf_id, {
pool_id: buf_id,
offset: p.offset,
width,
height,
stride: p.stride,
format,
})
true
}
///|
fn emit_seat_caps(c : ClientConn, seat_id : UInt, touch : Bool) -> Unit {
let w = WireWriter::new()
@@ -706,6 +868,12 @@ fn WaylandServer::dispatch_msg(
emit_seat_info(c, new_id, ver, self.touch)
} else if iface == "wp_cursor_shape_manager_v1" {
c.objects.set(new_id, ObjCursorShapeMgr)
} else if iface == "zwp_linux_dmabuf_v1" {
c.objects.set(new_id, ObjDmabuf)
// Version 4 clients get formats from get_default_feedback instead.
if ver < 4U {
emit_dmabuf_formats(c, new_id, ver)
}
} else if iface == "wl_data_device_manager" {
c.objects.set(new_id, ObjDataManager)
c.data_ver = ver
@@ -727,7 +895,7 @@ fn WaylandServer::dispatch_msg(
c.objects.set(sid, ObjSurface(sid))
c.surfaces.set(sid, {
attached_buffer: None,
pending_frame_cb: None,
pending_frame_cbs: [],
xdg_surface_id: None,
window_id: None,
buffer_scale: 1,
@@ -776,7 +944,7 @@ fn WaylandServer::dispatch_msg(
} else if opcode == 3U {
// frame(callback)
let cb_id = reader.u32()
surf.pending_frame_cb = Some(cb_id)
surf.pending_frame_cbs.push(cb_id)
} else if opcode == 10U {
// offset(x, y) (version 5): moves the surface; for a drag icon, its hotspot.
surf.pend_dx = surf.pend_dx + reader.i32()
@@ -873,17 +1041,14 @@ fn WaylandServer::dispatch_msg(
None => ()
}
surf.attached_buffer = None
match surf.pending_frame_cb {
Some(cb_id) => {
surf.pending_frame_cb = None
if self.hold_frames {
self.held_frames.push((c.client_id, cb_id))
} else {
self.frame_done(c, cb_id)
}
for cb_id in surf.pending_frame_cbs {
if self.hold_frames {
self.held_frames.push((c.client_id, cb_id))
} else {
self.frame_done(c, cb_id)
}
None => ()
}
surf.pending_frame_cbs.clear()
}
}
ObjSubcompositor =>
@@ -1142,6 +1307,91 @@ fn WaylandServer::dispatch_msg(
None => ()
}
}
ObjDmabuf =>
if opcode == 0U {
c.objects.remove(obj_id)
send_delete_id(c, obj_id)
} else if opcode == 1U {
// create_params(params_id: new_id)
let pid = reader.u32()
c.objects.set(pid, ObjDmabufParams(pid))
c.dmabuf_params.set(pid, { fd: -1, offset: 0, stride: 0, modifier_ok: true })
} else if opcode == 2U || opcode == 3U {
// get_default_feedback(id) / get_surface_feedback(id, surface)
let fid = reader.u32()
c.objects.set(fid, ObjDmabufFeedback)
emit_dmabuf_feedback(c, fid)
}
ObjDmabufFeedback =>
if opcode == 0U {
c.objects.remove(obj_id)
send_delete_id(c, obj_id)
}
ObjDmabufParams(pid) =>
if opcode == 0U {
// destroy
match c.dmabuf_params.get(pid) {
Some(p) =>
if p.fd >= 0 {
@sys.close_fd(p.fd)
}
None => ()
}
c.dmabuf_params.remove(pid)
c.objects.remove(pid)
send_delete_id(c, pid)
} else if opcode == 1U {
// add(fd, plane_idx, offset, stride, modifier_hi, modifier_lo)
let fd = c.take_fd()
let plane = reader.u32()
let offset = reader.u32()
let stride = reader.u32()
let mod_hi = reader.u32()
let mod_lo = reader.u32()
match c.dmabuf_params.get(pid) {
Some(p) =>
if plane != 0U || p.fd >= 0 {
if fd >= 0 {
@sys.close_fd(fd)
}
p.modifier_ok = false
} else {
p.fd = fd
p.offset = offset.reinterpret_as_int()
p.stride = stride.reinterpret_as_int()
p.modifier_ok = mod_hi == 0U && mod_lo == 0U
}
None =>
if fd >= 0 {
@sys.close_fd(fd)
}
}
} else if opcode == 2U {
// create(width, height, format, flags): answered with created(buffer) or failed
let width = reader.i32()
let height = reader.i32()
let format = reader.u32().reinterpret_as_int()
let _flags = reader.u32()
let buf_id = c.next_offer
c.next_offer = c.next_offer + 1U
if c.import_dmabuf(pid, buf_id, width, height, format) {
let w = WireWriter::new()
w.u32(buf_id)
c.send_msg(w.finish_msg(pid, 0U))
} else {
c.send_msg(WireWriter::new().finish_msg(pid, 1U))
}
} else if opcode == 3U {
// create_immed(buffer_id, width, height, format, flags)
let buf_id = reader.u32()
let width = reader.i32()
let height = reader.i32()
let format = reader.u32().reinterpret_as_int()
let _flags = reader.u32()
if !c.import_dmabuf(pid, buf_id, width, height, format) {
c.objects.set(buf_id, ObjBuffer(buf_id))
}
}
ObjShm =>
if opcode == 0U {
// create_pool(id: new_id, fd: out-of-band, size: i32)
+8 -1
View File
@@ -149,8 +149,15 @@ fi
# an earlier session (systemd keeps the user's services between logins) would keep another
# desktop's choice, so Chrome and Firefox would not follow the Dark mode switch: restart it if it
# is running. Apps start it on demand otherwise.
# Done in the background once the compositor's socket is up: the restart starts the portal
# backends, which connect to WAYLAND_DISPLAY and crash while it doesn't exist, and systemctl
# waits for all of that (about 30 s), which kept the compositor from starting at all.
if command -v systemctl >/dev/null 2>&1; then
systemctl --user try-restart xdg-desktop-portal.service >>"$log" 2>&1 || true
(
i=0
while [ ! -S "$sock" ] && [ $i -lt 200 ]; do sleep 0.1; i=$((i + 1)); done
systemctl --user --no-block try-restart xdg-desktop-portal.service
) >>"$log" 2>&1 &
fi
# Flatpak apps need the document portal's FUSE mount: `flatpak run` binds
+27 -3
View File
@@ -16,6 +16,8 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <linux/dma-buf.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <sys/socket.h>
#include <sys/stat.h>
@@ -759,6 +761,12 @@ static const uint8_t *pool_map(int fd, const struct stat *st) {
return p;
}
/* Wait for the GPU to finish writing a dma-buf before the CPU reads it; harmless on shm files. */
static int dmabuf_sync(int fd, int start) {
struct dma_buf_sync sync = { .flags = (start ? DMA_BUF_SYNC_START : DMA_BUF_SYNC_END) | DMA_BUF_SYNC_READ };
return ioctl(fd, DMA_BUF_IOCTL_SYNC, &sync);
}
/* Copy a client buffer (stride * height bytes at `offset` of the file behind fd, little-endian
* B, G, R, A/X) into a surface. 0 on failure. */
uint32_t rs_capture(int32_t fd, int32_t offset, int32_t stride, int32_t w, int32_t h, int32_t format) {
@@ -766,11 +774,27 @@ uint32_t rs_capture(int32_t fd, int32_t offset, int32_t stride, int32_t w, int32
int64_t len = (int64_t)stride * h, end = offset + len;
struct stat st;
if (fstat(fd, &st) < 0 || st.st_size < end) return 0;
const uint8_t *p = pool_map(fd, &st);
if (!p) return 0;
/* A dma-buf is mapped afresh every time: the cache would hand a later buffer the mapping of an
* earlier one that had the same inode and size (the window then shows another app's pixels). */
int is_dmabuf = dmabuf_sync(fd, 1) == 0;
const uint8_t *p;
if (is_dmabuf) {
p = mmap(NULL, (size_t)st.st_size, PROT_READ, MAP_SHARED, fd, 0);
if (p == MAP_FAILED) { dmabuf_sync(fd, 0); return 0; }
} else {
p = pool_map(fd, &st);
if (!p) return 0;
}
uint8_t *rgba = px_alloc((size_t)w * h * 4);
if (!rgba) return 0;
if (!rgba) {
if (is_dmabuf) { munmap((void *)p, (size_t)st.st_size); dmabuf_sync(fd, 0); }
return 0;
}
int opaque = swizzle_rows(p + offset, stride, rgba, w, h, format == 1);
if (is_dmabuf) {
dmabuf_sync(fd, 0);
munmap((void *)p, (size_t)st.st_size);
}
do { next_surface++; } while (next_surface == 0 || surface(next_surface));
Surface *sf = malloc(sizeof *sf);
sf->id = next_surface; sf->w = w; sf->h = h; sf->rgba = rgba; sf->opaque = opaque;