Linux Serial subsystem development
 help / color / mirror / Atom feed
* [PATCH 0/3] serial: max310x: transmit path fixes
@ 2026-11-16  9:57 Tapio Reijonen
  2026-11-16  9:57 ` [PATCH 1/3] serial: max310x: do not advance the TX fifo past a flush Tapio Reijonen
                   ` (2 more replies)
  0 siblings, 3 replies; 7+ messages in thread
From: Tapio Reijonen @ 2026-11-16  9:57 UTC (permalink / raw)
  To: Greg Kroah-Hartman, Jiri Slaby
  Cc: linux-serial, linux-kernel, Hugo Villeneuve, Tapio Reijonen,
	stable

Three fixes for the MAX310x transmit path, found while stress testing
the software-timed RS-485 delays that are new in v7.4.

Patch 1 fixes a race between the transmit work and a flush. The work
advances the fifo after the SPI transfer without the port lock; since
the kfifo conversion in v6.10 a uart_flush_buffer() during the transfer
leaves the fifo length wrapped to about 4G. tcdrain() then never
returns and stale data is sent until the port is closed. It carries
Cc stable, but does not apply to v7.3 and older as it is: the context
is the v7.4 driver. I will send backports for 6.12.y and later.

Patches 2 and 3 fix commit 33632215e1bb ("serial: max310x: drive RTS in
software when hardware delays are too short"), which is in v7.4-rc1.
With patch 2, data written while an envelope is closing no longer
leaves after RTS has been released. With patch 3, a late TX-empty
interrupt of the previous envelope no longer pushes the head of the
next write out before RTS is up. Both lose data silently on an RS-485
bus, so it would be good to have them in v7.4.

Tested on a MAX14830 behind a single-core i.MX6SX, on v7.4-rc3:

- flush during transmission on all four ports, five minutes: the fifo
  length stays within 4096;
- 20 unbinds with a tcdrain() blocked on a slow port: no task is left
  sleeping;
- RS-485 loopback with data verification on three ports, 57600 baud,
  25-byte writes every 20 ms, 20 ms before-send delay, ten minutes:
  no byte lost or misframed. The numbers without patches 2 and 3 are
  in their commit messages;
- baud rate changes at random moments under traffic, each one moving
  the port between chip-timed and driver-timed RTS: 7672 changes in
  ten minutes, no stall, every byte sent;
- TIOCSERGETLSR and tcdrain() polled after every write, 12500 writes:
  the port is never reported idle with data unsent;
- xmit_fifo_size raised to 256 with TIOCSSERIAL: 570000 bytes per
  port, all sent, nothing in the log;
- output stopped with TCOOFF, data queued, baud rate changed: nothing
  is sent while stopped, everything after TCOON;
- TIOCSRS485 repeated every few milliseconds while a second block is
  written at the end of the first, with and without CPU load, 50
  minutes on v7.4-rc2 and v7.4-rc3: 30900 block pairs verified through
  the loopback, none lost.

The envelope timing was checked on a logic analyser with an earlier
version of the three patches, on v7.3-rc7.

Not addressed here, all older than this series:

- an x_char is written without regard to the RTS envelope;
- a reconfigure while stopped output has data queued asserts RTS for
  about one character time;
- by the code, a TIOCSRS485 applied at the very end of an envelope can
  arm the after-send hold while a new write is being pushed, and RTS
  then drops under that write. Patch 2 closes this window for the
  transmit work, not for the work item that applies the ioctl. I could
  not provoke it: see the last test above.
- sc16is7xx advances the transmit fifo after a sleeping write without
  the port lock in the same way; patch 1's race should apply there
  too. I have not looked at that driver further.

I will send the max310x ones separately.

Tool use: Claude Code (Anthropic) was used throughout. It drafted the
code and the commit messages, wrote the test scripts and the hardware
test plans, and analysed the function traces. An LLM review of an
earlier version found two faults, in patches 1 and 3; both were
reproduced on hardware and are fixed in what is posted here. I decided
the approach of each fix, reviewed every change against the code, and
ran the hardware tests. The code and the messages are mine to defend.

Signed-off-by: Tapio Reijonen <tapio.reijonen@vaisala.com>
---
Tapio Reijonen (3):
      serial: max310x: do not advance the TX fifo past a flush
      serial: max310x: re-check the TX queue before the after-send hold
      serial: max310x: hold TX data until the software RTS send phase

 drivers/tty/serial/max310x.c | 122 ++++++++++++++++++++++++++++++++++---------
 1 file changed, 96 insertions(+), 26 deletions(-)
---
base-commit: 6628e7d4c6b25c8d18f1345e3a20d21829aae7e4
change-id: 20261112-max310x-tx-fixes-eba3803195ae

Best regards,
-- 
Tapio Reijonen <tapio.reijonen@vaisala.com>


^ permalink raw reply	[flat|nested] 7+ messages in thread

* [PATCH 1/3] serial: max310x: do not advance the TX fifo past a flush
  2026-11-16  9:57 [PATCH 0/3] serial: max310x: transmit path fixes Tapio Reijonen
@ 2026-11-16  9:57 ` Tapio Reijonen
  2026-11-16 10:18   ` sashiko-bot
  2026-11-16  9:57 ` [PATCH 2/3] serial: max310x: re-check the TX queue before the after-send hold Tapio Reijonen
  2026-11-16  9:57 ` [PATCH 3/3] serial: max310x: hold TX data until the software RTS send phase Tapio Reijonen
  2 siblings, 1 reply; 7+ messages in thread
From: Tapio Reijonen @ 2026-11-16  9:57 UTC (permalink / raw)
  To: Greg Kroah-Hartman, Jiri Slaby
  Cc: linux-serial, linux-kernel, Hugo Villeneuve, Tapio Reijonen,
	stable

max310x_handle_tx() runs from a work item. It peeks at the transmit
fifo with kfifo_out_linear_ptr(), writes the bytes to the chip over
SPI, which sleeps, and advances the fifo afterwards with
uart_xmit_advance(), all without the port lock. uart_flush_buffer()
resets the fifo under the port lock. When the reset lands between the
peek and the advance, the advance adds the chunk length to a read
index that is already zero, the index ends up ahead of the write
index, and kfifo_len() wraps to a value near 4G.

From then on the fifo never reads as empty: tcdrain() sleeps forever
in tty_wait_until_sent(), and while the port stays open the work item
keeps sending stale bytes from the buffer. Observed with a tcdrain()
in flight at 300 baud when the port was hung up by an unbind, which
flushes twice: the first flush left 498 bytes, the second found
4294967217, the draining task read 4294967276 and never woke again.
Before the kfifo conversion the same race left the circular buffer
with up to 4 KiB of stale data to resend, after which it recovered.

Copy the bytes into a per-port buffer under the port lock, send them
from there, and take the lock again for the advance. A flush_buffer()
callback records a reset of the fifo, and the advance is skipped when
one happened during the transfer. kfifo_reset() is documented to
require that no other thread accesses the fifo, so the consumer has to
hold the same lock as the flush.

The bytes stay in the fifo until the chip has them. tx_empty() reads
only the chip FIFO level, so taking them out before the transfer would
make tcdrain() and close() see an idle transmitter with up to one FIFO
load still to be sent.

The lock is not held over the SPI transfer. regmap hands that to the
controller straight from the buffer, which is why the buffer is per
port and not on the stack. The copy is limited to the buffer size: its
length is derived from port->fifosize, which TIOCSSERIAL can change,
and from a FIFO level read from the chip.

Fixes: 1788cf6a91d9 ("tty: serial: switch from circ_buf to kfifo")
Cc: stable@vger.kernel.org
Signed-off-by: Tapio Reijonen <tapio.reijonen@vaisala.com>
---
 drivers/tty/serial/max310x.c | 46 ++++++++++++++++++++++++++++++++++++--------
 1 file changed, 38 insertions(+), 8 deletions(-)

diff --git a/drivers/tty/serial/max310x.c b/drivers/tty/serial/max310x.c
index a0ed70185555eed745d905b36c8b8f162468dd6f..e6a740295b96653281a92f8d94999f06c2c74685 100644
--- a/drivers/tty/serial/max310x.c
+++ b/drivers/tty/serial/max310x.c
@@ -317,11 +317,13 @@ struct max310x_one {
 	bool			sw_rts_during_tx;
 	bool			cancel_tx_delay_tmr;
 	bool			tx_teardown;	/* envelope being torn down */
+	bool			tx_flushed;	/* fifo reset under a transfer */
 	bool			rs485_pending;	/* rs_work not yet applied */
 	bool			tx_break;	/* break_ctl() owns the transceiver */
 	enum max310x_tx_state	tx_state;
 
 	u8 rx_buf[MAX310X_FIFO_SIZE];
+	u8 tx_buf[MAX310X_FIFO_SIZE];
 };
 #define to_max310x_port(_port) \
 	container_of(_port, struct max310x_one, port)
@@ -911,6 +913,7 @@ static void max310x_delayed_stop_tx(struct uart_port *port)
 
 static void max310x_handle_tx(struct uart_port *port)
 {
+	struct max310x_one *one = to_max310x_port(port);
 	struct tty_port *tport = &port->state->port;
 
 	if (unlikely(port->x_char)) {
@@ -931,23 +934,41 @@ static void max310x_handle_tx(struct uart_port *port)
 		return;
 	}
 
-	/*
-	 * It's a circ buffer -- wrap around.
-	 * We could do that in one SPI transaction, but meh.
-	 */
 	while (!kfifo_is_empty(&tport->xmit_fifo)) {
 		unsigned int txlen, to_send;
-		unsigned char *tail;
+		unsigned long flags;
 
 		/* Limit to space available in TX FIFO */
 		txlen = max310x_port_read(port, MAX310X_TXFIFOLVL_REG);
 		txlen = port->fifosize - txlen;
+		txlen = min(txlen, sizeof(one->tx_buf));
 		if (!txlen)
 			break;
 
-		to_send = kfifo_out_linear_ptr(&tport->xmit_fifo, &tail, txlen);
-		max310x_batch_write(port, tail, to_send);
-		uart_xmit_advance(port, to_send);
+		/*
+		 * Copy the bytes under the port lock, but leave them in the
+		 * fifo until the chip has them: an empty fifo with an empty
+		 * chip FIFO reads as an idle transmitter.
+		 */
+		uart_port_lock_irqsave(port, &flags);
+		to_send = kfifo_out_peek(&tport->xmit_fifo, one->tx_buf, txlen);
+		one->tx_flushed = false;
+		uart_port_unlock_irqrestore(port, flags);
+		if (!to_send)
+			break;
+
+		max310x_batch_write(port, one->tx_buf, to_send);
+
+		/*
+		 * uart_flush_buffer() reset the fifo during the transfer:
+		 * advancing now would move the read index past that reset.
+		 */
+		uart_port_lock_irqsave(port, &flags);
+		if (one->tx_flushed)
+			port->icount.tx += to_send;
+		else
+			uart_xmit_advance(port, to_send);
+		uart_port_unlock_irqrestore(port, flags);
 	}
 
 	if (kfifo_len(&tport->xmit_fifo) < WAKEUP_CHARS)
@@ -1094,6 +1115,14 @@ static irqreturn_t max310x_ist(int irq, void *dev_id)
 	return IRQ_RETVAL(handled);
 }
 
+/* called with port.lock taken and irqs off */
+static void max310x_flush_buffer(struct uart_port *port)
+{
+	struct max310x_one *one = to_max310x_port(port);
+
+	one->tx_flushed = true;
+}
+
 static void max310x_tx_proc(struct work_struct *ws)
 {
 	struct max310x_one *one = container_of(ws, struct max310x_one, tx_work);
@@ -1732,6 +1761,7 @@ static const struct uart_ops max310x_ops = {
 	.break_ctl	= max310x_break_ctl,
 	.startup	= max310x_startup,
 	.shutdown	= max310x_shutdown,
+	.flush_buffer	= max310x_flush_buffer,
 	.set_termios	= max310x_set_termios,
 	.type		= max310x_type,
 	.request_port	= max310x_request_port,

-- 
2.47.3


^ permalink raw reply related	[flat|nested] 7+ messages in thread

* [PATCH 2/3] serial: max310x: re-check the TX queue before the after-send hold
  2026-11-16  9:57 [PATCH 0/3] serial: max310x: transmit path fixes Tapio Reijonen
  2026-11-16  9:57 ` [PATCH 1/3] serial: max310x: do not advance the TX fifo past a flush Tapio Reijonen
@ 2026-11-16  9:57 ` Tapio Reijonen
  2026-11-16 10:12   ` sashiko-bot
  2026-11-16  9:57 ` [PATCH 3/3] serial: max310x: hold TX data until the software RTS send phase Tapio Reijonen
  2 siblings, 1 reply; 7+ messages in thread
From: Tapio Reijonen @ 2026-11-16  9:57 UTC (permalink / raw)
  To: Greg Kroah-Hartman, Jiri Slaby
  Cc: linux-serial, linux-kernel, Hugo Villeneuve, Tapio Reijonen

max310x_delayed_stop_tx() decides that a software-timed RS-485 envelope
is over when the transmit queue is empty and the chip's TX FIFO is
empty. It tests the queue first, then reads TXFIFOLVL over the bus, and
only then takes the port lock and arms the after-send hold. The bus read
sleeps, under load for tens of milliseconds, and write() queues data
under the port lock in that window. start_tx() finds the envelope in
MAX310X_TX_SEND and does nothing but reschedule tx_work.

When the stop routine resumes it sees an empty chip FIFO and arms the
hold on a queue that was empty before the read. The hold expires, the
RTS release is scheduled, the rescheduled tx_work pushes the new data
into the chip FIFO, and RTS drops while the chip is still shifting it
out. The tail of the write leaves through a disabled transceiver. No
FIFO overflows, so no counter moves; the loss is silent.

Seen on a MAX14830 behind a slow SPI path with 20 ms of before-send
delay: 25-byte writes every 20 ms lost 1600 to 2200 bytes per port in
five minutes in RS-485 mode and nothing in RS-232 mode under the same
traffic, overrun counters equal; 96-byte writes every 60 ms lost
partial chunks of 14 to 75 bytes a few times per run.

Re-check the queue under the port lock before arming the hold. Data
queued before the check keeps the envelope open and the pending tx_work
ends it once that data has drained; data queued after the hold is
armed is already handled by start_tx(), which cancels the hold.

Fixes: 33632215e1bb ("serial: max310x: drive RTS in software when hardware delays are too short")
Signed-off-by: Tapio Reijonen <tapio.reijonen@vaisala.com>
---
 drivers/tty/serial/max310x.c | 8 ++++++++
 1 file changed, 8 insertions(+)

diff --git a/drivers/tty/serial/max310x.c b/drivers/tty/serial/max310x.c
index e6a740295b96653281a92f8d94999f06c2c74685..7ddfe8773faf9bc51621c49fa5d8e7d6b1e4bc34 100644
--- a/drivers/tty/serial/max310x.c
+++ b/drivers/tty/serial/max310x.c
@@ -897,6 +897,14 @@ static void max310x_delayed_stop_tx(struct uart_port *port)
 	    READ_ONCE(one->tx_state) != MAX310X_TX_SEND)
 		return;
 
+	/*
+	 * Data queued while TXFIFOLVL was read: start_tx() saw SEND and only
+	 * rescheduled tx_work, so arming the hold now would drop RTS under it.
+	 */
+	if (!kfifo_is_empty(&port->state->port.xmit_fifo) &&
+	    !uart_tx_stopped(port))
+		return;
+
 	if (!hrtimer_active(&one->tx_delay_tmr)) {
 		/*
 		 * Add one character for the byte still in the shift register -

-- 
2.47.3


^ permalink raw reply related	[flat|nested] 7+ messages in thread

* [PATCH 3/3] serial: max310x: hold TX data until the software RTS send phase
  2026-11-16  9:57 [PATCH 0/3] serial: max310x: transmit path fixes Tapio Reijonen
  2026-11-16  9:57 ` [PATCH 1/3] serial: max310x: do not advance the TX fifo past a flush Tapio Reijonen
  2026-11-16  9:57 ` [PATCH 2/3] serial: max310x: re-check the TX queue before the after-send hold Tapio Reijonen
@ 2026-11-16  9:57 ` Tapio Reijonen
  2026-11-16 10:34   ` sashiko-bot
  2 siblings, 1 reply; 7+ messages in thread
From: Tapio Reijonen @ 2026-11-16  9:57 UTC (permalink / raw)
  To: Greg Kroah-Hartman, Jiri Slaby
  Cc: linux-serial, linux-kernel, Hugo Villeneuve, Tapio Reijonen

On the software-timed RS-485 path, start_tx() begins an envelope by
setting MAX310X_TX_WAIT_BEFORE_SEND and queuing the RTS worker; the
data may only go to the chip once the before-send timer has moved the
envelope to MAX310X_TX_SEND and scheduled tx_work. Nothing enforced
that: max310x_handle_tx() pushed whatever was queued whenever it ran.

The chip latches its TX-empty interrupt when the last byte of the
previous envelope leaves the FIFO. Under load the IRQ thread reads that
bit late, after the next write has started a new envelope, and
schedules tx_work for it. That run found the new data and pushed it
into the FIFO while RTS was still down or the setup delay still
running; the chip transmitted at once, the head of the write left
through a disabled transceiver and the receiver saw the rest misframed.

Seen on a MAX14830 with a 20 ms before-send delay: with 25-byte writes
every 20 ms, 33 to 88 such losses per port in five minutes remained
after the after-send race was fixed, several of them as misframed
bytes.

Hold the data while the envelope is not in its send phase. The
before-send timer schedules tx_work when it moves the envelope to
MAX310X_TX_SEND, and so does a write arriving during a send, so the
data leaves as soon as RTS is up.

One more path enters MAX310X_TX_SEND, and it does not schedule
tx_work: a set_termios() that moves a running transfer from chip-timed
to driver-timed RTS adopts it in max310x_adopt_hw_tx(). A tx_work that
runs after the path has changed and before the adoption is now held,
and with the chip FIFO empty nothing sends the queued data until the
serial core's runtime PM calls start_tx() about 0.5 s later. With only
the hold in place, 10 of 338 baud rate changes made near the end of a
chip FIFO load stalled for 370 to 490 ms. Restart the transmission at
the end of set_termios() the way rs_work does after an RS485
reconfigure, through a helper for both. The helper leaves stopped
output alone, as serial core does.

A software envelope between two FIFO loads looks the same as an
adopted transfer, so a set_termios() that lands there restarts it as
well: RTS stays asserted and the rest of the data waits for one more
before-send delay. rs_work has always done that for TIOCSRS485.

The comment in the IRQ handler said that a stale TX-empty interrupt
cannot push data during the setup delay; correct it. The hold does
not apply to the hardware RTS path, which does not use tx_state.

Fixes: 33632215e1bb ("serial: max310x: drive RTS in software when hardware delays are too short")
Signed-off-by: Tapio Reijonen <tapio.reijonen@vaisala.com>
---
 drivers/tty/serial/max310x.c | 72 ++++++++++++++++++++++++++++++++------------
 1 file changed, 52 insertions(+), 20 deletions(-)

diff --git a/drivers/tty/serial/max310x.c b/drivers/tty/serial/max310x.c
index 7ddfe8773faf9bc51621c49fa5d8e7d6b1e4bc34..d92bf241558862cd83073c1d12ec9f0aaf88f090 100644
--- a/drivers/tty/serial/max310x.c
+++ b/drivers/tty/serial/max310x.c
@@ -942,6 +942,16 @@ static void max310x_handle_tx(struct uart_port *port)
 		return;
 	}
 
+	/*
+	 * Outside the send phase of a software envelope RTS is down, still
+	 * in its setup delay, or about to drop: a late TX-empty interrupt
+	 * must not push the data out now. start_tx() opens an envelope and
+	 * tmr_tx() reschedules us at MAX310X_TX_SEND.
+	 */
+	if (READ_ONCE(one->sw_rts_during_tx) &&
+	    READ_ONCE(one->tx_state) != MAX310X_TX_SEND)
+		return;
+
 	while (!kfifo_is_empty(&tport->xmit_fifo)) {
 		unsigned int txlen, to_send;
 		unsigned long flags;
@@ -1077,8 +1087,8 @@ static irqreturn_t max310x_port_irq(struct max310x_port *s, int portno)
 		if (rxlen)
 			max310x_handle_rx(port, rxlen);
 		/*
-		 * TXEMPTY latches on the FIFO becoming empty, so a stale
-		 * interrupt cannot pump data during an RTS setup delay.
+		 * A TX-empty read late can belong to the previous envelope;
+		 * max310x_handle_tx() holds the data until the send phase.
 		 */
 		if (ists & MAX310X_IRQ_TXEMPTY_BIT)
 			schedule_work(&s->p[portno].tx_work);
@@ -1314,6 +1324,28 @@ static void max310x_set_rts_ctl_params(struct max310x_one *one)
 			    MAX310X_IRDA_RTSINVERT_BIT, irda);
 }
 
+/*
+ * A reconfigure is applied: restart a transmission that it left queued, on
+ * the path that is now configured. A send state without chip data has
+ * nothing in flight: restart it as a fresh envelope so the before-send delay
+ * is honoured. start_tx() can drop and retake the lock through the uart_port
+ * API - callers must take it with uart_port_lock*(), not a spinlock guard.
+ */
+static void max310x_restart_tx(struct max310x_one *one, bool chip_tx_empty)
+{
+	struct uart_port *port = &one->port;
+
+	lockdep_assert_held(&port->lock);
+
+	if (!port->x_char && (kfifo_is_empty(&port->state->port.xmit_fifo) ||
+			      uart_tx_stopped(port)))
+		return;
+
+	if (chip_tx_empty && READ_ONCE(one->tx_state) == MAX310X_TX_SEND)
+		WRITE_ONCE(one->tx_state, MAX310X_TX_OFF);
+	max310x_start_tx(port);
+}
+
 static void max310x_break_ctl(struct uart_port *port, int break_state)
 {
 	struct max310x_one *one = to_max310x_port(port);
@@ -1363,7 +1395,10 @@ static void max310x_set_termios(struct uart_port *port,
 				const struct ktermios *old)
 {
 	unsigned int frame_bits = tty_get_frame_size(termios->c_cflag);
+	struct max310x_one *one = to_max310x_port(port);
 	unsigned int lcr = 0, flow = 0;
+	unsigned long flags;
+	bool chip_tx_empty;
 	int baud;
 
 	/* Mask termios capabilities we don't support */
@@ -1482,10 +1517,19 @@ static void max310x_set_termios(struct uart_port *port,
 	 * taking over an in-flight transfer arms the after-send hold from
 	 * the character time.
 	 */
-	to_max310x_port(port)->baud = baud;
-	to_max310x_port(port)->char_time_us =
-		DIV_ROUND_UP(USEC_PER_SEC * frame_bits, baud);
-	max310x_set_rts_ctl_params(to_max310x_port(port));
+	one->baud = baud;
+	one->char_time_us = DIV_ROUND_UP(USEC_PER_SEC * frame_bits, baud);
+	max310x_set_rts_ctl_params(one);
+
+	/*
+	 * A tx_work that ran while the RTS path was switched above has
+	 * returned without sending, and nothing else pushes the data it left.
+	 */
+	chip_tx_empty = !max310x_port_read(port, MAX310X_TXFIFOLVL_REG);
+
+	uart_port_lock_irqsave(port, &flags);
+	max310x_restart_tx(one, chip_tx_empty);
+	uart_port_unlock_irqrestore(port, flags);
 }
 
 static void max310x_rs_proc(struct work_struct *ws)
@@ -1518,26 +1562,14 @@ static void max310x_rs_proc(struct work_struct *ws)
 	/*
 	 * The configuration is applied: release any TX that start_tx()
 	 * deferred while the reconfigure was pending, now on the right
-	 * path. start_tx() can drop and retake the lock through the
-	 * uart_port API - a raw spinlock guard here would unbalance it.
+	 * path.
 	 */
 	chip_tx_empty = !max310x_port_read(&one->port,
 					   MAX310X_TXFIFOLVL_REG);
 
 	uart_port_lock_irqsave(&one->port, &flags);
 	one->rs485_pending = false;
-	if (one->port.x_char ||
-	    !kfifo_is_empty(&one->port.state->port.xmit_fifo)) {
-		/*
-		 * A send state adopted without chip data is the deferred
-		 * write itself: restart it as a fresh envelope so the
-		 * before-send delay is honoured.
-		 */
-		if (chip_tx_empty &&
-		    READ_ONCE(one->tx_state) == MAX310X_TX_SEND)
-			WRITE_ONCE(one->tx_state, MAX310X_TX_OFF);
-		max310x_start_tx(&one->port);
-	}
+	max310x_restart_tx(one, chip_tx_empty);
 	uart_port_unlock_irqrestore(&one->port, flags);
 }
 

-- 
2.47.3


^ permalink raw reply related	[flat|nested] 7+ messages in thread

* Re: [PATCH 2/3] serial: max310x: re-check the TX queue before the after-send hold
  2026-11-16  9:57 ` [PATCH 2/3] serial: max310x: re-check the TX queue before the after-send hold Tapio Reijonen
@ 2026-11-16 10:12   ` sashiko-bot
  0 siblings, 0 replies; 7+ messages in thread
From: sashiko-bot @ 2026-11-16 10:12 UTC (permalink / raw)
  To: Tapio Reijonen; +Cc: linux-serial

> max310x_delayed_stop_tx() decides that a software-timed RS-485 envelope
> is over when the transmit queue is empty and the chip's TX FIFO is
> empty. It tests the queue first, then reads TXFIFOLVL over the bus, and
> only then takes the port lock and arms the after-send hold. The bus read
> sleeps, under load for tens of milliseconds, and write() queues data
> under the port lock in that window. start_tx() finds the envelope in
> MAX310X_TX_SEND and does nothing but reschedule tx_work.
> 
> When the stop routine resumes it sees an empty chip FIFO and arms the
> hold on a queue that was empty before the read. The hold expires, the
> RTS release is scheduled, the rescheduled tx_work pushes the new data
> into the chip FIFO, and RTS drops while the chip is still shifting it
> out. The tail of the write leaves through a disabled transceiver. No
> FIFO overflows, so no counter moves; the loss is silent.
> 
> Seen on a MAX14830 behind a slow SPI path with 20 ms of before-send
> delay: 25-byte writes every 20 ms lost 1600 to 2200 bytes per port in
> five minutes in RS-485 mode and nothing in RS-232 mode under the same
> traffic, overrun counters equal; 96-byte writes every 60 ms lost
> partial chunks of 14 to 75 bytes a few times per run.
> 
> Re-check the queue under the port lock before arming the hold. Data
> queued before the check keeps the envelope open and the pending tx_work
> ends it once that data has drained; data queued after the hold is
> armed is already handled by start_tx(), which cancels the hold.
> 
> Fixes: 33632215e1bb ("serial: max310x: drive RTS in software when hardware delays are too short")
> Signed-off-by: Tapio Reijonen <tapio.reijonen@vaisala.com>

Sashiko has reviewed this patch and found no issues.

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/20261116-max310x-tx-fixes-v1-0-61c01f180911@vaisala.com?part=2


^ permalink raw reply	[flat|nested] 7+ messages in thread

* Re: [PATCH 1/3] serial: max310x: do not advance the TX fifo past a flush
  2026-11-16  9:57 ` [PATCH 1/3] serial: max310x: do not advance the TX fifo past a flush Tapio Reijonen
@ 2026-11-16 10:18   ` sashiko-bot
  0 siblings, 0 replies; 7+ messages in thread
From: sashiko-bot @ 2026-11-16 10:18 UTC (permalink / raw)
  To: Tapio Reijonen; +Cc: linux-serial

Thank you for your contribution! Sashiko AI review found no new issues
in this patch, but noticed 1 related pre-existing issue it does not
introduce:
- [Critical] serial: max310x: out-of-bounds write in max310x_handle_rx()
  [1]
--

commit 12622456e1b4a71d597213ac90888e9dce7b8d1e
Author: Tapio Reijonen <tapio.reijonen@vaisala.com>

serial: max310x: do not advance the TX fifo past a flush

This commit copies outgoing bytes into a per-port buffer under the port
lock before transmitting over SPI and skips advancing the TX kfifo if
uart_flush_buffer() ran during the transfer.

> diff --git a/drivers/tty/serial/max310x.c b/drivers/tty/serial/max310x.c
> index a0ed70185555e..e6a740295b966 100644
> --- a/drivers/tty/serial/max310x.c
> +++ b/drivers/tty/serial/max310x.c
> @@ -317,11 +317,13 @@ struct max310x_one {
>  	bool			sw_rts_during_tx;
>  	bool			cancel_tx_delay_tmr;
>  	bool			tx_teardown;	/* envelope being torn down */
> +	bool			tx_flushed;	/* fifo reset under a transfer */
>  	bool			rs485_pending;	/* rs_work not yet applied */
>  	bool			tx_break;	/* break_ctl() owns the transceiver */
>  	enum max310x_tx_state	tx_state;
>  
>  	u8 rx_buf[MAX310X_FIFO_SIZE];
> +	u8 tx_buf[MAX310X_FIFO_SIZE];
>  };
>  #define to_max310x_port(_port) \
>  	container_of(_port, struct max310x_one, port)

[ ... ]

> @@ -931,23 +934,41 @@ static void max310x_handle_tx(struct uart_port *port)
>  		return;
>  	}
>  
> -	/*
> -	 * It's a circ buffer -- wrap around.
> -	 * We could do that in one SPI transaction, but meh.
> -	 */
>  	while (!kfifo_is_empty(&tport->xmit_fifo)) {
>  		unsigned int txlen, to_send;
> -		unsigned char *tail;
> +		unsigned long flags;
>  
>  		/* Limit to space available in TX FIFO */
>  		txlen = max310x_port_read(port, MAX310X_TXFIFOLVL_REG);
>  		txlen = port->fifosize - txlen;
> +		txlen = min(txlen, sizeof(one->tx_buf));

[Severity: Critical]
This problem wasn't introduced by this patch, but can max310x_handle_rx()
overflow one->rx_buf in the batched read path [1]?

drivers/tty/serial/max310x.c:max310x_handle_rx() {
	...
	if (port->read_status_mask == MAX310X_LSR_RXOVR_BIT) {
		...
		sts = max310x_port_read(port, MAX310X_LSR_IRQSTS_REG);
		max310x_batch_read(port, one->rx_buf, rxlen);
	...
	} else {
		if (unlikely(rxlen >= port->fifosize)) {
			dev_warn_ratelimited(port->dev, "Possible RX FIFO overrun\n");
			port->icount.buf_overrun++;
			/* Ensure sanity of RX level */
			rxlen = port->fifosize;
		}
	...
}

Unlike the non-batched branch (and the new txlen clamp above), the batched
branch passes rxlen read from MAX310X_RXFIFOLVL_REG straight to
max310x_batch_read() without clamping it to sizeof(one->rx_buf).  If the
chip reports a length larger than MAX310X_FIFO_SIZE (128 bytes),
regmap_noinc_read() writes past the end of one->rx_buf and corrupts the
enclosing struct max310x_port allocation.

[1] https://sashiko.dev/#/bug/linux-faf2b0a9-9b3f-4e76-a18b-7e85a4d79395

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/20261116-max310x-tx-fixes-v1-0-61c01f180911@vaisala.com?part=1

^ permalink raw reply	[flat|nested] 7+ messages in thread

* Re: [PATCH 3/3] serial: max310x: hold TX data until the software RTS send phase
  2026-11-16  9:57 ` [PATCH 3/3] serial: max310x: hold TX data until the software RTS send phase Tapio Reijonen
@ 2026-11-16 10:34   ` sashiko-bot
  0 siblings, 0 replies; 7+ messages in thread
From: sashiko-bot @ 2026-11-16 10:34 UTC (permalink / raw)
  To: Tapio Reijonen; +Cc: linux-serial

Thank you for your contribution! Sashiko AI review found 3 potential
issues to consider:
- [Medium] serial: max310x: max310x_adopt_hw_tx() bypasses send-phase
  hold on empty FIFO
- [Medium] serial: max310x: x_char sent before software RTS send-phase
  check
- [Medium] serial: max310x: early return in max310x_restart_tx() strands
  TX_SEND state
It also noticed 2 related pre-existing issues this patch does not
introduce:
- [High] serial: max310x: missing port lock in max310x_port_irq() [1]
- [Medium] serial: max310x: unprotected port->status modification in
  max310x_set_termios() [2]
--

commit c6e5f39e8c525f49645d0ceb47c724d2102f907b
Author: Tapio Reijonen <tapio.reijonen@vaisala.com>

serial: max310x: hold TX data until the software RTS send phase

This commit holds queued TX data in max310x_handle_tx() until the
software-timed RS-485 RTS envelope reaches MAX310X_TX_SEND, and adds
max310x_restart_tx() to restart pending transmissions after set_termios()
and RS-485 reconfiguration.

> diff --git a/drivers/tty/serial/max310x.c b/drivers/tty/serial/max310x.c
> index 7ddfe8773faf9..d92bf24155886 100644
> --- a/drivers/tty/serial/max310x.c
> +++ b/drivers/tty/serial/max310x.c
> @@ -942,6 +942,16 @@ static void max310x_handle_tx(struct uart_port *port)
>  		return;
>  	}
>  
> +	/*
> +	 * Outside the send phase of a software envelope RTS is down, still
> +	 * in its setup delay, or about to drop: a late TX-empty interrupt
> +	 * must not push the data out now. start_tx() opens an envelope and
> +	 * tmr_tx() reschedules us at MAX310X_TX_SEND.
> +	 */
> +	if (READ_ONCE(one->sw_rts_during_tx) &&
> +	    READ_ONCE(one->tx_state) != MAX310X_TX_SEND)
> +		return;
> +
>  	while (!kfifo_is_empty(&tport->xmit_fifo)) {
>  		unsigned int txlen, to_send;
>  		unsigned long flags;

[Severity: Medium]
Can port->x_char still be sent before the software RTS envelope reaches
MAX310X_TX_SEND?

At the top of max310x_handle_tx(), port->x_char is written to
MAX310X_THR_REG and cleared before this send-phase check:

drivers/tty/serial/max310x.c:max310x_handle_tx() {
	if (unlikely(port->x_char)) {
		max310x_port_write(port, MAX310X_THR_REG, port->x_char);
		port->icount.tx++;
		port->x_char = 0;
		return;
	}

When uart_send_xchar() calls max310x_start_tx() on the software RTS path,
it opens an envelope in MAX310X_TX_WAIT_BEFORE_SEND.  If a late TX-empty
interrupt from the previous envelope schedules tx_work before the
before-send timer expires, max310x_handle_tx() transmits port->x_char while
RTS is still deasserted or in its setup delay, losing or misframing the
flow-control byte.

> @@ -1077,8 +1087,8 @@ static irqreturn_t max310x_port_irq(struct max310x_port *s, int portno)
>  		if (rxlen)
>  			max310x_handle_rx(port, rxlen);
>  		/*
> -		 * TXEMPTY latches on the FIFO becoming empty, so a stale
> -		 * interrupt cannot pump data during an RTS setup delay.
> +		 * A TX-empty read late can belong to the previous envelope;
> +		 * max310x_handle_tx() holds the data until the send phase.
>  		 */
>  		if (ists & MAX310X_IRQ_TXEMPTY_BIT)
>  			schedule_work(&s->p[portno].tx_work);

[Severity: High]
This problem wasn't introduced by this patch, but max310x_port_irq() calls
uart_handle_cts_change() without holding port->lock [1]:

drivers/tty/serial/max310x.c:max310x_port_irq() {
		if (ists & MAX310X_IRQ_CTS_BIT) {
			lsr = max310x_port_read(port, MAX310X_LSR_IRQSTS_REG);
			uart_handle_cts_change(port, lsr & MAX310X_LSR_CTS_BIT);
		}

uart_handle_cts_change() requires the caller to hold port->lock (checked via
lockdep_assert_held_once(&uport->lock)), so a CTS interrupt triggers a
lockdep warning and races on port->hw_stopped, port->icount.cts, and TX
start/stop state.

> @@ -1314,6 +1324,28 @@ static void max310x_set_rts_ctl_params(struct max310x_one *one)
>  			    MAX310X_IRDA_RTSINVERT_BIT, irda);
>  }
>  
> +/*
> + * A reconfigure is applied: restart a transmission that it left queued, on
> + * the path that is now configured. A send state without chip data has
> + * nothing in flight: restart it as a fresh envelope so the before-send delay
> + * is honoured. start_tx() can drop and retake the lock through the uart_port
> + * API - callers must take it with uart_port_lock*(), not a spinlock guard.
> + */
> +static void max310x_restart_tx(struct max310x_one *one, bool chip_tx_empty)
> +{
> +	struct uart_port *port = &one->port;
> +
> +	lockdep_assert_held(&port->lock);
> +
> +	if (!port->x_char && (kfifo_is_empty(&port->state->port.xmit_fifo) ||
> +			      uart_tx_stopped(port)))
> +		return;
> +
> +	if (chip_tx_empty && READ_ONCE(one->tx_state) == MAX310X_TX_SEND)
> +		WRITE_ONCE(one->tx_state, MAX310X_TX_OFF);
> +	max310x_start_tx(port);
> +}

[Severity: Medium]
Can returning early in max310x_restart_tx() when xmit_fifo is empty or
uart_tx_stopped(port) is true leave one->tx_state stranded in
MAX310X_TX_SEND with RTS asserted?

When max310x_set_rts_ctl_params() adopts a transfer with an empty chip FIFO
and queued data in xmit_fifo, max310x_adopt_hw_tx() sets one->tx_state to
MAX310X_TX_SEND, asserts RTS, and calls max310x_delayed_stop_tx(), which
returns early without arming tx_delay_tmr because xmit_fifo is non-empty
and unstopped:

CPU0                                  CPU1
max310x_set_termios()
  max310x_set_rts_ctl_params()
    max310x_adopt_hw_tx()
      one->tx_state = MAX310X_TX_SEND
    max310x_rts_ctl(..., true)
    max310x_delayed_stop_tx()
      /* xmit_fifo not empty: returns */
  /* unlocked SPI/I2C writes */
                                      uart_flush_buffer()
                                        kfifo_reset(&tport->xmit_fifo)
  max310x_restart_tx(one, true)
    if (kfifo_is_empty(...))
      return;  <-- tx_state stuck at MAX310X_TX_SEND

Because the chip TX FIFO is already empty, no TXEMPTY interrupt will fire
to arm the after-send timer, leaving RTS permanently asserted on the RS-485
bus until a later write or port close.  In addition, max310x_adopt_hw_tx()
does not check uart_tx_stopped(port), so reconfiguring while TX is stopped
with bytes in xmit_fifo adopts the stopped queue and asserts RTS on an idle
bus.

> @@ -1363,7 +1395,10 @@ static void max310x_set_termios(struct uart_port *port,
>  				const struct ktermios *old)
>  {
>  	unsigned int frame_bits = tty_get_frame_size(termios->c_cflag);
> +	struct max310x_one *one = to_max310x_port(port);
>  	unsigned int lcr = 0, flow = 0;
> +	unsigned long flags;
> +	bool chip_tx_empty;
>  	int baud;

[Severity: Medium]
This problem wasn't introduced by this patch, but max310x_set_termios()
modifies port->status without holding port->lock [2]:

drivers/tty/serial/max310x.c:max310x_set_termios() {
	port->status &= ~(UPSTAT_AUTOCTS | UPSTAT_AUTORTS | UPSTAT_AUTOXOFF);

	if (termios->c_cflag & CRTSCTS) {
		/* Enable AUTORTS and AUTOCTS */
		port->status |= UPSTAT_AUTOCTS | UPSTAT_AUTORTS;
    ...
	if (termios->c_iflag & IXOFF) {
		port->status |= UPSTAT_AUTOXOFF;

serial_core requires holding port->lock (along with termios_rwsem and the
port mutex) when modifying port->status so updates do not race with
concurrent serial core and interrupt handlers.

> @@ -1482,10 +1517,19 @@ static void max310x_set_termios(struct uart_port *port,
>  	 * taking over an in-flight transfer arms the after-send hold from
>  	 * the character time.
>  	 */
> -	to_max310x_port(port)->baud = baud;
> -	to_max310x_port(port)->char_time_us =
> -		DIV_ROUND_UP(USEC_PER_SEC * frame_bits, baud);
> -	max310x_set_rts_ctl_params(to_max310x_port(port));
> +	one->baud = baud;
> +	one->char_time_us = DIV_ROUND_UP(USEC_PER_SEC * frame_bits, baud);
> +	max310x_set_rts_ctl_params(one);
> +
> +	/*
> +	 * A tx_work that ran while the RTS path was switched above has
> +	 * returned without sending, and nothing else pushes the data it left.
> +	 */
> +	chip_tx_empty = !max310x_port_read(port, MAX310X_TXFIFOLVL_REG);
> +
> +	uart_port_lock_irqsave(port, &flags);
> +	max310x_restart_tx(one, chip_tx_empty);
> +	uart_port_unlock_irqrestore(port, flags);
>  }

[Severity: Medium]
Can tx_work run between max310x_adopt_hw_tx() and max310x_restart_tx() when
the chip FIFO is empty, bypassing the send-phase hold?

In max310x_adopt_hw_tx(), a non-empty xmit_fifo causes one->tx_state to be
set to MAX310X_TX_SEND even when MAX310X_TXFIFOLVL_REG is 0:

drivers/tty/serial/max310x.c:max310x_adopt_hw_tx() {
	if (!max310x_port_read(port, MAX310X_TXFIFOLVL_REG) &&
	    kfifo_is_empty(&port->state->port.xmit_fifo))
		return false;

	scoped_guard(spinlock_irqsave, &port->lock) {
		if (one->tx_teardown)
			return false;
		if (READ_ONCE(one->tx_state) != MAX310X_TX_OFF)
			return true;
		WRITE_ONCE(one->tx_state, MAX310X_TX_SEND);
		one->cancel_tx_delay_tmr = false;
	}

Between that store and max310x_restart_tx() rewinding one->tx_state back to
MAX310X_TX_OFF, the driver performs several sleeping SPI/I2C register
accesses:

CPU0                                  CPU1 (kworker)
max310x_set_termios()
  max310x_set_rts_ctl_params()
    max310x_adopt_hw_tx()
      /* TXFIFOLVL == 0, xmit_fifo != empty */
      one->tx_state = MAX310X_TX_SEND
                                      max310x_handle_tx()
                                        /* sees tx_state == MAX310X_TX_SEND */
                                        max310x_batch_write()  <-- no setup delay
    max310x_rts_ctl(..., true)
    ...
  max310x_restart_tx()

Any tx_work running in that window (or scheduled by a concurrent
max310x_start_tx() that sees MAX310X_TX_SEND) passes the new check in
max310x_handle_tx() and pushes bytes into the chip FIFO before RTS is
asserted and before delay_rts_before_send has elapsed.

[1] https://sashiko.dev/#/bug/linux-f1129200-a607-415f-a0e8-4690c614c508
[2] https://sashiko.dev/#/bug/linux-9474384d-0d83-420d-ac64-f26b48f8e734

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/20261116-max310x-tx-fixes-v1-0-61c01f180911@vaisala.com?part=3

^ permalink raw reply	[flat|nested] 7+ messages in thread

end of thread, other threads:[~2026-11-16 10:34 UTC | newest]

Thread overview: 7+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2026-11-16  9:57 [PATCH 0/3] serial: max310x: transmit path fixes Tapio Reijonen
2026-11-16  9:57 ` [PATCH 1/3] serial: max310x: do not advance the TX fifo past a flush Tapio Reijonen
2026-11-16 10:18   ` sashiko-bot
2026-11-16  9:57 ` [PATCH 2/3] serial: max310x: re-check the TX queue before the after-send hold Tapio Reijonen
2026-11-16 10:12   ` sashiko-bot
2026-11-16  9:57 ` [PATCH 3/3] serial: max310x: hold TX data until the software RTS send phase Tapio Reijonen
2026-11-16 10:34   ` sashiko-bot

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox