Skip to content

LordOS — a free, fast and secure GNU/Linux distribution based on Debian, with its own desktop environment: display server and Wayland compositor in C, a React UI engine on QuickJS, and private native apps.

GPU: re-import app windows when the GPU context is re-created

Federico Pereira43a30d9af43a
diff --git a/server/Makefile b/server/Makefile
index 7b69179..93167ac 100644
--- a/server/Makefile
+++ b/server/Makefile
@@ -352,6 +352,10 @@ endef
$(foreach p,$(CLIENT_PROTO),$(eval $(call wl_client_proto,$(p))))
build/dmabuf-client: tests/dmabuf_client.c $(CLIENT_GEN)
$(CC) $(CFLAGS) -D_GNU_SOURCE -Ibuild/gen $(WARN) -std=c11 -o $@ tests/dmabuf_client.c $(filter %.c,$(CLIENT_GEN)) -lwayland-client
+# off/on-monitor cycles against one session (tests/gpu_cycle.sh, docs/GPU.md); a test tool, never installed
+build/seat-cycle: tests/seat_cycle.c
+ @mkdir -p build
+ $(CC) $(CFLAGS) $(WARN) -std=c11 -o $@ tests/seat_cycle.c
MEDIA_PKGS := libavcodec libavformat libavutil libswscale libswresample
MEDIA_VA := $(shell pkg-config --exists libva libva-drm 2>/dev/null && echo 1 || echo 0)
diff --git a/server/src/gpu/gpu.c b/server/src/gpu/gpu.c
index c319368..2b16b86 100644
--- a/server/src/gpu/gpu.c
+++ b/server/src/gpu/gpu.c
@@ -31,6 +31,10 @@ int gpu_device(dev_t *dev) { (void)dev; return -1; }
GpuTex *gpu_tex_pixels(GpuTex *t, const uint32_t *px, int w, int h, int opaque) { (void)t; (void)px; (void)w; (void)h; (void)opaque; return NULL; }
GpuTex *gpu_tex_dmabuf(const GpuDmabuf *d) { (void)d; return NULL; }
void gpu_tex_free(GpuTex *t) { (void)t; }
+int gpu_tex_current(const GpuTex *t) { (void)t; return 0; }
+unsigned gpu_generation(void) { return 0; }
+void gpu_set_hooks(void (*lost)(void), void (*changed)(void)) { (void)lost; (void)changed; }
+int gpu_tex_read(const GpuTex *t, uint32_t *px, int w, int h) { (void)t; (void)px; (void)w; (void)h; return -1; }
int gpu_add_output(Kms *k) { (void)k; return -1; }
int gpu_frame(int out, const Canvas *s, Rect d, void (*f)(int)) { (void)out; (void)s; (void)d; (void)f; return -1; }
void gpu_draw(GpuTex *t, float dx, float dy, float dw, float dh, float sx, float sy, float sw, float sh, Rect c, float o) {
@@ -83,6 +87,7 @@ struct GpuTex {
GLuint id;
int w, h, opaque, external, swap;
EGLImageKHR image;
+ unsigned gen; /* the context it was made in (gpu_generation) */
};
/* What is on screen (or on its way): a BO of the gbm_surface or an app's dmabuf. */
@@ -126,8 +131,17 @@ static struct {
PFNEGLQUERYDMABUFMODIFIERSEXTPROC query_modifiers;
long frames, scanouts;
char render_node[64]; /* where Mesa renders (on the Pi 5: v3d, not vc4) */
+ unsigned gen; /* this context's generation (0 = none) */
} G;
+/* These outlive the context (G is wiped by gpu_shutdown). */
+static unsigned last_gen;
+static void (*hook_lost)(void), (*hook_changed)(void);
+
+void gpu_set_hooks(void (*lost)(void), void (*changed)(void)) { hook_lost = lost; hook_changed = changed; }
+unsigned gpu_generation(void) { return G.on ? G.gen : 0; }
+int gpu_tex_current(const GpuTex *t) { return t && G.on && t->gen == G.gen; }
+
static void dbg(const char *fmt, ...) __attribute__((format(printf, 1, 2)));
static void dbg(const char *fmt, ...) {
if (!G.debug) return;
@@ -331,6 +345,7 @@ static void out_texture(GOut *o) {
o->canvas.w = o->W;
o->canvas.h = o->H;
o->canvas.swap = !G.bgra;
+ o->canvas.gen = G.gen;
}
static void out_teardown(GOut *o) {
@@ -395,6 +410,8 @@ int gpu_init(Kms *k) {
static const EGLint ctx_attr[] = { EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE };
G.ctx = eglCreateContext(G.dpy, cfg, EGL_NO_CONTEXT, ctx_attr);
G.cfg = cfg;
+ G.gen = ++last_gen;
+ if (last_gen == 0) G.gen = last_gen = 1; /* 0 means "no context" */
if (G.ctx == EGL_NO_CONTEXT || out_setup(&G.out[0], k)) { fprintf(stderr, "gpu: could not create the context or the surface, CPU composition\n"); goto fail; }
const char *rend = (const char *)glGetString(GL_RENDERER), *gl_exts = (const char *)glGetString(GL_EXTENSIONS);
@@ -431,6 +448,7 @@ int gpu_init(Kms *k) {
fprintf(stderr, "gpu: GPU composition (%s, EGL %d.%d, dmabuf %s, render %s, display %s)\n", G.renderer, maj, min,
G.create_image ? (G.query_modifiers ? "with modifiers" : "yes") : "no",
G.render_node[0] ? G.render_node : "the card's", k->driver[0] ? k->driver : drv);
+ if (hook_changed) hook_changed(); /* windows re-import their buffers in this context */
return 0;
fail:
gpu_shutdown();
@@ -438,6 +456,12 @@ fail:
}
void gpu_shutdown(void) {
+ int was_on = G.on;
+ if (was_on && hook_lost) {
+ /* the compositor reads back and frees what it holds while the context still works */
+ for (int i = 0; i < OUT_MAX; i++)
+ if (G.out[i].used && eglMakeCurrent(G.dpy, G.out[i].surf, G.out[i].surf, G.ctx)) { hook_lost(); break; }
+ }
if (G.dpy != EGL_NO_DISPLAY && G.dpy) {
for (int i = OUT_MAX - 1; i >= 0; i--) out_teardown(&G.out[i]);
eglMakeCurrent(G.dpy, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
@@ -449,6 +473,7 @@ void gpu_shutdown(void) {
int debug = G.debug;
memset(&G, 0, sizeof G);
G.debug = debug;
+ if (was_on && hook_changed) hook_changed(); /* now on the CPU path */
}
/* ---- formats and device (linux-dmabuf) ---- */
@@ -519,7 +544,7 @@ static void tex_params(GLenum target) {
GpuTex *gpu_tex_pixels(GpuTex *t, const uint32_t *px, int w, int h, int opaque) {
if (!G.on || !px || w <= 0 || h <= 0) return t;
- if (t && t->external) { gpu_tex_free(t); t = NULL; }
+ if (t && (t->external || t->gen != G.gen)) { gpu_tex_free(t); t = NULL; } /* stale: from a dead context */
int fresh = !t;
if (!t) {
t = calloc(1, sizeof *t);
@@ -527,6 +552,7 @@ GpuTex *gpu_tex_pixels(GpuTex *t, const uint32_t *px, int w, int h, int opaque)
glGenTextures(1, &t->id);
glBindTexture(GL_TEXTURE_2D, t->id);
tex_params(GL_TEXTURE_2D);
+ t->gen = G.gen;
} else glBindTexture(GL_TEXTURE_2D, t->id);
GLenum fmt = G.bgra ? GL_BGRA_EXT : GL_RGBA;
if (fresh || t->w != w || t->h != h) glTexImage2D(GL_TEXTURE_2D, 0, fmt, w, h, 0, fmt, GL_UNSIGNED_BYTE, px);
@@ -558,6 +584,7 @@ GpuTex *gpu_tex_dmabuf(const GpuDmabuf *d) {
G.image_target(GL_TEXTURE_EXTERNAL_OES, (GLeglImageOES)img);
t->image = img;
t->external = 1;
+ t->gen = G.gen;
t->w = d->width;
t->h = d->height;
t->opaque = d->fourcc == DRM_FORMAT_XRGB8888 || d->fourcc == DRM_FORMAT_XBGR8888;
@@ -591,17 +618,63 @@ static EGLImageKHR import_image(const GpuDmabuf *d, int with_mod) {
void gpu_tex_free(GpuTex *t) {
if (!t) return;
- if (G.on) {
+ if (G.on && t->gen == G.gen) { /* a stale one's GL name may now be someone else's */
glDeleteTextures(1, &t->id);
if (t->image && G.destroy_image) G.destroy_image(G.dpy, t->image);
}
free(t);
}
+int gpu_tex_read(const GpuTex *t, uint32_t *px, int w, int h) {
+ if (!gpu_tex_current(t) || !px || w != t->w || h != t->h || w <= 0 || h <= 0 || w > 8192 || h > 8192) return -1;
+ while (glGetError() != GL_NO_ERROR) {}
+ GLuint tex = 0, fbo = 0;
+ glGenTextures(1, &tex);
+ glBindTexture(GL_TEXTURE_2D, tex);
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
+ glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
+ glGenFramebuffers(1, &fbo);
+ glBindFramebuffer(GL_FRAMEBUFFER, fbo);
+ glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, tex, 0);
+ int ok = glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE;
+ if (ok) {
+ glViewport(0, 0, w, h);
+ glDisable(GL_BLEND);
+ glDisable(GL_SCISSOR_TEST);
+ int p = t->external ? 1 : 0;
+ glUseProgram(G.prog[p]);
+ glActiveTexture(GL_TEXTURE0);
+ glBindTexture(t->external ? GL_TEXTURE_EXTERNAL_OES : GL_TEXTURE_2D, t->id);
+ glUniform1i(G.u_tex[p], 0);
+ glUniform1f(G.u_op[p], 1.0f);
+ glUniform1f(G.u_opaque[p], t->opaque ? 1.0f : 0.0f);
+ glUniform1f(G.u_swap[p], t->swap ? 1.0f : 0.0f);
+ /* the image's first row at y = -1: glReadPixels returns it first */
+ static const GLfloat v[] = { -1, -1, 0, 0, 1, -1, 1, 0, -1, 1, 0, 1, 1, 1, 1, 1 };
+ glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 16, v);
+ glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 16, v + 2);
+ glEnableVertexAttribArray(0);
+ glEnableVertexAttribArray(1);
+ glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
+ glReadPixels(0, 0, w, h, GL_RGBA, GL_UNSIGNED_BYTE, px);
+ ok = glGetError() == GL_NO_ERROR;
+ for (size_t i = 0, n = (size_t)w * (size_t)h; ok && i < n; i++) { /* RGBA bytes → ARGB words */
+ const uint8_t *b = (const uint8_t *)&px[i];
+ px[i] = (uint32_t)b[3] << 24 | (uint32_t)b[0] << 16 | (uint32_t)b[1] << 8 | b[2];
+ }
+ glEnable(GL_BLEND);
+ }
+ glBindFramebuffer(GL_FRAMEBUFFER, 0);
+ glDeleteFramebuffers(1, &fbo);
+ glDeleteTextures(1, &tex);
+ return ok ? 0 : -1;
+}
+
/* ---- drawing ---- */
void gpu_draw(GpuTex *t, float dx, float dy, float dw, float dh, float sx, float sy, float sw, float sh, Rect clip, float op) {
- if (!G.on || !G.cur || !t || dw <= 0 || dh <= 0 || op <= 0.004f) return;
+ if (!G.on || !G.cur || !t || t->gen != G.gen || dw <= 0 || dh <= 0 || op <= 0.004f) return;
const int W = G.cur->W, H = G.cur->H; /* the display being drawn */
if (clip.x0 < 0) clip.x0 = 0;
if (clip.y0 < 0) clip.y0 = 0;
diff --git a/server/src/gpu/gpu.h b/server/src/gpu/gpu.h
index 443b65f..27dcfa2 100644
--- a/server/src/gpu/gpu.h
+++ b/server/src/gpu/gpu.h
@@ -35,6 +35,20 @@ GpuTex *gpu_tex_pixels(GpuTex *t, const uint32_t *px, int w, int h, int opaque);
GpuTex *gpu_tex_dmabuf(const GpuDmabuf *d);
void gpu_tex_free(GpuTex *t);
+/* GPU context lifetime. Each gpu_init that succeeds starts a new context ("generation"); a
+ * texture made in an earlier one is stale: its GL name and EGLImage died with that context, so it
+ * must never be drawn and gpu_tex_free only frees its memory. The session leaving and coming back
+ * to the monitor, a remote viewer, a display change or a failed frame all re-create the context. */
+int gpu_tex_current(const GpuTex *t); /* 1 if t belongs to the live context */
+unsigned gpu_generation(void); /* 0 while there is no GPU */
+/* Hooks for the compositor: lost() runs inside gpu_shutdown with the old context still current
+ * (last chance to read textures back or free them); changed() runs once the switch is done, after
+ * a successful gpu_init and after gpu_shutdown (to re-import buffers and re-send dmabuf feedback). */
+void gpu_set_hooks(void (*lost)(void), void (*changed)(void));
+/* Reads a texture back as premultiplied ARGB pixels (t->w × t->h, rows top to bottom), for the
+ * last good frame of a dmabuf window when the GPU goes away. 0 on success. */
+int gpu_tex_read(const GpuTex *t, uint32_t *px, int w, int h);
+
/* One frame: what changed in the UI canvas is uploaded, the layers are drawn and the flip is done.
* draw_layer(0) = app windows (below the UI), draw_layer(1) = app menus and
* fullscreen (on top). */
diff --git a/server/src/wl/wl.c b/server/src/wl/wl.c
index 71f399c..0fecfc8 100644
--- a/server/src/wl/wl.c
+++ b/server/src/wl/wl.c
@@ -61,9 +61,9 @@ enum { R_NONE, R_TOPLEVEL, R_POPUP, R_SUB, R_CURSOR };
typedef struct Dmabuf {
GpuDmabuf d;
struct wl_resource *res; /* NULL if the app already destroyed it */
- GpuTex *tex; /* EGLImage (GPU path) */
+ GpuTex *tex; /* EGLImage (GPU path); stale once its context is gone */
int refs, scanned;
- int cpu; /* EGL does not import it: it is mapped and copied (linear) */
+ unsigned no_import; /* the GPU context (generation) where EGL refused it: mapped and copied */
} Dmabuf;
typedef struct Surf Surf;
@@ -177,6 +177,12 @@ static struct wl_list rel_pointers;
typedef struct { struct wl_resource *res; Surf *surf; int lock, active, oneshot; } Constraint;
static Constraint *constraint; /* the only active (or pending) one */
static dev_t drm_dev;
+/* linux-dmabuf feedback objects (re-sent when the GPU comes or goes), the signature of the table
+ * last sent, and the formats the last GPU context imported (accepted off the GPU, see dmabuf_usable) */
+static struct wl_list feedbacks;
+static uint64_t feedback_sig;
+static GpuFormat gpu_fmt_cache[256];
+static int ngpu_fmt;
static unsigned now_ms(void) {
struct timespec t;
@@ -356,6 +362,26 @@ static Dmabuf *dmabuf_of(struct wl_resource *buf) {
return buf && wl_resource_instance_of(buf, &wl_buffer_interface, &dmabuf_buffer_impl) ? wl_resource_get_user_data(buf) : NULL;
}
+/* The buffer's texture in the live GPU context. The import is cached per wl_buffer, but only for
+ * one context: after the GPU is re-created (the session back on the monitor, a remote viewer
+ * leaving, a display change) the old texture is dropped and the buffer imported again. */
+static GpuTex *dm_tex(Dmabuf *d) {
+ if (!gpu_active()) return NULL;
+ if (d->tex && !gpu_tex_current(d->tex)) { gpu_tex_free(d->tex); d->tex = NULL; }
+ if (!d->tex && d->no_import != gpu_generation()) {
+ d->tex = gpu_tex_dmabuf(&d->d);
+ if (!d->tex) d->no_import = gpu_generation();
+ }
+ return d->tex;
+}
+
+/* Linear ARGB/XRGB8888 in one plane: the CPU path can map and copy it. */
+static int dm_linear(const Dmabuf *d) {
+ const GpuDmabuf *g = &d->d;
+ return g->nplanes == 1 && (g->modifier == DRM_FORMAT_MOD_LINEAR || g->modifier == DRM_FORMAT_MOD_INVALID) &&
+ (g->fourcc == DRM_FORMAT_ARGB8888 || g->fourcc == DRM_FORMAT_XRGB8888);
+}
+
/* CPU path: a linear dmabuf (ARGB/XRGB8888, one plane) is mapped and copied to px. */
static int map_linear(Surf *s, Dmabuf *d) {
const GpuDmabuf *g = &d->d;
@@ -397,7 +423,7 @@ static void queue_release(Dmabuf *d) {
static void take_buffer(Surf *s, struct wl_resource *buf) {
Dmabuf *dm = dmabuf_of(buf), *old = s->dmabuf;
s->dmabuf = NULL;
- if (dm && gpu_active() && !dm->cpu && s->role != R_CURSOR) {
+ if (dm && s->role != R_CURSOR && dm_tex(dm)) {
dm->refs++;
s->dmabuf = dm;
s->w = dm->d.width;
@@ -406,11 +432,24 @@ static void take_buffer(Surf *s, struct wl_resource *buf) {
s->content = 1;
free(s->px);
s->px = NULL;
- } else if (dm) {
- s->content = map_linear(s, dm) == 0;
- if (!s->content) { free(s->px); s->px = NULL; s->w = s->h = 0; }
+ } else if (dm && map_linear(s, dm) == 0) {
+ s->content = 1;
s->tex_dirty = 1;
wl_buffer_send_release(buf);
+ } else if (dm && !gpu_active() && s->role != R_CURSOR) {
+ /* Off the GPU (the session left the monitor, or a remote viewer) with a buffer the CPU
+ * can't read (tiled, or a driver that doesn't map it): keep showing the last good frame
+ * (px, read back from the GPU) and hold the buffer, so it is imported as soon as the GPU
+ * is back without waiting for the app's next frame. */
+ dm->refs++;
+ s->dmabuf = dm;
+ s->content = s->px != NULL;
+ } else if (dm) {
+ s->content = 0;
+ free(s->px);
+ s->px = NULL;
+ s->w = s->h = 0;
+ wl_buffer_send_release(buf);
} else {
copy_buffer(s, buf);
s->tex_dirty = 1;
@@ -1884,8 +1923,9 @@ void wl_paint_popups(Canvas *c) {
/* Texture with a surface's current content (GPU path). */
static GpuTex *surface_tex(Surf *s) {
if (s->dmabuf) {
- if (!s->dmabuf->tex) s->dmabuf->tex = gpu_tex_dmabuf(&s->dmabuf->d);
- return s->dmabuf->tex;
+ GpuTex *t = dm_tex(s->dmabuf);
+ if (t || !s->px) return t;
+ /* this context does not import it: the last good frame (px) is drawn instead */
}
if (s->px && (s->tex_dirty || !s->tex)) {
s->tex = gpu_tex_pixels(s->tex, s->px, s->w, s->h, s->opaque);
@@ -2234,14 +2274,14 @@ static void params_add(struct wl_client *c, struct wl_resource *r, int32_t fd, u
}
/* Can we show it? On GPU, it must import as an EGLImage; on CPU, it must be linear and mappable. */
+static int gpu_format_known(const GpuDmabuf *g);
static int dmabuf_usable(Dmabuf *d) {
- if (gpu_active() && (d->tex = gpu_tex_dmabuf(&d->d)) != NULL) return 1;
+ if (dm_tex(d)) return 1;
/* no GPU, or a dmabuf EGL does not import (for example udmabuf with a driver that does not
- * accept it): if it is linear it is mapped and copied, as in the CPU path */
- const GpuDmabuf *g = &d->d;
- d->cpu = g->nplanes == 1 && (g->modifier == DRM_FORMAT_MOD_LINEAR || g->modifier == DRM_FORMAT_MOD_INVALID) &&
- (g->fourcc == DRM_FORMAT_ARGB8888 || g->fourcc == DRM_FORMAT_XRGB8888);
- return d->cpu;
+ * accept it): if it is linear it is mapped and copied, as in the CPU path. Off the GPU, a
+ * format the last GPU context imported is accepted too (an app may still be allocating with
+ * the old feedback): it is held and imported once the GPU is back. */
+ return dm_linear(d) || (!gpu_active() && gpu_format_known(&d->d));
}
static void params_create_common(struct wl_client *c, struct wl_resource *r, uint32_t buffer_id, int32_t w, int32_t h,
@@ -2305,10 +2345,34 @@ static int dmabuf_formats(GpuFormat *out, int max) {
static void feedback_destroy(struct wl_client *c, struct wl_resource *r) { (void)c; wl_resource_destroy(r); }
static const struct zwp_linux_dmabuf_feedback_v1_interface feedback_impl = { .destroy = feedback_destroy };
+static void feedback_gone(struct wl_resource *r) { wl_list_remove(wl_resource_get_link(r)); }
+
+static int gpu_format_known(const GpuDmabuf *g) {
+ for (int i = 0; i < ngpu_fmt; i++)
+ if (gpu_fmt_cache[i].fourcc == g->fourcc && gpu_fmt_cache[i].modifier == g->modifier) return 1;
+ return 0;
+}
+
+/* What the feedback says right now (formats and device), to know when it must be sent again. */
+static uint64_t formats_sig(const GpuFormat *f, int n, dev_t dev) {
+ uint64_t h = 1469598103934665603ull ^ (uint64_t)dev;
+ for (int i = 0; i < n; i++) {
+ h = (h ^ f[i].fourcc) * 1099511628211ull;
+ h = (h ^ f[i].modifier) * 1099511628211ull;
+ }
+ return h;
+}
+
+static dev_t feedback_dev(void) {
+ dev_t dev = drm_dev;
+ if (gpu_active()) gpu_device(&dev);
+ return dev;
+}
static void send_feedback(struct wl_resource *fb) {
GpuFormat f[256];
int n = dmabuf_formats(f, 256);
+ feedback_sig = formats_sig(f, n, feedback_dev());
size_t size = (size_t)n * 16;
int fd = memfd_create("lord-dmabuf-formats", MFD_CLOEXEC | MFD_ALLOW_SEALING);
if (fd < 0 || ftruncate(fd, (off_t)size)) { if (fd >= 0) close(fd); return; }
@@ -2323,8 +2387,7 @@ static void send_feedback(struct wl_resource *fb) {
fcntl(fd, F_ADD_SEALS, F_SEAL_SHRINK | F_SEAL_GROW | F_SEAL_WRITE | F_SEAL_SEAL);
zwp_linux_dmabuf_feedback_v1_send_format_table(fb, fd, (uint32_t)size);
close(fd);
- dev_t dev = drm_dev;
- if (gpu_active()) gpu_device(&dev);
+ dev_t dev = feedback_dev();
struct wl_array devs, idx;
wl_array_init(&devs);
dev_t *dp = wl_array_add(&devs, sizeof dev);
@@ -2351,7 +2414,8 @@ static void dmabuf_create_params(struct wl_client *c, struct wl_resource *r, uin
static void dmabuf_get_feedback(struct wl_client *c, struct wl_resource *r, uint32_t id) {
struct wl_resource *fb = wl_resource_create(c, &zwp_linux_dmabuf_feedback_v1_interface, wl_resource_get_version(r), id);
if (!fb) { wl_client_post_no_memory(c); return; }
- wl_resource_set_implementation(fb, &feedback_impl, NULL, NULL);
+ wl_resource_set_implementation(fb, &feedback_impl, NULL, feedback_gone);
+ wl_list_insert(&feedbacks, wl_resource_get_link(fb));
send_feedback(fb);
}
static void dmabuf_get_surface_feedback(struct wl_client *c, struct wl_resource *r, uint32_t id, struct wl_resource *surface) {
@@ -2381,6 +2445,70 @@ static void bind_dmabuf(struct wl_client *c, void *data, uint32_t ver, uint32_t
void wl_set_drm_device(dev_t dev) { drm_dev = dev; }
+/* ---- GPU context re-created (docs/GPU.md, "When the GPU context is re-created") ---- */
+
+/* The GPU is going away (gpu_shutdown, its context still current): every window showing a dmabuf
+ * keeps its last good frame as pixels for the CPU path, and textures are freed while they still can be. */
+static void wl_gpu_lost(void) {
+ for (int i = 0; i < MAX_SURF; i++) {
+ Surf *s = surfs[i];
+ if (!s) continue;
+ Dmabuf *d = s->dmabuf;
+ if (d && gpu_tex_current(d->tex)) {
+ int w = d->d.width, h = d->d.height;
+ uint32_t *px = w <= 8192 && h <= 8192 ? malloc((size_t)w * (size_t)h * 4) : NULL;
+ if (px && gpu_tex_read(d->tex, px, w, h) == 0) {
+ free(s->px);
+ s->px = px;
+ s->w = w;
+ s->h = h;
+ } else {
+ free(px);
+ if (map_linear(s, d)) { free(s->px); s->px = NULL; }
+ }
+ }
+ if (d) { gpu_tex_free(d->tex); d->tex = NULL; }
+ gpu_tex_free(s->tex);
+ s->tex = NULL;
+ s->tex_dirty = 1;
+ }
+}
+
+/* The switch is done (GPU → CPU or a new GPU context): held buffers are imported again, pixel
+ * textures re-uploaded, everything is repainted and the dmabuf feedback is re-sent if the formats
+ * or the device changed, so apps reallocate buffers the new path can use. */
+static void wl_gpu_changed(void) {
+ if (!dpy) return;
+ if (gpu_active()) ngpu_fmt = gpu_formats(gpu_fmt_cache, 256);
+ for (int i = 0; i < MAX_SURF; i++) {
+ Surf *s = surfs[i];
+ if (!s) continue;
+ if (s->dmabuf && dm_tex(s->dmabuf)) {
+ const GpuDmabuf *g = &s->dmabuf->d;
+ s->w = g->width;
+ s->h = g->height;
+ s->opaque = g->fourcc == DRM_FORMAT_XRGB8888 || g->fourcc == DRM_FORMAT_XBGR8888;
+ s->content = 1;
+ free(s->px);
+ s->px = NULL;
+ apply_viewport(s);
+ }
+ s->tex_dirty = 1;
+ if (s->node) damage_node(s);
+ }
+ need_frame = 1;
+ ui.dirty = 1;
+ damage_add((Box){ 0, 0, ui.width, ui.height });
+ GpuFormat f[256];
+ int n = dmabuf_formats(f, 256);
+ if (formats_sig(f, n, feedback_dev()) != feedback_sig) {
+ struct wl_resource *fb;
+ int sent = 0;
+ wl_resource_for_each(fb, &feedbacks) { send_feedback(fb); sent++; }
+ if (sent) fprintf(stderr, "wayland: dmabuf feedback sent again (%s formats) to %d object(s)\n", gpu_active() ? "GPU" : "CPU", sent);
+ }
+}
+
/* ---- wp_presentation: when each frame was seen ---- */
static void pres_destroy(struct wl_client *c, struct wl_resource *r) { (void)c; wl_resource_destroy(r); }
@@ -2713,6 +2841,9 @@ int wl_start(void) {
wl_global_create(dpy, &xdg_wm_base_interface, 6, NULL, bind_wm_base);
wl_global_create(dpy, &zxdg_decoration_manager_v1_interface, 1, NULL, bind_decm);
wl_list_init(&rel_pointers);
+ wl_list_init(&feedbacks);
+ if (gpu_active()) ngpu_fmt = gpu_formats(gpu_fmt_cache, 256);
+ gpu_set_hooks(wl_gpu_lost, wl_gpu_changed);
wl_global_create(dpy, &zwp_linux_dmabuf_v1_interface, 4, NULL, bind_dmabuf);
wl_global_create(dpy, &wp_presentation_interface, 1, NULL, bind_presentation);
wl_global_create(dpy, &wp_viewporter_interface, 1, NULL, bind_viewporter);
diff --git a/server/tests/gpu_cycle.sh b/server/tests/gpu_cycle.sh
new file mode 100644
index 0000000..f9b454f
--- /dev/null
+++ b/server/tests/gpu_cycle.sh
@@ -0,0 +1,54 @@
+#!/bin/sh
+# gpu_cycle.sh — a session leaves the monitor and comes back N times while Wayland apps keep
+# drawing; checks that their windows are not black afterwards and that fds and memory stay flat
+# (docs/GPU.md, "When the GPU context is re-created"). Integration test, not part of `make test`:
+# it needs a free DRM card (stop lordos.service first), sudo (the seat side is root, as
+# lord-sessiond is) and, for the dmabuf client, /dev/udmabuf.
+#
+# sh tests/gpu_cycle.sh <lord-server> <cycles> [card] [gpu] (gpu: 1 = LORD_GPU=1, 0 = CPU)
+#
+# Prints per-cycle fd count and RSS of the session and leaves the DRM snapshots in $OUT
+# (default /tmp/gpu-cycle). Run from server/ after `make build/dmabuf-client build/seat-cycle`.
+set -eu
+BIN=$1
+CYCLES=${2:-10}
+CARD=${3:-/dev/dri/card0}
+GPU=${4:-1}
+OUT=${OUT:-/tmp/gpu-cycle}
+LIB=${LIB:-/usr/lib/lordos}
+RT=$OUT/rt
+rm -rf "$OUT"
+mkdir -p "$RT" "$OUT/home"
+chmod 700 "$RT"
+
+env -i PATH=/usr/bin:/bin HOME="$OUT/home" XDG_RUNTIME_DIR="$RT" LORD_GPU="$GPU" LORD_GPU_DEBUG=1 \
+ "$BIN" --headless 1280x800 --theme "$LIB/themes/default/theme.bundle.js" \
+ --fonts "$LIB/assets/fonts" --shell "$LIB/assets/shell" 2>"$OUT/stderr.log" &
+SESS=$!
+trap 'kill $SESS 2>/dev/null; sudo pkill -f "$OUT/rt" 2>/dev/null || true' EXIT
+for _ in $(seq 50); do [ -S "$RT/lordos/remote.sock" ] && break; sleep 0.2; done
+sleep 3
+WL=$(cd "$RT" && ls wayland-* | grep -v lock | head -1)
+
+# a dmabuf client (udmabuf, linear) and, if there is one, Chromium on Wayland with an animation
+sudo env XDG_RUNTIME_DIR="$RT" WAYLAND_DISPLAY="$WL" build/dmabuf-client --frames 100000000 --size 480x320 \
+ >"$OUT/dmabuf-client.log" 2>&1 &
+if command -v chromium >/dev/null; then
+ cat >"$OUT/anim.html" <<'EOF'
+<body style="margin:0;background:#123"><canvas id=c width=600 height=400></canvas><script>
+const g=c.getContext('2d');let t=0;(function f(){t++;g.fillStyle=`hsl(${t%360},80%,50%)`;g.fillRect(0,0,600,400);
+g.fillStyle='#fff';g.font='48px sans-serif';g.fillText('frame '+t,40,200);requestAnimationFrame(f)})()</script>
+EOF
+ env -i PATH=/usr/bin:/bin HOME="$OUT/home" XDG_RUNTIME_DIR="$RT" WAYLAND_DISPLAY="$WL" \
+ chromium --ozone-platform=wayland --user-data-dir="$OUT/chrome" --no-first-run --window-size=700,500 \
+ "file://$OUT/anim.html" >"$OUT/chromium.log" 2>&1 &
+fi
+sleep 8
+
+echo "before: fds=$(ls /proc/$SESS/fd | wc -l) rss_kb=$(awk '/VmRSS/{print $2}' /proc/$SESS/status)"
+# after each cycle (the session off the monitor): open fds and RSS of the session
+sudo build/seat-cycle "$RT/lordos/remote.sock" "$CARD" "$CYCLES" 3000 1500 "$OUT/c" \
+ "echo cycle \$CYCLE: fds=\$(ls /proc/$SESS/fd | wc -l) rss_kb=\$(awk '/VmRSS/{print \$2}' /proc/$SESS/status)"
+echo "end (on the monitor): fds=$(ls /proc/$SESS/fd | wc -l) rss_kb=$(awk '/VmRSS/{print $2}' /proc/$SESS/status)"
+grep -E "^(gpu|monitor|wayland):" "$OUT/home/.cache/lordos/session.log" | sort | uniq -c | sort -rn | head -20
+echo "snapshots: $OUT/c-NN.bmp (each time it was shown) and $OUT/c-final.bmp"
diff --git a/server/tests/seat_cycle.c b/server/tests/seat_cycle.c
new file mode 100644
index 0000000..f6fb5e9
--- /dev/null
+++ b/server/tests/seat_cycle.c
@@ -0,0 +1,170 @@
+/* seat_cycle.c — plays lord-sessiond's monitor part against one session, to test what happens
+ * when a session leaves the monitor and comes back (docs/GPU.md, "When the GPU context is
+ * re-created"; run by tests/gpu_cycle.sh).
+ *
+ * sudo build/seat-cycle <remote.sock> <card> <cycles> <on_ms> <off_ms> [snapshot-prefix [hook]]
+ *
+ * It connects to the session's remote.sock as root, says RP_SEAT and, <cycles> times, opens the
+ * card (DRM master), lends it with RP_DISPLAY, waits <on_ms>, saves what the CRTC shows as
+ * <prefix>-NN.bmp (GETFB2 + MAP_DUMB: works with dumb-backed buffers such as vkms with Mesa's
+ * kms_swrast), sends RP_UNDISPLAY, waits <off_ms>, drops master and closes the card: the same
+ * steps lord-sessiond takes on a session switch. No input devices are lent. After each cycle it runs
+ * <hook> (a shell command, with the cycle number in $CYCLE), and at the end it lends the card once more
+ * and leaves the session on the monitor (snapshot <prefix>-final.bmp).
+ * A test tool only: it is never installed. */
+#define _GNU_SOURCE
+#include <errno.h>
+#include <fcntl.h>
+#include <poll.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/ioctl.h>
+#include <sys/mman.h>
+#include <sys/socket.h>
+#include <sys/un.h>
+#include <time.h>
+#include <unistd.h>
+#include <drm/drm.h>
+#include <drm/drm_mode.h>
+
+enum { RP_SEAT = 18, RP_DISPLAY = 19, RP_UNDISPLAY = 22 };
+
+static int sock = -1;
+
+static int send_msg(int type, const void *d, size_t n, int fd) {
+ unsigned char h[5];
+ uint32_t len = (uint32_t)(1 + n);
+ memcpy(h, &len, 4);
+ h[4] = (unsigned char)type;
+ struct iovec iov[2] = { { h, 5 }, { (void *)d, n } };
+ char cbuf[CMSG_SPACE(sizeof(int))];
+ memset(cbuf, 0, sizeof cbuf);
+ struct msghdr mh = { .msg_iov = iov, .msg_iovlen = n ? 2 : 1 };
+ if (fd >= 0) {
+ mh.msg_control = cbuf;
+ mh.msg_controllen = sizeof cbuf;
+ struct cmsghdr *cm = CMSG_FIRSTHDR(&mh);
+ cm->cmsg_level = SOL_SOCKET;
+ cm->cmsg_type = SCM_RIGHTS;
+ cm->cmsg_len = CMSG_LEN(sizeof(int));
+ memcpy(CMSG_DATA(cm), &fd, sizeof(int));
+ }
+ return sendmsg(sock, &mh, MSG_NOSIGNAL) == (ssize_t)(5 + n) ? 0 : -1;
+}
+
+/* Waits ms while reading (and ignoring) whatever the session sends. */
+static void wait_ms(int ms) {
+ struct timespec t0;
+ clock_gettime(CLOCK_MONOTONIC, &t0);
+ for (;;) {
+ struct timespec t;
+ clock_gettime(CLOCK_MONOTONIC, &t);
+ long left = ms - ((t.tv_sec - t0.tv_sec) * 1000 + (t.tv_nsec - t0.tv_nsec) / 1000000);
+ if (left <= 0) return;
+ struct pollfd p = { sock, POLLIN, 0 };
+ if (poll(&p, 1, (int)left) > 0) {
+ char buf[4096];
+ if (read(sock, buf, sizeof buf) <= 0) { fprintf(stderr, "seat-cycle: the session closed the socket\n"); exit(1); }
+ }
+ }
+}
+
+static void put16(FILE *f, unsigned v) { fputc(v & 255, f); fputc(v >> 8 & 255, f); }
+static void put32(FILE *f, unsigned v) { put16(f, v & 0xffff); put16(f, v >> 16); }
+
+/* What the first active CRTC shows, as a 24-bit BMP. 0 if saved. */
+static int snapshot(int card, const char *path) {
+ uint32_t crtcs[16];
+ struct drm_mode_card_res r = {0};
+ if (ioctl(card, DRM_IOCTL_MODE_GETRESOURCES, &r)) return -1;
+ r = (struct drm_mode_card_res){ .crtc_id_ptr = (uint64_t)(uintptr_t)crtcs, .count_crtcs = r.count_crtcs < 16 ? r.count_crtcs : 16 };
+ if (ioctl(card, DRM_IOCTL_MODE_GETRESOURCES, &r)) return -1;
+ for (uint32_t i = 0; i < r.count_crtcs && i < 16; i++) {
+ struct drm_mode_crtc c = { .crtc_id = crtcs[i] };
+ if (ioctl(card, DRM_IOCTL_MODE_GETCRTC, &c) || !c.fb_id) continue;
+ struct drm_mode_fb_cmd2 fb = { .fb_id = c.fb_id };
+ if (ioctl(card, DRM_IOCTL_MODE_GETFB2, &fb) || !fb.handles[0]) return -1;
+ struct drm_mode_map_dumb md = { .handle = fb.handles[0] };
+ int ret = -1;
+ size_t size = (size_t)fb.pitches[0] * fb.height;
+ if (!ioctl(card, DRM_IOCTL_MODE_MAP_DUMB, &md)) {
+ uint8_t *m = mmap(NULL, size + fb.offsets[0], PROT_READ, MAP_SHARED, card, (off_t)md.offset);
+ FILE *f = m != MAP_FAILED ? fopen(path, "wb") : NULL;
+ if (f) {
+ unsigned w = fb.width, h = fb.height, row = (w * 3 + 3) & ~3u;
+ fputc('B', f); fputc('M', f); put32(f, 54 + row * h); put32(f, 0); put32(f, 54);
+ put32(f, 40); put32(f, w); put32(f, h); put16(f, 1); put16(f, 24); put32(f, 0);
+ put32(f, row * h); put32(f, 2835); put32(f, 2835); put32(f, 0); put32(f, 0);
+ for (unsigned y = h; y-- > 0;) {
+ const uint32_t *px = (const uint32_t *)(m + fb.offsets[0] + (size_t)y * fb.pitches[0]);
+ for (unsigned x = 0; x < w; x++) { fputc(px[x] & 255, f); fputc(px[x] >> 8 & 255, f); fputc(px[x] >> 16 & 255, f); }
+ for (unsigned x = w * 3; x < row; x++) fputc(0, f);
+ }
+ fclose(f);
+ ret = 0;
+ }
+ if (m != MAP_FAILED) munmap(m, size + fb.offsets[0]);
+ }
+ struct drm_gem_close gc = { .handle = fb.handles[0] };
+ ioctl(card, DRM_IOCTL_GEM_CLOSE, &gc);
+ return ret;
+ }
+ return -1;
+}
+
+int main(int argc, char **argv) {
+ if (argc < 6) {
+ fprintf(stderr, "usage: %s <remote.sock> <card> <cycles> <on_ms> <off_ms> [snapshot-prefix [hook]]\n", argv[0]);
+ return 2;
+ }
+ int cycles = atoi(argv[3]), on_ms = atoi(argv[4]), off_ms = atoi(argv[5]);
+ const char *prefix = argc > 6 && argv[6][0] ? argv[6] : NULL, *hook = argc > 7 ? argv[7] : NULL;
+ sock = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0);
+ struct sockaddr_un a = { .sun_family = AF_UNIX };
+ snprintf(a.sun_path, sizeof a.sun_path, "%s", argv[1]);
+ if (sock < 0 || connect(sock, (struct sockaddr *)&a, sizeof a)) { perror("seat-cycle: connect"); return 1; }
+ if (send_msg(RP_SEAT, NULL, 0, -1)) { perror("seat-cycle: RP_SEAT"); return 1; }
+ for (int i = 0; i < cycles; i++) {
+ int card = open(argv[2], O_RDWR | O_CLOEXEC);
+ if (card < 0) { perror("seat-cycle: card"); return 1; }
+ ioctl(card, DRM_IOCTL_SET_MASTER, 0);
+ unsigned char d[2] = { 1, 0 };
+ if (send_msg(RP_DISPLAY, d, sizeof d, card)) { perror("seat-cycle: RP_DISPLAY"); return 1; }
+ wait_ms(on_ms);
+ if (prefix) {
+ char path[512];
+ snprintf(path, sizeof path, "%s-%02d.bmp", prefix, i + 1);
+ if (snapshot(card, path)) fprintf(stderr, "seat-cycle: no snapshot for cycle %d\n", i + 1);
+ }
+ printf("cycle %d: shown\n", i + 1);
+ fflush(stdout);
+ if (send_msg(RP_UNDISPLAY, NULL, 0, -1)) { perror("seat-cycle: RP_UNDISPLAY"); return 1; }
+ wait_ms(off_ms);
+ ioctl(card, DRM_IOCTL_DROP_MASTER, 0);
+ close(card);
+ if (hook) {
+ char n[16];
+ snprintf(n, sizeof n, "%d", i + 1);
+ setenv("CYCLE", n, 1);
+ fflush(stdout);
+ if (system(hook) != 0) fprintf(stderr, "seat-cycle: the hook failed\n");
+ }
+ }
+ /* back on the monitor at the end, so the last state can be looked at */
+ int card = open(argv[2], O_RDWR | O_CLOEXEC);
+ if (card >= 0) {
+ ioctl(card, DRM_IOCTL_SET_MASTER, 0);
+ unsigned char d[2] = { 1, 0 };
+ send_msg(RP_DISPLAY, d, sizeof d, card);
+ wait_ms(on_ms);
+ if (prefix) {
+ char path[512];
+ snprintf(path, sizeof path, "%s-final.bmp", prefix);
+ snapshot(card, path);
+ }
+ close(card);
+ }
+ return 0;
+}