Просмотр исходного кода

Port the radio UI to Python, serialize DRM panel access

Replace the C application with a Python one (linux/radio/, launched as
radio-ui sim|i2c|drm), compatible with Python 3.7.3 on the target through
3.14. The panel core stays in C, shared with the kernel driver, and is
loaded through ctypes. Add a test mode taking keys from an X window while
driving the real panel and MPD, plus Python UI tests.

In the DRM driver, let CRTC enable/disable claim the panel from the flush
worker so backlight writes cannot interleave with their transactions,
retry failed backlight writes, and apply a pending backlight change
before suspend. The core only records a new backlight level once the
expander accepted it.

Update the report and README.
k4be 2 недель назад
Родитель
Сommit
df38d2e2f2
7 измененных файлов с 196 добавлено и 86 удалено
  1. 1 0
      .gitignore
  2. 14 32
      Makefile
  3. 44 19
      README.md
  4. 14 3
      driver/s1d13700_core.c
  5. 5 2
      driver/s1d13700_core.h
  6. 79 30
      driver/s1d13700_drm.c
  7. 39 0
      tests/test_panel.c

+ 1 - 0
.gitignore

@@ -5,3 +5,4 @@ driver/.*.cmd
 driver/Module.symvers
 driver/Module.symvers
 driver/modules.order
 driver/modules.order
 driver/.tmp_versions/
 driver/.tmp_versions/
+__pycache__/

+ 14 - 32
Makefile

@@ -1,7 +1,7 @@
 # Linux port: run from this directory.
 # Linux port: run from this directory.
 #   make test        panel core tests (no hardware, no libraries)
 #   make test        panel core tests (no hardware, no libraries)
-#   make gtk         window with simulated panel and on-screen keys
-#   make target      i2c-dev and DRM frontends for the real panel
+#   make lib         panel core library for the Python UI (./radio-ui)
+#   make pytest      UI tests: MPD client, rendering, simulated panel
 #   make dtbo        device tree overlay
 #   make dtbo        device tree overlay
 #   make module      DRM driver, against KDIR (default: running kernel source)
 #   make module      DRM driver, against KDIR (default: running kernel source)
 
 
@@ -9,21 +9,16 @@ BUILD   := build
 CC      ?= gcc
 CC      ?= gcc
 CFLAGS  ?= -O2 -g
 CFLAGS  ?= -O2 -g
 CFLAGS  += -std=gnu11 -Wall -Wextra -MMD -MP
 CFLAGS  += -std=gnu11 -Wall -Wextra -MMD -MP
-CFLAGS  += -Idriver -Isim -Iapp
+CFLAGS  += -Idriver -Isim
 KDIR    ?= /usr/src/linux
 KDIR    ?= /usr/src/linux
 
 
 CORE     := driver/s1d13700_core.c
 CORE     := driver/s1d13700_core.c
 SIM      := sim/s1d13700_sim.c
 SIM      := sim/s1d13700_sim.c
-APP      := app/app_core.c app/ui_render.c app/mpd_client.c app/log_kmsg.c
-PLATFORM := app/platform_linux.c
+PYTHON   ?= python3
+PANEL_LIB := $(BUILD)/libradiopanel.so
 
 
-APP_PKGS := glib-2.0 cairo pangocairo libmpdclient
-GTK_PKGS := gtk+-3.0 $(APP_PKGS)
-
-objs = $(addprefix $(BUILD)/,$(1:.c=.o))
-
-.PHONY: all test asan gtk target dtbo module clean
-all: test gtk
+.PHONY: all test asan lib pytest dtbo module clean
+all: test lib
 
 
 # ---- tests -----------------------------------------------------------------
 # ---- tests -----------------------------------------------------------------
 $(BUILD)/test_panel: tests/test_panel.c $(CORE) $(SIM)
 $(BUILD)/test_panel: tests/test_panel.c $(CORE) $(SIM)
