s1d13700-recommendations.md 17 KB

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:

#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
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.

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:

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.

#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():

struct s1d_device *s = container_of(to_delayed_work(work), struct s1d_device,
				    flush_work);

Replace the update call and its error handling:

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:

/* 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:

/* 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:

/* 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:

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.

/* 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:

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:

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:

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