1 // SPDX-License-Identifier: GPL-1.0+
3 * n_tty.c --- implements the N_TTY line discipline.
5 * This code used to be in tty_io.c, but things are getting hairy
6 * enough that it made sense to split things off. (The N_TTY
7 * processing has changed so much that it's hardly recognizable,
10 * Note that the open routine for N_TTY is guaranteed never to return
11 * an error. This is because Linux will fall back to setting a line
12 * to N_TTY if it can not switch to any other line discipline.
14 * Written by Theodore Ts'o, Copyright 1994.
16 * This file also contains code originally written by Linus Torvalds,
17 * Copyright 1991, 1992, 1993, and by Julian Cowley, Copyright 1994.
19 * Reduced memory usage for older ARM systems - Russell King.
21 * 2000/01/20 Fixed SMP locking on put_tty_queue using bits of
22 * the patch by Andrew J. Kroll <ag784@freenet.buffalo.edu>
23 * who actually finally proved there really was a race.
25 * 2002/03/18 Implemented n_tty_wakeup to send SIGIO POLL_OUTs to
26 * waiting writing processes-Sapan Bhatia <sapan@corewars.org>.
27 * Also fixed a bug in BLOCKING mode where n_tty_write returns
31 #include <linux/bitmap.h>
32 #include <linux/bitops.h>
33 #include <linux/ctype.h>
34 #include <linux/errno.h>
35 #include <linux/export.h>
36 #include <linux/fcntl.h>
37 #include <linux/file.h>
38 #include <linux/jiffies.h>
39 #include <linux/math.h>
40 #include <linux/poll.h>
41 #include <linux/ratelimit.h>
42 #include <linux/sched.h>
43 #include <linux/signal.h>
44 #include <linux/slab.h>
45 #include <linux/string.h>
46 #include <linux/tty.h>
47 #include <linux/types.h>
48 #include <linux/uaccess.h>
49 #include <linux/vmalloc.h>
54 * Until this number of characters is queued in the xmit buffer, select will
55 * return "we have room for writes".
57 #define WAKEUP_CHARS 256
59 #define N_TTY_BUF_SIZE 4096
62 * This defines the low- and high-watermarks for throttling and
63 * unthrottling the TTY driver. These watermarks are used for
64 * controlling the space in the read buffer.
66 #define TTY_THRESHOLD_THROTTLE 128 /* now based on remaining room */
67 #define TTY_THRESHOLD_UNTHROTTLE 128
70 * Special byte codes used in the echo buffer to represent operations
71 * or special handling of characters. Bytes in the echo buffer that
72 * are not part of such special blocks are treated as normal character
75 #define ECHO_OP_START 0xff
76 #define ECHO_OP_MOVE_BACK_COL 0x80
77 #define ECHO_OP_SET_CANON_COL 0x81
78 #define ECHO_OP_ERASE_TAB 0x82
80 #define ECHO_COMMIT_WATERMARK 256
81 #define ECHO_BLOCK 256
82 #define ECHO_DISCARD_WATERMARK N_TTY_BUF_SIZE - (ECHO_BLOCK + 32)
85 /* producer-published */
92 DECLARE_BITMAP(char_map, 256);
94 /* private to n_tty_receive_overrun (single-threaded) */
95 unsigned long overrun_time;
96 unsigned int num_overrun;
101 /* must hold exclusive termios_rwsem to reset these */
102 unsigned char lnext:1, erasing:1, raw:1, real_raw:1, icanon:1;
103 unsigned char push:1;
105 /* shared by producer and consumer */
106 u8 read_buf[N_TTY_BUF_SIZE];
107 DECLARE_BITMAP(read_flags, N_TTY_BUF_SIZE);
108 u8 echo_buf[N_TTY_BUF_SIZE];
110 /* consumer-published */
114 /* # of chars looked ahead (to find software flow control chars) */
115 size_t lookahead_count;
117 /* protected by output lock */
119 unsigned int canon_column;
122 struct mutex atomic_read_lock;
123 struct mutex output_lock;
126 #define MASK(x) ((x) & (N_TTY_BUF_SIZE - 1))
128 static inline size_t read_cnt(struct n_tty_data *ldata)
130 return ldata->read_head - ldata->read_tail;
133 static inline u8 read_buf(struct n_tty_data *ldata, size_t i)
135 return ldata->read_buf[MASK(i)];
138 static inline u8 *read_buf_addr(struct n_tty_data *ldata, size_t i)
140 return &ldata->read_buf[MASK(i)];
143 static inline u8 echo_buf(struct n_tty_data *ldata, size_t i)
145 smp_rmb(); /* Matches smp_wmb() in add_echo_byte(). */
146 return ldata->echo_buf[MASK(i)];
149 static inline u8 *echo_buf_addr(struct n_tty_data *ldata, size_t i)
151 return &ldata->echo_buf[MASK(i)];
154 /* If we are not echoing the data, perhaps this is a secret so erase it */
155 static void zero_buffer(const struct tty_struct *tty, u8 *buffer, size_t size)
157 if (L_ICANON(tty) && !L_ECHO(tty))
158 memset(buffer, 0, size);
161 static void tty_copy(const struct tty_struct *tty, void *to, size_t tail,
164 struct n_tty_data *ldata = tty->disc_data;
165 size_t size = N_TTY_BUF_SIZE - tail;
166 void *from = read_buf_addr(ldata, tail);
169 tty_audit_add_data(tty, from, size);
170 memcpy(to, from, size);
171 zero_buffer(tty, from, size);
174 from = ldata->read_buf;
177 tty_audit_add_data(tty, from, n);
179 zero_buffer(tty, from, n);
183 * n_tty_kick_worker - start input worker (if required)
186 * Re-schedules the flip buffer work if it may have stopped.
189 * * Caller holds exclusive %termios_rwsem, or
190 * * n_tty_read()/consumer path:
191 * holds non-exclusive %termios_rwsem
193 static void n_tty_kick_worker(const struct tty_struct *tty)
195 struct n_tty_data *ldata = tty->disc_data;
197 /* Did the input worker stop? Restart it */
198 if (unlikely(READ_ONCE(ldata->no_room))) {
199 WRITE_ONCE(ldata->no_room, 0);
201 WARN_RATELIMIT(tty->port->itty == NULL,
202 "scheduling with invalid itty\n");
203 /* see if ldisc has been killed - if so, this means that
204 * even though the ldisc has been halted and ->buf.work
205 * cancelled, ->buf.work is about to be rescheduled
207 WARN_RATELIMIT(test_bit(TTY_LDISC_HALTED, &tty->flags),
208 "scheduling buffer work for halted ldisc\n");
209 tty_buffer_restart_work(tty->port);
213 static ssize_t chars_in_buffer(const struct tty_struct *tty)
215 const struct n_tty_data *ldata = tty->disc_data;
216 size_t head = ldata->icanon ? ldata->canon_head : ldata->commit_head;
218 return head - ldata->read_tail;
222 * n_tty_write_wakeup - asynchronous I/O notifier
225 * Required for the ptys, serial driver etc. since processes that attach
226 * themselves to the master and rely on ASYNC IO must be woken up.
228 static void n_tty_write_wakeup(struct tty_struct *tty)
230 clear_bit(TTY_DO_WRITE_WAKEUP, &tty->flags);
231 kill_fasync(&tty->fasync, SIGIO, POLL_OUT);
234 static void n_tty_check_throttle(struct tty_struct *tty)
236 struct n_tty_data *ldata = tty->disc_data;
239 * Check the remaining room for the input canonicalization
240 * mode. We don't want to throttle the driver if we're in
241 * canonical mode and don't have a newline yet!
243 if (ldata->icanon && ldata->canon_head == ldata->read_tail)
247 tty_set_flow_change(tty, TTY_THROTTLE_SAFE);
248 if (N_TTY_BUF_SIZE - read_cnt(ldata) >= TTY_THRESHOLD_THROTTLE)
250 } while (!tty_throttle_safe(tty));
252 __tty_set_flow_change(tty, 0);
255 static void n_tty_check_unthrottle(struct tty_struct *tty)
257 if (tty->driver->type == TTY_DRIVER_TYPE_PTY) {
258 if (chars_in_buffer(tty) > TTY_THRESHOLD_UNTHROTTLE)
260 n_tty_kick_worker(tty);
261 tty_wakeup(tty->link);
265 /* If there is enough space in the read buffer now, let the
266 * low-level driver know. We use chars_in_buffer() to
267 * check the buffer, as it now knows about canonical mode.
268 * Otherwise, if the driver is throttled and the line is
269 * longer than TTY_THRESHOLD_UNTHROTTLE in canonical mode,
270 * we won't get any more characters.
274 tty_set_flow_change(tty, TTY_UNTHROTTLE_SAFE);
275 if (chars_in_buffer(tty) > TTY_THRESHOLD_UNTHROTTLE)
278 n_tty_kick_worker(tty);
279 } while (!tty_unthrottle_safe(tty));
281 __tty_set_flow_change(tty, 0);
285 * put_tty_queue - add character to tty
289 * Add a character to the tty read_buf queue.
292 * * n_tty_receive_buf()/producer path:
293 * caller holds non-exclusive %termios_rwsem
295 static inline void put_tty_queue(u8 c, struct n_tty_data *ldata)
297 *read_buf_addr(ldata, ldata->read_head) = c;
302 * reset_buffer_flags - reset buffer state
303 * @ldata: line disc data to reset
305 * Reset the read buffer counters and clear the flags. Called from
306 * n_tty_open() and n_tty_flush_buffer().
309 * * caller holds exclusive %termios_rwsem, or
310 * * (locking is not required)
312 static void reset_buffer_flags(struct n_tty_data *ldata)
314 ldata->read_head = ldata->canon_head = ldata->read_tail = 0;
315 ldata->commit_head = 0;
316 ldata->line_start = 0;
319 bitmap_zero(ldata->read_flags, N_TTY_BUF_SIZE);
322 ldata->lookahead_count = 0;
325 static void n_tty_packet_mode_flush(struct tty_struct *tty)
329 if (tty->link->ctrl.packet) {
330 spin_lock_irqsave(&tty->ctrl.lock, flags);
331 tty->ctrl.pktstatus |= TIOCPKT_FLUSHREAD;
332 spin_unlock_irqrestore(&tty->ctrl.lock, flags);
333 wake_up_interruptible(&tty->link->read_wait);
338 * n_tty_flush_buffer - clean input queue
339 * @tty: terminal device
341 * Flush the input buffer. Called when the tty layer wants the buffer flushed
342 * (eg at hangup) or when the %N_TTY line discipline internally has to clean
343 * the pending queue (for example some signals).
345 * Holds %termios_rwsem to exclude producer/consumer while buffer indices are
348 * Locking: %ctrl.lock, exclusive %termios_rwsem
350 static void n_tty_flush_buffer(struct tty_struct *tty)
352 down_write(&tty->termios_rwsem);
353 reset_buffer_flags(tty->disc_data);
354 n_tty_kick_worker(tty);
357 n_tty_packet_mode_flush(tty);
358 up_write(&tty->termios_rwsem);
362 * is_utf8_continuation - utf8 multibyte check
365 * Returns: true if the utf8 character @c is a multibyte continuation
366 * character. We use this to correctly compute the on-screen size of the
367 * character when printing.
369 static inline int is_utf8_continuation(u8 c)
371 return (c & 0xc0) == 0x80;
375 * is_continuation - multibyte check
377 * @tty: terminal device
379 * Returns: true if the utf8 character @c is a multibyte continuation character
380 * and the terminal is in unicode mode.
382 static inline int is_continuation(u8 c, const struct tty_struct *tty)
384 return I_IUTF8(tty) && is_utf8_continuation(c);
388 * do_output_char - output one character
389 * @c: character (or partial unicode symbol)
390 * @tty: terminal device
391 * @space: space available in tty driver write buffer
393 * This is a helper function that handles one output character (including
394 * special characters like TAB, CR, LF, etc.), doing OPOST processing and
395 * putting the results in the tty driver's write buffer.
397 * Note that Linux currently ignores TABDLY, CRDLY, VTDLY, FFDLY and NLDLY.
398 * They simply aren't relevant in the world today. If you ever need them, add
401 * Returns: the number of bytes of buffer space used or -1 if no space left.
403 * Locking: should be called under the %output_lock to protect the column state
404 * and space left in the buffer.
406 static int do_output_char(u8 c, struct tty_struct *tty, int space)
408 struct n_tty_data *ldata = tty->disc_data;
421 ldata->canon_column = ldata->column = 0;
422 tty->ops->write(tty, "\r\n", 2);
425 ldata->canon_column = ldata->column;
428 if (O_ONOCR(tty) && ldata->column == 0)
433 ldata->canon_column = ldata->column = 0;
436 ldata->canon_column = ldata->column = 0;
439 spaces = 8 - (ldata->column & 7);
440 if (O_TABDLY(tty) == XTABS) {
443 ldata->column += spaces;
444 tty->ops->write(tty, " ", spaces);
447 ldata->column += spaces;
450 if (ldata->column > 0)
457 if (!is_continuation(c, tty))
463 tty_put_char(tty, c);
468 * process_output - output post processor
469 * @c: character (or partial unicode symbol)
470 * @tty: terminal device
472 * Output one character with OPOST processing.
474 * Returns: -1 when the output device is full and the character must be
477 * Locking: %output_lock to protect column state and space left (also, this is
478 *called from n_tty_write() under the tty layer write lock).
480 static int process_output(u8 c, struct tty_struct *tty)
482 struct n_tty_data *ldata = tty->disc_data;
484 guard(mutex)(&ldata->output_lock);
486 if (do_output_char(c, tty, tty_write_room(tty)) < 0)
493 * process_output_block - block post processor
494 * @tty: terminal device
495 * @buf: character buffer
496 * @nr: number of bytes to output
498 * Output a block of characters with OPOST processing.
500 * This path is used to speed up block console writes, among other things when
501 * processing blocks of output data. It handles only the simple cases normally
502 * found and helps to generate blocks of symbols for the console driver and
503 * thus improve performance.
505 * Returns: the number of characters output.
507 * Locking: %output_lock to protect column state and space left (also, this is
508 * called from n_tty_write() under the tty layer write lock).
510 static ssize_t process_output_block(struct tty_struct *tty,
511 const u8 *buf, unsigned int nr)
513 struct n_tty_data *ldata = tty->disc_data;
514 unsigned int space, i;
517 guard(mutex)(&ldata->output_lock);
519 space = tty_write_room(tty);
526 for (i = 0, cp = buf; i < nr; i++, cp++) {
535 ldata->canon_column = ldata->column;
538 if (O_ONOCR(tty) && ldata->column == 0)
542 ldata->canon_column = ldata->column = 0;
547 if (ldata->column > 0)
554 if (!is_continuation(c, tty))
561 return tty->ops->write(tty, buf, i);
564 static int n_tty_process_echo_ops(struct tty_struct *tty, size_t *tail,
567 struct n_tty_data *ldata = tty->disc_data;
571 * Since add_echo_byte() is called without holding output_lock, we
572 * might see only portion of multi-byte operation.
574 if (MASK(ldata->echo_commit) == MASK(*tail + 1))
578 * If the buffer byte is the start of a multi-byte operation, get the
579 * next byte, which is either the op code or a control character value.
581 op = echo_buf(ldata, *tail + 1);
584 case ECHO_OP_ERASE_TAB: {
585 unsigned int num_chars, num_bs;
587 if (MASK(ldata->echo_commit) == MASK(*tail + 2))
590 num_chars = echo_buf(ldata, *tail + 2);
593 * Determine how many columns to go back in order to erase the
594 * tab. This depends on the number of columns used by other
595 * characters within the tab area. If this (modulo 8) count is
596 * from the start of input rather than from a previous tab, we
597 * offset by canon column. Otherwise, tab spacing is normal.
599 if (!(num_chars & 0x80))
600 num_chars += ldata->canon_column;
601 num_bs = 8 - (num_chars & 7);
608 tty_put_char(tty, '\b');
609 if (ldata->column > 0)
615 case ECHO_OP_SET_CANON_COL:
616 ldata->canon_column = ldata->column;
620 case ECHO_OP_MOVE_BACK_COL:
621 if (ldata->column > 0)
627 /* This is an escaped echo op start code */
631 tty_put_char(tty, ECHO_OP_START);
639 * If the op is not a special byte code, it is a ctrl char
640 * tagged to be echoed as "^X" (where X is the letter
641 * representing the control char). Note that we must ensure
642 * there is enough space for the whole ctrl pair.
647 tty_put_char(tty, '^');
648 tty_put_char(tty, op ^ 0100);
659 * __process_echoes - write pending echo characters
660 * @tty: terminal device
662 * Write previously buffered echo (and other ldisc-generated) characters to the
665 * Characters generated by the ldisc (including echoes) need to be buffered
666 * because the driver's write buffer can fill during heavy program output.
667 * Echoing straight to the driver will often fail under these conditions,
668 * causing lost characters and resulting mismatches of ldisc state information.
670 * Since the ldisc state must represent the characters actually sent to the
671 * driver at the time of the write, operations like certain changes in column
672 * state are also saved in the buffer and executed here.
674 * A circular fifo buffer is used so that the most recent characters are
675 * prioritized. Also, when control characters are echoed with a prefixed "^",
676 * the pair is treated atomically and thus not separated.
678 * Locking: callers must hold %output_lock.
680 static size_t __process_echoes(struct tty_struct *tty)
682 struct n_tty_data *ldata = tty->disc_data;
683 unsigned int space, old_space;
687 old_space = space = tty_write_room(tty);
689 tail = ldata->echo_tail;
690 while (MASK(ldata->echo_commit) != MASK(tail)) {
691 c = echo_buf(ldata, tail);
692 if (c == ECHO_OP_START) {
693 int ret = n_tty_process_echo_ops(tty, &tail, space);
701 int retval = do_output_char(c, tty, space);
708 tty_put_char(tty, c);
715 /* If the echo buffer is nearly full (so that the possibility exists
716 * of echo overrun before the next commit), then discard enough
717 * data at the tail to prevent a subsequent overrun */
718 while (ldata->echo_commit > tail &&
719 ldata->echo_commit - tail >= ECHO_DISCARD_WATERMARK) {
720 if (echo_buf(ldata, tail) == ECHO_OP_START) {
721 if (echo_buf(ldata, tail + 1) == ECHO_OP_ERASE_TAB)
730 ldata->echo_tail = tail;
731 return old_space - space;
734 static void commit_echoes(struct tty_struct *tty)
736 struct n_tty_data *ldata = tty->disc_data;
737 size_t nr, old, echoed;
740 mutex_lock(&ldata->output_lock);
741 head = ldata->echo_head;
742 ldata->echo_mark = head;
743 old = ldata->echo_commit - ldata->echo_tail;
745 /* Process committed echoes if the accumulated # of bytes
746 * is over the threshold (and try again each time another
747 * block is accumulated) */
748 nr = head - ldata->echo_tail;
749 if (nr < ECHO_COMMIT_WATERMARK ||
750 (nr % ECHO_BLOCK > old % ECHO_BLOCK)) {
751 mutex_unlock(&ldata->output_lock);
755 ldata->echo_commit = head;
756 echoed = __process_echoes(tty);
757 mutex_unlock(&ldata->output_lock);
759 if (echoed && tty->ops->flush_chars)
760 tty->ops->flush_chars(tty);
763 static void process_echoes(struct tty_struct *tty)
765 struct n_tty_data *ldata = tty->disc_data;
768 if (ldata->echo_mark == ldata->echo_tail)
771 mutex_lock(&ldata->output_lock);
772 ldata->echo_commit = ldata->echo_mark;
773 echoed = __process_echoes(tty);
774 mutex_unlock(&ldata->output_lock);
776 if (echoed && tty->ops->flush_chars)
777 tty->ops->flush_chars(tty);
780 /* NB: echo_mark and echo_head should be equivalent here */
781 static void flush_echoes(struct tty_struct *tty)
783 struct n_tty_data *ldata = tty->disc_data;
785 if ((!L_ECHO(tty) && !L_ECHONL(tty)) ||
786 ldata->echo_commit == ldata->echo_head)
789 mutex_lock(&ldata->output_lock);
790 ldata->echo_commit = ldata->echo_head;
791 __process_echoes(tty);
792 mutex_unlock(&ldata->output_lock);
796 * add_echo_byte - add a byte to the echo buffer
797 * @c: unicode byte to echo
800 * Add a character or operation byte to the echo buffer.
802 static inline void add_echo_byte(u8 c, struct n_tty_data *ldata)
804 *echo_buf_addr(ldata, ldata->echo_head) = c;
805 smp_wmb(); /* Matches smp_rmb() in echo_buf(). */
810 * echo_move_back_col - add operation to move back a column
813 * Add an operation to the echo buffer to move back one column.
815 static void echo_move_back_col(struct n_tty_data *ldata)
817 add_echo_byte(ECHO_OP_START, ldata);
818 add_echo_byte(ECHO_OP_MOVE_BACK_COL, ldata);
822 * echo_set_canon_col - add operation to set the canon column
825 * Add an operation to the echo buffer to set the canon column to the current
828 static void echo_set_canon_col(struct n_tty_data *ldata)
830 add_echo_byte(ECHO_OP_START, ldata);
831 add_echo_byte(ECHO_OP_SET_CANON_COL, ldata);
835 * echo_erase_tab - add operation to erase a tab
836 * @num_chars: number of character columns already used
837 * @after_tab: true if num_chars starts after a previous tab
840 * Add an operation to the echo buffer to erase a tab.
842 * Called by the eraser function, which knows how many character columns have
843 * been used since either a previous tab or the start of input. This
844 * information will be used later, along with canon column (if applicable), to
845 * go back the correct number of columns.
847 static void echo_erase_tab(unsigned int num_chars, int after_tab,
848 struct n_tty_data *ldata)
850 add_echo_byte(ECHO_OP_START, ldata);
851 add_echo_byte(ECHO_OP_ERASE_TAB, ldata);
853 /* We only need to know this modulo 8 (tab spacing) */
856 /* Set the high bit as a flag if num_chars is after a previous tab */
860 add_echo_byte(num_chars, ldata);
864 * echo_char_raw - echo a character raw
865 * @c: unicode byte to echo
866 * @ldata: line disc data
868 * Echo user input back onto the screen. This must be called only when
869 * L_ECHO(tty) is true. Called from the &tty_driver.receive_buf() path.
871 * This variant does not treat control characters specially.
873 static void echo_char_raw(u8 c, struct n_tty_data *ldata)
875 if (c == ECHO_OP_START) {
876 add_echo_byte(ECHO_OP_START, ldata);
877 add_echo_byte(ECHO_OP_START, ldata);
879 add_echo_byte(c, ldata);
884 * echo_char - echo a character
885 * @c: unicode byte to echo
886 * @tty: terminal device
888 * Echo user input back onto the screen. This must be called only when
889 * L_ECHO(tty) is true. Called from the &tty_driver.receive_buf() path.
891 * This variant tags control characters to be echoed as "^X" (where X is the
892 * letter representing the control char).
894 static void echo_char(u8 c, const struct tty_struct *tty)
896 struct n_tty_data *ldata = tty->disc_data;
898 if (c == ECHO_OP_START) {
899 add_echo_byte(ECHO_OP_START, ldata);
900 add_echo_byte(ECHO_OP_START, ldata);
902 if (L_ECHOCTL(tty) && iscntrl(c) && c != '\t')
903 add_echo_byte(ECHO_OP_START, ldata);
904 add_echo_byte(c, ldata);
909 * finish_erasing - complete erase
912 static inline void finish_erasing(struct n_tty_data *ldata)
914 if (ldata->erasing) {
915 echo_char_raw('/', ldata);
921 * eraser - handle erase function
922 * @c: character input
923 * @tty: terminal device
925 * Perform erase and necessary output when an erase character is present in the
926 * stream from the driver layer. Handles the complexities of UTF-8 multibyte
929 * Locking: n_tty_receive_buf()/producer path:
930 * caller holds non-exclusive %termios_rwsem
932 static void eraser(u8 c, const struct tty_struct *tty)
934 struct n_tty_data *ldata = tty->disc_data;
935 enum { ERASE, WERASE, KILL } kill_type;
940 if (ldata->read_head == ldata->canon_head) {
941 /* process_output('\a', tty); */ /* what do you think? */
944 if (c == ERASE_CHAR(tty))
946 else if (c == WERASE_CHAR(tty))
950 ldata->read_head = ldata->canon_head;
953 if (!L_ECHOK(tty) || !L_ECHOKE(tty) || !L_ECHOE(tty)) {
954 ldata->read_head = ldata->canon_head;
955 finish_erasing(ldata);
956 echo_char(KILL_CHAR(tty), tty);
957 /* Add a newline if ECHOK is on and ECHOKE is off. */
959 echo_char_raw('\n', ldata);
966 while (MASK(ldata->read_head) != MASK(ldata->canon_head)) {
967 head = ldata->read_head;
969 /* erase a single possibly multibyte character */
972 c = read_buf(ldata, head);
973 } while (is_continuation(c, tty) &&
974 MASK(head) != MASK(ldata->canon_head));
976 /* do not partially erase */
977 if (is_continuation(c, tty))
980 if (kill_type == WERASE) {
981 /* Equivalent to BSD's ALTWERASE. */
982 if (isalnum(c) || c == '_')
984 else if (seen_alnums)
987 cnt = ldata->read_head - head;
988 ldata->read_head = head;
990 if (L_ECHOPRT(tty)) {
991 if (!ldata->erasing) {
992 echo_char_raw('\\', ldata);
995 /* if cnt > 1, output a multi-byte character */
999 echo_char_raw(read_buf(ldata, head), ldata);
1000 echo_move_back_col(ldata);
1002 } else if (kill_type == ERASE && !L_ECHOE(tty)) {
1003 echo_char(ERASE_CHAR(tty), tty);
1004 } else if (c == '\t') {
1005 unsigned int num_chars = 0;
1007 size_t tail = ldata->read_head;
1010 * Count the columns used for characters
1011 * since the start of input or after a
1013 * This info is used to go back the correct
1014 * number of columns.
1016 while (MASK(tail) != MASK(ldata->canon_head)) {
1018 c = read_buf(ldata, tail);
1022 } else if (iscntrl(c)) {
1025 } else if (!is_continuation(c, tty)) {
1029 echo_erase_tab(num_chars, after_tab, ldata);
1031 if (iscntrl(c) && L_ECHOCTL(tty)) {
1032 echo_char_raw('\b', ldata);
1033 echo_char_raw(' ', ldata);
1034 echo_char_raw('\b', ldata);
1036 if (!iscntrl(c) || L_ECHOCTL(tty)) {
1037 echo_char_raw('\b', ldata);
1038 echo_char_raw(' ', ldata);
1039 echo_char_raw('\b', ldata);
1043 if (kill_type == ERASE)
1046 if (ldata->read_head == ldata->canon_head && L_ECHO(tty))
1047 finish_erasing(ldata);
1051 static void __isig(int sig, struct tty_struct *tty)
1053 struct pid *tty_pgrp = tty_get_pgrp(tty);
1055 kill_pgrp(tty_pgrp, sig, 1);
1061 * isig - handle the ISIG optio
1065 * Called when a signal is being sent due to terminal input. Called from the
1066 * &tty_driver.receive_buf() path, so serialized.
1068 * Performs input and output flush if !NOFLSH. In this context, the echo
1069 * buffer is 'output'. The signal is processed first to alert any current
1070 * readers or writers to discontinue and exit their i/o loops.
1072 * Locking: %ctrl.lock
1074 static void isig(int sig, struct tty_struct *tty)
1076 struct n_tty_data *ldata = tty->disc_data;
1078 if (L_NOFLSH(tty)) {
1082 } else { /* signal and flush */
1083 up_read(&tty->termios_rwsem);
1084 down_write(&tty->termios_rwsem);
1088 /* clear echo buffer */
1089 mutex_lock(&ldata->output_lock);
1090 ldata->echo_head = ldata->echo_tail = 0;
1091 ldata->echo_mark = ldata->echo_commit = 0;
1092 mutex_unlock(&ldata->output_lock);
1094 /* clear output buffer */
1095 tty_driver_flush_buffer(tty);
1097 /* clear input buffer */
1098 reset_buffer_flags(tty->disc_data);
1100 /* notify pty master of flush */
1102 n_tty_packet_mode_flush(tty);
1104 up_write(&tty->termios_rwsem);
1105 down_read(&tty->termios_rwsem);
1110 * n_tty_receive_break - handle break
1113 * An RS232 break event has been hit in the incoming bitstream. This can cause
1114 * a variety of events depending upon the termios settings.
1116 * Locking: n_tty_receive_buf()/producer path:
1117 * caller holds non-exclusive termios_rwsem
1119 * Note: may get exclusive %termios_rwsem if flushing input buffer
1121 static void n_tty_receive_break(struct tty_struct *tty)
1123 struct n_tty_data *ldata = tty->disc_data;
1127 if (I_BRKINT(tty)) {
1131 if (I_PARMRK(tty)) {
1132 put_tty_queue('\377', ldata);
1133 put_tty_queue('\0', ldata);
1135 put_tty_queue('\0', ldata);
1139 * n_tty_receive_overrun - handle overrun reporting
1142 * Data arrived faster than we could process it. While the tty driver has
1143 * flagged this the bits that were missed are gone forever.
1145 * Called from the receive_buf path so single threaded. Does not need locking
1146 * as num_overrun and overrun_time are function private.
1148 static void n_tty_receive_overrun(const struct tty_struct *tty)
1150 struct n_tty_data *ldata = tty->disc_data;
1152 ldata->num_overrun++;
1153 if (time_is_before_jiffies(ldata->overrun_time + HZ)) {
1154 tty_warn(tty, "%u input overrun(s)\n", ldata->num_overrun);
1155 ldata->overrun_time = jiffies;
1156 ldata->num_overrun = 0;
1161 * n_tty_receive_parity_error - error notifier
1162 * @tty: terminal device
1165 * Process a parity error and queue the right data to indicate the error case
1168 * Locking: n_tty_receive_buf()/producer path:
1169 * caller holds non-exclusive %termios_rwsem
1171 static void n_tty_receive_parity_error(const struct tty_struct *tty,
1174 struct n_tty_data *ldata = tty->disc_data;
1179 if (I_PARMRK(tty)) {
1180 put_tty_queue('\377', ldata);
1181 put_tty_queue('\0', ldata);
1182 put_tty_queue(c, ldata);
1184 put_tty_queue('\0', ldata);
1186 put_tty_queue(c, ldata);
1190 n_tty_receive_signal_char(struct tty_struct *tty, int signal, u8 c)
1199 process_echoes(tty);
1202 static bool n_tty_is_char_flow_ctrl(struct tty_struct *tty, u8 c)
1204 return c == START_CHAR(tty) || c == STOP_CHAR(tty);
1208 * n_tty_receive_char_flow_ctrl - receive flow control chars
1209 * @tty: terminal device
1211 * @lookahead_done: lookahead has processed this character already
1213 * Receive and process flow control character actions.
1215 * In case lookahead for flow control chars already handled the character in
1216 * advance to the normal receive, the actions are skipped during normal
1219 * Returns true if @c is consumed as flow-control character, the character
1220 * must not be treated as normal character.
1222 static bool n_tty_receive_char_flow_ctrl(struct tty_struct *tty, u8 c,
1223 bool lookahead_done)
1225 if (!n_tty_is_char_flow_ctrl(tty, c))
1231 if (c == START_CHAR(tty)) {
1233 process_echoes(tty);
1242 static void n_tty_receive_handle_newline(struct tty_struct *tty, u8 c)
1244 struct n_tty_data *ldata = tty->disc_data;
1246 set_bit(MASK(ldata->read_head), ldata->read_flags);
1247 put_tty_queue(c, ldata);
1248 smp_store_release(&ldata->canon_head, ldata->read_head);
1249 kill_fasync(&tty->fasync, SIGIO, POLL_IN);
1250 wake_up_interruptible_poll(&tty->read_wait, EPOLLIN | EPOLLRDNORM);
1253 static bool n_tty_receive_char_canon(struct tty_struct *tty, u8 c)
1255 struct n_tty_data *ldata = tty->disc_data;
1257 if (c == ERASE_CHAR(tty) || c == KILL_CHAR(tty) ||
1258 (c == WERASE_CHAR(tty) && L_IEXTEN(tty))) {
1265 if (c == LNEXT_CHAR(tty) && L_IEXTEN(tty)) {
1268 finish_erasing(ldata);
1269 if (L_ECHOCTL(tty)) {
1270 echo_char_raw('^', ldata);
1271 echo_char_raw('\b', ldata);
1279 if (c == REPRINT_CHAR(tty) && L_ECHO(tty) && L_IEXTEN(tty)) {
1280 size_t tail = ldata->canon_head;
1282 finish_erasing(ldata);
1284 echo_char_raw('\n', ldata);
1285 while (MASK(tail) != MASK(ldata->read_head)) {
1286 echo_char(read_buf(ldata, tail), tty);
1295 if (L_ECHO(tty) || L_ECHONL(tty)) {
1296 echo_char_raw('\n', ldata);
1299 n_tty_receive_handle_newline(tty, c);
1304 if (c == EOF_CHAR(tty)) {
1305 c = __DISABLED_CHAR;
1306 n_tty_receive_handle_newline(tty, c);
1311 if ((c == EOL_CHAR(tty)) ||
1312 (c == EOL2_CHAR(tty) && L_IEXTEN(tty))) {
1314 * XXX are EOL_CHAR and EOL2_CHAR echoed?!?
1317 /* Record the column of first canon char. */
1318 if (ldata->canon_head == ldata->read_head)
1319 echo_set_canon_col(ldata);
1324 * XXX does PARMRK doubling happen for
1325 * EOL_CHAR and EOL2_CHAR?
1327 if (c == '\377' && I_PARMRK(tty))
1328 put_tty_queue(c, ldata);
1330 n_tty_receive_handle_newline(tty, c);
1338 static void n_tty_receive_char_special(struct tty_struct *tty, u8 c,
1339 bool lookahead_done)
1341 struct n_tty_data *ldata = tty->disc_data;
1343 if (I_IXON(tty) && n_tty_receive_char_flow_ctrl(tty, c, lookahead_done))
1347 if (c == INTR_CHAR(tty)) {
1348 n_tty_receive_signal_char(tty, SIGINT, c);
1350 } else if (c == QUIT_CHAR(tty)) {
1351 n_tty_receive_signal_char(tty, SIGQUIT, c);
1353 } else if (c == SUSP_CHAR(tty)) {
1354 n_tty_receive_signal_char(tty, SIGTSTP, c);
1359 if (tty->flow.stopped && !tty->flow.tco_stopped && I_IXON(tty) && I_IXANY(tty)) {
1361 process_echoes(tty);
1369 } else if (c == '\n' && I_INLCR(tty))
1372 if (ldata->icanon && n_tty_receive_char_canon(tty, c))
1376 finish_erasing(ldata);
1378 echo_char_raw('\n', ldata);
1380 /* Record the column of first canon char. */
1381 if (ldata->canon_head == ldata->read_head)
1382 echo_set_canon_col(ldata);
1388 /* PARMRK doubling check */
1389 if (c == '\377' && I_PARMRK(tty))
1390 put_tty_queue(c, ldata);
1392 put_tty_queue(c, ldata);
1396 * n_tty_receive_char - perform processing
1397 * @tty: terminal device
1400 * Process an individual character of input received from the driver. This is
1401 * serialized with respect to itself by the rules for the driver above.
1403 * Locking: n_tty_receive_buf()/producer path:
1404 * caller holds non-exclusive %termios_rwsem
1405 * publishes canon_head if canonical mode is active
1407 static void n_tty_receive_char(struct tty_struct *tty, u8 c)
1409 struct n_tty_data *ldata = tty->disc_data;
1411 if (tty->flow.stopped && !tty->flow.tco_stopped && I_IXON(tty) && I_IXANY(tty)) {
1413 process_echoes(tty);
1416 finish_erasing(ldata);
1417 /* Record the column of first canon char. */
1418 if (ldata->canon_head == ldata->read_head)
1419 echo_set_canon_col(ldata);
1423 /* PARMRK doubling check */
1424 if (c == '\377' && I_PARMRK(tty))
1425 put_tty_queue(c, ldata);
1426 put_tty_queue(c, ldata);
1429 static void n_tty_receive_char_closing(struct tty_struct *tty, u8 c,
1430 bool lookahead_done)
1434 if (I_IUCLC(tty) && L_IEXTEN(tty))
1438 if (!n_tty_receive_char_flow_ctrl(tty, c, lookahead_done) &&
1439 tty->flow.stopped && !tty->flow.tco_stopped && I_IXANY(tty) &&
1440 c != INTR_CHAR(tty) && c != QUIT_CHAR(tty) &&
1441 c != SUSP_CHAR(tty)) {
1443 process_echoes(tty);
1449 n_tty_receive_char_flagged(struct tty_struct *tty, u8 c, u8 flag)
1453 n_tty_receive_break(tty);
1457 n_tty_receive_parity_error(tty, c);
1460 n_tty_receive_overrun(tty);
1463 tty_err(tty, "unknown flag %u\n", flag);
1469 n_tty_receive_char_lnext(struct tty_struct *tty, u8 c, u8 flag)
1471 struct n_tty_data *ldata = tty->disc_data;
1474 if (likely(flag == TTY_NORMAL)) {
1477 if (I_IUCLC(tty) && L_IEXTEN(tty))
1479 n_tty_receive_char(tty, c);
1481 n_tty_receive_char_flagged(tty, c, flag);
1484 /* Caller must ensure count > 0 */
1485 static void n_tty_lookahead_flow_ctrl(struct tty_struct *tty, const u8 *cp,
1486 const u8 *fp, size_t count)
1488 struct n_tty_data *ldata = tty->disc_data;
1489 u8 flag = TTY_NORMAL;
1491 ldata->lookahead_count += count;
1499 if (likely(flag == TTY_NORMAL))
1500 n_tty_receive_char_flow_ctrl(tty, *cp, false);
1506 n_tty_receive_buf_real_raw(const struct tty_struct *tty, const u8 *cp,
1509 struct n_tty_data *ldata = tty->disc_data;
1511 /* handle buffer wrap-around by a loop */
1512 for (unsigned int i = 0; i < 2; i++) {
1513 size_t head = MASK(ldata->read_head);
1514 size_t n = min(count, N_TTY_BUF_SIZE - head);
1516 memcpy(read_buf_addr(ldata, head), cp, n);
1518 ldata->read_head += n;
1525 n_tty_receive_buf_raw(struct tty_struct *tty, const u8 *cp, const u8 *fp,
1528 struct n_tty_data *ldata = tty->disc_data;
1529 u8 flag = TTY_NORMAL;
1534 if (likely(flag == TTY_NORMAL))
1535 put_tty_queue(*cp++, ldata);
1537 n_tty_receive_char_flagged(tty, *cp++, flag);
1542 n_tty_receive_buf_closing(struct tty_struct *tty, const u8 *cp, const u8 *fp,
1543 size_t count, bool lookahead_done)
1545 u8 flag = TTY_NORMAL;
1550 if (likely(flag == TTY_NORMAL))
1551 n_tty_receive_char_closing(tty, *cp++, lookahead_done);
1555 static void n_tty_receive_buf_standard(struct tty_struct *tty, const u8 *cp,
1556 const u8 *fp, size_t count,
1557 bool lookahead_done)
1559 struct n_tty_data *ldata = tty->disc_data;
1560 u8 flag = TTY_NORMAL;
1569 n_tty_receive_char_lnext(tty, c, flag);
1573 if (unlikely(flag != TTY_NORMAL)) {
1574 n_tty_receive_char_flagged(tty, c, flag);
1580 if (I_IUCLC(tty) && L_IEXTEN(tty))
1582 if (L_EXTPROC(tty)) {
1583 put_tty_queue(c, ldata);
1587 if (test_bit(c, ldata->char_map))
1588 n_tty_receive_char_special(tty, c, lookahead_done);
1590 n_tty_receive_char(tty, c);
1594 static void __receive_buf(struct tty_struct *tty, const u8 *cp, const u8 *fp,
1597 struct n_tty_data *ldata = tty->disc_data;
1598 bool preops = I_ISTRIP(tty) || (I_IUCLC(tty) && L_IEXTEN(tty));
1599 size_t la_count = min(ldata->lookahead_count, count);
1601 if (ldata->real_raw)
1602 n_tty_receive_buf_real_raw(tty, cp, count);
1603 else if (ldata->raw || (L_EXTPROC(tty) && !preops))
1604 n_tty_receive_buf_raw(tty, cp, fp, count);
1605 else if (tty->closing && !L_EXTPROC(tty)) {
1607 n_tty_receive_buf_closing(tty, cp, fp, la_count, true);
1614 n_tty_receive_buf_closing(tty, cp, fp, count, false);
1617 n_tty_receive_buf_standard(tty, cp, fp, la_count, true);
1624 n_tty_receive_buf_standard(tty, cp, fp, count, false);
1627 if (tty->ops->flush_chars)
1628 tty->ops->flush_chars(tty);
1631 ldata->lookahead_count -= la_count;
1633 if (ldata->icanon && !L_EXTPROC(tty))
1636 /* publish read_head to consumer */
1637 smp_store_release(&ldata->commit_head, ldata->read_head);
1639 if (read_cnt(ldata)) {
1640 kill_fasync(&tty->fasync, SIGIO, POLL_IN);
1641 wake_up_interruptible_poll(&tty->read_wait, EPOLLIN | EPOLLRDNORM);
1646 * n_tty_receive_buf_common - process input
1647 * @tty: device to receive input
1649 * @fp: flags for each char (if %NULL, all chars are %TTY_NORMAL)
1650 * @count: number of input chars in @cp
1651 * @flow: enable flow control
1653 * Called by the terminal driver when a block of characters has been received.
1654 * This function must be called from soft contexts not from interrupt context.
1655 * The driver is responsible for making calls one at a time and in order (or
1656 * using flush_to_ldisc()).
1658 * Returns: the # of input chars from @cp which were processed.
1660 * In canonical mode, the maximum line length is 4096 chars (including the line
1661 * termination char); lines longer than 4096 chars are truncated. After 4095
1662 * chars, input data is still processed but not stored. Overflow processing
1663 * ensures the tty can always receive more input until at least one line can be
1666 * In non-canonical mode, the read buffer will only accept 4095 chars; this
1667 * provides the necessary space for a newline char if the input mode is
1668 * switched to canonical.
1670 * Note it is possible for the read buffer to _contain_ 4096 chars in
1671 * non-canonical mode: the read buffer could already contain the maximum canon
1672 * line of 4096 chars when the mode is switched to non-canonical.
1674 * Locking: n_tty_receive_buf()/producer path:
1675 * claims non-exclusive %termios_rwsem
1676 * publishes commit_head or canon_head
1679 n_tty_receive_buf_common(struct tty_struct *tty, const u8 *cp, const u8 *fp,
1680 size_t count, bool flow)
1682 struct n_tty_data *ldata = tty->disc_data;
1686 down_read(&tty->termios_rwsem);
1690 * When PARMRK is set, each input char may take up to 3 chars
1691 * in the read buf; reduce the buffer space avail by 3x
1693 * If we are doing input canonicalization, and there are no
1694 * pending newlines, let characters through without limit, so
1695 * that erase characters will be handled. Other excess
1696 * characters will be beeped.
1698 * paired with store in *_copy_from_read_buf() -- guarantees
1699 * the consumer has loaded the data in read_buf up to the new
1700 * read_tail (so this producer will not overwrite unread data)
1702 size_t tail = smp_load_acquire(&ldata->read_tail);
1704 room = N_TTY_BUF_SIZE - (ldata->read_head - tail);
1706 room = DIV_ROUND_UP(room, 3);
1709 overflow = ldata->icanon && ldata->canon_head == tail;
1710 if (overflow && room < 0)
1713 WRITE_ONCE(ldata->no_room, flow && !room);
1717 n = min_t(size_t, count, room);
1721 /* ignore parity errors if handling overflow */
1722 if (!overflow || !fp || *fp != TTY_PARITY)
1723 __receive_buf(tty, cp, fp, n);
1730 } while (!test_bit(TTY_LDISC_CHANGING, &tty->flags));
1732 tty->receive_room = room;
1734 /* Unthrottle if handling overflow on pty */
1735 if (tty->driver->type == TTY_DRIVER_TYPE_PTY) {
1737 tty_set_flow_change(tty, TTY_UNTHROTTLE_SAFE);
1738 tty_unthrottle_safe(tty);
1739 __tty_set_flow_change(tty, 0);
1742 n_tty_check_throttle(tty);
1744 if (unlikely(ldata->no_room)) {
1746 * Barrier here is to ensure to read the latest read_tail in
1747 * chars_in_buffer() and to make sure that read_tail is not loaded
1748 * before ldata->no_room is set.
1751 if (!chars_in_buffer(tty))
1752 n_tty_kick_worker(tty);
1755 up_read(&tty->termios_rwsem);
1760 static void n_tty_receive_buf(struct tty_struct *tty, const u8 *cp,
1761 const u8 *fp, size_t count)
1763 n_tty_receive_buf_common(tty, cp, fp, count, false);
1766 static size_t n_tty_receive_buf2(struct tty_struct *tty, const u8 *cp,
1767 const u8 *fp, size_t count)
1769 return n_tty_receive_buf_common(tty, cp, fp, count, true);
1773 * n_tty_set_termios - termios data changed
1775 * @old: previous data
1777 * Called by the tty layer when the user changes termios flags so that the line
1778 * discipline can plan ahead. This function cannot sleep and is protected from
1779 * re-entry by the tty layer. The user is guaranteed that this function will
1780 * not be re-entered or in progress when the ldisc is closed.
1782 * Locking: Caller holds @tty->termios_rwsem
1784 static void n_tty_set_termios(struct tty_struct *tty, const struct ktermios *old)
1786 struct n_tty_data *ldata = tty->disc_data;
1788 if (!old || (old->c_lflag ^ tty->termios.c_lflag) & (ICANON | EXTPROC)) {
1789 bitmap_zero(ldata->read_flags, N_TTY_BUF_SIZE);
1790 ldata->line_start = ldata->read_tail;
1791 if (!L_ICANON(tty) || !read_cnt(ldata)) {
1792 ldata->canon_head = ldata->read_tail;
1795 set_bit(MASK(ldata->read_head - 1), ldata->read_flags);
1796 ldata->canon_head = ldata->read_head;
1799 ldata->commit_head = ldata->read_head;
1804 ldata->icanon = (L_ICANON(tty) != 0);
1806 if (I_ISTRIP(tty) || I_IUCLC(tty) || I_IGNCR(tty) ||
1807 I_ICRNL(tty) || I_INLCR(tty) || L_ICANON(tty) ||
1808 I_IXON(tty) || L_ISIG(tty) || L_ECHO(tty) ||
1810 bitmap_zero(ldata->char_map, 256);
1812 if (I_IGNCR(tty) || I_ICRNL(tty))
1813 set_bit('\r', ldata->char_map);
1815 set_bit('\n', ldata->char_map);
1817 if (L_ICANON(tty)) {
1818 set_bit(ERASE_CHAR(tty), ldata->char_map);
1819 set_bit(KILL_CHAR(tty), ldata->char_map);
1820 set_bit(EOF_CHAR(tty), ldata->char_map);
1821 set_bit('\n', ldata->char_map);
1822 set_bit(EOL_CHAR(tty), ldata->char_map);
1823 if (L_IEXTEN(tty)) {
1824 set_bit(WERASE_CHAR(tty), ldata->char_map);
1825 set_bit(LNEXT_CHAR(tty), ldata->char_map);
1826 set_bit(EOL2_CHAR(tty), ldata->char_map);
1828 set_bit(REPRINT_CHAR(tty),
1833 set_bit(START_CHAR(tty), ldata->char_map);
1834 set_bit(STOP_CHAR(tty), ldata->char_map);
1837 set_bit(INTR_CHAR(tty), ldata->char_map);
1838 set_bit(QUIT_CHAR(tty), ldata->char_map);
1839 set_bit(SUSP_CHAR(tty), ldata->char_map);
1841 clear_bit(__DISABLED_CHAR, ldata->char_map);
1843 ldata->real_raw = 0;
1846 if ((I_IGNBRK(tty) || (!I_BRKINT(tty) && !I_PARMRK(tty))) &&
1847 (I_IGNPAR(tty) || !I_INPCK(tty)) &&
1848 (tty->driver->flags & TTY_DRIVER_REAL_RAW))
1849 ldata->real_raw = 1;
1851 ldata->real_raw = 0;
1854 * Fix tty hang when I_IXON(tty) is cleared, but the tty
1855 * been stopped by STOP_CHAR(tty) before it.
1857 if (!I_IXON(tty) && old && (old->c_iflag & IXON) && !tty->flow.tco_stopped) {
1859 process_echoes(tty);
1862 /* The termios change make the tty ready for I/O */
1863 wake_up_interruptible(&tty->write_wait);
1864 wake_up_interruptible(&tty->read_wait);
1868 * n_tty_close - close the ldisc for this tty
1871 * Called from the terminal layer when this line discipline is being shut down,
1872 * either because of a close or becsuse of a discipline change. The function
1873 * will not be called while other ldisc methods are in progress.
1875 static void n_tty_close(struct tty_struct *tty)
1877 struct n_tty_data *ldata = tty->disc_data;
1880 n_tty_packet_mode_flush(tty);
1882 down_write(&tty->termios_rwsem);
1884 tty->disc_data = NULL;
1885 up_write(&tty->termios_rwsem);
1889 * n_tty_open - open an ldisc
1890 * @tty: terminal to open
1892 * Called when this line discipline is being attached to the terminal device.
1893 * Can sleep. Called serialized so that no other events will occur in parallel.
1894 * No further open will occur until a close.
1896 static int n_tty_open(struct tty_struct *tty)
1898 struct n_tty_data *ldata;
1900 /* Currently a malloc failure here can panic */
1901 ldata = vzalloc(sizeof(*ldata));
1905 ldata->overrun_time = jiffies;
1906 mutex_init(&ldata->atomic_read_lock);
1907 mutex_init(&ldata->output_lock);
1909 tty->disc_data = ldata;
1911 /* indicate buffer work may resume */
1912 clear_bit(TTY_LDISC_HALTED, &tty->flags);
1913 n_tty_set_termios(tty, NULL);
1914 tty_unthrottle(tty);
1918 static inline int input_available_p(const struct tty_struct *tty, int poll)
1920 const struct n_tty_data *ldata = tty->disc_data;
1921 int amt = poll && !TIME_CHAR(tty) && MIN_CHAR(tty) ? MIN_CHAR(tty) : 1;
1923 if (ldata->icanon && !L_EXTPROC(tty))
1924 return ldata->canon_head != ldata->read_tail;
1926 return ldata->commit_head - ldata->read_tail >= amt;
1930 * copy_from_read_buf - copy read data directly
1931 * @tty: terminal device
1935 * Helper function to speed up n_tty_read(). It is only called when %ICANON is
1936 * off; it copies characters straight from the tty queue.
1938 * Returns: true if it successfully copied data, but there is still more data
1942 * * called under the @ldata->atomic_read_lock sem
1943 * * n_tty_read()/consumer path:
1944 * caller holds non-exclusive %termios_rwsem;
1945 * read_tail published
1947 static bool copy_from_read_buf(const struct tty_struct *tty, u8 **kbp,
1951 struct n_tty_data *ldata = tty->disc_data;
1954 size_t head = smp_load_acquire(&ldata->commit_head);
1955 size_t tail = MASK(ldata->read_tail);
1957 n = min3(head - ldata->read_tail, N_TTY_BUF_SIZE - tail, *nr);
1961 u8 *from = read_buf_addr(ldata, tail);
1962 memcpy(*kbp, from, n);
1963 is_eof = n == 1 && *from == EOF_CHAR(tty);
1964 tty_audit_add_data(tty, from, n);
1965 zero_buffer(tty, from, n);
1966 smp_store_release(&ldata->read_tail, ldata->read_tail + n);
1968 /* Turn single EOF into zero-length read */
1969 if (L_EXTPROC(tty) && ldata->icanon && is_eof &&
1970 head == ldata->read_tail)
1976 /* If we have more to copy, let the caller know */
1977 return head != ldata->read_tail;
1981 * canon_copy_from_read_buf - copy read data in canonical mode
1982 * @tty: terminal device
1986 * Helper function for n_tty_read(). It is only called when %ICANON is on; it
1987 * copies one line of input up to and including the line-delimiting character
1988 * into the result buffer.
1990 * Note: When termios is changed from non-canonical to canonical mode and the
1991 * read buffer contains data, n_tty_set_termios() simulates an EOF push (as if
1992 * C-d were input) _without_ the %DISABLED_CHAR in the buffer. This causes data
1993 * already processed as input to be immediately available as input although a
1994 * newline has not been received.
1997 * * called under the %atomic_read_lock mutex
1998 * * n_tty_read()/consumer path:
1999 * caller holds non-exclusive %termios_rwsem;
2000 * read_tail published
2002 static bool canon_copy_from_read_buf(const struct tty_struct *tty, u8 **kbp,
2005 struct n_tty_data *ldata = tty->disc_data;
2006 size_t n, size, more, c;
2008 size_t tail, canon_head;
2011 /* N.B. avoid overrun if nr == 0 */
2015 canon_head = smp_load_acquire(&ldata->canon_head);
2016 n = min(*nr, canon_head - ldata->read_tail);
2018 tail = MASK(ldata->read_tail);
2019 size = min_t(size_t, tail + n, N_TTY_BUF_SIZE);
2021 eol = find_next_bit(ldata->read_flags, size, tail);
2022 more = n - (size - tail);
2023 if (eol == N_TTY_BUF_SIZE && more) {
2024 /* scan wrapped without finding set bit */
2025 eol = find_first_bit(ldata->read_flags, more);
2026 found = eol != more;
2028 found = eol != size;
2031 if (n > N_TTY_BUF_SIZE)
2032 n += N_TTY_BUF_SIZE;
2035 if (!found || read_buf(ldata, eol) != __DISABLED_CHAR)
2038 tty_copy(tty, *kbp, tail, n);
2043 clear_bit(eol, ldata->read_flags);
2044 smp_store_release(&ldata->read_tail, ldata->read_tail + c);
2048 ldata->line_start = ldata->read_tail;
2055 /* No EOL found - do a continuation retry if there is more data */
2056 return ldata->read_tail != canon_head;
2060 * If we finished a read at the exact location of an
2061 * EOF (special EOL character that's a __DISABLED_CHAR)
2062 * in the stream, silently eat the EOF.
2064 static void canon_skip_eof(struct n_tty_data *ldata)
2066 size_t tail, canon_head;
2068 canon_head = smp_load_acquire(&ldata->canon_head);
2069 tail = ldata->read_tail;
2072 if (tail == canon_head)
2075 // See if the tail position is EOF in the circular buffer
2076 tail &= (N_TTY_BUF_SIZE - 1);
2077 if (!test_bit(tail, ldata->read_flags))
2079 if (read_buf(ldata, tail) != __DISABLED_CHAR)
2082 // Clear the EOL bit, skip the EOF char.
2083 clear_bit(tail, ldata->read_flags);
2084 smp_store_release(&ldata->read_tail, ldata->read_tail + 1);
2088 * job_control - check job control
2090 * @file: file handle
2092 * Perform job control management checks on this @file/@tty descriptor and if
2093 * appropriate send any needed signals and return a negative error code if
2094 * action should be taken.
2097 * * redirected write test is safe
2098 * * current->signal->tty check is safe
2099 * * ctrl.lock to safely reference @tty->ctrl.pgrp
2101 static int job_control(struct tty_struct *tty, struct file *file)
2103 /* Job control check -- must be done at start and after
2104 every sleep (POSIX.1 7.1.1.4). */
2105 /* NOTE: not yet done after every sleep pending a thorough
2106 check of the logic of this change. -- jlc */
2107 /* don't stop on /dev/console */
2108 if (file->f_op->write_iter == redirected_tty_write)
2111 return __tty_check_change(tty, SIGTTIN);
2115 * We still hold the atomic_read_lock and the termios_rwsem, and can just
2116 * continue to copy data.
2118 static ssize_t n_tty_continue_cookie(struct tty_struct *tty, u8 *kbuf,
2119 size_t nr, void **cookie)
2121 struct n_tty_data *ldata = tty->disc_data;
2124 if (ldata->icanon && !L_EXTPROC(tty)) {
2126 * If we have filled the user buffer, see if we should skip an
2127 * EOF character before releasing the lock and returning done.
2130 canon_skip_eof(ldata);
2131 else if (canon_copy_from_read_buf(tty, &kb, &nr))
2134 if (copy_from_read_buf(tty, &kb, &nr))
2138 /* No more data - release locks and stop retries */
2139 n_tty_kick_worker(tty);
2140 n_tty_check_unthrottle(tty);
2141 up_read(&tty->termios_rwsem);
2142 mutex_unlock(&ldata->atomic_read_lock);
2148 static int n_tty_wait_for_input(struct tty_struct *tty, struct file *file,
2149 struct wait_queue_entry *wait, long *timeout)
2151 if (test_bit(TTY_OTHER_CLOSED, &tty->flags))
2153 if (tty_hung_up_p(file))
2156 * Abort readers for ttys which never actually get hung up.
2157 * See __tty_hangup().
2159 if (test_bit(TTY_HUPPING, &tty->flags))
2163 if (tty_io_nonblock(tty, file))
2165 if (signal_pending(current))
2166 return -ERESTARTSYS;
2168 up_read(&tty->termios_rwsem);
2169 *timeout = wait_woken(wait, TASK_INTERRUPTIBLE, *timeout);
2170 down_read(&tty->termios_rwsem);
2176 * n_tty_read - read function for tty
2178 * @file: file object
2179 * @kbuf: kernelspace buffer pointer
2181 * @cookie: if non-%NULL, this is a continuation read
2182 * @offset: where to continue reading from (unused in n_tty)
2184 * Perform reads for the line discipline. We are guaranteed that the line
2185 * discipline will not be closed under us but we may get multiple parallel
2186 * readers and must handle this ourselves. We may also get a hangup. Always
2187 * called in user context, may sleep.
2189 * This code must be sure never to sleep through a hangup.
2191 * Locking: n_tty_read()/consumer path:
2192 * claims non-exclusive termios_rwsem;
2193 * publishes read_tail
2195 static ssize_t n_tty_read(struct tty_struct *tty, struct file *file, u8 *kbuf,
2196 size_t nr, void **cookie, unsigned long offset)
2198 struct n_tty_data *ldata = tty->disc_data;
2200 DEFINE_WAIT_FUNC(wait, woken_wake_function);
2207 /* Is this a continuation of a read started earlier? */
2209 return n_tty_continue_cookie(tty, kbuf, nr, cookie);
2211 retval = job_control(tty, file);
2216 * Internal serialization of reads.
2218 if (file->f_flags & O_NONBLOCK) {
2219 if (!mutex_trylock(&ldata->atomic_read_lock))
2222 if (mutex_lock_interruptible(&ldata->atomic_read_lock))
2223 return -ERESTARTSYS;
2226 down_read(&tty->termios_rwsem);
2229 timeout = MAX_SCHEDULE_TIMEOUT;
2230 if (!ldata->icanon) {
2231 minimum = MIN_CHAR(tty);
2233 time = (HZ / 10) * TIME_CHAR(tty);
2235 timeout = (HZ / 10) * TIME_CHAR(tty);
2240 packet = tty->ctrl.packet;
2241 old_tail = ldata->read_tail;
2243 add_wait_queue(&tty->read_wait, &wait);
2245 /* First test for status change. */
2246 if (packet && tty->link->ctrl.pktstatus) {
2250 spin_lock_irq(&tty->link->ctrl.lock);
2251 cs = tty->link->ctrl.pktstatus;
2252 tty->link->ctrl.pktstatus = 0;
2253 spin_unlock_irq(&tty->link->ctrl.lock);
2259 if (!input_available_p(tty, 0)) {
2260 up_read(&tty->termios_rwsem);
2261 tty_buffer_flush_work(tty->port);
2262 down_read(&tty->termios_rwsem);
2263 if (!input_available_p(tty, 0)) {
2264 int ret = n_tty_wait_for_input(tty, file, &wait,
2274 if (ldata->icanon && !L_EXTPROC(tty)) {
2275 if (canon_copy_from_read_buf(tty, &kb, &nr))
2276 goto more_to_be_read;
2278 /* Deal with packet mode. */
2279 if (packet && kb == kbuf) {
2280 *kb++ = TIOCPKT_DATA;
2284 if (copy_from_read_buf(tty, &kb, &nr) && kb - kbuf >= minimum)
2285 goto more_to_be_read;
2288 n_tty_check_unthrottle(tty);
2290 if (kb - kbuf >= minimum)
2295 if (old_tail != ldata->read_tail) {
2297 * Make sure no_room is not read in n_tty_kick_worker()
2298 * before setting ldata->read_tail in copy_from_read_buf().
2301 n_tty_kick_worker(tty);
2303 up_read(&tty->termios_rwsem);
2305 remove_wait_queue(&tty->read_wait, &wait);
2306 mutex_unlock(&ldata->atomic_read_lock);
2314 * There is more to be had and we have nothing more to wait for, so
2315 * let's mark us for retries.
2317 * NOTE! We return here with both the termios_sem and atomic_read_lock
2318 * still held, the retries will release them when done.
2320 remove_wait_queue(&tty->read_wait, &wait);
2327 * n_tty_write - write function for tty
2329 * @file: file object
2330 * @buf: userspace buffer pointer
2333 * Write function of the terminal device. This is serialized with respect to
2334 * other write callers but not to termios changes, reads and other such events.
2335 * Since the receive code will echo characters, thus calling driver write
2336 * methods, the %output_lock is used in the output processing functions called
2337 * here as well as in the echo processing function to protect the column state
2338 * and space left in the buffer.
2340 * This code must be sure never to sleep through a hangup.
2342 * Locking: output_lock to protect column state and space left
2343 * (note that the process_output*() functions take this lock themselves)
2346 static ssize_t n_tty_write(struct tty_struct *tty, struct file *file,
2347 const u8 *buf, size_t nr)
2350 DEFINE_WAIT_FUNC(wait, woken_wake_function);
2351 ssize_t num, retval = 0;
2353 /* Job control check -- must be done at start (POSIX.1 7.1.1.4). */
2354 if (L_TOSTOP(tty) && file->f_op->write_iter != redirected_tty_write) {
2355 retval = tty_check_change(tty);
2360 down_read(&tty->termios_rwsem);
2362 /* Write out any echoed characters that are still pending */
2363 process_echoes(tty);
2365 add_wait_queue(&tty->write_wait, &wait);
2367 if (signal_pending(current)) {
2368 retval = -ERESTARTSYS;
2371 if (tty_hung_up_p(file) || (tty->link && !tty->link->count)) {
2377 num = process_output_block(tty, b, nr);
2388 if (process_output(*b, tty) < 0)
2392 if (tty->ops->flush_chars)
2393 tty->ops->flush_chars(tty);
2395 struct n_tty_data *ldata = tty->disc_data;
2398 mutex_lock(&ldata->output_lock);
2399 num = tty->ops->write(tty, b, nr);
2400 mutex_unlock(&ldata->output_lock);
2413 if (tty_io_nonblock(tty, file)) {
2417 up_read(&tty->termios_rwsem);
2419 wait_woken(&wait, TASK_INTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT);
2421 down_read(&tty->termios_rwsem);
2424 remove_wait_queue(&tty->write_wait, &wait);
2425 if (nr && tty->fasync)
2426 set_bit(TTY_DO_WRITE_WAKEUP, &tty->flags);
2427 up_read(&tty->termios_rwsem);
2428 return (b - buf) ? b - buf : retval;
2432 * n_tty_poll - poll method for N_TTY
2433 * @tty: terminal device
2434 * @file: file accessing it
2437 * Called when the line discipline is asked to poll() for data or for special
2438 * events. This code is not serialized with respect to other events save
2441 * This code must be sure never to sleep through a hangup.
2443 * Locking: called without the kernel lock held -- fine.
2445 static __poll_t n_tty_poll(struct tty_struct *tty, struct file *file,
2450 poll_wait(file, &tty->read_wait, wait);
2451 poll_wait(file, &tty->write_wait, wait);
2452 if (input_available_p(tty, 1))
2453 mask |= EPOLLIN | EPOLLRDNORM;
2455 tty_buffer_flush_work(tty->port);
2456 if (input_available_p(tty, 1))
2457 mask |= EPOLLIN | EPOLLRDNORM;
2459 if (tty->ctrl.packet && tty->link->ctrl.pktstatus)
2460 mask |= EPOLLPRI | EPOLLIN | EPOLLRDNORM;
2461 if (test_bit(TTY_OTHER_CLOSED, &tty->flags))
2463 if (tty_hung_up_p(file))
2465 if (tty->ops->write && !tty_is_writelocked(tty) &&
2466 tty_chars_in_buffer(tty) < WAKEUP_CHARS &&
2467 tty_write_room(tty) > 0)
2468 mask |= EPOLLOUT | EPOLLWRNORM;
2472 static unsigned long inq_canon(struct n_tty_data *ldata)
2474 size_t nr, head, tail;
2476 if (ldata->canon_head == ldata->read_tail)
2478 head = ldata->canon_head;
2479 tail = ldata->read_tail;
2481 /* Skip EOF-chars.. */
2482 while (MASK(head) != MASK(tail)) {
2483 if (test_bit(MASK(tail), ldata->read_flags) &&
2484 read_buf(ldata, tail) == __DISABLED_CHAR)
2491 static int n_tty_ioctl(struct tty_struct *tty, unsigned int cmd,
2494 struct n_tty_data *ldata = tty->disc_data;
2499 return put_user(tty_chars_in_buffer(tty), (int __user *) arg);
2501 down_write(&tty->termios_rwsem);
2502 if (L_ICANON(tty) && !L_EXTPROC(tty))
2503 num = inq_canon(ldata);
2505 num = read_cnt(ldata);
2506 up_write(&tty->termios_rwsem);
2507 return put_user(num, (unsigned int __user *) arg);
2509 return n_tty_ioctl_helper(tty, cmd, arg);
2513 static struct tty_ldisc_ops n_tty_ops = {
2514 .owner = THIS_MODULE,
2518 .close = n_tty_close,
2519 .flush_buffer = n_tty_flush_buffer,
2521 .write = n_tty_write,
2522 .ioctl = n_tty_ioctl,
2523 .set_termios = n_tty_set_termios,
2525 .receive_buf = n_tty_receive_buf,
2526 .write_wakeup = n_tty_write_wakeup,
2527 .receive_buf2 = n_tty_receive_buf2,
2528 .lookahead_buf = n_tty_lookahead_flow_ctrl,
2532 * n_tty_inherit_ops - inherit N_TTY methods
2533 * @ops: struct tty_ldisc_ops where to save N_TTY methods
2535 * Enables a 'subclass' line discipline to 'inherit' N_TTY methods.
2538 void n_tty_inherit_ops(struct tty_ldisc_ops *ops)
2543 EXPORT_SYMBOL_GPL(n_tty_inherit_ops);
2545 void __init n_tty_init(void)
2547 tty_register_ldisc(&n_tty_ops);