Skip to contentSkip to conversation

tty: n_tty: read termios under lock in poll

PATCH In review Cen Zhang 2 participants 2 messages May 10 TTY layer and serial drivers

lore
Share & tools
lore

Cen Zhang

author
#0 lore raw

PATCH 1/1 tty: n_tty: read termios under lock in poll

n_tty_poll() uses input_available_p() to decide whether buffered input makes the tty readable. That helper reads termios state through L_EXTPROC(), VMIN, and VTIME, but the poll path does not hold the read side of tty->termios_rwsem.

tty_set_termios() updates tty->termios under the write side of the same semaphore, including c_lflag and c_cc[]. n_tty_read() already takes the read side before reading the same termios fields and before calling input_available_p(). Protect the poll-side readiness checks the same way so poll observes a coherent termios state when deciding whether to report readable input.

Do not hold termios_rwsem across tty_buffer_flush_work(), matching the read path which drops the semaphore before flushing pending receive work and then checks input availability again after reacquiring it.

---
 drivers/tty/n_tty.c | 12 ++++++++----
 1 file changed, 8 insertions(+), 4 deletions(-)
drivers/tty/n_tty.c +8 -4
index e6a0f5b40d0a..c8e1882782db 100644
@@ -2437,13 +2437,17 @@ static __poll_t n_tty_poll(struct tty_struct *tty, struct file *file,
 
 	poll_wait(file, &tty->read_wait, wait);
 	poll_wait(file, &tty->write_wait, wait);
-	if (input_available_p(tty, 1))
-		mask |= EPOLLIN | EPOLLRDNORM;
-	else {
-		tty_buffer_flush_work(tty->port);
+	scoped_guard(rwsem_read, &tty->termios_rwsem) {
 		if (input_available_p(tty, 1))
 			mask |= EPOLLIN | EPOLLRDNORM;
 	}
+	if (!(mask & (EPOLLIN | EPOLLRDNORM))) {
+		tty_buffer_flush_work(tty->port);
+		scoped_guard(rwsem_read, &tty->termios_rwsem) {
+			if (input_available_p(tty, 1))
+				mask |= EPOLLIN | EPOLLRDNORM;
+		}
+	}
 	if (tty->ctrl.packet && tty->link->ctrl.pktstatus)
 		mask |= EPOLLPRI | EPOLLIN | EPOLLRDNORM;
 	if (test_bit(TTY_OTHER_CLOSED, &tty->flags))
Signature · 1 line
2.43.0
maintainer
#1 lore raw
Quoted 11 lines · Cen Zhang

n_tty_poll() uses input_available_p() to decide whether buffered input makes the tty readable. That helper reads termios state through L_EXTPROC(), VMIN, and VTIME, but the poll path does not hold the read side of tty->termios_rwsem.

tty_set_termios() updates tty->termios under the write side of the same semaphore, including c_lflag and c_cc[]. n_tty_read() already takes the read side before reading the same termios fields and before calling input_available_p(). Protect the poll-side readiness checks the same way so poll observes a coherent termios state when deciding whether to report readable input.

But why does that matter? If it changes right after you grab/release the lock, the data will be stale as well. What userspace logic is broken because of there not being a lock held here?

thanks,

greg k-h