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

Add Linux port of the radio front panel

Replace the LPC1114 with software on the Linux board, driving the S1D13700
LCD and the keys through TCA9539 I2C expanders:

- panel core shared by all frontends: init, pixel conversion, write
  planner and the TCA9539 byte stream
- simulator of the expander and controller, with panel core tests
- UI and MPD client, with GTK (simulated panel), i2c-dev and DRM
  frontends
- DRM kernel driver and a device tree overlay

The review recommendations are applied to the core and the driver,
including retry of failed updates, enable-before-plane ordering and
recovery of the control line state after a lost message. The control
lines are mapped to the actual board, and the geometry and gray test
patterns were confirmed on the real panel.
k4be 2 недель назад
Сommit
b0a757a133
12 измененных файлов с 2624 добавлено и 0 удалено
  1. 7 0
      .gitignore
  2. 80 0
      Makefile
  3. 78 0
      README.md
  4. 427 0
      docs/s1d13700-recommendations.md
  5. 3 0
      driver/Kbuild
  6. 500 0
      driver/s1d13700_core.c
  7. 169 0
      driver/s1d13700_core.h
  8. 570 0
      driver/s1d13700_drm.c
  9. 81 0
      dts/radio-panel.dts
  10. 234 0
      sim/s1d13700_sim.c
  11. 63 0
      sim/s1d13700_sim.h
  12. 412 0
      tests/test_panel.c

+ 7 - 0
.gitignore