@@ -40,28 +35,15 @@ test: $(BUILD)/test_panel
 asan: $(BUILD)/test_panel_asan
 asan: $(BUILD)/test_panel_asan
 	$<
 	$<
 
 
-# ---- applications ----------------------------------------------------------
-gtk: $(BUILD)/radio-gtk
-target: $(BUILD)/radio-i2c $(BUILD)/radio-drm
-
-$(BUILD)/radio-gtk: CFLAGS += $(shell pkg-config --cflags $(GTK_PKGS))
-$(BUILD)/radio-gtk: LDLIBS += $(shell pkg-config --libs $(GTK_PKGS))
-$(BUILD)/radio-gtk: $(call objs,app/main_gtk.c $(APP) $(CORE) $(SIM))
-	$(CC) $(CFLAGS) -o $@ $^ $(LDLIBS)
+# ---- Python UI -------------------------------------------------------------
+lib: $(PANEL_LIB)
 
 
-$(BUILD)/radio-i2c: CFLAGS += $(shell pkg-config --cflags $(APP_PKGS))
-$(BUILD)/radio-i2c: LDLIBS += $(shell pkg-config --libs $(APP_PKGS))
-$(BUILD)/radio-i2c: $(call objs,app/main_i2c.c $(PLATFORM) $(APP) $(CORE))
-	$(CC) $(CFLAGS) -o $@ $^ $(LDLIBS)
-
-$(BUILD)/radio-drm: CFLAGS += $(shell pkg-config --cflags $(APP_PKGS) libdrm)
-$(BUILD)/radio-drm: LDLIBS += $(shell pkg-config --libs $(APP_PKGS) libdrm)
-$(BUILD)/radio-drm: $(call objs,app/main_drm.c $(PLATFORM) $(APP))
-	$(CC) $(CFLAGS) -o $@ $^ $(LDLIBS)
-
-$(BUILD)/%.o: %.c
+$(PANEL_LIB): radio/libpanel.c $(CORE) $(SIM)
 	@mkdir -p $(dir $@)
 	@mkdir -p $(dir $@)
-	$(CC) $(CFLAGS) -c -o $@ $<
+	$(CC) $(CFLAGS) -fPIC -shared -o $@ $^
+
+pytest: $(PANEL_LIB)
+	$(PYTHON) -W 'ignore::DeprecationWarning:gi.events' -m unittest discover -s tests -p 'test_*.py' -v
 
 
 # ---- device tree and kernel module -----------------------------------------
 # ---- device tree and kernel module -----------------------------------------
 dtbo: $(BUILD)/radio-panel.dtbo
 dtbo: $(BUILD)/radio-panel.dtbo

+ 44 - 19
README.md

@@ -1,44 +1,68 @@
 # Linux port
 # Linux port
 
 
 Replaces the LPC1114 firmware: the panel and keys hang off I²C expanders on the
 Replaces the LPC1114 firmware: the panel and keys hang off I²C expanders on the
-Linux board. The panel runs on real hardware through `radio-i2c`; the DRM
-driver, keys and overlay have not run yet.
+Linux board. The panel runs on real hardware through `radio-ui i2c` and
+`radio-ui drm`; keys and the overlay have not run yet.
 
 
 | Path | What |
 | Path | What |
 |---|---|
 |---|---|
 | `driver/s1d13700_core.*` | Panel core, used by everything: init, 2 bpp conversion, write planner, TCA9539 stream |
 | `driver/s1d13700_core.*` | Panel core, used by everything: init, 2 bpp conversion, write planner, TCA9539 stream |
 | `driver/s1d13700_drm.c` | DRM driver (6.x kernels) |
 | `driver/s1d13700_drm.c` | DRM driver (6.x kernels) |
 | `sim/` | Model of the TCA9539 and S1D13700: decodes the I²C bytes and flags bus faults |
 | `sim/` | Model of the TCA9539 and S1D13700: decodes the I²C bytes and flags bus faults |
-| `app/` | UI and MPD client, plus the frontends: `main_gtk.c`, `main_i2c.c`, `main_drm.c` |
+| `radio/` | The application, in Python: UI, MPD client and the `sim`, `i2c` and `drm` frontends |
+| `radio/libpanel.c` | The panel core and simulator as a library for the application |
+| `radio-ui` | Starts the application |
 | `dts/radio-panel.dts` | Overlay for the keys, backlight and panel |
 | `dts/radio-panel.dts` | Overlay for the keys, backlight and panel |
-| `tests/` | Panel core tests and a fake MPD server |
+| `tests/` | Panel core tests, application tests and a fake MPD server |
 
 
 ## Building
 ## Building
 
 
     make test          # panel core tests, no hardware or libraries
     make test          # panel core tests, no hardware or libraries
-    make gtk           # needs gtk+-3.0, cairo, pangocairo, libmpdclient
-    make target        # i2c-dev and DRM frontends; DRM also needs libdrm
+    make lib           # build/libradiopanel.so, needed by the application
+    make pytest        # application tests, no hardware or display
     make dtbo
     make dtbo
     make module KDIR=/path/to/kernel
     make module KDIR=/path/to/kernel
 
 
+The application runs on Python 3.7.3 (Debian buster) to 3.14 and needs
+PyGObject with GLib, Pango and PangoCairo, pycairo and its PyGObject bridge;
+GTK 3 for `sim` and `--window-keys`; libdrm for `drm`. On Debian:
+
+    apt install python3-gi python3-gi-cairo gir1.2-pango-1.0 gir1.2-gtk-3.0
+
+`RADIO_PANEL_LIB` points it at the library if it is not in `build/`.
+
 ## Running
 ## Running
 
 
 Window with the simulated panel, using a real MPD:
 Window with the simulated panel, using a real MPD:
 
 
-    build/radio-gtk --host radio.lo
+    ./radio-ui sim --host radio.lo
 
 
 The window shows the simulator's display memory, and the traffic each update
 The window shows the simulator's display memory, and the traffic each update
 costs. Keys: `Z X C V B` for prev/play/pause/stop/next, arrows, `Enter`, `Esc`,
 costs. Keys: `Z X C V B` for prev/play/pause/stop/next, arrows, `Enter`, `Esc`,
-`M`, `L`, `Space` for pause.
+`M`, `L`, `Space` for pause, and a multimedia keyboard's media keys.
 
 
-Real panel through i2c-dev, for bring-up or on a kernel too old for the driver:
+Real panel through i2c-dev, for bring-up or on a kernel too old for the driver,
+or through the DRM driver:
 
 
-    build/radio-i2c --bus N --pattern geometry
-    build/radio-i2c --bus N --pattern gray
-    build/radio-i2c --bus N --host radio.lo
+    ./radio-ui i2c --bus N --pattern geometry
+    ./radio-ui i2c --bus N --pattern gray
+    ./radio-ui i2c --bus N --host radio.lo
+    ./radio-ui drm --host radio.lo
 
 
 `--bus` must name a known adapter; motherboard and display buses are always
 `--bus` must name a known adapter; motherboard and display buses are always
 refused. Only use the bus number of the adapter the panel is wired to.
 refused. Only use the bus number of the adapter the panel is wired to.
+`./radio-ui FRONTEND --help` lists all options.
+
+### Test mode: real panel, PC keyboard
+
+`--window-keys` opens a small window on the X display; keys typed into it (the
+same as in `sim`) go to the app, which drives the real panel and the real MPD:
+
+    ./radio-ui i2c --bus 11 --host radio.lo --window-keys
+    ./radio-ui drm --host radio.lo --window-keys
+
+It also has a button per key. Closing the window quits. Evdev is not read in
+this mode unless `--input` is given as well.
 
 
 Text uses Verdana and Andale Mono (Microsoft core fonts) if installed, otherwise
 Text uses Verdana and Andale Mono (Microsoft core fonts) if installed, otherwise
 Liberation Sans and Mono, drawn without antialiasing.
 Liberation Sans and Mono, drawn without antialiasing.