@@ -0,0 +1,7 @@
+build/
+driver/*.mod
+driver/*.mod.c
+driver/.*.cmd
+driver/Module.symvers
+driver/modules.order
+driver/.tmp_versions/

+ 80 - 0
Makefile

@@ -0,0 +1,80 @@
+# Linux port: run from this directory.
+#   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 dtbo        device tree overlay
+#   make module      DRM driver, against KDIR (default: running kernel source)
+
+BUILD   := build
+CC      ?= gcc
+CFLAGS  ?= -O2 -g
+CFLAGS  += -std=gnu11 -Wall -Wextra -MMD -MP
+CFLAGS  += -Idriver -Isim -Iapp
+KDIR    ?= /usr/src/linux
+
+CORE     := driver/s1d13700_core.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
+
+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
+
+# ---- tests -----------------------------------------------------------------
+$(BUILD)/test_panel: tests/test_panel.c $(CORE) $(SIM)
+	@mkdir -p $(dir $@)
+	$(CC) $(CFLAGS) -o $@ $^
+
+$(BUILD)/test_panel_asan: tests/test_panel.c $(CORE) $(SIM)
+	@mkdir -p $(dir $@)
+	$(CC) $(CFLAGS) -fsanitize=address,undefined -fno-sanitize-recover=all -o $@ $^
+
+test: $(BUILD)/test_panel
+	$<
+
+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)
+
+$(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
+	@mkdir -p $(dir $@)
+	$(CC) $(CFLAGS) -c -o $@ $<
+
+# ---- device tree and kernel module -----------------------------------------
+dtbo: $(BUILD)/radio-panel.dtbo
+
+$(BUILD)/radio-panel.dtbo: dts/radio-panel.dts
+	@mkdir -p $(dir $@)
+	dtc -@ -I dts -O dtb -o $@ $<
+
+module:
+	$(MAKE) -C $(KDIR) M=$(CURDIR)/driver modules
+
+clean:
+	rm -rf $(BUILD)
+	-$(MAKE) -C $(KDIR) M=$(CURDIR)/driver clean
+
+-include $(shell find $(BUILD) -name '*.d' 2>/dev/null)

+ 78 - 0
README.md

@@ -0,0 +1,78 @@
+# Linux port
+
+Replaces the LPC1114 firmware: the panel and keys hang off I²C expanders on the
+Linux board. Nothing here has run on real hardware yet.
+
+| Path | What |
+|---|---|
+| `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) |
+| `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` |
+| `dts/radio-panel.dts` | Overlay for the keys, backlight and panel |
+| `tests/` | Panel core tests and a fake MPD server |
+
+## Building
+
+    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 dtbo
+    make module KDIR=/path/to/kernel
+
+## Running
+
+Window with the simulated panel, using a real MPD:
+
+    build/radio-gtk --host radio.lo
+
+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`,
+`M`, `L`, `Space` for pause.
+
+Real panel through i2c-dev, for bring-up or on a kernel too old for the driver:
+
+    build/radio-i2c --bus N --pattern geometry
+    build/radio-i2c --bus N --pattern gray
+    build/radio-i2c --bus N --host radio.lo
+
+`--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.
+
+## Wiring
+
+**U1, TCA9539 at 0x74** (A1=L, A0=L), raw I²C client of the panel code
+
+| Pin | Signal | Module pin |
+|---|---|---|
+| P0.0-7 | D0-D7 | D0-D7 |
+| P1.0 | Backlight enable (active high, assumed) | |
+| P1.1 | RES# | RST |
+| P1.2 | A0 | A15 |
+| P1.3 | WR# | WE |
+| P1.4 | RD# | RE |
+| P1.5 | CS# (held low after reset; was hardwired low on the old board) | CS0 |
+| P1.6-7 | spare | |
+
+**U2, TCA9539 at 0x75** (A1=L, A0=H), stock `gpio-pca953x`
+
+Each key has its own pin to ground and a 10k pull-up (the TCA9539 has no
+internal ones). `INT` goes to a host GPIO with a pull-up.
+
+| Pin | Key | Pin | Key |
+|---|---|---|---|
+| P0.0 | Esc | P1.0 | Down |
+| P0.1 | Next | P1.1 | Pause |
+| P0.2 | Stop | P1.2 | OK |
+| P0.3 | Menu | P1.3 | Left |
+| P0.4 | List | P1.4 | Play |
+| P0.5 | Up | P1.5 | Backlight enable (active high, pull-down) |
+| P0.6 | Prev | P1.6-7 | spare |
+| P0.7 | Right | | |
+
+## To confirm on hardware
+
+- The TCA9539 stays in the register pair across a long write (the whole stream depends on it)
+- Panel size: 240×160 is assumed; `--pattern geometry` shows the real one
+- TC/R (`--tcr`) for frame rate; 162 comes from the AVR project's 2 bpp setup
+- Pixel polarity (white = level 0 here)

+ 427 - 0
docs/s1d13700-recommendations.md

@@ -0,0 +1,427 @@
+# S1D13700 / TCA9539 DRM driver: review recommendations
+
+Target: Linux 6.18 on **32-bit ARM (Cortex-A7)**.
+
+Line numbers refer to the reviewed versions of the two files:
+
+- **core**: `s1d13700_core.c`
+- **driver**: the DRM driver (`s1d_probe`, `s1d_flush_work`, ...)
+
+## How this was checked
+
+| Check | Result |
+|---|---|
+| Original module, ARMv7 (`multi_v7_defconfig`, `W=1`) | Compiles, but references `__aeabi_uldivmod` (see R1) |
+| Patched module with the code below, ARMv7, `W=1` | Compiles without warnings; the division now uses the exported `__do_div64` |
+| Original and patched core against a mock TCA9539 + S1D13700 | 20,000 random updates over 5 `tx_cap` values: VRAM always converged, no bus protocol violations |
+| Failure injection on the mock | R3 reproduced on the original and gone after the fix |
+| DRM behaviour | Read from the v6.18 source. **Not run on a live DRM stack or real hardware** |
+
+`s1d13700_core.h` was not available, so it was reconstructed from usage. Register values, pin assignments and cost constants were assumed (see R19).
+
+## Summary
+
+| ID | Priority | Where | Recommendation |
+|---|---|---|---|
+| R1 | **Must fix, blocks ARM** | core 448–454 | Replace the 64-bit division and fix the overflow |
+| R2 | **Must fix** | driver 292–296, 219–235 | Run CRTC enable before plane updates |
+| R3 | **Must fix** | core 95–102, 373–405 | Resend the cursor direction on a full refresh |
+| R4 | **Must fix** | driver 115–142, 219–249 | Retry failed updates and failed init |
+| R5 | Must fix if using a crystal | core 202–204 | Move the oscillator wait after P1 |
+| R6 | Should fix | core 130–132 | Enforce the stricter TC/R rule |
+| R7 | Should fix (32-bit) | driver 368–373, header | Decide how to handle wrapping counters |
+| R8 | Should fix (32-bit) | driver 146–155, core 426 | Reject framebuffers with a misaligned pitch |
+| R9 | Should fix | driver 229 | Skip the full reset on a plain re-enable |
+| R10 | Minor | core 313, 387 | Stop early after a bus error |
+| R11 | Minor | driver 173 | Log `begin_cpu_access` failures |
+| R12 | Minor | driver 181 | Handle I/O-memory framebuffers |
+| R13 | Minor | driver 443–450 | Turn the display off on unload |
+| R14 | Minor | driver | Add suspend/resume |
+| R15 | Minor | driver 197 | Use a long-running workqueue |
+| R16 | Minor | core 263–273 | Keep the direction cache correct in `s1d_panel_command` |
+| R17 | Cleanup | core 4 | Remove the unused include |
+| R18 | Cleanup | driver 51–62 | Move panel description to DT |
+| R19 | Verify | header | Confirm the constants and types |
+
+**Apply R2 and R4 together.** R4 uses `cancel_delayed_work_sync()` in `atomic_enable`, which is only safe once enables run before plane updates.
+
+---
+
+## Must fix
+
+### R1. 64-bit division breaks the ARM build, and the calculation overflows
+
+**Where:** core 448–454, `s1d_stats_bus_us()`
+
+**Problem:**
+
+1. Line 453 divides an `unsigned long long`. On ARMv7 the compiler emits a call to `__aeabi_uldivmod`, which the kernel does not export (`arch/arm/kernel/armksyms.c`), so the module can't load or link without `KBUILD_MODPOST_WARN`.
+2. `clocks` is computed in `unsigned long` before the cast. On 32-bit it overflows after about 477 million I²C bytes.
+3. The result is returned as `unsigned long` microseconds, which wraps after about 71.6 minutes of accumulated bus time.
+4. `scl_hz == 0` divides by zero.
+
+**Fix:** the driver doesn't currently call this function, so removing it is also valid. To keep it:
+
+```c
+#ifdef __KERNEL__
+#include <linux/errno.h>
+#include <linux/math64.h>
+#include <linux/string.h>
+#else
+#include <errno.h>
+#include <string.h>
+#endif
+
+#include "s1d13700_core.h"
+
+#ifndef __KERNEL__
+static inline uint64_t div_u64(uint64_t n, uint32_t d)
+{
+	return n / d;
+}
+#endif
+```
+
+```c
+uint64_t s1d_stats_bus_us(const struct s1d_stats *st, unsigned int scl_hz)
+{
+	/* 9 clocks per byte, plus address byte and START/STOP per message */
+	uint64_t clocks = ((uint64_t)st->i2c_bytes + st->i2c_msgs) * 9 +
+			  (uint64_t)st->i2c_msgs * 2;
+
+	return scl_hz ? div_u64(clocks * 1000000u, scl_hz) : 0;
+}
+```
+
+Change the prototype in the header to return `uint64_t` as well.
+
+Add an ARMv7 build to your regular checks, because an x86-64 build can't catch this class of bug.
+
+### R2. The first frame is lost on every enable
+
+**Where:** driver 292–296 (no `helper_private`), 219–235 (`atomic_enable`)
+
+**Problem:** the default `drm_atomic_helper_commit_tail` runs disables → planes → enables. So on enable:
+
+1. `atomic_update` converts the full frame and queues the worker.
+2. `atomic_enable` calls `flush_work`, which sends that frame to the uninitialised controller and consumes the dirty range.
+3. `s1d_panel_init` clears VRAM and the shadow.
+4. Nothing is left dirty. The panel stays blank, and later only damaged rows are painted.
+
+**Fix:** use the variant that runs enables first and skips inactive CRTCs. A modeset already forces full damage through `drm_atomic_helper_check_plane_damage()`, so the frame arrives complete after init.
+
+```c
+static const struct drm_mode_config_helper_funcs s1d_mode_config_helpers = {
+	.atomic_commit_tail = drm_atomic_helper_commit_tail_rpm,
+};
+
+/* in s1d_kms_init() */
+drm->mode_config.helper_private = &s1d_mode_config_helpers;
+```
+
+### R3. A failed I²C write can leave the cursor direction wrong
+
+**Where:** core 95–102 (`set_direction`), 373–405 (`s1d_panel_update`)
+
+**Problem:** `p->vertical` is updated when the command is queued. If the message carrying `CSRDIR_R` is lost, the cache says horizontal while the chip still steps down. The forced full refresh then skips the direction command and writes the frame with the wrong stepping. It returns 0 and clears `force_full`, while the shadow claims the panel is correct.
+
+On the mock, the retry returned success with VRAM wrong.
+
+**Fix:** a full refresh already means the hardware state is in doubt, so resend the direction:
+
+```c
+if (full) {
+	y0 = 0;
+	y1 = p->cfg.height;
+	cmd(p, p->vertical ? S1D_CMD_CSRDIR_D : S1D_CMD_CSRDIR_R);
+}
+```
+
+### R4. Failed updates and failed init are never retried
+
+**Where:** driver 115–142, 219–249, 443–458
+
+**Problem:** the rewrite after a failure only happens when new damage arrives, so an idle screen stays corrupted. A failed `s1d_panel_init` is only logged, and later updates go to an unconfigured controller.
+
+**Fix:** use delayed work with backoff, and let the worker redo init.
+
+```c
+#define RETRY_MIN_MS	100u
+#define RETRY_MAX_MS	5000u
+
+/* in struct s1d_device, replacing struct work_struct flush_work */
+struct delayed_work flush_work;
+bool panel_ready;		/* worker-owned, like panel */
+unsigned int retry_ms;		/* worker-owned */
+```
+
+In `s1d_flush_work()`:
+
+```c
+struct s1d_device *s = container_of(to_delayed_work(work), struct s1d_device,
+				    flush_work);
+```
+
+Replace the update call and its error handling:
+
+```c
+ret = s->panel_ready ? 0 : s1d_panel_init(&s->panel);
+if (!ret) {
+	s->panel_ready = true;
+	ret = s1d_panel_update(&s->panel, s->work_frame, y0, y1);
+}
+
+if (ret) {
+	drm_err_ratelimited(&s->drm, "panel update failed: %d\n", ret);
+	mutex_lock(&s->lock);
+	s->dirty_y0 = 0;
+	s->dirty_y1 = s->cfg.height;
+	mutex_unlock(&s->lock);
+	queue_delayed_work(system_long_wq, &s->flush_work,
+			   msecs_to_jiffies(s->retry_ms));
+	s->retry_ms = min(s->retry_ms * 2, RETRY_MAX_MS);
+} else {
+	s->retry_ms = RETRY_MIN_MS;
+}
+```
+
+Marking the whole frame dirty also copies all of `pending_frame`, so a re-init in the worker has a complete frame to send.
+
+The other call sites:
+
+```c
+/* s1d_plane_atomic_update(): new damage overrides any backoff */
+if (any)
+	mod_delayed_work(system_long_wq, &s->flush_work, 0);
+
+/* s1d_crtc_atomic_enable() */
+cancel_delayed_work_sync(&s->flush_work);
+ret = s1d_panel_init(&s->panel);
+if (ret)
+	drm_err(&s->drm, "panel init failed: %d\n", ret);
+s->panel_ready = !ret;
+s->retry_ms = RETRY_MIN_MS;
+memset(s->work_frame, 0, s->panel.size);
+
+/* s1d_crtc_atomic_disable() */
+cancel_delayed_work_sync(&s->flush_work);
+if (s->panel_ready)
+	s1d_panel_display(&s->panel, false);
+
+/* s1d_probe() */
+INIT_DELAYED_WORK(&s->flush_work, s1d_flush_work);
+s->retry_ms = RETRY_MIN_MS;
+
+/* s1d_remove() and s1d_shutdown() */
+cancel_delayed_work_sync(&s->flush_work);
+```
+
+Use `cancel_delayed_work_sync()` rather than `flush_delayed_work()`, because a retry that re-arms itself could otherwise run concurrently with init. Dropping queued work is safe here since the next enable forces full damage.
+
+### R5. The oscillator wait is in the wrong place when using a crystal
+
+**Where:** core 202–204. **Applies to XCG/XCD clocking; harmless with CLKI.**
+
+**Problem:** Epson's sequence for the internal oscillator is SYSTEM SET, P1, wait at least 3 ms, then SYSTEM SET with its parameters again. The current code waits between the command and P1, so the oscillator only starts after the delay and the remaining parameters are written while it is unstable.
+
+**Fix:**
+
+```c
+/* command + P1 releases power save; the oscillator then needs >= 3 ms */
+cmd(p, S1D_CMD_SYSTEM_SET);
+param(p, 0x10 | 1 << 5);
+tx_flush(p);
+p->ops->delay_ms(p->ctx, 10);
+
+cmd(p, S1D_CMD_SYSTEM_SET);
+param(p, 0x10 | 1 << 5);		/* single panel, no origin offset */
+param(p, 0x80 | 7);			/* FX = 7: required above 1 bpp */
+/* ... remaining parameters unchanged ... */
+```
+
+---
+
+## Should fix
+
+### R6. Enforce the stricter TC/R rule
+
+**Where:** core 130–132
+
+**Problem:** the Hardware Functional Specification requires [TC/R] ≥ [C/R] + 2, while the Technical Manual requires [TC/R] ≥ [C/R] + 4. The default configuration (TC/R 162, stride 60) satisfies both, but the `tcr` module parameter can select values that only meet the weaker rule.
+
+**Fix:** the register holds [TC/R] − 1 and `stride` is [C/R], so:
+
+```c
+/* Technical Manual: [TC/R] >= [C/R] + 4 (HW spec says +2; take the stricter) */
+if (cfg->tcr > 255 || cfg->tcr < stride + 3)
+	return 0;
+```
+
+This limits the stride to 252, so the question of whether the documented C/R limit of 253 is a count or a register value no longer matters.
+
+### R7. Statistics counters wrap on 32-bit
+
+**Where:** driver 368–373, `struct s1d_stats`
+
+**Problem:** `debugfs_create_ulong` requires `unsigned long`, which is 32 bits on the Cortex-A7. At 400 kHz, `i2c_bytes` wraps after about 26.8 hours of continuous transfer.
+
+**Fix:** choose one:
+
+- Keep `unsigned long` and treat the values as wrapping counters, reading them as differences. Document this. It needs no code change.
+- Change the fields to `u64` and use `debugfs_create_u64`. Reads can tear on 32-bit, which is acceptable for debug statistics. This option was not compile-tested.
+
+### R8. Reject framebuffers with a misaligned pitch
+
+**Where:** driver 146–155, core 426
+
+**Problem:** core line 426 casts each line to `const uint32_t *`. DRM's framebuffer checks only enforce a minimum pitch, so userspace can pass a pitch that isn't a multiple of 4. Unaligned access is undefined behaviour in C, and on ARM it can reach the alignment fixup path, depending on the instruction the compiler chooses.
+
+**Fix:** in `s1d_plane_atomic_check()`, before the helper call:
+
+```c
+if (ps->fb && ps->fb->pitches[0] % 4)
+	return -EINVAL;
+```
+
+### R9. Skip the full reset on a plain re-enable
+
+**Where:** driver 229
+
+**Problem:** every enable does a hardware reset and clears VRAM, then repaints. That blocks the commit for about 0.9 s at 400 kHz, even for a simple DPMS cycle where VRAM is still valid.
+
+**Fix:** if `panel_ready` is true and power was never removed, send `DISP_ON` with `s1d_panel_display(&s->panel, true)` instead. Keep the full init for first enable, after a failure and after resume.
+
+---
+
+## Minor
+
+### R10. Stop early after a bus error
+
+**Where:** core 313, 387
+
+After a failed transfer the loops keep running with transfers suppressed, wasting CPU and inflating `writes`, `seeks` and `data_bytes`. `force_full` is already set, so stopping is safe.
+
+```c
+/* scan_emit() */
+while (i < count && !p->err) {
+
+/* s1d_panel_update() */
+while (y < y1 && !p->err) {
+```
+
+### R11. Log `begin_cpu_access` failures
+
+**Where:** driver 173
+
+The damage is silently dropped. At least make it visible:
+
+```c
+if (drm_gem_fb_begin_cpu_access(fb, DMA_FROM_DEVICE)) {
+	drm_err_ratelimited(plane->dev, "CPU access to framebuffer failed\n");
+	return;
+}
+```
+
+### R12. Handle I/O-memory framebuffers
+
+**Where:** driver 181
+
+`shadow->data[0].vaddr` is the wrong union member when an imported dma-buf is mapped as I/O memory (`is_iomem`). Either refuse such buffers with a one-time warning, or copy lines through `iosys_map_memcpy_from()` into a temporary buffer before converting.
+
+### R13. Turn the display off on unload
+
+**Where:** driver 443–450
+
+After `drm_dev_unplug`, `atomic_disable` returns immediately, so unloading leaves the last image on screen. The worker is stopped by then and every other path is guarded by `drm_dev_enter`, so call the core directly:
+
+```c
+drm_dev_unplug(&s->drm);
+cancel_delayed_work_sync(&s->flush_work);
+if (s->panel_ready)
+	s1d_panel_display(&s->panel, false);
+drm_atomic_helper_shutdown(&s->drm);
+```
+
+### R14. Add suspend/resume
+
+The driver has no power management. Add `drm_mode_config_helper_suspend()` and `drm_mode_config_helper_resume()`, and clear `panel_ready` on suspend if the controller can lose power. This is especially relevant if R9 is applied.
+
+### R15. Use a long-running workqueue
+
+**Where:** driver 197
+
+A pass can take about 0.9 s, so `system_long_wq` or a dedicated unbound queue fits better than the system workqueue. The code in R4 already does this.
+
+### R16. Keep the direction cache correct in `s1d_panel_command`
+
+**Where:** core 263–273
+
+Sending `CSRDIR_*` through this function changes the direction without updating `p->vertical` (reproduced on the mock). The driver doesn't use it, so this only affects other callers. Update the cache there, or document that direction commands are not allowed:
+
+```c
+if (c == S1D_CMD_CSRDIR_R || c == S1D_CMD_CSRDIR_D)
+	p->vertical = c == S1D_CMD_CSRDIR_D;
+```
+
+This snippet was not compile-tested. Other direction commands (left, up) would still need handling or rejecting.
+
+---
+
+## Cleanup and verification
+
+### R17. Remove the unused include
+
+**Where:** core 4
+
+`<linux/export.h>` isn't used because nothing is exported. The R1 snippet replaces it with `<linux/math64.h>`.
+
+### R18. Move panel description to DT
+
+**Where:** driver 51–62
+
+Module parameters limit a system to one panel configuration and are a poor fit for a hardware description. Use DT properties for width, height, bpp and TC/R.
+
+Also describe the hardware around the expander, such as a supply and the TCA9539 RESET# pin, if your board doesn't tie it high.
+
+### R19. Confirm the header
+
+These assumptions come from the reconstructed header:
+
+| Item | Expected | Why |
+|---|---|---|
+| `S1D_SEEK_COST` | 6 | Measured: a seek costs 24 I²C bytes, and a data byte costs 4 |
+| `S1D_DIR_COST` | 1 | Net cost of a direction command is 4 I²C bytes, since the following seek saves one A0 update |
+| `struct s1d_stats` fields | `unsigned long` | Required by `debugfs_create_ulong` (see R7) |
+| `S1D_P1_*`, `S1D_P1_CONFIG` | Match the board | Could not be checked |
+| Kernel branch of the header | Includes `<linux/types.h>` | The core uses `uint8_t` and `bool` |
+
+---
+
+## Checked and needing no change
+
+**32-bit:**
+
+- After R1, no 64-bit helper other than the exported `__do_div64` remains in the module.
+- The planner's `unsigned long` costs and all address arithmetic stay well inside 32 bits, because VRAM is 32 KiB.
+- The Cortex-A7 runs little-endian, so reading XRGB8888 as native `uint32_t` is correct.
+
+**Core:**
+
+- The bus sequence holds A0 and data stable around WR#, and no write is split across messages.
+- Planner and emitter agree on gap bridging, and the seek cost matches the wire cost.
+- SL as lines − 1, FX = 7 and HDOT = 0 above 1 bpp match the specification.
+- Pixel conversion is correct at 1, 2 and 4 bpp, including clip alignment.
+
+**Driver:**
+
+- Worker locking and merging of damage are sound.
+- Keeping a persistent `work_frame` makes full rewrites safe.
+- `drm_dev_unplug` before cancelling the work is the right order.
+- The timing comments are accurate: a full 9600-byte frame takes about 866 ms at 400 kHz, and the bus hold for `TX_CAP` is about 23 ms.
+
+## Sources
+
+- [S1D13700F01 Hardware Functional Specification](https://global-origin.epson.com/products_and_drivers/semicon/pdf/id003161.pdf) (first 100,000 of 159,731 characters read; the TC/R inequality symbol was garbled in extraction, so confirm the +2 in the original)
+- [S1D13700 Technical Manual, TC/R section](https://manualslib.com/manual/1453715/Epson-S1d13700.html?page=69)
+- [Epson S1D13700 FAQ](https://global-origin.epson.com/products_and_drivers/semicon/products/display_controllers/faq/faq_s1d13700.html)
+- Linux v6.18: `drivers/gpu/drm/drm_atomic_helper.c`, `drivers/gpu/drm/drm_damage_helper.c`, `drivers/gpu/drm/drm_framebuffer.c`, `arch/arm/kernel/armksyms.c`

+ 3 - 0
driver/Kbuild

@@ -0,0 +1,3 @@
+# The core file is also built into the userspace tools.
+obj-m := s1d13700-tca.o
+s1d13700-tca-y := s1d13700_drm.o s1d13700_core.o

+ 500 - 0
driver/s1d13700_core.c

@@ -0,0 +1,500 @@
+// SPDX-License-Identifier: GPL-2.0-only
+#ifdef __KERNEL__
+#include <linux/errno.h>
+#include <linux/string.h>
+#else
+#include <errno.h>
+#include <string.h>
+#endif
+
+#include "s1d13700_core.h"
+
+/* Bytes one LCD write can need: A0 settle pair + WR low pair + WR high pair */
+#define MAX_WRITE_BYTES		6u
+
+/* ---- Transport --------------------------------------------------------- */
+
+static void tx_reset(struct s1d_panel *p)
+{
+	p->tx[0] = TCA_REG_OUTPUT0;
+	p->tx_len = 1;
+}
+
+static void tx_flush(struct s1d_panel *p)
+{
+	int ret;
+
+	if (p->tx_len > 1 && !p->err) {
+		ret = p->ops->xfer(p->ctx, p->tx, p->tx_len);
+		if (ret) {
+			p->err = ret;
+			p->force_full = true;
+		} else {
+			p->p1_sent = p->p1;
+			p->stats.i2c_msgs++;
+			p->stats.i2c_bytes += p->tx_len;
+		}
+	}
+	tx_reset(p);
+}
+
+static void put_pair(struct s1d_panel *p, uint8_t data, uint8_t ctrl)
+{
+	p->tx[p->tx_len++] = data;
+	p->tx[p->tx_len++] = ctrl;
+	p->p1 = ctrl;
+}
+
+/*
+ * One LCD bus cycle. A0 needs setup time before the WR# edge, and both are in
+ * the same port, so an A0 change gets its own update with WR# still high.
+ * A write is never split across messages, so WR# is not left low on a bus
+ * release. The data byte is presented before WR# falls and repeated while it
+ * is low, because the register pair toggle makes that slot unavoidable.
+ */
+static void bus_write(struct s1d_panel *p, bool a0, uint8_t data)
+{
+	uint8_t ctrl = p->p1 | S1D_P1_WR;
+
+	ctrl = a0 ? (ctrl | S1D_P1_A0) : (ctrl & ~S1D_P1_A0);
+
+	if (p->tx_len + MAX_WRITE_BYTES > p->tx_cap)
+		tx_flush(p);
+
+	if (ctrl != p->p1)
+		put_pair(p, data, ctrl);
+	put_pair(p, data, ctrl & ~S1D_P1_WR);
+	put_pair(p, data, ctrl);
+	p->stats.writes++;
+}
+
+static void cmd(struct s1d_panel *p, uint8_t c)
+{
+	bus_write(p, true, c);
+}
+
+static void param(struct s1d_panel *p, uint8_t v)
+{
+	bus_write(p, false, v);
+}
+
+static void param16(struct s1d_panel *p, unsigned int v)
+{
+	param(p, v & 0xff);
+	param(p, v >> 8);
+}
+
+static void seek(struct s1d_panel *p, unsigned int addr)
+{
+	cmd(p, S1D_CMD_CSRW);
+	param16(p, addr);
+	cmd(p, S1D_CMD_MWRITE);
+	p->stats.seeks++;
+}
+
+static void set_direction(struct s1d_panel *p, bool vertical)
+{
+	if (p->vertical == vertical)
+		return;
+	cmd(p, vertical ? S1D_CMD_CSRDIR_D : S1D_CMD_CSRDIR_R);
+	p->vertical = vertical;
+	p->stats.dir_changes++;
+}
+
+static int take_error(struct s1d_panel *p)
+{
+	int err = p->err;
+
+	/*
+	 * Queued writes that were never sent moved p1 ahead of the pins. Fall
+	 * back to what the expander last accepted, so the next A0 change still
+	 * gets its own update before WR# falls.
+	 */
+	if (err)
+		p->p1 = p->p1_sent;
+	p->err = 0;
+	return err;
+}
+
+/* ---- Setup and init ----------------------------------------------------- */
+
+unsigned int s1d_frame_size(const struct s1d_config *cfg)
+{
+	unsigned int ppb, stride;
+
+	if (cfg->bpp != 1 && cfg->bpp != 2 && cfg->bpp != 4)
+		return 0;
+	ppb = 8 / cfg->bpp;
+	if (!cfg->width || !cfg->height || cfg->width % ppb)
+		return 0;
+	if (cfg->height > 256)
+		return 0;
+
+	stride = cfg->width / ppb;
+	/* C/R register is 8 bits and capped at 253; the whole frame must fit */
+	if (stride - 1 > 253 || stride * cfg->height > S1D_VRAM_SIZE)
+		return 0;
+	/*
+	 * The register holds [TC/R] - 1. Technical Manual: [TC/R] >= [C/R] + 4
+	 * (the Hardware Functional Specification says + 2; take the stricter).
+	 */
+	if (cfg->tcr > 255 || cfg->tcr < stride + 3)
+		return 0;
+	return stride * cfg->height;
+}
+
+int s1d_panel_setup(struct s1d_panel *p, const struct s1d_config *cfg,
+		    const struct s1d_ops *ops, void *ctx,
+		    uint8_t *shadow, uint8_t *tx, size_t tx_cap)
+{
+	unsigned int size = s1d_frame_size(cfg);
+
+	if (!size || tx_cap < MAX_WRITE_BYTES + 1)
+		return -EINVAL;
+
+	memset(p, 0, sizeof(*p));
+	p->cfg = *cfg;
+	p->size = size;
+	p->stride = size / cfg->height;
+	p->ops = ops;
+	p->ctx = ctx;
+	p->shadow = shadow;
+	p->tx = tx;
+	p->tx_cap = tx_cap;
+	p->force_full = true;
+	tx_reset(p);
+	return 0;
+}
+
+static void write_regs(struct s1d_panel *p, uint8_t reg, uint8_t v0, uint8_t v1)
+{
+	p->tx[0] = reg;
+	p->tx[1] = v0;
+	p->tx[2] = v1;
+	p->tx_len = 3;
+	tx_flush(p);
+}
+
+static void clear_vram(struct s1d_panel *p)
+{
+	unsigned int i;
+
+	seek(p, 0);
+	for (i = 0; i < p->size; i++)
+		param(p, 0);
+	memset(p->shadow, 0, p->size);
+}
+
+int s1d_panel_init(struct s1d_panel *p)
+{
+	const struct s1d_config *c = &p->cfg;
+	unsigned int bpp_code = c->bpp == 4 ? 2 : c->bpp == 2 ? 1 : 0;
+
+	p->err = 0;
+	p->vertical = false;
+
+	/*
+	 * Output latches first, then direction, so no control line glitches.
+	 * RES# stays low; WR#, RD#, A0 and CS# idle high.
+	 */
+	p->p1 = S1D_P1_WR | S1D_P1_RD | S1D_P1_A0 | S1D_P1_CS |
+		(p->backlight ? S1D_P1_BL : 0);
+	write_regs(p, TCA_REG_OUTPUT0, 0x00, p->p1);
+	write_regs(p, TCA_REG_POLARITY0, 0x00, 0x00);
+	write_regs(p, TCA_REG_CONFIG0, 0x00, S1D_P1_CONFIG);
+	p->ops->delay_ms(p->ctx, 20);
+
+	/* out of reset and selected for good: WR# frames every cycle */
+	p->p1 |= S1D_P1_RES;
+	write_regs(p, TCA_REG_OUTPUT0, 0x00, p->p1);
+	p->p1 &= ~S1D_P1_CS;
+	write_regs(p, TCA_REG_OUTPUT0, 0x00, p->p1);
+	p->ops->delay_ms(p->ctx, 20);
+	if (p->err)
+		return take_error(p);
+
+	/*
+	 * Command + P1 releases power save; a crystal oscillator then needs
+	 * at least 3 ms before SYSTEM SET is sent again in full. Harmless
+	 * with an external clock on CLKI.
+	 */
+	cmd(p, S1D_CMD_SYSTEM_SET);
+	param(p, 0x10 | 1 << 5);
+	tx_flush(p);
+	p->ops->delay_ms(p->ctx, 10);
+
+	cmd(p, S1D_CMD_SYSTEM_SET);
+	param(p, 0x10 | 1 << 5);		/* single panel, no origin offset */
+	param(p, 0x80 | 7);			/* FX = 7: required above 1 bpp */
+	param(p, 7);				/* FY */
+	param(p, p->stride - 1);		/* C/R */
+	param(p, c->tcr);			/* TC/R */
+	param(p, c->height - 1);		/* L/F */
+	param16(p, p->stride);			/* AP */
+
+	/*
+	 * One graphics block. The second layer is blanked below but still gets
+	 * a sane address. SL uses the same lines-1 value as L/F.
+	 */
+	cmd(p, S1D_CMD_SCROLL);
+	param16(p, 0);				/* SAD1 */
+	param(p, c->height - 1);		/* SL1 */
+	param16(p, p->size);			/* SAD2 */
+	param(p, c->height - 1);		/* SL2 */
+	param16(p, 0);				/* SAD3 */
+	param16(p, 0);				/* SAD4 */
+
+	cmd(p, S1D_CMD_CSRFORM);
+	param(p, 0x04);
+	param(p, 0x80 | 7);			/* CM must be 1 in graphics mode */
+
+	cmd(p, S1D_CMD_CGRAM_ADR);
+	param16(p, 0x7000);
+
+	cmd(p, S1D_CMD_CSRDIR_R);
+
+	cmd(p, S1D_CMD_HDOT_SCR);
+	param(p, 0);				/* must be 0 above 1 bpp */
+
+	cmd(p, S1D_CMD_OVLAY);
+	param(p, 0x0c);				/* both layers graphics, OR */
+
+	cmd(p, S1D_CMD_GRAYSCALE);
+	param(p, bpp_code);
+
+	/* clear before showing, so no power-on garbage is ever visible */
+	clear_vram(p);
+
+	cmd(p, S1D_CMD_DISP_ON);
+	param(p, 0x04);				/* SAD1 on, others and cursor off */
+
+	tx_flush(p);
+	if (!p->err)
+		p->force_full = false;
+	return take_error(p);
+}
+
+int s1d_panel_display(struct s1d_panel *p, bool on)
+{
+	cmd(p, on ? S1D_CMD_DISP_ON : S1D_CMD_DISP_OFF);
+	param(p, 0x04);
+	tx_flush(p);
+	return take_error(p);
+}
+
+int s1d_panel_backlight(struct s1d_panel *p, bool on)
+{
+	p->backlight = on;
+	/* nothing accepted yet: the pins are still inputs, init sets the level */
+	if (!p->p1_sent)
+		return 0;
+	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 */
+	write_regs(p, TCA_REG_OUTPUT0, 0x00, p->p1);
+	return take_error(p);
+}
+
+int s1d_panel_command(struct s1d_panel *p, uint8_t c,
+		      const uint8_t *params, size_t nparams)
+{
+	size_t i;
+
+	/* p->vertical only models right and down */
+	if (c == S1D_CMD_CSRDIR_L || c == S1D_CMD_CSRDIR_U)
+		return -EINVAL;
+	if (c == S1D_CMD_CSRDIR_R || c == S1D_CMD_CSRDIR_D)
+		p->vertical = c == S1D_CMD_CSRDIR_D;
+
+	cmd(p, c);
+	for (i = 0; i < nparams; i++)
+		param(p, params[i]);
+	tx_flush(p);
+	return take_error(p);
+}
+
+/* ---- Update planner ----------------------------------------------------- */
+
+static bool differs(const struct s1d_panel *p, const uint8_t *next, unsigned int a)
+{
+	return p->force_full || next[a] != p->shadow[a];
+}
+
+/*
+ * Walk a line of display memory (horizontally or down one column). Changed
+ * bytes are grouped into runs; an unchanged gap no longer than a seek is
+ * rewritten rather than seeked over.
+ */
+static unsigned long scan_cost(const struct s1d_panel *p, const uint8_t *next,
+			       unsigned int start, unsigned int step,
+			       unsigned int count)
+{
+	unsigned long cost = 0;
+	unsigned int i, last = 0;
+	bool open = false;
+
+	for (i = 0; i < count; i++) {
+		if (!differs(p, next, start + i * step))
+			continue;
+		if (open && i - last - 1 <= S1D_SEEK_COST)
+			cost += i - last;
+		else
+			cost += S1D_SEEK_COST + 1;
+		last = i;
+		open = true;
+	}
+	return cost;
+}
+
+static void scan_emit(struct s1d_panel *p, const uint8_t *next,
+		      unsigned int start, unsigned int step, unsigned int count)
+{
+	unsigned int i = 0;
+
+	/* after a bus error nothing more is sent, and force_full is set */
+	while (i < count && !p->err) {
+		unsigned int run_end, gap_scan, k;
+
+		if (!differs(p, next, start + i * step)) {
+			i++;
+			continue;
+		}
+
+		/* extend the run while the next change is within reach */
+		run_end = i;
+		gap_scan = i + 1;
+		while (gap_scan < count && gap_scan - run_end - 1 <= S1D_SEEK_COST) {
+			if (differs(p, next, start + gap_scan * step))
+				run_end = gap_scan;
+			gap_scan++;
+		}
+
+		seek(p, start + i * step);
+		for (k = i; k <= run_end && !p->err; k++) {
+			unsigned int a = start + k * step;
+
+			param(p, next[a]);
+			p->shadow[a] = next[a];
+			p->stats.data_bytes++;
+		}
+		i = run_end + 1;
+	}
+}
+
+/* Rows [y0, y1) all contain changes: pick the cheaper write direction. */
+static void update_band(struct s1d_panel *p, const uint8_t *next,
+			unsigned int y0, unsigned int y1)
+{
+	unsigned int rows = y1 - y0, x;
+	unsigned long horiz, vert = 0;
+
+	/* memory is linear, so full-width runs continue across row ends */
+	horiz = scan_cost(p, next, y0 * p->stride, 1, rows * p->stride);
+	for (x = 0; x < p->stride; x++)
+		vert += scan_cost(p, next, y0 * p->stride + x, p->stride, rows);
+
+	horiz += p->vertical ? S1D_DIR_COST : 0;
+	vert += p->vertical ? 0 : S1D_DIR_COST;
+
+	if (horiz <= vert) {
+		set_direction(p, false);
+		scan_emit(p, next, y0 * p->stride, 1, rows * p->stride);
+	} else {
+		set_direction(p, true);
+		for (x = 0; x < p->stride; x++)
+			scan_emit(p, next, y0 * p->stride + x, p->stride, rows);
+	}
+}
+
+static bool row_differs(const struct s1d_panel *p, const uint8_t *next, unsigned int y)
+{
+	return p->force_full ||
+	       memcmp(next + y * p->stride, p->shadow + y * p->stride, p->stride);
+}
+
+int s1d_panel_update(struct s1d_panel *p, const uint8_t *next,
+		     unsigned int y0, unsigned int y1)
+{
+	bool full = p->force_full;
+	unsigned int y;
+
+	if (full) {
+		/* the hardware state is in doubt, including the cursor direction */
+		y0 = 0;
+		y1 = p->cfg.height;
+		cmd(p, p->vertical ? S1D_CMD_CSRDIR_D : S1D_CMD_CSRDIR_R);
+	}
+	if (y1 > p->cfg.height)
+		y1 = p->cfg.height;
+
+	y = y0;
+	while (y < y1 && !p->err) {
+		unsigned int band_end;
+
+		if (!row_differs(p, next, y)) {
+			y++;
+			continue;
+		}
+		band_end = y + 1;
+		while (band_end < y1 && row_differs(p, next, band_end))
+			band_end++;
+		update_band(p, next, y, band_end);
+		y = band_end;
+	}
+
+	tx_flush(p);
+	if (full && !p->err)
+		p->force_full = false;
+	return take_error(p);
+}
+
+/* ---- Pixel conversion --------------------------------------------------- */
+
+void s1d_convert_xrgb8888(const struct s1d_config *cfg, const void *src,
+			  unsigned int pitch, uint8_t *dst,
+			  unsigned int x0, unsigned int y0,
+			  unsigned int x1, unsigned int y1)
+{
+	unsigned int bpp = cfg->bpp, ppb = 8 / bpp;
+	unsigned int stride = cfg->width / ppb;
+	unsigned int x, y;
+
+	x0 -= x0 % ppb;
+	x1 = (x1 + ppb - 1) / ppb * ppb;
+	if (x1 > cfg->width)
+		x1 = cfg->width;
+	if (y1 > cfg->height)
+		y1 = cfg->height;
+
+	for (y = y0; y < y1; y++) {
+		const uint32_t *line = (const uint32_t *)
+			((const uint8_t *)src + (size_t)y * pitch);
+		uint8_t *out = dst + y * stride + x0 / ppb;
+
+		for (x = x0; x < x1; x += ppb) {
+			uint8_t byte = 0;
+			unsigned int i;
+
+			for (i = 0; i < ppb; i++) {
+				uint32_t c = line[x + i];
+				unsigned int luma = (((c >> 16) & 0xff) * 77 +
+						     ((c >> 8) & 0xff) * 150 +
+						     (c & 0xff) * 29) >> 8;
+
+				byte = (uint8_t)(byte << bpp) |
+				       ((255 - luma) >> (8 - bpp));
+			}
+			*out++ = byte;
+		}
+	}
+}
+
+#ifndef __KERNEL__	/* the driver has no use for it, so no div_u64() needed */
+uint64_t s1d_stats_bus_us(const struct s1d_stats *st, unsigned int scl_hz)
+{
+	/* 9 clocks per byte, plus address byte and START/STOP per message */
+	uint64_t clocks = ((uint64_t)st->i2c_bytes + st->i2c_msgs) * 9 +
+			  (uint64_t)st->i2c_msgs * 2;
+
+	return scl_hz ? clocks * 1000000u / scl_hz : 0;
+}
+#endif

+ 169 - 0
driver/s1d13700_core.h

@@ -0,0 +1,169 @@
+/* SPDX-License-Identifier: GPL-2.0-only */
+/*
+ * S1D13700 behind a TCA9539: hardware-independent panel core.
+ *
+ * Shared by the DRM driver, the i2c-dev frontend, the GTK simulator and the
+ * tests. It owns everything between "new frame in native format" and "bytes
+ * for one I2C write", and has no kernel or libc dependency beyond memcmp().
+ *
+ * Wire format: every write starts with the Output Port 0 command byte, then
+ * alternates P0 (LCD data) and P1 (LCD control), relying on the TCA9539
+ * staying within the addressed register pair. Each transfer therefore holds
+ * an odd number of bytes and always restarts at P0.
+ */
+#ifndef S1D13700_CORE_H
+#define S1D13700_CORE_H
+
+#ifdef __KERNEL__
+#include <linux/types.h>
+#else
+#include <stdbool.h>
+#include <stddef.h>
+#include <stdint.h>
+#endif
+
+/* TCA9539 command bytes */
+#define TCA_REG_OUTPUT0		0x02
+#define TCA_REG_POLARITY0	0x04
+#define TCA_REG_CONFIG0		0x06
+
+/* U1 port 1: LCD control lines (module pin names in brackets) */
+#define S1D_P1_BL		0x01	/* backlight enable, active high */
+#define S1D_P1_RES		0x02	/* RES# [RST] */
+#define S1D_P1_A0		0x04	/* [A15]: 1 = command, 0 = parameter/data */
+#define S1D_P1_WR		0x08	/* WR# [WE] */
+#define S1D_P1_RD		0x10	/* RD# [RE] */
+#define S1D_P1_CS		0x20	/* CS# [CS0] */
+#define S1D_P1_CONFIG		0xc0	/* P1.6-7 unused: stay inputs */
+
+/* S1D13700 indirect-mode commands */
+#define S1D_CMD_SYSTEM_SET	0x40
+#define S1D_CMD_MWRITE		0x42
+#define S1D_CMD_MREAD		0x43
+#define S1D_CMD_SCROLL		0x44
+#define S1D_CMD_CSRW		0x46
+#define S1D_CMD_CSRR		0x47
+#define S1D_CMD_CSRDIR_R	0x4c
+#define S1D_CMD_CSRDIR_L	0x4d
+#define S1D_CMD_CSRDIR_U	0x4e
+#define S1D_CMD_CSRDIR_D	0x4f
+#define S1D_CMD_SLEEP		0x53
+#define S1D_CMD_DISP_OFF	0x58
+#define S1D_CMD_DISP_ON		0x59
+#define S1D_CMD_HDOT_SCR	0x5a
+#define S1D_CMD_OVLAY		0x5b
+#define S1D_CMD_CGRAM_ADR	0x5c
+#define S1D_CMD_CSRFORM		0x5d
+#define S1D_CMD_GRAYSCALE	0x60
+
+#define S1D_VRAM_SIZE		32768u
+
+/*
+ * Rewriting an unchanged gap costs one LCD write per byte; seeking costs
+ * CSRW + 2 parameters + MWRITE (4 writes, 16 I2C bytes) plus four A0
+ * transitions of one extra P0/P1 pair each (8 I2C bytes). That is 24 I2C
+ * bytes, the same as 6 data bytes.
+ */
+#define S1D_SEEK_COST		6u
+#define S1D_DIR_COST		1u
+
+struct s1d_config {
+	unsigned int width;	/* pixels, multiple of the pixels in one byte */
+	unsigned int height;
+	unsigned int bpp;	/* 1, 2 or 4 */
+	unsigned int tcr;	/* SYSTEM SET TC/R: tune for frame rate */
+};
+
+struct s1d_ops {
+	/* buf[0] is the TCA9539 command byte; the transport adds the address */
+	int (*xfer)(void *ctx, const uint8_t *buf, size_t len);
+	void (*delay_ms)(void *ctx, unsigned int ms);
+};
+
+/*
+ * Wrapping counters: unsigned long for debugfs_create_ulong(), so 32 bits on
+ * the target, where i2c_bytes wraps after about a day of continuous traffic
+ * at 400 kHz. Read them as differences between two samples.
+ */
+struct s1d_stats {
+	unsigned long writes;		/* LCD bus cycles */
+	unsigned long data_bytes;	/* of which display memory */
+	unsigned long seeks;
+	unsigned long dir_changes;
+	unsigned long i2c_msgs;
+	unsigned long i2c_bytes;	/* payload, including command bytes */
+};
+
+struct s1d_panel {
+	struct s1d_config cfg;
+	unsigned int stride;
+	unsigned int size;
+
+	const struct s1d_ops *ops;
+	void *ctx;
+
+	uint8_t *shadow;	/* what the panel holds; cfg-sized */
+	uint8_t *tx;
+	size_t tx_cap;
+	size_t tx_len;
+
+	uint8_t p1;		/* last control byte queued; WR high between writes */
+	uint8_t p1_sent;	/* last control byte the expander acknowledged */
+	bool vertical;		/* cursor direction currently programmed */
+	bool backlight;		/* S1D_P1_BL level to keep driving */
+	bool force_full;	/* shadow cannot be trusted: rewrite everything */
+	int err;		/* first transport error of the current operation */
+
+	struct s1d_stats stats;
+};
+
+/* Native framebuffer size for a configuration; 0 if it is not valid. */
+unsigned int s1d_frame_size(const struct s1d_config *cfg);
+
+/*
+ * shadow must hold s1d_frame_size() bytes; tx is the transfer buffer and must
+ * be DMA-safe in the kernel. tx_cap limits one I2C message (at least 7).
+ */
+int s1d_panel_setup(struct s1d_panel *p, const struct s1d_config *cfg,
+		    const struct s1d_ops *ops, void *ctx,
+		    uint8_t *shadow, uint8_t *tx, size_t tx_cap);
+
+/* Program the expander, reset and configure the controller, clear VRAM. */
+int s1d_panel_init(struct s1d_panel *p);
+
+/*
+ * Bring rows [y0, y1) of the panel up to date with the native frame "next",
+ * sending only what differs from the shadow. After a transport error the next
+ * call rewrites the whole frame, so "next" must always be a complete frame.
+ */
+int s1d_panel_update(struct s1d_panel *p, const uint8_t *next,
+		     unsigned int y0, unsigned int y1);
+
+int s1d_panel_display(struct s1d_panel *p, bool on);
+
+/* Backlight pin on the expander. Applied at once if the panel is set up. */
+int s1d_panel_backlight(struct s1d_panel *p, bool on);
+
+/*
+ * Program a raw controller command, for bring-up experiments. CSRDIR_L and
+ * CSRDIR_U are refused, since the update planner only knows right and down.
+ */
+int s1d_panel_command(struct s1d_panel *p, uint8_t cmd,
+		      const uint8_t *params, size_t nparams);
+
+/*
+ * Convert XRGB8888 pixels to the native format: white is level 0 (pixel off),
+ * black the highest level, leftmost pixel in the most significant bits. The
+ * rectangle is widened to whole bytes; src must cover those pixels.
+ */
+void s1d_convert_xrgb8888(const struct s1d_config *cfg, const void *src,
+			  unsigned int pitch, uint8_t *dst,
+			  unsigned int x0, unsigned int y0,
+			  unsigned int x1, unsigned int y1);
+
+#ifndef __KERNEL__
+/* Approximate bus time in microseconds at the given SCL rate. */
+uint64_t s1d_stats_bus_us(const struct s1d_stats *st, unsigned int scl_hz);
+#endif
+
+#endif /* S1D13700_CORE_H */

+ 570 - 0
driver/s1d13700_drm.c

@@ -0,0 +1,570 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/*
+ * DRM driver for an S1D13700 LCD controller wired to a TCA9539 I2C expander.
+ *
+ * The expander is an ordinary I2C client of this driver rather than a
+ * gpiochip: the display traffic needs one continuous write alternating both
+ * ports, which the GPIO API cannot express.
+ *
+ * A full frame takes most of a second on the bus, so atomic_update only
+ * converts the damage into a pending frame; a worker sends it, and damage
+ * arriving meanwhile is merged into the next pass. A failed pass is retried
+ * with backoff, redoing the controller init first if that is what failed.
+ *
+ * Needs a recent kernel (written against 6.18).
+ */
+#include <linux/debugfs.h>
+#include <linux/delay.h>
+#include <linux/i2c.h>
+#include <linux/module.h>
+#include <linux/mutex.h>
+#include <linux/of.h>
+#include <linux/pm.h>
+#include <linux/slab.h>
+#include <linux/workqueue.h>
+
+#include <drm/clients/drm_client_setup.h>
+#include <drm/drm_atomic.h>
+#include <drm/drm_atomic_helper.h>
+#include <drm/drm_connector.h>
+#include <drm/drm_crtc.h>
+#include <drm/drm_crtc_helper.h>
+#include <drm/drm_damage_helper.h>
+#include <drm/drm_drv.h>
+#include <drm/drm_encoder.h>
+#include <drm/drm_fbdev_shmem.h>
+#include <drm/drm_fourcc.h>
+#include <drm/drm_framebuffer.h>
+#include <drm/drm_gem_atomic_helper.h>
+#include <drm/drm_gem_framebuffer_helper.h>
+#include <drm/drm_gem_shmem_helper.h>
+#include <drm/drm_managed.h>
+#include <drm/drm_modes.h>
+#include <drm/drm_modeset_helper.h>
+#include <drm/drm_modeset_helper_vtables.h>
+#include <drm/drm_plane.h>
+#include <drm/drm_print.h>
+#include <drm/drm_probe_helper.h>
+
+#include "s1d13700_core.h"
+
+#define DRIVER_NAME	"s1d13700-tca"
+/* Bus held for about 23 ms at 400 kHz, so other devices on it are not starved */
+#define TX_CAP		1025u
+#define RETRY_MIN_MS	100u
+#define RETRY_MAX_MS	5000u
+
+static unsigned int width = 240;
+module_param(width, uint, 0444);
+MODULE_PARM_DESC(width, "Panel width in pixels");
+static unsigned int height = 160;
+module_param(height, uint, 0444);
+MODULE_PARM_DESC(height, "Panel height in pixels");
+static unsigned int bpp = 2;
+module_param(bpp, uint, 0444);
+MODULE_PARM_DESC(bpp, "Bits per pixel: 1, 2 or 4");
+static unsigned int tcr = 162;
+module_param(tcr, uint, 0444);
+MODULE_PARM_DESC(tcr, "SYSTEM SET TC/R: sets the frame rate");
+
+struct s1d_device {
+	struct drm_device drm;
+	struct drm_plane plane;
+	struct drm_crtc crtc;
+	struct drm_encoder encoder;
+	struct drm_connector connector;
+	struct drm_display_mode mode;
+
+	struct i2c_client *client;
+	struct s1d_config cfg;
+
+	/* touched only by the worker, or with the worker stopped */
+	struct s1d_panel panel;
+	u8 *work_frame;
+	bool panel_ready;	/* controller initialised and still powered */
+	unsigned int retry_ms;
+
+	struct delayed_work flush_work;
+
+	struct mutex lock;	/* protects pending_frame, dirty_y0, dirty_y1 */
+	u8 *pending_frame;
+	unsigned int dirty_y0, dirty_y1;
+};
+
+static struct s1d_device *to_s1d(struct drm_device *drm)
+{
+	return container_of(drm, struct s1d_device, drm);
+}
+
+/* ---- transport ---------------------------------------------------------- */
+
+static int s1d_xfer(void *ctx, const u8 *buf, size_t len)
+{
+	struct s1d_device *s = ctx;
+	int ret = i2c_master_send(s->client, buf, len);
+
+	if (ret < 0)
+		return ret;
+	return ret == len ? 0 : -EIO;
+}
+
+static void s1d_delay_ms(void *ctx, unsigned int ms)
+{
+	msleep(ms);
+}
+
+static const struct s1d_ops s1d_panel_ops = {
+	.xfer = s1d_xfer,
+	.delay_ms = s1d_delay_ms,
+};
+
+/* ---- worker ------------------------------------------------------------- */
+
+static void s1d_flush_work(struct work_struct *work)
+{
+	struct s1d_device *s = container_of(to_delayed_work(work), struct s1d_device,
+					    flush_work);
+	unsigned int stride = s->panel.stride, y0, y1;
+	int idx, ret;
+
+	mutex_lock(&s->lock);
+	y0 = s->dirty_y0;
+	y1 = s->dirty_y1;
+	s->dirty_y0 = s->cfg.height;
+	s->dirty_y1 = 0;
+	if (y1 > y0)
+		memcpy(s->work_frame + y0 * stride, s->pending_frame + y0 * stride,
+		       (y1 - y0) * stride);
+	mutex_unlock(&s->lock);
+
+	if (y1 <= y0)
+		return;
+	if (!drm_dev_enter(&s->drm, &idx))
+		return;
+
+	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 (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);
+		queue_delayed_work(system_long_wq, &s->flush_work,
+				   msecs_to_jiffies(s->retry_ms));
+		s->retry_ms = min(s->retry_ms * 2, RETRY_MAX_MS);
+	} else {
+		s->retry_ms = RETRY_MIN_MS;
+	}
+
+	drm_dev_exit(idx);
+}
+
+/* ---- plane -------------------------------------------------------------- */
+
+static int s1d_plane_atomic_check(struct drm_plane *plane, struct drm_atomic_state *state)
+{
+	struct drm_plane_state *ps = drm_atomic_get_new_plane_state(state, plane);
+	struct drm_crtc_state *cs = NULL;
+
+	/* lines are read as u32 */
+	if (ps->fb && ps->fb->pitches[0] % 4)
+		return -EINVAL;
+
+	if (ps->crtc)
+		cs = drm_atomic_get_new_crtc_state(state, ps->crtc);
+	return drm_atomic_helper_check_plane_state(ps, cs, DRM_PLANE_NO_SCALING,
+						   DRM_PLANE_NO_SCALING, false, false);
+}
+
+static void s1d_plane_atomic_update(struct drm_plane *plane, struct drm_atomic_state *state)
+{
+	struct drm_plane_state *old = drm_atomic_get_old_plane_state(state, plane);
+	struct drm_plane_state *ps = drm_atomic_get_new_plane_state(state, plane);
+	struct drm_shadow_plane_state *shadow = to_drm_shadow_plane_state(ps);
+	struct s1d_device *s = to_s1d(plane->dev);
+	struct drm_framebuffer *fb = ps->fb;
+	struct drm_atomic_helper_damage_iter iter;
+	struct drm_rect clip;
+	unsigned int ox, oy;
+	const u8 *base;
+	bool any = false;
+	int idx;
+
+	if (!fb || !ps->visible)
+		return;
+	if (shadow->data[0].is_iomem) {
+		drm_warn_once(plane->dev, "framebuffers in I/O memory are not supported\n");
+		return;
+	}
+	if (drm_gem_fb_begin_cpu_access(fb, DMA_FROM_DEVICE)) {
+		drm_err_ratelimited(plane->dev, "CPU access to framebuffer failed\n");
+		return;
+	}
+	if (!drm_dev_enter(plane->dev, &idx))
+		goto out_cpu;
+
+	/* the panel origin is the plane's source origin in the framebuffer */
+	ox = ps->src.x1 >> 16;
+	oy = ps->src.y1 >> 16;
+	base = (const u8 *)shadow->data[0].vaddr + oy * fb->pitches[0] + ox * 4;
+
+	mutex_lock(&s->lock);
+	drm_atomic_helper_damage_iter_init(&iter, old, ps);
+	drm_atomic_for_each_plane_damage(&iter, &clip) {
+		unsigned int y0 = clip.y1 - oy, y1 = clip.y2 - oy;
+
+		s1d_convert_xrgb8888(&s->cfg, base, fb->pitches[0], s->pending_frame,
+				     clip.x1 - ox, y0, clip.x2 - ox, y1);
+		s->dirty_y0 = min(s->dirty_y0, y0);
+		s->dirty_y1 = max(s->dirty_y1, y1);
+		any = true;
+	}
+	mutex_unlock(&s->lock);
+
+	/* new damage overrides any retry backoff */
+	if (any)
+		mod_delayed_work(system_long_wq, &s->flush_work, 0);
+
+	drm_dev_exit(idx);
+out_cpu:
+	drm_gem_fb_end_cpu_access(fb, DMA_FROM_DEVICE);
+}
+
+static const struct drm_plane_helper_funcs s1d_plane_helper_funcs = {
+	DRM_GEM_SHADOW_PLANE_HELPER_FUNCS,
+	.atomic_check = s1d_plane_atomic_check,
+	.atomic_update = s1d_plane_atomic_update,
+};
+
+static const struct drm_plane_funcs s1d_plane_funcs = {
+	.update_plane = drm_atomic_helper_update_plane,
+	.disable_plane = drm_atomic_helper_disable_plane,
+	.destroy = drm_plane_cleanup,
+	DRM_GEM_SHADOW_PLANE_FUNCS,
+};
+
+/* ---- CRTC --------------------------------------------------------------- */
+
+static void s1d_crtc_atomic_enable(struct drm_crtc *crtc, struct drm_atomic_state *state)
+{
+	struct s1d_device *s = to_s1d(crtc->dev);
+	int idx, ret;
+
+	if (!drm_dev_enter(crtc->dev, &idx))
+		return;
+
+	/*
+	 * Enables run before plane updates (commit_tail_rpm), so this frame's
+	 * damage is not queued yet; a dropped retry is covered by the full
+	 * damage a modeset brings.
+	 */
+	cancel_delayed_work_sync(&s->flush_work);
+	s->retry_ms = RETRY_MIN_MS;
+
+	/* VRAM survives a plain disable, so only the display needs turning on */
+	if (s->panel_ready && !s1d_panel_display(&s->panel, true))
+		goto out;
+
+	/* VRAM is cleared by init, so the shadow and work frame start at zero */
+	ret = s1d_panel_init(&s->panel);
+	if (ret)
+		drm_err(&s->drm, "panel init failed: %d\n", ret);
+	s->panel_ready = !ret;
+	memset(s->work_frame, 0, s->panel.size);
+out:
+	drm_dev_exit(idx);
+}
+
+static void s1d_crtc_atomic_disable(struct drm_crtc *crtc, struct drm_atomic_state *state)
+{
+	struct s1d_device *s = to_s1d(crtc->dev);
+	int idx;
+
+	if (!drm_dev_enter(crtc->dev, &idx))
+		return;
+
+	cancel_delayed_work_sync(&s->flush_work);
+	if (s->panel_ready)
+		s1d_panel_display(&s->panel, false);
+
+	drm_dev_exit(idx);
+}
+
+static const struct drm_crtc_helper_funcs s1d_crtc_helper_funcs = {
+	.atomic_check = drm_crtc_helper_atomic_check,
+	.atomic_enable = s1d_crtc_atomic_enable,
+	.atomic_disable = s1d_crtc_atomic_disable,
+};
+
+static const struct drm_crtc_funcs s1d_crtc_funcs = {
+	.reset = drm_atomic_helper_crtc_reset,
+	.destroy = drm_crtc_cleanup,
+	.set_config = drm_atomic_helper_set_config,
+	.page_flip = drm_atomic_helper_page_flip,
+	.atomic_duplicate_state = drm_atomic_helper_crtc_duplicate_state,
+	.atomic_destroy_state = drm_atomic_helper_crtc_destroy_state,
+};
+
+/* ---- encoder and connector ---------------------------------------------- */
+
+static const struct drm_encoder_funcs s1d_encoder_funcs = {
+	.destroy = drm_encoder_cleanup,
+};
+
+static int s1d_connector_get_modes(struct drm_connector *connector)
+{
+	return drm_connector_helper_get_modes_fixed(connector,
+						    &to_s1d(connector->dev)->mode);
+}
+
+static const struct drm_connector_helper_funcs s1d_connector_helper_funcs = {
+	.get_modes = s1d_connector_get_modes,
+};
+
+static const struct drm_connector_funcs s1d_connector_funcs = {
+	.reset = drm_atomic_helper_connector_reset,
+	.fill_modes = drm_helper_probe_single_connector_modes,
+	.destroy = drm_connector_cleanup,
+	.atomic_duplicate_state = drm_atomic_helper_connector_duplicate_state,
+	.atomic_destroy_state = drm_atomic_helper_connector_destroy_state,
+};
+
+/* ---- device ------------------------------------------------------------- */
+
+/* enables before plane updates, so the first frame reaches an initialised panel */
+static const struct drm_mode_config_helper_funcs s1d_mode_config_helpers = {
+	.atomic_commit_tail = drm_atomic_helper_commit_tail_rpm,
+};
+
+static const struct drm_mode_config_funcs s1d_mode_config_funcs = {
+	.fb_create = drm_gem_fb_create_with_dirty,
+	.atomic_check = drm_atomic_helper_check,
+	.atomic_commit = drm_atomic_helper_commit,
+};
+
+static const u32 s1d_formats[] = { DRM_FORMAT_XRGB8888 };
+static const u64 s1d_modifiers[] = { DRM_FORMAT_MOD_LINEAR, DRM_FORMAT_MOD_INVALID };
+
+DEFINE_DRM_GEM_FOPS(s1d_fops);
+
+static const struct drm_driver s1d_drm_driver = {
+	.driver_features = DRIVER_MODESET | DRIVER_GEM | DRIVER_ATOMIC,
+	.name = DRIVER_NAME,
+	.desc = "S1D13700 LCD behind a TCA9539 expander",
+	.major = 1,
+	.minor = 0,
+	.fops = &s1d_fops,
+	DRM_GEM_SHMEM_DRIVER_OPS,
+	DRM_FBDEV_SHMEM_DRIVER_OPS,
+};
+
+static int s1d_kms_init(struct s1d_device *s)
+{
+	struct drm_device *drm = &s->drm;
+	int ret;
+
+	ret = drmm_mode_config_init(drm);
+	if (ret)
+		return ret;
+	drm->mode_config.funcs = &s1d_mode_config_funcs;
+	drm->mode_config.helper_private = &s1d_mode_config_helpers;
+	drm->mode_config.min_width = s->cfg.width;
+	drm->mode_config.max_width = s->cfg.width;
+	drm->mode_config.min_height = s->cfg.height;
+	drm->mode_config.max_height = s->cfg.height;
+	drm->mode_config.preferred_depth = 24;
+
+	ret = drm_universal_plane_init(drm, &s->plane, 0, &s1d_plane_funcs,
+				       s1d_formats, ARRAY_SIZE(s1d_formats),
+				       s1d_modifiers, DRM_PLANE_TYPE_PRIMARY, NULL);
+	if (ret)
+		return ret;
+	drm_plane_helper_add(&s->plane, &s1d_plane_helper_funcs);
+	drm_plane_enable_fb_damage_clips(&s->plane);
+
+	ret = drm_crtc_init_with_planes(drm, &s->crtc, &s->plane, NULL,
+					&s1d_crtc_funcs, NULL);
+	if (ret)
+		return ret;
+	drm_crtc_helper_add(&s->crtc, &s1d_crtc_helper_funcs);
+
+	ret = drm_encoder_init(drm, &s->encoder, &s1d_encoder_funcs,
+			       DRM_MODE_ENCODER_NONE, NULL);
+	if (ret)
+		return ret;
+	s->encoder.possible_crtcs = drm_crtc_mask(&s->crtc);
+
+	ret = drm_connector_init(drm, &s->connector, &s1d_connector_funcs,
+				 DRM_MODE_CONNECTOR_Unknown);
+	if (ret)
+		return ret;
+	drm_connector_helper_add(&s->connector, &s1d_connector_helper_funcs);
+
+	ret = drm_connector_attach_encoder(&s->connector, &s->encoder);
+	if (ret)
+		return ret;
+
+	drm_mode_config_reset(drm);
+	return 0;
+}
+
+static void s1d_debugfs_init(struct s1d_device *s)
+{
+	struct dentry *d = s->client->debugfs;
+	struct s1d_stats *st = &s->panel.stats;
+
+	debugfs_create_ulong("lcd_writes", 0444, d, &st->writes);
+	debugfs_create_ulong("data_bytes", 0444, d, &st->data_bytes);
+	debugfs_create_ulong("seeks", 0444, d, &st->seeks);
+	debugfs_create_ulong("dir_changes", 0444, d, &st->dir_changes);
+	debugfs_create_ulong("i2c_msgs", 0444, d, &st->i2c_msgs);
+	debugfs_create_ulong("i2c_bytes", 0444, d, &st->i2c_bytes);
+}
+
+static int s1d_probe(struct i2c_client *client)
+{
+	struct device *dev = &client->dev;
+	const struct i2c_adapter_quirks *quirks = client->adapter->quirks;
+	struct drm_display_mode mode = {
+		DRM_SIMPLE_MODE(width, height, 0, 0),
+	};
+	struct s1d_device *s;
+	size_t tx_cap = TX_CAP;
+	unsigned int size;
+	u8 *shadow, *tx;
+	int ret;
+
+	if (!i2c_check_functionality(client->adapter, I2C_FUNC_I2C))
+		return dev_err_probe(dev, -EOPNOTSUPP, "adapter lacks raw I2C\n");
+
+	/* a plain register read tells us whether the expander is there at all */
+	ret = i2c_smbus_read_byte_data(client, TCA_REG_CONFIG0);
+	if (ret < 0)
+		return dev_err_probe(dev, ret, "expander not responding\n");
+
+	s = devm_drm_dev_alloc(dev, &s1d_drm_driver, struct s1d_device, drm);
+	if (IS_ERR(s))
+		return PTR_ERR(s);
+
+	s->client = client;
+	s->cfg = (struct s1d_config){ width, height, bpp, tcr };
+	s->mode = mode;
+	s->dirty_y0 = height;
+	s->retry_ms = RETRY_MIN_MS;
+	INIT_DELAYED_WORK(&s->flush_work, s1d_flush_work);
+	ret = drmm_mutex_init(&s->drm, &s->lock);
+	if (ret)
+		return ret;
+
+	size = s1d_frame_size(&s->cfg);
+	if (!size)
+		return dev_err_probe(dev, -EINVAL, "invalid panel configuration\n");
+
+	if (quirks && quirks->max_write_len && quirks->max_write_len < tx_cap)
+		tx_cap = quirks->max_write_len;
+
+	shadow = devm_kzalloc(dev, size, GFP_KERNEL);
+	s->work_frame = devm_kzalloc(dev, size, GFP_KERNEL);
+	s->pending_frame = devm_kzalloc(dev, size, GFP_KERNEL);
+	tx = devm_kmalloc(dev, tx_cap, GFP_KERNEL);	/* must be DMA-safe */
+	if (!shadow || !s->work_frame || !s->pending_frame || !tx)
+		return -ENOMEM;
+
+	ret = s1d_panel_setup(&s->panel, &s->cfg, &s1d_panel_ops, s, shadow, tx, tx_cap);
+	if (ret)
+		return dev_err_probe(dev, ret, "panel setup failed\n");
+
+	ret = s1d_kms_init(s);
+	if (ret)
+		return dev_err_probe(dev, ret, "KMS init failed\n");
+
+	i2c_set_clientdata(client, s);
+
+	ret = drm_dev_register(&s->drm, 0);
+	if (ret)
+		return dev_err_probe(dev, ret, "DRM registration failed\n");
+
+	s1d_debugfs_init(s);
+	drm_client_setup(&s->drm, NULL);
+	return 0;
+}
+
+static void s1d_remove(struct i2c_client *client)
+{
+	struct s1d_device *s = i2c_get_clientdata(client);
+
+	drm_dev_unplug(&s->drm);
+	cancel_delayed_work_sync(&s->flush_work);
+	/* atomic_disable is a no-op once unplugged, so blank the panel here */
+	if (s->panel_ready)
+		s1d_panel_display(&s->panel, false);
+	drm_atomic_helper_shutdown(&s->drm);
+}
+
+static void s1d_shutdown(struct i2c_client *client)
+{
+	struct s1d_device *s = i2c_get_clientdata(client);
+
+	drm_atomic_helper_shutdown(&s->drm);
+	cancel_delayed_work_sync(&s->flush_work);
+}
+
+static int s1d_suspend(struct device *dev)
+{
+	struct s1d_device *s = dev_get_drvdata(dev);
+	int ret;
+
+	ret = drm_mode_config_helper_suspend(&s->drm);
+	if (ret)
+		return ret;
+	/* the CRTC is off and the worker stopped; the controller may lose power */
+	s->panel_ready = false;
+	return 0;
+}
+
+static int s1d_resume(struct device *dev)
+{
+	struct s1d_device *s = dev_get_drvdata(dev);
+
+	return drm_mode_config_helper_resume(&s->drm);
+}
+
+static DEFINE_SIMPLE_DEV_PM_OPS(s1d_pm_ops, s1d_suspend, s1d_resume);
+
+static const struct of_device_id s1d_of_match[] = {
+	{ .compatible = "k4be,s1d13700-tca9539" },
+	{ }
+};
+MODULE_DEVICE_TABLE(of, s1d_of_match);
+
+static const struct i2c_device_id s1d_id[] = {
+	{ "s1d13700-tca9539" },
+	{ }
+};
+MODULE_DEVICE_TABLE(i2c, s1d_id);
+
+static struct i2c_driver s1d_i2c_driver = {
+	.driver = {
+		.name = DRIVER_NAME,
+		.of_match_table = s1d_of_match,
+		.pm = pm_sleep_ptr(&s1d_pm_ops),
+	},
+	.probe = s1d_probe,
+	.remove = s1d_remove,
+	.shutdown = s1d_shutdown,
+	.id_table = s1d_id,
+};
+module_i2c_driver(s1d_i2c_driver);
+
+MODULE_DESCRIPTION("DRM driver for an S1D13700 LCD behind a TCA9539 expander");
+MODULE_LICENSE("GPL");

+ 81 - 0
dts/radio-panel.dts

@@ -0,0 +1,81 @@
+/*
+ * Device tree overlay for the radio front panel on an Allwinner board.
+ *
+ * Plain numbers instead of #include, so it also works with armbian-add-overlay.
+ *
+ * TO CHECK against the actual board before use:
+ *   - root compatible, and the i2c bus in fragment@0 (i2c0)
+ *   - the U2 INT line: placeholder PA6 (<0 6 ...> = bank A, pin 6)
+ *
+ * U1 (0x74) is left to the s1d13700-tca driver and must not bind to pca953x.
+ * For the i2c-dev frontend, remove the panel@74 node.
+ */
+/dts-v1/;
+/plugin/;
+
+/ {
+	compatible = "allwinner,sun8i-h3";
+
+	fragment@0 {
+		target = <&i2c0>;
+
+		__overlay__ {
+			#address-cells = <1>;
+			#size-cells = <0>;
+			clock-frequency = <400000>;
+			status = "okay";
+
+			panel@74 {
+				compatible = "k4be,s1d13700-tca9539";
+				reg = <0x74>;
+			};
+
+			radio_u2: gpio@75 {
+				compatible = "ti,tca9539";
+				reg = <0x75>;
+				gpio-controller;
+				#gpio-cells = <2>;
+				interrupt-controller;
+				#interrupt-cells = <2>;
+				interrupt-parent = <&pio>;
+				interrupts = <0 6 8>;	/* PA6, level low: PLACEHOLDER */
+			};
+		};
+	};
+
+	fragment@1 {
+		target-path = "/";
+
+		__overlay__ {
+			/*
+			 * Keys are active low and read directly: one pin each, with
+			 * a 10k pull-up (the TCA9539 has none). Pins 0-7 are P0.0-7,
+			 * pins 8-15 are P1.0-7. Flag 1 = GPIO_ACTIVE_LOW.
+			 */
+			radio-keys {
+				compatible = "gpio-keys";
+				autorepeat;
+
+				esc	{ label = "esc";   gpios = <&radio_u2 0 1>;  linux,code = <1>;   debounce-interval = <20>; };
+				next	{ label = "next";  gpios = <&radio_u2 1 1>;  linux,code = <163>; debounce-interval = <20>; };
+				stop	{ label = "stop";  gpios = <&radio_u2 2 1>;  linux,code = <166>; debounce-interval = <20>; };
+				menu	{ label = "menu";  gpios = <&radio_u2 3 1>;  linux,code = <139>; debounce-interval = <20>; };
+				list	{ label = "list";  gpios = <&radio_u2 4 1>;  linux,code = <395>; debounce-interval = <20>; };
+				up	{ label = "up";    gpios = <&radio_u2 5 1>;  linux,code = <103>; debounce-interval = <20>; };
+				prev	{ label = "prev";  gpios = <&radio_u2 6 1>;  linux,code = <165>; debounce-interval = <20>; };
+				right	{ label = "right"; gpios = <&radio_u2 7 1>;  linux,code = <106>; debounce-interval = <20>; };
+				down	{ label = "down";  gpios = <&radio_u2 8 1>;  linux,code = <108>; debounce-interval = <20>; };
+				pause	{ label = "pause"; gpios = <&radio_u2 9 1>;  linux,code = <201>; debounce-interval = <20>; };
+				ok	{ label = "ok";    gpios = <&radio_u2 10 1>; linux,code = <352>; debounce-interval = <20>; };
+				left	{ label = "left";  gpios = <&radio_u2 11 1>; linux,code = <105>; debounce-interval = <20>; };
+				play	{ label = "play";  gpios = <&radio_u2 12 1>; linux,code = <200>; debounce-interval = <20>; };
+			};
+
+			radio-backlight {
+				compatible = "gpio-backlight";
+				gpios = <&radio_u2 13 0>;	/* P1.5, active high */
+				default-on;
+			};
+		};
+	};
+};

+ 234 - 0
sim/s1d13700_sim.c

@@ -0,0 +1,234 @@
+#include <string.h>
+
+#include "s1d13700_core.h"
+#include "s1d13700_sim.h"
+
+void s1d_sim_init(struct s1d_sim *s)
+{
+	memset(s, 0, sizeof(*s));
+	/* TCA9539 power-on state: output latches high, all pins inputs */
+	s->out[0] = s->out[1] = 0xff;
+	s->config[0] = s->config[1] = 0xff;
+	s->step = 1;
+}
+
+/* Control pin level: an input pin is held high by the external pull-ups */
+static uint8_t p1_pins(const uint8_t out, const uint8_t config)
+{
+	return out | config;
+}
+
+static void reset_controller(struct s1d_sim *s)
+{
+	s->cmd = 0;
+	s->nparam = 0;
+	s->configured = false;
+	s->display_on = false;
+	s->step = 1;
+}
+
+static void apply_system_set(struct s1d_sim *s)
+{
+	const uint8_t *p = s->params;
+
+	s->fx = p[1] & 0x0f;
+	s->cr = p[3];
+	s->tcr = p[4];
+	s->lf = p[5];
+	s->ap = p[6] | p[7] << 8;
+	s->configured = true;
+	if (s->fx != 7 || s->ap != s->cr + 1 || s->tcr < s->cr + 4)
+		s->faults.bad_system_set++;
+}
+
+static void latch_command(struct s1d_sim *s, uint8_t c)
+{
+	s->cmd = c;
+	s->nparam = 0;
+
+	switch (c) {
+	case S1D_CMD_CSRDIR_R: s->step = 1; s->cmd = 0; break;
+	case S1D_CMD_CSRDIR_L: s->step = -1; s->cmd = 0; break;
+	case S1D_CMD_CSRDIR_U: s->step = -(int)s->ap; s->cmd = 0; break;
+	case S1D_CMD_CSRDIR_D: s->step = (int)s->ap; s->cmd = 0; break;
+	case S1D_CMD_SYSTEM_SET:
+	case S1D_CMD_MWRITE:
+	case S1D_CMD_SCROLL:
+	case S1D_CMD_CSRW:
+	case S1D_CMD_DISP_ON:
+	case S1D_CMD_DISP_OFF:
+	case S1D_CMD_HDOT_SCR:
+	case S1D_CMD_OVLAY:
+	case S1D_CMD_CGRAM_ADR:
+	case S1D_CMD_CSRFORM:
+	case S1D_CMD_GRAYSCALE:
+		break;
+	default:
+		s->faults.unknown_command++;
+		s->cmd = 0;
+		break;
+	}
+}
+
+static unsigned int expected_params(uint8_t c)
+{
+	switch (c) {
+	case S1D_CMD_SYSTEM_SET: return 8;
+	case S1D_CMD_SCROLL: return 10;
+	case S1D_CMD_CSRW: return 2;
+	case S1D_CMD_DISP_ON:
+	case S1D_CMD_DISP_OFF:
+	case S1D_CMD_HDOT_SCR:
+	case S1D_CMD_OVLAY:
+	case S1D_CMD_GRAYSCALE: return 1;
+	case S1D_CMD_CGRAM_ADR:
+	case S1D_CMD_CSRFORM: return 2;
+	default: return 0;
+	}
+}
+
+static void latch_data(struct s1d_sim *s, uint8_t d)
+{
+	if (!s->cmd) {
+		s->faults.data_no_command++;
+		return;
+	}
+
+	if (s->cmd == S1D_CMD_MWRITE) {
+		s->vram[s->cursor & 0x7fff] = d;
+		s->cursor = (unsigned int)((int)s->cursor + s->step) & 0xffff;
+		return;
+	}
+
+	if (s->nparam >= expected_params(s->cmd)) {
+		s->faults.data_no_mwrite++;
+		return;
+	}
+	s->params[s->nparam++] = d;
+	if (s->nparam < expected_params(s->cmd))
+		return;
+
+	switch (s->cmd) {
+	case S1D_CMD_SYSTEM_SET:
+		apply_system_set(s);
+		break;
+	case S1D_CMD_SCROLL:
+		s->sad1 = s->params[0] | s->params[1] << 8;
+		s->sl1 = s->params[2];
+		break;
+	case S1D_CMD_CSRW:
+		s->cursor = s->params[0] | s->params[1] << 8;
+		break;
+	case S1D_CMD_GRAYSCALE:
+		s->bpp = 1u << (s->params[0] & 3);
+		break;
+	case S1D_CMD_DISP_ON:
+		s->display_on = true;
+		s->disp_flags = s->params[0];
+		break;
+	case S1D_CMD_DISP_OFF:
+		s->display_on = false;
+		break;
+	default:
+		break;
+	}
+}
+
+static void port1_changed(struct s1d_sim *s, uint8_t old_pins, uint8_t pins)
+{
+	uint8_t changed = old_pins ^ pins;
+
+	if ((changed & S1D_P1_A0) && (changed & S1D_P1_WR))
+		s->faults.a0_with_wr_edge++;
+
+	if (!(pins & S1D_P1_RES)) {
+		reset_controller(s);
+		if (!(pins & S1D_P1_WR))
+			s->faults.write_in_reset++;
+		return;
+	}
+
+	/* the 8080-style bus latches on the rising edge of WR#, if selected */
+	if ((changed & S1D_P1_WR) && (pins & S1D_P1_WR) && !(pins & S1D_P1_CS)) {
+		uint8_t data = s->out[0] | s->config[0];
+
+		s->latches++;
+		if (pins & S1D_P1_A0)
+			latch_command(s, data);
+		else
+			latch_data(s, data);
+	}
+}
+
+void s1d_sim_i2c_write(struct s1d_sim *s, const uint8_t *buf, size_t len)
+{
+	unsigned int reg;
+	size_t i;
+
+	if (!len)
+		return;
+	reg = buf[0];
+	if (reg != TCA_REG_OUTPUT0 && reg != TCA_REG_OUTPUT0 + 1 &&
+	    reg != TCA_REG_CONFIG0 && reg != TCA_REG_CONFIG0 + 1 &&
+	    reg != TCA_REG_POLARITY0 && reg != TCA_REG_POLARITY0 + 1) {
+		s->faults.bad_tca_register++;
+		return;
+	}
+	if (reg == TCA_REG_OUTPUT0 && !(len & 1))
+		s->faults.short_message++;
+
+	for (i = 1; i < len; i++, reg ^= 1) {
+		uint8_t old = p1_pins(s->out[1], s->config[1]);
+
+		switch (reg) {
+		case TCA_REG_OUTPUT0:
+			s->out[0] = buf[i];
+			break;
+		case TCA_REG_OUTPUT0 + 1:
+			s->out[1] = buf[i];
+			port1_changed(s, old, p1_pins(s->out[1], s->config[1]));
+			break;
+		case TCA_REG_CONFIG0:
+			s->config[0] = buf[i];
+			break;
+		case TCA_REG_CONFIG0 + 1:
+			s->config[1] = buf[i];
+			port1_changed(s, old, p1_pins(s->out[1], s->config[1]));
+			break;
+		default:
+			break;	/* polarity: must stay 0 for this design */
+		}
+	}
+}
+
+unsigned int s1d_sim_fault_count(const struct s1d_sim *s)
+{
+	const struct s1d_sim_faults *f = &s->faults;
+
+	return f->a0_with_wr_edge + f->data_no_command + f->data_no_mwrite +
+	       f->unknown_command + f->bad_tca_register + f->short_message +
+	       f->bad_system_set + f->write_in_reset;
+}
+
+bool s1d_sim_render(const struct s1d_sim *s, unsigned int width,
+		    unsigned int height, uint8_t *levels)
+{
+	unsigned int bpp = s->bpp ? s->bpp : 1;
+	unsigned int x, y, mask = (1u << bpp) - 1;
+
+	if (!s->configured || !s->display_on || !(s->disp_flags & 0x0c))
+		return false;
+	if ((s->cr + 1) * 8 / bpp != width || s->lf + 1 != height)
+		return false;
+
+	for (y = 0; y < height; y++) {
+		for (x = 0; x < width; x++) {
+			unsigned int bit = x * bpp;
+			uint8_t byte = s->vram[(s->sad1 + y * s->ap + bit / 8) & 0x7fff];
+			unsigned int shift = 8 - bpp - bit % 8;
+
+			levels[y * width + x] = (byte >> shift) & mask;
+		}
+	}
+	return true;
+}

+ 63 - 0
sim/s1d13700_sim.h

@@ -0,0 +1,63 @@
+/*
+ * Model of the TCA9539 output stage and the S1D13700 indirect interface.
+ *
+ * It sees only the I2C bytes the panel core produces, so what it renders is
+ * what the real panel would receive, and it counts anything the hardware
+ * would not tolerate.
+ */
+#ifndef S1D13700_SIM_H
+#define S1D13700_SIM_H
+
+#include <stdbool.h>
+#include <stddef.h>
+#include <stdint.h>
+
+struct s1d_sim_faults {
+	unsigned int a0_with_wr_edge;	/* A0 changed in the same update as WR# */
+	unsigned int data_no_command;	/* parameter with no command in progress */
+	unsigned int data_no_mwrite;	/* parameter beyond what a command takes */
+	unsigned int unknown_command;
+	unsigned int bad_tca_register;
+	unsigned int short_message;	/* message ended between P0 and P1 */
+	unsigned int bad_system_set;	/* FX != 7 or C/R, AP mismatch */
+	unsigned int write_in_reset;
+};
+
+struct s1d_sim {
+	uint8_t vram[32768];
+	uint8_t out[2];			/* TCA output latches */
+	uint8_t config[2];		/* TCA direction: 1 = input */
+
+	uint8_t cmd;
+	unsigned int nparam;
+	uint8_t params[16];
+
+	unsigned int cursor;
+	int step;
+
+	/* decoded configuration */
+	unsigned int cr, tcr, lf, ap, fx, sad1, sl1, bpp;
+	bool configured;
+	bool display_on;
+	uint8_t disp_flags;
+
+	struct s1d_sim_faults faults;
+	unsigned long latches;
+};
+
+void s1d_sim_init(struct s1d_sim *s);
+
+/* One I2C write message: buf[0] is the TCA9539 command byte */
+void s1d_sim_i2c_write(struct s1d_sim *s, const uint8_t *buf, size_t len);
+
+unsigned int s1d_sim_fault_count(const struct s1d_sim *s);
+
+/*
+ * Render what the panel shows into levels[width * height], one level per
+ * pixel, using only the controller's decoded configuration. Returns false if
+ * the display is off or not configured, or the size does not match.
+ */
+bool s1d_sim_render(const struct s1d_sim *s, unsigned int width,
+		    unsigned int height, uint8_t *levels);
+
+#endif /* S1D13700_SIM_H */

+ 412 - 0
tests/test_panel.c

@@ -0,0 +1,412 @@
+/*
+ * Panel core tests: the planner's output is decoded by the simulator and the
+ * resulting display memory compared with the intended frame.
+ */
+#include <errno.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "s1d13700_core.h"
+#include "s1d13700_sim.h"
+
+#define W 240
+#define H 160
+
+static int failures;
+
+#define CHECK(c) do { \
+	if (!(c)) { \
+		printf("FAIL %s:%d: %s\n", __func__, __LINE__, #c); \
+		failures++; \
+	} \
+} while (0)
+
+struct rig {
+	struct s1d_sim sim;
+	struct s1d_panel panel;
+	uint8_t shadow[S1D_VRAM_SIZE];
+	uint8_t tx[4096];
+	size_t max_msg;
+	int fail_after;		/* <0: never */
+};
+
+static int rig_xfer(void *ctx, const uint8_t *buf, size_t len)
+{
+	struct rig *r = ctx;
+
+	if (r->fail_after == 0)
+		return -EIO;
+	if (r->fail_after > 0)
+		r->fail_after--;
+	if (len > r->max_msg)
+		r->max_msg = len;
+	s1d_sim_i2c_write(&r->sim, buf, len);
+	return 0;
+}
+
+static void rig_delay(void *ctx, unsigned int ms)
+{
+	(void)ctx;
+	(void)ms;
+}
+
+static const struct s1d_ops rig_ops = { rig_xfer, rig_delay };
+
+static void rig_setup(struct rig *r, unsigned int bpp, size_t tx_cap)
+{
+	struct s1d_config cfg = { W, H, bpp, 162 };
+
+	memset(r, 0, sizeof(*r));
+	r->fail_after = -1;
+	s1d_sim_init(&r->sim);
+	CHECK(s1d_panel_setup(&r->panel, &cfg, &rig_ops, r, r->shadow, r->tx, tx_cap) == 0);
+	CHECK(s1d_panel_init(&r->panel) == 0);
+	CHECK(s1d_sim_fault_count(&r->sim) == 0);
+	memset(&r->panel.stats, 0, sizeof(r->panel.stats));
+}
+
+static int vram_matches(const struct rig *r, const uint8_t *frame)
+{
+	return !memcmp(r->sim.vram, frame, r->panel.size);
+}
+
+static void test_init(void)
+{
+	struct rig r;
+
+	rig_setup(&r, 2, 1025);
+	CHECK(r.sim.configured);
+	CHECK(r.sim.display_on);
+	CHECK(r.sim.fx == 7);
+	CHECK(r.sim.cr == 59);
+	CHECK(r.sim.ap == 60);
+	CHECK(r.sim.lf == 159);
+	CHECK(r.sim.bpp == 2);
+	CHECK(r.sim.step == 1);
+	CHECK(r.max_msg <= 1025);
+}
+
+static void test_invalid_config(void)
+{
+	static const struct s1d_config bad[] = {
+		{ 241, 160, 2, 162 },	/* not a whole number of bytes */
+		{ 240, 160, 3, 162 },
+		{ 240, 160, 2, 40 },	/* TC/R too small */
+		{ 240, 160, 2, 62 },	/* [TC/R] = [C/R] + 3, needs + 4 */
+		{ 2024, 160, 1, 255 },	/* C/R does not fit */
+		{ 240, 300, 2, 162 },
+	};
+
+	static const struct s1d_config edge = { 240, 160, 2, 63 };
+	unsigned int i;
+
+	for (i = 0; i < sizeof(bad) / sizeof(bad[0]); i++)
+		CHECK(s1d_frame_size(&bad[i]) == 0);
+	CHECK(s1d_frame_size(&edge) == 9600);
+}
+
+static void test_no_change_no_traffic(void)
+{
+	static struct rig r;
+	uint8_t frame[S1D_VRAM_SIZE] = { 0 };
+
+	rig_setup(&r, 2, 1025);
+	CHECK(s1d_panel_update(&r.panel, frame, 0, H) == 0);
+	CHECK(r.panel.stats.i2c_msgs == 0);
+	CHECK(r.panel.stats.writes == 0);
+}
+
+static void test_digit_uses_vertical(void)
+{
+	static struct rig r;
+	uint8_t frame[S1D_VRAM_SIZE] = { 0 };
+	unsigned int y;
+
+	rig_setup(&r, 2, 1025);
+	for (y = 40; y < 53; y++) {
+		frame[y * 60 + 20] = 0xa5;
+		frame[y * 60 + 21] = 0x5a;
+	}
+	CHECK(s1d_panel_update(&r.panel, frame, 0, H) == 0);
+	CHECK(vram_matches(&r, frame));
+	CHECK(s1d_sim_fault_count(&r.sim) == 0);
+	CHECK(r.panel.stats.seeks == 2);
+	CHECK(r.panel.stats.dir_changes == 1);
+	CHECK(r.sim.step == 60);
+	printf("  8x13 digit: %lu writes, %lu I2C bytes, %llu us at 400 kHz\n",
+	       r.panel.stats.writes, r.panel.stats.i2c_bytes,
+	       (unsigned long long)s1d_stats_bus_us(&r.panel.stats, 400000));
+	CHECK(s1d_stats_bus_us(&r.panel.stats, 400000) < 5000);
+}
+
+static void test_full_frame_is_one_run(void)
+{
+	static struct rig r;
+	uint8_t frame[S1D_VRAM_SIZE];
+
+	rig_setup(&r, 2, 1025);
+	memset(frame, 0xff, sizeof(frame));
+	CHECK(s1d_panel_update(&r.panel, frame, 0, H) == 0);
+	CHECK(vram_matches(&r, frame));
+	CHECK(r.panel.stats.seeks == 1);
+	CHECK(r.panel.stats.data_bytes == 9600);
+	CHECK(r.max_msg <= 1025);
+	printf("  full frame: %lu I2C bytes, %lu msgs, %llu us at 400 kHz\n",
+	       r.panel.stats.i2c_bytes, r.panel.stats.i2c_msgs,
+	       (unsigned long long)s1d_stats_bus_us(&r.panel.stats, 400000));
+	CHECK(s1d_stats_bus_us(&r.panel.stats, 0) == 0);
+}
+
+static void test_gap_merge(void)
+{
+	static struct rig r;
+	uint8_t frame[S1D_VRAM_SIZE] = { 0 };
+
+	/* wide row: horizontal, gap equal to a seek is merged, a longer one not */
+	rig_setup(&r, 2, 1025);
+	memset(frame + 10 * 60, 0x11, 4);
+	memset(frame + 10 * 60 + 4 + S1D_SEEK_COST, 0x22, 4);
+	CHECK(s1d_panel_update(&r.panel, frame, 0, H) == 0);
+	CHECK(r.panel.stats.seeks == 1);
+	CHECK(vram_matches(&r, frame));
+
+	rig_setup(&r, 2, 1025);
+	memset(frame, 0, sizeof(frame));
+	memset(frame + 10 * 60, 0x11, 4);
+	memset(frame + 10 * 60 + 4 + S1D_SEEK_COST + 1, 0x22, 4);
+	CHECK(s1d_panel_update(&r.panel, frame, 0, H) == 0);
+	CHECK(r.panel.stats.seeks == 2);
+	CHECK(vram_matches(&r, frame));
+}
+
+static void test_random_updates(unsigned int bpp, size_t tx_cap)
+{
+	static struct rig r;
+	static uint8_t frame[S1D_VRAM_SIZE];
+	unsigned int size, round;
+
+	rig_setup(&r, bpp, tx_cap);
+	size = r.panel.size;
+	memset(frame, 0, sizeof(frame));
+
+	for (round = 0; round < 400; round++) {
+		unsigned int n = rand() % 12, i;
+
+		for (i = 0; i < n; i++) {
+			unsigned int w = 1 + rand() % r.panel.stride;
+			unsigned int h = 1 + rand() % H;
+			unsigned int x = rand() % (r.panel.stride - w + 1);
+			unsigned int y = rand() % (H - h + 1), yy, xx;
+			int solid = rand() & 1;
+			uint8_t v = rand();
+
+			for (yy = y; yy < y + h; yy++)
+				for (xx = x; xx < x + w; xx++)
+					frame[yy * r.panel.stride + xx] = solid ? v : rand();
+		}
+		CHECK(s1d_panel_update(&r.panel, frame, 0, H) == 0);
+		if (!vram_matches(&r, frame)) {
+			printf("FAIL random bpp=%u round=%u\n", bpp, round);
+			failures++;
+			return;
+		}
+	}
+	CHECK(!memcmp(r.panel.shadow, frame, size));
+	CHECK(s1d_sim_fault_count(&r.sim) == 0);
+	CHECK(r.max_msg <= tx_cap);
+}
+
+static void test_transport_error_recovers(void)
+{
+	static struct rig r;
+	uint8_t frame[S1D_VRAM_SIZE];
+
+	rig_setup(&r, 2, 65);
+	memset(frame, 0x3c, sizeof(frame));
+	r.fail_after = 3;
+	CHECK(s1d_panel_update(&r.panel, frame, 0, H) == -EIO);
+	CHECK(r.panel.force_full);
+	CHECK(!vram_matches(&r, frame));
+	CHECK(r.panel.stats.writes < 100);	/* stopped at the error */
+
+	/* a later update with no new damage still repairs the whole panel */
+	r.fail_after = -1;
+	CHECK(s1d_panel_update(&r.panel, frame, 5, 6) == 0);
+	CHECK(!r.panel.force_full);
+	CHECK(vram_matches(&r, frame));
+	CHECK(s1d_sim_fault_count(&r.sim) == 0);
+}
+
+/* Random damage with dropped messages: every retry must converge cleanly. */
+static void test_random_failures(size_t tx_cap)
+{
+	static struct rig r;
+	static uint8_t frame[S1D_VRAM_SIZE];
+	unsigned int round, errors = 0;
+
+	rig_setup(&r, 2, tx_cap);
+	memset(frame, 0, sizeof(frame));
+
+	for (round = 0; round < 300; round++) {
+		unsigned int w = 1 + rand() % r.panel.stride;
+		unsigned int h = 1 + rand() % H;
+		unsigned int x = rand() % (r.panel.stride - w + 1);
+		unsigned int y = rand() % (H - h + 1), yy, xx;
+
+		for (yy = y; yy < y + h; yy++)
+			for (xx = x; xx < x + w; xx++)
+				frame[yy * r.panel.stride + xx] = rand();
+
+		r.fail_after = rand() % 3 ? -1 : rand() % 8;
+		if (s1d_panel_update(&r.panel, frame, y, y + h)) {
+			errors++;
+			r.fail_after = -1;
+			CHECK(s1d_panel_update(&r.panel, frame, 0, 1) == 0);
+		}
+		if (!vram_matches(&r, frame)) {
+			printf("FAIL random failures cap=%zu round=%u\n", tx_cap, round);
+			failures++;
+			return;
+		}
+	}
+	CHECK(errors > 0);
+	CHECK(s1d_sim_fault_count(&r.sim) == 0);
+}
+
+/* A lost direction command must not survive into the repair pass. */
+static void test_lost_direction_recovers(void)
+{
+	static struct rig r;
+	static uint8_t frame[S1D_VRAM_SIZE];
+	unsigned int y;
+
+	rig_setup(&r, 2, 7);	/* one LCD write per message */
+	memset(frame, 0, sizeof(frame));
+	for (y = 40; y < 53; y++)
+		frame[y * 60 + 20] = 0xa5;
+	CHECK(s1d_panel_update(&r.panel, frame, 0, H) == 0);
+	CHECK(r.sim.step == 60);
+
+	/* a wide row goes horizontal: drop the CSRDIR_R that starts it */
+	memset(frame + 100 * 60, 0x5a, 60);
+	r.fail_after = 0;
+	CHECK(s1d_panel_update(&r.panel, frame, 0, H) == -EIO);
+	CHECK(r.sim.step == 60);
+
+	r.fail_after = -1;
+	CHECK(s1d_panel_update(&r.panel, frame, 100, 101) == 0);
+	CHECK(vram_matches(&r, frame));
+	CHECK(s1d_sim_fault_count(&r.sim) == 0);
+}
+
+static void test_command_tracks_direction(void)
+{
+	static struct rig r;
+
+	rig_setup(&r, 2, 1025);
+	CHECK(s1d_panel_command(&r.panel, S1D_CMD_CSRDIR_D, NULL, 0) == 0);
+	CHECK(r.panel.vertical && r.sim.step == 60);
+	CHECK(s1d_panel_command(&r.panel, S1D_CMD_CSRDIR_R, NULL, 0) == 0);
+	CHECK(!r.panel.vertical && r.sim.step == 1);
+	CHECK(s1d_panel_command(&r.panel, S1D_CMD_CSRDIR_L, NULL, 0) == -EINVAL);
+	CHECK(s1d_panel_command(&r.panel, S1D_CMD_CSRDIR_U, NULL, 0) == -EINVAL);
+	CHECK(r.sim.step == 1);
+}
+
+static void test_convert(void)
+{
+	static const struct s1d_config cfg = { 8, 2, 2, 162 };
+	uint32_t src[16];
+	uint8_t dst[4] = { 0 };
+
+	memset(src, 0xff, sizeof(src));		/* white */
+	src[0] = 0x000000;			/* leftmost pixel black */
+	src[3] = 0x555555;			/* level 2: (255-85)>>6 */
+	src[4 + 8] = 0x000000;			/* second row, x=4 */
+
+	s1d_convert_xrgb8888(&cfg, src, 8 * 4, dst, 0, 0, 8, 2);
+	CHECK(dst[0] == 0xc2);
+	CHECK(dst[1] == 0x00);
+	CHECK(dst[2] == 0x00);
+	CHECK(dst[3] == 0xc0);
+
+	/* partial damage widens to whole bytes and leaves other bytes alone */
+	memset(dst, 0x77, sizeof(dst));
+	s1d_convert_xrgb8888(&cfg, src, 8 * 4, dst, 1, 0, 2, 1);
+	CHECK(dst[0] == 0xc2);
+	CHECK(dst[1] == 0x77);
+	CHECK(dst[2] == 0x77);
+}
+
+static void test_sim_render(void)
+{
+	static struct rig r;
+	static uint8_t frame[S1D_VRAM_SIZE], levels[W * H];
+
+	rig_setup(&r, 2, 1025);
+	frame[0] = 0xe4;	/* pixels 3, 2, 1, 0 */
+	CHECK(s1d_panel_update(&r.panel, frame, 0, H) == 0);
+	CHECK(s1d_sim_render(&r.sim, W, H, levels));
+	CHECK(levels[0] == 3 && levels[1] == 2 && levels[2] == 1 && levels[3] == 0);
+	CHECK(!s1d_sim_render(&r.sim, 320, H, levels));
+	CHECK(s1d_panel_display(&r.panel, false) == 0);
+	CHECK(!s1d_sim_render(&r.sim, W, H, levels));
+}
+
+/* The fault detector itself must fire, or a clean result proves nothing. */
+static void test_sim_detects_faults(void)
+{
+	static struct s1d_sim s;
+	/* A0 and WR# change together */
+	static const uint8_t bad_a0[] = {
+		TCA_REG_OUTPUT0, 0x00,
+		S1D_P1_WR | S1D_P1_RD | S1D_P1_RES | S1D_P1_A0,
+		0x42, S1D_P1_RD | S1D_P1_RES,
+	};
+	static const uint8_t cfg_out[] = { TCA_REG_CONFIG0, 0x00, 0xf0 };
+	static const uint8_t even[] = { TCA_REG_OUTPUT0, 1, 2, 3 };
+	static const uint8_t bad_reg[] = { 0x01, 0 };
+
+	s1d_sim_init(&s);
+	s1d_sim_i2c_write(&s, cfg_out, sizeof(cfg_out));
+	s1d_sim_i2c_write(&s, bad_a0, sizeof(bad_a0));
+	CHECK(s.faults.a0_with_wr_edge == 1);
+	s1d_sim_i2c_write(&s, even, sizeof(even));
+	CHECK(s.faults.short_message == 1);
+	s1d_sim_i2c_write(&s, bad_reg, sizeof(bad_reg));
+	CHECK(s.faults.bad_tca_register == 1);
+}
+
+int main(void)
+{
+	srand(12345);
+
+	test_init();
+	test_invalid_config();
+	test_no_change_no_traffic();
+	test_digit_uses_vertical();
+	test_full_frame_is_one_run();
+	test_gap_merge();
+	test_random_updates(1, 1025);
+	test_random_updates(2, 1025);
+	test_random_updates(4, 1025);
+	test_random_updates(2, 7);	/* smallest legal message */
+	test_random_updates(2, 61);	/* MCP2221-sized reports */
+	test_transport_error_recovers();
+	test_lost_direction_recovers();
+	test_random_failures(7);
+	test_random_failures(61);
+	test_random_failures(1025);
+	test_command_tracks_direction();
+	test_convert();
+	test_sim_render();
+	test_sim_detects_faults();
+
+	if (failures) {
+		printf("%d check(s) failed\n", failures);
+		return 1;
+	}
+	printf("all panel tests passed\n");
+	return 0;
+}