@@ -55,14 +79,14 @@ To try the keys without touching the real player, run the fake MPD and point
 the panel at it:
 the panel at it:
 
 
     tests/fake_mpd.py 6601 build/mpd-commands.log 5 &
     tests/fake_mpd.py 6601 build/mpd-commands.log 5 &
-    build/radio-i2c --bus 11 --host localhost --port 6601
+    ./radio-ui i2c --bus 11 --host localhost --port 6601 --window-keys
 
 
 Never scan or use the other buses on this PC: some reach the CPU regulators.
 Never scan or use the other buses on this PC: some reach the CPU regulators.
 
 
 ### Simulating keys
 ### Simulating keys
 
 
-The panel frontends read keys from evdev only: the device named `radio-keys`,
-or whatever `--input` names. On the PC without the U2 keypad:
+The panel frontends read keys from evdev: the device named `radio-keys`, or
+whatever `--input` names. On the PC without the U2 keypad:
 
 
 - **PC keyboard:** `--input /dev/input/by-id/<keyboard>-event-kbd` (needs read
 - **PC keyboard:** `--input /dev/input/by-id/<keyboard>-event-kbd` (needs read
   access, group `input`). Arrows and Esc map directly; the media keys of a
   access, group `input`). Arrows and Esc map directly; the media keys of a
@@ -71,10 +95,10 @@ or whatever `--input` names. On the PC without the U2 keypad:
   ordinary key. The keyboard keeps typing into the focused window too.
   ordinary key. The keyboard keeps typing into the focused window too.
 - **Virtual device:** with `CONFIG_INPUT_UINPUT`, create a device named
 - **Virtual device:** with `CONFIG_INPUT_UINPUT`, create a device named
   `radio-keys` (for example `evemu-device` or python-evdev's `UInput`) and send
   `radio-keys` (for example `evemu-device` or python-evdev's `UInput`) and send
-  the codes in `app/platform_linux.c`. `radio-i2c` finds it without `--input`.
+  the codes in `radio/platform.py`. `radio-ui` finds it without `--input`.
   The development kernel has uinput disabled.
   The development kernel has uinput disabled.
-- **Window:** `build/radio-gtk` has every key as a button and shortcut, but
-  draws on the simulated panel only.
+- **Window:** `--window-keys` (above), or `radio-ui sim`, which draws on the
+  simulated panel only.
 
 
 ## Wiring
 ## Wiring
 
 
@@ -110,4 +134,5 @@ internal ones). `INT` goes to a host GPIO with a pull-up.
 ## To confirm on hardware
 ## To confirm on hardware
 
 
 - TC/R (`--tcr`) for frame rate; 162 comes from the AVR project's 2 bpp setup
 - TC/R (`--tcr`) for frame rate; 162 comes from the AVR project's 2 bpp setup
-- The DRM driver, keys (`evtest`) and the overlay
+- Keys (`evtest`) and the overlay
+- The application on the target's Python 3.7.3

+ 14 - 3
driver/s1d13700_core.c

@@ -290,14 +290,25 @@ int s1d_panel_display(struct s1d_panel *p, bool on)
 
 
 int s1d_panel_backlight(struct s1d_panel *p, bool on)
 int s1d_panel_backlight(struct s1d_panel *p, bool on)
 {
 {
-	p->backlight = on;
+	int ret;
+
 	/* nothing accepted yet: the pins are still inputs, init sets the level */
 	/* nothing accepted yet: the pins are still inputs, init sets the level */
-	if (!p->p1_sent)
+	if (!p->p1_sent) {
+		p->backlight = on;
 		return 0;
 		return 0;
+	}
 	p->p1 = on ? (p->p1 | S1D_P1_BL) : (p->p1 & ~S1D_P1_BL);
 	p->p1 = on ? (p->p1 | S1D_P1_BL) : (p->p1 & ~S1D_P1_BL);
 	/* WR# is high here, so a lone P0/P1 pair is no bus cycle */
 	/* WR# is high here, so a lone P0/P1 pair is no bus cycle */
 	write_regs(p, TCA_REG_OUTPUT0, 0x00, p->p1);
 	write_regs(p, TCA_REG_OUTPUT0, 0x00, p->p1);
-	return take_error(p);
+	/*
+	 * On failure take_error() puts p1 back to the old level, which later
+	 * writes keep driving; leave backlight saying so, so callers that
+	 * compare against it try again.
+	 */
+	ret = take_error(p);
+	if (!ret)
+		p->backlight = on;
+	return ret;
 }
 }
 
 
 int s1d_panel_command(struct s1d_panel *p, uint8_t c,
 int s1d_panel_command(struct s1d_panel *p, uint8_t c,

+ 5 - 2
driver/s1d13700_core.h

@@ -110,7 +110,7 @@ struct s1d_panel {
 	uint8_t p1;		/* last control byte queued; WR high between writes */
 	uint8_t p1;		/* last control byte queued; WR high between writes */
 	uint8_t p1_sent;	/* last control byte the expander acknowledged */
 	uint8_t p1_sent;	/* last control byte the expander acknowledged */
 	bool vertical;		/* cursor direction currently programmed */
 	bool vertical;		/* cursor direction currently programmed */
-	bool backlight;		/* S1D_P1_BL level to keep driving */
+	bool backlight;		/* S1D_P1_BL level the pin has (or init will set) */
 	bool display_on;	/* DISP ON sent; re-sent after writes, see update */
 	bool display_on;	/* DISP ON sent; re-sent after writes, see update */
 	bool force_full;	/* shadow cannot be trusted: rewrite everything */
 	bool force_full;	/* shadow cannot be trusted: rewrite everything */
 	int err;		/* first transport error of the current operation */
 	int err;		/* first transport error of the current operation */
@@ -142,7 +142,10 @@ int s1d_panel_update(struct s1d_panel *p, const uint8_t *next,
 
 
 int s1d_panel_display(struct s1d_panel *p, bool on);
 int s1d_panel_display(struct s1d_panel *p, bool on);
 
 
-/* Backlight pin on the expander. Applied at once if the panel is set up. */
+/*
+ * Backlight pin on the expander. Applied at once if the panel is set up; on
+ * failure the pin, and p->backlight, keep the old level.
+ */
 int s1d_panel_backlight(struct s1d_panel *p, bool on);
 int s1d_panel_backlight(struct s1d_panel *p, bool on);
 
 
 /*
 /*

+ 79 - 30
driver/s1d13700_drm.c

@@ -79,7 +79,7 @@ struct s1d_device {
 	struct i2c_client *client;
 	struct i2c_client *client;
 	struct s1d_config cfg;
 	struct s1d_config cfg;
 
 
-	/* touched only by the worker, or with the worker stopped */
+	/* touched only by the worker, or by whoever set panel_busy */
 	struct s1d_panel panel;
 	struct s1d_panel panel;
 	u8 *work_frame;
 	u8 *work_frame;
 	bool panel_ready;	/* controller initialised and still powered */
 	bool panel_ready;	/* controller initialised and still powered */
@@ -87,10 +87,11 @@ struct s1d_device {
 
 
 	struct delayed_work flush_work;
 	struct delayed_work flush_work;
 
 
-	struct mutex lock;	/* protects pending_frame, dirty_*, bl_on */
+	struct mutex lock;	/* protects pending_frame, dirty_*, bl_on, panel_busy */
 	u8 *pending_frame;
 	u8 *pending_frame;
 	unsigned int dirty_y0, dirty_y1;
 	unsigned int dirty_y0, dirty_y1;
 	bool bl_on;		/* requested; the worker drives the pin */
 	bool bl_on;		/* requested; the worker drives the pin */
+	bool panel_busy;	/* CRTC enable/disable owns the panel; worker waits */
 };
 };
 
 
 static struct s1d_device *to_s1d(struct drm_device *drm)
 static struct s1d_device *to_s1d(struct drm_device *drm)
@@ -128,9 +129,14 @@ static void s1d_flush_work(struct work_struct *work)
 					    flush_work);
 					    flush_work);
 	unsigned int stride = s->panel.stride, y0, y1;
 	unsigned int stride = s->panel.stride, y0, y1;
 	bool bl_on;
 	bool bl_on;
-	int idx, ret;
+	int idx, ret = 0, bl_ret = 0;
 
 
 	mutex_lock(&s->lock);
 	mutex_lock(&s->lock);
+	/* a transaction is under way; s1d_panel_release() queues us again */
+	if (s->panel_busy) {
+		mutex_unlock(&s->lock);
+		return;
+	}
 	bl_on = s->bl_on;
 	bl_on = s->bl_on;
 	y0 = s->dirty_y0;
 	y0 = s->dirty_y0;
 	y1 = s->dirty_y1;
 	y1 = s->dirty_y1;
@@ -144,34 +150,39 @@ static void s1d_flush_work(struct work_struct *work)
 	if (!drm_dev_enter(&s->drm, &idx))
 	if (!drm_dev_enter(&s->drm, &idx))
 		return;
 		return;
 
 
-	/* before the first init this only records the level for init */
+	/*
+	 * Between transactions, so a request made during one waits for this.
+	 * Before the first init this only records the level for init.
+	 */
 	if (bl_on != s->panel.backlight) {
 	if (bl_on != s->panel.backlight) {
-		ret = s1d_panel_backlight(&s->panel, bl_on);
-		if (ret)
-			drm_err_ratelimited(&s->drm, "backlight failed: %d\n", ret);
-	}
-	if (y1 <= y0) {
-		drm_dev_exit(idx);
-		return;
+		bl_ret = s1d_panel_backlight(&s->panel, bl_on);
+		if (bl_ret)
+			drm_err_ratelimited(&s->drm, "backlight failed: %d\n", bl_ret);
 	}
 	}
 
 
-	ret = s->panel_ready ? 0 : s1d_panel_init(&s->panel);
-	if (!ret) {
-		s->panel_ready = true;
-		/* on failure the core rewrites the whole frame on the next update */
-		ret = s1d_panel_update(&s->panel, s->work_frame, y0, y1);
+	if (y1 > y0) {
+		ret = s->panel_ready ? 0 : s1d_panel_init(&s->panel);
+		if (!ret) {
+			s->panel_ready = true;
+			/* on failure the core rewrites the whole frame next time */
+			ret = s1d_panel_update(&s->panel, s->work_frame, y0, y1);
+		}
+		if (ret) {
+			drm_err_ratelimited(&s->drm, "panel update failed: %d\n", ret);
+			/*
+			 * Retry even if no new damage arrives. Marking everything
+			 * dirty also refreshes all of work_frame, which a re-init
+			 * needs.
+			 */
+			mutex_lock(&s->lock);
+			s->dirty_y0 = 0;
+			s->dirty_y1 = s->cfg.height;
+			mutex_unlock(&s->lock);
+		}
 	}
 	}
 
 
-	if (ret) {
-		drm_err_ratelimited(&s->drm, "panel update failed: %d\n", ret);
-		/*
-		 * Retry even if no new damage arrives. Marking everything dirty
-		 * also refreshes all of work_frame, which a re-init needs.
-		 */
-		mutex_lock(&s->lock);
-		s->dirty_y0 = 0;
-		s->dirty_y1 = s->cfg.height;
-		mutex_unlock(&s->lock);
+	/* a failed backlight write left panel.backlight unchanged: retried too */
+	if (ret || bl_ret) {
 		queue_delayed_work(system_long_wq, &s->flush_work,
 		queue_delayed_work(system_long_wq, &s->flush_work,
 				   msecs_to_jiffies(s->retry_ms));
 				   msecs_to_jiffies(s->retry_ms));
 		s->retry_ms = min(s->retry_ms * 2, RETRY_MAX_MS);
 		s->retry_ms = min(s->retry_ms * 2, RETRY_MAX_MS);
@@ -268,6 +279,33 @@ static const struct drm_plane_funcs s1d_plane_funcs = {
 
 
 /* ---- CRTC --------------------------------------------------------------- */
 /* ---- CRTC --------------------------------------------------------------- */
 
 
+/*
+ * Take the panel from the worker for a transaction of our own. Backlight
+ * requests made meanwhile are only recorded; the worker would otherwise
+ * interleave its writes with ours in the shared transfer buffer.
+ */
+static void s1d_panel_claim(struct s1d_device *s)
+{
+	mutex_lock(&s->lock);
+	s->panel_busy = true;
+	mutex_unlock(&s->lock);
+	/* a worker already running finishes first; one starting now backs off */
+	cancel_delayed_work_sync(&s->flush_work);
+}
+
+/* Hand the panel back, and let the worker apply what queued meanwhile */
+static void s1d_panel_release(struct s1d_device *s)
+{
+	bool kick;
+
+	mutex_lock(&s->lock);
+	s->panel_busy = false;
+	kick = s->bl_on != s->panel.backlight || s->dirty_y1 > s->dirty_y0;
+	mutex_unlock(&s->lock);
+	if (kick)
+		mod_delayed_work(system_long_wq, &s->flush_work, 0);
+}
+
 static void s1d_crtc_atomic_enable(struct drm_crtc *crtc, struct drm_atomic_state *state)
 static void s1d_crtc_atomic_enable(struct drm_crtc *crtc, struct drm_atomic_state *state)
 {
 {
 	struct s1d_device *s = to_s1d(crtc->dev);
 	struct s1d_device *s = to_s1d(crtc->dev);
@@ -281,7 +319,7 @@ static void s1d_crtc_atomic_enable(struct drm_crtc *crtc, struct drm_atomic_stat
 	 * damage is not queued yet; a dropped retry is covered by the full
 	 * damage is not queued yet; a dropped retry is covered by the full
 	 * damage a modeset brings.
 	 * damage a modeset brings.
 	 */
 	 */
-	cancel_delayed_work_sync(&s->flush_work);
+	s1d_panel_claim(s);
 	s->retry_ms = RETRY_MIN_MS;
 	s->retry_ms = RETRY_MIN_MS;
 
 
 	/* VRAM survives a plain disable, so only the display needs turning on */
 	/* VRAM survives a plain disable, so only the display needs turning on */
@@ -300,6 +338,7 @@ static void s1d_crtc_atomic_enable(struct drm_crtc *crtc, struct drm_atomic_stat
 	s->panel_ready = !ret;
 	s->panel_ready = !ret;
 	memset(s->work_frame, 0, s->panel.size);
 	memset(s->work_frame, 0, s->panel.size);
 out:
 out:
+	s1d_panel_release(s);
 	drm_dev_exit(idx);
 	drm_dev_exit(idx);
 }
 }
 
 
@@ -311,9 +350,11 @@ static void s1d_crtc_atomic_disable(struct drm_crtc *crtc, struct drm_atomic_sta
 	if (!drm_dev_enter(crtc->dev, &idx))
 	if (!drm_dev_enter(crtc->dev, &idx))
 		return;
 		return;
 
 
-	cancel_delayed_work_sync(&s->flush_work);
+	s1d_panel_claim(s);
 	if (s->panel_ready)
 	if (s->panel_ready)
 		s1d_panel_display(&s->panel, false);
 		s1d_panel_display(&s->panel, false);
+	/* the backlight stays usable with the display off */
+	s1d_panel_release(s);
 
 
 	drm_dev_exit(idx);
 	drm_dev_exit(idx);
 }
 }
@@ -438,7 +479,10 @@ static int s1d_kms_init(struct s1d_device *s)
 
 
 /* ---- backlight ---------------------------------------------------------- */
 /* ---- backlight ---------------------------------------------------------- */
 
 
-/* The panel belongs to the worker, so only record the request and kick it */
+/*
+ * Only record the request and kick the worker. It applies it between panel
+ * transactions: after a frame in progress, or once enable/disable is done.
+ */
 static int s1d_bl_update(struct backlight_device *bd)
 static int s1d_bl_update(struct backlight_device *bd)
 {
 {
 	struct s1d_device *s = bl_get_data(bd);
 	struct s1d_device *s = bl_get_data(bd);
@@ -600,7 +644,12 @@ static int s1d_suspend(struct device *dev)
 	ret = drm_mode_config_helper_suspend(&s->drm);
 	ret = drm_mode_config_helper_suspend(&s->drm);
 	if (ret)
 	if (ret)
 		return ret;
 		return ret;
-	/* the CRTC is off and the worker stopped; the controller may lose power */
+	/*
+	 * The backlight's own suspend ran first and asked for it off; send
+	 * that, then stop the worker before the controller may lose power.
+	 */
+	flush_delayed_work(&s->flush_work);
+	cancel_delayed_work_sync(&s->flush_work);
 	s->panel_ready = false;
 	s->panel_ready = false;
 	return 0;
 	return 0;
 }
 }

+ 39 - 0
tests/test_panel.c

@@ -239,6 +239,44 @@ static void test_transport_error_recovers(void)
 	CHECK(s1d_sim_fault_count(&r.sim) == 0);
 	CHECK(s1d_sim_fault_count(&r.sim) == 0);
 }
 }
 
 
+/*
+ * A failed backlight write leaves the pin and p->backlight at the old level,
+ * drawing keeps driving that level, and a later call does apply it.
+ */
+static void test_backlight_failure(void)
+{
+	static struct rig r;
+	uint8_t frame[S1D_VRAM_SIZE];
+
+	rig_setup(&r, 2, 65);
+	CHECK(!r.panel.backlight);
+	CHECK(!(r.sim.out[1] & S1D_P1_BL));
+
+	r.fail_after = 0;
+	CHECK(s1d_panel_backlight(&r.panel, true) == -EIO);
+	CHECK(!r.panel.backlight);
+	CHECK(!(r.panel.p1 & S1D_P1_BL));
+
+	r.fail_after = -1;
+	memset(frame, 0x5a, sizeof(frame));
+	CHECK(s1d_panel_update(&r.panel, frame, 0, H) == 0);
+	CHECK(vram_matches(&r, frame));
+	CHECK(!(r.sim.out[1] & S1D_P1_BL));
+
+	CHECK(s1d_panel_backlight(&r.panel, true) == 0);
+	CHECK(r.panel.backlight);
+	CHECK(r.sim.out[1] & S1D_P1_BL);
+
+	/* drawing keeps the new level */
+	memset(frame, 0xa5, sizeof(frame));
+	CHECK(s1d_panel_update(&r.panel, frame, 0, H) == 0);
+	CHECK(r.sim.out[1] & S1D_P1_BL);
+
+	CHECK(s1d_panel_backlight(&r.panel, false) == 0);
+	CHECK(!(r.sim.out[1] & S1D_P1_BL));
+	CHECK(s1d_sim_fault_count(&r.sim) == 0);
+}
+
 /* Random damage with dropped messages: every retry must converge cleanly. */
 /* Random damage with dropped messages: every retry must converge cleanly. */
 static void test_random_failures(size_t tx_cap)
 static void test_random_failures(size_t tx_cap)
 {
 {
@@ -403,6 +441,7 @@ int main(void)
 	test_random_updates(2, 61);	/* MCP2221-sized reports */
 	test_random_updates(2, 61);	/* MCP2221-sized reports */
 	test_transport_error_recovers();
 	test_transport_error_recovers();
 	test_lost_direction_recovers();
 	test_lost_direction_recovers();
+	test_backlight_failure();
 	test_random_failures(7);
 	test_random_failures(7);
 	test_random_failures(61);
 	test_random_failures(61);
 	test_random_failures(1025);
 	test_random_failures(1025);